text
stringlengths 54
60.6k
|
---|
<commit_before>#include <RcppArmadillo.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string.h>
#include <iostream>
#include <cmath>
#include "rtoarmadillo.h"
// Format for sensor information
struct imu_info{
std::string name;
int time_type;
int data_type;
int header_size;
double scale_gyro;
double scale_acc;
};
// Helper function to create the data structure needed
imu_info get_imu_info(std::string imu_type){
// Transform imu_type to capitals
transform(imu_type.begin(), imu_type.end(), imu_type.begin(), ::toupper);
// Create class definition
imu_info imu;
// opted for if/else vs. map to save in constructing all imu types. so, O(n) instead of O(log(n)) =(
if(imu_type == "IMAR"){
imu.name = "IMAR";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 0.10000000*M_PI/180.0/3600.0; // Scale gyro to rad
imu.scale_acc = 0.00152588/1000.0; // scale accel to m/s
}else if(imu_type == "LN200"){
imu.name = "LN200";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 1.0/2097152.0; // Scale gyro to rad
imu.scale_acc = 1.0/16384.0; // scale accel to m/s
}else if(imu_type == "LN200IG"){
imu.name = "LN200IG";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 1.0/524288.0; // Scale gyro to rad
imu.scale_acc = 1.0/16384.0; // scale accel to m/s
}else if(imu_type == "IXSEA"){
imu.name = "IXSEA";
imu.time_type = 8; // double
imu.data_type = 8; // double
imu.header_size = 0;
imu.scale_gyro = M_PI/180.0/3600.0; // Scale gyro to rad
imu.scale_acc = 0.001; // scale accel to m/s
}else if(imu_type == "NAVCHIP_FLT"){
imu.name = "NAVCHIP_FLT";
imu.time_type = 8; // double
imu.data_type = 8; // double
imu.header_size = 0;
imu.scale_gyro = ((1.0/3600.0)/360.0)*2.0*M_PI; // Scale gyro to rad
imu.scale_acc = 0.001; // scale accel to m/s
}else if(imu_type == "NAVCHIP_INT"){
imu.name = "NAVCHIP_INT";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 0.00000625; // Scale gyro to rad
imu.scale_acc = 0.0000390625; // scale accel to m/s
}else{
throw std::runtime_error("The IMU type "+ imu_type + " is not supported");
}
return imu;
}
//' Read an IMU Binary File into R
//'
//' The function will take a file location in addition to the type of sensor it
//' came from and read the data into R.
//'
//' @param file_path A \code{string} that contains the full file path.
//' @param imu_type A \code{string} that contains a supported IMU type given below.
//' @details
//' Currently supports the following IMUs:
//' \itemize{
//' \item IMAR
//' \item LN200
//' \item LN200IG
//' \item IXSEA
//' \item NAVCHIP_INT
//' \item NAVCHIP_FLT
//' }
//'
//' We hope to soon be able to support delimited files.
//' @return A matrix with dimensions N x 7, where the columns represent:
//' \describe{
//' \item{Col 0}{Time}
//' \item{Col 1}{Gyro 1}
//' \item{Col 2}{Gyro 2}
//' \item{Col 3}{Gyro 3}
//' \item{Col 4}{Accel 1}
//' \item{Col 5}{Accel 2}
//' \item{Col 6}{Accel 3}
//' }
//' @references
//' Thanks goes to Philipp Clausen of Labo TOPO, EPFL, Switzerland, topo.epfl.ch, Tel:+41(0)21 693 27 55
//' for providing a matlab function that reads in IMUs.
//' The function below is a heavily modified port of MATLAB code into Armadillo/C++.
//'
//' @examples
//' read_imu("F:/Desktop/short_test_data.imu","IXSEA")
// [[Rcpp::export]]
arma::field<arma::mat> read_imu(std::string file_path, std::string imu_type) {
// -- File Operations
// Split the file name from the path.
size_t found = file_path.find_last_of("/\\");
std::string file_loc = file_path.substr(0,found);
std::string file_name = file_path.substr(found+1);
// Open data file - need "r" to read, and "b" to indicate binary (o.w. fails on Windows)
FILE *fid = fopen((char*)file_path.c_str(),"rb");
if (fid == NULL){
throw std::runtime_error("Cannot open the " + file_name + " at " + file_loc);
}
// -- Check IMU Type requested
// Get data structure
imu_info imu = get_imu_info(imu_type);
// BitsPerEpoch
unsigned int BitsPerEpoch = imu.time_type + 6*imu.data_type;
// Set cursor at end of file
fseek(fid, 0, SEEK_END);
// ftell returns the file position (end location)
double lsize = ftell(fid); // probably could get away with a float here.
// Count epochs and control it
double nEpochs = (lsize-imu.header_size)/BitsPerEpoch;
// Is nEpochs an integer?
if(trunc(nEpochs) != nEpochs){
throw std::runtime_error("The file does not have the expected file size. Check the type of IMU or if the file is corrupted.");
}
// display info to command window
std::cout << file_name << " contains " << (int)nEpochs << " epochs " << std::endl << "Reading ..." << std::endl;
// -- Read time
// Initialize data matrix
arma::mat data(nEpochs,7);
// Set cursor at begining of data (e.g. skip header if it exists)
fseek(fid, imu.header_size, SEEK_SET);
// Fill the data matrix
if(imu.data_type == 8){ // Data is only doubles
double data_buffer[7];
for(unsigned int i = 0; i < nEpochs; i++){
fread(&data_buffer, sizeof(double), 7, fid); // double
for(int j = 0; j < 7; j++){
data(i,j) = data_buffer[j];
}
}
}else{ // Data is a mix of double then 6 longs
double time_buffer[1];
long data_buffer[6];
for(unsigned int i = 0; i < nEpochs; i++){
fread(&time_buffer, sizeof(double), 1, fid); // double
fread(&data_buffer, 4, 6, fid); // long
data(i,0) = time_buffer[0];
for(int j = 1; j <= 6; j++){
data(i,j) = data_buffer[j-1];
}
}
} // end if
// Close the file connection
fclose(fid);
// Data Rate
double fIMU = 1.0/mean_diff(data.col(0));
fIMU = round(fIMU);
//printf("(data @ %.2f Hz, sGr %f sAc %f) ...", fIMU, imu.scale_gyro, imu.scale_acc);
// Scale data
data.cols(1,3) *= fIMU * imu.scale_gyro;
data.cols(4,6) *= fIMU * imu.scale_acc;
arma::vec stats(3);
stats(0) = fIMU;
stats(1) = imu.scale_gyro;
stats(2) = imu.scale_acc;
arma::field<arma::mat> out(2);
out(0) = data;
out(1) = stats;
return out;
}
<commit_msg>Clang vs. gcc issue >.<<commit_after>#include <RcppArmadillo.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string.h>
#include <iostream>
#include <cmath>
#include "rtoarmadillo.h"
// Format for sensor information
struct imu_info{
std::string name;
int time_type;
int data_type;
int header_size;
double scale_gyro;
double scale_acc;
};
// Helper function to create the data structure needed
imu_info get_imu_info(std::string imu_type){
// Transform imu_type to capitals
transform(imu_type.begin(), imu_type.end(), imu_type.begin(), ::toupper);
// Create class definition
imu_info imu;
// opted for if/else vs. map to save in constructing all imu types. so, O(n) instead of O(log(n)) =(
if(imu_type == "IMAR"){
imu.name = "IMAR";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 0.10000000*M_PI/180.0/3600.0; // Scale gyro to rad
imu.scale_acc = 0.00152588/1000.0; // scale accel to m/s
}else if(imu_type == "LN200"){
imu.name = "LN200";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 1.0/2097152.0; // Scale gyro to rad
imu.scale_acc = 1.0/16384.0; // scale accel to m/s
}else if(imu_type == "LN200IG"){
imu.name = "LN200IG";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 1.0/524288.0; // Scale gyro to rad
imu.scale_acc = 1.0/16384.0; // scale accel to m/s
}else if(imu_type == "IXSEA"){
imu.name = "IXSEA";
imu.time_type = 8; // double
imu.data_type = 8; // double
imu.header_size = 0;
imu.scale_gyro = M_PI/180.0/3600.0; // Scale gyro to rad
imu.scale_acc = 0.001; // scale accel to m/s
}else if(imu_type == "NAVCHIP_FLT"){
imu.name = "NAVCHIP_FLT";
imu.time_type = 8; // double
imu.data_type = 8; // double
imu.header_size = 0;
imu.scale_gyro = ((1.0/3600.0)/360.0)*2.0*M_PI; // Scale gyro to rad
imu.scale_acc = 0.001; // scale accel to m/s
}else if(imu_type == "NAVCHIP_INT"){
imu.name = "NAVCHIP_INT";
imu.time_type = 8; // double
imu.data_type = 4; // long
imu.header_size = 0;
imu.scale_gyro = 0.00000625; // Scale gyro to rad
imu.scale_acc = 0.0000390625; // scale accel to m/s
}else{
throw std::runtime_error("The IMU type "+ imu_type + " is not supported");
}
return imu;
}
//' Read an IMU Binary File into R
//'
//' The function will take a file location in addition to the type of sensor it
//' came from and read the data into R.
//'
//' @param file_path A \code{string} that contains the full file path.
//' @param imu_type A \code{string} that contains a supported IMU type given below.
//' @details
//' Currently supports the following IMUs:
//' \itemize{
//' \item IMAR
//' \item LN200
//' \item LN200IG
//' \item IXSEA
//' \item NAVCHIP_INT
//' \item NAVCHIP_FLT
//' }
//'
//' We hope to soon be able to support delimited files.
//' @return A matrix with dimensions N x 7, where the columns represent:
//' \describe{
//' \item{Col 0}{Time}
//' \item{Col 1}{Gyro 1}
//' \item{Col 2}{Gyro 2}
//' \item{Col 3}{Gyro 3}
//' \item{Col 4}{Accel 1}
//' \item{Col 5}{Accel 2}
//' \item{Col 6}{Accel 3}
//' }
//' @references
//' Thanks goes to Philipp Clausen of Labo TOPO, EPFL, Switzerland, topo.epfl.ch, Tel:+41(0)21 693 27 55
//' for providing a matlab function that reads in IMUs.
//' The function below is a heavily modified port of MATLAB code into Armadillo/C++.
//'
//' @examples
//' read_imu("F:/Desktop/short_test_data.imu","IXSEA")
// [[Rcpp::export]]
arma::field<arma::mat> read_imu(std::string file_path, std::string imu_type) {
// -- File Operations
// Split the file name from the path.
size_t found = file_path.find_last_of("/\\");
std::string file_loc = file_path.substr(0,found);
std::string file_name = file_path.substr(found+1);
// Open data file - need "r" to read, and "b" to indicate binary (o.w. fails on Windows)
FILE *fid = fopen((char*)file_path.c_str(),"rb");
if (fid == NULL){
throw std::runtime_error("Cannot open the " + file_name + " at " + file_loc);
}
// -- Check IMU Type requested
// Get data structure
imu_info imu = get_imu_info(imu_type);
// BitsPerEpoch
unsigned int BitsPerEpoch = imu.time_type + 6*imu.data_type;
// Set cursor at end of file
fseek(fid, 0, SEEK_END);
// ftell returns the file position (end location)
double lsize = ftell(fid); // probably could get away with a float here.
// Count epochs and control it
double nEpochs = (lsize-imu.header_size)/BitsPerEpoch;
// Is nEpochs an integer?
if(trunc(nEpochs) != nEpochs){
throw std::runtime_error("The file does not have the expected file size. Check the type of IMU or if the file is corrupted.");
}
// display info to command window
std::cout << file_name << " contains " << (int)nEpochs << " epochs " << std::endl << "Reading ..." << std::endl;
// -- Read time
// Initialize data matrix
arma::mat data(nEpochs,7);
// Set cursor at begining of data (e.g. skip header if it exists)
fseek(fid, imu.header_size, SEEK_SET);
// Fill the data matrix
if(imu.data_type == 8){ // Data is only doubles
double data_buffer[7];
for(unsigned int i = 0; i < nEpochs; i++){
fread(&data_buffer, 8, 7, fid); // double
for(int j = 0; j < 7; j++){
data(i,j) = data_buffer[j];
}
}
}else{ // Data is a mix of double then 6 longs
double time_buffer[1];
long data_buffer[6];
for(unsigned int i = 0; i < nEpochs; i++){
fread(&time_buffer, 8, 1, fid); // double
fread(&data_buffer, 4, 6, fid); // long
data(i,0) = time_buffer[0];
for(int j = 1; j <= 6; j++){
data(i,j) = data_buffer[j-1];
}
}
} // end if
// Close the file connection
fclose(fid);
// Data Rate
double fIMU = 1.0/mean_diff(data.col(0));
fIMU = round(fIMU);
//printf("(data @ %.2f Hz, sGr %f sAc %f) ...", fIMU, imu.scale_gyro, imu.scale_acc);
// Scale data
data.cols(1,3) *= fIMU * imu.scale_gyro;
data.cols(4,6) *= fIMU * imu.scale_acc;
arma::vec stats(3);
stats(0) = fIMU;
stats(1) = imu.scale_gyro;
stats(2) = imu.scale_acc;
arma::field<arma::mat> out(2);
out(0) = data;
out(1) = stats;
return out;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "helper.hh"
namespace wrencc {
template <typename T>
class LinkedList final : private UnCopyable {
template <typename _Tp> struct ListNode {
ListNode<_Tp>* next;
_Tp value;
};
using NodeType = ListNode<T>;
sz_t size_{};
NodeType* head_{};
NodeType* tail_{};
NodeType* create_aux(const T& value) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, value);
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
NodeType* create_aux(T&& value) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, std::move(value));
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
template <typename... Args> NodeType* create_aux(Args&&... args) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, std::forward<Args>(args)...);
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
void destroy_aux(NodeType* node) noexcept {
destroy(&node->value);
SimpleAlloc<NodeType>::deallocate(node);
}
void append_aux(NodeType* new_node) {
if (head_ == nullptr) {
head_ = tail_ = new_node;
}
else {
tail_->next = new_node;
tail_ = new_node;
}
++size_;
}
public:
LinkedList() noexcept {}
~LinkedList() noexcept { clear(); }
inline bool empty() const noexcept { return size_ == 0; }
inline sz_t size() const noexcept { return size_; }
inline NodeType* get_head() const noexcept { return head_; }
inline NodeType* get_tail() const noexcept { return tail_; }
void clear() {
while (head_ != nullptr) {
auto* node = head_;
head_ = head_->next;
destroy_aux(node);
}
tail_ = nullptr;
size_ = 0;
}
inline void append(const T& x) { append_aux(create_aux(x)); }
inline void append(T&& x) { append_aux(create_aux(std::move(x))); }
template <typename... Args> inline void append(Args&&... args) {
append_aux(create_aux(std::forward<Args>(args)...));
}
T pop_head() {
NodeType* node = head_;
if (head_ = head_->value; head_ == nullptr)
tail_ = nullptr;
T r = node->value;
destroy_aux(node);
--size_;
return r;
}
template <typename Function> inline void for_each(Function&& fn) noexcept {
for (auto* n = head_; n != nullptr; n = n->next)
fn(n->value);
}
};
}
<commit_msg>:bug: fix(list): fixed pop function of linked-list<commit_after>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "helper.hh"
namespace wrencc {
template <typename T>
class LinkedList final : private UnCopyable {
template <typename _Tp> struct ListNode {
ListNode<_Tp>* next;
_Tp value;
};
using NodeType = ListNode<T>;
sz_t size_{};
NodeType* head_{};
NodeType* tail_{};
NodeType* create_aux(const T& value) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, value);
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
NodeType* create_aux(T&& value) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, std::move(value));
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
template <typename... Args> NodeType* create_aux(Args&&... args) {
NodeType* node = SimpleAlloc<NodeType>::allocate();
try {
construct(&node->value, std::forward<Args>(args)...);
node->next = nullptr;
}
catch (...) {
SimpleAlloc<NodeType>::deallocate(node);
throw;
}
return node;
}
void destroy_aux(NodeType* node) noexcept {
destroy(&node->value);
SimpleAlloc<NodeType>::deallocate(node);
}
void append_aux(NodeType* new_node) {
if (head_ == nullptr) {
head_ = tail_ = new_node;
}
else {
tail_->next = new_node;
tail_ = new_node;
}
++size_;
}
public:
LinkedList() noexcept {}
~LinkedList() noexcept { clear(); }
inline bool empty() const noexcept { return size_ == 0; }
inline sz_t size() const noexcept { return size_; }
inline NodeType* get_head() const noexcept { return head_; }
inline NodeType* get_tail() const noexcept { return tail_; }
void clear() {
while (head_ != nullptr) {
auto* node = head_;
head_ = head_->next;
destroy_aux(node);
}
tail_ = nullptr;
size_ = 0;
}
inline void append(const T& x) { append_aux(create_aux(x)); }
inline void append(T&& x) { append_aux(create_aux(std::move(x))); }
template <typename... Args> inline void append(Args&&... args) {
append_aux(create_aux(std::forward<Args>(args)...));
}
T pop_head() {
NodeType* node = head_;
if (head_ = head_->next; head_ == nullptr)
tail_ = nullptr;
T r = node->value;
destroy_aux(node);
--size_;
return r;
}
template <typename Function> inline void for_each(Function&& fn) noexcept {
for (auto* n = head_; n != nullptr; n = n->next)
fn(n->value);
}
};
}
<|endoftext|> |
<commit_before>
/*
pbrt source code is Copyright(c) 1998-2015
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
// core/fileutil.cpp*
#include "pbrt.h"
#include "fileutil.h"
#include <cstdlib>
#include <climits>
#ifndef PBRT_IS_WINDOWS
#include <libgen.h>
#endif
static std::string searchDirectory;
#ifdef PBRT_IS_WINDOWS
bool IsAbsolutePath(const std::string &filename) {
if (filename.size() == 0) return false;
return (filename[0] == '\\' || filename[0] == '/' ||
filename.find(':') != string::npos);
}
std::string AbsolutePath(const std::string &filename) {
char full[_MAX_PATH];
if (_fullpath(full, filename.c_str(), _MAX_PATH))
return std::string(full);
else
return filename;
}
std::string ResolveFilename(const std::string &filename) {
if (searchDirectory.size() == 0 || filename.size() == 0)
return filename;
else if (IsAbsolutePath(filename))
return filename;
char searchDirectoryEnd = searchDirectory[searchDirectory.size() - 1];
if (searchDirectoryEnd == '\\' || searchDirectoryEnd == '/')
return searchDirectory + filename;
else
return searchDirectory + "\\" + filename;
}
std::string DirectoryContaining(const std::string &filename) {
// This code isn't tested but I believe it should work. Might need to add
// some const_casts to make it compile though.
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char ext[_MAX_EXT];
errno_t err = _splitpath_s(filename.c_str(), drive, _MAX_DRIVE, dir,
_MAX_DIR, nullptr, 0, ext, _MAX_EXT);
if (err == 0) {
char fullDir[_MAX_PATH];
err = _makepath_s(fullDir, _MAX_PATH, drive, dir, nullptr, nullptr);
if (err == 0) return std::string(fullDir);
}
return filename;
}
#else
bool IsAbsolutePath(const std::string &filename) {
return (filename.size() > 0) && filename[0] == '/';
}
std::string AbsolutePath(const std::string &filename) {
char full[PATH_MAX];
if (realpath(filename.c_str(), full))
return std::string(full);
else
return filename;
}
std::string ResolveFilename(const std::string &filename) {
if (searchDirectory.size() == 0 || filename.size() == 0)
return filename;
else if (IsAbsolutePath(filename))
return filename;
else if (searchDirectory[searchDirectory.size() - 1] == '/')
return searchDirectory + filename;
else
return searchDirectory + "/" + filename;
}
std::string DirectoryContaining(const std::string &filename) {
char *t = strdup(filename.c_str());
std::string result = dirname(t);
free(t);
return result;
}
#endif
void SetSearchDirectory(const std::string &dirname) {
searchDirectory = dirname;
}
<commit_msg>Added missing std:: namespace prefix<commit_after>
/*
pbrt source code is Copyright(c) 1998-2015
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
// core/fileutil.cpp*
#include "pbrt.h"
#include "fileutil.h"
#include <cstdlib>
#include <climits>
#ifndef PBRT_IS_WINDOWS
#include <libgen.h>
#endif
static std::string searchDirectory;
#ifdef PBRT_IS_WINDOWS
bool IsAbsolutePath(const std::string &filename) {
if (filename.size() == 0) return false;
return (filename[0] == '\\' || filename[0] == '/' ||
filename.find(':') != std::string::npos);
}
std::string AbsolutePath(const std::string &filename) {
char full[_MAX_PATH];
if (_fullpath(full, filename.c_str(), _MAX_PATH))
return std::string(full);
else
return filename;
}
std::string ResolveFilename(const std::string &filename) {
if (searchDirectory.size() == 0 || filename.size() == 0)
return filename;
else if (IsAbsolutePath(filename))
return filename;
char searchDirectoryEnd = searchDirectory[searchDirectory.size() - 1];
if (searchDirectoryEnd == '\\' || searchDirectoryEnd == '/')
return searchDirectory + filename;
else
return searchDirectory + "\\" + filename;
}
std::string DirectoryContaining(const std::string &filename) {
// This code isn't tested but I believe it should work. Might need to add
// some const_casts to make it compile though.
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char ext[_MAX_EXT];
errno_t err = _splitpath_s(filename.c_str(), drive, _MAX_DRIVE, dir,
_MAX_DIR, nullptr, 0, ext, _MAX_EXT);
if (err == 0) {
char fullDir[_MAX_PATH];
err = _makepath_s(fullDir, _MAX_PATH, drive, dir, nullptr, nullptr);
if (err == 0) return std::string(fullDir);
}
return filename;
}
#else
bool IsAbsolutePath(const std::string &filename) {
return (filename.size() > 0) && filename[0] == '/';
}
std::string AbsolutePath(const std::string &filename) {
char full[PATH_MAX];
if (realpath(filename.c_str(), full))
return std::string(full);
else
return filename;
}
std::string ResolveFilename(const std::string &filename) {
if (searchDirectory.size() == 0 || filename.size() == 0)
return filename;
else if (IsAbsolutePath(filename))
return filename;
else if (searchDirectory[searchDirectory.size() - 1] == '/')
return searchDirectory + filename;
else
return searchDirectory + "/" + filename;
}
std::string DirectoryContaining(const std::string &filename) {
char *t = strdup(filename.c_str());
std::string result = dirname(t);
free(t);
return result;
}
#endif
void SetSearchDirectory(const std::string &dirname) {
searchDirectory = dirname;
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
#include <queso/RngGsl.h>
#include <gsl/gsl_randist.h>
#include <mpi.h>
namespace QUESO {
// Default constructor ------------------------------
RngGsl::RngGsl()
:
RngBase()
{
UQ_FATAL_TEST_MACRO(true,
m_worldRank,
"RngGsl::constructor(), default",
"should not be used by user");
}
//! Constructor with seed ---------------------------
RngGsl::RngGsl(int seed, int worldRank)
:
RngBase(seed,worldRank),
m_rng (NULL)
{
gsl_rng_default_seed = (unsigned long int) m_seed;
m_rng = gsl_rng_alloc(gsl_rng_ranlxd2);
UQ_FATAL_TEST_MACRO((m_rng == NULL),
m_worldRank,
"RngGsl::constructor()",
"null m_rng");
//gsl_rng_set(m_rng, gsl_rng_default_seed);
#if 0
if (m_worldRank == 0) {
std::cout << "In RngGsl::constructor():"
<< "\n m_seed = " << m_seed
<< "\n internal seed = " << gsl_rng_default_seed
//<< "\n first generated sample from uniform distribution = " << gsl_rng_uniform(m_rng)
//<< "\n first generated sample from std normal distribution = " << gsl_ran_gaussian(m_rng,1.)
<< std::endl;
}
#endif
}
// Destructor ---------------------------------------
RngGsl::~RngGsl()
{
if (m_rng) gsl_rng_free(m_rng);
}
// Sampling methods ---------------------------------
void
RngGsl::resetSeed(int newSeed)
{
RngBase::resetSeed(newSeed);
gsl_rng_free(m_rng);
gsl_rng_default_seed = (unsigned long int) m_seed;
m_rng = gsl_rng_alloc(gsl_rng_ranlxd2);
UQ_FATAL_TEST_MACRO((m_rng == NULL),
m_worldRank,
"RngGsl::resetSeed()",
"null m_rng");
return;
}
// --------------------------------------------------
double
RngGsl::uniformSample() const
{
return gsl_rng_uniform(m_rng);
}
// --------------------------------------------------
double
RngGsl::gaussianSample(double stdDev) const
{
return gsl_ran_gaussian(m_rng,stdDev);
}
// --------------------------------------------------
double
RngGsl::betaSample(double alpha, double beta) const
{
return gsl_ran_beta(m_rng,alpha,beta);
}
// --------------------------------------------------
double
RngGsl::gammaSample(double a, double b) const
{
return gsl_ran_gamma(m_rng,a,b);
}
} // End namespace QUESO
<commit_msg>Added rng method for getting a pointer to the gsl_rng object<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
#include <queso/RngGsl.h>
#include <gsl/gsl_randist.h>
#include <mpi.h>
namespace QUESO {
// Default constructor ------------------------------
RngGsl::RngGsl()
:
RngBase()
{
UQ_FATAL_TEST_MACRO(true,
m_worldRank,
"RngGsl::constructor(), default",
"should not be used by user");
}
//! Constructor with seed ---------------------------
RngGsl::RngGsl(int seed, int worldRank)
:
RngBase(seed,worldRank),
m_rng (NULL)
{
gsl_rng_default_seed = (unsigned long int) m_seed;
m_rng = gsl_rng_alloc(gsl_rng_ranlxd2);
UQ_FATAL_TEST_MACRO((m_rng == NULL),
m_worldRank,
"RngGsl::constructor()",
"null m_rng");
//gsl_rng_set(m_rng, gsl_rng_default_seed);
#if 0
if (m_worldRank == 0) {
std::cout << "In RngGsl::constructor():"
<< "\n m_seed = " << m_seed
<< "\n internal seed = " << gsl_rng_default_seed
//<< "\n first generated sample from uniform distribution = " << gsl_rng_uniform(m_rng)
//<< "\n first generated sample from std normal distribution = " << gsl_ran_gaussian(m_rng,1.)
<< std::endl;
}
#endif
}
// Destructor ---------------------------------------
RngGsl::~RngGsl()
{
if (m_rng) gsl_rng_free(m_rng);
}
// Sampling methods ---------------------------------
void
RngGsl::resetSeed(int newSeed)
{
RngBase::resetSeed(newSeed);
gsl_rng_free(m_rng);
gsl_rng_default_seed = (unsigned long int) m_seed;
m_rng = gsl_rng_alloc(gsl_rng_ranlxd2);
UQ_FATAL_TEST_MACRO((m_rng == NULL),
m_worldRank,
"RngGsl::resetSeed()",
"null m_rng");
return;
}
// --------------------------------------------------
double
RngGsl::uniformSample() const
{
return gsl_rng_uniform(m_rng);
}
// --------------------------------------------------
double
RngGsl::gaussianSample(double stdDev) const
{
return gsl_ran_gaussian(m_rng,stdDev);
}
// --------------------------------------------------
double
RngGsl::betaSample(double alpha, double beta) const
{
return gsl_ran_beta(m_rng,alpha,beta);
}
// --------------------------------------------------
double
RngGsl::gammaSample(double a, double b) const
{
return gsl_ran_gamma(m_rng,a,b);
}
const gsl_rng*
RngGsl::rng() const
{
return m_rng;
}
} // End namespace QUESO
<|endoftext|> |
<commit_before>#include "text-diff.h"
#include "libmba-diff.h"
#include "text-slice.h"
#include <vector>
#include <string.h>
#include <ostream>
#include <cassert>
using std::move;
using std::ostream;
using std::vector;
static Point previous_column(Point position) {
assert(position.column > 0);
position.column--;
return position;
}
static int MAX_EDIT_DISTANCE = 1024;
Patch text_diff(const Text &old_text, const Text &new_text) {
Patch result;
Text empty;
Text cr{u"\r"};
Text lf{u"\n"};
vector<diff_edit> edit_script;
if (diff(
old_text.content.data(),
old_text.content.size(),
new_text.content.data(),
new_text.content.size(),
MAX_EDIT_DISTANCE,
&edit_script
) == -1) {
result.splice(Point(), old_text.extent(), new_text.extent(), old_text, new_text);
return result;
}
size_t old_offset = 0;
size_t new_offset = 0;
Point old_position;
Point new_position;
for (struct diff_edit &edit : edit_script) {
switch (edit.op) {
case DIFF_MATCH:
if (edit.len == 0) continue;
// If the previous change ended between a CR and an LF, then expand
// that change downward to include the LF.
if (new_text.at(new_offset) == '\n' &&
((old_offset > 0 && old_text.at(old_offset - 1) == '\r') ||
(new_offset > 0 && new_text.at(new_offset - 1) == '\r'))) {
result.splice(new_position, Point(1, 0), Point(1, 0), lf, lf);
old_position.row++;
old_position.column = 0;
new_position.row++;
new_position.column = 0;
}
old_offset += edit.len;
new_offset += edit.len;
old_position = old_text.position_for_offset(old_offset, 0, false);
new_position = new_text.position_for_offset(new_offset, 0, false);
// If the next change starts between a CR and an LF, then expand that
// change leftward to include the CR.
if (new_text.at(new_offset - 1) == '\r' &&
((old_offset < old_text.size() && old_text.at(old_offset) == '\n') ||
(new_offset < new_text.size() && new_text.at(new_offset) == '\n'))) {
result.splice(previous_column(new_position), Point(0, 1), Point(0, 1), cr, cr);
}
break;
case DIFF_DELETE: {
uint32_t deletion_end = old_offset + edit.len;
Text deleted_text{old_text.begin() + old_offset, old_text.begin() + deletion_end};
old_offset = deletion_end;
Point next_old_position = old_text.position_for_offset(old_offset, 0, false);
result.splice(new_position, next_old_position.traversal(old_position), Point(), deleted_text, empty);
old_position = next_old_position;
break;
}
case DIFF_INSERT: {
uint32_t insertion_end = new_offset + edit.len;
Text inserted_text{new_text.begin() + new_offset, new_text.begin() + insertion_end};
new_offset = insertion_end;
Point next_new_position = new_text.position_for_offset(new_offset, 0, false);
result.splice(new_position, Point(), next_new_position.traversal(new_position), empty, inserted_text);
new_position = next_new_position;
break;
}
}
}
return result;
}
<commit_msg>Fix fallback behaviour when maximum edit distance is reached during diff<commit_after>#include "text-diff.h"
#include "libmba-diff.h"
#include "text-slice.h"
#include <vector>
#include <string.h>
#include <ostream>
#include <cassert>
using std::move;
using std::ostream;
using std::vector;
static Point previous_column(Point position) {
assert(position.column > 0);
position.column--;
return position;
}
static int MAX_EDIT_DISTANCE = 4 * 1024;
Patch text_diff(const Text &old_text, const Text &new_text) {
Patch result;
Text empty;
Text cr{u"\r"};
Text lf{u"\n"};
vector<diff_edit> edit_script;
int edit_distance = diff(
old_text.content.data(),
old_text.content.size(),
new_text.content.data(),
new_text.content.size(),
MAX_EDIT_DISTANCE,
&edit_script
);
if (edit_distance == -1 || edit_distance >= MAX_EDIT_DISTANCE) {
result.splice(Point(), old_text.extent(), new_text.extent(), old_text, new_text);
return result;
}
size_t old_offset = 0;
size_t new_offset = 0;
Point old_position;
Point new_position;
for (struct diff_edit &edit : edit_script) {
switch (edit.op) {
case DIFF_MATCH:
if (edit.len == 0) continue;
// If the previous change ended between a CR and an LF, then expand
// that change downward to include the LF.
if (new_text.at(new_offset) == '\n' &&
((old_offset > 0 && old_text.at(old_offset - 1) == '\r') ||
(new_offset > 0 && new_text.at(new_offset - 1) == '\r'))) {
result.splice(new_position, Point(1, 0), Point(1, 0), lf, lf);
old_position.row++;
old_position.column = 0;
new_position.row++;
new_position.column = 0;
}
old_offset += edit.len;
new_offset += edit.len;
old_position = old_text.position_for_offset(old_offset, 0, false);
new_position = new_text.position_for_offset(new_offset, 0, false);
// If the next change starts between a CR and an LF, then expand that
// change leftward to include the CR.
if (new_text.at(new_offset - 1) == '\r' &&
((old_offset < old_text.size() && old_text.at(old_offset) == '\n') ||
(new_offset < new_text.size() && new_text.at(new_offset) == '\n'))) {
result.splice(previous_column(new_position), Point(0, 1), Point(0, 1), cr, cr);
}
break;
case DIFF_DELETE: {
uint32_t deletion_end = old_offset + edit.len;
Text deleted_text{old_text.begin() + old_offset, old_text.begin() + deletion_end};
old_offset = deletion_end;
Point next_old_position = old_text.position_for_offset(old_offset, 0, false);
result.splice(new_position, next_old_position.traversal(old_position), Point(), deleted_text, empty);
old_position = next_old_position;
break;
}
case DIFF_INSERT: {
uint32_t insertion_end = new_offset + edit.len;
Text inserted_text{new_text.begin() + new_offset, new_text.begin() + insertion_end};
new_offset = insertion_end;
Point next_new_position = new_text.position_for_offset(new_offset, 0, false);
result.splice(new_position, Point(), next_new_position.traversal(new_position), empty, inserted_text);
new_position = next_new_position;
break;
}
}
}
return result;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* This file is part of "Patrick's Programming Library", Version 7 (PPL7).
* Web: http://www.pfp.de/ppl/
*
* $Author$
* $Revision$
* $Date$
* $Id$
*
*******************************************************************************
* Copyright (c) 2013, Patrick Fedick <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_LIBMHASH
#define PROTOTYPES 1
#undef HAVE__BOOL
#include <mutils/mhash.h>
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "ppl7.h"
#include "ppl7-crypto.h"
namespace ppl7 {
bool __OpenSSLDigestAdded = false;
Mutex __OpenSSLGlobalMutex;
void InitOpenSSLDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
__OpenSSLGlobalMutex.lock();
if (!__OpenSSLDigestAdded) {
::OpenSSL_add_all_digests();
__OpenSSLDigestAdded=true;
}
__OpenSSLGlobalMutex.unlock();
#endif
}
Digest::Digest()
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
#endif
}
Digest::~Digest()
{
#ifdef HAVE_OPENSSL
free(ret);
if (ctx) EVP_MD_CTX_destroy((EVP_MD_CTX*)ctx);
#endif
}
Digest::Digest(const String &name)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(name);
#endif
}
Digest::Digest(Algorithm algorithm)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(algorithm);
#endif
}
void Digest::setAlgorithm(const String &name)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
m=EVP_get_digestbyname((const char*)name);
if (!m) {
throw InvalidAlgorithmException("%s",(const char*)name);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::setAlgorithm(Algorithm algorithm)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
switch(algorithm) {
#ifndef OPENSSL_NO_MD4
case Algo_MD4: m=EVP_md4(); break;
#endif
#ifndef OPENSSL_NO_MD5
case Algo_MD5: m=EVP_md5(); break;
#endif
#ifndef OPENSSL_NO_SHA
case Algo_SHA1: m=EVP_sha1(); break;
case Algo_ECDSA: m=EVP_ecdsa(); break;
#endif
#ifndef OPENSSL_NO_SHA256
case Algo_SHA224: m=EVP_sha224(); break;
case Algo_SHA256: m=EVP_sha256(); break;
#endif
#ifndef OPENSSL_NO_SHA512
case Algo_SHA384: m=EVP_sha384(); break;
case Algo_SHA512: m=EVP_sha512(); break;
#endif
#ifndef OPENSSL_NO_WHIRLPOOL
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
case Algo_WHIRLPOOL: m=EVP_whirlpool(); break;
#endif
#endif
#ifndef OPENSSL_NO_RIPEMD
case Algo_RIPEMD160: m=EVP_ripemd160(); break;
#endif
default: throw InvalidAlgorithmException();
}
if (!m) {
throw InvalidAlgorithmException("%i",algorithm);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::addData(const void *data, size_t size)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
EVP_DigestUpdate((EVP_MD_CTX*)ctx,data,size);
bytecount+=size;
#endif
}
void Digest::addData(const ByteArrayPtr &data)
{
addData(data.ptr(),data.size());
}
void Digest::addData(const String &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(const WideString &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(FileObject &file)
{
file.seek(0);
size_t bsize=1024*1024*1; // We allocate 1 MB maximum
ppluint64 fsize=file.size();
if (fsize<bsize) bsize=fsize; // or filesize if file is < 1 MB
void *buffer=malloc(bsize);
if (!buffer) {
throw OutOfMemoryException();
}
ppluint64 rest=fsize;
try {
while(rest) {
size_t bytes=rest;
if (bytes>bsize) bytes=bsize;
if (!file.read(buffer,bytes)) {
throw ReadException();
}
addData(buffer,bytes);
rest-=bytes;
}
} catch (...) {
free(buffer);
throw;
}
free(buffer);
}
void Digest::addFile(const String &filename)
{
File ff;
ff.open(filename,File::READ);
addData(ff);
}
ppluint64 Digest::bytesHashed() const
{
return bytecount;
}
void Digest::saveDigest(ByteArray &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
result=getDigest();
#endif
}
void Digest::saveDigest(String &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
void Digest::saveDigest(WideString &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
ByteArray Digest::getDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
unsigned int len;
if (!ret) {
ret=(unsigned char*)malloc(EVP_MAX_MD_SIZE);
if (!ret) throw OutOfMemoryException();
}
EVP_DigestFinal((EVP_MD_CTX*)ctx,ret,&len);
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
bytecount=0;
return ByteArray(ret,len);
#endif
}
void Digest::reset()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
if (!ctx) throw NoAlgorithmSpecifiedException();
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit((EVP_MD_CTX*)ctx,(const EVP_MD*)m);
bytecount=0;
#endif
}
ByteArray Digest::hash(const ByteArrayPtr &data, Algorithm algorithm)
{
Digest dig(algorithm);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::hash(const ByteArrayPtr &data, const String &algorithmName)
{
Digest dig(algorithmName);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::md4(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD4);
}
ByteArray Digest::md5(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD5);
}
ByteArray Digest::sha1(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA1);
}
ByteArray Digest::sha224(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA224);
}
ByteArray Digest::sha256(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA256);
}
ByteArray Digest::sha384(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA384);
}
ByteArray Digest::sha512(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA512);
}
ByteArray Digest::ecdsa(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_ECDSA);
}
ppluint32 Digest::crc32(const ByteArrayPtr &data)
{
#ifdef HAVE_LIBZ
uLong crc=::crc32(0L,Z_NULL,0);
return ::crc32(crc,(const Bytef*)data.ptr(),(uInt)data.size());
#endif
return Crc32(data.ptr(),data.size());
}
ppluint32 Digest::adler32(const ByteArrayPtr &data)
{
const unsigned char *buffer = (const unsigned char *)data.ptr();
size_t buflength=data.size();
ppluint32 s1 = 1;
ppluint32 s2 = 0;
for (size_t n = 0; n < buflength; n++) {
s1 = (s1 + buffer[n]) % 65521;
s2 = (s2 + s1) % 65521;
}
return (s2 << 16) | s1;
}
}
<commit_msg>Digest: fixed compatibility with OpenSSL >= 1.1.x<commit_after>/*******************************************************************************
* This file is part of "Patrick's Programming Library", Version 7 (PPL7).
* Web: http://www.pfp.de/ppl/
*
* $Author$
* $Revision$
* $Date$
* $Id$
*
*******************************************************************************
* Copyright (c) 2013, Patrick Fedick <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_LIBMHASH
#define PROTOTYPES 1
#undef HAVE__BOOL
#include <mutils/mhash.h>
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "ppl7.h"
#include "ppl7-crypto.h"
namespace ppl7 {
bool __OpenSSLDigestAdded = false;
Mutex __OpenSSLGlobalMutex;
void InitOpenSSLDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
__OpenSSLGlobalMutex.lock();
if (!__OpenSSLDigestAdded) {
::OpenSSL_add_all_digests();
__OpenSSLDigestAdded=true;
}
__OpenSSLGlobalMutex.unlock();
#endif
}
Digest::Digest()
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
#endif
}
Digest::~Digest()
{
#ifdef HAVE_OPENSSL
free(ret);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (ctx) EVP_MD_CTX_free((EVP_MD_CTX*)ctx);
#else
if (ctx) EVP_MD_CTX_destroy((EVP_MD_CTX*)ctx);
#endif
#endif
}
Digest::Digest(const String &name)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(name);
#endif
}
Digest::Digest(Algorithm algorithm)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(algorithm);
#endif
}
void Digest::setAlgorithm(const String &name)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
m=EVP_get_digestbyname((const char*)name);
if (!m) {
throw InvalidAlgorithmException("%s",(const char*)name);
}
if (!ctx) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
ctx=EVP_MD_CTX_new();
#else
ctx=EVP_MD_CTX_create();
#endif
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::setAlgorithm(Algorithm algorithm)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
switch(algorithm) {
#ifndef OPENSSL_NO_MD4
case Algo_MD4: m=EVP_md4(); break;
#endif
#ifndef OPENSSL_NO_MD5
case Algo_MD5: m=EVP_md5(); break;
#endif
#ifndef OPENSSL_NO_SHA
case Algo_SHA1: m=EVP_sha1(); break;
case Algo_ECDSA:
#if OPENSSL_VERSION_NUMBER < 0x10100000L
m=EVP_ecdsa(); break;
#endif
#endif
#ifndef OPENSSL_NO_SHA256
case Algo_SHA224: m=EVP_sha224(); break;
case Algo_SHA256: m=EVP_sha256(); break;
#endif
#ifndef OPENSSL_NO_SHA512
case Algo_SHA384: m=EVP_sha384(); break;
case Algo_SHA512: m=EVP_sha512(); break;
#endif
#ifndef OPENSSL_NO_WHIRLPOOL
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
case Algo_WHIRLPOOL: m=EVP_whirlpool(); break;
#endif
#endif
#ifndef OPENSSL_NO_RIPEMD
case Algo_RIPEMD160: m=EVP_ripemd160(); break;
#endif
default: throw InvalidAlgorithmException();
}
if (!m) {
throw InvalidAlgorithmException("%i",algorithm);
}
if (!ctx) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
ctx=EVP_MD_CTX_new();
#else
ctx=EVP_MD_CTX_create();
#endif
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::addData(const void *data, size_t size)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
EVP_DigestUpdate((EVP_MD_CTX*)ctx,data,size);
bytecount+=size;
#endif
}
void Digest::addData(const ByteArrayPtr &data)
{
addData(data.ptr(),data.size());
}
void Digest::addData(const String &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(const WideString &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(FileObject &file)
{
file.seek(0);
size_t bsize=1024*1024*1; // We allocate 1 MB maximum
ppluint64 fsize=file.size();
if (fsize<bsize) bsize=fsize; // or filesize if file is < 1 MB
void *buffer=malloc(bsize);
if (!buffer) {
throw OutOfMemoryException();
}
ppluint64 rest=fsize;
try {
while(rest) {
size_t bytes=rest;
if (bytes>bsize) bytes=bsize;
if (!file.read(buffer,bytes)) {
throw ReadException();
}
addData(buffer,bytes);
rest-=bytes;
}
} catch (...) {
free(buffer);
throw;
}
free(buffer);
}
void Digest::addFile(const String &filename)
{
File ff;
ff.open(filename,File::READ);
addData(ff);
}
ppluint64 Digest::bytesHashed() const
{
return bytecount;
}
void Digest::saveDigest(ByteArray &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
result=getDigest();
#endif
}
void Digest::saveDigest(String &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
void Digest::saveDigest(WideString &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
ByteArray Digest::getDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
unsigned int len;
if (!ret) {
ret=(unsigned char*)malloc(EVP_MAX_MD_SIZE);
if (!ret) throw OutOfMemoryException();
}
EVP_DigestFinal((EVP_MD_CTX*)ctx,ret,&len);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
EVP_MD_CTX_reset((EVP_MD_CTX*)ctx);
#else
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
#endif
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
bytecount=0;
return ByteArray(ret,len);
#endif
}
void Digest::reset()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
if (!ctx) throw NoAlgorithmSpecifiedException();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
EVP_MD_CTX_reset((EVP_MD_CTX*)ctx);
#else
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
#endif
EVP_DigestInit((EVP_MD_CTX*)ctx,(const EVP_MD*)m);
bytecount=0;
#endif
}
ByteArray Digest::hash(const ByteArrayPtr &data, Algorithm algorithm)
{
Digest dig(algorithm);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::hash(const ByteArrayPtr &data, const String &algorithmName)
{
Digest dig(algorithmName);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::md4(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD4);
}
ByteArray Digest::md5(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD5);
}
ByteArray Digest::sha1(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA1);
}
ByteArray Digest::sha224(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA224);
}
ByteArray Digest::sha256(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA256);
}
ByteArray Digest::sha384(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA384);
}
ByteArray Digest::sha512(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA512);
}
ByteArray Digest::ecdsa(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_ECDSA);
}
ppluint32 Digest::crc32(const ByteArrayPtr &data)
{
#ifdef HAVE_LIBZ
uLong crc=::crc32(0L,Z_NULL,0);
return ::crc32(crc,(const Bytef*)data.ptr(),(uInt)data.size());
#endif
return Crc32(data.ptr(),data.size());
}
ppluint32 Digest::adler32(const ByteArrayPtr &data)
{
const unsigned char *buffer = (const unsigned char *)data.ptr();
size_t buflength=data.size();
ppluint32 s1 = 1;
ppluint32 s2 = 0;
for (size_t n = 0; n < buflength; n++) {
s1 = (s1 + buffer[n]) % 65521;
s2 = (s2 + s1) % 65521;
}
return (s2 << 16) | s1;
}
}
<|endoftext|> |
<commit_before>class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int h = citations.size();
int i = 0;
for(int i = 0;i < citations.size();i++)
{
if(citations[i] >= h)
break;
h--;
}
return h;
}
};<commit_msg>274. H-Index<commit_after>class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int h = citations.size();
for (int i = 0;i < citations.size();i++) {
if (citations[i] >= h)
break;
h--;
}
return h;
}
};
<|endoftext|> |
<commit_before>// Vsevolod Ivanov
#include <stdlib.h>
#include <sstream>
#include <iostream>
#include <chrono>
#include <restinio/all.hpp>
#include <http_parser.h>
template <typename LAMBDA>
void do_with_socket(LAMBDA && lambda, const std::string & addr = "127.0.0.1",
std::uint16_t port = 8080)
{
restinio::asio_ns::io_context io_context;
restinio::asio_ns::ip::tcp::socket socket{io_context};
restinio::asio_ns::ip::tcp::resolver resolver{io_context};
restinio::asio_ns::ip::tcp::resolver::query
query{restinio::asio_ns::ip::tcp::v4(), addr, std::to_string(port)};
restinio::asio_ns::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
restinio::asio_ns::connect(socket, iterator);
lambda(socket, io_context);
socket.close();
}
inline void do_request(const std::string & request,
const std::string & addr, std::uint16_t port,
http_parser &parser, http_parser_settings &settings)
{
std::string result;
do_with_socket([&](auto & socket, auto & io_context){
// write request
restinio::asio_ns::streambuf b;
std::ostream req_stream(&b);
req_stream << request;
restinio::asio_ns::write(socket, b);
// read response
std::array<char, 1024> m_read_buffer;
socket.async_read_some(restinio::asio_ns::buffer(m_read_buffer), [&](auto ec, size_t length){
std::vector<char> data;
data.insert(std::end(data), std::begin(m_read_buffer), std::begin(m_read_buffer) + length);
auto nparsed = http_parser_execute(&parser, &settings, data.data(), data.size());
if (HPE_OK != parser.http_errno && HPE_PAUSED != parser.http_errno){
auto err = HTTP_PARSER_ERRNO(&parser);
std::cerr << "Couldn't parse the response: " << http_errno_name(err) << std::endl;
}
});
io_context.run();
}, addr, port);
}
std::string create_http_request(const restinio::http_request_header_t header,
const restinio::http_header_fields_t header_fields,
const restinio::http_connection_header_t connection)
{
std::stringstream request;
request << restinio::method_to_string(header.method()) << " " <<
header.request_target() << " " <<
"HTTP/" << header.http_major() << "." << header.http_minor() << "\r\n";
for (auto header_field: header_fields)
request << header_field.name() << ": " << header_field.value() << "\r\n";
std::string conn_str;
switch (connection)
{
case restinio::http_connection_header_t::keep_alive:
conn_str = "keep-alive";
break;
case restinio::http_connection_header_t::close:
conn_str = "close";
break;
case restinio::http_connection_header_t::upgrade:
throw std::invalid_argument("upgrade");
break;
}
request << "Connection: " << conn_str << "\r\n\r\n";
return request.str();
}
int main(const int argc, char* argv[])
{
if (argc < 4){
std::cerr << "Insufficient arguments! Needs <addr> <port> <target>" << std::endl;
return 1;
}
const std::string addr = argv[1];
const in_port_t port = atoi(argv[2]);
const std::string target = argv[3];
restinio::http_request_header_t header;
header.request_target(target);
header.method(restinio::http_method_t::http_get);
restinio::http_header_fields_t header_fields;
header_fields.append_field(restinio::http_field_t::host,
(addr + ":" + std::to_string(port)).c_str());
header_fields.append_field(restinio::http_field_t::user_agent, "RESTinio client");
header_fields.append_field(restinio::http_field_t::accept, "*/*");
auto connection = restinio::http_connection_header_t::keep_alive;
// build request
auto request = create_http_request(header, header_fields, connection);
printf(request.c_str());
// setup http_parser & callbacks
http_parser_settings settings; // = restinio::impl::create_parser_settings();
http_parser_settings_init(&settings);
settings.on_url = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on url cb\n");
return 0;
};
settings.on_header_field = [](http_parser * parser, const char * at, size_t length) -> int {
printf("on header field cb\n");
return 0;
};
settings.on_header_value = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on header value cb\n");
return 0;
};
settings.on_headers_complete = []( http_parser * parser ) -> int {
printf("on headers complete cb\n");
return 0;
};
settings.on_body = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on body cb\n");
return 0;
};
settings.on_message_complete = [](http_parser * parser) -> int {
printf("on message complete cb\n");
return 0;
};
settings.on_status = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on status cb code=%i message=%s\n", parser->status_code, std::string(at, length).c_str());
return 0;
};
http_parser *m_parser = new http_parser();
http_parser_init(m_parser, HTTP_RESPONSE);
// send request and give parser for response processing
do_request(request, addr, port, *m_parser, settings);
return 0;
}
<commit_msg>cpp/restinio: add client post feature<commit_after>// Vsevolod Ivanov
#include <stdlib.h>
#include <sstream>
#include <iostream>
#include <chrono>
#include <restinio/all.hpp>
#include <http_parser.h>
template <typename LAMBDA>
void do_with_socket(LAMBDA && lambda, const std::string & addr = "127.0.0.1",
std::uint16_t port = 8080)
{
restinio::asio_ns::io_context io_context;
restinio::asio_ns::ip::tcp::socket socket{io_context};
restinio::asio_ns::ip::tcp::resolver resolver{io_context};
restinio::asio_ns::ip::tcp::resolver::query
query{restinio::asio_ns::ip::tcp::v4(), addr, std::to_string(port)};
restinio::asio_ns::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
restinio::asio_ns::connect(socket, iterator);
lambda(socket, io_context);
socket.close();
}
inline void do_request(const std::string & request,
const std::string & addr, std::uint16_t port,
http_parser &parser, http_parser_settings &settings)
{
std::string result;
do_with_socket([&](auto & socket, auto & io_context){
// write request
restinio::asio_ns::streambuf b;
std::ostream req_stream(&b);
req_stream << request;
restinio::asio_ns::write(socket, b);
// read response
std::array<char, 1024> m_read_buffer;
socket.async_read_some(restinio::asio_ns::buffer(m_read_buffer), [&](auto ec, size_t length){
std::vector<char> data;
data.insert(std::end(data), std::begin(m_read_buffer), std::begin(m_read_buffer) + length);
auto nparsed = http_parser_execute(&parser, &settings, data.data(), data.size());
if (HPE_OK != parser.http_errno && HPE_PAUSED != parser.http_errno){
auto err = HTTP_PARSER_ERRNO(&parser);
std::cerr << "Couldn't parse the response: " << http_errno_name(err) << std::endl;
}
});
io_context.run();
}, addr, port);
}
std::string create_http_request(const restinio::http_request_header_t header,
const restinio::http_header_fields_t header_fields,
const restinio::http_connection_header_t connection,
const std::string body)
{
std::stringstream request;
request << restinio::method_to_string(header.method()) << " " <<
header.request_target() << " " <<
"HTTP/" << header.http_major() << "." << header.http_minor() << "\r\n";
for (auto header_field: header_fields)
request << header_field.name() << ": " << header_field.value() << "\r\n";
std::string conn_str;
switch (connection)
{
case restinio::http_connection_header_t::keep_alive:
conn_str = "keep-alive";
break;
case restinio::http_connection_header_t::close:
conn_str = "close";
break;
case restinio::http_connection_header_t::upgrade:
throw std::invalid_argument("upgrade");
break;
}
request << "Connection: " << conn_str << "\r\n";
if (!body.empty()){
request << "Content-Length: " << body.size() << "\r\n\r\n";
request << body;
}
request << "\r\n\r\n";
return request.str();
}
int main(const int argc, char* argv[])
{
if (argc < 5){
std::cerr << "Insufficient arguments! Needs <method> <addr> <port> <target> <body_if_any>" << std::endl;
return 1;
}
const std::string method_str = argv[1];
const std::string addr = argv[2];
const in_port_t port = atoi(argv[3]);
const std::string target = argv[4];
const std::string body = argv[5] ? argv[5] : "";
restinio::http_request_header_t header;
header.request_target(target);
restinio::http_method_t method;
if (method_str == "get")
method = restinio::http_method_t::http_get;
else if (method_str == "post")
method = restinio::http_method_t::http_post;
else
throw std::invalid_argument(method_str);
header.method(method);
restinio::http_header_fields_t header_fields;
header_fields.append_field(restinio::http_field_t::host,
(addr + ":" + std::to_string(port)).c_str());
header_fields.append_field(restinio::http_field_t::user_agent, "RESTinio client");
header_fields.append_field(restinio::http_field_t::accept, "*/*");
// build request
auto connection = restinio::http_connection_header_t::keep_alive;
auto request = create_http_request(header, header_fields, connection, body);
printf(request.c_str());
return 1;
// setup http_parser & callbacks
http_parser_settings settings; // = restinio::impl::create_parser_settings();
http_parser_settings_init(&settings);
settings.on_url = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on url cb\n");
return 0;
};
settings.on_header_field = [](http_parser * parser, const char * at, size_t length) -> int {
printf("on header field cb\n");
return 0;
};
settings.on_header_value = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on header value cb\n");
return 0;
};
settings.on_headers_complete = []( http_parser * parser ) -> int {
printf("on headers complete cb\n");
return 0;
};
settings.on_body = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on body cb\n");
return 0;
};
settings.on_message_complete = [](http_parser * parser) -> int {
printf("on message complete cb\n");
return 0;
};
settings.on_status = []( http_parser * parser, const char * at, size_t length ) -> int {
printf("on status cb code=%i message=%s\n", parser->status_code, std::string(at, length).c_str());
return 0;
};
http_parser *m_parser = new http_parser();
http_parser_init(m_parser, HTTP_RESPONSE);
// send request and give parser for response processing
do_request(request, addr, port, *m_parser, settings);
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <[email protected]> *
* Raphael Hiesgen <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPENCL_PROGRAM_HPP
#define CPPA_OPENCL_PROGRAM_HPP
#include <memory>
#include "cppa/opencl/global.hpp"
#include "cppa/opencl/smart_ptr.hpp"
namespace cppa { namespace opencl {
template<typename Signature>
class actor_facade;
class program {
template<typename Signature>
friend class actor_facade;
public:
static program create(const char* kernel_source);
private:
//program();
program(context_ptr context, program_ptr program);
context_ptr m_context;
program_ptr m_program;
};
} } // namespace cppa::opencl
#endif // CPPA_OPENCL_PROGRAM_HPP
<commit_msg>added doxygen comments to cppa::opencl::program<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <[email protected]> *
* Raphael Hiesgen <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_OPENCL_PROGRAM_HPP
#define CPPA_OPENCL_PROGRAM_HPP
#include <memory>
#include "cppa/opencl/global.hpp"
#include "cppa/opencl/smart_ptr.hpp"
namespace cppa { namespace opencl {
template<typename Signature>
class actor_facade;
/**
* @brief A wrapper for OpenCL's cl_program.
*/
class program {
template<typename Signature>
friend class actor_facade;
public:
/**
* @brief Factory method, that creates a cppa::opencl::program
* from a given @p kernel_source.
* @returns A program object.
*/
static program create(const char* kernel_source);
private:
program(context_ptr context, program_ptr program);
context_ptr m_context;
program_ptr m_program;
};
} } // namespace cppa::opencl
#endif // CPPA_OPENCL_PROGRAM_HPP
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <cstring>
#include <stdexcept>
#include "../../Headers/genotype/gene.hpp"
#include "../../Headers/Utility/jsmn.h"
#include "../../Headers/type.hpp"
#include "../../Headers/training/parameters.hpp"
#include "../../Headers/utility/random.hpp"
using namespace Hippocrates::Genotype;
Gene::Gene() {
SetRandomWeight();
}
Gene::Gene(std::string json) {
jsmn_parser parser;
jsmn_init(&parser);
jsmntok_t tokens[256];
std::size_t token_count = jsmn_parse(&parser, json.c_str(), json.length(), tokens, 256);
for (std::size_t i = 0; i < token_count - 1; i++) {
auto key = json.substr(tokens[i].start, tokens[i].end - tokens[i].start);
auto value = json.substr(tokens[i + 1].start, tokens[i + 1].end - tokens[i + 1].start);
if (key == "historicalMarking") {
HIPPOCRATES_SSCANF(value.c_str(), "%zu", &historicalMarking);
} else
if (key == "to") {
HIPPOCRATES_SSCANF(value.c_str(), "%zu", &to);
} else
if (key == "weight") {
weight = stof(value);
} else
if (key == "isEnabled") {
isEnabled = value == "true";
} else
if (key == "isRecursive") {
isRecursive = value == "true";
}
}
}
auto Gene::operator==(const Gene & other) const -> bool
{
if (historicalMarking == other.historicalMarking
|| (from == other.from
&& to == other.to)) {
if (isRecursive != other.isRecursive)
throw std::logic_error("Two identical genes have different recursive flags");
return true;
}
return false;
}
auto Gene::SetRandomWeight() -> void {
weight = Utility::Random::Number(Training::GetParameters().ranges.minWeight, Training::GetParameters().ranges.maxWeight);
}
auto Gene::GetJSON() const -> std::string {
auto BoolToString = [](bool b) {
return b ? "true" : "false";
};
std::string s("{\"historicalMarking\":");
s += std::to_string(historicalMarking);
s += ",\"from\":";
s += std::to_string(from);
s += ",\"to\":";
s += std::to_string(to);
s += ",\"weight\":";
s += std::to_string(weight);
s += ",\"isEnabled\":";
s += BoolToString(isEnabled);
s += ",\"isRecursive\":";
s += BoolToString(isRecursive);
s += "}";
return s;
}
<commit_msg>Fix case<commit_after>#include <stdlib.h>
#include <cstring>
#include <stdexcept>
#include "../../Headers/genotype/gene.hpp"
#include "../../Headers/utility/jsmn.h"
#include "../../Headers/type.hpp"
#include "../../Headers/training/parameters.hpp"
#include "../../Headers/utility/random.hpp"
using namespace Hippocrates::Genotype;
Gene::Gene() {
SetRandomWeight();
}
Gene::Gene(std::string json) {
jsmn_parser parser;
jsmn_init(&parser);
jsmntok_t tokens[256];
std::size_t token_count = jsmn_parse(&parser, json.c_str(), json.length(), tokens, 256);
for (std::size_t i = 0; i < token_count - 1; i++) {
auto key = json.substr(tokens[i].start, tokens[i].end - tokens[i].start);
auto value = json.substr(tokens[i + 1].start, tokens[i + 1].end - tokens[i + 1].start);
if (key == "historicalMarking") {
HIPPOCRATES_SSCANF(value.c_str(), "%zu", &historicalMarking);
} else
if (key == "to") {
HIPPOCRATES_SSCANF(value.c_str(), "%zu", &to);
} else
if (key == "weight") {
weight = stof(value);
} else
if (key == "isEnabled") {
isEnabled = value == "true";
} else
if (key == "isRecursive") {
isRecursive = value == "true";
}
}
}
auto Gene::operator==(const Gene & other) const -> bool
{
if (historicalMarking == other.historicalMarking
|| (from == other.from
&& to == other.to)) {
if (isRecursive != other.isRecursive)
throw std::logic_error("Two identical genes have different recursive flags");
return true;
}
return false;
}
auto Gene::SetRandomWeight() -> void {
weight = Utility::Random::Number(Training::GetParameters().ranges.minWeight, Training::GetParameters().ranges.maxWeight);
}
auto Gene::GetJSON() const -> std::string {
auto BoolToString = [](bool b) {
return b ? "true" : "false";
};
std::string s("{\"historicalMarking\":");
s += std::to_string(historicalMarking);
s += ",\"from\":";
s += std::to_string(from);
s += ",\"to\":";
s += std::to_string(to);
s += ",\"weight\":";
s += std::to_string(weight);
s += ",\"isEnabled\":";
s += BoolToString(isEnabled);
s += ",\"isRecursive\":";
s += BoolToString(isRecursive);
s += "}";
return s;
}
<|endoftext|> |
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]>
* Copyright (c) 2010 Ruslan Kabatsayev <[email protected]>
*
* 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 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include "../oxygenmetrics.h"
#include <stdlib.h>
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void InnerShadowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if( gdk_display_supports_composite( gtk_widget_get_display( widget ) ) && G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") )
{
_compositeEnabled = true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::connect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
registerChild( child );
}
//_____________________________________________
void InnerShadowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
{ iter->second.disconnect( iter->first ); }
// disconnect signals
_exposeId.disconnect();
// clear child data
_childrenData.clear();
}
//_____________________________________________
void InnerShadowData::registerChild( GtkWidget* widget )
{
#if GTK_CHECK_VERSION(2,22,0)
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
ChildData data;
data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );
GdkWindow* window(gtk_widget_get_window(widget));
if(
// check window
window &&
gdk_window_get_window_type( window ) == GDK_WINDOW_CHILD &&
// check compositing
gdk_display_supports_composite( gtk_widget_get_display( widget ) ) &&
// check widget type (might move to blacklist method)
( G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") ) &&
// make sure widget is scrollable
GTK_WIDGET_GET_CLASS( widget )->set_scroll_adjustments_signal )
{
data.initiallyComposited=gdk_window_get_composited(window);
gdk_window_set_composited(window,TRUE);
}
_childrenData.insert( std::make_pair( widget, data ) );
}
#endif
}
//________________________________________________________________________________
void InnerShadowData::unregisterChild( GtkWidget* widget )
{
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// disconnect signals
_unrealizeId.disconnect();
// remove compositing flag
GdkWindow* window( gtk_widget_get_window( widget ) );
if( GTK_IS_WINDOW( window ) && G_OBJECT_TYPE_NAME( widget ) != std::string("GtkPizza") )
{ gdk_window_set_composited(window,initiallyComposited); }
}
//____________________________________________________________________________________________
gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<InnerShadowData*>(data)->unregisterChild( widget );
return FALSE;
}
//_________________________________________________________________________________________
gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
#if GTK_CHECK_VERSION(2,24,0)
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " path: " << Gtk::gtk_widget_path( child )
<< " area: " << event->area
<< std::endl;
#endif
if(!gdk_window_get_composited(window))
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Window isn't composite. Doing nohing\n";
#endif
return FALSE;
}
// make sure the child window doesn't contain garbage
gdk_window_process_updates(window,TRUE);
// get window geometry
GtkAllocation allocation( Gtk::gdk_rectangle() );
gdk_window_get_geometry( window, &allocation.x, &allocation.y, &allocation.width, &allocation.height, 0L );
// create context with clipping
Cairo::Context context(gtk_widget_get_window(widget), &allocation );
// add event region
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw child
gdk_cairo_set_source_window( context, window, allocation.x, allocation.y );
cairo_paint(context);
#if OXYGEN_DEBUG_INNERSHADOWS
// Show updated parts in random color
cairo_rectangle(context,allocation.x,allocation.y,allocation.width,allocation.height);
double red=((double)rand())/RAND_MAX;
double green=((double)rand())/RAND_MAX;
double blue=((double)rand())/RAND_MAX;
cairo_set_source_rgba(context,red,green,blue,0.5);
cairo_fill(context);
#endif
// draw the shadow
/*
TODO: here child widget's allocation is used instead of window geometry.
I think this is the correct thing to do (unlike above), but this is to be double check
*/
allocation = Gtk::gtk_widget_get_allocation( child );
int basicOffset=2;
// we only draw SHADOW_IN here
if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
{
if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
{
basicOffset=0;
} else {
// FIXME: do we need this special case?
// special_case {
// we still want to draw shadow on GtkFrames with shadow containing GtkScrolledWindow without shadow
GtkWidget* box=gtk_widget_get_parent(widget);
GtkWidget* frame=0;
if(GTK_IS_BOX(box) && GTK_IS_FRAME(frame=gtk_widget_get_parent(box)) &&
gtk_frame_get_shadow_type(GTK_FRAME(frame))==GTK_SHADOW_IN)
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent: Box children: " << GTK_CONTAINER(box) << std::endl;
#endif
// make sure GtkScrolledWindow is the only visible child
GList* children=gtk_container_get_children(GTK_CONTAINER(box));
for(GList* child=g_list_first(children); child; child=g_list_next(child))
{
GtkWidget* childWidget(GTK_WIDGET(child->data));
if(gtk_widget_get_visible(childWidget) && !GTK_IS_SCROLLED_WINDOW(childWidget))
{
g_list_free(children);
return FALSE;
}
}
int frameX, frameY;
GtkAllocation frameAlloc;
if(gtk_widget_translate_coordinates(frame,widget,0,0,&frameX,&frameY))
{
#if OXYGEN_DEBUG
std::cerr << "coords translation: x=" << frameX << "; y=" << frameY << std::endl;
#endif
gtk_widget_get_allocation(frame,&frameAlloc);
allocation.x+=frameX;
allocation.y+=frameY;
allocation.width=frameAlloc.width;
allocation.height=frameAlloc.height;
basicOffset=0;
}
} else {
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
#endif
return FALSE;
}
}
}
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
{
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
}
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
int offsetX=basicOffset+Entry_SideMargin;
int offsetY=basicOffset;
// clipRect
GdkRectangle clipRect( allocation );
// hole background
Style::instance().renderHoleBackground(
gtk_widget_get_window(widget), widget, &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2 );
// adjust offset and render hole
offsetX -= Entry_SideMargin;
Style::instance().renderHole(
gtk_widget_get_window(widget), &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2,
options, data );
#endif // Gtk version
// let the event propagate
return FALSE;
}
}
<commit_msg>Fix typo which lead failure of reverting composited state of various widgets on theme switch from oxygen-gtk to any other<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]>
* Copyright (c) 2010 Ruslan Kabatsayev <[email protected]>
*
* 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 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include "../oxygenmetrics.h"
#include <stdlib.h>
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void InnerShadowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if( gdk_display_supports_composite( gtk_widget_get_display( widget ) ) && G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") )
{
_compositeEnabled = true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::connect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
registerChild( child );
}
//_____________________________________________
void InnerShadowData::disconnect( GtkWidget* widget )
{
_target = 0;
for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
{ iter->second.disconnect( iter->first ); }
// disconnect signals
_exposeId.disconnect();
// clear child data
_childrenData.clear();
}
//_____________________________________________
void InnerShadowData::registerChild( GtkWidget* widget )
{
#if GTK_CHECK_VERSION(2,22,0)
// make sure widget is not already in map
if( _childrenData.find( widget ) == _childrenData.end() )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
ChildData data;
data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );
GdkWindow* window(gtk_widget_get_window(widget));
if(
// check window
window &&
gdk_window_get_window_type( window ) == GDK_WINDOW_CHILD &&
// check compositing
gdk_display_supports_composite( gtk_widget_get_display( widget ) ) &&
// check widget type (might move to blacklist method)
( G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") ) &&
// make sure widget is scrollable
GTK_WIDGET_GET_CLASS( widget )->set_scroll_adjustments_signal )
{
data.initiallyComposited=gdk_window_get_composited(window);
gdk_window_set_composited(window,TRUE);
}
_childrenData.insert( std::make_pair( widget, data ) );
}
#endif
}
//________________________________________________________________________________
void InnerShadowData::unregisterChild( GtkWidget* widget )
{
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::ChildData::disconnect -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
// disconnect signals
_unrealizeId.disconnect();
// remove compositing flag
GdkWindow* window( gtk_widget_get_window( widget ) );
if( GDK_IS_WINDOW( window ) && G_OBJECT_TYPE_NAME( widget ) != std::string("GtkPizza") )
{ gdk_window_set_composited(window,initiallyComposited); }
}
//____________________________________________________________________________________________
gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<InnerShadowData*>(data)->unregisterChild( widget );
return FALSE;
}
//_________________________________________________________________________________________
gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
#if GTK_CHECK_VERSION(2,24,0)
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " path: " << Gtk::gtk_widget_path( child )
<< " area: " << event->area
<< std::endl;
#endif
if(!gdk_window_get_composited(window))
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Window isn't composite. Doing nohing\n";
#endif
return FALSE;
}
// make sure the child window doesn't contain garbage
gdk_window_process_updates(window,TRUE);
// get window geometry
GtkAllocation allocation( Gtk::gdk_rectangle() );
gdk_window_get_geometry( window, &allocation.x, &allocation.y, &allocation.width, &allocation.height, 0L );
// create context with clipping
Cairo::Context context(gtk_widget_get_window(widget), &allocation );
// add event region
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw child
gdk_cairo_set_source_window( context, window, allocation.x, allocation.y );
cairo_paint(context);
#if OXYGEN_DEBUG_INNERSHADOWS
// Show updated parts in random color
cairo_rectangle(context,allocation.x,allocation.y,allocation.width,allocation.height);
double red=((double)rand())/RAND_MAX;
double green=((double)rand())/RAND_MAX;
double blue=((double)rand())/RAND_MAX;
cairo_set_source_rgba(context,red,green,blue,0.5);
cairo_fill(context);
#endif
// draw the shadow
/*
TODO: here child widget's allocation is used instead of window geometry.
I think this is the correct thing to do (unlike above), but this is to be double check
*/
allocation = Gtk::gtk_widget_get_allocation( child );
int basicOffset=2;
// we only draw SHADOW_IN here
if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
{
if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
{
basicOffset=0;
} else {
// FIXME: do we need this special case?
// special_case {
// we still want to draw shadow on GtkFrames with shadow containing GtkScrolledWindow without shadow
GtkWidget* box=gtk_widget_get_parent(widget);
GtkWidget* frame=0;
if(GTK_IS_BOX(box) && GTK_IS_FRAME(frame=gtk_widget_get_parent(box)) &&
gtk_frame_get_shadow_type(GTK_FRAME(frame))==GTK_SHADOW_IN)
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent: Box children: " << GTK_CONTAINER(box) << std::endl;
#endif
// make sure GtkScrolledWindow is the only visible child
GList* children=gtk_container_get_children(GTK_CONTAINER(box));
for(GList* child=g_list_first(children); child; child=g_list_next(child))
{
GtkWidget* childWidget(GTK_WIDGET(child->data));
if(gtk_widget_get_visible(childWidget) && !GTK_IS_SCROLLED_WINDOW(childWidget))
{
g_list_free(children);
return FALSE;
}
}
int frameX, frameY;
GtkAllocation frameAlloc;
if(gtk_widget_translate_coordinates(frame,widget,0,0,&frameX,&frameY))
{
#if OXYGEN_DEBUG
std::cerr << "coords translation: x=" << frameX << "; y=" << frameY << std::endl;
#endif
gtk_widget_get_allocation(frame,&frameAlloc);
allocation.x+=frameX;
allocation.y+=frameY;
allocation.width=frameAlloc.width;
allocation.height=frameAlloc.height;
basicOffset=0;
}
} else {
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
#endif
return FALSE;
}
}
}
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
{
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
}
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
int offsetX=basicOffset+Entry_SideMargin;
int offsetY=basicOffset;
// clipRect
GdkRectangle clipRect( allocation );
// hole background
Style::instance().renderHoleBackground(
gtk_widget_get_window(widget), widget, &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2 );
// adjust offset and render hole
offsetX -= Entry_SideMargin;
Style::instance().renderHole(
gtk_widget_get_window(widget), &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2,
options, data );
#endif // Gtk version
// let the event propagate
return FALSE;
}
}
<|endoftext|> |
<commit_before>
#include "ProcessingPyConf.h"
#include "xPyFunc.h"
static PyObject *PySymbolicElement(SymbolicElement *element)
{
PyObject *dictSEClass = xPyDict_New();
PyDict_SetItemString(dictSEClass, "source", PyString_FromFormat("%s", element->getSource()->str().c_str()));
PyDict_SetItemString(dictSEClass, "destination", PyString_FromFormat("%s", element->getDestination()->str().c_str()));
PyDict_SetItemString(dictSEClass, "expression", PyString_FromFormat("%s", element->getExpression()->str().c_str()));
PyDict_SetItemString(dictSEClass, "id", PyInt_FromLong(element->getID()));
PyDict_SetItemString(dictSEClass, "isTainted", PyBool_FromLong(element->isTainted));
PyObject *SEClassName = xPyString_FromString("SymbolicElement");
PyObject *SEClass = xPyClass_New(NULL, dictSEClass, SEClassName);
return SEClass;
}
ProcessingPyConf::ProcessingPyConf(AnalysisProcessor *ap, Trigger *analysisTrigger)
{
this->ap = ap;
this->analysisTrigger = analysisTrigger;
}
ProcessingPyConf::~ProcessingPyConf()
{
}
void ProcessingPyConf::startAnalysisFromAddr(IRBuilder *irb)
{
// Check if the DSE must be start at this address
if (PyTritonOptions::startAnalysisFromAddr.find(irb->getAddress()) != PyTritonOptions::startAnalysisFromAddr.end())
this->analysisTrigger->update(true);
}
void ProcessingPyConf::stopAnalysisFromAddr(IRBuilder *irb)
{
// Check if the DSE must be stop at this address
if (PyTritonOptions::stopAnalysisFromAddr.find(irb->getAddress()) != PyTritonOptions::stopAnalysisFromAddr.end())
this->analysisTrigger->update(false);
}
void ProcessingPyConf::taintRegFromAddr(IRBuilder *irb)
{
// Apply this bindings only if the analysis is enable
if (!this->analysisTrigger->getState())
return;
// Check if there is registers tainted via the python bindings
std::list<uint64_t> regsTainted = PyTritonOptions::taintRegFromAddr[irb->getAddress()];
std::list<uint64_t>::iterator it = regsTainted.begin();
for ( ; it != regsTainted.end(); it++)
this->ap->taintReg(*it);
}
void ProcessingPyConf::untaintRegFromAddr(IRBuilder *irb)
{
// Apply this bindings only if the analysis is enable
if (!this->analysisTrigger->getState())
return;
// Check if there is registers untainted via the python bindings
std::list<uint64_t> regsUntainted = PyTritonOptions::untaintRegFromAddr[irb->getAddress()];
std::list<uint64_t>::iterator it = regsUntainted.begin();
for ( ; it != regsUntainted.end(); it++)
this->ap->untaintReg(*it);
}
/*
* When a callback is setup (triton.addCallback()), a class (Instruction) is
* sent to the callback function as unique argument.
*
*
* Class Instruction:
*
* - address (integer)
* - assembly (string)
* - isBranch (bool)
* - opcode (integer)
* - opcodeCategory (IDREF.OPCODE_CATEGORY)
* - symbolicElements (list of SymbolicElement)
* - threadId (integer)
*
*
* Class SymbolicElement:
*
* - source (string)
* - destination (string)
* - expression (string)
* - id (integer)
* - isTainted (bool)
*
*/
void ProcessingPyConf::callbackAfter(Inst *inst, AnalysisProcessor *ap)
{
// Check if there is a callback wich must be called at each instruction instrumented
if (this->analysisTrigger->getState() && PyTritonOptions::callbackAfter){
/* Create the class dictionary */
PyObject *dictInstClass = xPyDict_New();
PyDict_SetItemString(dictInstClass, "address", PyInt_FromLong(inst->getAddress()));
PyDict_SetItemString(dictInstClass, "threadId", PyInt_FromLong(inst->getThreadID()));
PyDict_SetItemString(dictInstClass, "opcode", PyInt_FromLong(inst->getOpcode()));
PyDict_SetItemString(dictInstClass, "opcodeCategory", PyInt_FromLong(inst->getOpcodeCategory()));
PyDict_SetItemString(dictInstClass, "assembly", PyString_FromFormat("%s", inst->getDisassembly().c_str()));
PyDict_SetItemString(dictInstClass, "isBranch", PyBool_FromLong(inst->isBranch()));
/* Setup the symbolic element list */
PyObject *SEList = xPyList_New(inst->numberOfElements());
std::list<SymbolicElement*> symElements = inst->getSymbolicElements();
std::list<SymbolicElement*>::iterator it = symElements.begin();
Py_ssize_t index = 0;
for ( ; it != symElements.end(); it++){
PyList_SetItem(SEList, index, PySymbolicElement(*it));
index++;
}
PyDict_SetItemString(dictInstClass, "symbolicElements", SEList);
/* Create the Instruction class */
PyObject *instClassName = xPyString_FromString("Instruction");
PyObject *instClass = xPyClass_New(NULL, dictInstClass, instClassName);
/* CallObject needs a tuple. The size of the tuple is the number of arguments.
* Triton sends only one argument to the callback. This argument is the Instruction
* class and contains all information. */
PyObject *args = xPyTuple_New(1);
PyTuple_SetItem(args, 0, instClass);
if (PyObject_CallObject(PyTritonOptions::callbackAfter, args) == NULL){
PyErr_Print();
exit(1);
}
/* Go through all symbolicElements in SEList. */
/* Free all items in the symbolicElement class. */
for (index = 0; index < PyList_Size(SEList); index++){
/* Get the object in the list */
PyObject *o = PyList_GetItem(SEList, index);
/* Cast the PyObject to PyClassObject */
PyClassObject *co = reinterpret_cast<PyClassObject*>(o);
/* Free the class name object */
Py_DECREF(co->cl_name);
/* Clear/Free the class dictionary items */
PyDict_Clear(co->cl_dict);
/* Free the class dictionary object */
Py_DECREF(co->cl_dict);
/* Free the initial object */
Py_DECREF(o);
/* Next object */
index++;
}
PyDict_Clear(dictInstClass); /* Clear all items in the dictionary */
Py_DECREF(SEList); /* Free the allocated symbolic element list */
Py_DECREF(dictInstClass); /* Free the allocated dictionary */
Py_DECREF(instClassName); /* Free the allocated Inst class name */
Py_DECREF(args); /* Free the allocated tuple */
}
}
void ProcessingPyConf::callbackBefore(IRBuilder *irb, AnalysisProcessor *ap)
{
// Check if there is a callback wich must be called at each instruction instrumented
if (this->analysisTrigger->getState() && PyTritonOptions::callbackBefore){
/* Create the class dictionary */
PyObject *dictInstClass = xPyDict_New();
PyDict_SetItemString(dictInstClass, "address", PyInt_FromLong(irb->getAddress()));
PyDict_SetItemString(dictInstClass, "threadId", PyInt_FromLong(ap->getThreadID()));
PyDict_SetItemString(dictInstClass, "opcode", PyInt_FromLong(irb->getOpcode()));
PyDict_SetItemString(dictInstClass, "opcodeCategory", PyInt_FromLong(irb->getOpcodeCategory()));
PyDict_SetItemString(dictInstClass, "assembly", PyString_FromFormat("%s", irb->getDisassembly().c_str()));
PyDict_SetItemString(dictInstClass, "isBranch", PyBool_FromLong(irb->isBranch()));
/* Before the processing, the symbolic element list is empty */
PyObject *SEList = xPyList_New(0);
PyDict_SetItemString(dictInstClass, "symbolicElements", SEList);
/* Create the Instruction class */
PyObject *instClassName = xPyString_FromString("Instruction");
PyObject *instClass = xPyClass_New(NULL, dictInstClass, instClassName);
/* CallObject needs a tuple. The size of the tuple is the number of arguments.
* Triton sends only one argument to the callback. This argument is the Instruction
* class and contains all information. */
PyObject *args = xPyTuple_New(1);
PyTuple_SetItem(args, 0, instClass);
if (PyObject_CallObject(PyTritonOptions::callbackBefore, args) == NULL){
PyErr_Print();
exit(1);
}
PyDict_Clear(dictInstClass); /* Clear all items in the dictionary */
Py_DECREF(SEList); /* Free the allocated symbolic element list */
Py_DECREF(dictInstClass); /* Free the allocated dictionary */
Py_DECREF(instClassName); /* Free the allocated Inst class name */
Py_DECREF(args); /* Free the allocated tuple */
}
}
void ProcessingPyConf::applyConfBeforeProcessing(IRBuilder *irb)
{
this->startAnalysisFromAddr(irb);
this->stopAnalysisFromAddr(irb);
this->taintRegFromAddr(irb);
this->untaintRegFromAddr(irb);
}
<commit_msg>Enhancement #48: routine name in Instruction<commit_after>
#include "ProcessingPyConf.h"
#include "xPyFunc.h"
static PyObject *PySymbolicElement(SymbolicElement *element)
{
PyObject *dictSEClass = xPyDict_New();
PyDict_SetItemString(dictSEClass, "source", PyString_FromFormat("%s", element->getSource()->str().c_str()));
PyDict_SetItemString(dictSEClass, "destination", PyString_FromFormat("%s", element->getDestination()->str().c_str()));
PyDict_SetItemString(dictSEClass, "expression", PyString_FromFormat("%s", element->getExpression()->str().c_str()));
PyDict_SetItemString(dictSEClass, "id", PyInt_FromLong(element->getID()));
PyDict_SetItemString(dictSEClass, "isTainted", PyBool_FromLong(element->isTainted));
PyObject *SEClassName = xPyString_FromString("SymbolicElement");
PyObject *SEClass = xPyClass_New(NULL, dictSEClass, SEClassName);
return SEClass;
}
ProcessingPyConf::ProcessingPyConf(AnalysisProcessor *ap, Trigger *analysisTrigger)
{
this->ap = ap;
this->analysisTrigger = analysisTrigger;
}
ProcessingPyConf::~ProcessingPyConf()
{
}
void ProcessingPyConf::startAnalysisFromAddr(IRBuilder *irb)
{
// Check if the DSE must be start at this address
if (PyTritonOptions::startAnalysisFromAddr.find(irb->getAddress()) != PyTritonOptions::startAnalysisFromAddr.end())
this->analysisTrigger->update(true);
}
void ProcessingPyConf::stopAnalysisFromAddr(IRBuilder *irb)
{
// Check if the DSE must be stop at this address
if (PyTritonOptions::stopAnalysisFromAddr.find(irb->getAddress()) != PyTritonOptions::stopAnalysisFromAddr.end())
this->analysisTrigger->update(false);
}
void ProcessingPyConf::taintRegFromAddr(IRBuilder *irb)
{
// Apply this bindings only if the analysis is enable
if (!this->analysisTrigger->getState())
return;
// Check if there is registers tainted via the python bindings
std::list<uint64_t> regsTainted = PyTritonOptions::taintRegFromAddr[irb->getAddress()];
std::list<uint64_t>::iterator it = regsTainted.begin();
for ( ; it != regsTainted.end(); it++)
this->ap->taintReg(*it);
}
void ProcessingPyConf::untaintRegFromAddr(IRBuilder *irb)
{
// Apply this bindings only if the analysis is enable
if (!this->analysisTrigger->getState())
return;
// Check if there is registers untainted via the python bindings
std::list<uint64_t> regsUntainted = PyTritonOptions::untaintRegFromAddr[irb->getAddress()];
std::list<uint64_t>::iterator it = regsUntainted.begin();
for ( ; it != regsUntainted.end(); it++)
this->ap->untaintReg(*it);
}
/*
* When a callback is setup (triton.addCallback()), a class (Instruction) is
* sent to the callback function as unique argument.
*
*
* Class Instruction:
*
* - address (integer)
* - assembly (string)
* - isBranch (bool)
* - opcode (integer)
* - opcodeCategory (IDREF.OPCODE_CATEGORY)
* - symbolicElements (list of SymbolicElement)
* - threadId (integer)
*
*
* Class SymbolicElement:
*
* - source (string)
* - destination (string)
* - expression (string)
* - id (integer)
* - isTainted (bool)
*
*/
void ProcessingPyConf::callbackAfter(Inst *inst, AnalysisProcessor *ap)
{
// Check if there is a callback wich must be called at each instruction instrumented
if (this->analysisTrigger->getState() && PyTritonOptions::callbackAfter){
/* Create the class dictionary */
PyObject *dictInstClass = xPyDict_New();
PyDict_SetItemString(dictInstClass, "address", PyInt_FromLong(inst->getAddress()));
PyDict_SetItemString(dictInstClass, "assembly", PyString_FromFormat("%s", inst->getDisassembly().c_str()));
PyDict_SetItemString(dictInstClass, "isBranch", PyBool_FromLong(inst->isBranch()));
PyDict_SetItemString(dictInstClass, "opcode", PyInt_FromLong(inst->getOpcode()));
PyDict_SetItemString(dictInstClass, "opcodeCategory", PyInt_FromLong(inst->getOpcodeCategory()));
PyDict_SetItemString(dictInstClass, "routineName", PyString_FromFormat("%s", RTN_FindNameByAddress(inst->getAddress()).c_str()));
PyDict_SetItemString(dictInstClass, "threadId", PyInt_FromLong(inst->getThreadID()));
/* Setup the symbolic element list */
PyObject *SEList = xPyList_New(inst->numberOfElements());
std::list<SymbolicElement*> symElements = inst->getSymbolicElements();
std::list<SymbolicElement*>::iterator it = symElements.begin();
Py_ssize_t index = 0;
for ( ; it != symElements.end(); it++){
PyList_SetItem(SEList, index, PySymbolicElement(*it));
index++;
}
PyDict_SetItemString(dictInstClass, "symbolicElements", SEList);
/* Create the Instruction class */
PyObject *instClassName = xPyString_FromString("Instruction");
PyObject *instClass = xPyClass_New(NULL, dictInstClass, instClassName);
/* CallObject needs a tuple. The size of the tuple is the number of arguments.
* Triton sends only one argument to the callback. This argument is the Instruction
* class and contains all information. */
PyObject *args = xPyTuple_New(1);
PyTuple_SetItem(args, 0, instClass);
if (PyObject_CallObject(PyTritonOptions::callbackAfter, args) == NULL){
PyErr_Print();
exit(1);
}
/* Go through all symbolicElements in SEList. */
/* Free all items in the symbolicElement class. */
for (index = 0; index < PyList_Size(SEList); index++){
/* Get the object in the list */
PyObject *o = PyList_GetItem(SEList, index);
/* Cast the PyObject to PyClassObject */
PyClassObject *co = reinterpret_cast<PyClassObject*>(o);
/* Free the class name object */
Py_DECREF(co->cl_name);
/* Clear/Free the class dictionary items */
PyDict_Clear(co->cl_dict);
/* Free the class dictionary object */
Py_DECREF(co->cl_dict);
/* Free the initial object */
Py_DECREF(o);
/* Next object */
index++;
}
PyDict_Clear(dictInstClass); /* Clear all items in the dictionary */
Py_DECREF(SEList); /* Free the allocated symbolic element list */
Py_DECREF(dictInstClass); /* Free the allocated dictionary */
Py_DECREF(instClassName); /* Free the allocated Inst class name */
Py_DECREF(args); /* Free the allocated tuple */
}
}
void ProcessingPyConf::callbackBefore(IRBuilder *irb, AnalysisProcessor *ap)
{
// Check if there is a callback wich must be called at each instruction instrumented
if (this->analysisTrigger->getState() && PyTritonOptions::callbackBefore){
/* Create the class dictionary */
PyObject *dictInstClass = xPyDict_New();
PyDict_SetItemString(dictInstClass, "address", PyInt_FromLong(irb->getAddress()));
PyDict_SetItemString(dictInstClass, "assembly", PyString_FromFormat("%s", irb->getDisassembly().c_str()));
PyDict_SetItemString(dictInstClass, "isBranch", PyBool_FromLong(irb->isBranch()));
PyDict_SetItemString(dictInstClass, "opcode", PyInt_FromLong(irb->getOpcode()));
PyDict_SetItemString(dictInstClass, "opcodeCategory", PyInt_FromLong(irb->getOpcodeCategory()));
PyDict_SetItemString(dictInstClass, "routineName", PyString_FromFormat("%s", RTN_FindNameByAddress(irb->getAddress()).c_str()));
PyDict_SetItemString(dictInstClass, "threadId", PyInt_FromLong(ap->getThreadID()));
/* Before the processing, the symbolic element list is empty */
PyObject *SEList = xPyList_New(0);
PyDict_SetItemString(dictInstClass, "symbolicElements", SEList);
/* Create the Instruction class */
PyObject *instClassName = xPyString_FromString("Instruction");
PyObject *instClass = xPyClass_New(NULL, dictInstClass, instClassName);
/* CallObject needs a tuple. The size of the tuple is the number of arguments.
* Triton sends only one argument to the callback. This argument is the Instruction
* class and contains all information. */
PyObject *args = xPyTuple_New(1);
PyTuple_SetItem(args, 0, instClass);
if (PyObject_CallObject(PyTritonOptions::callbackBefore, args) == NULL){
PyErr_Print();
exit(1);
}
PyDict_Clear(dictInstClass); /* Clear all items in the dictionary */
Py_DECREF(SEList); /* Free the allocated symbolic element list */
Py_DECREF(dictInstClass); /* Free the allocated dictionary */
Py_DECREF(instClassName); /* Free the allocated Inst class name */
Py_DECREF(args); /* Free the allocated tuple */
}
}
void ProcessingPyConf::applyConfBeforeProcessing(IRBuilder *irb)
{
this->startAnalysisFromAddr(irb);
this->stopAnalysisFromAddr(irb);
this->taintRegFromAddr(irb);
this->untaintRegFromAddr(irb);
}
<|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Connects to a Watcher server and writes the event stream to a KML file suitable for use
* with Google Earth.
*
* @author [email protected]
*/
#include <unistd.h>
#include <getopt.h>
#include <stdint.h>
#include <cassert>
#include <iostream>
#include <cstdlib>
#include "logger.h"
#include "initConfig.h"
#include "singletonConfig.h"
#include "libwatcher/messageStream.h"
#include "libwatcher/watcherGraph.h"
#include "libwatcher/playbackTimeRange.h"
#define TOOL_NAME "earthWatcher"
DECLARE_GLOBAL_LOGGER(TOOL_NAME);
using namespace watcher;
void write_kml(const WatcherGraph& graph, const std::string& outputFile); // kml.cc
namespace watcher {
float LayerPadding = 10;
float Lonoff = 0.0;
float Latoff = 0.0;
float Altoff = 0.0;
}
namespace {
//arguments to getopt_long()
const option OPTIONS[] = {
{ "latoff", required_argument, 0, 'a' },
{ "altoff", required_argument, 0, 'A' },
{ "config", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "output", required_argument, 0, 'o' },
{ "lonoff", required_argument, 0, 'O' },
{ "refresh", required_argument, 0, 'r' },
{ "seek", required_argument, 0, 'S' },
{ "server", required_argument, 0, 's' },
{ "speed", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
const char *CONFIG_FILE = TOOL_NAME ".cfg";
const char *OUTPUT_FILE = "watcher.kml";
const char *PROPERTY_FILE = TOOL_NAME ".log.properties";
const char *DEFAULT_HOST = "127.0.0.1";
const unsigned int DEFAULT_REFRESH = 1; // SECONDS
void usage()
{
const char *SEP = "\t\t"; // separator for argument/description columns
std::cout << "usage: earthWatcher [ -h ] [ -c FILE ]\n"
" -a, --latoff OFF" << SEP << "translate GPS coordinates relative to a given latitude\n"
" -A, --altoff OFF" << SEP << "translate GPS coordinates relative to the given altitude\n"
" -c, --config FILE" << SEP << "specify a configuration file (default: " << CONFIG_FILE << ")\n"
" -d, --speed SPEED" << SEP << "specify the event playback rate (default: 1.0)\n"
" -h, --help\t" << SEP << "display this help message\n"
" -o, --output FILE" << SEP << "specifies the output KML file (default: " << OUTPUT_FILE << ")\n"
" -O, --lonoff OFF" << SEP << "translate GPS coordinates relative to a given longitude\n"
" -r, --refresh SECS" << SEP << "write the the output every SECS seconds (default: " << DEFAULT_REFRESH << ")\n"
" -s, --server HOST" << SEP << "connect to the watcher server on the given host (default: " << DEFAULT_HOST << ")\n"
" -S, --seek POS" << SEP << "start event playback at timestamp POS (default: -1)\n"
"\tPOS may be specified relative to the first and last timestamps in the Watcher database by prefixing the offset with + or -\n"
"\tExample: +5000 means 5 seconds after the first event in the database.\n"
<< std::endl;
}
} // end namespace
int main(int argc, char **argv)
{
TRACE_ENTER();
const char *output_file = 0;
Timestamp start_timestamp = -1 ; // default to EOF (live playback)
unsigned int refresh = DEFAULT_REFRESH;
float speed = 1.0;
bool relativeTS = false; // when true, start_timestamp is relative to first or last event in the Watcher DB
unsigned int args = 0;
enum {
argLayerPadding = (1<<0),
argLonoff = (1<<1),
argLatoff = (1<<2),
argAltoff = (1<<3),
argOutputFile = (1<<4),
argServerName = (1<<5)
};
std::string outputFile(OUTPUT_FILE);
std::string serverName(DEFAULT_HOST);
for (int i; (i = getopt_long(argc, argv, "a:A:hc:d:o:O:r:S:", OPTIONS, 0)) != -1; ) {
switch (i) {
case 'c':
break; //handled by initConfig()
case 'a':
Latoff = atof(optarg);
args |= argLatoff;
break;
case 'A':
Altoff = atof(optarg);
args |= argAltoff;
break;
case 'd':
speed = atoi(optarg);
break;
case 'o': // output-file
outputFile = optarg;
args |= argOutputFile;
break;
case 'O':
Lonoff = atoi(optarg);
args |= argLonoff;
break;
case 'r':
refresh = atoi(optarg);
break;
case 'S':
relativeTS = (optarg[0] == '+' || optarg[0] == '-'); // when +/- is prefix, seek relative to starting/ending event
start_timestamp = atol(optarg);
if (start_timestamp == -1)
relativeTS = false; // special case for EOF value
break;
case 's':
serverName = optarg;
args |= argServerName;
case 'h':
default:
usage();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
break;
}
}
libconfig::Config& config = SingletonConfig::instance();
SingletonConfig::lock();
std::string configFilename; //filled by initConfig()
if (! watcher::initConfig(config, argc, argv, configFilename))
std::cout << "Configuration file not found. Creating new configuration file and using default runtime values." << std::endl;
SingletonConfig::unlock();
std::string logConf(PROPERTY_FILE);
std::string service("watcherd");
struct {
const char *configName;
std::string *value;
unsigned int bit;
} ConfigString[] = {
{ "logPropertiesFile", &logConf, 0 },
{ "server", &serverName, argServerName },
{ "service", &service, 0 },
{ "outputFile", &outputFile, argOutputFile },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigString[i].configName != 0; ++i) {
if ((args & ConfigString[i].bit) == 0 && !config.lookupValue(ConfigString[i].configName, *ConfigString[i].value)) {
LOG_INFO("'" << ConfigString[i].configName << "' not found in the configuration file, using default: " << *ConfigString[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigString[i].configName, libconfig::Setting::TypeString) = *ConfigString[i].value;
}
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
struct {
const char *configName;
float* value;
unsigned int bit;
} ConfigFloat[] = {
{ "layerPadding", &LayerPadding, argLayerPadding },
{ "lonOff", &Lonoff, argLonoff },
{ "latOff", &Latoff, argLatoff },
{ "altOff", &Altoff, argAltoff },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigFloat[i].configName != 0; ++i) {
if ((args & ConfigFloat[i].bit) == 0 && !config.lookupValue(ConfigFloat[i].configName, *ConfigFloat[i].value)) {
LOG_INFO("'" << ConfigFloat[i].configName << "' not found in the configuration file, using default: " << *ConfigFloat[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigFloat[i].configName, libconfig::Setting::TypeFloat) = *ConfigFloat[i].value;
}
}
// open a message stream of live events for now
MessageStreamPtr ms(MessageStream::createNewMessageStream(serverName, service, start_timestamp, speed));
if (!ms) {
LOG_FATAL("Unable to create new message stream to server \"" << serverName << "\" using service (or port) \"" << service);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
if (relativeTS) {
ms->getMessageTimeRange();
} else {
LOG_INFO("Starting event playback");
ms->startStream();
}
srandom(time(0));//we use random() to select the icon below
WatcherGraph graph;
unsigned int messageNumber = 0;
MessagePtr mp;
time_t last_output = 0; // counter to allow for writing the kml file on a fixed time interval
bool changed = false;
bool needTimeRange = relativeTS;
LOG_INFO("Waiting for events ");
while (ms->getNextMessage(mp)) {
// std::cout << "Message #" << (++messageNumber) << ": " << *mp << std::endl;
if (needTimeRange) {
PlaybackTimeRangeMessagePtr trp(boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(mp));
if (trp.get() != 0) {
LOG_INFO( "first offset=" << trp->min_ << ", last offset=" << trp->max_ );
needTimeRange = false;
Timestamp off = start_timestamp + (( start_timestamp >= 0 ) ? trp->min_ : trp->max_ );
ms->setStreamTimeStart(off);
LOG_INFO("Starting event playback");
ms->startStream();
continue;
}
}
changed |= graph.updateGraph(mp);
if (changed) {
time_t now = time(0);
if (now - last_output >= refresh) {
graph.doMaintanence(); // expire stale links
LOG_DEBUG("writing kml file");
last_output = now;
write_kml(graph, outputFile);
}
changed = false; // reset flag
}
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
TRACE_EXIT_RET(0);
return 0;
}
<commit_msg>earthWatcher: break after parsing 's' option.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Connects to a Watcher server and writes the event stream to a KML file suitable for use
* with Google Earth.
*
* @author [email protected]
*/
#include <unistd.h>
#include <getopt.h>
#include <stdint.h>
#include <cassert>
#include <iostream>
#include <cstdlib>
#include "logger.h"
#include "initConfig.h"
#include "singletonConfig.h"
#include "libwatcher/messageStream.h"
#include "libwatcher/watcherGraph.h"
#include "libwatcher/playbackTimeRange.h"
#define TOOL_NAME "earthWatcher"
DECLARE_GLOBAL_LOGGER(TOOL_NAME);
using namespace watcher;
void write_kml(const WatcherGraph& graph, const std::string& outputFile); // kml.cc
namespace watcher {
float LayerPadding = 10;
float Lonoff = 0.0;
float Latoff = 0.0;
float Altoff = 0.0;
}
namespace {
//arguments to getopt_long()
const option OPTIONS[] = {
{ "latoff", required_argument, 0, 'a' },
{ "altoff", required_argument, 0, 'A' },
{ "config", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "output", required_argument, 0, 'o' },
{ "lonoff", required_argument, 0, 'O' },
{ "refresh", required_argument, 0, 'r' },
{ "seek", required_argument, 0, 'S' },
{ "server", required_argument, 0, 's' },
{ "speed", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
const char *CONFIG_FILE = TOOL_NAME ".cfg";
const char *OUTPUT_FILE = "watcher.kml";
const char *PROPERTY_FILE = TOOL_NAME ".log.properties";
const char *DEFAULT_HOST = "127.0.0.1";
const unsigned int DEFAULT_REFRESH = 1; // SECONDS
void usage()
{
const char *SEP = "\t\t"; // separator for argument/description columns
std::cout << "usage: earthWatcher [ -h ] [ -c FILE ]\n"
" -a, --latoff OFF" << SEP << "translate GPS coordinates relative to a given latitude\n"
" -A, --altoff OFF" << SEP << "translate GPS coordinates relative to the given altitude\n"
" -c, --config FILE" << SEP << "specify a configuration file (default: " << CONFIG_FILE << ")\n"
" -d, --speed SPEED" << SEP << "specify the event playback rate (default: 1.0)\n"
" -h, --help\t" << SEP << "display this help message\n"
" -o, --output FILE" << SEP << "specifies the output KML file (default: " << OUTPUT_FILE << ")\n"
" -O, --lonoff OFF" << SEP << "translate GPS coordinates relative to a given longitude\n"
" -r, --refresh SECS" << SEP << "write the the output every SECS seconds (default: " << DEFAULT_REFRESH << ")\n"
" -s, --server HOST" << SEP << "connect to the watcher server on the given host (default: " << DEFAULT_HOST << ")\n"
" -S, --seek POS" << SEP << "start event playback at timestamp POS (default: -1)\n"
"\tPOS may be specified relative to the first and last timestamps in the Watcher database by prefixing the offset with + or -\n"
"\tExample: +5000 means 5 seconds after the first event in the database.\n"
<< std::endl;
}
} // end namespace
int main(int argc, char **argv)
{
TRACE_ENTER();
const char *output_file = 0;
Timestamp start_timestamp = -1 ; // default to EOF (live playback)
unsigned int refresh = DEFAULT_REFRESH;
float speed = 1.0;
bool relativeTS = false; // when true, start_timestamp is relative to first or last event in the Watcher DB
unsigned int args = 0;
enum {
argLayerPadding = (1<<0),
argLonoff = (1<<1),
argLatoff = (1<<2),
argAltoff = (1<<3),
argOutputFile = (1<<4),
argServerName = (1<<5)
};
std::string outputFile(OUTPUT_FILE);
std::string serverName(DEFAULT_HOST);
for (int i; (i = getopt_long(argc, argv, "a:A:hc:d:o:O:r:S:", OPTIONS, 0)) != -1; ) {
switch (i) {
case 'c':
break; //handled by initConfig()
case 'a':
Latoff = atof(optarg);
args |= argLatoff;
break;
case 'A':
Altoff = atof(optarg);
args |= argAltoff;
break;
case 'd':
speed = atoi(optarg);
break;
case 'o': // output-file
outputFile = optarg;
args |= argOutputFile;
break;
case 'O':
Lonoff = atoi(optarg);
args |= argLonoff;
break;
case 'r':
refresh = atoi(optarg);
break;
case 'S':
relativeTS = (optarg[0] == '+' || optarg[0] == '-'); // when +/- is prefix, seek relative to starting/ending event
start_timestamp = atol(optarg);
if (start_timestamp == -1)
relativeTS = false; // special case for EOF value
break;
case 's':
serverName = optarg;
args |= argServerName;
break;
case 'h':
default:
usage();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
break;
}
}
libconfig::Config& config = SingletonConfig::instance();
SingletonConfig::lock();
std::string configFilename; //filled by initConfig()
if (! watcher::initConfig(config, argc, argv, configFilename))
std::cout << "Configuration file not found. Creating new configuration file and using default runtime values." << std::endl;
SingletonConfig::unlock();
std::string logConf(PROPERTY_FILE);
std::string service("watcherd");
struct {
const char *configName;
std::string *value;
unsigned int bit;
} ConfigString[] = {
{ "logPropertiesFile", &logConf, 0 },
{ "server", &serverName, argServerName },
{ "service", &service, 0 },
{ "outputFile", &outputFile, argOutputFile },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigString[i].configName != 0; ++i) {
if ((args & ConfigString[i].bit) == 0 && !config.lookupValue(ConfigString[i].configName, *ConfigString[i].value)) {
LOG_INFO("'" << ConfigString[i].configName << "' not found in the configuration file, using default: " << *ConfigString[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigString[i].configName, libconfig::Setting::TypeString) = *ConfigString[i].value;
}
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
struct {
const char *configName;
float* value;
unsigned int bit;
} ConfigFloat[] = {
{ "layerPadding", &LayerPadding, argLayerPadding },
{ "lonOff", &Lonoff, argLonoff },
{ "latOff", &Latoff, argLatoff },
{ "altOff", &Altoff, argAltoff },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigFloat[i].configName != 0; ++i) {
if ((args & ConfigFloat[i].bit) == 0 && !config.lookupValue(ConfigFloat[i].configName, *ConfigFloat[i].value)) {
LOG_INFO("'" << ConfigFloat[i].configName << "' not found in the configuration file, using default: " << *ConfigFloat[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigFloat[i].configName, libconfig::Setting::TypeFloat) = *ConfigFloat[i].value;
}
}
// open a message stream of live events for now
MessageStreamPtr ms(MessageStream::createNewMessageStream(serverName, service, start_timestamp, speed));
if (!ms) {
LOG_FATAL("Unable to create new message stream to server \"" << serverName << "\" using service (or port) \"" << service);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
if (relativeTS) {
ms->getMessageTimeRange();
} else {
LOG_INFO("Starting event playback");
ms->startStream();
}
srandom(time(0));//we use random() to select the icon below
WatcherGraph graph;
unsigned int messageNumber = 0;
MessagePtr mp;
time_t last_output = 0; // counter to allow for writing the kml file on a fixed time interval
bool changed = false;
bool needTimeRange = relativeTS;
LOG_INFO("Waiting for events ");
while (ms->getNextMessage(mp)) {
// std::cout << "Message #" << (++messageNumber) << ": " << *mp << std::endl;
if (needTimeRange) {
PlaybackTimeRangeMessagePtr trp(boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(mp));
if (trp.get() != 0) {
LOG_INFO( "first offset=" << trp->min_ << ", last offset=" << trp->max_ );
needTimeRange = false;
Timestamp off = start_timestamp + (( start_timestamp >= 0 ) ? trp->min_ : trp->max_ );
ms->setStreamTimeStart(off);
LOG_INFO("Starting event playback");
ms->startStream();
continue;
}
}
changed |= graph.updateGraph(mp);
if (changed) {
time_t now = time(0);
if (now - last_output >= refresh) {
graph.doMaintanence(); // expire stale links
LOG_DEBUG("writing kml file");
last_output = now;
write_kml(graph, outputFile);
}
changed = false; // reset flag
}
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
TRACE_EXIT_RET(0);
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2014, 2016 IBM Corporation and others
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
#ifndef SystemModelInBuilding_hpp
#define SystemModelInBuilding_hpp
#include <stdio.h>
#include "RandomWalker.hpp"
#include "RandomWalkerMotion.hpp"
#include "Building.hpp"
namespace loc{
class SystemModelInBuildingProperty{
double probabilityUp_ = 0.25;
double probabilityDown_ = 0.25;
double probabilityStay_ = 0.5;
double probabilityFloorJump_ = 0.0;
double wallCrossingAliveRate_ = 1.0; // fixed value
double maxIncidenceAngle_ = 45/180*M_PI;
// Field velocity rate
double velocityRateFloor_ = 1.0;
double velocityRateStair_ = 0.5;
double velocityRateElevator_ = 0.5;
double velocityRateEscalator_ = 0.5;
double relativeVelocityEscalator_ = 0.4;
double weightDecayRate_ = 0.9;
int maxTrial_ = 1; // fixed value
public:
using Ptr = std::shared_ptr<SystemModelInBuildingProperty>;
SystemModelInBuildingProperty& probabilityUp(double probabilityUp);
SystemModelInBuildingProperty& probabilityDown(double probabilityDown);
SystemModelInBuildingProperty& probabilityStay(double probabilityStay);
SystemModelInBuildingProperty& wallCrossingAliveRate(double wallCrossingAliveRate);
SystemModelInBuildingProperty& maxIncidenceAngle(double maxIncidenceAngle);
SystemModelInBuildingProperty& velocityRateFloor(double velocityRateFloor);
SystemModelInBuildingProperty& velocityRateStair(double velocityRateStair);
SystemModelInBuildingProperty& velocityRateElevator(double velocityRateElevator);
SystemModelInBuildingProperty& velocityRateEscalator(double velocityRateEscalator);
SystemModelInBuildingProperty& relativeVelocityEscalator(double relativeVelocityEscalator);
SystemModelInBuildingProperty& weightDecayRate(double weightDecayRate);
double probabilityUp() const;
double probabilityDown() const;
double probabilityStay() const;
double wallCrossingAliveRate() const;
double maxIncidenceAngle() const;
double velocityRateFloor() const;
double velocityRateStair() const;
double velocityRateElevator() const;
double velocityRateEscalator() const;
double relativeVelocityEscalator() const;
double weightDecayRate() const;
int maxTrial() const;
SystemModelInBuildingProperty& probabilityFloorJump(double probability);
double probabilityFloorJump() const;
};
template<class Tstate, class Tinput>
class SystemModelInBuilding: public SystemModel<Tstate, Tinput>{
public:
using SystemModelT = SystemModel<Tstate, Tinput>;
using Ptr = std::shared_ptr<SystemModelInBuilding>;
private:
RandomGenerator mRandomGenerator;
typename SystemModel<Tstate, Tinput>::Ptr mSysModel;
Building::Ptr mBuilding;
SystemModelInBuildingProperty::Ptr mProperty;
Tstate moveOnElevator(const Tstate& state, Tinput input);
Tstate moveOnStair(const Tstate& state, Tinput input);
Tstate moveOnEscalator(const Tstate& state, Tinput input);
Tstate moveOnFloor(const Tstate& state, Tinput input);
Tstate moveOnFloorRetry(const Tstate& state, const Tstate& stateNew, Tinput input);
Tstate moveFloorJump(const Tstate& state, Tinput input);
public:
SystemModelInBuilding() = default;
virtual ~SystemModelInBuilding() = default;
SystemModelInBuilding(typename SystemModelT::Ptr poseRandomWalker, Building::Ptr building, SystemModelInBuildingProperty::Ptr property);
SystemModelInBuilding& systemModel(typename SystemModelT::Ptr sysModel);
SystemModelInBuilding& building(Building::Ptr building);
SystemModelInBuilding& property(SystemModelInBuildingProperty::Ptr property);
Tstate predict(Tstate state, Tinput input) override;
std::vector<Tstate> predict(std::vector<Tstate> states, Tinput input) override;
virtual void notifyObservationUpdated() override;
};
// This class is retained for compatibility.
using PoseRandomWalkerInBuildingProperty = SystemModelInBuildingProperty;
class PoseRandomWalkerInBuilding: public SystemModelInBuilding<State, SystemModelInput>{
public:
using Ptr = std::shared_ptr<PoseRandomWalkerInBuilding>;
virtual ~PoseRandomWalkerInBuilding() = default;
virtual void poseRandomWalkerInBuildingProperty(SystemModelInBuildingProperty::Ptr property){
SystemModelInBuilding<State, SystemModelInput>::property(property);
}
virtual void poseRandomWalker(typename SystemModel<State, SystemModelInput>::Ptr sysModel){
SystemModelInBuilding<State, SystemModelInput>::systemModel(sysModel);
}
};
}
#endif /* SystemModelInBuilding_hpp */
<commit_msg>Updated default value of velocity parameters<commit_after>/*******************************************************************************
* Copyright (c) 2014, 2016 IBM Corporation and others
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
#ifndef SystemModelInBuilding_hpp
#define SystemModelInBuilding_hpp
#include <stdio.h>
#include "RandomWalker.hpp"
#include "RandomWalkerMotion.hpp"
#include "Building.hpp"
namespace loc{
class SystemModelInBuildingProperty{
double probabilityUp_ = 0.1;
double probabilityDown_ = 0.1;
double probabilityStay_ = 0.8;
double probabilityFloorJump_ = 0.0;
double wallCrossingAliveRate_ = 1.0; // fixed value
double maxIncidenceAngle_ = 45/180*M_PI;
// Field velocity rate
double velocityRateFloor_ = 1.0;
double velocityRateStair_ = 0.5;
double velocityRateElevator_ = 0.5;
double velocityRateEscalator_ = 0.5;
double relativeVelocityEscalator_ = 0.4;
double weightDecayRate_ = 0.9;
int maxTrial_ = 1; // fixed value
public:
using Ptr = std::shared_ptr<SystemModelInBuildingProperty>;
SystemModelInBuildingProperty& probabilityUp(double probabilityUp);
SystemModelInBuildingProperty& probabilityDown(double probabilityDown);
SystemModelInBuildingProperty& probabilityStay(double probabilityStay);
SystemModelInBuildingProperty& wallCrossingAliveRate(double wallCrossingAliveRate);
SystemModelInBuildingProperty& maxIncidenceAngle(double maxIncidenceAngle);
SystemModelInBuildingProperty& velocityRateFloor(double velocityRateFloor);
SystemModelInBuildingProperty& velocityRateStair(double velocityRateStair);
SystemModelInBuildingProperty& velocityRateElevator(double velocityRateElevator);
SystemModelInBuildingProperty& velocityRateEscalator(double velocityRateEscalator);
SystemModelInBuildingProperty& relativeVelocityEscalator(double relativeVelocityEscalator);
SystemModelInBuildingProperty& weightDecayRate(double weightDecayRate);
double probabilityUp() const;
double probabilityDown() const;
double probabilityStay() const;
double wallCrossingAliveRate() const;
double maxIncidenceAngle() const;
double velocityRateFloor() const;
double velocityRateStair() const;
double velocityRateElevator() const;
double velocityRateEscalator() const;
double relativeVelocityEscalator() const;
double weightDecayRate() const;
int maxTrial() const;
SystemModelInBuildingProperty& probabilityFloorJump(double probability);
double probabilityFloorJump() const;
};
template<class Tstate, class Tinput>
class SystemModelInBuilding: public SystemModel<Tstate, Tinput>{
public:
using SystemModelT = SystemModel<Tstate, Tinput>;
using Ptr = std::shared_ptr<SystemModelInBuilding>;
private:
RandomGenerator mRandomGenerator;
typename SystemModel<Tstate, Tinput>::Ptr mSysModel;
Building::Ptr mBuilding;
SystemModelInBuildingProperty::Ptr mProperty;
Tstate moveOnElevator(const Tstate& state, Tinput input);
Tstate moveOnStair(const Tstate& state, Tinput input);
Tstate moveOnEscalator(const Tstate& state, Tinput input);
Tstate moveOnFloor(const Tstate& state, Tinput input);
Tstate moveOnFloorRetry(const Tstate& state, const Tstate& stateNew, Tinput input);
Tstate moveFloorJump(const Tstate& state, Tinput input);
public:
SystemModelInBuilding() = default;
virtual ~SystemModelInBuilding() = default;
SystemModelInBuilding(typename SystemModelT::Ptr poseRandomWalker, Building::Ptr building, SystemModelInBuildingProperty::Ptr property);
SystemModelInBuilding& systemModel(typename SystemModelT::Ptr sysModel);
SystemModelInBuilding& building(Building::Ptr building);
SystemModelInBuilding& property(SystemModelInBuildingProperty::Ptr property);
Tstate predict(Tstate state, Tinput input) override;
std::vector<Tstate> predict(std::vector<Tstate> states, Tinput input) override;
virtual void notifyObservationUpdated() override;
};
// This class is retained for compatibility.
using PoseRandomWalkerInBuildingProperty = SystemModelInBuildingProperty;
class PoseRandomWalkerInBuilding: public SystemModelInBuilding<State, SystemModelInput>{
public:
using Ptr = std::shared_ptr<PoseRandomWalkerInBuilding>;
virtual ~PoseRandomWalkerInBuilding() = default;
virtual void poseRandomWalkerInBuildingProperty(SystemModelInBuildingProperty::Ptr property){
SystemModelInBuilding<State, SystemModelInput>::property(property);
}
virtual void poseRandomWalker(typename SystemModel<State, SystemModelInput>::Ptr sysModel){
SystemModelInBuilding<State, SystemModelInput>::systemModel(sysModel);
}
};
}
#endif /* SystemModelInBuilding_hpp */
<|endoftext|> |
<commit_before>// Copyright (C) 2013 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
#include "theia/image/keypoint_detector/sift_detector.h"
extern "C" {
#include <vl/sift.h>
}
#include <vector>
#include "theia/image/image.h"
#include "theia/image/keypoint_detector/keypoint.h"
namespace theia {
SiftDetector::~SiftDetector() {
if (sift_filter_ != nullptr)
vl_sift_delete(sift_filter_);
}
bool SiftDetector::DetectKeypoints(const FloatImage& image,
std::vector<Keypoint>* keypoints) {
// If the filter has been set, but is not usable for the input image (i.e. the
// width and height are different) then we must make a new filter. Adding this
// statement will save the function from regenerating the filter for
// successive calls with images of the same size (e.g. a video sequence).
if (sift_filter_ == nullptr || (sift_filter_->width != image.Cols() ||
sift_filter_->height != image.Rows())) {
vl_sift_delete(sift_filter_);
sift_filter_ = vl_sift_new(image.Cols(), image.Rows(),
sift_params_.num_octaves,
sift_params_.num_levels,
sift_params_.first_octave);
vl_sift_set_edge_thresh(sift_filter_, sift_params_.edge_threshold);
vl_sift_set_peak_thresh(sift_filter_, sift_params_.peak_threshold);
}
// The VLFeat functions take in a non-const image pointer so that it can
// calculate gaussian pyramids. Obviously, we do not want to break our const
// input, so the best solution (for now) is to copy the image.
FloatImage mutable_image(image.AsGrayscaleImage());
// Calculate the first octave to process.
int vl_status = vl_sift_process_first_octave(sift_filter_,
mutable_image.Data());
// Reserve an amount that is slightly larger than what a typical detector
// would return.
keypoints->reserve(2000);
// Process octaves until you can't anymore.
while (vl_status != VL_ERR_EOF) {
// Detect the keypoints.
vl_sift_detect(sift_filter_);
// Get the keypoints.
const VlSiftKeypoint* vl_keypoints = vl_sift_get_keypoints(sift_filter_);
int num_keypoints = vl_sift_get_nkeypoints(sift_filter_);
for (int i = 0; i < num_keypoints; i++) {
// Calculate (up to 4) orientations of the keypoint.
double angles[4];
int num_angles = vl_sift_calc_keypoint_orientations(sift_filter_,
angles,
&vl_keypoints[i]);
// If upright sift is enabled, only use the first keypoint at a given
// pixel location.
if (sift_params_.upright_sift && num_angles > 1) {
num_angles = 1;
}
for (int j = 0; j < num_angles; j++) {
Keypoint keypoint(vl_keypoints[i].x, vl_keypoints[i].y, Keypoint::SIFT);
keypoint.set_scale(vl_keypoints[i].sigma);
keypoint.set_orientation(angles[j]);
keypoints->push_back(keypoint);
}
}
// Attempt to process the next octave.
vl_status = vl_sift_process_next_octave(sift_filter_);
}
return true;
}
} // namespace theia
<commit_msg>Disable array-bounds diagnostics<commit_after>// Copyright (C) 2013 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney ([email protected])
#include "theia/image/keypoint_detector/sift_detector.h"
extern "C" {
#include <vl/sift.h>
}
#include <vector>
#include "theia/image/image.h"
#include "theia/image/keypoint_detector/keypoint.h"
namespace theia {
SiftDetector::~SiftDetector() {
if (sift_filter_ != nullptr)
vl_sift_delete(sift_filter_);
}
bool SiftDetector::DetectKeypoints(const FloatImage& image,
std::vector<Keypoint>* keypoints) {
// If the filter has been set, but is not usable for the input image (i.e. the
// width and height are different) then we must make a new filter. Adding this
// statement will save the function from regenerating the filter for
// successive calls with images of the same size (e.g. a video sequence).
if (sift_filter_ == nullptr || (sift_filter_->width != image.Cols() ||
sift_filter_->height != image.Rows())) {
vl_sift_delete(sift_filter_);
sift_filter_ = vl_sift_new(image.Cols(), image.Rows(),
sift_params_.num_octaves,
sift_params_.num_levels,
sift_params_.first_octave);
vl_sift_set_edge_thresh(sift_filter_, sift_params_.edge_threshold);
vl_sift_set_peak_thresh(sift_filter_, sift_params_.peak_threshold);
}
// The VLFeat functions take in a non-const image pointer so that it can
// calculate gaussian pyramids. Obviously, we do not want to break our const
// input, so the best solution (for now) is to copy the image.
FloatImage mutable_image(image.AsGrayscaleImage());
// Calculate the first octave to process.
int vl_status = vl_sift_process_first_octave(sift_filter_,
mutable_image.Data());
// Reserve an amount that is slightly larger than what a typical detector
// would return.
keypoints->reserve(2000);
// Process octaves until you can't anymore.
while (vl_status != VL_ERR_EOF) {
// Detect the keypoints.
vl_sift_detect(sift_filter_);
// Get the keypoints.
const VlSiftKeypoint* vl_keypoints = vl_sift_get_keypoints(sift_filter_);
int num_keypoints = vl_sift_get_nkeypoints(sift_filter_);
for (int i = 0; i < num_keypoints; i++) {
// Calculate (up to 4) orientations of the keypoint.
double angles[4];
int num_angles = vl_sift_calc_keypoint_orientations(sift_filter_,
angles,
&vl_keypoints[i]);
// If upright sift is enabled, only use the first keypoint at a given
// pixel location.
if (sift_params_.upright_sift && num_angles > 1) {
num_angles = 1;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
for (int j = 0; j < num_angles; j++) {
Keypoint keypoint(vl_keypoints[i].x, vl_keypoints[i].y, Keypoint::SIFT);
keypoint.set_scale(vl_keypoints[i].sigma);
keypoint.set_orientation(angles[j]);
keypoints->push_back(keypoint);
}
#pragma GCC diagnostic pop
}
// Attempt to process the next octave.
vl_status = vl_sift_process_next_octave(sift_filter_);
}
return true;
}
} // namespace theia
<|endoftext|> |
<commit_before>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your *
* option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#include <QApplication>
#include <QMatrix4x4>
#include <qoglviewer.h>
#include <vec.h>
#include <QMouseEvent>
#include <core/cmap/cmap2.h>
#include <io/map_import.h>
#include <geometry/algos/bounding_box.h>
#include <rendering/map_render.h>
#include <rendering/shaders/shader_flat.h>
#include <rendering/shaders/vbo.h>
#include <rendering/drawer.h>
#include <geometry/algos/picking.h>
#define DEFAULT_MESH_PATH CGOGN_STR(CGOGN_TEST_MESHES_PATH)
using Map2 = cgogn::CMap2<cgogn::DefaultMapTraits>;
//using Vec3 = Eigen::Vector3d;
using Vec3 = cgogn::geometry::Vec_T<std::array<double,3>>;
template<typename T>
using VertexAttributeHandler = Map2::VertexAttributeHandler<T>;
class Viewer : public QOGLViewer
{
public:
Viewer();
Viewer(const Viewer&) = delete;
Viewer& operator=(const Viewer&) = delete;
virtual void draw();
virtual void init();
virtual void mousePressEvent(QMouseEvent *e);
virtual void keyPressEvent(QKeyEvent *);
void import(const std::string& surfaceMesh);
virtual ~Viewer();
private:
void rayClick(QMouseEvent* event, QVector3D& P, QVector3D& Q);
QRect viewport_;
QMatrix4x4 proj_;
QMatrix4x4 view_;
Map2 map_;
VertexAttributeHandler<Vec3> vertex_position_;
cgogn::geometry::BoundingBox<Vec3> bb_;
cgogn::rendering::MapRender* render_;
cgogn::rendering::VBO* vbo_pos_;
cgogn::rendering::ShaderFlat* shader2_;
cgogn::rendering::Drawer* drawer_;
int cell_picking;
};
//
// IMPLEMENTATION
//
void Viewer::import(const std::string& surfaceMesh)
{
cgogn::io::import_surface<Vec3>(map_, surfaceMesh);
vertex_position_ = map_.get_attribute<Vec3, Map2::Vertex::ORBIT>("position");
cgogn::geometry::compute_bounding_box(vertex_position_, bb_);
setSceneRadius(bb_.diag_size()/2.0);
Vec3 center = bb_.center();
setSceneCenter(qoglviewer::Vec(center[0], center[1], center[2]));
showEntireScene();
}
Viewer::~Viewer()
{
delete render_;
delete vbo_pos_;
delete shader2_;
}
Viewer::Viewer() :
map_(),
vertex_position_(),
bb_(),
render_(nullptr),
vbo_pos_(nullptr),
shader2_(nullptr),
drawer_(nullptr),
cell_picking(0)
{}
void Viewer::draw()
{
camera()->getProjectionMatrix(proj_);
camera()->getModelViewMatrix(view_);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0f, 1.0f);
shader2_->bind();
shader2_->set_matrices(proj_,view_);
shader2_->bind_vao(0);
render_->draw(cgogn::rendering::TRIANGLES);
shader2_->release_vao(0);
shader2_->release();
glDisable(GL_POLYGON_OFFSET_FILL);
drawer_->call_list(proj_,view_);
}
void Viewer::init()
{
glClearColor(0.1f,0.1f,0.3f,0.0f);
vbo_pos_ = new cgogn::rendering::VBO(3);
cgogn::rendering::update_vbo(vertex_position_, *vbo_pos_);
render_ = new cgogn::rendering::MapRender();
render_->init_primitives<Vec3>(map_, cgogn::rendering::TRIANGLES, vertex_position_);
shader2_ = new cgogn::rendering::ShaderFlat;
shader2_->add_vao();
shader2_->set_vao(0, vbo_pos_);
shader2_->bind();
shader2_->set_front_color(QColor(0,200,0));
shader2_->set_back_color(QColor(0,0,200));
shader2_->set_ambiant_color(QColor(5,5,5));
shader2_->release();
drawer_ = new cgogn::rendering::Drawer(this);
}
void Viewer::rayClick(QMouseEvent* event, QVector3D& P, QVector3D& Q)
{
int vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
QRect viewport = QRect(vp[0],vp[1],vp[2],vp[3]);
unsigned int x = event->x()*devicePixelRatio();
unsigned int y = (this->height()-event->y())*devicePixelRatio();
QVector3D wp(x,y,0.01);
P = wp.unproject(view_,proj_,viewport);
QVector3D wq(x,y,0.99);
Q = wq.unproject(view_,proj_,viewport);
}
void Viewer::keyPressEvent(QKeyEvent *ev)
{
switch (ev->key())
{
case Qt::Key_0:
cell_picking = 0;
break;
case Qt::Key_1:
cell_picking = 1;
break;
case Qt::Key_2:
cell_picking = 2;
break;
case Qt::Key_3:
cell_picking = 3;
break;
}
QOGLViewer::keyPressEvent(ev);
}
void Viewer::mousePressEvent(QMouseEvent* event)
{
if (event->modifiers() & Qt::ShiftModifier)
{
QVector3D P;
QVector3D Q;
rayClick(event,P,Q);
Vec3 A(P[0],P[1],P[2]);
Vec3 B(Q[0],Q[1],Q[2]);
drawer_->new_list();
switch(cell_picking)
{
case 0:
{
std::vector<Map2::Vertex> selected;
cgogn::geometry::picking_vertex<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected vertices: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->point_size_aa(4.0);
drawer_->begin(GL_POINTS);
// closest point in red
drawer_->color3f(1.0,0.0,0.0);
drawer_->vertex3fv(vertex_position_[selected[0]]);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
drawer_->vertex3fv(vertex_position_[selected[i]]);
drawer_->end();
}
}
break;
case 1:
{
std::vector<Map2::Edge> selected;
cgogn::geometry::picking_edge<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected edges: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_edge_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_edge_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
case 2:
{
std::vector<Map2::Face> selected;
cgogn::geometry::picking_face<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected faces: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_face_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_face_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
case 3:
{
std::vector<Map2::Volume> selected;
cgogn::geometry::picking_volume<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected volumes: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_volume_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_volume_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
}
drawer_->end_list();
}
QOGLViewer::mousePressEvent(event);
}
int main(int argc, char** argv)
{
std::string surfaceMesh;
if (argc < 2)
{
std::cout << "USAGE: " << argv[0] << " [filename]" << std::endl;
surfaceMesh = std::string(DEFAULT_MESH_PATH) + std::string("aneurysm3D_1.off");
std::cout << "Using default mesh : " << surfaceMesh << std::endl;
}
else
surfaceMesh = std::string(argv[1]);
QApplication application(argc, argv);
qoglviewer::init_ogl_context();
// Instantiate the viewer.
Viewer viewer;
viewer.setWindowTitle("simpleViewer");
viewer.import(surfaceMesh);
viewer.show();
viewer.resize(800,600);
// Run main loop.
return application.exec();
}
<commit_msg>remove feature supported only in Qt 5.5<commit_after>/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your *
* option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#include <QApplication>
#include <QMatrix4x4>
#include <qoglviewer.h>
#include <vec.h>
#include <QMouseEvent>
#include <QVector3D>
#include <core/cmap/cmap2.h>
#include <io/map_import.h>
#include <geometry/algos/bounding_box.h>
#include <rendering/map_render.h>
#include <rendering/shaders/shader_flat.h>
#include <rendering/shaders/vbo.h>
#include <rendering/drawer.h>
#include <geometry/algos/picking.h>
#define DEFAULT_MESH_PATH CGOGN_STR(CGOGN_TEST_MESHES_PATH)
using Map2 = cgogn::CMap2<cgogn::DefaultMapTraits>;
//using Vec3 = Eigen::Vector3d;
using Vec3 = cgogn::geometry::Vec_T<std::array<double,3>>;
template<typename T>
using VertexAttributeHandler = Map2::VertexAttributeHandler<T>;
class Viewer : public QOGLViewer
{
public:
Viewer();
Viewer(const Viewer&) = delete;
Viewer& operator=(const Viewer&) = delete;
virtual void draw();
virtual void init();
virtual void mousePressEvent(QMouseEvent *e);
virtual void keyPressEvent(QKeyEvent *);
void import(const std::string& surfaceMesh);
virtual ~Viewer();
private:
void rayClick(QMouseEvent* event, qoglviewer::Vec& P, qoglviewer::Vec& Q);
QRect viewport_;
QMatrix4x4 proj_;
QMatrix4x4 view_;
Map2 map_;
VertexAttributeHandler<Vec3> vertex_position_;
cgogn::geometry::BoundingBox<Vec3> bb_;
cgogn::rendering::MapRender* render_;
cgogn::rendering::VBO* vbo_pos_;
cgogn::rendering::ShaderFlat* shader2_;
cgogn::rendering::Drawer* drawer_;
int cell_picking;
};
//
// IMPLEMENTATION
//
void Viewer::import(const std::string& surfaceMesh)
{
cgogn::io::import_surface<Vec3>(map_, surfaceMesh);
vertex_position_ = map_.get_attribute<Vec3, Map2::Vertex::ORBIT>("position");
cgogn::geometry::compute_bounding_box(vertex_position_, bb_);
setSceneRadius(bb_.diag_size()/2.0);
Vec3 center = bb_.center();
setSceneCenter(qoglviewer::Vec(center[0], center[1], center[2]));
showEntireScene();
}
Viewer::~Viewer()
{
delete render_;
delete vbo_pos_;
delete shader2_;
}
Viewer::Viewer() :
map_(),
vertex_position_(),
bb_(),
render_(nullptr),
vbo_pos_(nullptr),
shader2_(nullptr),
drawer_(nullptr),
cell_picking(0)
{}
void Viewer::draw()
{
camera()->getProjectionMatrix(proj_);
camera()->getModelViewMatrix(view_);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0f, 1.0f);
shader2_->bind();
shader2_->set_matrices(proj_,view_);
shader2_->bind_vao(0);
render_->draw(cgogn::rendering::TRIANGLES);
shader2_->release_vao(0);
shader2_->release();
glDisable(GL_POLYGON_OFFSET_FILL);
drawer_->call_list(proj_,view_);
}
void Viewer::init()
{
glClearColor(0.1f,0.1f,0.3f,0.0f);
vbo_pos_ = new cgogn::rendering::VBO(3);
cgogn::rendering::update_vbo(vertex_position_, *vbo_pos_);
render_ = new cgogn::rendering::MapRender();
render_->init_primitives<Vec3>(map_, cgogn::rendering::TRIANGLES, vertex_position_);
shader2_ = new cgogn::rendering::ShaderFlat;
shader2_->add_vao();
shader2_->set_vao(0, vbo_pos_);
shader2_->bind();
shader2_->set_front_color(QColor(0,200,0));
shader2_->set_back_color(QColor(0,0,200));
shader2_->set_ambiant_color(QColor(5,5,5));
shader2_->release();
drawer_ = new cgogn::rendering::Drawer(this);
}
void Viewer::rayClick(QMouseEvent* event, qoglviewer::Vec& P, qoglviewer::Vec& Q)
{
P = camera()->unprojectedCoordinatesOf(qoglviewer::Vec(event->x(),event->y(),0.01));
Q = camera()->unprojectedCoordinatesOf(qoglviewer::Vec(event->x(),event->y(),0.99));
}
void Viewer::keyPressEvent(QKeyEvent *ev)
{
switch (ev->key())
{
case Qt::Key_0:
cell_picking = 0;
break;
case Qt::Key_1:
cell_picking = 1;
break;
case Qt::Key_2:
cell_picking = 2;
break;
case Qt::Key_3:
cell_picking = 3;
break;
}
QOGLViewer::keyPressEvent(ev);
}
void Viewer::mousePressEvent(QMouseEvent* event)
{
if (event->modifiers() & Qt::ShiftModifier)
{
qoglviewer::Vec P;
qoglviewer::Vec Q;
rayClick(event,P,Q);
Vec3 A(P[0],P[1],P[2]);
Vec3 B(Q[0],Q[1],Q[2]);
drawer_->new_list();
switch(cell_picking)
{
case 0:
{
std::vector<Map2::Vertex> selected;
cgogn::geometry::picking_vertex<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected vertices: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->point_size_aa(4.0);
drawer_->begin(GL_POINTS);
// closest point in red
drawer_->color3f(1.0,0.0,0.0);
drawer_->vertex3fv(vertex_position_[selected[0]]);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
drawer_->vertex3fv(vertex_position_[selected[i]]);
drawer_->end();
}
}
break;
case 1:
{
std::vector<Map2::Edge> selected;
cgogn::geometry::picking_edge<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected edges: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_edge_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_edge_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
case 2:
{
std::vector<Map2::Face> selected;
cgogn::geometry::picking_face<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected faces: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_face_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_face_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
case 3:
{
std::vector<Map2::Volume> selected;
cgogn::geometry::picking_volume<Vec3>(map_,vertex_position_,A,B,selected);
std::cout<< "Selected volumes: "<< selected.size()<<std::endl;
if (!selected.empty())
{
drawer_->line_width(2.0);
drawer_->begin(GL_LINES);
// closest face in red
drawer_->color3f(1.0,0.0,0.0);
cgogn::rendering::add_volume_to_drawer<Vec3>(map_,selected[0],vertex_position_,drawer_);
// others in yellow
drawer_->color3f(1.0,1.0,0.0);
for(unsigned int i=1u;i<selected.size();++i)
cgogn::rendering::add_volume_to_drawer<Vec3>(map_,selected[i],vertex_position_,drawer_);
drawer_->end();
}
}
break;
}
drawer_->end_list();
}
QOGLViewer::mousePressEvent(event);
}
int main(int argc, char** argv)
{
std::string surfaceMesh;
if (argc < 2)
{
std::cout << "USAGE: " << argv[0] << " [filename]" << std::endl;
surfaceMesh = std::string(DEFAULT_MESH_PATH) + std::string("aneurysm3D_1.off");
std::cout << "Using default mesh : " << surfaceMesh << std::endl;
}
else
surfaceMesh = std::string(argv[1]);
QApplication application(argc, argv);
qoglviewer::init_ogl_context();
// Instantiate the viewer.
Viewer viewer;
viewer.setWindowTitle("simpleViewer");
viewer.import(surfaceMesh);
viewer.show();
viewer.resize(800,600);
// Run main loop.
return application.exec();
}
<|endoftext|> |
<commit_before>#include <memory_cache_serversettings.h>
#include <log.h>
#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QByteArray>
#include <QDateTime>
#include <QDir>
// IMemoryCache
QString MemoryCacheServerSettings::name(){
return "serversettings";
}
// ---------------------------------------------------------------------
MemoryCacheServerSettings::MemoryCacheServerSettings(IWebSocketServer *pWebSocketServer){
m_pWebSocketServer = pWebSocketServer;
TAG = "MemoryCacheServerSettings";
QString sGroupProfile = "profile";
addNewSetting(new ServerSettHelper(sGroupProfile, "profile_change_nick", true));
QString sGroupMail = "mail";
addNewSetting(new ServerSettHelper(sGroupMail, "mail_from", QString("[email protected]")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_host", QString("ssl://smtp.gmail.com")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_port", 465));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_username", QString("[email protected]")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_password", QString("some"), true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_auth", true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_allow", true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_system_message_admin_email", QString("")));
// Google Map API
QString sGroupGoogleMap = "google_map";
addNewSetting(new ServerSettHelper(sGroupGoogleMap, "google_map_api_key", QString("some")));
// server folders
QString sGroupServerFolders = "server_folders";
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_games", QString("/var/www/html/fhq/files/games/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_games_url", QString("https://freehackquest.com/files/games/")));
QStringList listFoundInDatabase;
QSqlDatabase db = *(pWebSocketServer->database());
// load from database
{
QSqlQuery query(db);
query.prepare("SELECT * FROM settings");
query.exec();
while (query.next()) {
QSqlRecord record = query.record();
QString sName = record.value("name").toString();
QString sValue = record.value("value").toString();
QString sType = record.value("type").toString();
QString sGroup = record.value("group").toString();
listFoundInDatabase << sName;
if(m_mapSettings.contains(sName)){
ServerSettHelper *pServerSettHelper = m_mapSettings[sName];
if(sType != pServerSettHelper->type()){
Log::err(TAG, "Wrong type for setting '" + sName + "' (expected '" + pServerSettHelper->type() + "', but got: '" + sType + "'");
// TODO change type of setting or remove
}else{
if(pServerSettHelper->isString()){
pServerSettHelper->setValue(sValue);
}else if(pServerSettHelper->isBoolean()){
pServerSettHelper->setValue(sValue == "yes");
}else if(pServerSettHelper->isInteger()){
// TODO check convertation string to int
pServerSettHelper->setValue(sValue.toInt());
}else if(pServerSettHelper->isPassword()){
pServerSettHelper->setValue(sValue);
}else{
Log::err(TAG, "No handle type for setting '" + sName + "'");
}
}
}else{
Log::warn(TAG, "Undefined settings name in database: " + sName);
}
}
}
// check string settings in database
foreach( QString sKey, m_mapSettings.keys()){
if(!listFoundInDatabase.contains(sKey)){
ServerSettHelper *pServerSettHelper = m_mapSettings.value(sKey);
initSettingDatabase(pServerSettHelper);
}
}
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::addNewSetting(ServerSettHelper* pServerSettHelper){
QString sName = pServerSettHelper->name();
if(!m_mapSettings.contains(sName)){
m_mapSettings[sName] = pServerSettHelper;
}else{
Log::warn(TAG, "Duplicate setting '" + sName + "'. Skip");
}
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettString(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
QString sResult = "";
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isString()){
Log::err(TAG, "Wrong type setting string (get): " + sName);
}else{
sResult = pServerSettHelper->valueAsString();
}
}else{
Log::err(TAG, "Not found server setting string (get): " + sName);
}
return sResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettString(QString sName, QString sValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isString()){
Log::err(TAG, "Wrong type setting string (set): " + sName);
}else{
pServerSettHelper->setValue(sValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting string (set): " + sName);
}
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettPassword(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
QString sResult = "";
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isPassword()){
Log::err(TAG, "Wrong type setting password (get): " + sName);
}else{
sResult = pServerSettHelper->valueAsString();
}
}else{
Log::err(TAG, "Not found server setting password (get): " + sName);
}
return sResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettPassword(QString sName, QString sValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isPassword()){
Log::err(TAG, "Wrong type setting string (set): " + sName);
}else{
pServerSettHelper->setValue(sValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting string (set): " + sName);
}
}
// ---------------------------------------------------------------------
int MemoryCacheServerSettings::getSettInteger(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
int nResult = 0;
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isInteger()){
Log::err(TAG, "Wrong type setting integer (get): " + sName);
}else{
nResult = pServerSettHelper->valueAsInteger();
}
}else{
Log::err(TAG, "Not found server setting integer (get): " + sName);
}
return nResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettInteger(QString sName, int nValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isInteger()){
Log::err(TAG, "Wrong type setting integer (set): " + sName);
}else{
pServerSettHelper->setValue(nValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting integer (set): " + sName);
}
}
// ---------------------------------------------------------------------
bool MemoryCacheServerSettings::getSettBoolean(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
bool bResult = false;
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isBoolean()){
Log::err(TAG, "Wrong type setting boolean (get): " + sName);
}else{
bResult = pServerSettHelper->valueAsBoolean();
}
}else{
Log::err(TAG, "Not found server setting boolean (get): " + sName);
}
return bResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettBoolean(QString sName, bool bValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isBoolean()){
Log::err(TAG, "Wrong type setting boolean (set): " + sName);
}else{
pServerSettHelper->setValue(bValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting integer (set): " + sName);
}
}
// ---------------------------------------------------------------------
bool MemoryCacheServerSettings::hasSett(QString sName){
return m_mapSettings.contains(sName);
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettType(QString sName){
if(m_mapSettings.contains(sName)){
return m_mapSettings[sName]->type();
}
return "";
}
// ---------------------------------------------------------------------
QJsonArray MemoryCacheServerSettings::toJsonArray(){
QJsonArray res;
foreach( QString sName, m_mapSettings.keys()){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
QJsonObject sett;
sett["name"] = pServerSettHelper->name();
if(pServerSettHelper->isBoolean()){
sett["value"] = pServerSettHelper->valueAsBoolean();
}else if(pServerSettHelper->isString()){
sett["value"] = pServerSettHelper->valueAsString();
}else if(pServerSettHelper->isInteger()){
sett["value"] = pServerSettHelper->valueAsInteger();
}else if(pServerSettHelper->isPassword()){
sett["value"] = "******";
}else{
sett["value"] = pServerSettHelper->valueAsString();
}
sett["group"] = pServerSettHelper->group();
sett["type"] = pServerSettHelper->type();
res.append(sett);
}
return res;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::initSettingDatabase(ServerSettHelper *pServerSettHelper){
Log::info(TAG, "Init settings to database: " + pServerSettHelper->name());
QSqlDatabase db = *(m_pWebSocketServer->database());
QSqlQuery query(db);
query.prepare("INSERT INTO settings (`name`, `value`, `group`, `type`) VALUES (:name, :value, :group, :type)");
query.bindValue(":name", pServerSettHelper->name());
query.bindValue(":value", pServerSettHelper->valueAsString());
query.bindValue(":group", pServerSettHelper->group());
query.bindValue(":type", pServerSettHelper->type());
if(!query.exec()){
Log::err(TAG, query.lastError().text());
}
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::updateSettingDatabase(ServerSettHelper *pServerSettHelper){
QSqlDatabase db = *(m_pWebSocketServer->database());
QSqlQuery query(db);
query.prepare("UPDATE settings SET value = :value WHERE name = :name");
query.bindValue(":value", pServerSettHelper->valueAsString());
query.bindValue(":name", pServerSettHelper->name());
if(!query.exec()){
Log::err(TAG, query.lastError().text());
}
}
<commit_msg>Updated server settings<commit_after>#include <memory_cache_serversettings.h>
#include <log.h>
#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QByteArray>
#include <QDateTime>
#include <QDir>
// IMemoryCache
QString MemoryCacheServerSettings::name(){
return "serversettings";
}
// ---------------------------------------------------------------------
MemoryCacheServerSettings::MemoryCacheServerSettings(IWebSocketServer *pWebSocketServer){
m_pWebSocketServer = pWebSocketServer;
TAG = "MemoryCacheServerSettings";
QString sGroupProfile = "profile";
addNewSetting(new ServerSettHelper(sGroupProfile, "profile_change_nick", true));
QString sGroupMail = "mail";
addNewSetting(new ServerSettHelper(sGroupMail, "mail_from", QString("[email protected]")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_host", QString("ssl://smtp.gmail.com")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_port", 465));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_username", QString("[email protected]")));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_password", QString("some"), true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_auth", true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_allow", true));
addNewSetting(new ServerSettHelper(sGroupMail, "mail_system_message_admin_email", QString("")));
// Google Map API
QString sGroupGoogleMap = "google_map";
addNewSetting(new ServerSettHelper(sGroupGoogleMap, "google_map_api_key", QString("some")));
// server folders
QString sGroupServerFolders = "server_folders";
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_games", QString("/var/www/html/fhq/files/games/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_games_url", QString("https://freehackquest.com/files/games/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_quests", QString("/var/www/html/fhq/files/quests/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_quests_url", QString("https://freehackquest.com/files/quests/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_users", QString("/var/www/html/fhq/files/quests/")));
addNewSetting(new ServerSettHelper(sGroupServerFolders, "server_folder_users_url", QString("https://freehackquest.com/files/quests/")));
QStringList listFoundInDatabase;
QSqlDatabase db = *(pWebSocketServer->database());
// load from database
{
QSqlQuery query(db);
query.prepare("SELECT * FROM settings");
query.exec();
while (query.next()) {
QSqlRecord record = query.record();
QString sName = record.value("name").toString();
QString sValue = record.value("value").toString();
QString sType = record.value("type").toString();
QString sGroup = record.value("group").toString();
listFoundInDatabase << sName;
if(m_mapSettings.contains(sName)){
ServerSettHelper *pServerSettHelper = m_mapSettings[sName];
if(sType != pServerSettHelper->type()){
Log::err(TAG, "Wrong type for setting '" + sName + "' (expected '" + pServerSettHelper->type() + "', but got: '" + sType + "'");
// TODO change type of setting or remove
}else{
if(pServerSettHelper->isString()){
pServerSettHelper->setValue(sValue);
}else if(pServerSettHelper->isBoolean()){
pServerSettHelper->setValue(sValue == "yes");
}else if(pServerSettHelper->isInteger()){
// TODO check convertation string to int
pServerSettHelper->setValue(sValue.toInt());
}else if(pServerSettHelper->isPassword()){
pServerSettHelper->setValue(sValue);
}else{
Log::err(TAG, "No handle type for setting '" + sName + "'");
}
}
}else{
Log::warn(TAG, "Undefined settings name in database: " + sName);
}
}
}
// check string settings in database
foreach( QString sKey, m_mapSettings.keys()){
if(!listFoundInDatabase.contains(sKey)){
ServerSettHelper *pServerSettHelper = m_mapSettings.value(sKey);
initSettingDatabase(pServerSettHelper);
}
}
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::addNewSetting(ServerSettHelper* pServerSettHelper){
QString sName = pServerSettHelper->name();
if(!m_mapSettings.contains(sName)){
m_mapSettings[sName] = pServerSettHelper;
}else{
Log::warn(TAG, "Duplicate setting '" + sName + "'. Skip");
}
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettString(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
QString sResult = "";
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isString()){
Log::err(TAG, "Wrong type setting string (get): " + sName);
}else{
sResult = pServerSettHelper->valueAsString();
}
}else{
Log::err(TAG, "Not found server setting string (get): " + sName);
}
return sResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettString(QString sName, QString sValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isString()){
Log::err(TAG, "Wrong type setting string (set): " + sName);
}else{
pServerSettHelper->setValue(sValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting string (set): " + sName);
}
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettPassword(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
QString sResult = "";
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isPassword()){
Log::err(TAG, "Wrong type setting password (get): " + sName);
}else{
sResult = pServerSettHelper->valueAsString();
}
}else{
Log::err(TAG, "Not found server setting password (get): " + sName);
}
return sResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettPassword(QString sName, QString sValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isPassword()){
Log::err(TAG, "Wrong type setting string (set): " + sName);
}else{
pServerSettHelper->setValue(sValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting string (set): " + sName);
}
}
// ---------------------------------------------------------------------
int MemoryCacheServerSettings::getSettInteger(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
int nResult = 0;
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isInteger()){
Log::err(TAG, "Wrong type setting integer (get): " + sName);
}else{
nResult = pServerSettHelper->valueAsInteger();
}
}else{
Log::err(TAG, "Not found server setting integer (get): " + sName);
}
return nResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettInteger(QString sName, int nValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isInteger()){
Log::err(TAG, "Wrong type setting integer (set): " + sName);
}else{
pServerSettHelper->setValue(nValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting integer (set): " + sName);
}
}
// ---------------------------------------------------------------------
bool MemoryCacheServerSettings::getSettBoolean(QString sName){
QMutexLocker locker (&m_mtxServerSettings);
bool bResult = false;
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isBoolean()){
Log::err(TAG, "Wrong type setting boolean (get): " + sName);
}else{
bResult = pServerSettHelper->valueAsBoolean();
}
}else{
Log::err(TAG, "Not found server setting boolean (get): " + sName);
}
return bResult;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::setSettBoolean(QString sName, bool bValue){
QMutexLocker locker (&m_mtxServerSettings);
if(m_mapSettings.contains(sName)){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
if(!pServerSettHelper->isBoolean()){
Log::err(TAG, "Wrong type setting boolean (set): " + sName);
}else{
pServerSettHelper->setValue(bValue);
updateSettingDatabase(pServerSettHelper);
}
}else{
Log::err(TAG, "Not found server setting integer (set): " + sName);
}
}
// ---------------------------------------------------------------------
bool MemoryCacheServerSettings::hasSett(QString sName){
return m_mapSettings.contains(sName);
}
// ---------------------------------------------------------------------
QString MemoryCacheServerSettings::getSettType(QString sName){
if(m_mapSettings.contains(sName)){
return m_mapSettings[sName]->type();
}
return "";
}
// ---------------------------------------------------------------------
QJsonArray MemoryCacheServerSettings::toJsonArray(){
QJsonArray res;
foreach( QString sName, m_mapSettings.keys()){
ServerSettHelper* pServerSettHelper = m_mapSettings.value(sName);
QJsonObject sett;
sett["name"] = pServerSettHelper->name();
if(pServerSettHelper->isBoolean()){
sett["value"] = pServerSettHelper->valueAsBoolean();
}else if(pServerSettHelper->isString()){
sett["value"] = pServerSettHelper->valueAsString();
}else if(pServerSettHelper->isInteger()){
sett["value"] = pServerSettHelper->valueAsInteger();
}else if(pServerSettHelper->isPassword()){
sett["value"] = "******";
}else{
sett["value"] = pServerSettHelper->valueAsString();
}
sett["group"] = pServerSettHelper->group();
sett["type"] = pServerSettHelper->type();
res.append(sett);
}
return res;
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::initSettingDatabase(ServerSettHelper *pServerSettHelper){
Log::info(TAG, "Init settings to database: " + pServerSettHelper->name());
QSqlDatabase db = *(m_pWebSocketServer->database());
QSqlQuery query(db);
query.prepare("INSERT INTO settings (`name`, `value`, `group`, `type`) VALUES (:name, :value, :group, :type)");
query.bindValue(":name", pServerSettHelper->name());
query.bindValue(":value", pServerSettHelper->valueAsString());
query.bindValue(":group", pServerSettHelper->group());
query.bindValue(":type", pServerSettHelper->type());
if(!query.exec()){
Log::err(TAG, query.lastError().text());
}
}
// ---------------------------------------------------------------------
void MemoryCacheServerSettings::updateSettingDatabase(ServerSettHelper *pServerSettHelper){
QSqlDatabase db = *(m_pWebSocketServer->database());
QSqlQuery query(db);
query.prepare("UPDATE settings SET value = :value WHERE name = :name");
query.bindValue(":value", pServerSettHelper->valueAsString());
query.bindValue(":name", pServerSettHelper->name());
if(!query.exec()){
Log::err(TAG, query.lastError().text());
}
}
<|endoftext|> |
<commit_before>#ifndef utf8_hh_INCLUDED
#define utf8_hh_INCLUDED
#include "assert.hh"
#include "unicode.hh"
#include "units.hh"
#include <cstddef>
namespace Kakoune
{
namespace utf8
{
template<typename Iterator>
[[gnu::always_inline]]
inline char read(Iterator& it) noexcept { char c = *it; ++it; return c; }
// return true if it points to the first byte of a (either single or
// multibyte) character
[[gnu::always_inline]]
inline bool is_character_start(char c) noexcept
{
return (c & 0xC0) != 0x80;
}
namespace InvalidPolicy
{
struct Assert
{
Codepoint operator()(Codepoint cp) const { kak_assert(false); return cp; }
};
struct Pass
{
Codepoint operator()(Codepoint cp) const noexcept { return cp; }
};
}
// returns the codepoint of the character whose first byte
// is pointed by it
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass,
typename Iterator>
Codepoint read_codepoint(Iterator& it, const Iterator& end)
noexcept(noexcept(InvalidPolicy{}(0)))
{
if (it == end)
return InvalidPolicy{}(-1);
// According to rfc3629, UTF-8 allows only up to 4 bytes.
// (21 bits codepoint)
unsigned char byte = read(it);
if ((byte & 0x80) == 0) // 0xxxxxxx
return byte;
if (it == end)
return InvalidPolicy{}(byte);
if ((byte & 0xE0) == 0xC0) // 110xxxxx
return ((byte & 0x1F) << 6) | (read(it) & 0x3F);
if ((byte & 0xF0) == 0xE0) // 1110xxxx
{
Codepoint cp = ((byte & 0x0F) << 12) | ((read(it) & 0x3F) << 6);
if (it == end)
return InvalidPolicy{}(cp);
return cp | (read(it) & 0x3F);
}
if ((byte & 0xF8) == 0xF0) // 11110xxx
{
Codepoint cp = ((byte & 0x0F) << 18) | ((read(it) & 0x3F) << 12);
if (it == end)
return InvalidPolicy{}(cp);
cp |= (read(it) & 0x3F) << 6;
if (it == end)
return InvalidPolicy{}(cp);
return cp | (read(it) & 0x3F);
}
return InvalidPolicy{}(byte);
}
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass,
typename Iterator>
Codepoint codepoint(Iterator it, const Iterator& end)
noexcept(noexcept(read_codepoint<InvalidPolicy>(it, end)))
{
return read_codepoint<InvalidPolicy>(it, end);
}
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass>
ByteCount codepoint_size(char byte)
noexcept(noexcept(InvalidPolicy{}(0)))
{
if ((byte & 0x80) == 0) // 0xxxxxxx
return 1;
else if ((byte & 0xE0) == 0xC0) // 110xxxxx
return 2;
else if ((byte & 0xF0) == 0xE0) // 1110xxxx
return 3;
else if ((byte & 0xF8) == 0xF0) // 11110xxx
return 4;
else
{
InvalidPolicy{}(byte);
return 1;
}
}
struct invalid_codepoint{};
inline ByteCount codepoint_size(Codepoint cp)
{
if (cp <= 0x7F)
return 1;
else if (cp <= 0x7FF)
return 2;
else if (cp <= 0xFFFF)
return 3;
else if (cp <= 0x10FFFF)
return 4;
else
throw invalid_codepoint{};
}
template<typename Iterator>
void to_next(Iterator& it, const Iterator& end) noexcept
{
if (it != end)
++it;
while (it != end and not is_character_start(*it))
++it;
}
// returns an iterator to next character first byte
template<typename Iterator>
Iterator next(Iterator it, const Iterator& end) noexcept
{
to_next(it, end);
return it;
}
// returns it's parameter if it points to a character first byte,
// or else returns next character first byte
template<typename Iterator>
Iterator finish(Iterator it, const Iterator& end) noexcept
{
while (it != end and (*(it) & 0xC0) == 0x80)
++it;
return it;
}
template<typename Iterator>
void to_previous(Iterator& it, const Iterator& begin) noexcept
{
if (it != begin)
--it;
while (not is_character_start(*it))
--it;
}
// returns an iterator to the previous character first byte
template<typename Iterator>
Iterator previous(Iterator it, const Iterator& begin) noexcept
{
to_previous(it, begin);
return it;
}
// returns an iterator pointing to the first byte of the
// dth character after (or before if d < 0) the character
// pointed by it
template<typename Iterator>
Iterator advance(Iterator it, const Iterator& end, CharCount d) noexcept
{
if (it == end)
return it;
if (d < 0)
{
while (it != end and d++ != 0)
to_previous(it, end);
}
else if (d > 0)
{
while (it != end and d-- != 0)
to_next(it, end);
}
return it;
}
// returns an iterator pointing to the first byte of the
// character at the dth column after (or before if d < 0)
// the character pointed by it
template<typename Iterator>
Iterator advance(Iterator it, const Iterator& end, ColumnCount d) noexcept
{
if (it == end)
return it;
if (d < 0)
{
while (it != end and d < 0)
{
auto cur = it;
to_previous(it, end);
d += codepoint_width(codepoint(it, cur));
}
}
else if (d > 0)
{
auto begin = it;
while (it != end and d > 0)
{
d -= codepoint_width(read_codepoint(it, end));
if (it != end and d < 0)
to_previous(it, begin);
}
}
return it;
}
// returns the character count between begin and end
template<typename Iterator>
CharCount distance(Iterator begin, const Iterator& end) noexcept
{
CharCount dist = 0;
while (begin != end)
{
if (is_character_start(read(begin)))
++dist;
}
return dist;
}
// returns the column count between begin and end
template<typename Iterator>
ColumnCount column_distance(Iterator begin, const Iterator& end) noexcept
{
ColumnCount dist = 0;
while (begin != end)
dist += codepoint_width(read_codepoint(begin, end));
return dist;
}
// returns an iterator to the first byte of the character it is into
template<typename Iterator>
Iterator character_start(Iterator it, const Iterator& begin) noexcept
{
while (it != begin and not is_character_start(*it))
--it;
return it;
}
template<typename OutputIterator>
void dump(OutputIterator&& it, Codepoint cp)
{
if (cp <= 0x7F)
*it++ = cp;
else if (cp <= 0x7FF)
{
*it++ = 0xC0 | (cp >> 6);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0xFFFF)
{
*it++ = 0xE0 | (cp >> 12);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0x10FFFF)
{
*it++ = 0xF0 | (cp >> 18);
*it++ = 0x80 | ((cp >> 12) & 0x3F);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else
throw invalid_codepoint{};
}
}
}
#endif // utf8_hh_INCLUDED
<commit_msg>Fix utf8::to_previous that could go before the begin iterator<commit_after>#ifndef utf8_hh_INCLUDED
#define utf8_hh_INCLUDED
#include "assert.hh"
#include "unicode.hh"
#include "units.hh"
#include <cstddef>
namespace Kakoune
{
namespace utf8
{
template<typename Iterator>
[[gnu::always_inline]]
inline char read(Iterator& it) noexcept { char c = *it; ++it; return c; }
// return true if it points to the first byte of a (either single or
// multibyte) character
[[gnu::always_inline]]
inline bool is_character_start(char c) noexcept
{
return (c & 0xC0) != 0x80;
}
namespace InvalidPolicy
{
struct Assert
{
Codepoint operator()(Codepoint cp) const { kak_assert(false); return cp; }
};
struct Pass
{
Codepoint operator()(Codepoint cp) const noexcept { return cp; }
};
}
// returns the codepoint of the character whose first byte
// is pointed by it
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass,
typename Iterator>
Codepoint read_codepoint(Iterator& it, const Iterator& end)
noexcept(noexcept(InvalidPolicy{}(0)))
{
if (it == end)
return InvalidPolicy{}(-1);
// According to rfc3629, UTF-8 allows only up to 4 bytes.
// (21 bits codepoint)
unsigned char byte = read(it);
if ((byte & 0x80) == 0) // 0xxxxxxx
return byte;
if (it == end)
return InvalidPolicy{}(byte);
if ((byte & 0xE0) == 0xC0) // 110xxxxx
return ((byte & 0x1F) << 6) | (read(it) & 0x3F);
if ((byte & 0xF0) == 0xE0) // 1110xxxx
{
Codepoint cp = ((byte & 0x0F) << 12) | ((read(it) & 0x3F) << 6);
if (it == end)
return InvalidPolicy{}(cp);
return cp | (read(it) & 0x3F);
}
if ((byte & 0xF8) == 0xF0) // 11110xxx
{
Codepoint cp = ((byte & 0x0F) << 18) | ((read(it) & 0x3F) << 12);
if (it == end)
return InvalidPolicy{}(cp);
cp |= (read(it) & 0x3F) << 6;
if (it == end)
return InvalidPolicy{}(cp);
return cp | (read(it) & 0x3F);
}
return InvalidPolicy{}(byte);
}
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass,
typename Iterator>
Codepoint codepoint(Iterator it, const Iterator& end)
noexcept(noexcept(read_codepoint<InvalidPolicy>(it, end)))
{
return read_codepoint<InvalidPolicy>(it, end);
}
template<typename InvalidPolicy = utf8::InvalidPolicy::Pass>
ByteCount codepoint_size(char byte)
noexcept(noexcept(InvalidPolicy{}(0)))
{
if ((byte & 0x80) == 0) // 0xxxxxxx
return 1;
else if ((byte & 0xE0) == 0xC0) // 110xxxxx
return 2;
else if ((byte & 0xF0) == 0xE0) // 1110xxxx
return 3;
else if ((byte & 0xF8) == 0xF0) // 11110xxx
return 4;
else
{
InvalidPolicy{}(byte);
return 1;
}
}
struct invalid_codepoint{};
inline ByteCount codepoint_size(Codepoint cp)
{
if (cp <= 0x7F)
return 1;
else if (cp <= 0x7FF)
return 2;
else if (cp <= 0xFFFF)
return 3;
else if (cp <= 0x10FFFF)
return 4;
else
throw invalid_codepoint{};
}
template<typename Iterator>
void to_next(Iterator& it, const Iterator& end) noexcept
{
if (it != end)
++it;
while (it != end and not is_character_start(*it))
++it;
}
// returns an iterator to next character first byte
template<typename Iterator>
Iterator next(Iterator it, const Iterator& end) noexcept
{
to_next(it, end);
return it;
}
// returns it's parameter if it points to a character first byte,
// or else returns next character first byte
template<typename Iterator>
Iterator finish(Iterator it, const Iterator& end) noexcept
{
while (it != end and (*(it) & 0xC0) == 0x80)
++it;
return it;
}
template<typename Iterator>
void to_previous(Iterator& it, const Iterator& begin) noexcept
{
if (it != begin)
--it;
while (it != begin and not is_character_start(*it))
--it;
}
// returns an iterator to the previous character first byte
template<typename Iterator>
Iterator previous(Iterator it, const Iterator& begin) noexcept
{
to_previous(it, begin);
return it;
}
// returns an iterator pointing to the first byte of the
// dth character after (or before if d < 0) the character
// pointed by it
template<typename Iterator>
Iterator advance(Iterator it, const Iterator& end, CharCount d) noexcept
{
if (it == end)
return it;
if (d < 0)
{
while (it != end and d++ != 0)
to_previous(it, end);
}
else if (d > 0)
{
while (it != end and d-- != 0)
to_next(it, end);
}
return it;
}
// returns an iterator pointing to the first byte of the
// character at the dth column after (or before if d < 0)
// the character pointed by it
template<typename Iterator>
Iterator advance(Iterator it, const Iterator& end, ColumnCount d) noexcept
{
if (it == end)
return it;
if (d < 0)
{
while (it != end and d < 0)
{
auto cur = it;
to_previous(it, end);
d += codepoint_width(codepoint(it, cur));
}
}
else if (d > 0)
{
auto begin = it;
while (it != end and d > 0)
{
d -= codepoint_width(read_codepoint(it, end));
if (it != end and d < 0)
to_previous(it, begin);
}
}
return it;
}
// returns the character count between begin and end
template<typename Iterator>
CharCount distance(Iterator begin, const Iterator& end) noexcept
{
CharCount dist = 0;
while (begin != end)
{
if (is_character_start(read(begin)))
++dist;
}
return dist;
}
// returns the column count between begin and end
template<typename Iterator>
ColumnCount column_distance(Iterator begin, const Iterator& end) noexcept
{
ColumnCount dist = 0;
while (begin != end)
dist += codepoint_width(read_codepoint(begin, end));
return dist;
}
// returns an iterator to the first byte of the character it is into
template<typename Iterator>
Iterator character_start(Iterator it, const Iterator& begin) noexcept
{
while (it != begin and not is_character_start(*it))
--it;
return it;
}
template<typename OutputIterator>
void dump(OutputIterator&& it, Codepoint cp)
{
if (cp <= 0x7F)
*it++ = cp;
else if (cp <= 0x7FF)
{
*it++ = 0xC0 | (cp >> 6);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0xFFFF)
{
*it++ = 0xE0 | (cp >> 12);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0x10FFFF)
{
*it++ = 0xF0 | (cp >> 18);
*it++ = 0x80 | ((cp >> 12) & 0x3F);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else
throw invalid_codepoint{};
}
}
}
#endif // utf8_hh_INCLUDED
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MasterPagesPanel.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-07-13 14:44:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "MasterPagesPanel.hxx"
#include "../ScrollPanel.hxx"
#include "CurrentMasterPagesSelector.hxx"
#include "RecentMasterPagesSelector.hxx"
#include "AllMasterPagesSelector.hxx"
#include "DrawViewShell.hxx"
#include "ViewShellBase.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
namespace sd { namespace toolpanel { namespace controls {
MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase)
: SubToolPanel (pParent)
{
SdDrawDocument* pDocument = rBase.GetDocument();
ScrollPanel* pScrollPanel = new ScrollPanel (this);
// Create a panel with the master pages that are in use by the currently
// edited document.
DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>(
rBase.GetMainViewShell());
controls::MasterPagesSelector* pSelector
= new controls::CurrentMasterPagesSelector (
this,
*pDocument,
rBase,
*pDrawViewShell);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE));
// Create a panel with the most recently used master pages.
pSelector = new controls::RecentMasterPagesSelector (
this,
*pDocument,
rBase);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE));
// Create a panel with all available master pages.
pSelector = new controls::AllMasterPagesSelector (
this,
*pDocument,
rBase,
*pDrawViewShell);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE));
AddControl (::std::auto_ptr<TreeNode>(pScrollPanel));
}
MasterPagesPanel::~MasterPagesPanel (void)
{
}
} } } // end of namespace ::sd::toolpanel::controls
<commit_msg>INTEGRATION: CWS presentationengine01 (1.2.12); FILE MERGED 2004/09/30 15:40:22 af 1.2.12.1: #i34242# Added support for help ids.<commit_after>/*************************************************************************
*
* $RCSfile: MasterPagesPanel.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-11-26 20:26:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "MasterPagesPanel.hxx"
#include "../ScrollPanel.hxx"
#include "CurrentMasterPagesSelector.hxx"
#include "RecentMasterPagesSelector.hxx"
#include "AllMasterPagesSelector.hxx"
#include "DrawViewShell.hxx"
#include "ViewShellBase.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#include "helpids.h"
namespace sd { namespace toolpanel { namespace controls {
MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase)
: SubToolPanel (pParent)
{
SdDrawDocument* pDocument = rBase.GetDocument();
ScrollPanel* pScrollPanel = new ScrollPanel (this);
// Create a panel with the master pages that are in use by the currently
// edited document.
DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>(
rBase.GetMainViewShell());
controls::MasterPagesSelector* pSelector
= new controls::CurrentMasterPagesSelector (
this,
*pDocument,
rBase,
*pDrawViewShell);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE),
HID_SD_CURRENT_MASTERS);
// Create a panel with the most recently used master pages.
pSelector = new controls::RecentMasterPagesSelector (
this,
*pDocument,
rBase);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE),
HID_SD_RECENT_MASTERS);
// Create a panel with all available master pages.
pSelector = new controls::AllMasterPagesSelector (
this,
*pDocument,
rBase,
*pDrawViewShell);
pSelector->LateInit();
pScrollPanel->AddControl (
::std::auto_ptr<TreeNode>(pSelector),
SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE),
HID_SD_ALL_MASTERS);
AddControl (::std::auto_ptr<TreeNode>(pScrollPanel));
}
MasterPagesPanel::~MasterPagesPanel (void)
{
}
} } } // end of namespace ::sd::toolpanel::controls
<|endoftext|> |
<commit_before>//
// Copyright (C) 2006-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
#include <mp/MpCodecFactory.h>
#include <os/OsTime.h>
#include <os/OsDateTime.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>
/// Sample rate in samples per second.
#define SAMPLE_RATE 8000
/// Size of audio frame in samples.
#define FRAME_SIZE 80
/// Maximum length of audio data we expect from decoder in samples.
#define DECODED_FRAME_MAX_SIZE (FRAME_SIZE*6)
/// Maximum size of encoded frame in bytes.
#define ENCODED_FRAME_MAX_SIZE (FRAME_SIZE*sizeof(MpAudioSample))
/// Number of RTP packets to encode/decode.
#define NUM_PACKETS_TO_TEST 3
/// Unit test for testing performance of supported codecs.
class MpCodecsPerformanceTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(MpCodecsPerformanceTest);
CPPUNIT_TEST(testCodecsPreformance);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
// Create pool for data buffers
mpPool = new MpBufPool(ENCODED_FRAME_MAX_SIZE + MpArrayBuf::getHeaderSize(), 1);
CPPUNIT_ASSERT(mpPool != NULL);
// Create pool for buffer headers
mpHeadersPool = new MpBufPool(sizeof(MpRtpBuf), 1);
CPPUNIT_ASSERT(mpHeadersPool != NULL);
// Set mpHeadersPool as default pool for audio and data pools.
MpRtpBuf::smpDefaultPool = mpHeadersPool;
}
void tearDown()
{
if (mpPool != NULL)
{
delete mpPool;
}
if (mpHeadersPool != NULL)
{
delete mpHeadersPool;
}
}
void testCodecsPreformance()
{
MpCodecFactory *pCodecFactory;
const UtlString *pCodecMimeTypes;
unsigned codecMimeTypesNum;
// Get/create codec factory
pCodecFactory = MpCodecFactory::getMpCodecFactory();
CPPUNIT_ASSERT(pCodecFactory != NULL);
// Load all available codecs
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pCodecFactory->loadAllDynCodecs(".", CODEC_PLUGINS_FILTER));
pCodecFactory->getMimeTypes(codecMimeTypesNum, (const UtlString*&)pCodecMimeTypes);
CPPUNIT_ASSERT(codecMimeTypesNum>0);
for (unsigned i=0; i<codecMimeTypesNum; i++)
{
const char **pCodecFmtps;
unsigned codecFmtpsNum;
pCodecFactory->getCodecFmtps(pCodecMimeTypes[i], codecFmtpsNum, pCodecFmtps);
if (codecFmtpsNum == 0)
{
testOneCodecPreformance(pCodecFactory, pCodecMimeTypes[i], "");
}
else
{
for (int fmtpNum=0; fmtpNum<codecFmtpsNum; fmtpNum++)
{
testOneCodecPreformance(pCodecFactory,
pCodecMimeTypes[i],
pCodecFmtps[fmtpNum]);
}
}
}
}
protected:
MpBufPool *mpPool; ///< Pool for data buffers
MpBufPool *mpHeadersPool; ///< Pool for buffers headers
void testOneCodecPreformance(MpCodecFactory *pCodecFactory,
const UtlString &codecMime,
const UtlString &codecFmtp,
int sampleRate,
int numChannels)
{
MpDecoderBase *pDecoder;
MpEncoderBase *pEncoder;
MpAudioSample pOriginal[FRAME_SIZE];
MpAudioSample pDecoded[DECODED_FRAME_MAX_SIZE];
int encodeFrameNum = 0;
// Create and initialize decoder and encoder
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pCodecFactory->createDecoder(codecMime, codecFmtp,
sampleRate, numChannels,
0, pDecoder));
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pDecoder->initDecode());
// Could not test speed of signaling codec
if (pDecoder->getInfo()->isSignalingCodec())
{
pDecoder->freeDecode();
delete pDecoder;
return;
}
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pCodecFactory->createEncoder(codecMime, codecFmtp, 0, pEncoder));
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pEncoder->initEncode());
for (int i=0; i<NUM_PACKETS_TO_TEST; i++)
{
int maxBytesPerPacket = (pEncoder->getInfo()->getMaxPacketBits() + 7) / 8;
int tmpSamplesConsumed;
int tmpEncodedSize;
UtlBoolean tmpSendNow;
MpAudioBuf::SpeechType tmpSpeechType;
MpRtpBufPtr pRtpPacket = mpPool->getBuffer();
unsigned char *pRtpPayloadPtr = (unsigned char *)pRtpPacket->getDataWritePtr();
int payloadSize = 0;
int samplesInPacket = 0;
OsTime start;
OsTime stop;
OsTime diff;
// Encode frames until we get tmpSendNow set or reach packet size limit.
do
{
// Encode one frame and measure time it took.
OsStatus result;
OsDateTime::getCurTime(start);
result = pEncoder->encode(pOriginal, FRAME_SIZE, tmpSamplesConsumed,
pRtpPayloadPtr,
ENCODED_FRAME_MAX_SIZE-payloadSize,
tmpEncodedSize, tmpSendNow,
tmpSpeechType);
OsDateTime::getCurTime(stop);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, result);
// Print timing in TSV format
diff = stop - start;
printf("encode %s %s;%d;%ld.%06ld;%ld.%06ld\n",
codecMime.data(), codecFmtp.data(),
encodeFrameNum,
start.seconds(), start.usecs(),
diff.seconds(), diff.usecs());
// Adjust encoding state
payloadSize += tmpEncodedSize;
pRtpPayloadPtr += tmpEncodedSize;
samplesInPacket += tmpSamplesConsumed;
CPPUNIT_ASSERT(payloadSize <= ENCODED_FRAME_MAX_SIZE);
encodeFrameNum++;
} while(! ((tmpSendNow == TRUE) || (maxBytesPerPacket == payloadSize)));
pRtpPacket->setPayloadSize(payloadSize);
// Decode frame, measure time and verify, that we decoded same number of samples.
OsDateTime::getCurTime(start);
tmpSamplesConsumed = pDecoder->decode(pRtpPacket, DECODED_FRAME_MAX_SIZE,
pDecoded);
OsDateTime::getCurTime(stop);
CPPUNIT_ASSERT_EQUAL(samplesInPacket, tmpSamplesConsumed);
// Print timing in TSV format
diff = stop - start;
printf("decode %s %s;%d;%ld.%06ld;%ld.%06ld\n",
codecMime.data(), codecFmtp.data(),
i,
start.seconds(), start.usecs(),
diff.seconds(), diff.usecs());
}
// Free encoder and decoder
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pDecoder->freeDecode());
delete pDecoder;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pEncoder->freeEncode());
delete pEncoder;
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(MpCodecsPerformanceTest);
<commit_msg>Update MpCodecsPerformanceTest to work with latest changes in codecs.<commit_after>//
// Copyright (C) 2006-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////
#include <mp/MpCodecFactory.h>
#include <os/OsTime.h>
#include <os/OsDateTime.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>
/// Sample rate in samples per second.
#define SAMPLE_RATE 8000
/// Size of audio frame in samples.
#define FRAME_SIZE 80
/// Maximum length of audio data we expect from decoder in samples.
#define DECODED_FRAME_MAX_SIZE (FRAME_SIZE*6)
/// Maximum size of encoded frame in bytes.
#define ENCODED_FRAME_MAX_SIZE (FRAME_SIZE*sizeof(MpAudioSample))
/// Number of RTP packets to encode/decode.
#define NUM_PACKETS_TO_TEST 3
/// Maximum number of milliseconds in packet.
#define MAX_PACKET_TIME 20
/// Maximum number of samples in packet.
#define MAX_PACKET_SAMPLES (MAX_PACKET_TIME*SAMPLE_RATE)/1000
// Setup codec paths..
static UtlString sCodecPaths[] = {
#ifdef WIN32
"bin",
"..\\bin",
#elif __pingtel_on_posix__
"../../../../bin",
"../../../bin",
#else
# error "Unknown platform"
#endif
"."
};
static size_t sNumCodecPaths = sizeof(sCodecPaths)/sizeof(sCodecPaths[0]);
/// Unit test for testing performance of supported codecs.
class MpCodecsPerformanceTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(MpCodecsPerformanceTest);
CPPUNIT_TEST(testCodecsPreformance);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
// Create pool for data buffers
mpPool = new MpBufPool(ENCODED_FRAME_MAX_SIZE + MpArrayBuf::getHeaderSize(), 1);
CPPUNIT_ASSERT(mpPool != NULL);
// Create pool for buffer headers
mpHeadersPool = new MpBufPool(sizeof(MpRtpBuf), 1);
CPPUNIT_ASSERT(mpHeadersPool != NULL);
// Set mpHeadersPool as default pool for audio and data pools.
MpRtpBuf::smpDefaultPool = mpHeadersPool;
}
void tearDown()
{
if (mpPool != NULL)
{
delete mpPool;
}
if (mpHeadersPool != NULL)
{
delete mpHeadersPool;
}
}
void testCodecsPreformance()
{
MpCodecFactory *pCodecFactory;
const MppCodecInfoV1_1 **pCodecInfo;
unsigned codecInfoNum;
// Get/create codec factory
pCodecFactory = MpCodecFactory::getMpCodecFactory();
CPPUNIT_ASSERT(pCodecFactory != NULL);
// Load all available codecs
size_t i;
for(i = 0; i < sNumCodecPaths; i++)
{
pCodecFactory->loadAllDynCodecs(sCodecPaths[i],
CODEC_PLUGINS_FILTER);
}
// Get list of loaded codecs
pCodecFactory->getCodecInfoArray(codecInfoNum, pCodecInfo);
CPPUNIT_ASSERT(codecInfoNum>0);
for (unsigned i=0; i<codecInfoNum; i++)
{
const char **pCodecFmtps;
unsigned codecFmtpsNum;
codecFmtpsNum = pCodecInfo[i]->fmtpsNum;
pCodecFmtps = pCodecInfo[i]->fmtps;
if (codecFmtpsNum == 0)
{
testOneCodecPreformance(pCodecFactory,
pCodecInfo[i]->mimeSubtype,
"",
pCodecInfo[i]->sampleRate,
pCodecInfo[i]->numChannels);
}
else
{
for (unsigned fmtpNum=0; fmtpNum<codecFmtpsNum; fmtpNum++)
{
testOneCodecPreformance(pCodecFactory,
pCodecInfo[i]->mimeSubtype,
pCodecFmtps[fmtpNum],
pCodecInfo[i]->sampleRate,
pCodecInfo[i]->numChannels);
}
}
}
// Free codec factory
MpCodecFactory::freeSingletonHandle();
}
protected:
MpBufPool *mpPool; ///< Pool for data buffers
MpBufPool *mpHeadersPool; ///< Pool for buffers headers
void testOneCodecPreformance(MpCodecFactory *pCodecFactory,
const UtlString &codecMime,
const UtlString &codecFmtp,
int sampleRate,
int numChannels)
{
MpDecoderBase *pDecoder;
MpEncoderBase *pEncoder;
MpAudioSample pOriginal[FRAME_SIZE];
MpAudioSample pDecoded[DECODED_FRAME_MAX_SIZE];
int encodeFrameNum = 0;
int codecFrameSamples;
// Create and initialize decoder and encoder
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pCodecFactory->createDecoder(codecMime, codecFmtp,
sampleRate, numChannels,
0, pDecoder));
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pDecoder->initDecode());
// Could not test speed of signaling codec
if (pDecoder->getInfo()->isSignalingCodec())
{
pDecoder->freeDecode();
delete pDecoder;
return;
}
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pCodecFactory->createEncoder(codecMime, codecFmtp,
sampleRate, numChannels,
0, pEncoder));
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pEncoder->initEncode());
// Get number of samples we'll pack to get one packet
if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_FRAME_BASED)
{
codecFrameSamples = pEncoder->getInfo()->getNumSamplesPerFrame();
}
else if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_SAMPLE_BASED)
{
codecFrameSamples = FRAME_SIZE;
}
else
{
assert(!"Unknown codec type!");
}
for (int i=0; i<NUM_PACKETS_TO_TEST; i++)
{
int tmpSamplesConsumed;
int tmpEncodedSize;
UtlBoolean tmpSendNow;
MpAudioBuf::SpeechType tmpSpeechType;
MpRtpBufPtr pRtpPacket = mpPool->getBuffer();
unsigned char *pRtpPayloadPtr = (unsigned char *)pRtpPacket->getDataWritePtr();
int payloadSize = 0;
int samplesInPacket = 0;
OsTime start;
OsTime stop;
OsTime diff;
// Encode frames until we get tmpSendNow set or reach packet size limit.
do
{
// Encode one frame and measure time it took.
OsStatus result;
OsDateTime::getCurTime(start);
result = pEncoder->encode(pOriginal, FRAME_SIZE, tmpSamplesConsumed,
pRtpPayloadPtr,
ENCODED_FRAME_MAX_SIZE-payloadSize,
tmpEncodedSize, tmpSendNow,
tmpSpeechType);
OsDateTime::getCurTime(stop);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, result);
// Print timing in TSV format
diff = stop - start;
printf("encode %s %s;%d;%ld.%06ld;%ld.%06ld\n",
codecMime.data(), codecFmtp.data(),
encodeFrameNum,
start.seconds(), start.usecs(),
diff.seconds(), diff.usecs());
// Adjust encoding state
payloadSize += tmpEncodedSize;
pRtpPayloadPtr += tmpEncodedSize;
samplesInPacket += tmpSamplesConsumed;
CPPUNIT_ASSERT(payloadSize <= ENCODED_FRAME_MAX_SIZE);
encodeFrameNum++;
} while( (tmpSendNow != TRUE) &&
(samplesInPacket+codecFrameSamples <= MAX_PACKET_SAMPLES));
pRtpPacket->setPayloadSize(payloadSize);
// Decode frame, measure time and verify, that we decoded same number of samples.
OsDateTime::getCurTime(start);
tmpSamplesConsumed = pDecoder->decode(pRtpPacket, DECODED_FRAME_MAX_SIZE,
pDecoded);
OsDateTime::getCurTime(stop);
CPPUNIT_ASSERT_EQUAL(samplesInPacket, tmpSamplesConsumed);
// Print timing in TSV format
diff = stop - start;
printf("decode %s %s;%d;%ld.%06ld;%ld.%06ld\n",
codecMime.data(), codecFmtp.data(),
i,
start.seconds(), start.usecs(),
diff.seconds(), diff.usecs());
}
// Free encoder and decoder
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pDecoder->freeDecode());
delete pDecoder;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
pEncoder->freeEncode());
delete pEncoder;
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(MpCodecsPerformanceTest);
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "indexing/value_index.h"
namespace zorba {
static store::Item_t get_uri(expr *e)
{
// The following two checks are required if we run after
// normalization. It does not hurt, otherwise -- so leave it
// here.
if (e->get_expr_kind() == promote_expr_kind) {
e = static_cast<promote_expr *>(e)->get_input();
}
if (is_data(e)) {
e = get_fo_arg(e, 0);
}
if (e->get_expr_kind() == const_expr_kind) {
return static_cast<const_expr *>(e)->get_val();
}
return NULL;
}
RULE_REWRITE_PRE(ExpandBuildIndex)
{
if (node->get_expr_kind() == fo_expr_kind) {
fo_expr *fo = static_cast<fo_expr *>(&*node);
if (fo->get_func() == LOOKUP_RESOLVED_FN(ZORBA_OPEXTENSIONS_NS, "build-index", 1)) {
store::Item_t uri_item(get_uri((*fo)[0].getp()));
if (uri_item == NULL) {
ZORBA_ASSERT(false);
}
xqpStringStore_t uristore;
uri_item->getStringValue(uristore);
xqp_string uri(uristore);
ValueIndex *vi = rCtx.getStaticContext()->lookup_index(uri);
if (vi == NULL) {
ZORBA_ASSERT(false);
}
std::vector<expr_t> se_args;
expr_t open_index_arg(new const_expr(fo->get_loc(), uri_item));
expr_t open_index(new fo_expr(fo->get_loc(), LOOKUP_OP1("index-session-opener"), open_index_arg));
se_args.push_back(open_index);
expr::substitution_t subst;
flwor_expr::clause_list_t clauses;
expr_t de = vi->getDomainExpression()->clone(subst);
var_expr_t dot = vi->getDomainVariable();
var_expr_t pos = vi->getDomainPositionVariable();
var_expr_t newdot = new var_expr(dot->get_loc(), dot->get_kind(), dot->get_varname());
var_expr_t newpos = new var_expr(pos->get_loc(), pos->get_kind(), pos->get_varname());
subst[dot] = newdot;
subst[pos] = newpos;
flwor_expr::forletref_t fc = new forlet_clause(forlet_clause::for_clause, newdot, newpos, NULL, de);
newdot->set_forlet_clause(fc);
newpos->set_forlet_clause(fc);
clauses.push_back(fc);
std::vector<expr_t> index_insert_args;
expr_t insert_index_uri(new const_expr(fo->get_loc(), uri_item));
index_insert_args.push_back(insert_index_uri);
expr_t insert_index_var(new wrapper_expr(fo->get_loc(), newdot));
index_insert_args.push_back(insert_index_var);
const std::vector<expr_t>& idx_fields(vi->getIndexFieldExpressions());
int n = idx_fields.size();
for(int i = 0; i < n; ++i) {
index_insert_args.push_back(idx_fields[i]->clone(subst));
}
expr_t re(new fo_expr(fo->get_loc(), LOOKUP_OPN("index-builder"), index_insert_args));
rchandle<flwor_expr> flwor = new flwor_expr(fo->get_loc(), clauses, re);
se_args.push_back(flwor.getp());
expr_t close_index_arg(new const_expr(fo->get_loc(), uri_item));
expr_t close_index(new fo_expr(fo->get_loc(), LOOKUP_OP1("index-session-closer"), close_index_arg));
se_args.push_back(close_index);
expr_t se = new sequential_expr(fo->get_loc(), se_args);
return se;
}
}
return NULL;
}
RULE_REWRITE_POST(ExpandBuildIndex)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>fix the windows build<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "indexing/value_index.h"
namespace zorba {
static store::Item_t get_uri(expr *e)
{
// The following two checks are required if we run after
// normalization. It does not hurt, otherwise -- so leave it
// here.
if (e->get_expr_kind() == promote_expr_kind) {
e = static_cast<promote_expr *>(e)->get_input();
}
if (is_data(e)) {
e = get_fo_arg(e, 0);
}
if (e->get_expr_kind() == const_expr_kind) {
return static_cast<const_expr *>(e)->get_val();
}
return NULL;
}
RULE_REWRITE_PRE(ExpandBuildIndex)
{
if (node->get_expr_kind() == fo_expr_kind) {
fo_expr *fo = static_cast<fo_expr *>(&*node);
if (fo->get_func() == LOOKUP_RESOLVED_FN(ZORBA_OPEXTENSIONS_NS, "build-index", 1)) {
store::Item_t uri_item(get_uri((*fo)[0].getp()));
if (uri_item == NULL) {
ZORBA_ASSERT(false);
}
xqpStringStore_t uristore;
uri_item->getStringValue(uristore);
xqp_string uri(uristore);
ValueIndex *vi = rCtx.getStaticContext()->lookup_index(uri);
if (vi == NULL) {
ZORBA_ASSERT(false);
}
std::vector<expr_t> se_args;
expr_t open_index_arg(new const_expr(fo->get_loc(), uri_item));
expr_t open_index(new fo_expr(fo->get_loc(), LOOKUP_OP1("index-session-opener"), open_index_arg));
se_args.push_back(open_index);
expr::substitution_t subst;
flwor_expr::clause_list_t clauses;
expr_t de = vi->getDomainExpression()->clone(subst);
var_expr_t dot = vi->getDomainVariable();
var_expr_t pos = vi->getDomainPositionVariable();
var_expr_t newdot = new var_expr(dot->get_loc(), dot->get_kind(), dot->get_varname());
var_expr_t newpos = new var_expr(pos->get_loc(), pos->get_kind(), pos->get_varname());
subst[dot] = newdot;
subst[pos] = newpos;
flwor_expr::forletref_t fc = new forlet_clause(forlet_clause::for_clause, newdot, newpos, NULL, de);
newdot->set_forlet_clause(fc);
newpos->set_forlet_clause(fc);
clauses.push_back(fc);
std::vector<expr_t> index_insert_args;
expr_t insert_index_uri(new const_expr(fo->get_loc(), uri_item));
index_insert_args.push_back(insert_index_uri);
expr_t insert_index_var(new wrapper_expr(fo->get_loc(), newdot.getp()));
index_insert_args.push_back(insert_index_var);
const std::vector<expr_t>& idx_fields(vi->getIndexFieldExpressions());
int n = idx_fields.size();
for(int i = 0; i < n; ++i) {
index_insert_args.push_back(idx_fields[i]->clone(subst));
}
expr_t re(new fo_expr(fo->get_loc(), LOOKUP_OPN("index-builder"), index_insert_args));
rchandle<flwor_expr> flwor = new flwor_expr(fo->get_loc(), clauses, re);
se_args.push_back(flwor.getp());
expr_t close_index_arg(new const_expr(fo->get_loc(), uri_item));
expr_t close_index(new fo_expr(fo->get_loc(), LOOKUP_OP1("index-session-closer"), close_index_arg));
se_args.push_back(close_index);
expr_t se = new sequential_expr(fo->get_loc(), se_args);
return se;
}
}
return NULL;
}
RULE_REWRITE_POST(ExpandBuildIndex)
{
return NULL;
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
* - Laura Schlimmer <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/cli/commands/cluster_remove_server.h>
#include <eventql/util/cli/flagparser.h>
#include "eventql/config/config_directory.h"
#include "eventql/util/random.h"
namespace eventql {
namespace cli {
const String ClusterRemoveServer::kName_ = "cluster-remove-server";
const String ClusterRemoveServer::kDescription_ =
"Remove an existing server from an existing cluster.";
ClusterRemoveServer::ClusterRemoveServer(
RefPtr<ProcessConfig> process_cfg) :
process_cfg_(process_cfg) {}
Status ClusterRemoveServer::execute(
const std::vector<std::string>& argv,
FileInputStream* stdin_is,
OutputStream* stdout_os,
OutputStream* stderr_os) {
::cli::FlagParser flags;
flags.defineFlag(
"server_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
flags.defineFlag(
"soft",
::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"switch",
"<switch>");
flags.defineFlag(
"hard",
::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"switch",
"<string>");
try {
flags.parseArgv(argv);
bool remove_hard = flags.isSet("hard");
bool remove_soft = flags.isSet("soft");
if (!(remove_hard ^ remove_soft)) {
stderr_os->write("ERROR: either --hard or --soft must be set\n");
return Status(eFlagError);
}
ScopedPtr<ConfigDirectory> cdir;
{
auto rc = ConfigDirectoryFactory::getConfigDirectoryForClient(
process_cfg_.get(),
&cdir);
if (rc.isSuccess()) {
rc = cdir->start();
}
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return rc;
}
}
auto cfg = cdir->getServerConfig(flags.getString("server_name"));
if (remove_soft) {
cfg.set_is_leaving(true);
}
if (remove_hard) {
cfg.set_is_dead(true);
}
cdir->updateServerConfig(cfg);
cdir->stop();
} catch (const Exception& e) {
stderr_os->write(StringUtil::format(
"$0: $1\n",
e.getTypeName(),
e.getMessage()));
return Status(e);
}
return Status::success();
}
const String& ClusterRemoveServer::getName() const {
return kName_;
}
const String& ClusterRemoveServer::getDescription() const {
return kDescription_;
}
void ClusterRemoveServer::printHelp(OutputStream* stdout_os) const {
stdout_os->write(StringUtil::format(
"\nevqlctl-$0 - $1\n\n", kName_, kDescription_));
stdout_os->write(
"Usage: evqlctl cluster-remove-server [OPTIONS]\n"
" --server_name The name of the server to add.\n"
" --soft Enable the soft-leave operation.\n"
" --hard Enable the hard-leave operation.\n");
}
} // namespace cli
} // namespace eventql
<commit_msg>evqlctl cluster-remove-server help message typo<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
* - Laura Schlimmer <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/cli/commands/cluster_remove_server.h>
#include <eventql/util/cli/flagparser.h>
#include "eventql/config/config_directory.h"
#include "eventql/util/random.h"
namespace eventql {
namespace cli {
const String ClusterRemoveServer::kName_ = "cluster-remove-server";
const String ClusterRemoveServer::kDescription_ =
"Remove an existing server from an existing cluster.";
ClusterRemoveServer::ClusterRemoveServer(
RefPtr<ProcessConfig> process_cfg) :
process_cfg_(process_cfg) {}
Status ClusterRemoveServer::execute(
const std::vector<std::string>& argv,
FileInputStream* stdin_is,
OutputStream* stdout_os,
OutputStream* stderr_os) {
::cli::FlagParser flags;
flags.defineFlag(
"server_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
flags.defineFlag(
"soft",
::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"switch",
"<switch>");
flags.defineFlag(
"hard",
::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"switch",
"<string>");
try {
flags.parseArgv(argv);
bool remove_hard = flags.isSet("hard");
bool remove_soft = flags.isSet("soft");
if (!(remove_hard ^ remove_soft)) {
stderr_os->write("ERROR: either --hard or --soft must be set\n");
return Status(eFlagError);
}
ScopedPtr<ConfigDirectory> cdir;
{
auto rc = ConfigDirectoryFactory::getConfigDirectoryForClient(
process_cfg_.get(),
&cdir);
if (rc.isSuccess()) {
rc = cdir->start();
}
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return rc;
}
}
auto cfg = cdir->getServerConfig(flags.getString("server_name"));
if (remove_soft) {
cfg.set_is_leaving(true);
}
if (remove_hard) {
cfg.set_is_dead(true);
}
cdir->updateServerConfig(cfg);
cdir->stop();
} catch (const Exception& e) {
stderr_os->write(StringUtil::format(
"$0: $1\n",
e.getTypeName(),
e.getMessage()));
return Status(e);
}
return Status::success();
}
const String& ClusterRemoveServer::getName() const {
return kName_;
}
const String& ClusterRemoveServer::getDescription() const {
return kDescription_;
}
void ClusterRemoveServer::printHelp(OutputStream* stdout_os) const {
stdout_os->write(StringUtil::format(
"\nevqlctl-$0 - $1\n\n", kName_, kDescription_));
stdout_os->write(
"Usage: evqlctl cluster-remove-server [OPTIONS]\n"
" --server_name The name of the server to remove.\n"
" --soft Enable the soft-leave operation.\n"
" --hard Enable the hard-leave operation.\n");
}
} // namespace cli
} // namespace eventql
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2016, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CC32xxEEPROMEmulation.cxx
* This file implements EEPROM emulation on the CC32xx SPI-flash filesystem.
*
* @author Balazs Racz
* @date 30 December 2016
*/
#include "freertos_drivers/ti/CC32xxEEPROMEmulation.hxx"
#include "freertos_drivers/ti/CC32xxHelper.hxx"
#include "fs.h"
const uint8_t CC32xxEEPROMEmulation::SECTOR_COUNT = 8;
extern "C" {
void eeprom_updated_notification();
}
CC32xxEEPROMEmulation::CC32xxEEPROMEmulation(
const char *name, size_t file_size_bytes)
: EEPROM(name, file_size_bytes)
{
data_ = (uint8_t *)malloc(file_size_bytes);
HASSERT(data_);
memset(data_, 0xff, file_size_bytes);
}
void CC32xxEEPROMEmulation::mount()
{
bool have_rot = false;
// First we need to find what was the last written segment.
for (unsigned sector = 0; sector < SECTOR_COUNT; ++sector)
{
int handle = open_file(sector, FS_MODE_OPEN_READ, true);
if (handle < 0)
{
continue;
}
unsigned b = 0xaa55aaaa;
SlCheckResult(sl_FsRead(handle, 0, (uint8_t *)&b, 4), 4);
sl_FsClose(handle, nullptr, nullptr, 0);
if (b >= fileVersion_)
{
readSector_ = sector;
have_rot = true;
}
}
if (have_rot)
{
int handle = open_file(readSector_, FS_MODE_OPEN_READ);
int ret = sl_FsRead(handle, 4, data_, file_size());
if (ret < 0)
{
SlCheckResult(ret);
}
}
}
CC32xxEEPROMEmulation::~CC32xxEEPROMEmulation()
{
flush();
free(data_);
}
void CC32xxEEPROMEmulation::flush_buffers()
{
if (!isDirty_)
return;
++fileVersion_;
++readSector_;
if (readSector_ >= SECTOR_COUNT)
readSector_ = 0;
int handle = open_file(readSector_, FS_MODE_OPEN_WRITE, true);
if (handle < 0)
{
handle =
open_file(readSector_, FS_MODE_OPEN_CREATE(file_size() + 4, 0));
}
SlCheckResult(sl_FsWrite(handle, 0, (uint8_t *)&fileVersion_, 4), 4);
SlCheckResult(sl_FsWrite(handle, 4, data_, file_size()), file_size());
SlCheckResult(sl_FsClose(handle, nullptr, nullptr, 0));
isDirty_ = 0;
}
int CC32xxEEPROMEmulation::open_file(
unsigned sector, uint32_t open_mode, bool ignore_error)
{
string filename(name);
filename.push_back('.');
filename.push_back('0' + sector);
int32_t handle = -1;
int ret = sl_FsOpen((uint8_t *)filename.c_str(), open_mode, NULL, &handle);
if (!ignore_error)
{
SlCheckResult(ret);
HASSERT(handle >= 0);
}
return handle;
}
void CC32xxEEPROMEmulation::write(
unsigned int index, const void *buf, size_t len)
{
// Boundary checks are performed by the EEPROM class.
if (isDirty_ || (memcmp(data_ + index, buf, len) != 0))
{
isDirty_ = 1;
memcpy(data_ + index, buf, len);
eeprom_updated_notification();
}
}
void CC32xxEEPROMEmulation::read(unsigned int index, void *buf, size_t len)
{
// Boundary checks are performed by the EEPROM class.
memcpy(buf, data_ + index, len);
}
<commit_msg>Fixes a silly bug in the CC32xx eeprom emulation.<commit_after>/** \copyright
* Copyright (c) 2016, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CC32xxEEPROMEmulation.cxx
* This file implements EEPROM emulation on the CC32xx SPI-flash filesystem.
*
* @author Balazs Racz
* @date 30 December 2016
*/
//#define LOGLEVEL VERBOSE
#include "utils/logging.h"
#include "freertos_drivers/ti/CC32xxEEPROMEmulation.hxx"
#include "freertos_drivers/ti/CC32xxHelper.hxx"
#include "fs.h"
const uint8_t CC32xxEEPROMEmulation::SECTOR_COUNT = 8;
extern "C" {
void eeprom_updated_notification();
}
CC32xxEEPROMEmulation::CC32xxEEPROMEmulation(
const char *name, size_t file_size_bytes)
: EEPROM(name, file_size_bytes)
{
data_ = (uint8_t *)malloc(file_size_bytes);
HASSERT(data_);
memset(data_, 0xff, file_size_bytes);
}
void CC32xxEEPROMEmulation::mount()
{
bool have_rot = false;
// First we need to find what was the last written segment.
for (unsigned sector = 0; sector < SECTOR_COUNT; ++sector)
{
int handle = open_file(sector, FS_MODE_OPEN_READ, true);
if (handle < 0)
{
LOG(VERBOSE, "EEPROM: sector %u: could not open.", sector);
continue;
}
unsigned b = 0xaa55aaaa;
SlCheckResult(sl_FsRead(handle, 0, (uint8_t *)&b, 4), 4);
sl_FsClose(handle, nullptr, nullptr, 0);
LOG(VERBOSE, "EEPROM: sector %u: version %u.", sector, b);
if (b >= fileVersion_)
{
readSector_ = sector;
fileVersion_ = b;
have_rot = true;
}
}
if (have_rot)
{
LOG(VERBOSE, "EEPROM: read sector %u:", readSector_);
int handle = open_file(readSector_, FS_MODE_OPEN_READ);
int ret = sl_FsRead(handle, 4, data_, file_size());
if (ret < 0)
{
SlCheckResult(ret);
}
} else {
LOG(VERBOSE, "EEPROM: no read sector");
}
}
CC32xxEEPROMEmulation::~CC32xxEEPROMEmulation()
{
flush();
free(data_);
}
void CC32xxEEPROMEmulation::flush_buffers()
{
if (!isDirty_)
return;
++fileVersion_;
++readSector_;
if (readSector_ >= SECTOR_COUNT)
readSector_ = 0;
LOG(VERBOSE, "EEPROM: write sector %u version %u", readSector_, fileVersion_);
int handle = open_file(readSector_, FS_MODE_OPEN_WRITE, true);
if (handle < 0)
{
handle =
open_file(readSector_, FS_MODE_OPEN_CREATE(file_size() + 4, 0));
}
SlCheckResult(sl_FsWrite(handle, 0, (uint8_t *)&fileVersion_, 4), 4);
SlCheckResult(sl_FsWrite(handle, 4, data_, file_size()), file_size());
SlCheckResult(sl_FsClose(handle, nullptr, nullptr, 0));
isDirty_ = 0;
}
int CC32xxEEPROMEmulation::open_file(
unsigned sector, uint32_t open_mode, bool ignore_error)
{
string filename(name);
filename.push_back('.');
filename.push_back('0' + sector);
int32_t handle = -1;
int ret = sl_FsOpen((uint8_t *)filename.c_str(), open_mode, NULL, &handle);
if (!ignore_error)
{
SlCheckResult(ret);
HASSERT(handle >= 0);
}
return handle;
}
void CC32xxEEPROMEmulation::write(
unsigned int index, const void *buf, size_t len)
{
// Boundary checks are performed by the EEPROM class.
if (memcmp(data_ + index, buf, len) == 0) {
return;
}
memcpy(data_ + index, buf, len);
isDirty_ = 1;
eeprom_updated_notification();
}
void CC32xxEEPROMEmulation::read(unsigned int index, void *buf, size_t len)
{
// Boundary checks are performed by the EEPROM class.
memcpy(buf, data_ + index, len);
}
<|endoftext|> |
<commit_before>#include "cuda/cudaTextureResource.h"
#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"
namespace idaten
{
void CudaLeyered2DTexture::init(
std::vector<const aten::vec4*>& p,
uint32_t width,
uint32_t height)
{
int layerNum = static_cast<int>(p.size());
int imgSize = width * height;
auto totalSize = imgSize * layerNum;
std::vector<aten::vec4> hostMem(totalSize);
for (int n = 0; n < layerNum; n++) {
for (int i = 0; i < imgSize; i++) {
hostMem[n * imgSize + i] = p[n][i];
}
}
auto bytes = imgSize * layerNum * sizeof(float4);
// allocate device memory for result.
float4* deviceMem = nullptr;
checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));
// allocate array and copy image data.
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();
checkCudaErrors(
cudaMalloc3DArray(
&m_array,
&channelDesc,
make_cudaExtent(width, height, layerNum),
cudaArrayLayered));
cudaMemcpy3DParms memcpyParams = { 0 };
memcpyParams.srcPos = make_cudaPos(0, 0, 0);
memcpyParams.dstPos = make_cudaPos(0, 0, 0);
memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
memcpyParams.dstArray = m_array;
memcpyParams.extent = make_cudaExtent(width, height, layerNum);
memcpyParams.kind = cudaMemcpyHostToDevice;
checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));
memset(&m_resDesc, 0, sizeof(m_resDesc));
m_resDesc.resType = cudaResourceTypeArray;
m_resDesc.res.array.array = m_array;
}
cudaTextureObject_t CudaLeyered2DTexture::bind()
{
if (m_tex == 0) {
// Make texture description:
cudaTextureDesc tex_desc = {};
tex_desc.readMode = cudaReadModeElementType;
tex_desc.filterMode = cudaFilterModePoint;
tex_desc.addressMode[0] = cudaAddressModeWrap;
tex_desc.addressMode[1] = cudaAddressModeWrap;
tex_desc.normalizedCoords = 0;
checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
}
return m_tex;
}
}<commit_msg>Fix wrong flag value<commit_after>#include "cuda/cudaTextureResource.h"
#include "cuda/cudadefs.h"
#include "cuda/helper_math.h"
#include "cuda/cudautil.h"
#include "cuda/cudamemory.h"
namespace idaten
{
void CudaLeyered2DTexture::init(
std::vector<const aten::vec4*>& p,
uint32_t width,
uint32_t height)
{
int layerNum = static_cast<int>(p.size());
int imgSize = width * height;
auto totalSize = imgSize * layerNum;
std::vector<aten::vec4> hostMem(totalSize);
for (int n = 0; n < layerNum; n++) {
for (int i = 0; i < imgSize; i++) {
hostMem[n * imgSize + i] = p[n][i];
}
}
auto bytes = imgSize * layerNum * sizeof(float4);
// allocate device memory for result.
float4* deviceMem = nullptr;
checkCudaErrors(cudaMalloc((void **)&deviceMem, bytes));
// allocate array and copy image data.
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float4>();
checkCudaErrors(
cudaMalloc3DArray(
&m_array,
&channelDesc,
make_cudaExtent(width, height, layerNum),
cudaArrayLayered));
cudaMemcpy3DParms memcpyParams = { 0 };
memcpyParams.srcPos = make_cudaPos(0, 0, 0);
memcpyParams.dstPos = make_cudaPos(0, 0, 0);
memcpyParams.srcPtr = make_cudaPitchedPtr(&hostMem[0], width * sizeof(float4), width, height);
memcpyParams.dstArray = m_array;
memcpyParams.extent = make_cudaExtent(width, height, layerNum);
memcpyParams.kind = cudaMemcpyHostToDevice;
checkCudaErrors(cudaMemcpy3DAsync(&memcpyParams));
memset(&m_resDesc, 0, sizeof(m_resDesc));
m_resDesc.resType = cudaResourceTypeArray;
m_resDesc.res.array.array = m_array;
}
cudaTextureObject_t CudaLeyered2DTexture::bind()
{
if (m_tex == 0) {
// Make texture description:
cudaTextureDesc tex_desc = {};
tex_desc.readMode = cudaReadModeElementType;
tex_desc.filterMode = cudaFilterModePoint;
tex_desc.addressMode[0] = cudaAddressModeWrap;
tex_desc.addressMode[1] = cudaAddressModeWrap;
tex_desc.normalizedCoords = true;
checkCudaErrors(cudaCreateTextureObject(&m_tex, &m_resDesc, &tex_desc, nullptr));
}
return m_tex;
}
}<|endoftext|> |
<commit_before>#include "../checkpoint/checkpoint.h"
#include "myrandom/myrand.h"
#include <algorithm> // for std::shuffle
#include <cstdint> // for std::int32_t
#include <iostream> // for std::cout
#include <random> // for std::mt19937
#include <utility> // for std::make_pair
#include <vector> // for std::vector
#include <boost/algorithm/cxx11/iota.hpp> // for boost::algorithm::iota
#include <boost/format.hpp> // for boost::format
#include <boost/range/algorithm.hpp> // for boost::find, boost::transform
#include <tbb/concurrent_vector.h> // for tbb::concurrent_vector
#include <tbb/parallel_for.h> // for tbb::parallel_for
namespace {
// ビンゴボードのマス数
static auto constexpr BOARDSIZE = 25U;
// モンテカルロシミュレーションの試行回数
static auto constexpr MCMAX = 1000000U;
// 行・列の総数
static auto constexpr ROWCOLUMNSIZE = 10U;
//! A typedef.
/*!
そのマスに書かれてある番号と、そのマスが当たったかどうかを示すフラグ
のstd::pair
*/
using mypair = std::pair<std::int32_t, bool>;
//! A typedef.
/*!
行・列が埋まるまでに要した回数と、その時点で埋まったマスのstd::pair
*/
using mypair2 = std::pair<std::int32_t, std::int32_t>;
//! A function.
/*!
ビンゴボードを生成する
\return ビンゴボードが格納された可変長配列
*/
auto makeBoard();
//! A function.
/*!
モンテカルロ・シミュレーションを行う
\return モンテカルロ法の結果が格納された二次元可変長配列
*/
std::vector< std::vector<mypair2> > montecarlo();
//! A function.
/*!
モンテカルロ・シミュレーションの実装
\return モンテカルロ法の結果が格納された可変長配列
*/
std::vector<mypair2> montecarloImpl();
//! A function.
/*!
モンテカルロ・シミュレーションをTBBで並列化して行う
\return モンテカルロ法の結果が格納された可変長配列
*/
tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB();
}
int main()
{
checkpoint::CheckPoint cp;
cp.checkpoint("処理開始", __LINE__);
// モンテカルロ・シミュレーションの結果を代入
auto const mcresult(montecarlo());
cp.checkpoint("並列化無効", __LINE__);
// TBBで並列化したモンテカルロ・シミュレーションの結果を代入
auto const mcresult2(montecarloTBB());
cp.checkpoint("並列化有効", __LINE__);
// モンテカルロ・シミュレーションの平均試行回数の結果を格納した可変長配列
std::vector<double> trialavg(ROWCOLUMNSIZE);
// モンテカルロ・シミュレーションのi回目の試行で、埋まっているマスの数を格納した可変長配列
std::vector<double> fillavg(ROWCOLUMNSIZE);
// 行・列の総数分繰り返す
for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
// 総和を0で初期化
auto trialsum = 0;
auto fillsum = 0;
// 試行回数分繰り返す
for (auto j = 0U; j < MCMAX; j++) {
// j回目の結果を加える
trialsum += mcresult[j][i].first;
fillsum += mcresult[j][i].second;
}
// 平均を算出してi行・列目のtrialavg、fillavgに代入
trialavg[i] = static_cast<double>(trialsum) / static_cast<double>(MCMAX);
fillavg[i] = static_cast<double>(fillsum) / static_cast<double>(MCMAX);
}
for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
auto const efficiency = trialavg[i] / static_cast<double>(i + 1);
std::cout
<< boost::format("%d個目に必要な平均試行回数:%.1f回, 効率 = %.1f(回/個), ")
% (i + 1) % trialavg[i] % efficiency
<< boost::format("埋まっているマスの平均個数:%.1f個\n")
% fillavg[i];
}
cp.checkpoint_print();
return 0;
}
namespace {
auto makeBoard()
{
// 仮のビンゴボードを生成
std::vector<std::int32_t> boardtmp(BOARDSIZE);
// 仮のビンゴボードに1~25の数字を代入
boost::algorithm::iota(boardtmp, 1);
// 仮のビンゴボードの数字をシャッフル
std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());
// ビンゴボードを生成
std::vector<mypair> board(BOARDSIZE);
// 仮のビンゴボードからビンゴボードを生成する
boost::transform(
boardtmp,
board.begin(),
[](auto n) { return std::make_pair(n, false); });
// ビンゴボードを返す
return board;
}
std::vector< std::vector<mypair2> > montecarlo()
{
// モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
std::vector< std::vector<mypair2> > mcresult;
// MCMAX個の容量を確保
mcresult.reserve(MCMAX);
// 試行回数分繰り返す
for (auto i = 0U; i < MCMAX; i++) {
// モンテカルロ・シミュレーションの結果を代入
mcresult.push_back(montecarloImpl());
}
// モンテカルロ・シミュレーションの結果を返す
return mcresult;
}
std::vector<mypair2> montecarloImpl()
{
// ビンゴボードを生成
auto board(makeBoard());
// 自作乱数クラスを初期化
myrandom::MyRand mr(1, BOARDSIZE);
// その行・列が既に埋まっているかどうかを格納する可変長配列
// ROWCOLUMNSIZE個の要素をfalseで初期化
std::vector<bool> rcfill(ROWCOLUMNSIZE, false);
// 行・列が埋まるまでに要した回数と、その時点で埋まったマスを格納した
// 可変長配列
std::vector< mypair2 > fillnum;
// ROWCOLUMNSIZE個の容量を確保
fillnum.reserve(ROWCOLUMNSIZE);
// その時点で埋まっているマスを計算するためのラムダ式
auto const sum = [](const std::vector< mypair > & vec)
{
auto cnt = 0;
for (auto & e : vec) {
if (e.second) {
cnt++;
}
}
return cnt;
};
// 無限ループ
for (auto i = 1; ; i++) {
// 乱数で得た数字で、かつまだ当たってないマスを検索
auto itr = boost::find(board, std::make_pair(mr.myrand(), false));
// そのようなマスがあった
if (itr != board.end()) {
// そのマスは当たったとし、フラグをtrueにする
itr->second = true;
}
// そのようなマスがなかった
else {
//ループ続行
continue;
}
// 各行・列が埋まったかどうかをチェック
for (auto j = 0; j < 5; j++) {
// 行をチェック
if (board[5 * j].second &&
board[5 * j + 1].second &&
board[5 * j + 2].second &&
board[5 * j + 3].second &&
board[5 * j + 4].second &&
// その行は既に埋まっているかどうか
!rcfill[j]) {
// その行は埋まったとして、フラグをtrueにする
rcfill[j] = true;
// 要した試行回数と、その時点で埋まったマスの数を格納
fillnum.push_back(std::make_pair(i, sum(board)));
}
// 列をチェック
if (board[j].second &&
board[j + 5].second &&
board[j + 10].second &&
board[j + 15].second &&
board[j + 20].second &&
// その列は既に埋まっているかどうか
!rcfill[j + 5]) {
// その列は埋まったとして、フラグをtrueにする
rcfill[j + 5] = true;
// 要した試行回数と、その時点で埋まったマスの数を格納
fillnum.push_back(std::make_pair(i, sum(board)));
}
}
// 全ての行・列が埋まったかどうか
if (fillnum.size() == ROWCOLUMNSIZE) {
// 埋まったのでループ脱出
break;
}
}
// 要した試行関数の可変長配列を返す
return fillnum;
}
tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB()
{
// モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
// 複数のスレッドが同時にアクセスする可能性があるためtbb::concurrent_vectorを使う
tbb::concurrent_vector< std::vector<mypair2> > mcresult;
// MCMAX個の容量を確保
mcresult.reserve(MCMAX);
// MCMAX回のループを並列化して実行
tbb::parallel_for(
std::uint32_t(0),
MCMAX,
std::uint32_t(1),
[&mcresult](auto) { mcresult.push_back(montecarloImpl()); });
// モンテカルロ・シミュレーションの結果を返す
return mcresult;
}
}
<commit_msg>C++14で書き直した<commit_after>#include "../checkpoint/checkpoint.h"
#include "myrandom/myrand.h"
#include <algorithm> // for std::shuffle
#include <cstdint> // for std::int32_t
#include <iostream> // for std::cout
#include <random> // for std::mt19937
#include <utility> // for std::make_pair
#include <vector> // for std::vector
#include <boost/algorithm/cxx11/iota.hpp> // for boost::algorithm::iota
#include <boost/format.hpp> // for boost::format
#include <boost/range/algorithm.hpp> // for boost::find, boost::transform
#include <tbb/concurrent_vector.h> // for tbb::concurrent_vector
#include <tbb/parallel_for.h> // for tbb::parallel_for
namespace {
// ビンゴボードのマス数
static auto constexpr BOARDSIZE = 25U;
// モンテカルロシミュレーションの試行回数
static auto constexpr MCMAX = 1000000U;
// 行・列の総数
static auto constexpr ROWCOLUMNSIZE = 10U;
//! A typedef.
/*!
そのマスに書かれてある番号と、そのマスが当たったかどうかを示すフラグ
のstd::pair
*/
using mypair = std::pair<std::int32_t, bool>;
//! A typedef.
/*!
行・列が埋まるまでに要した回数と、その時点で埋まったマスのstd::pair
*/
using mypair2 = std::pair<std::int32_t, std::int32_t>;
//! A function.
/*!
ビンゴボードを生成する
\return ビンゴボードが格納された可変長配列
*/
auto makeBoard();
//! A function.
/*!
モンテカルロ・シミュレーションを行う
\return モンテカルロ法の結果が格納された二次元可変長配列
*/
std::vector< std::vector<mypair2> > montecarlo();
//! A function.
/*!
モンテカルロ・シミュレーションの実装
\return モンテカルロ法の結果が格納された可変長配列
*/
std::vector<mypair2> montecarloImpl();
//! A function.
/*!
モンテカルロ・シミュレーションをTBBで並列化して行う
\return モンテカルロ法の結果が格納された可変長配列
*/
tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB();
}
int main()
{
checkpoint::CheckPoint cp;
cp.checkpoint("処理開始", __LINE__);
// モンテカルロ・シミュレーションの結果を代入
auto const mcresult(montecarlo());
cp.checkpoint("並列化無効", __LINE__);
// TBBで並列化したモンテカルロ・シミュレーションの結果を代入
auto const mcresult2(montecarloTBB());
cp.checkpoint("並列化有効", __LINE__);
// モンテカルロ・シミュレーションの平均試行回数の結果を格納した可変長配列
std::vector<double> trialavg(ROWCOLUMNSIZE);
// モンテカルロ・シミュレーションのi回目の試行で、埋まっているマスの数を格納した可変長配列
std::vector<double> fillavg(ROWCOLUMNSIZE);
// 行・列の総数分繰り返す
for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
// 総和を0で初期化
auto trialsum = 0;
auto fillsum = 0;
// 試行回数分繰り返す
for (auto j = 0U; j < MCMAX; j++) {
// j回目の結果を加える
trialsum += mcresult[j][i].first;
fillsum += mcresult[j][i].second;
}
// 平均を算出してi行・列目のtrialavg、fillavgに代入
trialavg[i] = static_cast<double>(trialsum) / static_cast<double>(MCMAX);
fillavg[i] = static_cast<double>(fillsum) / static_cast<double>(MCMAX);
}
for (auto i = 0U; i < ROWCOLUMNSIZE; i++) {
auto const efficiency = trialavg[i] / static_cast<double>(i + 1);
std::cout
<< boost::format("%d個目に必要な平均試行回数:%.1f回, 効率 = %.1f(回/個), ")
% (i + 1) % trialavg[i] % efficiency
<< boost::format("埋まっているマスの平均個数:%.1f個\n")
% fillavg[i];
}
cp.checkpoint_print();
return 0;
}
namespace {
auto makeBoard()
{
// 仮のビンゴボードを生成
std::vector<std::int32_t> boardtmp(BOARDSIZE);
// 仮のビンゴボードに1~25の数字を代入
boost::algorithm::iota(boardtmp, 1);
// 仮のビンゴボードの数字をシャッフル
std::shuffle(boardtmp.begin(), boardtmp.end(), std::mt19937());
// ビンゴボードを生成
std::vector<mypair> board(BOARDSIZE);
// 仮のビンゴボードからビンゴボードを生成する
boost::transform(
boardtmp,
board.begin(),
[](auto n) { return std::make_pair(n, false); });
// ビンゴボードを返す
return board;
}
std::vector< std::vector<mypair2> > montecarlo()
{
// モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
std::vector< std::vector<mypair2> > mcresult;
// MCMAX個の容量を確保
mcresult.reserve(MCMAX);
// 試行回数分繰り返す
for (auto i = 0U; i < MCMAX; i++) {
// モンテカルロ・シミュレーションの結果を代入
mcresult.push_back(montecarloImpl());
}
// モンテカルロ・シミュレーションの結果を返す
return mcresult;
}
std::vector<mypair2> montecarloImpl()
{
// ビンゴボードを生成
auto board(makeBoard());
// 自作乱数クラスを初期化
myrandom::MyRand mr(1, BOARDSIZE);
// その行・列が既に埋まっているかどうかを格納する可変長配列
// ROWCOLUMNSIZE個の要素をfalseで初期化
std::vector<bool> rcfill(ROWCOLUMNSIZE, false);
// 行・列が埋まるまでに要した回数と、その時点で埋まったマスを格納した
// 可変長配列
std::vector< mypair2 > fillnum;
// ROWCOLUMNSIZE個の容量を確保
fillnum.reserve(ROWCOLUMNSIZE);
// その時点で埋まっているマスを計算するためのラムダ式
auto const sum = [](auto const & vec)
{
auto cnt = 0;
for (auto & e : vec) {
if (e.second) {
cnt++;
}
}
return cnt;
};
// 無限ループ
for (auto i = 1; ; i++) {
// 乱数で得た数字で、かつまだ当たってないマスを検索
auto itr = boost::find(board, std::make_pair(mr.myrand(), false));
// そのようなマスがあった
if (itr != board.end()) {
// そのマスは当たったとし、フラグをtrueにする
itr->second = true;
}
// そのようなマスがなかった
else {
//ループ続行
continue;
}
// 各行・列が埋まったかどうかをチェック
for (auto j = 0; j < 5; j++) {
// 行をチェック
if (board[5 * j].second &&
board[5 * j + 1].second &&
board[5 * j + 2].second &&
board[5 * j + 3].second &&
board[5 * j + 4].second &&
// その行は既に埋まっているかどうか
!rcfill[j]) {
// その行は埋まったとして、フラグをtrueにする
rcfill[j] = true;
// 要した試行回数と、その時点で埋まったマスの数を格納
fillnum.push_back(std::make_pair(i, sum(board)));
}
// 列をチェック
if (board[j].second &&
board[j + 5].second &&
board[j + 10].second &&
board[j + 15].second &&
board[j + 20].second &&
// その列は既に埋まっているかどうか
!rcfill[j + 5]) {
// その列は埋まったとして、フラグをtrueにする
rcfill[j + 5] = true;
// 要した試行回数と、その時点で埋まったマスの数を格納
fillnum.push_back(std::make_pair(i, sum(board)));
}
}
// 全ての行・列が埋まったかどうか
if (fillnum.size() == ROWCOLUMNSIZE) {
// 埋まったのでループ脱出
break;
}
}
// 要した試行関数の可変長配列を返す
return fillnum;
}
tbb::concurrent_vector< std::vector<mypair2> > montecarloTBB()
{
// モンテカルロ・シミュレーションの結果を格納するための二次元可変長配列
// 複数のスレッドが同時にアクセスする可能性があるためtbb::concurrent_vectorを使う
tbb::concurrent_vector< std::vector<mypair2> > mcresult;
// MCMAX個の容量を確保
mcresult.reserve(MCMAX);
// MCMAX回のループを並列化して実行
tbb::parallel_for(
std::uint32_t(0),
MCMAX,
std::uint32_t(1),
[&mcresult](auto) { mcresult.push_back(montecarloImpl()); });
// モンテカルロ・シミュレーションの結果を返す
return mcresult;
}
}
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <[email protected]>
* http://www.berlin-consortium.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; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Desktop/WindowImpl.hh"
#include <Berlin/Vertex.hh>
#include <Prague/Sys/Tracer.hh>
using namespace Prague;
class Mover : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Vertex *delta;
if (any >>= delta)
{
Vertex p = handle->position();
handle->position(p + *delta);
}
else cerr << "Mover::execute : wrong message type !" << endl;
}
};
class Resizer : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Vertex *delta;
if (any >>= delta)
{
Vertex s = handle->size();
Graphic::Requisition r;
handle->child()->request(r);
if (r.x.defined)
{
if (delta->x > 0.) s.x = min(s.x + delta->x, r.x.maximum);
else s.x = max(s.x + delta->x, r.x.minimum);
}
else s.x += delta->x;
if (r.y.defined)
{
if (delta->y > 0.) s.y = min(s.y + delta->y, r.y.maximum);
else s.y = max(s.y + delta->y, r.y.minimum);
}
else s.y += delta->y;
handle->size(s);
}
else cerr << "Resizer::execute : wrong message type !" << endl;
}
};
class MoveResizer : public WindowImpl::Manipulator
{
public:
MoveResizer(Alignment x, Alignment y, CORBA::Short b) : xalign(x), yalign(y), border(b) {}
virtual void execute(const CORBA::Any &any)
{
Trace trace("MoveResizer::execute");
if (CORBA::is_nil(handle)) return;
Vertex *vertex;
if (any >>= vertex)
{
Graphic::Requisition r;
handle->child()->request(r);
Vertex pos = handle->position();
Vertex size = handle->size();
Vertex p = pos, s = size;
if (border & Window::left && xalign != 0.)
{
s.x = min(r.x.maximum, max(r.x.minimum, size.x - vertex->x/xalign));
p.x = pos.x - xalign * (s.x - size.x);
}
else if (border & Window::right && xalign != 1.)
{
s.x = min(r.x.maximum, max(r.x.minimum, size.x + vertex->x/(1.-xalign)));
p.x = pos.x - xalign * (s.x - size.x);
}
if (border & Window::top && yalign != 0.)
{
s.y = min(r.y.maximum, max(r.y.minimum, size.y - vertex->y/yalign));
p.y = pos.y - yalign * (s.y - size.y);
}
else if (border & Window::bottom && yalign != 1.)
{
s.y = min(r.y.maximum, max(r.y.minimum, size.y + vertex->y/(1.-yalign)));
p.y = pos.y - yalign * (s.y - size.y);
}
handle->parent()->begin();
handle->position(p);
handle->size(s);
handle->parent()->end();
}
else cerr << "MoveResizer::execute : wrong message type !" << endl;
}
private:
Alignment xalign, yalign;
CORBA::Short border;
};
class Relayerer : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Stage::Index i;
if (any >>= i)
{
handle->layer(i);
}
else cerr << "Relayerer::execute : wrong message type !" << endl;
}
};
void WindowImpl::Mapper::execute(const CORBA::Any &)
{
if (flag) window->map();
else window->unmap();
}
WindowImpl::WindowImpl()
: ControllerImpl(false), unmapped(0), manipulators(3), mapper(0)
{
manipulators[0] = new Mover;
manipulators[0]->_obj_is_ready(_boa());
manipulators[1] = new Resizer;
manipulators[1]->_obj_is_ready(_boa());
manipulators[2] = new Relayerer;
manipulators[2]->_obj_is_ready(_boa());
mapper = new Mapper(this, true);
mapper->_obj_is_ready(_boa());
unmapper = new Mapper(this, false);
unmapper->_obj_is_ready(_boa());
}
WindowImpl::~WindowImpl()
{
cout << "WindowImpl::~WindowImpl" << endl;
for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
(*i)->_dispose();
mapper->_dispose();
unmapper->_dispose();
}
// void WindowImpl::needResize()
// {
// }
/*
* cache the focus holding controllers so we can restore them when the window
* receives focus again...
*/
CORBA::Boolean WindowImpl::requestFocus(Controller_ptr c, Input::Device d)
{
if (unmapped) return false;
Controller_var parent = parentController();
if (CORBA::is_nil(parent)) return false;
if (parent->requestFocus(c, d))
{
if (focus.size() <= d) focus.resize(d + 1);
focus[d] = Controller::_duplicate(c);
return true;
}
else return false;
}
void WindowImpl::insert(Desktop_ptr desktop, bool mapped)
{
Trace trace("WindowImpl::insert");
Vertex position, size;
position.x = position.y = 1000., position.z = 0.;
Graphic::Requisition r;
request(r);
size.x = r.x.natural, size.y = r.y.natural, size.z = 0;
unmapped = new UnmappedStageHandle(desktop, Graphic_var(_this()), position, size, 0);
unmapped->_obj_is_ready(_boa());
handle = StageHandle_var(unmapped->_this());
if (mapped) map();
}
Command_ptr WindowImpl::move() { return manipulators[0]->_this();}
Command_ptr WindowImpl::resize() { return manipulators[1]->_this();}
Command_ptr WindowImpl::moveResize(Alignment x, Alignment y, CORBA::Short b)
{
manipulators.push_back(new MoveResizer(x, y, b));
manipulators.back()->_obj_is_ready(_boa());
return manipulators.back()->_this();
}
Command_ptr WindowImpl::relayer() { return manipulators[2]->_this();}
Command_ptr WindowImpl::map(CORBA::Boolean f)
{
return f ? mapper->_this() : unmapper->_this();
}
// void WindowImpl::pick(PickTraversal_ptr traversal)
// {
// SectionLog section("WindowImpl::pick");
// traversal->enterController(Controller_var(_this()));
// MonoGraphic::traverse(traversal);
// traversal->leaveController();
// }
void WindowImpl::map()
{
Trace trace("WindowImpl::map");
MutexGuard guard(mutex);
if (!unmapped) return;
Stage_var stage = handle->parent();
stage->begin();
StageHandle_var tmp = stage->insert(Graphic_var(_this()), handle->position(), handle->size(), handle->layer());
stage->end();
handle = tmp;
for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
(*i)->bind(handle);
unmapped->_dispose();
unmapped = 0;
}
void WindowImpl::unmap()
{
Trace trace("WindowImpl::unmap");
MutexGuard guard(mutex);
if (unmapped) return;
unmapped = new UnmappedStageHandle(handle);
unmapped->_obj_is_ready(_boa());
handle->remove();
// Stage_var stage = handle->parent();
// stage->begin();
// stage->remove(handle);
// stage->end();
}
<commit_msg>windows now resize upon request<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <[email protected]>
* http://www.berlin-consortium.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; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Desktop/WindowImpl.hh"
#include <Berlin/Vertex.hh>
#include <Prague/Sys/Tracer.hh>
#include <Warsaw/IO.hh>
using namespace Prague;
class Mover : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Vertex *delta;
if (any >>= delta)
{
Vertex p = handle->position();
handle->position(p + *delta);
}
else cerr << "Mover::execute : wrong message type !" << endl;
}
};
class Resizer : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Vertex *delta;
if (any >>= delta)
{
Vertex s = handle->size();
Graphic::Requisition r;
handle->child()->request(r);
if (r.x.defined)
{
if (delta->x > 0.) s.x = min(s.x + delta->x, r.x.maximum);
else s.x = max(s.x + delta->x, r.x.minimum);
}
else s.x += delta->x;
if (r.y.defined)
{
if (delta->y > 0.) s.y = min(s.y + delta->y, r.y.maximum);
else s.y = max(s.y + delta->y, r.y.minimum);
}
else s.y += delta->y;
handle->size(s);
}
else cerr << "Resizer::execute : wrong message type !" << endl;
}
};
class MoveResizer : public WindowImpl::Manipulator
{
public:
MoveResizer(Alignment x, Alignment y, CORBA::Short b) : xalign(x), yalign(y), border(b) {}
virtual void execute(const CORBA::Any &any)
{
Trace trace("MoveResizer::execute");
if (CORBA::is_nil(handle)) return;
Vertex *vertex;
if (any >>= vertex)
{
Graphic::Requisition r;
handle->child()->request(r);
Vertex pos = handle->position();
Vertex size = handle->size();
Vertex p = pos, s = size;
if (border & Window::left && xalign != 0.)
{
s.x = min(r.x.maximum, max(r.x.minimum, size.x - vertex->x/xalign));
p.x = pos.x - xalign * (s.x - size.x);
}
else if (border & Window::right && xalign != 1.)
{
s.x = min(r.x.maximum, max(r.x.minimum, size.x + vertex->x/(1.-xalign)));
p.x = pos.x - xalign * (s.x - size.x);
}
if (border & Window::top && yalign != 0.)
{
s.y = min(r.y.maximum, max(r.y.minimum, size.y - vertex->y/yalign));
p.y = pos.y - yalign * (s.y - size.y);
}
else if (border & Window::bottom && yalign != 1.)
{
s.y = min(r.y.maximum, max(r.y.minimum, size.y + vertex->y/(1.-yalign)));
p.y = pos.y - yalign * (s.y - size.y);
}
handle->parent()->begin();
handle->position(p);
handle->size(s);
handle->parent()->end();
}
else cerr << "MoveResizer::execute : wrong message type !" << endl;
}
private:
Alignment xalign, yalign;
CORBA::Short border;
};
class Relayerer : public WindowImpl::Manipulator
{
public:
virtual void execute(const CORBA::Any &any)
{
if (CORBA::is_nil(handle)) return;
Stage::Index i;
if (any >>= i)
{
handle->layer(i);
}
else cerr << "Relayerer::execute : wrong message type !" << endl;
}
};
void WindowImpl::Mapper::execute(const CORBA::Any &)
{
if (flag) window->map();
else window->unmap();
}
WindowImpl::WindowImpl()
: ControllerImpl(false), unmapped(0), manipulators(3), mapper(0)
{
manipulators[0] = new Mover;
manipulators[0]->_obj_is_ready(_boa());
manipulators[1] = new Resizer;
manipulators[1]->_obj_is_ready(_boa());
manipulators[2] = new Relayerer;
manipulators[2]->_obj_is_ready(_boa());
mapper = new Mapper(this, true);
mapper->_obj_is_ready(_boa());
unmapper = new Mapper(this, false);
unmapper->_obj_is_ready(_boa());
}
WindowImpl::~WindowImpl()
{
cout << "WindowImpl::~WindowImpl" << endl;
for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
(*i)->_dispose();
mapper->_dispose();
unmapper->_dispose();
}
void WindowImpl::needResize()
{
Trace trace("WindowImpl::needResize");
Vertex size = handle->size();
Graphic::Requisition r;
request(r);
if (r.x.minimum <= size.x && r.x.maximum >= size.x && r.y.minimum <= size.y && r.y.maximum >= size.y)
needRedraw();
else
{
size.x = min(r.x.maximum, max(r.x.minimum, size.x));
size.y = min(r.y.maximum, max(r.y.minimum, size.y));
handle->size(size);
}
}
/*
* cache the focus holding controllers so we can restore them when the window
* receives focus again...
*/
CORBA::Boolean WindowImpl::requestFocus(Controller_ptr c, Input::Device d)
{
if (unmapped) return false;
Controller_var parent = parentController();
if (CORBA::is_nil(parent)) return false;
if (parent->requestFocus(c, d))
{
if (focus.size() <= d) focus.resize(d + 1);
focus[d] = Controller::_duplicate(c);
return true;
}
else return false;
}
void WindowImpl::insert(Desktop_ptr desktop, bool mapped)
{
Trace trace("WindowImpl::insert");
Vertex position, size;
position.x = position.y = 1000., position.z = 0.;
Graphic::Requisition r;
request(r);
size.x = r.x.natural, size.y = r.y.natural, size.z = 0;
unmapped = new UnmappedStageHandle(desktop, Graphic_var(_this()), position, size, 0);
unmapped->_obj_is_ready(_boa());
handle = StageHandle_var(unmapped->_this());
if (mapped) map();
}
Command_ptr WindowImpl::move() { return manipulators[0]->_this();}
Command_ptr WindowImpl::resize() { return manipulators[1]->_this();}
Command_ptr WindowImpl::moveResize(Alignment x, Alignment y, CORBA::Short b)
{
manipulators.push_back(new MoveResizer(x, y, b));
manipulators.back()->_obj_is_ready(_boa());
return manipulators.back()->_this();
}
Command_ptr WindowImpl::relayer() { return manipulators[2]->_this();}
Command_ptr WindowImpl::map(CORBA::Boolean f)
{
return f ? mapper->_this() : unmapper->_this();
}
// void WindowImpl::pick(PickTraversal_ptr traversal)
// {
// SectionLog section("WindowImpl::pick");
// traversal->enterController(Controller_var(_this()));
// MonoGraphic::traverse(traversal);
// traversal->leaveController();
// }
void WindowImpl::map()
{
Trace trace("WindowImpl::map");
MutexGuard guard(mutex);
if (!unmapped) return;
Stage_var stage = handle->parent();
stage->begin();
StageHandle_var tmp = stage->insert(Graphic_var(_this()), handle->position(), handle->size(), handle->layer());
stage->end();
handle = tmp;
for (mtable_t::iterator i = manipulators.begin(); i != manipulators.end(); i++)
(*i)->bind(handle);
unmapped->_dispose();
unmapped = 0;
}
void WindowImpl::unmap()
{
Trace trace("WindowImpl::unmap");
MutexGuard guard(mutex);
if (unmapped) return;
unmapped = new UnmappedStageHandle(handle);
unmapped->_obj_is_ready(_boa());
handle->remove();
// Stage_var stage = handle->parent();
// stage->begin();
// stage->remove(handle);
// stage->end();
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
int T;
int main(){
int i, j;
return 0;
}
<commit_msg>Delete CJ2015-QUALITIFICATION-B.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright 2013 Tanel Lebedev
#include "./main.h"
#include <sstream>
#include "Poco/Message.h"
#include "Poco/Util/Application.h"
#define ERRLEN 1024
namespace command_line_client {
void Main::usage() {
std::cout << "Recognized commands are: "
"sync, start, stop, status, pushable, list, continue, listen"
<< std::endl;
}
void Main::defineOptions(Poco::Util::OptionSet& options) {
Poco::Util::Application::defineOptions(options);
options.addOption(Poco::Util::Option(
"verbose", "v", "verbose logging, to the console"));
}
std::string KopsikModelChangeToString(
KopsikModelChange &change) {
std::stringstream ss;
ss << "model_type=" << change.ModelType
<< ", change_type=" << change.ChangeType
<< ", model_id=" << change.ModelID
<< ", GUID=" << change.GUID;
return ss.str();
}
std::string KopsikTimeEntryViewItemToString(
KopsikTimeEntryViewItem *item) {
std::stringstream ss;
ss << "description: " << item->Description;
if (item->Project) {
ss << " project: " << item->Project;
}
if (item->Duration) {
ss << " duration: " << item->Duration;
}
return ss.str();
}
void on_view_item_change(kopsik_api_result result,
char *err_string,
int unsigned err_len,
KopsikModelChange *change) {
if (KOPSIK_API_SUCCESS != result) {
std::string err("");
err.append(err_string, err_len);
std::cerr << "on_view_item_change error! "
<< err << std::endl;
free(err_string);
return;
}
std::cout << "on_view_item_change "
<< KopsikModelChangeToString(*change)
<< std::endl;
}
int Main::main(const std::vector<std::string>& args) {
if (args.empty()) {
usage();
return Poco::Util::Application::EXIT_USAGE;
}
char* apiToken = getenv("TOGGL_API_TOKEN");
if (!apiToken) {
std::cerr << "Please set TOGGL_API_TOKEN in environment" <<
std::endl;
return Poco::Util::Application::EXIT_USAGE;
}
kopsik_set_db_path(ctx, "kopsik.db");
kopsik_set_log_path(ctx, "kopsik.log");
Poco::ErrorHandler::set(this);
// Start session in lib
char err[ERRLEN];
std::fill(err, err + ERRLEN, 0);
if (KOPSIK_API_SUCCESS != kopsik_set_api_token(
ctx, err, ERRLEN, apiToken)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
// Load user that is referenced by the session
KopsikUser *user = kopsik_user_init();
if (KOPSIK_API_SUCCESS != kopsik_current_user(
ctx, err, ERRLEN, user)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
kopsik_user_clear(user);
if ("sync" == args[0]) {
if (KOPSIK_API_SUCCESS != kopsik_sync(ctx, err, ERRLEN, 1)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
std::cout << "Synced." << std::endl;
return Poco::Util::Application::EXIT_OK;
}
if ("status" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
int found(0);
if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(
ctx, err, ERRLEN, te, &found)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (found) {
std::cout << "Tracking: " << te->Description << std::endl;
} else {
std::cout << "Not tracking." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("pushable" == args[0]) {
KopsikPushableModelStats stats;
if (KOPSIK_API_SUCCESS != kopsik_pushable_models(
ctx, err, ERRLEN, &stats)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
std::cout << stats.TimeEntries << " pushable time entries." << std::endl;
return Poco::Util::Application::EXIT_OK;
}
if ("start" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_start(
ctx, err, ERRLEN, "New time entry", te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Started: " << te->Description << std::endl;
} else {
std::cout << "Started." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("stop" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_stop(
ctx, err, ERRLEN, te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Stopped: " << te->Description << std::endl;
} else {
std::cout << "Stopped." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("list" == args[0]) {
KopsikTimeEntryViewItemList *list =
kopsik_time_entry_view_item_list_init();
if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
ctx, err, ERRLEN, list)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_SOFTWARE;
}
for (unsigned int i = 0; i < list->Length; i++) {
KopsikTimeEntryViewItem *item = list->ViewItems[i];
std::cout << KopsikTimeEntryViewItemToString(item) << std::endl;
}
std::cout << "Got " << list->Length << " time entry view items."
<< std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_OK;
}
if ("listen" == args[0]) {
std::cout << "Listening to websocket.. " << std::endl;
kopsik_set_change_callback(ctx, on_view_item_change);
if (KOPSIK_API_SUCCESS != kopsik_websocket_start(ctx, err, ERRLEN)) {
std::cerr << "Error starting websocket: "
<< err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
while (true) {
Poco::Thread::sleep(1000);
}
if (KOPSIK_API_SUCCESS != kopsik_websocket_stop(ctx, err, ERRLEN)) {
std::cerr << "Error stopping websocket: "
<< err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
return Poco::Util::Application::EXIT_OK;
}
if ("continue" == args[0]) {
KopsikTimeEntryViewItemList *list =
kopsik_time_entry_view_item_list_init();
if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
ctx, err, ERRLEN, list)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (!list->Length) {
std::cout << "No time entry found to continue." << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_OK;
}
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_continue(
ctx, err, ERRLEN, list->ViewItems[0]->GUID, te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Started: " << te->Description << std::endl;
} else {
std::cout << "Started." << std::endl;
}
kopsik_time_entry_view_item_list_clear(list);
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
usage();
return Poco::Util::Application::EXIT_USAGE;
}
} // namespace command_line_client
<commit_msg>rename model change event in cmd line app<commit_after>// Copyright 2013 Tanel Lebedev
#include "./main.h"
#include <sstream>
#include "Poco/Message.h"
#include "Poco/Util/Application.h"
#define ERRLEN 1024
namespace command_line_client {
void Main::usage() {
std::cout << "Recognized commands are: "
"sync, start, stop, status, pushable, list, continue, listen"
<< std::endl;
}
void Main::defineOptions(Poco::Util::OptionSet& options) {
Poco::Util::Application::defineOptions(options);
options.addOption(Poco::Util::Option(
"verbose", "v", "verbose logging, to the console"));
}
std::string KopsikModelChangeToString(
KopsikModelChange &change) {
std::stringstream ss;
ss << "model_type=" << change.ModelType
<< ", change_type=" << change.ChangeType
<< ", model_id=" << change.ModelID
<< ", GUID=" << change.GUID;
return ss.str();
}
std::string KopsikTimeEntryViewItemToString(
KopsikTimeEntryViewItem *item) {
std::stringstream ss;
ss << "description: " << item->Description;
if (item->Project) {
ss << " project: " << item->Project;
}
if (item->Duration) {
ss << " duration: " << item->Duration;
}
return ss.str();
}
void on_model_change(kopsik_api_result result,
char *err_string,
int unsigned err_len,
KopsikModelChange *change) {
if (KOPSIK_API_SUCCESS != result) {
std::string err("");
err.append(err_string, err_len);
std::cerr << "on_model_change error! "
<< err << std::endl;
free(err_string);
return;
}
std::cout << "on_view_item_change "
<< KopsikModelChangeToString(*change)
<< std::endl;
}
int Main::main(const std::vector<std::string>& args) {
if (args.empty()) {
usage();
return Poco::Util::Application::EXIT_USAGE;
}
char* apiToken = getenv("TOGGL_API_TOKEN");
if (!apiToken) {
std::cerr << "Please set TOGGL_API_TOKEN in environment" <<
std::endl;
return Poco::Util::Application::EXIT_USAGE;
}
kopsik_set_db_path(ctx, "kopsik.db");
kopsik_set_log_path(ctx, "kopsik.log");
Poco::ErrorHandler::set(this);
// Start session in lib
char err[ERRLEN];
std::fill(err, err + ERRLEN, 0);
if (KOPSIK_API_SUCCESS != kopsik_set_api_token(
ctx, err, ERRLEN, apiToken)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
// Load user that is referenced by the session
KopsikUser *user = kopsik_user_init();
if (KOPSIK_API_SUCCESS != kopsik_current_user(
ctx, err, ERRLEN, user)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
kopsik_user_clear(user);
if ("sync" == args[0]) {
if (KOPSIK_API_SUCCESS != kopsik_sync(ctx, err, ERRLEN, 1)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
std::cout << "Synced." << std::endl;
return Poco::Util::Application::EXIT_OK;
}
if ("status" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
int found(0);
if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(
ctx, err, ERRLEN, te, &found)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (found) {
std::cout << "Tracking: " << te->Description << std::endl;
} else {
std::cout << "Not tracking." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("pushable" == args[0]) {
KopsikPushableModelStats stats;
if (KOPSIK_API_SUCCESS != kopsik_pushable_models(
ctx, err, ERRLEN, &stats)) {
std::cerr << err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
std::cout << stats.TimeEntries << " pushable time entries." << std::endl;
return Poco::Util::Application::EXIT_OK;
}
if ("start" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_start(
ctx, err, ERRLEN, "New time entry", te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Started: " << te->Description << std::endl;
} else {
std::cout << "Started." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("stop" == args[0]) {
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_stop(
ctx, err, ERRLEN, te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Stopped: " << te->Description << std::endl;
} else {
std::cout << "Stopped." << std::endl;
}
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
if ("list" == args[0]) {
KopsikTimeEntryViewItemList *list =
kopsik_time_entry_view_item_list_init();
if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
ctx, err, ERRLEN, list)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_SOFTWARE;
}
for (unsigned int i = 0; i < list->Length; i++) {
KopsikTimeEntryViewItem *item = list->ViewItems[i];
std::cout << KopsikTimeEntryViewItemToString(item) << std::endl;
}
std::cout << "Got " << list->Length << " time entry view items."
<< std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_OK;
}
if ("listen" == args[0]) {
std::cout << "Listening to websocket.. " << std::endl;
kopsik_set_change_callback(ctx, on_model_change);
if (KOPSIK_API_SUCCESS != kopsik_websocket_start(ctx, err, ERRLEN)) {
std::cerr << "Error starting websocket: "
<< err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
while (true) {
Poco::Thread::sleep(1000);
}
if (KOPSIK_API_SUCCESS != kopsik_websocket_stop(ctx, err, ERRLEN)) {
std::cerr << "Error stopping websocket: "
<< err << std::endl;
return Poco::Util::Application::EXIT_SOFTWARE;
}
return Poco::Util::Application::EXIT_OK;
}
if ("continue" == args[0]) {
KopsikTimeEntryViewItemList *list =
kopsik_time_entry_view_item_list_init();
if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(
ctx, err, ERRLEN, list)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (!list->Length) {
std::cout << "No time entry found to continue." << std::endl;
kopsik_time_entry_view_item_list_clear(list);
return Poco::Util::Application::EXIT_OK;
}
KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();
if (KOPSIK_API_SUCCESS != kopsik_continue(
ctx, err, ERRLEN, list->ViewItems[0]->GUID, te)) {
std::cerr << err << std::endl;
kopsik_time_entry_view_item_list_clear(list);
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_SOFTWARE;
}
if (KOPSIK_API_SUCCESS != kopsik_push(ctx, err, ERRLEN)) {
std::cerr << err << std::endl;
}
if (te->Description) {
std::cout << "Started: " << te->Description << std::endl;
} else {
std::cout << "Started." << std::endl;
}
kopsik_time_entry_view_item_list_clear(list);
kopsik_time_entry_view_item_clear(te);
return Poco::Util::Application::EXIT_OK;
}
usage();
return Poco::Util::Application::EXIT_USAGE;
}
} // namespace command_line_client
<|endoftext|> |
<commit_before>
#include <iostream>
#include <glow/Buffer.h>
#include <glow/Error.h>
namespace glow
{
Buffer::Buffer()
: Object(genBuffer())
, _target(0)
{
}
Buffer::Buffer(GLenum target)
: Object(genBuffer())
, _target(target)
{
}
Buffer::Buffer(GLuint id, GLenum target, bool ownsGLObject)
: Object(id, ownsGLObject)
, _target(target)
{
}
GLuint Buffer::genBuffer()
{
GLuint id = 0;
glGenBuffers(1, &id);
CheckGLError();
return id;
}
Buffer::~Buffer()
{
if (m_id)
{
glDeleteBuffers(1, &m_id);
CheckGLError();
}
}
void Buffer::bind()
{
glBindBuffer(_target, m_id);
CheckGLError();
}
void Buffer::bind(GLenum target)
{
_target = target;
bind();
}
void Buffer::unbind()
{
glBindBuffer(_target, 0);
CheckGLError();
}
void* Buffer::map(GLenum access)
{
bind();
void* result = glMapBuffer(_target, access);
CheckGLError();
return result;
}
void* Buffer::map(GLenum target, GLenum access)
{
bind(target);
void* result = glMapBuffer(target, access);
CheckGLError();
return result;
}
void Buffer::unmap()
{
glUnmapBuffer(_target);
CheckGLError();
}
void Buffer::setData(const AbstractArray& data, GLenum usage)
{
setData(data.rawSize(), data.rawData(), usage);
}
void Buffer::setData(GLsizei size, const GLvoid* data, GLenum usage)
{
bind();
glBufferData(_target, size, data, usage);
CheckGLError();
}
void Buffer::drawArrays(GLenum mode, GLint first, GLsizei count)
{
bind();
glDrawArrays(mode, first, count);
CheckGLError();
}
void Buffer::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
bind();
glDrawElements(mode, count, type, indices);
CheckGLError();
}
void Buffer::bindBase(GLenum target, GLuint index)
{
glBindBufferBase(target, index, m_id);
CheckGLError();
}
void Buffer::bindRange(GLenum target, GLuint index, GLintptr offset, GLsizeiptr size)
{
glBindBufferRange(target, index, m_id, offset, size);
CheckGLError();
}
} // namespace glow
<commit_msg>ref #15 beautification<commit_after>
#include <iostream>
#include <glow/Buffer.h>
#include <glow/Error.h>
namespace glow
{
Buffer::Buffer()
: Object(genBuffer())
, _target(0)
{
}
Buffer::Buffer(GLenum target)
: Object(genBuffer())
, _target(target)
{
}
Buffer::Buffer(GLuint id, GLenum target, bool ownsGLObject)
: Object(id, ownsGLObject)
, _target(target)
{
}
GLuint Buffer::genBuffer()
{
GLuint id = 0;
glGenBuffers(1, &id);
CheckGLError();
return id;
}
Buffer::~Buffer()
{
if (m_id)
{
glDeleteBuffers(1, &m_id);
CheckGLError();
}
}
void Buffer::bind()
{
glBindBuffer(_target, m_id);
CheckGLError();
}
void Buffer::bind(GLenum target)
{
_target = target;
bind();
}
void Buffer::unbind()
{
glBindBuffer(_target, 0);
CheckGLError();
}
void* Buffer::map(GLenum access)
{
bind();
void* result = glMapBuffer(_target, access);
CheckGLError();
return result;
}
void* Buffer::map(GLenum target, GLenum access)
{
bind(target);
void* result = glMapBuffer(target, access);
CheckGLError();
return result;
}
void Buffer::unmap()
{
glUnmapBuffer(_target);
CheckGLError();
}
void Buffer::setData(const AbstractArray& data, GLenum usage)
{
setData(data.rawSize(), data.rawData(), usage);
}
void Buffer::setData(GLsizei size, const GLvoid* data, GLenum usage)
{
bind();
glBufferData(_target, size, data, usage);
CheckGLError();
}
void Buffer::drawArrays(GLenum mode, GLint first, GLsizei count)
{
bind();
glDrawArrays(mode, first, count);
CheckGLError();
}
void Buffer::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
bind();
glDrawElements(mode, count, type, indices);
CheckGLError();
}
void Buffer::bindBase(GLenum target, GLuint index)
{
glBindBufferBase(target, index, m_id);
CheckGLError();
}
void Buffer::bindRange(GLenum target, GLuint index, GLintptr offset, GLsizeiptr size)
{
glBindBufferRange(target, index, m_id, offset, size);
CheckGLError();
}
} // namespace glow
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Kamil Michalak <[email protected]>
*
* 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 <unistd.h>
#include <stdio.h>
#include <gtest/gtest.h>
#include "configtest.hpp"
#include "../inc/config.hpp"
void ConfigTest::SetUp()
{
config_file = "test.conf";
config_path = "./";
}
void ConfigTest::TearDown()
{
// delete file if it exists
std::string file = config_path + config_file;
if (access(file.c_str(), 0) == F_OK) {
int status = remove(file.c_str());
if (status != 0) {
FAIL() << "Cannot delete test configuration file";
}
}
}
TEST_F(ConfigTest, ConstructorCreatesValidConfigurationObject)
{
// when
jippi::Config *conf = new jippi::Config(config_file, config_path);
// then
EXPECT_EQ(config_path + config_file, conf->get_file());
// cleanup
delete conf;
}
TEST_F(ConfigTest, StorePropertySavesValue)
{
// given
const std::string value = "test_value";
const std::string group = "test_group";
const std::string key = "test_property";
// when
jippi::Config *conf = new jippi::Config(config_file, config_path);
conf->store_property(group, key, value);
conf->writeConfiguration();
conf->readConfiguration();
std::string config_value = conf->get_property(group, key);
// then
EXPECT_EQ(value, config_value);
// cleanup
delete conf;
}<commit_msg>Rename configtest.h and move it to the 'inc' directory<commit_after>/*
* Copyright 2014 Kamil Michalak <[email protected]>
*
* 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 <unistd.h>
#include <stdio.h>
#include <gtest/gtest.h>
#include "inc/configtest.hpp"
#include "../inc/config.hpp"
void ConfigTest::SetUp()
{
config_file = "test.conf";
config_path = "./";
}
void ConfigTest::TearDown()
{
// delete file if it exists
std::string file = config_path + config_file;
if (access(file.c_str(), 0) == F_OK) {
int status = remove(file.c_str());
if (status != 0) {
FAIL() << "Cannot delete test configuration file";
}
}
}
TEST_F(ConfigTest, ConstructorCreatesValidConfigurationObject)
{
// when
jippi::Config *conf = new jippi::Config(config_file, config_path);
// then
EXPECT_EQ(config_path + config_file, conf->get_file());
// cleanup
delete conf;
}
TEST_F(ConfigTest, StorePropertySavesValue)
{
// given
const std::string value = "test_value";
const std::string group = "test_group";
const std::string key = "test_property";
// when
jippi::Config *conf = new jippi::Config(config_file, config_path);
conf->store_property(group, key, value);
conf->writeConfiguration();
conf->readConfiguration();
std::string config_value = conf->get_property(group, key);
// then
EXPECT_EQ(value, config_value);
// cleanup
delete conf;
}<|endoftext|> |
<commit_before>
#include <cassert>
#include <QDebug>
#include <QApplication>
#include <QBasicTimer>
#include <QResizeEvent>
#include "AbstractPainter.h"
#include "AdaptiveGrid.h"
#include "FileAssociatedShader.h"
#include "Camera.h"
#include "Navigation.h"
#include "NavigationMath.h"
#include "Timer.h"
#include "CyclicTime.h"
#include "Canvas.h"
Canvas::Canvas(
const QSurfaceFormat & format
, QScreen * screen)
: QWindow(screen)
, m_context(new QOpenGLContext)
, m_painter(nullptr)
, m_camera(new Camera())
, m_navigation(new Navigation(*m_camera))
, m_swapInterval(VerticalSyncronization)
, m_repaintTimer(new QBasicTimer())
, m_continuousRepaint(false)
, m_fpsTimer(nullptr)
, m_time(new CyclicTime(0.0L, 60.0)) // this is one day in 60 seconds (1d/1h)
, m_swapts(0.0)
, m_swaps(0)
, m_update(false)
{
setSurfaceType(OpenGLSurface);
create();
m_camera->setFovy(40.0);
m_navigation->reset();
initializeGL(format);
}
Canvas::~Canvas()
{
}
QSurfaceFormat Canvas::format() const
{
if (!m_context)
return QSurfaceFormat();
return m_context->format();
}
void Canvas::setContinuousRepaint(
bool enable
, int msec)
{
if (m_continuousRepaint)
m_repaintTimer->stop();
m_continuousRepaint = enable;
if (m_continuousRepaint)
m_repaintTimer->start(msec, this);
}
bool Canvas::continuousRepaint() const
{
return m_continuousRepaint;
}
const QString Canvas::querys(const GLenum penum)
{
const QString result = reinterpret_cast<const char*>(glGetString(penum));
//glError();
return result;
}
const GLint Canvas::queryi(const GLenum penum)
{
GLint result;
glGetIntegerv(penum, &result);
return result;
}
void Canvas::initializeGL(const QSurfaceFormat & format)
{
m_context->setFormat(format);
m_context->create();
m_context->makeCurrent(this);
if (!initializeOpenGLFunctions())
{
qCritical() << "Initializing OpenGL failed.";
return;
}
// print some hardware information
qDebug();
qDebug().nospace() << "GPU: "
<< qPrintable(querys(GL_RENDERER)) << " ("
<< qPrintable(querys(GL_VENDOR)) << ", "
<< qPrintable(querys(GL_VERSION)) << ")";
qDebug().nospace() << "GL Version: "
<< qPrintable(QString::number(queryi(GL_MAJOR_VERSION))) << "."
<< qPrintable(QString::number(queryi(GL_MINOR_VERSION))) << " "
<< (queryi(GL_CONTEXT_CORE_PROFILE_BIT) ? "Core" : "Compatibility");
qDebug();
verifyExtensions(); // false if no painter ...
m_grid.reset(new AdaptiveGrid(*this));
m_grid->setNearFar(m_camera->zNear(), m_camera->zFar());
connect(m_camera.data(), &Camera::changed, this, &Canvas::cameraChanged);
m_context->doneCurrent();
m_time->setf(0.0);
m_time->start();
}
void Canvas::resizeEvent(QResizeEvent * event)
{
if (!m_painter)
return;
m_camera->setViewport(event->size());
m_context->makeCurrent(this);
m_painter->resize(event->size().width(), event->size().height());
m_grid->update(m_camera->eye(), m_camera->viewProjection());
m_context->doneCurrent();
if (isExposed() && Hidden != visibility())
paintGL();
}
void Canvas::paintGL()
{
if (!m_painter || !isExposed() || Hidden == visibility())
return;
m_context->makeCurrent(this);
auto programsWithInvalidatedUniforms(FileAssociatedShader::process()); // recompile file associated shaders if required
if (m_update)
{
m_painter->update();
m_grid->update(m_camera->eye(), m_camera->viewProjection());
m_update = false;
}
else
m_painter->update(programsWithInvalidatedUniforms);
m_painter->paint(m_time->getf(true));
m_grid->draw(*this);
m_context->swapBuffers(this);
m_context->doneCurrent();
emit timeUpdate(m_time->getf());
if (!m_fpsTimer)
{
m_fpsTimer.reset(new Timer(true, false));
m_swapts = 0.0;
}
else
m_fpsTimer->update();
++m_swaps;
if (m_fpsTimer->elapsed() - m_swapts >= 1e+9)
{
const float fps = 1e+9f * static_cast<float>(static_cast<long double>
(m_swaps) / (m_fpsTimer->elapsed() - m_swapts));
emit fpsUpdate(fps);
m_swapts = m_fpsTimer->elapsed();
m_swaps = 0;
}
}
void Canvas::cameraChanged()
{
m_update = true;
}
void Canvas::timerEvent(QTimerEvent * event)
{
assert(m_repaintTimer);
if(event->timerId() != m_repaintTimer->timerId())
return;
paintGL();
}
void Canvas::assignPainter(AbstractPainter * painter)
{
if (m_painter == painter)
return;
m_painter = painter;
if (!m_painter)
return;
m_context->makeCurrent(this);
m_painter->initialize();
m_painter->setCamera(m_camera.data());
verifyExtensions();
m_context->doneCurrent();
m_navigation->setCoordinateProvider(m_painter);
}
bool Canvas::verifyExtensions() const
{
if (!m_painter)
return false;
if (!m_context->isValid())
{
qWarning("Extensions cannot be verified due to invalid context.");
return false;
}
QStringList unsupported;
const QStringList & extensions(m_painter->extensions());
foreach(const QString & extension, extensions)
if (!m_context->hasExtension(qPrintable(extension)))
unsupported << extension;
if (unsupported.isEmpty())
return true;
if (unsupported.size() > 1)
qWarning("The following mandatory OpenGL extensions are not supported:");
else
qWarning("The following mandatory OpenGL extension is not supported:");
foreach(const QString & extension, unsupported)
qWarning() << extension;
qWarning("");
return false;
}
void Canvas::setSwapInterval(SwapInterval swapInterval)
{
m_context->makeCurrent(this);
bool result(false);
m_swapInterval = swapInterval;
#ifdef WIN32
// ToDo: C++11 - type aliases
typedef bool(WINAPI * SWAPINTERVALEXTPROC) (int);
static SWAPINTERVALEXTPROC wglSwapIntervalEXT = nullptr;
if (!wglSwapIntervalEXT)
wglSwapIntervalEXT = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("wglSwapIntervalEXT"));
if (wglSwapIntervalEXT)
result = wglSwapIntervalEXT(swapInterval);
#elif __APPLE__
qWarning("ToDo: Setting swap interval is currently not implemented for __APPLE__");
#else
// ToDo: C++11 - type aliases
typedef int(APIENTRY * SWAPINTERVALEXTPROC) (int);
static SWAPINTERVALEXTPROC glXSwapIntervalSGI = nullptr;
if (!glXSwapIntervalSGI)
glXSwapIntervalSGI = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("glXSwapIntervalSGI"));
if (glXSwapIntervalSGI)
result = glXSwapIntervalSGI(swapInterval);
#endif
if (!result)
qWarning("Setting swap interval to %s failed."
, qPrintable(swapIntervalToString(swapInterval)));
else
qDebug("Setting swap interval to %s."
, qPrintable(swapIntervalToString(swapInterval)));
m_context->doneCurrent();
}
void Canvas::toggleSwapInterval()
{
switch (m_swapInterval)
{
case NoVerticalSyncronization:
setSwapInterval(VerticalSyncronization);
break;
case VerticalSyncronization:
setSwapInterval(AdaptiveVerticalSyncronization);
break;
case AdaptiveVerticalSyncronization:
setSwapInterval(NoVerticalSyncronization);
break;
}
}
const QString Canvas::swapIntervalToString(SwapInterval swapInterval)
{
switch (swapInterval)
{
case NoVerticalSyncronization:
return QString("NoVerticalSyncronization");
case VerticalSyncronization:
return QString("VerticalSyncronization");
case AdaptiveVerticalSyncronization:
return QString("AdaptiveVerticalSyncronization");
default:
return QString();
}
}
void Canvas::keyPressEvent(QKeyEvent * event)
{
if (!m_navigation)
return;
m_navigation->keyPressEvent(event);
// forward event to painter for exercise mode switching
m_painter->keyPressEvent(event);
}
void Canvas::keyReleaseEvent(QKeyEvent * event)
{
if (!m_navigation)
return;
m_navigation->keyReleaseEvent(event);
}
void Canvas::mouseMoveEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseMoveEvent(event);
emit mouseUpdate(event->pos());
if (m_painter)
{
if (NavigationMath::validDepth(m_painter->depthAt(event->pos())))
emit objUpdate(m_painter->objAt(event->pos()));
else
emit objUpdate(QVector3D());
}
m_context->doneCurrent();
}
void Canvas::mousePressEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mousePressEvent(event);
m_context->doneCurrent();
}
void Canvas::mouseReleaseEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseReleaseEvent(event);
m_context->doneCurrent();
}
void Canvas::mouseDoubleClickEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseDoubleClickEvent(event);
m_context->doneCurrent();
}
void Canvas::wheelEvent(QWheelEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->wheelEvent(event);
m_context->doneCurrent();
}
<commit_msg>additional error message<commit_after>
#include <cassert>
#include <QDebug>
#include <QApplication>
#include <QBasicTimer>
#include <QResizeEvent>
#include "AbstractPainter.h"
#include "AdaptiveGrid.h"
#include "FileAssociatedShader.h"
#include "Camera.h"
#include "Navigation.h"
#include "NavigationMath.h"
#include "Timer.h"
#include "CyclicTime.h"
#include "Canvas.h"
Canvas::Canvas(
const QSurfaceFormat & format
, QScreen * screen)
: QWindow(screen)
, m_context(new QOpenGLContext)
, m_painter(nullptr)
, m_camera(new Camera())
, m_navigation(new Navigation(*m_camera))
, m_swapInterval(VerticalSyncronization)
, m_repaintTimer(new QBasicTimer())
, m_continuousRepaint(false)
, m_fpsTimer(nullptr)
, m_time(new CyclicTime(0.0L, 60.0)) // this is one day in 60 seconds (1d/1h)
, m_swapts(0.0)
, m_swaps(0)
, m_update(false)
{
setSurfaceType(OpenGLSurface);
create();
m_camera->setFovy(40.0);
m_navigation->reset();
initializeGL(format);
}
Canvas::~Canvas()
{
}
QSurfaceFormat Canvas::format() const
{
if (!m_context)
return QSurfaceFormat();
return m_context->format();
}
void Canvas::setContinuousRepaint(
bool enable
, int msec)
{
if (m_continuousRepaint)
m_repaintTimer->stop();
m_continuousRepaint = enable;
if (m_continuousRepaint)
m_repaintTimer->start(msec, this);
}
bool Canvas::continuousRepaint() const
{
return m_continuousRepaint;
}
const QString Canvas::querys(const GLenum penum)
{
const QString result = reinterpret_cast<const char*>(glGetString(penum));
//glError();
return result;
}
const GLint Canvas::queryi(const GLenum penum)
{
GLint result;
glGetIntegerv(penum, &result);
return result;
}
void Canvas::initializeGL(const QSurfaceFormat & format)
{
m_context->setFormat(format);
if (!m_context->create())
{
qCritical() << "Errors during creation of OpenGL context.";
return;
}
m_context->makeCurrent(this);
if (!initializeOpenGLFunctions())
{
qCritical() << "Initializing OpenGL failed.";
return;
}
// print some hardware information
qDebug();
qDebug().nospace() << "GPU: "
<< qPrintable(querys(GL_RENDERER)) << " ("
<< qPrintable(querys(GL_VENDOR)) << ", "
<< qPrintable(querys(GL_VERSION)) << ")";
qDebug().nospace() << "GL Version: "
<< qPrintable(QString::number(queryi(GL_MAJOR_VERSION))) << "."
<< qPrintable(QString::number(queryi(GL_MINOR_VERSION))) << " "
<< (queryi(GL_CONTEXT_CORE_PROFILE_BIT) ? "Core" : "Compatibility");
qDebug();
verifyExtensions(); // false if no painter ...
m_grid.reset(new AdaptiveGrid(*this));
m_grid->setNearFar(m_camera->zNear(), m_camera->zFar());
connect(m_camera.data(), &Camera::changed, this, &Canvas::cameraChanged);
m_context->doneCurrent();
m_time->setf(0.0);
m_time->start();
}
void Canvas::resizeEvent(QResizeEvent * event)
{
if (!m_painter)
return;
m_camera->setViewport(event->size());
m_context->makeCurrent(this);
m_painter->resize(event->size().width(), event->size().height());
m_grid->update(m_camera->eye(), m_camera->viewProjection());
m_context->doneCurrent();
if (isExposed() && Hidden != visibility())
paintGL();
}
void Canvas::paintGL()
{
if (!m_painter || !isExposed() || Hidden == visibility())
return;
m_context->makeCurrent(this);
auto programsWithInvalidatedUniforms(FileAssociatedShader::process()); // recompile file associated shaders if required
if (m_update)
{
m_painter->update();
m_grid->update(m_camera->eye(), m_camera->viewProjection());
m_update = false;
}
else
m_painter->update(programsWithInvalidatedUniforms);
m_painter->paint(m_time->getf(true));
m_grid->draw(*this);
m_context->swapBuffers(this);
m_context->doneCurrent();
emit timeUpdate(m_time->getf());
if (!m_fpsTimer)
{
m_fpsTimer.reset(new Timer(true, false));
m_swapts = 0.0;
}
else
m_fpsTimer->update();
++m_swaps;
if (m_fpsTimer->elapsed() - m_swapts >= 1e+9)
{
const float fps = 1e+9f * static_cast<float>(static_cast<long double>
(m_swaps) / (m_fpsTimer->elapsed() - m_swapts));
emit fpsUpdate(fps);
m_swapts = m_fpsTimer->elapsed();
m_swaps = 0;
}
}
void Canvas::cameraChanged()
{
m_update = true;
}
void Canvas::timerEvent(QTimerEvent * event)
{
assert(m_repaintTimer);
if(event->timerId() != m_repaintTimer->timerId())
return;
paintGL();
}
void Canvas::assignPainter(AbstractPainter * painter)
{
if (m_painter == painter)
return;
m_painter = painter;
if (!m_painter)
return;
m_context->makeCurrent(this);
m_painter->initialize();
m_painter->setCamera(m_camera.data());
verifyExtensions();
m_context->doneCurrent();
m_navigation->setCoordinateProvider(m_painter);
}
bool Canvas::verifyExtensions() const
{
if (!m_painter)
return false;
if (!m_context->isValid())
{
qWarning("Extensions cannot be verified due to invalid context.");
return false;
}
QStringList unsupported;
const QStringList & extensions(m_painter->extensions());
foreach(const QString & extension, extensions)
if (!m_context->hasExtension(qPrintable(extension)))
unsupported << extension;
if (unsupported.isEmpty())
return true;
if (unsupported.size() > 1)
qWarning("The following mandatory OpenGL extensions are not supported:");
else
qWarning("The following mandatory OpenGL extension is not supported:");
foreach(const QString & extension, unsupported)
qWarning() << extension;
qWarning("");
return false;
}
void Canvas::setSwapInterval(SwapInterval swapInterval)
{
m_context->makeCurrent(this);
bool result(false);
m_swapInterval = swapInterval;
#ifdef WIN32
// ToDo: C++11 - type aliases
typedef bool(WINAPI * SWAPINTERVALEXTPROC) (int);
static SWAPINTERVALEXTPROC wglSwapIntervalEXT = nullptr;
if (!wglSwapIntervalEXT)
wglSwapIntervalEXT = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("wglSwapIntervalEXT"));
if (wglSwapIntervalEXT)
result = wglSwapIntervalEXT(swapInterval);
#elif __APPLE__
qWarning("ToDo: Setting swap interval is currently not implemented for __APPLE__");
#else
// ToDo: C++11 - type aliases
typedef int(APIENTRY * SWAPINTERVALEXTPROC) (int);
static SWAPINTERVALEXTPROC glXSwapIntervalSGI = nullptr;
if (!glXSwapIntervalSGI)
glXSwapIntervalSGI = reinterpret_cast<SWAPINTERVALEXTPROC>(m_context->getProcAddress("glXSwapIntervalSGI"));
if (glXSwapIntervalSGI)
result = glXSwapIntervalSGI(swapInterval);
#endif
if (!result)
qWarning("Setting swap interval to %s failed."
, qPrintable(swapIntervalToString(swapInterval)));
else
qDebug("Setting swap interval to %s."
, qPrintable(swapIntervalToString(swapInterval)));
m_context->doneCurrent();
}
void Canvas::toggleSwapInterval()
{
switch (m_swapInterval)
{
case NoVerticalSyncronization:
setSwapInterval(VerticalSyncronization);
break;
case VerticalSyncronization:
setSwapInterval(AdaptiveVerticalSyncronization);
break;
case AdaptiveVerticalSyncronization:
setSwapInterval(NoVerticalSyncronization);
break;
}
}
const QString Canvas::swapIntervalToString(SwapInterval swapInterval)
{
switch (swapInterval)
{
case NoVerticalSyncronization:
return QString("NoVerticalSyncronization");
case VerticalSyncronization:
return QString("VerticalSyncronization");
case AdaptiveVerticalSyncronization:
return QString("AdaptiveVerticalSyncronization");
default:
return QString();
}
}
void Canvas::keyPressEvent(QKeyEvent * event)
{
if (!m_navigation)
return;
m_navigation->keyPressEvent(event);
// forward event to painter for exercise mode switching
m_painter->keyPressEvent(event);
}
void Canvas::keyReleaseEvent(QKeyEvent * event)
{
if (!m_navigation)
return;
m_navigation->keyReleaseEvent(event);
}
void Canvas::mouseMoveEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseMoveEvent(event);
emit mouseUpdate(event->pos());
if (m_painter)
{
if (NavigationMath::validDepth(m_painter->depthAt(event->pos())))
emit objUpdate(m_painter->objAt(event->pos()));
else
emit objUpdate(QVector3D());
}
m_context->doneCurrent();
}
void Canvas::mousePressEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mousePressEvent(event);
m_context->doneCurrent();
}
void Canvas::mouseReleaseEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseReleaseEvent(event);
m_context->doneCurrent();
}
void Canvas::mouseDoubleClickEvent(QMouseEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->mouseDoubleClickEvent(event);
m_context->doneCurrent();
}
void Canvas::wheelEvent(QWheelEvent * event)
{
if (!m_navigation)
return;
m_context->makeCurrent(this);
m_navigation->wheelEvent(event);
m_context->doneCurrent();
}
<|endoftext|> |
<commit_before>/*
* Illarionserver - server for the game Illarion
* Copyright 2011 Illarion e.V.
*
* This file is part of Illarionserver.
*
* Illarionserver 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.
*
* Illarionserver 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
* Illarionserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CONNECTION_HPP_
#define _CONNECTION_HPP_
#include <memory>
#include <string>
#include <pqxx/connection.hxx>
#include <pqxx/transaction.hxx>
namespace Database {
class Connection;
using PConnection = std::shared_ptr<Connection>;
class Connection {
private:
/* The libpgxx representation of the connection to the database. */
std::unique_ptr<pqxx::connection> internalConnection = nullptr;
std::unique_ptr<pqxx::transaction_base> transaction = nullptr;
public:
explicit Connection(const std::string &connectionString);
void beginTransaction(void);
auto query(const std::string &query) -> pqxx::result;
void commitTransaction(void);
void rollbackTransaction(void);
template<typename T> inline auto quote(const T &t) const -> std::string {
return internalConnection->quote(t);
}
inline auto transactionActive() const -> bool {
return bool(transaction);
}
private:
Connection(const Connection &org) = delete;
auto operator=(const Connection &org) -> Connection & = delete;
};
}
#endif // _CONNECTION_HPP_
<commit_msg>Remove redundant void argument<commit_after>/*
* Illarionserver - server for the game Illarion
* Copyright 2011 Illarion e.V.
*
* This file is part of Illarionserver.
*
* Illarionserver 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.
*
* Illarionserver 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
* Illarionserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CONNECTION_HPP_
#define _CONNECTION_HPP_
#include <memory>
#include <string>
#include <pqxx/connection.hxx>
#include <pqxx/transaction.hxx>
namespace Database {
class Connection;
using PConnection = std::shared_ptr<Connection>;
class Connection {
private:
/* The libpgxx representation of the connection to the database. */
std::unique_ptr<pqxx::connection> internalConnection = nullptr;
std::unique_ptr<pqxx::transaction_base> transaction = nullptr;
public:
explicit Connection(const std::string &connectionString);
void beginTransaction();
auto query(const std::string &query) -> pqxx::result;
void commitTransaction();
void rollbackTransaction();
template<typename T> inline auto quote(const T &t) const -> std::string {
return internalConnection->quote(t);
}
inline auto transactionActive() const -> bool {
return bool(transaction);
}
private:
Connection(const Connection &org) = delete;
auto operator=(const Connection &org) -> Connection & = delete;
};
}
#endif // _CONNECTION_HPP_
<|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 "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/browser_test_utils.h"
using content::BrowserThread;
class FastShutdown : public InProcessBrowserTest {
protected:
FastShutdown() {
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kDisablePopupBlocking);
}
private:
DISALLOW_COPY_AND_ASSIGN(FastShutdown);
};
// This tests for a previous error where uninstalling an onbeforeunload handler
// would enable fast shutdown even if an onunload handler still existed.
// Flaky on all platforms, http://crbug.com/89173
#if !defined(OS_CHROMEOS) // ChromeOS opens tabs instead of windows for popups.
IN_PROC_BROWSER_TEST_F(FastShutdown, SlowTermination) {
// Need to run these tests on http:// since we only allow cookies on that (and
// https obviously).
ASSERT_TRUE(test_server()->Start());
// This page has an unload handler.
GURL url = test_server()->GetURL("files/fast_shutdown/on_unloader.html");
TabContents* tab = chrome::GetActiveTabContents(browser());
EXPECT_EQ("", content::GetCookies(tab->profile(), url));
content::WindowedNotificationObserver window_observer(
chrome::NOTIFICATION_BROWSER_WINDOW_READY,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE);
window_observer.Wait();
// Close the new window, removing the one and only beforeunload handler.
ASSERT_EQ(2u, BrowserList::size());
BrowserList::const_iterator i = BrowserList::begin();
++i;
chrome::CloseWindow(*i);
// Need to wait for the renderer process to shutdown to ensure that we got the
// set cookies IPC.
content::WindowedNotificationObserver renderer_shutdown_observer(
content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
content::NotificationService::AllSources());
// Close the tab. This should launch the unload handler, which sets a cookie
// that's stored to disk.
chrome::CloseTab(browser());
renderer_shutdown_observer.Wait();
EXPECT_EQ("unloaded=ohyeah", content::GetCookies(tab->profile(), url));
}
#endif
<commit_msg>tes<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 "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/browser_test_utils.h"
using content::BrowserThread;
class FastShutdown : public InProcessBrowserTest {
protected:
FastShutdown() {
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kDisablePopupBlocking);
}
private:
DISALLOW_COPY_AND_ASSIGN(FastShutdown);
};
// This tests for a previous error where uninstalling an onbeforeunload handler
// would enable fast shutdown even if an onunload handler still existed.
// Flaky on all platforms, http://crbug.com/89173
#if !defined(OS_CHROMEOS) // ChromeOS opens tabs instead of windows for popups.
IN_PROC_BROWSER_TEST_F(FastShutdown, SlowTermination) {
// Need to run these tests on http:// since we only allow cookies on that (and
// https obviously).
ASSERT_TRUE(test_server()->Start());
// This page has an unload handler.
GURL url = test_server()->GetURL("files/fast_shutdown/on_unloader.html");
TabContents* tab = chrome::GetActiveTabContents(browser());
EXPECT_EQ("", content::GetCookies(tab->profile(), url));
content::WindowedNotificationObserver window_observer(
chrome::NOTIFICATION_BROWSER_WINDOW_READY,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE);
window_observer.Wait();
// Close the new window, removing the one and only beforeunload handler.
ASSERT_EQ(2u, BrowserList::size());
BrowserList::const_iterator i = BrowserList::begin();
++i;
chrome::CloseWindow(*i);
// Need to wait for the renderer process to shutdown to ensure that we got the
// set cookies IPC.
content::WindowedNotificationObserver renderer_shutdown_observer(
content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
content::NotificationService::AllSources());
// Close the tab. This should launch the unload handler, which sets a cookie
// that's stored to disk.
chrome::CloseTab(browser());
renderer_shutdown_observer.Wait();
EXPECT_EQ("unloaded=ohyeah", content::GetCookies(tab->profile(), url));
}
#endif
<|endoftext|> |
<commit_before>#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include "FileUtils.h"
#include <pwd.h>
#include <map>
#include <vector>
class CStickyChan : public CModule
{
public:
MODCONSTRUCTOR(CStickyChan) {}
virtual ~CStickyChan()
{
}
virtual bool OnLoad(const CString& sArgs);
virtual CString GetDescription()
{
return ( "configless sticky chans, keeps you there very stickily even" );
}
virtual void OnModCommand( const CString& sCommand )
{
CString sCmdName = sCommand.Token(0);
CString sChannel = sCommand.Token(1);
sChannel.MakeLower();
if ( ( sCmdName == "stick" ) && ( !sChannel.empty() ) )
{
SetNV( sChannel, sCommand.Token(2) );
PutModule( "Stuck " + sChannel );
}
else if ( ( sCmdName == "unstick" ) && ( !sChannel.empty() ) )
{
MCString::iterator it = FindNV( sChannel );
if ( it != EndNV() )
DelNV( it );
PutModule( "UnStuck " + sChannel );
}
else
{
PutModule( "USAGE: [un]stick #channel [key]" );
}
}
virtual void RunJob()
{
for( MCString::iterator it = BeginNV(); it != EndNV(); it++ )
{
if ( !m_pUser->FindChan( it->first ) )
{
CChan *pChan = new CChan( it->first, m_pUser );
if ( !it->second.empty() )
pChan->SetKey( it->second );
m_pUser->AddChan( pChan );
PutModule( "Joining [" + it->first + "]" );
}
}
}
private:
};
static void RunTimer( CModule * pModule, CFPTimer *pTimer )
{
((CStickyChan *)pModule)->RunJob();
}
bool CStickyChan::OnLoad(const CString& sArgs)
{
AddTimer( RunTimer, "StickyChanTimer", 15 );
return( true );
}
MODULEDEFS(CStickyChan)
<commit_msg>speed things up a bit<commit_after>#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "Utils.h"
#include "FileUtils.h"
#include <pwd.h>
#include <map>
#include <vector>
class CStickyChan : public CModule
{
public:
MODCONSTRUCTOR(CStickyChan) {}
virtual ~CStickyChan()
{
}
virtual bool OnLoad(const CString& sArgs);
virtual CString GetDescription()
{
return ( "configless sticky chans, keeps you there very stickily even" );
}
virtual void OnModCommand( const CString& sCommand )
{
CString sCmdName = sCommand.Token(0);
CString sChannel = sCommand.Token(1);
sChannel.MakeLower();
if ( ( sCmdName == "stick" ) && ( !sChannel.empty() ) )
{
SetNV( sChannel, sCommand.Token(2) );
PutModule( "Stuck " + sChannel );
}
else if ( ( sCmdName == "unstick" ) && ( !sChannel.empty() ) )
{
MCString::iterator it = FindNV( sChannel );
if ( it != EndNV() )
DelNV( it );
PutModule( "UnStuck " + sChannel );
}
else
{
PutModule( "USAGE: [un]stick #channel [key]" );
}
}
virtual void RunJob()
{
for( MCString::iterator it = BeginNV(); it != EndNV(); it++ )
{
if ( !m_pUser->FindChan( it->first ) )
{
CChan *pChan = new CChan( it->first, m_pUser );
if ( !it->second.empty() )
pChan->SetKey( it->second );
m_pUser->AddChan( pChan );
PutModule( "Joining [" + it->first + "]" );
PutIRC( "JOIN " + it->first + ( it->second.empty() ? "" : it->second ) );
}
}
}
private:
};
static void RunTimer( CModule * pModule, CFPTimer *pTimer )
{
((CStickyChan *)pModule)->RunJob();
}
bool CStickyChan::OnLoad(const CString& sArgs)
{
AddTimer( RunTimer, "StickyChanTimer", 15 );
return( true );
}
MODULEDEFS(CStickyChan)
<|endoftext|> |
<commit_before>#include <unistd.h>
#include "acmacs-base/argv.hh"
#include "acmacs-base/temp-file.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-map-draw/setup-dbs.hh"
#include "acmacs-map-draw/log.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
constexpr const std::string_view sHelpPost = R"(
one input chart: make map
two input charts: make procrustes
output /: do not generate any output
no output: generate temp pdf and open it (and then delete it)
-D <arg> --define <arg>
)";
using namespace acmacs::argv;
struct MapiOptions : public acmacs::argv::v2::argv
{
MapiOptions(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) { parse(a_argc, a_argv, on_err); }
// std::string_view help_pre() const override { return sHelpPost; }
std::string_view help_post() const override { return sHelpPost; }
option<str> db_dir{*this, "db-dir"};
// option<str> seqdb{*this, "seqdb"};
option<str_array> settings_files{*this, 's'};
option<str_array> defines{*this, 'D', "define", desc{"see {ACMACSD_ROOT}/share/doc/mapi.org"}};
option<str_array> apply{*this, 'a', "apply", dflt{str_array{"main"}}, desc{"comma separated names or json array to use as \"apply\", e.g. [\"/all-grey\",\"/egg\",\"/clades\",\"/labels\"]"}};
option<bool> interactive{*this, 'i', "interactive"};
// option<str> previous{*this, "previous"};
option<size_t> projection{*this, 'p', "projection", dflt{0ul}};
option<size_t> secondary_projection{*this, 'r', "secondary-projection", dflt{static_cast<size_t>(-1)}};
option<bool> open{*this, "open"};
option<bool> ql{*this, "ql"};
option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of enablers"}};
argument<str_array> files{*this, arg_name{"input: chart.ace, chart.save, chart.acd1; output: map.pdf, /"}, mandatory};
};
// option<str> apply_from{*this, "apply-from", desc{"read json array to use as \"apply\" from file (or stdin if \"-\""}};
// option<bool> clade{*this, "clade"};
// option<double> point_scale{*this, "point-scale", dflt{1.0}};
// option<double> rotate_degrees{*this, 'r', "rotate-degrees", dflt{0.0}, desc{"counter clockwise"}};
// option<bool> flip_ew{*this, "flip-ew"};
// option<bool> flip_ns{*this, "flip-ns"};
// option<str> save{*this, "save", desc{"save resulting chart with modified projection and plot spec"}};
// ----------------------------------------------------------------------
static std::pair<std::vector<std::string_view>, std::vector<std::string_view>> parse_files(const argument<str_array>& files);
static void signal_handler(int sig_num);
int main(int argc, char* const argv[])
{
using namespace std::string_view_literals;
int exit_code = 0;
try {
acmacs::log::register_enabler_acmacs_base();
MapiOptions opt(argc, argv);
acmacs::log::enable(opt.verbose);
setup_dbs(opt.db_dir, !opt.verbose.empty());
const auto [inputs, outputs] = parse_files(opt.files);
ChartDraw chart_draw{inputs, opt.projection};
acmacs::mapi::Settings settings{chart_draw};
settings.load(opt.settings_files, opt.defines);
for (size_t chart_no = 0; chart_no < chart_draw.number_of_charts(); ++chart_no)
settings.setenv_toplevel(fmt::format("chart[{}]", chart_no), chart_draw.chart(chart_no).filename());
if (opt.interactive)
signal(SIGHUP, signal_handler);
for (;;) {
for (const auto& to_apply : opt.apply) {
if (!to_apply.empty()) {
if (to_apply[0] == '{' || to_apply[0] == '[') {
settings.apply(to_apply);
}
else {
for (const auto& to_apply_one : acmacs::string::split(to_apply))
settings.apply(to_apply_one);
}
}
}
chart_draw.calculate_viewport();
AD_INFO("{:.2f}", chart_draw.viewport("mapi main"));
AD_INFO("transformation: {}", chart_draw.chart(0).modified_transformation());
if (outputs.empty()) {
acmacs::file::temp output{fmt::format("{}--p{}.pdf", fs::path(inputs[0]).stem(), opt.projection)};
chart_draw.draw(output, 800, report_time::yes);
acmacs::quicklook(output, 2);
}
else if (outputs[0] == "/dev/null"sv || outputs[0] == "/"sv) { // do not generate pdf
}
else {
chart_draw.draw(outputs[0], 800, report_time::yes);
acmacs::open_or_quicklook(opt.open, opt.ql, outputs[0]);
}
if (opt.interactive) {
fmt::print(stderr, "mapi-i >> ");
fd_set set;
FD_ZERO(&set);
FD_SET(0, &set);
if (select(FD_SETSIZE, &set, nullptr, nullptr, nullptr) > 0) {
// fmt::print(stderr, " (reading)\n");
std::string input(20, ' ');
if (const auto bytes = ::read(0, input.data(), input.size()); bytes > 0) {
input.resize(static_cast<size_t>(bytes));
// fmt::print(stderr, " (read {} bytes)\n", bytes);
}
}
acmacs::run_and_detach({"tink"}, 0);
}
else
break;
chart_draw.reset();
chart_draw.remove_legend();
try {
settings.reload();
}
catch (std::exception& err) {
AD_ERROR("{}", err);
acmacs::run_and_detach({"submarine"}, 0);
}
}
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
std::pair<std::vector<std::string_view>, std::vector<std::string_view>> parse_files(const argument<str_array>& files)
{
using namespace std::string_view_literals;
std::vector<std::string_view> inputs, outputs;
constexpr std::array input_suffixes{".ace"sv, ".acd1"sv, ".acd1.xz"sv, ".acd1.bz2"sv, ".save"sv, ".save.xz"sv, ".save.bz2"sv};
const auto is_input = [&input_suffixes](std::string_view name) -> bool {
return std::any_of(std::begin(input_suffixes), std::end(input_suffixes), [name](std::string_view suff) -> bool { return acmacs::string::endswith(name, suff); });
};
for (const auto& file : files) {
if (is_input(file))
inputs.push_back(file);
else
outputs.push_back(file);
}
if (inputs.empty())
throw std::runtime_error{"no input files (charts) found in the command line"};
if (inputs.size() > 2)
throw std::runtime_error{fmt::format("too many input files () found in the command line", inputs)};
return {inputs, outputs};
} // parse_files
// ----------------------------------------------------------------------
void signal_handler(int sig_num)
{
fmt::print("SIGNAL {}\n", sig_num);
} // signal_handler
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>porting to linux<commit_after>#include <unistd.h>
#include <signal.h>
#include "acmacs-base/argv.hh"
#include "acmacs-base/temp-file.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-base/filesystem.hh"
#include "acmacs-map-draw/setup-dbs.hh"
#include "acmacs-map-draw/log.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
constexpr const std::string_view sHelpPost = R"(
one input chart: make map
two input charts: make procrustes
output /: do not generate any output
no output: generate temp pdf and open it (and then delete it)
-D <arg> --define <arg>
)";
using namespace acmacs::argv;
struct MapiOptions : public acmacs::argv::v2::argv
{
MapiOptions(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) { parse(a_argc, a_argv, on_err); }
// std::string_view help_pre() const override { return sHelpPost; }
std::string_view help_post() const override { return sHelpPost; }
option<str> db_dir{*this, "db-dir"};
// option<str> seqdb{*this, "seqdb"};
option<str_array> settings_files{*this, 's'};
option<str_array> defines{*this, 'D', "define", desc{"see {ACMACSD_ROOT}/share/doc/mapi.org"}};
option<str_array> apply{*this, 'a', "apply", dflt{str_array{"main"}}, desc{"comma separated names or json array to use as \"apply\", e.g. [\"/all-grey\",\"/egg\",\"/clades\",\"/labels\"]"}};
option<bool> interactive{*this, 'i', "interactive"};
// option<str> previous{*this, "previous"};
option<size_t> projection{*this, 'p', "projection", dflt{0ul}};
option<size_t> secondary_projection{*this, 'r', "secondary-projection", dflt{static_cast<size_t>(-1)}};
option<bool> open{*this, "open"};
option<bool> ql{*this, "ql"};
option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of enablers"}};
argument<str_array> files{*this, arg_name{"input: chart.ace, chart.save, chart.acd1; output: map.pdf, /"}, mandatory};
};
// option<str> apply_from{*this, "apply-from", desc{"read json array to use as \"apply\" from file (or stdin if \"-\""}};
// option<bool> clade{*this, "clade"};
// option<double> point_scale{*this, "point-scale", dflt{1.0}};
// option<double> rotate_degrees{*this, 'r', "rotate-degrees", dflt{0.0}, desc{"counter clockwise"}};
// option<bool> flip_ew{*this, "flip-ew"};
// option<bool> flip_ns{*this, "flip-ns"};
// option<str> save{*this, "save", desc{"save resulting chart with modified projection and plot spec"}};
// ----------------------------------------------------------------------
static std::pair<std::vector<std::string_view>, std::vector<std::string_view>> parse_files(const argument<str_array>& files);
static void signal_handler(int sig_num);
int main(int argc, char* const argv[])
{
using namespace std::string_view_literals;
int exit_code = 0;
try {
acmacs::log::register_enabler_acmacs_base();
MapiOptions opt(argc, argv);
acmacs::log::enable(opt.verbose);
setup_dbs(opt.db_dir, !opt.verbose.empty());
const auto [inputs, outputs] = parse_files(opt.files);
ChartDraw chart_draw{inputs, opt.projection};
acmacs::mapi::Settings settings{chart_draw};
settings.load(opt.settings_files, opt.defines);
for (size_t chart_no = 0; chart_no < chart_draw.number_of_charts(); ++chart_no)
settings.setenv_toplevel(fmt::format("chart[{}]", chart_no), chart_draw.chart(chart_no).filename());
if (opt.interactive)
signal(SIGHUP, signal_handler);
for (;;) {
for (const auto& to_apply : opt.apply) {
if (!to_apply.empty()) {
if (to_apply[0] == '{' || to_apply[0] == '[') {
settings.apply(to_apply);
}
else {
for (const auto& to_apply_one : acmacs::string::split(to_apply))
settings.apply(to_apply_one);
}
}
}
chart_draw.calculate_viewport();
AD_INFO("{:.2f}", chart_draw.viewport("mapi main"));
AD_INFO("transformation: {}", chart_draw.chart(0).modified_transformation());
if (outputs.empty()) {
acmacs::file::temp output{fmt::format("{}--p{}.pdf", fs::path(inputs[0]).stem(), opt.projection)};
chart_draw.draw(output, 800, report_time::yes);
acmacs::quicklook(output, 2);
}
else if (outputs[0] == "/dev/null"sv || outputs[0] == "/"sv) { // do not generate pdf
}
else {
chart_draw.draw(outputs[0], 800, report_time::yes);
acmacs::open_or_quicklook(opt.open, opt.ql, outputs[0]);
}
if (opt.interactive) {
fmt::print(stderr, "mapi-i >> ");
fd_set set;
FD_ZERO(&set);
FD_SET(0, &set);
if (select(FD_SETSIZE, &set, nullptr, nullptr, nullptr) > 0) {
// fmt::print(stderr, " (reading)\n");
std::string input(20, ' ');
if (const auto bytes = ::read(0, input.data(), input.size()); bytes > 0) {
input.resize(static_cast<size_t>(bytes));
// fmt::print(stderr, " (read {} bytes)\n", bytes);
}
}
acmacs::run_and_detach({"tink"}, 0);
}
else
break;
chart_draw.reset();
chart_draw.remove_legend();
try {
settings.reload();
}
catch (std::exception& err) {
AD_ERROR("{}", err);
acmacs::run_and_detach({"submarine"}, 0);
}
}
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
std::pair<std::vector<std::string_view>, std::vector<std::string_view>> parse_files(const argument<str_array>& files)
{
using namespace std::string_view_literals;
std::vector<std::string_view> inputs, outputs;
constexpr std::array input_suffixes{".ace"sv, ".acd1"sv, ".acd1.xz"sv, ".acd1.bz2"sv, ".save"sv, ".save.xz"sv, ".save.bz2"sv};
const auto is_input = [&input_suffixes](std::string_view name) -> bool {
return std::any_of(std::begin(input_suffixes), std::end(input_suffixes), [name](std::string_view suff) -> bool { return acmacs::string::endswith(name, suff); });
};
for (const auto& file : files) {
if (is_input(file))
inputs.push_back(file);
else
outputs.push_back(file);
}
if (inputs.empty())
throw std::runtime_error{"no input files (charts) found in the command line"};
if (inputs.size() > 2)
throw std::runtime_error{fmt::format("too many input files () found in the command line", inputs)};
return {inputs, outputs};
} // parse_files
// ----------------------------------------------------------------------
void signal_handler(int sig_num)
{
fmt::print("SIGNAL {}\n", sig_num);
} // signal_handler
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <CGAL/Linear_cell_complex.h>
#include <CGAL/Delaunay_triangulation_3.h>
using namespace std;
typedef CGAL::Point_3 Point;
typedef CGAL::Delaunay_triangulation_3 Delaunay;
// PLC:
map <unsigned, Point> PLCvertices; // mapping between vertex coordinates and corresponding unique id
list <unsigned, unsigned, unsigned> PLCfaces; // contains ids of vertices/points making the triangle
// Delaunay tetrahedralization:
Delaunay DT;
// CDT: output mesh:
map <unsigned, Point> CDTvertices;
list <unsigned, unsigned, unsigned, unsigned> CDTtets; // contains ids of vertices making tetrahedron
// reads input PLC
void readPLCInput()
{
// read PLY file(assumed to contain the PLC)
// initialize inputVertices
// initialize inputFaces
}
// computes the initial delaunay tetrahedralization
void computeInitialDelaunayTetrahedralization()
{
list <Point> tempPointList;
for (map<unsigned, Point>::iterator pit = PLCvertices.begin(); pit != PLCvertices.end(); pit++)
tempPointList.push(PLCvertices.find(i)->second);
DT.insert(tempPointList.begin(). tempPointList.end());
}
// removes local degeneracies from Delaunay tetrahedralization
void removeLocalDegeneracies()
{
// compute all local degeneracies in DT and add them to Q
// repeat while Q != NULL
// for each local degeneracy l in Q:
// if l is removable:
// remove l by small perturbation
// else,
// compute vb to break l
// if vb encroaches upon any segment or subface,
// push l into queue
// call boundary protection procedure
// else
// insert vb to break l
// end if
// end if
// end for
// end repeat
}
// recovers the constraint faces
void recoverConstraintFaces()
{
}
// main procedure
int main()
{
readPLCInput();
computeInitialDelaunayTetrahedralization();
removeLocalDegeneracies();
recoverConstraintFaces();
return 0;
}
<commit_msg>initialized plcVertex and plcFaces using rply library<commit_after>#include <CGAL/Linear_cell_complex.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include "rply.h"
using namespace std;
typedef CGAL::Point_3 Point;
typedef CGAL::Delaunay_triangulation_3 Delaunay;
// PLC:
map <unsigned, Point> plcVertices; // mapping between vertex coordinates and corresponding unique id
list <unsigned, unsigned, unsigned> plcFaces; // contains ids of vertices/points making the triangle
// Delaunay tetrahedralization:
Delaunay DT;
// CDT: output mesh:
map <unsigned, Point> cdtVertices;
list <unsigned, unsigned, unsigned, unsigned> cdtTets; // contains ids of vertices making tetrahedron
static unsigned tempPoint[3];
unsigned int dimensionId = 0;
static unsigned pointId = 0;
static tempFace[3];
void vertex_cb(p_ply_argument argument)
{
long eol;
ply_get_argument_user_data(argument, NULL, &eol);
tempPoint[dimensionId++] = ply_get_argument_value(argument);
// insert the vertex into plcVertex
if (strcmp(argument.element.name, 'z'))
{
plcVertex.push(pointId++, Point(tempPoint[0],tempPoint[1],tempPoint[2]));
dimensionId = 0;
}
}
void face_cb(p_ply_argument argument)
{
long length, value_index;
ply_get_argument_property(argument, NULL, &length, &value_index);
switch (value_index)
{
case 0:
case 1:
tempFace[pointId++] = ply_get_argument_value(argument);
break;
case 2:
tempFace[pointId] = ply_get_argument_value(argument);
pointId = 0;
plcFaces.push(tempFace[0], tempFace[1], tempFace[2]);
break;
default:
cout << "Invalid number of points in a face specified :(";
break;
}
}
// reads input PLC
void readPLCInput()
{
// read PLY file(assumed to contain the PLC)
string fileName;
cout << "Please enter input filename";
cin >> fileName;
p_ply inputPLY = ply_open(fileName);
if (!inputPLY) return 1;
if (!ply_read_header(inputPLY)) return 1;
if (!read_ply(inputPLY))
{
cout << "Cannot read the PLY file :(";
exit(0);
}
// Initialize plcVertex and plcFaces
ply_set_read_cb(ply, "vertex", "x", vertex_cb, NULL, 0);
ply_set_read_cb(ply, "vertex", "y", vertex_cb, NULL, 0);
ply_set_read_cb(ply, "vertex", "z", vertex_cb, NULL, 0);
ply_set_read_cb(ply, "face", "vertex_indices", face_cb, NULL, 0);
inputPLY.close();
}
// computes the initial delaunay tetrahedralization
void computeInitialDelaunayTetrahedralization()
{
list <Point> tempPointList;
for (map<unsigned, Point>::iterator pit = PLCvertices.begin(); pit != PLCvertices.end(); pit++)
tempPointList.push(PLCvertices.find(i)->second);
DT.insert(tempPointList.begin(), tempPointList.end());
}
// removes local degeneracies from Delaunay tetrahedralization
void removeLocalDegeneracies()
{
// compute all local degeneracies in DT and add them to Q
// repeat while Q != NULL
// for each local degeneracy l in Q:
// if l is removable:
// remove l by small perturbation
// else,
// compute vb to break l
// if vb encroaches upon any segment or subface,
// push l into queue
// call boundary protection procedure
// else
// insert vb to break l
// end if
// end if
// end for
// end repeat
}
// recovers the constraint faces
void recoverConstraintFaces()
{
}
// main procedure
int main()
{
readPLCInput();
computeInitialDelaunayTetrahedralization();
removeLocalDegeneracies();
recoverConstraintFaces();
return 0;
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include <db_cxx.h>
int dbcreate(char *dbfile, char *dbname, int argc, char *argv[]) {
int r;
#if USE_ENV
DbEnv *env = new DbEnv(DB_CXX_NO_EXCEPTIONS);
r = env->open(".", DB_INIT_MPOOL + DB_CREATE + DB_PRIVATE, 0777); assert(r == 0);
#else
DbEnv *env = 0;
#endif
Db *db = new Db(env, DB_CXX_NO_EXCEPTIONS);
r = db->open(0, dbfile, dbname, DB_BTREE, DB_CREATE, 0777);
assert(r == 0);
int i = 0;
while (i < argc) {
char *k = argv[i++];
if (i < argc) {
char *v = argv[i++];
Dbt key(k, strlen(k)); Dbt val(v, strlen(v));
r = db->put(0, &key, &val, 0); assert(r == 0);
}
}
r = db->close(0); assert(r == 0);
if (env) {
r = env->close(0); assert(r == 0);
delete env;
}
delete db;
return 0;
}
int usage() {
printf("db_create [-s DBNAME] DBFILE [KEY VAL]*\n");
return 1;
}
int main(int argc, char *argv[]) {
char *dbname = 0;
int i;
for (i=1; i<argc; i++) {
char *arg = argv[i];
if (0 == strcmp(arg, "-h") || 0 == strcmp(arg, "--help"))
return usage();
if (0 == strcmp(arg, "-s")) {
i++;
if (i >= argc)
return usage();
dbname = argv[i];
continue;
}
break;
}
if (i >= argc)
return usage();
char *dbfile = argv[i++];
return dbcreate(dbfile, dbname, argc-i, &argv[i]);
}
<commit_msg>test for nodup and dupsort trees in the same file. addresses #333<commit_after>#include <assert.h>
#include <db_cxx.h>
int dbcreate(char *dbfile, char *dbname, int dbflags, int argc, char *argv[]) {
int r;
#if USE_ENV
DbEnv *env = new DbEnv(DB_CXX_NO_EXCEPTIONS);
r = env->open(".", DB_INIT_MPOOL + DB_CREATE + DB_PRIVATE, 0777); assert(r == 0);
#else
DbEnv *env = 0;
#endif
Db *db = new Db(env, DB_CXX_NO_EXCEPTIONS);
r = db->set_flags(dbflags);
assert(r == 0);
r = db->open(0, dbfile, dbname, DB_BTREE, DB_CREATE, 0777);
assert(r == 0);
int i = 0;
while (i < argc) {
char *k = argv[i++];
if (i < argc) {
char *v = argv[i++];
Dbt key(k, strlen(k)); Dbt val(v, strlen(v));
r = db->put(0, &key, &val, 0); assert(r == 0);
}
}
r = db->close(0); assert(r == 0);
if (env) {
r = env->close(0); assert(r == 0);
delete env;
}
delete db;
return 0;
}
int usage() {
printf("db_create [-s DBNAME] [-D] [-S] DBFILE [KEY VAL]*\n");
return 1;
}
int main(int argc, char *argv[]) {
char *dbname = 0;
int dbflags = 0;
int i;
for (i=1; i<argc; i++) {
char *arg = argv[i];
if (0 == strcmp(arg, "-h") || 0 == strcmp(arg, "--help"))
return usage();
if (0 == strcmp(arg, "-s")) {
if (i+1 >= argc)
return usage();
dbname = argv[++i];
continue;
}
if (0 == strcmp(arg, "-D")) {
dbflags += DB_DUP;
continue;
}
if (0 == strcmp(arg, "-S")) {
dbflags += DB_DUPSORT;
continue;
}
break;
}
if (i >= argc)
return usage();
char *dbfile = argv[i++];
return dbcreate(dbfile, dbname, dbflags, argc-i, &argv[i]);
}
<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***********************************************************************/
// example file on how to use moses library
#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif
#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"
#include "TranslationAnalysis.h"
#if HAVE_CONFIG_H
#include "config.h"
#else
// those not using autoconf have to build MySQL support for now
# define USE_MYSQL 1
#endif
using namespace std;
Timer timer;
bool readInput(InputOutput *inputOutput, int inputType, InputType*& source)
{
delete source;
source=inputOutput->GetInput((inputType ?
static_cast<InputType*>(new ConfusionNet) :
static_cast<InputType*>(new Sentence(Input))));
return (source ? true : false);
}
int main(int argc, char* argv[])
{
// Welcome message
TRACE_ERR( "Moses (built on " << __DATE__ << ")" << endl );
TRACE_ERR( "a beam search decoder for phrase-based statistical machine translation models" << endl );
TRACE_ERR( "written by Hieu Hoang, with contributions by Nicola Bertoldi, Ondrej Bojar," << endl <<
"Chris Callison-Burch, Alexandra Constantin, Brooke Cowan, Chris Dyer, Marcello Federico," << endl <<
"Evan Herbst, Philipp Koehn, Christine Moran, Wade Shen, and Richard Zens." << endl);
TRACE_ERR( "(c) 2006 University of Edinburgh, Scotland" << endl );
TRACE_ERR( "command: " );
for(int i=0;i<argc;++i) TRACE_ERR( argv[i]<<" " );
TRACE_ERR(endl);
// load data structures
timer.start("Starting...");
StaticData staticData;
if (!staticData.LoadParameters(argc, argv))
return EXIT_FAILURE;
// set up read/writing class
InputOutput *inputOutput = GetInputOutput(staticData);
std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();
std::cerr << "The global weight vector looks like this:\n";
vector<float> weights = staticData.GetAllWeights();
std::cerr << weights[0];
for (size_t j=1; j<weights.size(); j++) { std::cerr << ", " << weights[j]; }
std::cerr << "\n";
// every score must have a weight! check that here:
assert(weights.size() == staticData.GetScoreIndexManager().GetTotalNumberOfScores());
if (inputOutput == NULL)
return EXIT_FAILURE;
// read each sentence & decode
InputType *source=0;
size_t lineCount = 0;
while(readInput(inputOutput,staticData.GetInputType(),source))
{
// note: source is only valid within this while loop!
ResetUserTime();
TRACE_ERR("\nTRANSLATING(" << ++lineCount << "): " << *source <<endl);
staticData.InitializeBeforeSentenceProcessing(*source);
Manager manager(*source, staticData);
manager.ProcessSentence();
inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
staticData.GetReportSourceSpan(),
staticData.GetReportAllFactors()
);
// n-best
size_t nBestSize = staticData.GetNBestSize();
if (nBestSize > 0)
{
TRACE_ERR("WRITING " << nBestSize << " TRANSLATION ALTERNATIVES TO " << staticData.GetNBestFilePath() << endl);
LatticePathList nBestList;
manager.CalcNBest(nBestSize, nBestList,staticData.OnlyDistinctNBest());
inputOutput->SetNBest(nBestList, source->GetTranslationId());
RemoveAllInColl(nBestList);
}
if (staticData.IsDetailedTranslationReportingEnabled()) {
TranslationAnalysis::PrintTranslationAnalysis(std::cerr, manager.GetBestHypothesis());
PrintUserTime(std::cerr, "Sentence Decoding Time:");
}
manager.CalcDecoderStatistics(staticData);
staticData.CleanUpAfterSentenceProcessing();
}
delete inputOutput;
timer.check("End.");
return EXIT_SUCCESS;
}
InputOutput *GetInputOutput(StaticData &staticData)
{
InputOutput *inputOutput;
const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder()
,&outputFactorOrder = staticData.GetOutputFactorOrder();
FactorMask inputFactorUsed(inputFactorOrder);
// io
if (staticData.GetIOMethod() == IOMethodFile)
{
TRACE_ERR("IO from File" << endl);
string inputFileHash;
list< Phrase > inputPhraseList;
string filePath = staticData.GetParam("input-file")[0];
TRACE_ERR("About to create ioFile" << endl);
IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath()
, filePath);
if(staticData.GetInputType())
{
TRACE_ERR("Do not read input phrases for confusion net translation\n");
}
else
{
TRACE_ERR("About to GetInputPhrase\n");
ioFile->GetInputPhrase(inputPhraseList);
}
TRACE_ERR("After GetInputPhrase" << endl);
inputOutput = ioFile;
inputFileHash = GetMD5Hash(filePath);
TRACE_ERR("About to LoadPhraseTables" << endl);
staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
ioFile->ResetSentenceId();
}
else
{
TRACE_ERR("IO from STDOUT/STDIN" << endl);
inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath());
staticData.LoadPhraseTables();
}
staticData.LoadMapping();
timer.check("Created input-output object");
return inputOutput;
}
<commit_msg>Added decoding time computation.<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***********************************************************************/
// example file on how to use moses library
#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif
#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"
#include "TranslationAnalysis.h"
#if HAVE_CONFIG_H
#include "config.h"
#else
// those not using autoconf have to build MySQL support for now
# define USE_MYSQL 1
#endif
using namespace std;
Timer timer;
bool readInput(InputOutput *inputOutput, int inputType, InputType*& source)
{
delete source;
source=inputOutput->GetInput((inputType ?
static_cast<InputType*>(new ConfusionNet) :
static_cast<InputType*>(new Sentence(Input))));
return (source ? true : false);
}
int main(int argc, char* argv[])
{
// Welcome message
TRACE_ERR( "Moses (built on " << __DATE__ << ")" << endl );
TRACE_ERR( "a beam search decoder for phrase-based statistical machine translation models" << endl );
TRACE_ERR( "written by Hieu Hoang, with contributions by Nicola Bertoldi, Ondrej Bojar," << endl <<
"Chris Callison-Burch, Alexandra Constantin, Brooke Cowan, Chris Dyer, Marcello Federico," << endl <<
"Evan Herbst, Philipp Koehn, Christine Moran, Wade Shen, and Richard Zens." << endl);
TRACE_ERR( "(c) 2006 University of Edinburgh, Scotland" << endl );
TRACE_ERR( "command: " );
for(int i=0;i<argc;++i) TRACE_ERR( argv[i]<<" " );
TRACE_ERR(endl);
// load data structures
timer.start("Starting...");
StaticData staticData;
if (!staticData.LoadParameters(argc, argv))
return EXIT_FAILURE;
// set up read/writing class
InputOutput *inputOutput = GetInputOutput(staticData);
std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();
std::cerr << "The global weight vector looks like this:\n";
vector<float> weights = staticData.GetAllWeights();
std::cerr << weights[0];
for (size_t j=1; j<weights.size(); j++) { std::cerr << ", " << weights[j]; }
std::cerr << "\n";
// every score must have a weight! check that here:
assert(weights.size() == staticData.GetScoreIndexManager().GetTotalNumberOfScores());
if (inputOutput == NULL)
return EXIT_FAILURE;
// read each sentence & decode
InputType *source=0;
size_t lineCount = 0;
while(readInput(inputOutput,staticData.GetInputType(),source))
{
// note: source is only valid within this while loop!
ResetUserTime();
TRACE_ERR("\nTRANSLATING(" << ++lineCount << "): " << *source <<endl);
staticData.InitializeBeforeSentenceProcessing(*source);
Manager manager(*source, staticData);
manager.ProcessSentence();
inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
staticData.GetReportSourceSpan(),
staticData.GetReportAllFactors()
);
// n-best
size_t nBestSize = staticData.GetNBestSize();
if (nBestSize > 0)
{
TRACE_ERR("WRITING " << nBestSize << " TRANSLATION ALTERNATIVES TO " << staticData.GetNBestFilePath() << endl);
LatticePathList nBestList;
manager.CalcNBest(nBestSize, nBestList,staticData.OnlyDistinctNBest());
inputOutput->SetNBest(nBestList, source->GetTranslationId());
RemoveAllInColl(nBestList);
}
if (staticData.IsDetailedTranslationReportingEnabled()) {
TranslationAnalysis::PrintTranslationAnalysis(std::cerr, manager.GetBestHypothesis());
}
PrintUserTime(std::cerr, "Sentence Decoding Time:");
manager.CalcDecoderStatistics(staticData);
staticData.CleanUpAfterSentenceProcessing();
}
delete inputOutput;
timer.check("End.");
return EXIT_SUCCESS;
}
InputOutput *GetInputOutput(StaticData &staticData)
{
InputOutput *inputOutput;
const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder()
,&outputFactorOrder = staticData.GetOutputFactorOrder();
FactorMask inputFactorUsed(inputFactorOrder);
// io
if (staticData.GetIOMethod() == IOMethodFile)
{
TRACE_ERR("IO from File" << endl);
string inputFileHash;
list< Phrase > inputPhraseList;
string filePath = staticData.GetParam("input-file")[0];
TRACE_ERR("About to create ioFile" << endl);
IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath()
, filePath);
if(staticData.GetInputType())
{
TRACE_ERR("Do not read input phrases for confusion net translation\n");
}
else
{
TRACE_ERR("About to GetInputPhrase\n");
ioFile->GetInputPhrase(inputPhraseList);
}
TRACE_ERR("After GetInputPhrase" << endl);
inputOutput = ioFile;
inputFileHash = GetMD5Hash(filePath);
TRACE_ERR("About to LoadPhraseTables" << endl);
staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
ioFile->ResetSentenceId();
}
else
{
TRACE_ERR("IO from STDOUT/STDIN" << endl);
inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath());
staticData.LoadPhraseTables();
}
staticData.LoadMapping();
timer.check("Created input-output object");
return inputOutput;
}
<|endoftext|> |
<commit_before>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include "ShaderFunctions.h"
#include "Timer.h"
#include "g_textures.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct renderpass {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
GLint uloc_iChannelResolution;
//iChannelTime not implemented
GLint uloc_iChannel[4];
GLint uloc_iMouse;
GLint uloc_iDate;
GLint uloc_iBlockOffset;
GLint uloc_iSampleRate;
GLuint texs[4];
};
struct Shadertoy {
renderpass image;
renderpass sound;
};
Shadertoy g_toy;
void keyboard(const SDL_Event& event, int key, int codes, int action, int mods)
{
(void)codes;
(void)mods;
if (action == SDL_KEYDOWN)
{
switch (key)
{
default:
break;
case SDLK_ESCAPE:
SDL_Quit();
exit(0);
break;
}
}
}
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
keyboard(event, event.key.keysym.sym, 0, event.key.type, 0);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
const renderpass& r = g_toy.image;
glUseProgram(r.prog);
if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds());
if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f);
SYSTEMTIME stNow;
GetLocalTime(&stNow);
if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate,
(float)stNow.wYear,
(float)stNow.wMonth - 1.f,
(float)stNow.wDay,
(float)stNow.wHour*60.f*60.f +
(float)stNow.wMinute*60.f +
(float)stNow.wSecond
);
for (int i=0; i<4; ++i)
{
glActiveTexture(GL_TEXTURE0+i);
glBindTexture(GL_TEXTURE_2D, r.texs[i]);
if (r.uloc_iChannel[i] > -1) glUniform1i(r.uloc_iChannel[i], i);
}
glRecti(-1,-1,1,1);
}
//
// Audio
//
struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
void SDLCALL fillerup(void *unused, Uint8 * stream, int len)
{
Uint8 *waveptr;
int waveleft;
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
while (waveleft <= len) { // wrap condition
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
void play_audio()
{
wave.spec.freq = 44100;
wave.spec.format = AUDIO_U8; //AUDIO_S16LSB;
wave.spec.channels = 2;
wave.spec.callback = fillerup;
const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio
wave.soundlen = mPlayTime * wave.spec.freq;
wave.sound = new Uint8[2*wave.soundlen];
glViewport(0,0,512,512);
const renderpass& r = g_toy.sound;
glUseProgram(r.prog);
unsigned char* mData = new unsigned char[512*512*4];
int mTmpBufferSamples = 512*512;
int mPlaySamples = wave.soundlen;
int numBlocks = mPlaySamples / mTmpBufferSamples;
for (int j=0; j<numBlocks; ++j)
{
int off = j * mTmpBufferSamples;
if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq);
glRecti(-1,-1,1,1);
// mData: Uint8Array[1048576]
glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData);
for (int i = 0; i<mTmpBufferSamples; ++i)
{
unsigned char Llo = mData[4*i+0];
unsigned char Lhi = mData[4*i+1];
unsigned char Rlo = mData[4*i+2];
unsigned char Rhi = mData[4*i+3];
const float aL = -1.0f + 2.0f*((float)Llo + 256.0f*(float)Lhi) / 65535.0f;
const float aR = -1.0f + 2.0f*((float)Rlo + 256.0f*(float)Rhi) / 65535.0f;
wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f);
wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f);
}
}
delete [] mData;
if (SDL_OpenAudio(&wave.spec, NULL) < 0)
{
SDL_FreeWAV(wave.sound);
SDL_Quit();
exit(2);
}
SDL_PauseAudio(0); // Start playing
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
renderpass& r = g_toy.image;
r.prog = makeShaderFromSource("passthru.vert", "image.frag");
r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution");
r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime");
r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution");
r.uloc_iChannel[0] = glGetUniformLocation(r.prog, "iChannel0");
r.uloc_iChannel[1] = glGetUniformLocation(r.prog, "iChannel1");
r.uloc_iChannel[2] = glGetUniformLocation(r.prog, "iChannel2");
r.uloc_iChannel[3] = glGetUniformLocation(r.prog, "iChannel3");
r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse");
r.uloc_iDate = glGetUniformLocation(r.prog, "iDate");
for (int i=0; i<4; ++i)
{
const int w = texdims[3*i];
const int h = texdims[3*i+1];
const int d = texdims[3*i+2];
if (w == 0)
continue;
GLuint t = 0;
glActiveTexture(GL_TEXTURE0+i);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
GLuint mode = 0;
switch (d)
{
default:break;
case 1: mode = GL_LUMINANCE; break;
case 3: mode = GL_RGB; break;
case 4: mode = GL_RGBA; break;
}
char texname[6] = "tex00";
texname[4] += i;
std::ifstream file(texname, std::ios::binary);
if (!file.is_open())
continue;
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D,
0, mode,
w, h,
0, mode,
GL_UNSIGNED_BYTE,
&buffer[0]);
r.texs[i] = t;
}
}
renderpass& s = g_toy.sound;
s.prog = makeShaderFromSource("passthru.vert", "sound.frag");
s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset");
s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate");
play_audio();
glViewport(0,0, winw, winh);
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
}
<commit_msg>Play a full 60 seconds of generated audio to match shadertoy.<commit_after>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include "ShaderFunctions.h"
#include "Timer.h"
#include "g_textures.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct renderpass {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
GLint uloc_iChannelResolution;
//iChannelTime not implemented
GLint uloc_iChannel[4];
GLint uloc_iMouse;
GLint uloc_iDate;
GLint uloc_iBlockOffset;
GLint uloc_iSampleRate;
GLuint texs[4];
};
struct Shadertoy {
renderpass image;
renderpass sound;
};
Shadertoy g_toy;
void keyboard(const SDL_Event& event, int key, int codes, int action, int mods)
{
(void)codes;
(void)mods;
if (action == SDL_KEYDOWN)
{
switch (key)
{
default:
break;
case SDLK_ESCAPE:
SDL_Quit();
exit(0);
break;
}
}
}
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
keyboard(event, event.key.keysym.sym, 0, event.key.type, 0);
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
const renderpass& r = g_toy.image;
glUseProgram(r.prog);
if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds());
if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f);
SYSTEMTIME stNow;
GetLocalTime(&stNow);
if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate,
(float)stNow.wYear,
(float)stNow.wMonth - 1.f,
(float)stNow.wDay,
(float)stNow.wHour*60.f*60.f +
(float)stNow.wMinute*60.f +
(float)stNow.wSecond
);
for (int i=0; i<4; ++i)
{
glActiveTexture(GL_TEXTURE0+i);
glBindTexture(GL_TEXTURE_2D, r.texs[i]);
if (r.uloc_iChannel[i] > -1) glUniform1i(r.uloc_iChannel[i], i);
}
glRecti(-1,-1,1,1);
}
//
// Audio
//
struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
void SDLCALL fillerup(void *unused, Uint8 * stream, int len)
{
Uint8 *waveptr;
int waveleft;
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
while (waveleft <= len) { // wrap condition
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
void play_audio()
{
wave.spec.freq = 44100;
wave.spec.format = AUDIO_U8; //AUDIO_S16LSB;
wave.spec.channels = 2;
wave.spec.callback = fillerup;
const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio
wave.soundlen = mPlayTime * wave.spec.freq * 2; // interlaced stereo
wave.sound = new Uint8[wave.soundlen];
glViewport(0,0,512,512);
const renderpass& r = g_toy.sound;
glUseProgram(r.prog);
unsigned char* mData = new unsigned char[512*512*4];
int mTmpBufferSamples = 512*512;
int mPlaySamples = wave.soundlen / 2;
int numBlocks = mPlaySamples / mTmpBufferSamples;
for (int j=0; j<numBlocks; ++j)
{
int off = j * mTmpBufferSamples;
if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq);
glRecti(-1,-1,1,1);
// mData: Uint8Array[1048576]
glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData);
for (int i = 0; i<mTmpBufferSamples; ++i)
{
unsigned char Llo = mData[4*i+0];
unsigned char Lhi = mData[4*i+1];
unsigned char Rlo = mData[4*i+2];
unsigned char Rhi = mData[4*i+3];
const float aL = -1.0f + 2.0f*((float)Llo + 256.0f*(float)Lhi) / 65535.0f;
const float aR = -1.0f + 2.0f*((float)Rlo + 256.0f*(float)Rhi) / 65535.0f;
wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f);
wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f);
}
}
delete [] mData;
if (SDL_OpenAudio(&wave.spec, NULL) < 0)
{
SDL_FreeWAV(wave.sound);
SDL_Quit();
exit(2);
}
SDL_PauseAudio(0); // Start playing
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
renderpass& r = g_toy.image;
r.prog = makeShaderFromSource("passthru.vert", "image.frag");
r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution");
r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime");
r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution");
r.uloc_iChannel[0] = glGetUniformLocation(r.prog, "iChannel0");
r.uloc_iChannel[1] = glGetUniformLocation(r.prog, "iChannel1");
r.uloc_iChannel[2] = glGetUniformLocation(r.prog, "iChannel2");
r.uloc_iChannel[3] = glGetUniformLocation(r.prog, "iChannel3");
r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse");
r.uloc_iDate = glGetUniformLocation(r.prog, "iDate");
for (int i=0; i<4; ++i)
{
const int w = texdims[3*i];
const int h = texdims[3*i+1];
const int d = texdims[3*i+2];
if (w == 0)
continue;
GLuint t = 0;
glActiveTexture(GL_TEXTURE0+i);
glGenTextures(1, &t);
glBindTexture(GL_TEXTURE_2D, t);
GLuint mode = 0;
switch (d)
{
default:break;
case 1: mode = GL_LUMINANCE; break;
case 3: mode = GL_RGB; break;
case 4: mode = GL_RGBA; break;
}
char texname[6] = "tex00";
texname[4] += i;
std::ifstream file(texname, std::ios::binary);
if (!file.is_open())
continue;
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D,
0, mode,
w, h,
0, mode,
GL_UNSIGNED_BYTE,
&buffer[0]);
r.texs[i] = t;
}
}
renderpass& s = g_toy.sound;
s.prog = makeShaderFromSource("passthru.vert", "sound.frag");
s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset");
s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate");
play_audio();
glViewport(0,0, winw, winh);
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_Quit();
}
<|endoftext|> |
<commit_before>/*
* Launch WAS child processes.
*
* author: Max Kellermann <[email protected]>
*/
#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "spawn/Interface.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <inline/compiler.h>
#include <sys/socket.h>
#include <unistd.h>
void
WasProcess::Close()
{
if (control_fd >= 0) {
close(control_fd);
control_fd = -1;
}
if (input_fd >= 0) {
close(input_fd);
input_fd = -1;
}
if (output_fd >= 0) {
close(output_fd);
output_fd = -1;
}
}
bool
was_launch(SpawnService &spawn_service,
WasProcess *process,
const char *name,
const char *executable_path,
ConstBuffer<const char *> args,
const ChildOptions &options,
ExitListener *listener,
GError **error_r)
{
int control_fds[2], input_fds[2], output_fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
set_error_errno_msg(error_r, "failed to create socket pair");
return false;
}
if (pipe_cloexec(input_fds) < 0) {
set_error_errno_msg(error_r, "failed to create first pipe");
close(control_fds[0]);
close(control_fds[1]);
return false;
}
if (pipe_cloexec(output_fds) < 0) {
set_error_errno_msg(error_r, "failed to create second pipe");
close(control_fds[0]);
close(control_fds[1]);
close(input_fds[0]);
close(input_fds[1]);
return false;
}
PreparedChildProcess p;
p.stdin_fd = output_fds[0];
p.stdout_fd = input_fds[1];
/* fd2 is retained */
p.control_fd = control_fds[1];
p.Append(executable_path);
for (auto i : args)
p.Append(i);
if (!options.CopyTo(p, true, nullptr, error_r)) {
close(control_fds[0]);
close(input_fds[0]);
close(output_fds[1]);
return false;
}
int pid = spawn_service.SpawnChildProcess(name, std::move(p), listener,
error_r);
if (pid < 0) {
close(control_fds[0]);
close(input_fds[0]);
close(output_fds[1]);
return false;
}
fd_set_nonblock(input_fds[0], true);
fd_set_nonblock(output_fds[1], true);
process->pid = pid;
process->control_fd = control_fds[0];
process->input_fd = input_fds[0];
process->output_fd = output_fds[1];
return true;
}
<commit_msg>was/launch: move PreparedChildProcess declaration up<commit_after>/*
* Launch WAS child processes.
*
* author: Max Kellermann <[email protected]>
*/
#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "spawn/Interface.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <inline/compiler.h>
#include <sys/socket.h>
#include <unistd.h>
void
WasProcess::Close()
{
if (control_fd >= 0) {
close(control_fd);
control_fd = -1;
}
if (input_fd >= 0) {
close(input_fd);
input_fd = -1;
}
if (output_fd >= 0) {
close(output_fd);
output_fd = -1;
}
}
bool
was_launch(SpawnService &spawn_service,
WasProcess *process,
const char *name,
const char *executable_path,
ConstBuffer<const char *> args,
const ChildOptions &options,
ExitListener *listener,
GError **error_r)
{
int control_fds[2], input_fds[2], output_fds[2];
PreparedChildProcess p;
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
set_error_errno_msg(error_r, "failed to create socket pair");
return false;
}
p.control_fd = control_fds[1];
if (pipe_cloexec(input_fds) < 0) {
set_error_errno_msg(error_r, "failed to create first pipe");
close(control_fds[0]);
return false;
}
p.stdout_fd = input_fds[1];
if (pipe_cloexec(output_fds) < 0) {
set_error_errno_msg(error_r, "failed to create second pipe");
close(control_fds[0]);
close(input_fds[0]);
return false;
}
p.stdin_fd = output_fds[0];
p.Append(executable_path);
for (auto i : args)
p.Append(i);
if (!options.CopyTo(p, true, nullptr, error_r)) {
close(control_fds[0]);
close(input_fds[0]);
close(output_fds[1]);
return false;
}
int pid = spawn_service.SpawnChildProcess(name, std::move(p), listener,
error_r);
if (pid < 0) {
close(control_fds[0]);
close(input_fds[0]);
close(output_fds[1]);
return false;
}
fd_set_nonblock(input_fds[0], true);
fd_set_nonblock(output_fds[1], true);
process->pid = pid;
process->control_fd = control_fds[0];
process->input_fd = input_fds[0];
process->output_fd = output_fds[1];
return true;
}
<|endoftext|> |
<commit_before>#include "bvs/bvs.h"
BVS::BVS* bvs;
BVS::Logger logger("Daemon");
int testLogger();
int testConfig();
/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
* This is a simple command line daemon. It serves as a client to the BVS
* framework. It is also intended as a sample client.
*
* It is interactive, you can use the following commands by just entering them
* on the command line and then pressing enter (short versions are also
* available, enter 'help<enter>' to see them):
*
* @li \c run run system until paused.
* @li \c continue same as run
* @li \c step advance system by one step.
* @li \c pause pause(stop) system.
* @li \c test call test functions.
* @li \c quit shutdown system and quit.
* @li \c help show help.
*/
class BVSD
{
};
}
/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
LOG(2, "starting!");
bvs = new BVS::BVS(argc, argv);
LOG(2, "loading modules!");
bvs->loadModules();
LOG(2, "connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
bvs->run();
std::string input;
while (input != "q" && input != "quit")
{
std::getline(std::cin, input);
if (input == "r" || input == "run" || input == "c" || input == "continue")
{
LOG(2, "RUN!!!");
bvs->run();
}
else if (input.empty() || input == "s" || input == "step")
{
LOG(2, "STEP!!!");
bvs->step();
}
else if (input == "p" || input == "pause")
{
LOG(2, "PAUSING!!!");
bvs->pause();
}
else if (input == "t" || input == "test")
{
testLogger();
testConfig();
}
else if (input == "q" || input == "quit")
{
LOG(2, "quitting...");
bvs->quit();
LOG(2, "finished!");
}
else if (input == "h" || input == "help")
{
std::cout << "usage:" << std::endl;
std::cout << " r|run run system until paused" << std::endl;
std::cout << " c|continue same as run" << std::endl;
std::cout << " s|step advance system by one step" << std::endl;
std::cout << " p|pause pause(stop) system" << std::endl;
std::cout << " t|test call test functions" << std::endl;
std::cout << " q|quit shutdown system and quit" << std::endl;
std::cout << " h|help show help" << std::endl;
}
}
delete bvs;
return 0;
}
/** Performs some logger tests.
* This functions performs some tests on the logger system. Nothing fancy, can
* be studied to gain some insight into using the logger system.
*/
int testLogger()
{
LOG(0, "to CLI FILE");
bvs->disableLogConsole();
LOG(0, "to FILE only");
BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
file.out(0) << "FILE ONLY" << std::endl;
bvs->enableLogConsole();
BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
cli.out(0) << "CLI ONLY" << std::endl;
bvs->disableLogConsole();
bvs->disableLogFile();
LOG(0, "NOOP");
bvs->enableLogConsole();
LOG(0, "to CLI");
bvs->disableLogConsole();
bvs->enableLogFile("BVSLog.txt", true);
LOG(0, "to FILE AGAIN");
bvs->enableLogConsole();
BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
both.out(0) << "to CLI AND FILE" << std::endl;
return 0;
}
/** Performs some config tests.
* This functions performs some tests on the config system. Nothing fancy, can
* be studied to gain some insight into using the config system.
*/
int testConfig()
{
LOG(0, "testing...");
int i;
std::string s;
bool b;
bvs->config.getValue("BVS.logVerbosity", i, 0)
.getValue("BVS.logFile", s, std::string("default"))
.getValue("BVS.logSystem", b, false);
LOG(0, "Getting int: " << i);
LOG(0, "Getting string: " << s);
LOG(0, "Getting bool: " << b);
i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
b = bvs->config.getValue<bool>("BVS.logSystem", false);
LOG(0, "Getting int directly: " << i);
LOG(0, "Getting string directly: " << s);
LOG(0, "Getting bool directly: " << b);
std::string empty;
bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
LOG(0, "This should be 'empty': " << empty);
std::vector<std::string> list;
bvs->config.getValue("BVS.modules", list);
LOG(0, "List: BVS.modules");
int count = 0;
for (auto& it : list)
{
(void) it;
(void) count;
LOG(0, count++ << ": " << it);
}
return 0;
}
<commit_msg>run: add hotswap call<commit_after>#include "bvs/bvs.h"
BVS::BVS* bvs;
BVS::Logger logger("Daemon");
int testLogger();
int testConfig();
/** BVSD namespace, contains only the bvs daemon. */
namespace BVSD
{
/** BVS framework's command line daemon.
* This is a simple command line daemon. It serves as a client to the BVS
* framework. It is also intended as a sample client.
*
* It is interactive, you can use the following commands by just entering them
* on the command line and then pressing enter (short versions are also
* available, enter 'help<enter>' to see them):
*
* @li \c run run system until paused.
* @li \c continue same as run
* @li \c step advance system by one step.
* @li \c pause pause(stop) system.
* @li \c test call test functions.
* @li \c quit shutdown system and quit.
* @li \c help show help.
*/
class BVSD
{
};
}
/** Main function, creates interactive loop. */
int main(int argc, char** argv)
{
LOG(2, "starting!");
bvs = new BVS::BVS(argc, argv);
LOG(2, "loading modules!");
bvs->loadModules();
LOG(2, "connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
//bvs->run();
std::string input;
while (input != "q" && input != "quit")
{
std::getline(std::cin, input);
if (input == "r" || input == "run" || input == "c" || input == "continue")
{
LOG(2, "RUN!!!");
bvs->run();
}
else if (input.empty() || input == "s" || input == "step")
{
LOG(2, "STEP!!!");
bvs->step();
}
else if (input == "p" || input == "pause")
{
LOG(2, "PAUSING!!!");
bvs->pause();
}
else if (input == "t" || input == "test")
{
testLogger();
testConfig();
}
else if (input.substr(0,2) == "hs" || input.substr(0, 7) == "hotswap")
{
size_t delimiter = input.find_first_of(" ");
input.erase(0, delimiter+1);
if (input.empty() || delimiter==std::string::npos) std::cout << "ERROR: no module ID given!" << std::endl;
else bvs->hotSwap(input);
}
else if (input == "q" || input == "quit")
{
LOG(2, "quitting...");
bvs->quit();
LOG(2, "finished!");
}
else if (input == "h" || input == "help")
{
std::cout << "usage:" << std::endl;
std::cout << " r|run run system until paused" << std::endl;
std::cout << " c|continue same as run" << std::endl;
std::cout << " s|step advance system by one step" << std::endl;
std::cout << " p|pause pause(stop) system" << std::endl;
std::cout << " hs|hotswap <arg> HotSwap(TM) <moduleID>" << std::endl;
std::cout << " t|test call test functions" << std::endl;
std::cout << " q|quit shutdown system and quit" << std::endl;
std::cout << " h|help show help" << std::endl;
}
}
delete bvs;
return 0;
}
/** Performs some logger tests.
* This functions performs some tests on the logger system. Nothing fancy, can
* be studied to gain some insight into using the logger system.
*/
int testLogger()
{
LOG(0, "to CLI FILE");
bvs->disableLogConsole();
LOG(0, "to FILE only");
BVS::Logger file("FILE LOG", 3, BVS::Logger::TO_FILE);
file.out(0) << "FILE ONLY" << std::endl;
bvs->enableLogConsole();
BVS::Logger cli("CLI LOG", 3, BVS::Logger::TO_CLI);
cli.out(0) << "CLI ONLY" << std::endl;
bvs->disableLogConsole();
bvs->disableLogFile();
LOG(0, "NOOP");
bvs->enableLogConsole();
LOG(0, "to CLI");
bvs->disableLogConsole();
bvs->enableLogFile("BVSLog.txt", true);
LOG(0, "to FILE AGAIN");
bvs->enableLogConsole();
BVS::Logger both("to BOTH", 0, BVS::Logger::TO_CLI_AND_FILE);
both.out(0) << "to CLI AND FILE" << std::endl;
return 0;
}
/** Performs some config tests.
* This functions performs some tests on the config system. Nothing fancy, can
* be studied to gain some insight into using the config system.
*/
int testConfig()
{
LOG(0, "testing...");
int i;
std::string s;
bool b;
bvs->config.getValue("BVS.logVerbosity", i, 0)
.getValue("BVS.logFile", s, std::string("default"))
.getValue("BVS.logSystem", b, false);
LOG(0, "Getting int: " << i);
LOG(0, "Getting string: " << s);
LOG(0, "Getting bool: " << b);
i = bvs->config.getValue<int>("BVS.logVerbosity", 0);
s = bvs->config.getValue<std::string>("BVS.logFile", std::string("default"));
b = bvs->config.getValue<bool>("BVS.logSystem", false);
LOG(0, "Getting int directly: " << i);
LOG(0, "Getting string directly: " << s);
LOG(0, "Getting bool directly: " << b);
std::string empty;
bvs->config.getValue("this.option.does.not.exist", empty, std::string("empty"));
LOG(0, "This should be 'empty': " << empty);
std::vector<std::string> list;
bvs->config.getValue("BVS.modules", list);
LOG(0, "List: BVS.modules");
int count = 0;
for (auto& it : list)
{
(void) it;
(void) count;
LOG(0, count++ << ": " << it);
}
return 0;
}
<|endoftext|> |
<commit_before>#ifdef WINDOWS
#include <windows.h>
#include <fstream>
#include "util/system.h"
namespace System{
bool isDirectory(const std::string & path){
return GetFileAttributes(path.c_str()) & FILE_ATTRIBUTE_DIRECTORY;
}
bool readableFile(const std::string & path){
return !isDirectory(path) && readable(path);
}
bool readable(const std::string & path){
std::ifstream stream(path.c_str());
bool ok = stream.good();
if (stream.is_open()){
stream.close();
}
return ok;
}
}
#endif
<commit_msg>directories are readable in windows<commit_after>#ifdef WINDOWS
#include <windows.h>
#include <fstream>
#include "util/system.h"
namespace System{
bool isDirectory(const std::string & path){
return GetFileAttributes(path.c_str()) & FILE_ATTRIBUTE_DIRECTORY;
}
bool readableFile(const std::string & path){
return !isDirectory(path) && readable(path);
}
bool readable(const std::string & path){
if (isDirectory(path)){
return true;
}
std::ifstream stream(path.c_str());
bool ok = stream.good();
if (stream.is_open()){
stream.close();
}
return ok;
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2014 The OpenMx 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.
*/
/***********************************************************
*
* omxFitFunction.cc
*
* Created: Timothy R. Brick Date: 2008-11-13 12:33:06
*
* FitFunction objects are a subclass of data matrix that evaluates
* itself anew at each iteration, so that any changes to
* free parameters can be incorporated into the update.
* // Question: Should FitFunction be a ``subtype'' of
* // omxAlgebra or a separate beast entirely?
*
**********************************************************/
#include "omxFitFunction.h"
#include "fitMultigroup.h"
typedef struct omxFitFunctionTableEntry omxFitFunctionTableEntry;
struct omxFitFunctionTableEntry {
char name[32];
void (*initFun)(omxFitFunction*);
void (*setVarGroup)(omxFitFunction*, FreeVarGroup *); // TODO ugh, just convert to C++
};
static void defaultSetFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
{
if (ff->freeVarGroup && ff->freeVarGroup != fvg) {
Rf_warning("%s: setFreeVarGroup called with different group (%d vs %d)",
ff->matrix->name, ff->freeVarGroup->id[0], fvg->id[0]);
}
ff->freeVarGroup = fvg;
}
static const omxFitFunctionTableEntry omxFitFunctionSymbolTable[] = {
{"MxFitFunctionAlgebra", &omxInitAlgebraFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionWLS", &omxInitWLSFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionRow", &omxInitRowFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionML", &omxInitMLFitFunction, defaultSetFreeVarGroup},
{"imxFitFunctionFIML", &omxInitFIMLFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionR", &omxInitRFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionMultigroup", &initFitMultigroup, mgSetFreeVarGroup},
};
void omxFreeFitFunctionArgs(omxFitFunction *off) {
if(off==NULL) return;
/* Completely destroy the fit function structures */
if(off->matrix != NULL) {
if (off->destructFun) off->destructFun(off);
off->matrix = NULL;
}
}
void omxFitFunctionCreateChildren(omxState *globalState)
{
if (Global->numThreads <= 1) return;
for(size_t j = 0; j < globalState->expectationList.size(); j++) {
if (!globalState->expectationList[j]->canDuplicate) return;
}
if (globalState->childList.size()) Rf_error("Children already created");
int numThreads = Global->numThreads;
globalState->childList.resize(numThreads);
for(int ii = 0; ii < numThreads; ii++) {
globalState->childList[ii] = new omxState;
omxInitState(globalState->childList[ii]);
omxDuplicateState(globalState->childList[ii], globalState);
}
}
void omxDuplicateFitMatrix(omxMatrix *tgt, const omxMatrix *src, omxState* newState) {
if(tgt == NULL || src == NULL) return;
omxFitFunction *ff = src->fitFunction;
if(ff == NULL) return;
omxFillMatrixFromMxFitFunction(tgt, ff->fitType, src->matrixNumber);
setFreeVarGroup(tgt->fitFunction, src->fitFunction->freeVarGroup);
tgt->fitFunction->rObj = ff->rObj;
omxCompleteFitFunction(tgt);
}
void omxFitFunctionCompute(omxFitFunction *off, int want, FitContext *fc)
{
if (!off->initialized) Rf_error("FitFunction not initialized");
off->computeFun(off, want, fc);
if (fc) fc->wanted |= want;
if (want & FF_COMPUTE_FIT) {
omxMarkClean(off->matrix);
}
}
void ComputeFit(omxMatrix *fitMat, int want, FitContext *fc)
{
bool doFit = want & FF_COMPUTE_FIT;
// R_CheckUserInterrupt(); add here? TODO
#pragma omp atomic
++Global->computeCount; // could avoid lock by keeping in FitContext
if (doFit) Global->checkpointPrefit(fc, fc->est, false);
omxFitFunction *ff = fitMat->fitFunction;
if (ff) {
omxFitFunctionCompute(ff, want, fc);
} else {
if (want != FF_COMPUTE_FIT) Rf_error("Only fit is available");
omxForceCompute(fitMat);
}
if (doFit) {
if (fitMat->rows != 1) {
if (strEQ(ff->fitType, "MxFitFunctionML") || strEQ(ff->fitType, "imxFitFunctionFIML")) {
// NOTE: Floating-point addition is not
// associative. If we compute this in parallel
// then we introduce non-determinancy.
double sum = 0;
for(int i = 0; i < fitMat->rows; i++) {
sum += log(omxVectorElement(fitMat, i));
}
fc->fit = sum * Global->llScale;
if (!Global->rowLikelihoodsWarning) {
Rf_warning("%s does not evaluate to a 1x1 matrix. Fixing model by adding "
"mxAlgebra(-2*sum(log(%s)), 'm2ll'), mxFitFunctionAlgebra('m2ll')",
fitMat->name, fitMat->name);
Global->rowLikelihoodsWarning = true;
}
} else {
omxRaiseErrorf("%s of type %s returned %d values instead of 1, not sure how to proceed",
fitMat->name, ff->fitType, fitMat->rows);
fc->fit = nan("unknown");
}
} else {
fc->fit = fitMat->data[0];
}
if (std::isfinite(fc->fit)) {
fc->resetIterationError();
}
Global->checkpointPostfit(fc);
}
}
void defaultAddOutput(omxFitFunction* oo, MxRList *out)
{}
void omxFillMatrixFromMxFitFunction(omxMatrix* om, const char *fitType, int matrixNumber)
{
omxFitFunction *obj = (omxFitFunction*) R_alloc(1, sizeof(omxFitFunction));
memset(obj, 0, sizeof(omxFitFunction));
/* Register FitFunction and Matrix with each other */
obj->matrix = om;
omxResizeMatrix(om, 1, 1); // FitFunction matrices MUST be 1x1.
om->fitFunction = obj;
om->hasMatrixNumber = TRUE;
om->matrixNumber = matrixNumber;
for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxFitFunctionSymbolTable); fx++) {
const omxFitFunctionTableEntry *entry = omxFitFunctionSymbolTable + fx;
if(strcmp(fitType, entry->name) == 0) {
obj->fitType = entry->name;
obj->initFun = entry->initFun;
// We need to set up the FreeVarGroup before calling initFun
// because older fit functions expect to know the number of
// free variables during initFun.
obj->setVarGroup = entry->setVarGroup; // ugh!
obj->addOutput = defaultAddOutput;
break;
}
}
if (obj->initFun == NULL) Rf_error("Fit function %s not implemented", fitType);
}
void omxCompleteFitFunction(omxMatrix *om)
{
omxFitFunction *obj = om->fitFunction;
if (obj->initialized) return;
SEXP rObj = obj->rObj;
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("expectation")));
if (LENGTH(slotValue) == 1) {
int expNumber = INTEGER(slotValue)[0];
if(expNumber != NA_INTEGER) {
obj->expectation = omxExpectationFromIndex(expNumber, om->currentState);
setFreeVarGroup(obj->expectation, obj->freeVarGroup);
omxCompleteExpectation(obj->expectation);
}
}
Rf_unprotect(1); /* slotValue */
obj->initFun(obj);
if(obj->computeFun == NULL) Rf_error("Failed to initialize fit function %s", obj->fitType);
obj->matrix->data[0] = NA_REAL;
omxMarkDirty(obj->matrix);
obj->initialized = TRUE;
}
void setFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
{
(*ff->setVarGroup)(ff, fvg);
}
void omxFitFunctionPrint(omxFitFunction* off, const char* d) {
mxLog("(FitFunction, type %s)", off->fitType);
omxPrintMatrix(off->matrix, d);
}
/* Helper functions */
omxMatrix* omxNewMatrixFromSlot(SEXP rObj, omxState* currentState, const char* slotName) {
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install(slotName)));
omxMatrix* newMatrix = omxMatrixLookupFromState1(slotValue, currentState);
Rf_unprotect(1);
return newMatrix;
}
<commit_msg>Reinstate R_CheckUserInterrupt<commit_after>/*
* Copyright 2007-2014 The OpenMx 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.
*/
/***********************************************************
*
* omxFitFunction.cc
*
* Created: Timothy R. Brick Date: 2008-11-13 12:33:06
*
* FitFunction objects are a subclass of data matrix that evaluates
* itself anew at each iteration, so that any changes to
* free parameters can be incorporated into the update.
* // Question: Should FitFunction be a ``subtype'' of
* // omxAlgebra or a separate beast entirely?
*
**********************************************************/
#include "omxFitFunction.h"
#include "fitMultigroup.h"
typedef struct omxFitFunctionTableEntry omxFitFunctionTableEntry;
struct omxFitFunctionTableEntry {
char name[32];
void (*initFun)(omxFitFunction*);
void (*setVarGroup)(omxFitFunction*, FreeVarGroup *); // TODO ugh, just convert to C++
};
static void defaultSetFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
{
if (ff->freeVarGroup && ff->freeVarGroup != fvg) {
Rf_warning("%s: setFreeVarGroup called with different group (%d vs %d)",
ff->matrix->name, ff->freeVarGroup->id[0], fvg->id[0]);
}
ff->freeVarGroup = fvg;
}
static const omxFitFunctionTableEntry omxFitFunctionSymbolTable[] = {
{"MxFitFunctionAlgebra", &omxInitAlgebraFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionWLS", &omxInitWLSFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionRow", &omxInitRowFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionML", &omxInitMLFitFunction, defaultSetFreeVarGroup},
{"imxFitFunctionFIML", &omxInitFIMLFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionR", &omxInitRFitFunction, defaultSetFreeVarGroup},
{"MxFitFunctionMultigroup", &initFitMultigroup, mgSetFreeVarGroup},
};
void omxFreeFitFunctionArgs(omxFitFunction *off) {
if(off==NULL) return;
/* Completely destroy the fit function structures */
if(off->matrix != NULL) {
if (off->destructFun) off->destructFun(off);
off->matrix = NULL;
}
}
void omxFitFunctionCreateChildren(omxState *globalState)
{
if (Global->numThreads <= 1) return;
for(size_t j = 0; j < globalState->expectationList.size(); j++) {
if (!globalState->expectationList[j]->canDuplicate) return;
}
if (globalState->childList.size()) Rf_error("Children already created");
int numThreads = Global->numThreads;
globalState->childList.resize(numThreads);
for(int ii = 0; ii < numThreads; ii++) {
globalState->childList[ii] = new omxState;
omxInitState(globalState->childList[ii]);
omxDuplicateState(globalState->childList[ii], globalState);
}
}
void omxDuplicateFitMatrix(omxMatrix *tgt, const omxMatrix *src, omxState* newState) {
if(tgt == NULL || src == NULL) return;
omxFitFunction *ff = src->fitFunction;
if(ff == NULL) return;
omxFillMatrixFromMxFitFunction(tgt, ff->fitType, src->matrixNumber);
setFreeVarGroup(tgt->fitFunction, src->fitFunction->freeVarGroup);
tgt->fitFunction->rObj = ff->rObj;
omxCompleteFitFunction(tgt);
}
void omxFitFunctionCompute(omxFitFunction *off, int want, FitContext *fc)
{
if (!off->initialized) Rf_error("FitFunction not initialized");
off->computeFun(off, want, fc);
if (fc) fc->wanted |= want;
if (want & FF_COMPUTE_FIT) {
omxMarkClean(off->matrix);
}
}
void ComputeFit(omxMatrix *fitMat, int want, FitContext *fc)
{
bool doFit = want & FF_COMPUTE_FIT;
R_CheckUserInterrupt();
#pragma omp atomic
++Global->computeCount; // could avoid lock by keeping in FitContext
if (doFit) Global->checkpointPrefit(fc, fc->est, false);
omxFitFunction *ff = fitMat->fitFunction;
if (ff) {
omxFitFunctionCompute(ff, want, fc);
} else {
if (want != FF_COMPUTE_FIT) Rf_error("Only fit is available");
omxForceCompute(fitMat);
}
if (doFit) {
if (fitMat->rows != 1) {
if (strEQ(ff->fitType, "MxFitFunctionML") || strEQ(ff->fitType, "imxFitFunctionFIML")) {
// NOTE: Floating-point addition is not
// associative. If we compute this in parallel
// then we introduce non-determinancy.
double sum = 0;
for(int i = 0; i < fitMat->rows; i++) {
sum += log(omxVectorElement(fitMat, i));
}
fc->fit = sum * Global->llScale;
if (!Global->rowLikelihoodsWarning) {
Rf_warning("%s does not evaluate to a 1x1 matrix. Fixing model by adding "
"mxAlgebra(-2*sum(log(%s)), 'm2ll'), mxFitFunctionAlgebra('m2ll')",
fitMat->name, fitMat->name);
Global->rowLikelihoodsWarning = true;
}
} else {
omxRaiseErrorf("%s of type %s returned %d values instead of 1, not sure how to proceed",
fitMat->name, ff->fitType, fitMat->rows);
fc->fit = nan("unknown");
}
} else {
fc->fit = fitMat->data[0];
}
if (std::isfinite(fc->fit)) {
fc->resetIterationError();
}
Global->checkpointPostfit(fc);
}
}
void defaultAddOutput(omxFitFunction* oo, MxRList *out)
{}
void omxFillMatrixFromMxFitFunction(omxMatrix* om, const char *fitType, int matrixNumber)
{
omxFitFunction *obj = (omxFitFunction*) R_alloc(1, sizeof(omxFitFunction));
memset(obj, 0, sizeof(omxFitFunction));
/* Register FitFunction and Matrix with each other */
obj->matrix = om;
omxResizeMatrix(om, 1, 1); // FitFunction matrices MUST be 1x1.
om->fitFunction = obj;
om->hasMatrixNumber = TRUE;
om->matrixNumber = matrixNumber;
for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxFitFunctionSymbolTable); fx++) {
const omxFitFunctionTableEntry *entry = omxFitFunctionSymbolTable + fx;
if(strcmp(fitType, entry->name) == 0) {
obj->fitType = entry->name;
obj->initFun = entry->initFun;
// We need to set up the FreeVarGroup before calling initFun
// because older fit functions expect to know the number of
// free variables during initFun.
obj->setVarGroup = entry->setVarGroup; // ugh!
obj->addOutput = defaultAddOutput;
break;
}
}
if (obj->initFun == NULL) Rf_error("Fit function %s not implemented", fitType);
}
void omxCompleteFitFunction(omxMatrix *om)
{
omxFitFunction *obj = om->fitFunction;
if (obj->initialized) return;
SEXP rObj = obj->rObj;
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("expectation")));
if (LENGTH(slotValue) == 1) {
int expNumber = INTEGER(slotValue)[0];
if(expNumber != NA_INTEGER) {
obj->expectation = omxExpectationFromIndex(expNumber, om->currentState);
setFreeVarGroup(obj->expectation, obj->freeVarGroup);
omxCompleteExpectation(obj->expectation);
}
}
Rf_unprotect(1); /* slotValue */
obj->initFun(obj);
if(obj->computeFun == NULL) Rf_error("Failed to initialize fit function %s", obj->fitType);
obj->matrix->data[0] = NA_REAL;
omxMarkDirty(obj->matrix);
obj->initialized = TRUE;
}
void setFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
{
(*ff->setVarGroup)(ff, fvg);
}
void omxFitFunctionPrint(omxFitFunction* off, const char* d) {
mxLog("(FitFunction, type %s)", off->fitType);
omxPrintMatrix(off->matrix, d);
}
/* Helper functions */
omxMatrix* omxNewMatrixFromSlot(SEXP rObj, omxState* currentState, const char* slotName) {
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install(slotName)));
omxMatrix* newMatrix = omxMatrixLookupFromState1(slotValue, currentState);
Rf_unprotect(1);
return newMatrix;
}
<|endoftext|> |
<commit_before>/**
* @author Mike Bogochow
* @version 2.4.0, Dec 8, 2015
*
* @file Bidder.cpp
*
* Bidder class implementation
*/
#include "Bidder.h"
#include "../lib_graphs/Graph.h"
#include "../lib_graphs/Subgraph.h"
#include "../lib_graphs/SpanningTree.h"
#include "../lib_graphs/Path.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"
#include "MBUtils.h"
#include <boost/lexical_cast.hpp>
#include <algorithm> // std::remove
#include <chrono>
#include <thread>
Bidder::Bidder(void)
{
g = nullptr;
rtc = 0;
roundNumber = 0;
roundUpdated = false;
winnerUpdated = false;
id = -1;
}
Bidder::~Bidder(void)
{
if (g != nullptr)
delete g;
}
bool
Bidder::OnNewMail(MOOSMSG_LIST &NewMail)
{
bool ret = AuctionMOOSApp::OnNewMail(NewMail);
MOOSMSG_LIST::reverse_iterator p;
for(p = NewMail.rbegin(); p != NewMail.rend(); p++)
{
CMOOSMsg &msg = *p;
std::string key = msg.GetKey();
if (key == MVAR_BID_TARGETS && g == nullptr) // ignore if already have g
{
// Parse the targets from the message
std::string sTargets = msg.GetString();
pathFromString(sTargets, targets);
// Add my position to the targets
targets.push_back(startPos);
size_t numTargets = targets.size();
dp.dprintf(LVL_MAX_VERB, "Parsed %lu targets from %s\n", numTargets,
sTargets.c_str());
// Connect edges between all targets and calculate weights
std::vector<Edge> edges;
std::vector<mbogo_weight_t> weights;
connectEdges(targets, edges, weights);
dp.dprintf(LVL_MAX_VERB, "Connected %lu edges\n", edges.size());
// Make a graph from the edges
g = new Graph(edges.data(), edges.size(), weights.data(), numTargets);
dp.dprintf(LVL_MAX_VERB, "Generated Graph:\n%s\n", g->toString().c_str());
// Intialize allocated and unallocated targets
allocated.reserve(numTargets);
unallocated.reserve(numTargets - 1);
allocated.push_back(numTargets - 1); // allocate my position
for (Vertex i = 0; i < numTargets - 1; i++)
unallocated.push_back(i);
}
else if (key == MVAR_BID_START)
{
size_t num = boost::lexical_cast<size_t>(msg.GetString());
if (num > roundNumber) // ignore duplicate messages
{
if (num != roundNumber + 1)
{
MOOSTrace("WARNING: received round number %i while on round %i",
num, roundNumber);
}
roundUpdated = true;
roundNumber = num;
dp.dprintf(LVL_MIN_VERB, "Got %s mail: %i\n", MVAR_BID_START.c_str(),
num);
}
}
else if (key == MVAR_BID_WINNER)
{
winnerUpdated = true;
winningBid = winningBidFromString(msg.GetString());
dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", MVAR_BID_WINNER.c_str(),
winningBid);
}
}
return ret;
}
bool
Bidder::Iterate(void)
{
bool ret = AuctionMOOSApp::Iterate();
if (g != nullptr)
{
if (winnerUpdated)
{ // Update info with new winner
if (winningBid.winner == id)
{ // I won so add winning target to my allocated targets
allocated.push_back(winningBid.target);
rtc += winningBid.bid;
}
unallocated.erase(
std::remove(unallocated.begin(), unallocated.end(),
winningBid.target), unallocated.end());
winnerUpdated = false;
}
dp.dprintf(LVL_MAX_VERB, "Number of unallocated targets remaining: %lu\n",
unallocated.size());
if (unallocated.size() > 0)
{
if (roundUpdated)
{ // Do round calculations for new round
performBiddingRound();
roundUpdated = false;
}
}
else
{ // All rounds complete so perform final calculation and post
assert(unallocated.size() == 0);
performFinalCalc();
// Exit pBidder
doNotify("EXITED_NORMALLY", "pBidder");
RequestQuit();
}
}
else
dp.dprintf(LVL_MAX_VERB, "Graph not initialized...\n");
return ret;
}
void
Bidder::performBiddingRound(void)
{
// Bidding round
Bid currentBid = std::make_pair(MAX_VERTEX, MAX_WEIGHT);
Graph *sub;
// Iterate through unallocated nodes to find bid
for (std::vector<Vertex>::iterator t = unallocated.begin();
t != unallocated.end(); t++)
{
Path *path;
SpanningTree *tree;
mbogo_weight_t cost;
mbogo_weight_t bid;
std::vector<Vertex> possibleAllocation;
possibleAllocation.reserve(allocated.size() + 1);
possibleAllocation = allocated;
dp.dprintf(LVL_BID, "Adding %s for possible allocation\n",
boost::lexical_cast<std::string>(*t).c_str());
possibleAllocation.push_back(*t);
// Catch simple cases for efficiency
if (possibleAllocation.size() == 1)
{
cost = bid = 0;
}
else if (possibleAllocation.size() == 2)
{
path = Path::fromPair(
std::make_pair(possibleAllocation.front(),
possibleAllocation.back()));
cost = path->getTotalCost(g->getGraph());
bid = cost - rtc;
delete path;
}
else
{
sub = g->getSubgraph(possibleAllocation);
dp.dprintf(LVL_BID, "Subgraph:\n%s\n", sub->toString().c_str());
tree = SpanningTree::fromGraph(sub->getGraph());
dp.dprintf(LVL_BID, "Spanning Tree:\n%s\n", tree->toString().c_str());
path = Path::fromTree(tree);
dp.dprintf(LVL_BID, "Path:\n%s\n", path->toString().c_str());
cost = path->getTotalCost(g->getGraph());
bid = cost - rtc;
delete path;
delete tree;
delete sub;
}
dp.dprintf(LVL_BID, "bid[%lu_%s]=%s (cost-rtc)=(%s-%s)\n", roundNumber,
boost::lexical_cast<std::string>(*t).c_str(),
boost::lexical_cast<std::string>(bid).c_str(),
boost::lexical_cast<std::string>(cost).c_str(),
boost::lexical_cast<std::string>(rtc).c_str()
);
if (currentBid.second > bid && bid >= 0)
currentBid = std::make_pair(*t, bid);
dp.dprintf(LVL_BID, "cur_bid=%s:%s\n",
boost::lexical_cast<std::string>(currentBid.first).c_str(),
boost::lexical_cast<std::string>(currentBid.second).c_str());
}
assert(currentBid.first != MAX_VERTEX
&& currentBid.second != MAX_WEIGHT);
// Send bid to MOOSDB
doNotify(getBidVar(id), bidToString(currentBid));
}
void
Bidder::performFinalCalc(void)
{
// Do final cost calculation and submit path
Subgraph *sub = Subgraph::fromGraph(g, allocated);
SpanningTree *tree = SpanningTree::fromGraph(sub->getGraph());
Path *path = Path::fromTree(tree);
Point *pathPoints = new Point[path->getLength()];
// Debug output
DebugLevel LVL_FINAL_PATH = LVL_MID_VERB;
if (dp.isValidLevel(LVL_FINAL_PATH)) // extra check to avoid extra work
{
dp.dprintf(LVL_FINAL_PATH, "Final allocated:\n");
int count = 0;
for (std::vector<Vertex>::iterator it = allocated.begin();
it != allocated.end(); it++)
{
dp.dprintf(LVL_FINAL_PATH, "\tallocated[%i]:%s\n", count++,
boost::lexical_cast<std::string>(*it).c_str());
}
dp.dprintf(LVL_FINAL_PATH, "Final path:\n%s\n", path->toString().c_str());
}
// Convert the path indices to those in the origin graph
path->convertPath(sub->getParentIndices());
dp.dprintf(LVL_FINAL_PATH, "Converted path:\n%s\n", path->toString().c_str());
// Get the coordinates of the vertices
path->getLocations(targets.data(), pathPoints);
dp.dprintf(LVL_MIN_VERB, "Final cost: %s\n",
boost::lexical_cast<std::string>(path->getTotalCost(g->getGraph())).c_str());
// Send the path to the MOOSDB
doNotify(getPathVar(id),
getPathVarVal(pathToString(pathPoints, path->getLength())));
delete sub;
delete tree;
delete path;
delete pathPoints;
}
bool
Bidder::OnStartUp(void)
{
bool ret;
// Read the DebugOutput configuration field
int debugLevel;
if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
debugLevel = LVL_OFF;
dp.setLevel((DebugLevel)debugLevel);
ret = AuctionMOOSApp::OnStartUp();
// Read the AgentID configuration field
if (ret && !m_MissionReader.GetConfigurationParam("AgentID", id))
ret = MissingRequiredParam("AgentID");
if (ret)
{
std::string tmp;
if (!m_MissionReader.GetConfigurationParam("START_POS", tmp))
ret = MissingRequiredParam("START_POS");
else
startPos = pointFromString(tmp);
if (ret)
RegisterVariables();
}
return ret;
}
bool
Bidder::OnConnectToServer(void)
{
bool ret = AuctionMOOSApp::OnConnectToServer();
RegisterVariables();
return ret;
}
void
Bidder::RegisterVariables(void)
{
m_Comms.Register(MVAR_BID_WINNER, 0);
m_Comms.Register(MVAR_BID_START, 0);
m_Comms.Register(MVAR_BID_TARGETS, 0);
}
<commit_msg>Adjustment so start position is not part of path<commit_after>/**
* @author Mike Bogochow
* @version 2.4.0, Dec 8, 2015
*
* @file Bidder.cpp
*
* Bidder class implementation
*/
#include "Bidder.h"
#include "../lib_graphs/Graph.h"
#include "../lib_graphs/Subgraph.h"
#include "../lib_graphs/SpanningTree.h"
#include "../lib_graphs/Path.h"
#include "../lib_auction/AuctionDefs.h"
#include "../lib_auction/DebugPrinter.h"
#include "MBUtils.h"
#include <boost/lexical_cast.hpp>
#include <algorithm> // std::remove
#include <chrono>
#include <thread>
Bidder::Bidder(void)
{
g = nullptr;
rtc = 0;
roundNumber = 0;
roundUpdated = false;
winnerUpdated = false;
id = -1;
}
Bidder::~Bidder(void)
{
if (g != nullptr)
delete g;
}
bool
Bidder::OnNewMail(MOOSMSG_LIST &NewMail)
{
bool ret = AuctionMOOSApp::OnNewMail(NewMail);
MOOSMSG_LIST::reverse_iterator p;
for(p = NewMail.rbegin(); p != NewMail.rend(); p++)
{
CMOOSMsg &msg = *p;
std::string key = msg.GetKey();
if (key == MVAR_BID_TARGETS && g == nullptr) // ignore if already have g
{
// Parse the targets from the message
std::string sTargets = msg.GetString();
pathFromString(sTargets, targets);
// Add my position to the targets
targets.push_back(startPos);
size_t numTargets = targets.size();
dp.dprintf(LVL_MAX_VERB, "Parsed %lu targets from %s\n", numTargets,
sTargets.c_str());
// Connect edges between all targets and calculate weights
std::vector<Edge> edges;
std::vector<mbogo_weight_t> weights;
connectEdges(targets, edges, weights);
dp.dprintf(LVL_MAX_VERB, "Connected %lu edges\n", edges.size());
// Make a graph from the edges
g = new Graph(edges.data(), edges.size(), weights.data(), numTargets);
dp.dprintf(LVL_MAX_VERB, "Generated Graph:\n%s\n", g->toString().c_str());
// Intialize allocated and unallocated targets
allocated.reserve(numTargets);
unallocated.reserve(numTargets - 1);
allocated.push_back(numTargets - 1); // allocate my position
for (Vertex i = 0; i < numTargets - 1; i++)
unallocated.push_back(i);
}
else if (key == MVAR_BID_START)
{
size_t num = boost::lexical_cast<size_t>(msg.GetString());
if (num > roundNumber) // ignore duplicate messages
{
if (num != roundNumber + 1)
{
MOOSTrace("WARNING: received round number %i while on round %i",
num, roundNumber);
}
roundUpdated = true;
roundNumber = num;
dp.dprintf(LVL_MIN_VERB, "Got %s mail: %i\n", MVAR_BID_START.c_str(),
num);
}
}
else if (key == MVAR_BID_WINNER)
{
winnerUpdated = true;
winningBid = winningBidFromString(msg.GetString());
dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", MVAR_BID_WINNER.c_str(),
winningBid);
}
}
return ret;
}
bool
Bidder::Iterate(void)
{
bool ret = AuctionMOOSApp::Iterate();
if (g != nullptr)
{
if (winnerUpdated)
{ // Update info with new winner
if (winningBid.winner == id)
{ // I won so add winning target to my allocated targets
allocated.push_back(winningBid.target);
rtc += winningBid.bid;
}
unallocated.erase(
std::remove(unallocated.begin(), unallocated.end(),
winningBid.target), unallocated.end());
winnerUpdated = false;
}
dp.dprintf(LVL_MAX_VERB, "Number of unallocated targets remaining: %lu\n",
unallocated.size());
if (unallocated.size() > 0)
{
if (roundUpdated)
{ // Do round calculations for new round
performBiddingRound();
roundUpdated = false;
}
}
else
{ // All rounds complete so perform final calculation and post
assert(unallocated.size() == 0);
performFinalCalc();
// Exit pBidder
doNotify("EXITED_NORMALLY", "pBidder");
RequestQuit();
}
}
else
dp.dprintf(LVL_MAX_VERB, "Graph not initialized...\n");
return ret;
}
void
Bidder::performBiddingRound(void)
{
// Bidding round
Bid currentBid = std::make_pair(MAX_VERTEX, MAX_WEIGHT);
Graph *sub;
// Iterate through unallocated nodes to find bid
for (std::vector<Vertex>::iterator t = unallocated.begin();
t != unallocated.end(); t++)
{
Path *path;
SpanningTree *tree;
mbogo_weight_t cost;
mbogo_weight_t bid;
std::vector<Vertex> possibleAllocation;
possibleAllocation.reserve(allocated.size() + 1);
possibleAllocation = allocated;
dp.dprintf(LVL_BID, "Adding %s for possible allocation\n",
boost::lexical_cast<std::string>(*t).c_str());
possibleAllocation.push_back(*t);
// Catch simple cases for efficiency
if (possibleAllocation.size() == 1)
{
cost = bid = 0;
}
else if (possibleAllocation.size() == 2)
{
path = Path::fromPair(
std::make_pair(possibleAllocation.front(),
possibleAllocation.back()));
cost = path->getTotalCost(g->getGraph());
bid = cost - rtc;
delete path;
}
else
{
sub = g->getSubgraph(possibleAllocation);
dp.dprintf(LVL_BID, "Subgraph:\n%s\n", sub->toString().c_str());
tree = SpanningTree::fromGraph(sub->getGraph());
dp.dprintf(LVL_BID, "Spanning Tree:\n%s\n", tree->toString().c_str());
path = Path::fromTree(tree);
dp.dprintf(LVL_BID, "Path:\n%s\n", path->toString().c_str());
cost = path->getTotalCost(g->getGraph());
bid = cost - rtc;
delete path;
delete tree;
delete sub;
}
dp.dprintf(LVL_BID, "bid[%lu_%s]=%s (cost-rtc)=(%s-%s)\n", roundNumber,
boost::lexical_cast<std::string>(*t).c_str(),
boost::lexical_cast<std::string>(bid).c_str(),
boost::lexical_cast<std::string>(cost).c_str(),
boost::lexical_cast<std::string>(rtc).c_str()
);
if (currentBid.second > bid && bid >= 0)
currentBid = std::make_pair(*t, bid);
dp.dprintf(LVL_BID, "cur_bid=%s:%s\n",
boost::lexical_cast<std::string>(currentBid.first).c_str(),
boost::lexical_cast<std::string>(currentBid.second).c_str());
}
assert(currentBid.first != MAX_VERTEX
&& currentBid.second != MAX_WEIGHT);
// Send bid to MOOSDB
doNotify(getBidVar(id), bidToString(currentBid));
}
void
Bidder::performFinalCalc(void)
{
// Do final cost calculation and submit path
Subgraph *sub = Subgraph::fromGraph(g, allocated);
SpanningTree *tree = SpanningTree::fromGraph(sub->getGraph());
Path *path = Path::fromTree(tree);
Point *pathPoints = new Point[path->getLength()];
// Debug output
DebugLevel LVL_FINAL_PATH = LVL_MID_VERB;
if (dp.isValidLevel(LVL_FINAL_PATH)) // extra check to avoid extra work
{
dp.dprintf(LVL_FINAL_PATH, "Final allocated:\n");
int count = 0;
for (std::vector<Vertex>::iterator it = allocated.begin();
it != allocated.end(); it++)
{
dp.dprintf(LVL_FINAL_PATH, "\tallocated[%i]:%s\n", count++,
boost::lexical_cast<std::string>(*it).c_str());
}
dp.dprintf(LVL_FINAL_PATH, "Final path:\n%s\n", path->toString().c_str());
}
// Convert the path indices to those in the origin graph
path->convertPath(sub->getParentIndices());
dp.dprintf(LVL_FINAL_PATH, "Converted path:\n%s\n", path->toString().c_str());
// Get the coordinates of the vertices
path->getLocations(targets.data(), pathPoints);
dp.dprintf(LVL_MIN_VERB, "Final cost: %s\n",
boost::lexical_cast<std::string>(path->getTotalCost(g->getGraph())).c_str());
// Send the path to the MOOSDB
doNotify(getPathVar(id),
getPathVarVal(pathToString(pathPoints + 1, path->getLength() - 1)));
delete sub;
delete tree;
delete path;
delete pathPoints;
}
bool
Bidder::OnStartUp(void)
{
bool ret;
// Read the DebugOutput configuration field
int debugLevel;
if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel))
debugLevel = LVL_OFF;
dp.setLevel((DebugLevel)debugLevel);
ret = AuctionMOOSApp::OnStartUp();
// Read the AgentID configuration field
if (ret && !m_MissionReader.GetConfigurationParam("AgentID", id))
ret = MissingRequiredParam("AgentID");
if (ret)
{
std::string tmp;
if (!m_MissionReader.GetConfigurationParam("START_POS", tmp))
ret = MissingRequiredParam("START_POS");
else
startPos = pointFromString(tmp);
if (ret)
RegisterVariables();
}
return ret;
}
bool
Bidder::OnConnectToServer(void)
{
bool ret = AuctionMOOSApp::OnConnectToServer();
RegisterVariables();
return ret;
}
void
Bidder::RegisterVariables(void)
{
m_Comms.Register(MVAR_BID_WINNER, 0);
m_Comms.Register(MVAR_BID_START, 0);
m_Comms.Register(MVAR_BID_TARGETS, 0);
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2017 by Contributors
* \file arg_binder.cc
* \brief Helper utility to match and bind arguments.
*/
#include <tvm/ir.h>
#include <tvm/ir_pass.h>
#include <tvm/runtime/device_api.h>
#include "./ir_util.h"
#include "./arg_binder.h"
#include "../arithmetic/compute_expr.h"
namespace tvm {
namespace ir {
void BinderAddAssert(Expr cond,
const std::string& arg_name,
std::vector<Stmt>* asserts) {
Expr scond = Simplify(cond);
if (is_zero(scond)) {
LOG(FATAL) << "Bind have an unmet assertion: "
<< cond << ", " << " on argument " << arg_name;
}
if (!is_one(scond)) {
std::ostringstream os;
os << "Argument " << arg_name << " has an unsatisfied constraint";
asserts->emplace_back(AssertStmt::make(scond, os.str(), Evaluate::make(0)));
}
}
bool ArgBinder::Bind_(const Expr& arg,
const Expr& value,
const std::string& arg_name,
bool with_lets) {
CHECK_EQ(arg.type(), value.type());
if (const Variable* v = arg.as<Variable>()) {
auto it = def_map_->find(v);
if (it == def_map_->end()) {
Var v_arg(arg.node_);
defs_.emplace_back(v_arg);
if (with_lets) {
(*def_map_)[v] = arg;
init_nest_.emplace_back(LetStmt::make(v_arg, value, Evaluate::make(0)));
} else {
(*def_map_)[v] = value;
}
return true;
} else {
BinderAddAssert(it->second == value, arg_name, &asserts_);
}
} else {
BinderAddAssert(arg == value, arg_name, &asserts_);
}
return false;
}
void ArgBinder::Bind(const Expr& arg,
const Expr& value,
const std::string& arg_name,
bool with_let) {
Bind_(arg, value, arg_name, with_let);
}
void ArgBinder::BindArray(const Array<Expr>& arg,
const Array<Expr>& value,
const std::string& arg_name) {
CHECK_EQ(arg.size(), value.size())
<< "Argument " << arg_name << " array size mismatch";
for (size_t i = 0; i < arg.size(); ++i) {
std::ostringstream os;
os << arg_name << "[" << i << "]";
this->Bind(arg[i], value[i], os.str());
}
}
void ArgBinder::BindBuffer(const Buffer& arg,
const Buffer& value,
const std::string& arg_name,
bool fuzzy_match) {
CHECK_EQ(arg->scope, value->scope)
<< "Argument " << arg_name
<< " Buffer bind scope mismatch";
CHECK_EQ(arg->dtype, value->dtype)
<< "Argument " << arg_name
<< " Buffer bind data type mismatch";
if (value->data_alignment % arg->data_alignment != 0) {
LOG(WARNING) << "Trying to bind buffer to another one with lower alignment requirement "
<< " required_alignment=" << arg->data_alignment
<< ", provided_alignment=" << value->data_alignment;
}
// bind pointer and offset.
if (is_zero(arg->elem_offset)) {
CHECK(is_zero(value->elem_offset))
<< "Trying to bind a Buffer with offset into one without offset";
}
this->Bind(arg->data, value->data, arg_name + ".data");
if (Bind_(arg->elem_offset, value->elem_offset, arg_name + ".elem_offset", false)) {
if (arg->offset_factor > 1) {
Expr offset = value->elem_offset;
Expr factor = make_const(offset.type(), arg->offset_factor);
Expr zero = make_zero(offset.type());
BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_);
}
}
if (arg->shape.size() < value->shape.size()) {
CHECK(fuzzy_match) << "Argument " << arg_name << " size mismatch";
size_t diff = value->shape.size() - arg->shape.size();
for (size_t i = 0; i < diff; ++i) {
CHECK(is_one(value->shape[i]))
<< "Argument " << arg_name << " shape mismatch"
<< arg->shape << " vs " << value->shape;
}
for (size_t i = 0; i < arg->shape.size(); ++i) {
std::ostringstream os;
os << arg_name << ".shape[" << i << "]";
this->Bind(arg->shape[i], value->shape[i + diff], os.str());
}
if (value->strides.size() != 0) {
CHECK_EQ(arg->strides.size(), arg->shape.size());
CHECK_EQ(value->strides.size(), value->shape.size());
for (size_t i = 0; i < arg->strides.size(); ++i) {
std::ostringstream os;
os << arg_name << ".strides[" << i << "]";
this->Bind(arg->strides[i], value->strides[i + diff], os.str());
}
}
} else {
this->BindArray(arg->shape, value->shape, arg_name + ".shape");
this->BindArray(arg->strides, value->strides, arg_name + ".strides");
}
}
inline Expr TVMArrayGet(Type t, Var arr, intrinsic::TVMStructFieldKind kind) {
return TVMStructGet(t, arr, 0, kind);
}
void ArgBinder::BindDLTensor(const Buffer& buffer,
const Expr& device_type,
const Expr& device_id,
const Var& handle,
const std::string& arg_name) {
const Type tvm_shape_type = TVMShapeIndexType();
const Type tvm_ndim_type = Int(32);
const Stmt nop = Evaluate::make(0);
// dimension checks
Expr v_ndim = TVMArrayGet(tvm_ndim_type, handle, intrinsic::kArrNDim);
Expr a_ndim = make_const(tvm_ndim_type,
static_cast<int64_t>(buffer->shape.size()));
std::ostringstream ndim_err_msg;
ndim_err_msg << arg_name
<< ".ndim is expected to equal "
<< buffer->shape.size();
asserts_.emplace_back(AssertStmt::make(a_ndim == v_ndim, ndim_err_msg.str(), nop));
// type checks
Type dtype = buffer->dtype;
std::ostringstream type_err_msg;
type_err_msg << arg_name << ".dtype is expected to be " << dtype;
Expr cond = (TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeCode) ==
UIntImm::make(UInt(8), dtype.code()) &&
TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeBits) ==
UIntImm::make(UInt(8), dtype.bits()) &&
TVMArrayGet(UInt(16), handle, intrinsic::kArrTypeLanes) ==
UIntImm::make(UInt(16), dtype.lanes()));
asserts_.emplace_back(AssertStmt::make(cond, type_err_msg.str(), nop));
// data field
if (Bind_(buffer->data, TVMArrayGet(Handle(), handle, intrinsic::kArrData),
arg_name + ".data", true)) {
Var vptr(buffer->data);
def_handle_dtype_.Set(vptr, make_const(buffer->dtype, 0));
// mark alignment of external bufs
init_nest_.emplace_back(AttrStmt::make(
vptr, ir::attr::storage_alignment,
IntImm::make(Int(32), buffer->data_alignment), nop));
}
Var v_shape(arg_name + ".shape", Handle());
def_handle_dtype_.Set(v_shape, make_const(tvm_shape_type, 0));
init_nest_.emplace_back(LetStmt::make(
v_shape, TVMArrayGet(Handle(), handle, intrinsic::kArrShape), nop));
for (size_t k = 0; k < buffer->shape.size(); ++k) {
std::ostringstream field_name;
field_name << v_shape->name_hint << '[' << k << ']';
Bind_(buffer->shape[k],
cast(buffer->shape[k].type(),
Load::make(tvm_shape_type, v_shape,
IntImm::make(Int(32), k), const_true(1))),
field_name.str(), true);
}
// strides field
Var v_strides(arg_name + ".strides", Handle());
def_handle_dtype_.Set(v_strides, make_const(tvm_shape_type, 0));
init_nest_.emplace_back(LetStmt::make(
v_strides, TVMArrayGet(Handle(), handle, intrinsic::kArrStrides),
nop));
Expr is_null = Call::make(
Bool(1), intrinsic::tvm_handle_is_null,
{v_strides}, Call::PureIntrinsic);
if (buffer->strides.size() == 0) {
// Assert the buffer is compact
Type stype = buffer->DefaultIndexType();
Expr expect_stride = make_const(stype, 1);
Array<Expr> conds;
for (size_t i = buffer->shape.size(); i != 0; --i) {
size_t k = i - 1;
Expr svalue = cast(
stype,
Load::make(tvm_shape_type, v_strides,
IntImm::make(Int(32), k), const_true(1)));
conds.push_back(expect_stride == svalue);
expect_stride = expect_stride * buffer->shape[k];
}
std::ostringstream stride_err_msg;
stride_err_msg << arg_name << ".strides:"
<< " expected to be compact array";
if (conds.size() != 0) {
Stmt check =
AssertStmt::make(arith::ComputeReduce<ir::And>(conds, Expr()),
stride_err_msg.str(), Evaluate::make(0));
check = IfThenElse::make(Not::make(is_null), check, Stmt());
init_nest_.emplace_back(Block::make(check, Evaluate::make(0)));
}
} else {
std::ostringstream stride_null_err_msg;
stride_null_err_msg << arg_name << ".strides: expected non-null strides.";
asserts_.emplace_back(AssertStmt::make(Not::make(is_null), stride_null_err_msg.str(), nop));
for (size_t k = 0; k < buffer->strides.size(); ++k) {
std::ostringstream field_name;
field_name << v_strides->name_hint << '[' << k << ']';
Bind_(buffer->strides[k],
cast(buffer->shape[k].type(),
Load::make(tvm_shape_type, v_strides,
IntImm::make(Int(32), k), const_true(1))),
field_name.str(), true);
}
}
// Byte_offset field.
int data_bytes = GetVectorBytes(buffer->dtype);
int64_t const_offset;
if (arith::GetConst(buffer->elem_offset, &const_offset)) {
Bind_(make_const(UInt(64), const_offset * data_bytes),
TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset),
arg_name + ".byte_offset", true);
} else {
if (Bind_(buffer->elem_offset,
cast(buffer->elem_offset.type(),
(TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset) /
make_const(UInt(64), data_bytes))),
arg_name + ".elem_offset", true)) {
if (buffer->offset_factor > 1) {
Expr offset = buffer->elem_offset;
Expr factor = make_const(offset.type(), buffer->offset_factor);
Expr zero = make_zero(offset.type());
BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_);
}
}
}
// device info.
Bind_(device_type,
TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceType),
arg_name + ".device_type", true);
Bind_(device_id,
TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceId),
arg_name + ".device_id", true);
}
} // namespace ir
} // namespace tvm
<commit_msg>Fix more type annotation (#1490)<commit_after>/*!
* Copyright (c) 2017 by Contributors
* \file arg_binder.cc
* \brief Helper utility to match and bind arguments.
*/
#include <tvm/ir.h>
#include <tvm/ir_pass.h>
#include <tvm/runtime/device_api.h>
#include "./ir_util.h"
#include "./arg_binder.h"
#include "../arithmetic/compute_expr.h"
namespace tvm {
namespace ir {
void BinderAddAssert(Expr cond,
const std::string& arg_name,
std::vector<Stmt>* asserts) {
Expr scond = Simplify(cond);
if (is_zero(scond)) {
LOG(FATAL) << "Bind have an unmet assertion: "
<< cond << ", " << " on argument " << arg_name;
}
if (!is_one(scond)) {
std::ostringstream os;
os << "Argument " << arg_name << " has an unsatisfied constraint";
asserts->emplace_back(AssertStmt::make(scond, os.str(), Evaluate::make(0)));
}
}
bool ArgBinder::Bind_(const Expr& arg,
const Expr& value,
const std::string& arg_name,
bool with_lets) {
CHECK_EQ(arg.type(), value.type());
if (const Variable* v = arg.as<Variable>()) {
auto it = def_map_->find(v);
if (it == def_map_->end()) {
Var v_arg(arg.node_);
defs_.emplace_back(v_arg);
if (with_lets) {
(*def_map_)[v] = arg;
init_nest_.emplace_back(LetStmt::make(v_arg, value, Evaluate::make(0)));
} else {
(*def_map_)[v] = value;
}
return true;
} else {
BinderAddAssert(it->second == value, arg_name, &asserts_);
}
} else {
BinderAddAssert(arg == value, arg_name, &asserts_);
}
return false;
}
void ArgBinder::Bind(const Expr& arg,
const Expr& value,
const std::string& arg_name,
bool with_let) {
Bind_(arg, value, arg_name, with_let);
}
void ArgBinder::BindArray(const Array<Expr>& arg,
const Array<Expr>& value,
const std::string& arg_name) {
CHECK_EQ(arg.size(), value.size())
<< "Argument " << arg_name << " array size mismatch";
for (size_t i = 0; i < arg.size(); ++i) {
std::ostringstream os;
os << arg_name << "[" << i << "]";
this->Bind(arg[i], value[i], os.str());
}
}
void ArgBinder::BindBuffer(const Buffer& arg,
const Buffer& value,
const std::string& arg_name,
bool fuzzy_match) {
CHECK_EQ(arg->scope, value->scope)
<< "Argument " << arg_name
<< " Buffer bind scope mismatch";
CHECK_EQ(arg->dtype, value->dtype)
<< "Argument " << arg_name
<< " Buffer bind data type mismatch";
if (value->data_alignment % arg->data_alignment != 0) {
LOG(WARNING) << "Trying to bind buffer to another one with lower alignment requirement "
<< " required_alignment=" << arg->data_alignment
<< ", provided_alignment=" << value->data_alignment;
}
// bind pointer and offset.
if (is_zero(arg->elem_offset)) {
CHECK(is_zero(value->elem_offset))
<< "Trying to bind a Buffer with offset into one without offset";
}
this->Bind(arg->data, value->data, arg_name + ".data");
if (Bind_(arg->elem_offset, value->elem_offset, arg_name + ".elem_offset", false)) {
if (arg->offset_factor > 1) {
Expr offset = value->elem_offset;
Expr factor = make_const(offset.type(), arg->offset_factor);
Expr zero = make_zero(offset.type());
BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_);
}
}
if (arg->shape.size() < value->shape.size()) {
CHECK(fuzzy_match) << "Argument " << arg_name << " size mismatch";
size_t diff = value->shape.size() - arg->shape.size();
for (size_t i = 0; i < diff; ++i) {
CHECK(is_one(value->shape[i]))
<< "Argument " << arg_name << " shape mismatch"
<< arg->shape << " vs " << value->shape;
}
for (size_t i = 0; i < arg->shape.size(); ++i) {
std::ostringstream os;
os << arg_name << ".shape[" << i << "]";
this->Bind(arg->shape[i], value->shape[i + diff], os.str());
}
if (value->strides.size() != 0) {
CHECK_EQ(arg->strides.size(), arg->shape.size());
CHECK_EQ(value->strides.size(), value->shape.size());
for (size_t i = 0; i < arg->strides.size(); ++i) {
std::ostringstream os;
os << arg_name << ".strides[" << i << "]";
this->Bind(arg->strides[i], value->strides[i + diff], os.str());
}
}
} else {
this->BindArray(arg->shape, value->shape, arg_name + ".shape");
this->BindArray(arg->strides, value->strides, arg_name + ".strides");
}
}
inline Expr TVMArrayGet(Type t, Var arr, intrinsic::TVMStructFieldKind kind) {
return TVMStructGet(t, arr, 0, kind);
}
void ArgBinder::BindDLTensor(const Buffer& buffer,
const Expr& device_type,
const Expr& device_id,
const Var& handle,
const std::string& arg_name) {
const Type tvm_shape_type = TVMShapeIndexType();
const Type tvm_ndim_type = Int(32);
const Stmt nop = Evaluate::make(0);
// dimension checks
Expr v_ndim = TVMArrayGet(tvm_ndim_type, handle, intrinsic::kArrNDim);
Expr a_ndim = make_const(tvm_ndim_type,
static_cast<int64_t>(buffer->shape.size()));
std::ostringstream ndim_err_msg;
ndim_err_msg << arg_name
<< ".ndim is expected to equal "
<< buffer->shape.size();
asserts_.emplace_back(AssertStmt::make(a_ndim == v_ndim, ndim_err_msg.str(), nop));
// type checks
Type dtype = buffer->dtype;
std::ostringstream type_err_msg;
type_err_msg << arg_name << ".dtype is expected to be " << dtype;
Expr cond = (TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeCode) ==
UIntImm::make(UInt(8), dtype.code()) &&
TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeBits) ==
UIntImm::make(UInt(8), dtype.bits()) &&
TVMArrayGet(UInt(16), handle, intrinsic::kArrTypeLanes) ==
UIntImm::make(UInt(16), dtype.lanes()));
asserts_.emplace_back(AssertStmt::make(cond, type_err_msg.str(), nop));
// data field
if (Bind_(buffer->data, TVMArrayGet(Handle(), handle, intrinsic::kArrData),
arg_name + ".data", true)) {
Var vptr(buffer->data);
def_handle_dtype_.Set(vptr, ir::TypeAnnotation(buffer->dtype));
// mark alignment of external bufs
init_nest_.emplace_back(AttrStmt::make(
vptr, ir::attr::storage_alignment,
IntImm::make(Int(32), buffer->data_alignment), nop));
}
Var v_shape(arg_name + ".shape", Handle());
def_handle_dtype_.Set(v_shape, make_const(tvm_shape_type, 0));
init_nest_.emplace_back(LetStmt::make(
v_shape, TVMArrayGet(Handle(), handle, intrinsic::kArrShape), nop));
for (size_t k = 0; k < buffer->shape.size(); ++k) {
std::ostringstream field_name;
field_name << v_shape->name_hint << '[' << k << ']';
Bind_(buffer->shape[k],
cast(buffer->shape[k].type(),
Load::make(tvm_shape_type, v_shape,
IntImm::make(Int(32), k), const_true(1))),
field_name.str(), true);
}
// strides field
Var v_strides(arg_name + ".strides", Handle());
def_handle_dtype_.Set(v_strides, ir::TypeAnnotation(tvm_shape_type));
init_nest_.emplace_back(LetStmt::make(
v_strides, TVMArrayGet(Handle(), handle, intrinsic::kArrStrides),
nop));
Expr is_null = Call::make(
Bool(1), intrinsic::tvm_handle_is_null,
{v_strides}, Call::PureIntrinsic);
if (buffer->strides.size() == 0) {
// Assert the buffer is compact
Type stype = buffer->DefaultIndexType();
Expr expect_stride = make_const(stype, 1);
Array<Expr> conds;
for (size_t i = buffer->shape.size(); i != 0; --i) {
size_t k = i - 1;
Expr svalue = cast(
stype,
Load::make(tvm_shape_type, v_strides,
IntImm::make(Int(32), k), const_true(1)));
conds.push_back(expect_stride == svalue);
expect_stride = expect_stride * buffer->shape[k];
}
std::ostringstream stride_err_msg;
stride_err_msg << arg_name << ".strides:"
<< " expected to be compact array";
if (conds.size() != 0) {
Stmt check =
AssertStmt::make(arith::ComputeReduce<ir::And>(conds, Expr()),
stride_err_msg.str(), Evaluate::make(0));
check = IfThenElse::make(Not::make(is_null), check, Stmt());
init_nest_.emplace_back(Block::make(check, Evaluate::make(0)));
}
} else {
std::ostringstream stride_null_err_msg;
stride_null_err_msg << arg_name << ".strides: expected non-null strides.";
asserts_.emplace_back(AssertStmt::make(Not::make(is_null), stride_null_err_msg.str(), nop));
for (size_t k = 0; k < buffer->strides.size(); ++k) {
std::ostringstream field_name;
field_name << v_strides->name_hint << '[' << k << ']';
Bind_(buffer->strides[k],
cast(buffer->shape[k].type(),
Load::make(tvm_shape_type, v_strides,
IntImm::make(Int(32), k), const_true(1))),
field_name.str(), true);
}
}
// Byte_offset field.
int data_bytes = GetVectorBytes(buffer->dtype);
int64_t const_offset;
if (arith::GetConst(buffer->elem_offset, &const_offset)) {
Bind_(make_const(UInt(64), const_offset * data_bytes),
TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset),
arg_name + ".byte_offset", true);
} else {
if (Bind_(buffer->elem_offset,
cast(buffer->elem_offset.type(),
(TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset) /
make_const(UInt(64), data_bytes))),
arg_name + ".elem_offset", true)) {
if (buffer->offset_factor > 1) {
Expr offset = buffer->elem_offset;
Expr factor = make_const(offset.type(), buffer->offset_factor);
Expr zero = make_zero(offset.type());
BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_);
}
}
}
// device info.
Bind_(device_type,
TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceType),
arg_name + ".device_type", true);
Bind_(device_id,
TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceId),
arg_name + ".device_id", true);
}
} // namespace ir
} // namespace tvm
<|endoftext|> |
<commit_before>#include "Logbook.h"
#define LOGBOOK_FILE_NAME "LOGBOOK.TXT"
const String NEW_LINE = "\n";
Logbook::Logbook() {
}
//////////////////////
// Public interface //
//////////////////////
LogbookData* Logbook::loadLogbookData()
{
LogbookData* logbookData = new LogbookData;
if (SD.exists(LOGBOOK_FILE_NAME)) {
SdFile logbookFile;
if (logbookFile.open(LOGBOOK_FILE_NAME, O_READ)) {
String line;
int counter = 0;
while (logbookFile.available()) {
line = readStringUntil(&logbookFile, '\n');
if (counter == 4) {
logbookData->totalNumberOfDives = readIntFromLineEnd(line);
} else if (counter == 5) {
logbookData->totalDiveHours = readIntFromLineEnd(line);
} else if (counter == 6) {
logbookData->totalDiveMinutes = readIntFromLineEnd(line);
} else if (counter == 7) {
logbookData->totalMaximumDepth = readFloatFromLineEnd(line);
} else if (counter == 8) {
logbookData->lastDiveDateTime = readStringFromLineEnd(line);
}
counter++;
}
// The first 4 lines were skipped - this is the Summary section
logbookData->numberOfStoredProfiles = counter - 14;
logbookFile.close();
}
} else {
//Create a new Logbook file, if it is not on the SD card with default values
updateLogbookData(logbookData);
}
return logbookData;
}
void Logbook::updateLogbookData(LogbookData* logbookData)
{
SD.remove(LOGBOOK_FILE_NAME);
SdFile logbookFile;
if (logbookFile.open(LOGBOOK_FILE_NAME, O_WRITE | O_CREAT | O_APPEND )) {
logbookFile.print(F("************\n"));
logbookFile.print(F("* Summary: *\n"));
logbookFile.print(F("************\n"));
logbookFile.print(NEW_LINE);
logbookFile.print(F("Number of dives = "));
logbookFile.print(logbookData->totalNumberOfDives);
logbookFile.print(NEW_LINE);
logbookFile.print(F("Logged dive hours = "));
logbookFile.print(logbookData->totalDiveHours);
logbookFile.print(NEW_LINE);
logbookFile.print(F("Logged dive minutes = "));
logbookFile.print(logbookData->totalDiveMinutes);
logbookFile.print(NEW_LINE);
logbookFile.print(F("Maximum depth (meter) = "));
logbookFile.print(logbookData->totalMaximumDepth, 1);
logbookFile.print(NEW_LINE);
logbookFile.print(F("Last dive = "));
logbookFile.print(logbookData->lastDiveDateTime);
logbookFile.print(NEW_LINE);
logbookFile.print(NEW_LINE);
logbookFile.flush();
logbookFile.print(F("**********\n"));
logbookFile.print(F("* Dives: *\n"));
logbookFile.print(F("**********\n"));
logbookFile.print(NEW_LINE);
logbookFile.flush();
for (int i=1; i<=logbookData->numberOfStoredProfiles; i++) {
logbookFile.print(getFileNameFromProfileNumber(i, false));
logbookFile.print(NEW_LINE);
}
logbookFile.flush();
logbookFile.close();
}
}
String Logbook::getFileNameFromProfileNumber(int profileNumber, bool isTemp)
{
//Create the name of the new profile file
String fileName = "";
if (isTemp) {
fileName += "Temp";
} else {
fileName += "Dive";
}
if (profileNumber < 10) {
fileName += "000";
} else if (profileNumber < 100) {
fileName += "00";
} else if (profileNumber < 1000) {
fileName += "0";
}
fileName += profileNumber;
fileName += ".json";
return fileName;
}
/**
* The value true is returned for success and the value false is returned for failure.
*/
bool Logbook::createNewProfileFile(int profileNumber)
{
//The String has to be converted into a char array, otherwise the board will reset itself
String tempProfileFileName = getFileNameFromProfileNumber(profileNumber, true);
char tempProfileFileNameArray[tempProfileFileName.length()+1];
tempProfileFileName.toCharArray(tempProfileFileNameArray, tempProfileFileName.length()+1);
return profileFile.open(tempProfileFileNameArray, O_WRITE | O_CREAT | O_APPEND );
}
void Logbook::storeProfileItem(float pressure, float depth, float temperature, int duration)
{
StaticJsonBuffer<JSON_OBJECT_SIZE(4)> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root.set("depth", depth);
root.set("pressure", pressure, 5);
root.set("duration", duration);
root.set("temperature", temperature);
root.printTo(profileFile);
profileFile.flush();
profileFile.print(F("\n"));
profileFile.flush();
if (!profileFile.sync() || profileFile.getWriteError()) {
error("SD card write error during dive profile save!");
}
}
void Logbook::storeDiveSummary(int profileNumber, unsigned int duration, float maxDepth, float minTemperature, float oxigenPercentage, String date, String time)
{
profileFile.close();
//The String has to be converted into a char array, otherwise the board will reset itself
String tempProfileFileName = getFileNameFromProfileNumber(profileNumber, true);
char tempProfileFileNameArray[tempProfileFileName.length()+1];
tempProfileFileName.toCharArray(tempProfileFileNameArray, tempProfileFileName.length()+1);
String finalProfileFileName = getFileNameFromProfileNumber(profileNumber, false);
char finalProfileFileNameArray[finalProfileFileName.length()+1];
finalProfileFileName.toCharArray(finalProfileFileNameArray, finalProfileFileName.length()+1);
File finalFile;
SdFile tempProfileFile;
if (finalFile.open(finalProfileFileNameArray, O_WRITE | O_CREAT | O_APPEND ) &&
tempProfileFile.open(tempProfileFileNameArray, O_READ )) {
finalFile.print(F("{ \"summary\":\n"));
finalFile.flush();
StaticJsonBuffer<JSON_OBJECT_SIZE(6)> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root.set("diveDuration", duration);
root.set("maxDepth", maxDepth);
root.set("minTemperature", minTemperature);
root.set("oxigenPercentage", oxigenPercentage);
root.set("diveDate", date.c_str());
root.set("diveTime", time.c_str());
root.printTo(finalFile);
finalFile.flush();
finalFile.print(F(",\n"));
finalFile.print(F("\"profile\": [\n"));
finalFile.flush();
bool isFirstline = true;
String line;
while (tempProfileFile.available()) {
if (isFirstline) {
isFirstline = false;
} else {
finalFile.print(",\n");
finalFile.flush();
}
line = readStringUntil(&tempProfileFile, '\n');
finalFile.print(line);
finalFile.flush();
}
finalFile.print(F("\n]\n}\n"));
finalFile.flush();
tempProfileFile.close();
finalFile.close();
//Remove the temporary dive profile file
if (SD.exists(tempProfileFileNameArray)) {
SD.remove(tempProfileFileNameArray);
}
}
}
ProfileData* Logbook::loadProfileDataFromFile(String profileFileName)
{
ProfileData* profileData = new ProfileData;
//The String has to be converted into a char array, otherwise the board will reset itself
char fileName[profileFileName.length()+1];
profileFileName.toCharArray(fileName, profileFileName.length()+1);
SdFile profileFile;
if (profileFile.open(fileName, O_READ)) {
Serial.print(F("Exists: "));
Serial.println(fileName);
String line;
int counter = 0;
while (profileFile.available()) {
line = readStringUntil(&profileFile, '\n');
line.trim();
if (counter == 4) {
profileData->diveDuration = readIntFromLineEnd(line);
} else if (counter == 5) {
profileData->maximumDepth = readFloatFromLineEnd(line);
} else if (counter == 6) {
profileData->minimumTemperature = readFloatFromLineEnd(line);
} else if (counter == 7) {
profileData->oxigenPercentage = readFloatFromLineEnd(line);
} else if (counter == 8) {
profileData->diveDate = readStringFromLineEnd(line);
} else if (counter == 9) {
profileData->diveTime = readStringFromLineEnd(line);
}
counter ++;
}
profileData->numberOfProfileItems = counter - 24;
profileFile.close();
}
return profileData;
}
void Logbook::drawProfileItems(UTFT* tft, int profileNumber, int pageNumber)
{
String profileFileName = getFileNameFromProfileNumber(profileNumber, false);
ProfileData* profileData = loadProfileDataFromFile(profileFileName);
//The String has to be converted into a char array, otherwise the board will reset itself
char fileName[profileFileName.length()+1];
profileFileName.toCharArray(fileName, profileFileName.length()+1);
if (SD.exists(fileName)) {
File profileFile = SD.open(fileName);
if (profileFile) {
//Skip the Summary section
profileFile.seek(40);
int firstLineNumberOnPage = 24 + ((pageNumber-1) * 460);
int lastLineNumberOnPage = 24 + (pageNumber * 460);
float heightUnit = 150/profileData->maximumDepth;
tft->setColor(VGA_BLACK);
tft->fillRect(10,160,470,315);
tft->setColor(VGA_FUCHSIA);
String line;
int counter = 0;
int positionOnPage = 0;
while (profileFile.available()) {
line = profileFile.readStringUntil('\n');
if (firstLineNumberOnPage < counter && counter <= lastLineNumberOnPage) {
tft->drawLine(10+positionOnPage, 160 + heightUnit*getDepthFromProfileLine(line), 10+positionOnPage, 310);
positionOnPage++;
}
counter ++;
}
profileFile.close();
}
}
}
/////////////////////
// Private methods //
/////////////////////
float Logbook::getDepthFromProfileLine(String line)
{
return line.substring(line.indexOf(',')+1).substring(0, line.indexOf(',')).toFloat();
}
int Logbook::readIntFromLineEnd(String line) {
return line.substring(line.indexOf('=')+1).toInt();
}
float Logbook::readFloatFromLineEnd(String line) {
return line.substring(line.indexOf('=')+1).toFloat();
}
String Logbook::readStringFromLineEnd(String line) {
return line.substring(line.indexOf('=')+2);
}
String Logbook::readStringUntil(SdFile* file, char terminator)
{
String ret;
int c = file->read();
while (c >= 0 && c != terminator)
{
ret += (char)c;
c = file->read();
}
return ret;
}
<commit_msg>Logbook file handling was done in a json file.<commit_after>#include "Logbook.h"
#define LOGBOOK_FILE_NAME "Logbook.json"
const String NEW_LINE = "\n";
Logbook::Logbook() {
}
//////////////////////
// Public interface //
//////////////////////
LogbookData* Logbook::loadLogbookData()
{
LogbookData* logbookData = new LogbookData;
if (SD.exists(LOGBOOK_FILE_NAME)) {
SdFile logbookFile;
if (logbookFile.open(LOGBOOK_FILE_NAME, O_READ)) {
char fileContent[logbookFile.fileSize()];
int counter = 0;
while (logbookFile.available()) {
fileContent[counter] = logbookFile.read();
counter++;
}
logbookFile.close();
StaticJsonBuffer<JSON_OBJECT_SIZE(8)+JSON_ARRAY_SIZE(16)> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(fileContent);
logbookData->totalNumberOfDives = root["numberOfDives"];
logbookData->totalDiveHours = root["loggedDiveHours"];
logbookData->totalDiveMinutes = root["loggedDiveMinutes"];
logbookData->totalMaximumDepth = root["maxDepth"];
logbookData->lastDiveDateTime = root["lastDiveDate"].as<String>() + " " + root["lastDiveTime"].as<String>();
logbookData->numberOfStoredProfiles = root["numberOfStoredProfiles"];
}
} else {
//Create a new Logbook file, if it is not on the SD card with default values
updateLogbookData(logbookData);
}
return logbookData;
}
void Logbook::updateLogbookData(LogbookData* logbookData)
{
SD.remove(LOGBOOK_FILE_NAME);
SdFile logbookFile;
if (logbookFile.open(LOGBOOK_FILE_NAME, O_WRITE | O_CREAT | O_APPEND )) {
StaticJsonBuffer<JSON_OBJECT_SIZE(7)> jsonBuffer;
String lastDiveDate = "";
String lastDiveTime = "";
if (NULL != logbookData->lastDiveDateTime && logbookData->lastDiveDateTime.length() > 12) {
lastDiveDate = logbookData->lastDiveDateTime.substring(0, 10);
lastDiveTime = logbookData->lastDiveDateTime.substring(11);
}
JsonObject& root = jsonBuffer.createObject();
root.set("numberOfDives", logbookData->totalNumberOfDives);
root.set("loggedDiveHours", logbookData->totalDiveHours);
root.set("loggedDiveMinutes", logbookData->totalDiveMinutes);
root.set("maxDepth", logbookData->totalMaximumDepth);
root.set("lastDiveDate", lastDiveDate);
root.set("lastDiveTime", lastDiveTime);
root.set("numberOfStoredProfiles", logbookData->numberOfStoredProfiles);
root.prettyPrintTo(logbookFile);
logbookFile.flush();
logbookFile.close();
}
}
String Logbook::getFileNameFromProfileNumber(int profileNumber, bool isTemp)
{
//Create the name of the new profile file
String fileName = "";
if (isTemp) {
fileName += "Temp";
} else {
fileName += "Dive";
}
if (profileNumber < 10) {
fileName += "000";
} else if (profileNumber < 100) {
fileName += "00";
} else if (profileNumber < 1000) {
fileName += "0";
}
fileName += profileNumber;
fileName += ".json";
return fileName;
}
/**
* The value true is returned for success and the value false is returned for failure.
*/
bool Logbook::createNewProfileFile(int profileNumber)
{
//The String has to be converted into a char array, otherwise the board will reset itself
String tempProfileFileName = getFileNameFromProfileNumber(profileNumber, true);
char tempProfileFileNameArray[tempProfileFileName.length()+1];
tempProfileFileName.toCharArray(tempProfileFileNameArray, tempProfileFileName.length()+1);
return profileFile.open(tempProfileFileNameArray, O_WRITE | O_CREAT | O_APPEND );
}
void Logbook::storeProfileItem(float pressure, float depth, float temperature, int duration)
{
StaticJsonBuffer<JSON_OBJECT_SIZE(4)> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root.set("depth", depth);
root.set("pressure", pressure, 5);
root.set("duration", duration);
root.set("temperature", temperature);
root.printTo(profileFile);
profileFile.flush();
profileFile.print(F("\n"));
profileFile.flush();
if (!profileFile.sync() || profileFile.getWriteError()) {
error("SD card write error during dive profile save!");
}
}
void Logbook::storeDiveSummary(int profileNumber, unsigned int duration, float maxDepth, float minTemperature, float oxigenPercentage, String date, String time)
{
profileFile.close();
//The String has to be converted into a char array, otherwise the board will reset itself
String tempProfileFileName = getFileNameFromProfileNumber(profileNumber, true);
char tempProfileFileNameArray[tempProfileFileName.length()+1];
tempProfileFileName.toCharArray(tempProfileFileNameArray, tempProfileFileName.length()+1);
String finalProfileFileName = getFileNameFromProfileNumber(profileNumber, false);
char finalProfileFileNameArray[finalProfileFileName.length()+1];
finalProfileFileName.toCharArray(finalProfileFileNameArray, finalProfileFileName.length()+1);
File finalFile;
SdFile tempProfileFile;
if (finalFile.open(finalProfileFileNameArray, O_WRITE | O_CREAT | O_APPEND ) &&
tempProfileFile.open(tempProfileFileNameArray, O_READ )) {
finalFile.print(F("{ \"summary\":\n"));
finalFile.flush();
StaticJsonBuffer<JSON_OBJECT_SIZE(6)> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root.set("diveDuration", duration);
root.set("maxDepth", maxDepth);
root.set("minTemperature", minTemperature);
root.set("oxigenPercentage", oxigenPercentage);
root.set("diveDate", date.c_str());
root.set("diveTime", time.c_str());
root.printTo(finalFile);
finalFile.flush();
finalFile.print(F(",\n"));
finalFile.print(F("\"profile\": [\n"));
finalFile.flush();
bool isFirstline = true;
String line;
while (tempProfileFile.available()) {
if (isFirstline) {
isFirstline = false;
} else {
finalFile.print(",\n");
finalFile.flush();
}
line = readStringUntil(&tempProfileFile, '\n');
finalFile.print(line);
finalFile.flush();
}
finalFile.print(F("\n]\n}\n"));
finalFile.flush();
tempProfileFile.close();
finalFile.close();
//Remove the temporary dive profile file
if (SD.exists(tempProfileFileNameArray)) {
SD.remove(tempProfileFileNameArray);
}
}
}
ProfileData* Logbook::loadProfileDataFromFile(String profileFileName)
{
ProfileData* profileData = new ProfileData;
//The String has to be converted into a char array, otherwise the board will reset itself
char fileName[profileFileName.length()+1];
profileFileName.toCharArray(fileName, profileFileName.length()+1);
SdFile profileFile;
if (profileFile.open(fileName, O_READ)) {
Serial.print(F("Exists: "));
Serial.println(fileName);
String line;
int counter = 0;
while (profileFile.available()) {
line = readStringUntil(&profileFile, '\n');
line.trim();
if (counter == 4) {
profileData->diveDuration = readIntFromLineEnd(line);
} else if (counter == 5) {
profileData->maximumDepth = readFloatFromLineEnd(line);
} else if (counter == 6) {
profileData->minimumTemperature = readFloatFromLineEnd(line);
} else if (counter == 7) {
profileData->oxigenPercentage = readFloatFromLineEnd(line);
} else if (counter == 8) {
profileData->diveDate = readStringFromLineEnd(line);
} else if (counter == 9) {
profileData->diveTime = readStringFromLineEnd(line);
}
counter ++;
}
profileData->numberOfProfileItems = counter - 24;
profileFile.close();
}
return profileData;
}
void Logbook::drawProfileItems(UTFT* tft, int profileNumber, int pageNumber)
{
String profileFileName = getFileNameFromProfileNumber(profileNumber, false);
ProfileData* profileData = loadProfileDataFromFile(profileFileName);
//The String has to be converted into a char array, otherwise the board will reset itself
char fileName[profileFileName.length()+1];
profileFileName.toCharArray(fileName, profileFileName.length()+1);
if (SD.exists(fileName)) {
File profileFile = SD.open(fileName);
if (profileFile) {
//Skip the Summary section
profileFile.seek(40);
int firstLineNumberOnPage = 24 + ((pageNumber-1) * 460);
int lastLineNumberOnPage = 24 + (pageNumber * 460);
float heightUnit = 150/profileData->maximumDepth;
tft->setColor(VGA_BLACK);
tft->fillRect(10,160,470,315);
tft->setColor(VGA_FUCHSIA);
String line;
int counter = 0;
int positionOnPage = 0;
while (profileFile.available()) {
line = profileFile.readStringUntil('\n');
if (firstLineNumberOnPage < counter && counter <= lastLineNumberOnPage) {
tft->drawLine(10+positionOnPage, 160 + heightUnit*getDepthFromProfileLine(line), 10+positionOnPage, 310);
positionOnPage++;
}
counter ++;
}
profileFile.close();
}
}
}
/////////////////////
// Private methods //
/////////////////////
float Logbook::getDepthFromProfileLine(String line)
{
return line.substring(line.indexOf(',')+1).substring(0, line.indexOf(',')).toFloat();
}
int Logbook::readIntFromLineEnd(String line) {
return line.substring(line.indexOf('=')+1).toInt();
}
float Logbook::readFloatFromLineEnd(String line) {
return line.substring(line.indexOf('=')+1).toFloat();
}
String Logbook::readStringFromLineEnd(String line) {
return line.substring(line.indexOf('=')+2);
}
String Logbook::readStringUntil(SdFile* file, char terminator)
{
String ret;
int c = file->read();
while (c >= 0 && c != terminator)
{
ret += (char)c;
c = file->read();
}
return ret;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Dialog.h"
#include "../../3RVX/Logger.h"
#include "../UITranslator.h"
#include "Control.h"
Dialog::Dialog() {
}
Dialog::Dialog(HWND parent, LPCWSTR dlgTemplate) :
_parent(parent),
_template(dlgTemplate) {
// _dlgHwnd = CreateDialogParam(
// NULL,
// dlgTemplate,
// parent,
// StaticDialogProc,
// (LPARAM) this);
// if (_dlgHwnd == NULL) {
// Logger::LogLastError();
// }
// UITranslator::TranslateWindowText(_dlgHwnd);
}
void Dialog::Show() {
DialogBoxParam(NULL, _template, _parent, StaticDialogProc, (LPARAM) this);
//UITranslator::TranslateWindowText(_dlgHwnd);
}
void Dialog::Close(int result) {
EndDialog(_dlgHwnd, result);
}
void Dialog::AddControl(Control *control) {
if (control == nullptr) {
return;
}
int id = control->ID();
_controlMap[id] = control;
}
HWND Dialog::DialogHandle() {
return _dlgHwnd;
}
HWND Dialog::ParentHandle() {
return _parent;
}
INT_PTR Dialog::StaticDialogProc(
HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
Dialog *dlg;
if (uMsg == WM_INITDIALOG) {
dlg = (Dialog *) lParam;
dlg->_dlgHwnd = hwndDlg;
SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg);
} else {
dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER);
if (!dlg) {
return FALSE;
}
}
return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam);
}
INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg,
WPARAM wParam, LPARAM lParam) {
unsigned short nCode, ctrlId;
switch (uMsg) {
case WM_INITDIALOG:
Initialize();
return FALSE;
case WM_CLOSE: {
Close();
break;
}
case WM_COMMAND: {
nCode = HIWORD(wParam);
ctrlId = LOWORD(wParam);
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Command(nCode);
} else {
return FALSE;
}
}
case WM_NOTIFY: {
NMHDR *nHdr = (NMHDR *) lParam;
ctrlId = nHdr->idFrom;
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Notification(nHdr);
} else {
return FALSE;
}
}
case WM_HSCROLL:
case WM_VSCROLL: {
WORD request = LOWORD(wParam);
WORD position = HIWORD(wParam);
HWND scrollHandle = (HWND) lParam;
ctrlId = GetDlgCtrlID(scrollHandle);
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Scroll(
(uMsg == WM_HSCROLL), request, position);
} else {
return FALSE;
}
}
}
return FALSE;
}
<commit_msg>Remove old dialog construction code<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Dialog.h"
#include "../../3RVX/Logger.h"
#include "../UITranslator.h"
#include "Control.h"
Dialog::Dialog() {
}
Dialog::Dialog(HWND parent, LPCWSTR dlgTemplate) :
_parent(parent),
_template(dlgTemplate) {
}
void Dialog::Show() {
DialogBoxParam(NULL, _template, _parent, StaticDialogProc, (LPARAM) this);
//UITranslator::TranslateWindowText(_dlgHwnd);
}
void Dialog::Close(int result) {
EndDialog(_dlgHwnd, result);
}
void Dialog::AddControl(Control *control) {
if (control == nullptr) {
return;
}
int id = control->ID();
_controlMap[id] = control;
}
HWND Dialog::DialogHandle() {
return _dlgHwnd;
}
HWND Dialog::ParentHandle() {
return _parent;
}
INT_PTR Dialog::StaticDialogProc(
HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
Dialog *dlg;
if (uMsg == WM_INITDIALOG) {
dlg = (Dialog *) lParam;
dlg->_dlgHwnd = hwndDlg;
SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR) dlg);
} else {
dlg = (Dialog *) GetWindowLongPtr(hwndDlg, DWLP_USER);
if (!dlg) {
return FALSE;
}
}
return dlg->DialogProc(hwndDlg, uMsg, wParam, lParam);
}
INT_PTR Dialog::DialogProc(HWND hwndDlg, UINT uMsg,
WPARAM wParam, LPARAM lParam) {
unsigned short nCode, ctrlId;
switch (uMsg) {
case WM_INITDIALOG:
Initialize();
return FALSE;
case WM_CLOSE: {
Close();
break;
}
case WM_COMMAND: {
nCode = HIWORD(wParam);
ctrlId = LOWORD(wParam);
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Command(nCode);
} else {
return FALSE;
}
}
case WM_NOTIFY: {
NMHDR *nHdr = (NMHDR *) lParam;
ctrlId = nHdr->idFrom;
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Notification(nHdr);
} else {
return FALSE;
}
}
case WM_HSCROLL:
case WM_VSCROLL: {
WORD request = LOWORD(wParam);
WORD position = HIWORD(wParam);
HWND scrollHandle = (HWND) lParam;
ctrlId = GetDlgCtrlID(scrollHandle);
if (_controlMap.count(ctrlId) > 0) {
return _controlMap[ctrlId]->Scroll(
(uMsg == WM_HSCROLL), request, position);
} else {
return FALSE;
}
}
}
return FALSE;
}
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
#if !defined(DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680)
#define DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#if defined(_MSC_VER)
#include <io.h>
#else
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
extern int errno;
#endif
#include <functional>
#include <iterator>
#include <xalanc/PlatformSupport/XalanFileOutputStream.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanUnicode.hpp>
XALAN_CPP_NAMESPACE_BEGIN
#if defined(_MSC_VER)
struct FindFileStruct : public _wfinddata_t
{
enum eAttributes
{
eAttributeArchive = _A_ARCH,
eAttributeDirectory = _A_SUBDIR,
eAttributeHidden = _A_HIDDEN,
eAttributeNormal = _A_NORMAL,
eReadOnly = _A_RDONLY,
eSystem = _A_SYSTEM
};
public:
/**
* Retrieve name of file
*
* @return file name
*/
const XalanDOMChar*
getName() const
{
return name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool
isDirectory() const
{
return attrib & eAttributeDirectory ? true : false;
}
bool
isSelfOrParent() const
{
if (isDirectory() == false)
{
return false;
}
else if (name[0] == '.')
{
if (name[1] == '\0')
{
return true;
}
else if (name[1] == '.' &&
name[2] == '\0')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
};
#else
struct FindFileStruct : public dirent
{
public:
/**
* Retrieve name of file
*
* @return file name
*/
const char* getName() const
{
return d_name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool isDirectory() const
{
struct stat stat_Info;
int retCode = stat (d_name, &stat_Info);
if ( retCode == -1 )
{
typedef XalanFileOutputStream::XalanFileOutputStreamOpenException XalanStatDirectoryException;
throw XalanStatDirectoryException( XalanDOMString(d_name), errno );
}
return S_ISDIR(stat_Info.st_mode);
}
bool
isSelfOrParent() const
{
if (isDirectory() == false)
{
return false;
}
else if (d_name[0] == '.')
{
if (d_name[1] == '\0')
{
return true;
}
else if (d_name[1] == '.' &&
d_name[2] == '\0')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
};
#endif
#if defined(XALAN_NO_STD_NAMESPACE)
struct DirectoryFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct DirectoryFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
return theFindData.isDirectory();
}
};
#if defined(XALAN_NO_STD_NAMESPACE)
struct FilesOnlyFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct FilesOnlyFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
DirectoryFilterPredicate theDirectoryPredicate;
return !theDirectoryPredicate(theFindData);
}
};
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theFullSearchSpec,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction,
#if defined(XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS)
bool fIncludeSelfAndParent)
#else
bool fIncludeSelfAndParent = false)
#endif
{
#if defined(_MSC_VER)
FindFileStruct theFindData;
#ifdef _WIN64
typedef intptr_t theHandleType;
#else
typedef long theHandleType;
#endif
#pragma warning(push)
#pragma warning(disable: 4244)
theHandleType theSearchHandle = _wfindfirst(const_cast<wchar_t*>(theConversionFunction(theFullSearchSpec)),
&theFindData);
#pragma warning(pop)
if (theSearchHandle != -1)
{
try
{
do
{
if ((fIncludeSelfAndParent == true || theFindData.isSelfOrParent() == false) &&
theFilterPredicate(theFindData) == true)
{
*theOutputIterator = StringType(theFindData.getName());
}
}
while(_wfindnext(theSearchHandle,
&theFindData) == 0);
}
catch(...)
{
_findclose(theSearchHandle);
throw;
}
_findclose(theSearchHandle);
}
#else
CharVectorType theTargetVector;
TranscodeToLocalCodePage(theFullSearchSpec, theTargetVector, false);
const CharVectorType::size_type theSize = theTargetVector.size();
int indexSuffix=0, indexName=0;
bool target_Dir = false;
if (theSize > 0)
{
if (theTargetVector.back() == '*')
{
target_Dir = true;
theTargetVector.pop_back();
if (theSize == 1)
{
theTargetVector.push_back('.');
}
}
else
{
target_Dir = false;
while(theTargetVector.back() != '*')
{
theTargetVector.pop_back();
indexSuffix++;
}
theTargetVector.pop_back();
while(theTargetVector.back() != '/')
{
theTargetVector.pop_back();
indexName++;
}
}
theTargetVector.push_back('\0');
const char* const theSpec = c_str(theTargetVector);
assert(theSpec != 0);
XalanDOMString theName;
XalanDOMString theSuffix;
if ( !target_Dir )
{
int lenSpec = strlen(theSpec);
theName = theFullSearchSpec.substr(lenSpec, indexName);
theSuffix = theFullSearchSpec.substr(lenSpec+indexName+1, indexSuffix);
}
DIR* const theDirectory = opendir(theSpec);
if (theDirectory != 0)
{
chdir(theSpec);
try
{
const FindFileStruct* theEntry =
(FindFileStruct*)readdir(theDirectory);
while(theEntry != 0)
{
if ((fIncludeSelfAndParent == true || theEntry->isSelfOrParent() == false))
{
if (theFilterPredicate(*theEntry) == true)
{
if( target_Dir )
{
*theOutputIterator = StringType(theEntry->getName());
}
else
{
XalanDOMString Getname = StringType(theEntry->getName());
int Check_1 = Getname.compare(theName);
XalanDOMString GetnameSuffix = Getname.substr(length(Getname)-indexSuffix, indexSuffix);
int Check_2 = GetnameSuffix.compare(theSuffix);
if ( Check_1 == 1 && (!Check_2) )
{
*theOutputIterator = Getname;
}
}
}
}
theEntry = (FindFileStruct*)readdir(theDirectory);
} //while
}//try
catch(...)
{
closedir(theDirectory);
throw;
}
if( target_Dir )
chdir("..");
else
chdir("../..");
closedir(theDirectory);
}
}
#endif
}
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theDirectory,
const StringType& theSearchSpec,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction,
#if defined(XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS)
bool fIncludeSelfAndParent)
#else
bool fIncludeSelfAndParent = false)
#endif
{
StringType theFullSearchSpec(theDirectory);
theFullSearchSpec += theSearchSpec;
EnumerateDirectory(theFullSearchSpec, theOutputIterator, theFilterPredicate, theConversionFunction, fIncludeSelfAndParent);
}
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
template<class CollectionType, class StringType>
struct DirectoryEnumeratorFunctor
{
CollectionType
operator()(const StringType& theDirectory) const
{
CollectionType theCollection;
operator()(theDirectory,
theCollection);
return theCollection;
}
void
operator()(
const StringType&,
const CollectionType&) const
{
}
};
#else
template<class CollectionType,
class StringType = XalanDOMString,
class FilterPredicateType = FilesOnlyFilterPredicate,
class StringConversionFunction = c_wstr_functor>
#if defined(XALAN_NO_STD_NAMESPACE)
struct DirectoryEnumeratorFunctor : public unary_function<StringType, CollectionType>
#else
struct DirectoryEnumeratorFunctor : public std::unary_function<StringType, CollectionType>
#endif
{
#if defined(XALAN_NO_STD_NAMESPACE)
typedef unary_function<StringType, CollectionType> BaseClassType;
#else
typedef std::unary_function<StringType, CollectionType> BaseClassType;
#endif
typedef typename BaseClassType::result_type result_type;
typedef typename BaseClassType::argument_type argument_type;
explicit
DirectoryEnumeratorFunctor(bool fIncludeSelfAndParent = false) :
m_includeSelfAndParent(fIncludeSelfAndParent)
{
}
void
operator()(
const argument_type& theFullSearchSpec,
CollectionType& theCollection) const
{
XALAN_USING_STD(back_inserter)
EnumerateDirectory(
theFullSearchSpec,
XALAN_STD_QUALIFIER back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction,
m_includeSelfAndParent);
}
result_type
operator()(const argument_type& theFullSearchSpec) const
{
result_type theCollection;
operator()(
theFullSearchSpec,
theCollection);
return theCollection;
}
void
operator()(
const argument_type& theDirectory,
const argument_type& theSearchSpec,
CollectionType& theCollection) const
{
EnumerateDirectory(
theDirectory,
theSearchSpec,
XALAN_STD_QUALIFIER back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction,
m_includeSelfAndParent);
}
result_type
operator()(
const argument_type& theDirectory,
const argument_type& theSearchSpec) const
{
result_type theCollection;
operator()(
theDirectory,
theSearchSpec,
theCollection);
return theCollection;
}
private:
FilterPredicateType m_filterPredicate;
StringConversionFunction m_conversionFunction;
const bool m_includeSelfAndParent;
};
#endif
XALAN_CPP_NAMESPACE_END
#endif // DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
<commit_msg>Fix for Tru64.<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
#if !defined(DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680)
#define DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#if defined(_MSC_VER)
#include <io.h>
#else
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
extern int errno;
#endif
#include <functional>
#include <iterator>
#include <xalanc/PlatformSupport/XalanFileOutputStream.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanUnicode.hpp>
XALAN_CPP_NAMESPACE_BEGIN
#if defined(_MSC_VER)
struct FindFileStruct : public _wfinddata_t
{
enum eAttributes
{
eAttributeArchive = _A_ARCH,
eAttributeDirectory = _A_SUBDIR,
eAttributeHidden = _A_HIDDEN,
eAttributeNormal = _A_NORMAL,
eReadOnly = _A_RDONLY,
eSystem = _A_SYSTEM
};
public:
/**
* Retrieve name of file
*
* @return file name
*/
const XalanDOMChar*
getName() const
{
return name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool
isDirectory() const
{
return attrib & eAttributeDirectory ? true : false;
}
bool
isSelfOrParent() const
{
if (isDirectory() == false)
{
return false;
}
else if (name[0] == '.')
{
if (name[1] == '\0')
{
return true;
}
else if (name[1] == '.' &&
name[2] == '\0')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
};
#else
struct FindFileStruct : public dirent
{
public:
/**
* Retrieve name of file
*
* @return file name
*/
const char* getName() const
{
return d_name;
}
/**
* Determine whether file is a directory
*
* @return true if file is a directory
*/
bool isDirectory() const
{
struct stat stat_Info;
int retCode = stat (d_name, &stat_Info);
if ( retCode == -1 )
{
typedef XalanFileOutputStream::XalanFileOutputStreamOpenException XalanStatDirectoryException;
throw XalanStatDirectoryException( XalanDOMString(d_name), errno );
}
return S_ISDIR(stat_Info.st_mode);
}
bool
isSelfOrParent() const
{
if (isDirectory() == false)
{
return false;
}
else if (d_name[0] == '.')
{
if (d_name[1] == '\0')
{
return true;
}
else if (d_name[1] == '.' &&
d_name[2] == '\0')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
};
#endif
#if defined(XALAN_NO_STD_NAMESPACE)
struct DirectoryFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct DirectoryFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
return theFindData.isDirectory();
}
};
#if defined(XALAN_NO_STD_NAMESPACE)
struct FilesOnlyFilterPredicate : public unary_function<FindFileStruct, bool>
#else
struct FilesOnlyFilterPredicate : public std::unary_function<FindFileStruct, bool>
#endif
{
result_type
operator()(const argument_type& theFindData) const
{
DirectoryFilterPredicate theDirectoryPredicate;
return !theDirectoryPredicate(theFindData);
}
};
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theFullSearchSpec,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction,
#if defined(XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS)
bool fIncludeSelfAndParent)
#else
bool fIncludeSelfAndParent = false)
#endif
{
#if defined(_MSC_VER)
FindFileStruct theFindData;
#ifdef _WIN64
typedef intptr_t theHandleType;
#else
typedef long theHandleType;
#endif
#pragma warning(push)
#pragma warning(disable: 4244)
theHandleType theSearchHandle = _wfindfirst(const_cast<wchar_t*>(theConversionFunction(theFullSearchSpec)),
&theFindData);
#pragma warning(pop)
if (theSearchHandle != -1)
{
try
{
do
{
if ((fIncludeSelfAndParent == true || theFindData.isSelfOrParent() == false) &&
theFilterPredicate(theFindData) == true)
{
*theOutputIterator = StringType(theFindData.getName());
}
}
while(_wfindnext(theSearchHandle,
&theFindData) == 0);
}
catch(...)
{
_findclose(theSearchHandle);
throw;
}
_findclose(theSearchHandle);
}
#else
CharVectorType theTargetVector;
TranscodeToLocalCodePage(theFullSearchSpec, theTargetVector, false);
const CharVectorType::size_type theSize = theTargetVector.size();
int indexSuffix=0, indexName=0;
bool target_Dir = false;
if (theSize > 0)
{
if (theTargetVector.back() == '*')
{
target_Dir = true;
theTargetVector.pop_back();
if (theSize == 1)
{
theTargetVector.push_back('.');
}
}
else
{
target_Dir = false;
while(theTargetVector.back() != '*')
{
theTargetVector.pop_back();
indexSuffix++;
}
theTargetVector.pop_back();
while(theTargetVector.back() != '/')
{
theTargetVector.pop_back();
indexName++;
}
}
theTargetVector.push_back('\0');
const char* const theSpec = c_str(theTargetVector);
assert(theSpec != 0);
XalanDOMString theName;
XalanDOMString theSuffix;
if ( !target_Dir )
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
using std::strlen;
#endif
int lenSpec = strlen(theSpec);
theName = theFullSearchSpec.substr(lenSpec, indexName);
theSuffix = theFullSearchSpec.substr(lenSpec+indexName+1, indexSuffix);
}
DIR* const theDirectory = opendir(theSpec);
if (theDirectory != 0)
{
chdir(theSpec);
try
{
const FindFileStruct* theEntry =
(FindFileStruct*)readdir(theDirectory);
while(theEntry != 0)
{
if ((fIncludeSelfAndParent == true || theEntry->isSelfOrParent() == false))
{
if (theFilterPredicate(*theEntry) == true)
{
if( target_Dir )
{
*theOutputIterator = StringType(theEntry->getName());
}
else
{
XalanDOMString Getname = StringType(theEntry->getName());
int Check_1 = Getname.compare(theName);
XalanDOMString GetnameSuffix = Getname.substr(length(Getname)-indexSuffix, indexSuffix);
int Check_2 = GetnameSuffix.compare(theSuffix);
if ( Check_1 == 1 && (!Check_2) )
{
*theOutputIterator = Getname;
}
}
}
}
theEntry = (FindFileStruct*)readdir(theDirectory);
} //while
}//try
catch(...)
{
closedir(theDirectory);
throw;
}
if( target_Dir )
chdir("..");
else
chdir("../..");
closedir(theDirectory);
}
}
#endif
}
template<class OutputIteratorType,
class FilterPredicateType,
class StringType,
class StringConversionFunction>
void
EnumerateDirectory(
const StringType& theDirectory,
const StringType& theSearchSpec,
OutputIteratorType theOutputIterator,
FilterPredicateType theFilterPredicate,
StringConversionFunction theConversionFunction,
#if defined(XALAN_TEMPLATE_FUNCTION_NO_DEFAULT_PARAMETERS)
bool fIncludeSelfAndParent)
#else
bool fIncludeSelfAndParent = false)
#endif
{
StringType theFullSearchSpec(theDirectory);
theFullSearchSpec += theSearchSpec;
EnumerateDirectory(theFullSearchSpec, theOutputIterator, theFilterPredicate, theConversionFunction, fIncludeSelfAndParent);
}
#if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS)
template<class CollectionType, class StringType>
struct DirectoryEnumeratorFunctor
{
CollectionType
operator()(const StringType& theDirectory) const
{
CollectionType theCollection;
operator()(theDirectory,
theCollection);
return theCollection;
}
void
operator()(
const StringType&,
const CollectionType&) const
{
}
};
#else
template<class CollectionType,
class StringType = XalanDOMString,
class FilterPredicateType = FilesOnlyFilterPredicate,
class StringConversionFunction = c_wstr_functor>
#if defined(XALAN_NO_STD_NAMESPACE)
struct DirectoryEnumeratorFunctor : public unary_function<StringType, CollectionType>
#else
struct DirectoryEnumeratorFunctor : public std::unary_function<StringType, CollectionType>
#endif
{
#if defined(XALAN_NO_STD_NAMESPACE)
typedef unary_function<StringType, CollectionType> BaseClassType;
#else
typedef std::unary_function<StringType, CollectionType> BaseClassType;
#endif
typedef typename BaseClassType::result_type result_type;
typedef typename BaseClassType::argument_type argument_type;
explicit
DirectoryEnumeratorFunctor(bool fIncludeSelfAndParent = false) :
m_includeSelfAndParent(fIncludeSelfAndParent)
{
}
void
operator()(
const argument_type& theFullSearchSpec,
CollectionType& theCollection) const
{
XALAN_USING_STD(back_inserter)
EnumerateDirectory(
theFullSearchSpec,
XALAN_STD_QUALIFIER back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction,
m_includeSelfAndParent);
}
result_type
operator()(const argument_type& theFullSearchSpec) const
{
result_type theCollection;
operator()(
theFullSearchSpec,
theCollection);
return theCollection;
}
void
operator()(
const argument_type& theDirectory,
const argument_type& theSearchSpec,
CollectionType& theCollection) const
{
EnumerateDirectory(
theDirectory,
theSearchSpec,
XALAN_STD_QUALIFIER back_inserter(theCollection),
m_filterPredicate,
m_conversionFunction,
m_includeSelfAndParent);
}
result_type
operator()(
const argument_type& theDirectory,
const argument_type& theSearchSpec) const
{
result_type theCollection;
operator()(
theDirectory,
theSearchSpec,
theCollection);
return theCollection;
}
private:
FilterPredicateType m_filterPredicate;
StringConversionFunction m_conversionFunction;
const bool m_includeSelfAndParent;
};
#endif
XALAN_CPP_NAMESPACE_END
#endif // DIRECTORY_ENUMERATOR_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>// TexturePaletteRecord.cpp
#include "flt.h"
#include "Registry.h"
#include "TexturePaletteRecord.h"
using namespace flt;
////////////////////////////////////////////////////////////////////
//
// TexturePaletteRecord
//
////////////////////////////////////////////////////////////////////
RegisterRecordProxy<TexturePaletteRecord> g_TexturePaletteProxy;
TexturePaletteRecord::TexturePaletteRecord()
{
}
// virtual
TexturePaletteRecord::~TexturePaletteRecord()
{
}
// virtual
void TexturePaletteRecord::endian()
{
STexturePalette *pSTexture = (STexturePalette*)getData();
ENDIAN( pSTexture->diIndex );
ENDIAN( pSTexture->diX );
ENDIAN( pSTexture->diY );
}
<commit_msg>From Brede Johansen, fix the TexturePaletteRecord::endian() to handle old flt versions (11, 12 & 13).<commit_after>// TexturePaletteRecord.cpp
#include "flt.h"
#include "Registry.h"
#include "TexturePaletteRecord.h"
using namespace flt;
////////////////////////////////////////////////////////////////////
//
// TexturePaletteRecord
//
////////////////////////////////////////////////////////////////////
RegisterRecordProxy<TexturePaletteRecord> g_TexturePaletteProxy;
TexturePaletteRecord::TexturePaletteRecord()
{
}
// virtual
TexturePaletteRecord::~TexturePaletteRecord()
{
}
// virtual
void TexturePaletteRecord::endian()
{
int flightVersion = getFlightVersion();
if (flightVersion > 13)
{
STexturePalette *pSTexture = (STexturePalette*)getData();
ENDIAN( pSTexture->diIndex );
ENDIAN( pSTexture->diX );
ENDIAN( pSTexture->diY );
}
else // version 11, 12 & 13
{
SOldTexturePalette *pSOldTexture = (SOldTexturePalette*)getData();
ENDIAN( pSOldTexture->diIndex );
ENDIAN( pSOldTexture->diX );
ENDIAN( pSOldTexture->diY );
}
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKcommon *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2009-12 Stanford University and the Authors. *
* Authors: Michael Sherman *
* Contributors: *
* *
* 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 "SimTKcommon/internal/common.h"
#include "SimTKcommon/internal/String.h"
#include "SimTKcommon/internal/Pathname.h"
#include <string>
using std::string;
#include <cctype>
using std::tolower;
#include <iostream>
#include <fstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <direct.h>
#pragma warning(disable:4996) // getenv() is apparently unsafe
#else
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include <dlfcn.h>
#include <dirent.h>
#include <unistd.h>
#endif
using namespace SimTK;
#ifdef _WIN32
static const bool IsWindows = true;
static const char MyPathSeparator = '\\';
static const char OtherPathSeparator = '/';
#else
static const bool IsWindows = false;
static const char MyPathSeparator = '/';
static const char OtherPathSeparator = '\\';
#endif
char Pathname::getPathSeparatorChar() {
return MyPathSeparator;
}
string Pathname::getPathSeparator() {
return String(getPathSeparatorChar());
}
static void makeNativeSlashesInPlace(string& inout) {
for (unsigned i=0; i < inout.size(); ++i)
if (inout[i] == OtherPathSeparator)
inout[i] = MyPathSeparator;
}
static void addFinalSeparatorInPlace(string& inout) {
if (!inout.empty() && !Pathname::isPathSeparator(inout[inout.size()-1]))
inout += MyPathSeparator;
}
static bool beginsWithPathSeparator(const string& in) {
return !in.empty() && Pathname::isPathSeparator(in[0]);
}
// Remove the last segment of a path name and the separator. The
// returned component does not include a separator.
static void removeLastPathComponentInPlace(string& inout, string& component) {
component.clear();
if (inout.empty()) return;
const string::size_type lastSeparator = inout.find_last_of("/\\");
if (lastSeparator == string::npos) {
component = inout;
inout.clear();
} else {
component = inout.substr(lastSeparator+1);
inout.erase(lastSeparator);
}
}
static void removeDriveInPlace(string& inout, string& drive) {
drive.clear();
if (IsWindows && inout.size() >= 2 && inout[1]==':') {
drive = (char)tolower(inout[0]);
inout.erase(0,2);
}
}
// We assume a path name structure like this:
// (1) Everything up to and including the final directory separator
// character is the directory; the rest is the file name. On return
// we fix the slashes in the directory name to suit the current
// system ('\' for Windows, '/' otherwise).
// (2) If the file name contains a ".", characters after the last
// "." are the extension and the last "." is removed.
// (5) What's left is the fileName.
// We accept both "/" and "\" as separator characters. We leave the
// case as it was supplied.
// Leading and trailing white space is removed; embedded white space
// remains.
// Leading "X:" for some drive letter X is recognized on Windows as
// a drive specification, otherwise the drive is the current drive.
// That is then removed for further processing.
// Absolute paths are designated like this:
// Leading "/" means root relative (on the drive).
// Leading "./" means current working directory relative (on the drive).
// Leading "../" is interpreted as "./..".
// Leading "@/" means relative to executable location.
// Above leading characters are removed and replaced with the
// full path name they represent, then the entire path is divided
// into components. If a component is "." or "" (empty) it is
// removed. If a component is ".." it and the previous component
// if any are removed. (".." as a first component will report as
// ill formed.)
// If there is something ill-formed about the file name we'll return
// false.
void Pathname::deconstructPathname( const string& name,
bool& isAbsolutePath,
string& directory,
string& fileName,
string& extension)
{
isAbsolutePath = false;
directory.erase(); fileName.erase(); extension.erase();
// Remove all the white space and make all the slashes be forward ones.
// (For Windows they'll be changed to backslashes later.)
String processed = String::trimWhiteSpace(name).replaceAllChar('\\', '/');
if (processed.empty())
return; // name consisted only of white space
string drive;
removeDriveInPlace(processed, drive);
// Now the drive if any has been removed and we're looking at
// the beginning of the path name.
// If the pathname in its entirety is just one of these, append
// a slash to avoid special cases below.
if (processed=="." || processed==".." || processed=="@")
processed += "/";
// If the path begins with "../" we'll make it ./../ to simplify handling.
if (processed.substr(0,3) == "../")
processed.insert(0, "./");
if (processed.substr(0,1) == "/") {
isAbsolutePath = true;
processed.erase(0,1);
if (drive.empty()) drive = getCurrentDriveLetter();
} else if (processed.substr(0,2) == "./") {
isAbsolutePath = true;
processed.replace(0,2,getCurrentWorkingDirectory(drive));
removeDriveInPlace(processed, drive);
} else if (processed.substr(0,2) == "@/") {
isAbsolutePath = true;
processed.replace(0,2,getThisExecutableDirectory());
removeDriveInPlace(processed, drive);
} else if (!drive.empty()) {
// Looks like a relative path name. But if it had an initial
// drive specification, e.g. X:something.txt, that is supposed
// to be interpreted relative to the current working directory
// on drive X, just as though it were X:./something.txt.
isAbsolutePath = true;
processed.insert(0, getCurrentWorkingDirectory(drive));
removeDriveInPlace(processed, drive);
}
// We may have picked up a new batch of backslashes above.
processed.replaceAllChar('\\', '/');
// Now we have the full path name if this is absolute, otherwise
// we're looking at a relative path name. In any case the last
// component is the file name if it isn't empty, ".", or "..".
// Process the ".." segments and eliminate meaningless ones
// as we go through.
Array_<string> segmentsInReverse;
bool isFinalSegment = true; // first time around might be the fileName
int numDotDotsSeen = 0;
while (!processed.empty()) {
string component;
removeLastPathComponentInPlace(processed, component);
if (component == "..")
++numDotDotsSeen;
else if (!component.empty() && component != ".") {
if (numDotDotsSeen)
--numDotDotsSeen; // skip component
else if (isFinalSegment) fileName = component;
else segmentsInReverse.push_back(component);
}
isFinalSegment = false;
}
// Now we can put together the canonicalized directory.
if (isAbsolutePath) {
if (!drive.empty())
directory = drive + ":";
directory += "/";
}
for (int i = (int)segmentsInReverse.size()-1; i >= 0; --i)
directory += segmentsInReverse[i] + "/";
// Fix the slashes.
makeNativeSlashesInPlace(directory);
// If there is a .extension, strip it off.
string::size_type lastDot = fileName.rfind('.');
if (lastDot != string::npos) {
extension = fileName.substr(lastDot);
fileName.erase(lastDot);
}
}
bool Pathname::fileExists(const std::string& fileName) {
std::ifstream f(fileName.c_str());
return f.good();
// File is closed by destruction of f.
}
string Pathname::getDefaultInstallDir() {
string installDir;
#ifdef _WIN32
installDir = getEnvironmentVariable("ProgramFiles");
if (!installDir.empty()) {
makeNativeSlashesInPlace(installDir);
addFinalSeparatorInPlace(installDir);
} else
installDir = "c:\\Program Files\\";
#else
installDir = "/usr/local/";
#endif
return installDir;
}
string Pathname::addDirectoryOffset(const string& base, const string& offset) {
string cleanOffset = beginsWithPathSeparator(offset)
? offset.substr(1) : offset; // remove leading path separator
addFinalSeparatorInPlace(cleanOffset); // add trailing / if non-empty
string result = base;
addFinalSeparatorInPlace(result);
result += cleanOffset;
return result;
}
string Pathname::getInstallDir(const std::string& envInstallDir,
const std::string& offsetFromDefaultInstallDir)
{ std::string installDir = getEnvironmentVariable(envInstallDir);
if (!installDir.empty()) {
makeNativeSlashesInPlace(installDir);
addFinalSeparatorInPlace(installDir);
} else
installDir = addDirectoryOffset(getDefaultInstallDir(), offsetFromDefaultInstallDir);
return installDir;
}
string Pathname::getThisExecutablePath() {
char buf[2048];
#if defined(_WIN32)
const DWORD nBytes = GetModuleFileName((HMODULE)0, (LPTSTR)buf, sizeof(buf));
buf[0] = (char)tolower(buf[0]); // drive name
#elif defined(__APPLE__)
uint32_t sz = (uint32_t)sizeof(buf);
int status = _NSGetExecutablePath(buf, &sz);
assert(status==0); // non-zero means path longer than buf, sz says what's needed
#else // Linux
// This isn't automatically null terminated.
const size_t nBytes = readlink("/proc/self/exe", buf, sizeof(buf));
buf[nBytes] = '\0';
#endif
return string(buf);
}
string Pathname::getThisExecutableDirectory() {
string path = getThisExecutablePath();
string component;
removeLastPathComponentInPlace(path, component);
path += MyPathSeparator;
return path;
}
string Pathname::getCurrentDriveLetter() {
#ifdef _WIN32
const int which = _getdrive();
return string() + (char)('a' + which-1);
#else
return string();
#endif
}
string Pathname::getCurrentDrive() {
#ifdef _WIN32
return getCurrentDriveLetter() + ":";
#else
return string();
#endif
}
string Pathname::getCurrentWorkingDirectory(const string& drive) {
char buf[2048];
#ifdef _WIN32
const int which = drive.empty() ? 0 : (tolower(drive[0]) - 'a') + 1;
assert(which >= 0);
if (which != 0) {
// Make sure this drive exists.
const ULONG mask = _getdrives();
if (!(mask & (1<<(which-1))))
return getRootDirectory(drive);
}
_getdcwd(which, buf, sizeof(buf));
buf[0] = (char)tolower(buf[0]); // drive letter
#else
#ifndef NDEBUG
char* bufp = getcwd(buf, sizeof(buf));
assert(bufp != 0); // buf not big enough if this happens
#else
(void) getcwd(buf, sizeof(buf));
#endif
#endif
string cwd(buf);
if (cwd.size() && cwd[cwd.size()-1] != MyPathSeparator)
cwd += MyPathSeparator;
return cwd;
}
string Pathname::getRootDirectory(const string& drive) {
#ifdef _WIN32
if (drive.empty())
return getCurrentDrive() + getPathSeparator();
return String(drive[0]).toLower() + ":" + getPathSeparator();
#else
return getPathSeparator();
#endif
}
bool Pathname::environmentVariableExists(const string& name) {
return getenv(name.c_str()) != 0;
}
string Pathname::getEnvironmentVariable(const string& name) {
char* value;
value = getenv(name.c_str());
return value ? string(value) : string();
}
<commit_msg>Fix Pathname GCC/Clang warning.<commit_after>/* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKcommon *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2009-12 Stanford University and the Authors. *
* Authors: Michael Sherman *
* Contributors: *
* *
* 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 "SimTKcommon/internal/common.h"
#include "SimTKcommon/internal/String.h"
#include "SimTKcommon/internal/Pathname.h"
#include <string>
using std::string;
#include <cctype>
using std::tolower;
#include <iostream>
#include <fstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <direct.h>
#pragma warning(disable:4996) // getenv() is apparently unsafe
#else
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include <dlfcn.h>
#include <dirent.h>
#include <unistd.h>
#endif
using namespace SimTK;
#ifdef _WIN32
static const bool IsWindows = true;
static const char MyPathSeparator = '\\';
static const char OtherPathSeparator = '/';
#else
static const bool IsWindows = false;
static const char MyPathSeparator = '/';
static const char OtherPathSeparator = '\\';
#endif
char Pathname::getPathSeparatorChar() {
return MyPathSeparator;
}
string Pathname::getPathSeparator() {
return String(getPathSeparatorChar());
}
static void makeNativeSlashesInPlace(string& inout) {
for (unsigned i=0; i < inout.size(); ++i)
if (inout[i] == OtherPathSeparator)
inout[i] = MyPathSeparator;
}
static void addFinalSeparatorInPlace(string& inout) {
if (!inout.empty() && !Pathname::isPathSeparator(inout[inout.size()-1]))
inout += MyPathSeparator;
}
static bool beginsWithPathSeparator(const string& in) {
return !in.empty() && Pathname::isPathSeparator(in[0]);
}
// Remove the last segment of a path name and the separator. The
// returned component does not include a separator.
static void removeLastPathComponentInPlace(string& inout, string& component) {
component.clear();
if (inout.empty()) return;
const string::size_type lastSeparator = inout.find_last_of("/\\");
if (lastSeparator == string::npos) {
component = inout;
inout.clear();
} else {
component = inout.substr(lastSeparator+1);
inout.erase(lastSeparator);
}
}
static void removeDriveInPlace(string& inout, string& drive) {
drive.clear();
if (IsWindows && inout.size() >= 2 && inout[1]==':') {
drive = (char)tolower(inout[0]);
inout.erase(0,2);
}
}
// We assume a path name structure like this:
// (1) Everything up to and including the final directory separator
// character is the directory; the rest is the file name. On return
// we fix the slashes in the directory name to suit the current
// system ('\' for Windows, '/' otherwise).
// (2) If the file name contains a ".", characters after the last
// "." are the extension and the last "." is removed.
// (5) What's left is the fileName.
// We accept both "/" and "\" as separator characters. We leave the
// case as it was supplied.
// Leading and trailing white space is removed; embedded white space
// remains.
// Leading "X:" for some drive letter X is recognized on Windows as
// a drive specification, otherwise the drive is the current drive.
// That is then removed for further processing.
// Absolute paths are designated like this:
// Leading "/" means root relative (on the drive).
// Leading "./" means current working directory relative (on the drive).
// Leading "../" is interpreted as "./..".
// Leading "@/" means relative to executable location.
// Above leading characters are removed and replaced with the
// full path name they represent, then the entire path is divided
// into components. If a component is "." or "" (empty) it is
// removed. If a component is ".." it and the previous component
// if any are removed. (".." as a first component will report as
// ill formed.)
// If there is something ill-formed about the file name we'll return
// false.
void Pathname::deconstructPathname( const string& name,
bool& isAbsolutePath,
string& directory,
string& fileName,
string& extension)
{
isAbsolutePath = false;
directory.erase(); fileName.erase(); extension.erase();
// Remove all the white space and make all the slashes be forward ones.
// (For Windows they'll be changed to backslashes later.)
String processed = String::trimWhiteSpace(name).replaceAllChar('\\', '/');
if (processed.empty())
return; // name consisted only of white space
string drive;
removeDriveInPlace(processed, drive);
// Now the drive if any has been removed and we're looking at
// the beginning of the path name.
// If the pathname in its entirety is just one of these, append
// a slash to avoid special cases below.
if (processed=="." || processed==".." || processed=="@")
processed += "/";
// If the path begins with "../" we'll make it ./../ to simplify handling.
if (processed.substr(0,3) == "../")
processed.insert(0, "./");
if (processed.substr(0,1) == "/") {
isAbsolutePath = true;
processed.erase(0,1);
if (drive.empty()) drive = getCurrentDriveLetter();
} else if (processed.substr(0,2) == "./") {
isAbsolutePath = true;
processed.replace(0,2,getCurrentWorkingDirectory(drive));
removeDriveInPlace(processed, drive);
} else if (processed.substr(0,2) == "@/") {
isAbsolutePath = true;
processed.replace(0,2,getThisExecutableDirectory());
removeDriveInPlace(processed, drive);
} else if (!drive.empty()) {
// Looks like a relative path name. But if it had an initial
// drive specification, e.g. X:something.txt, that is supposed
// to be interpreted relative to the current working directory
// on drive X, just as though it were X:./something.txt.
isAbsolutePath = true;
processed.insert(0, getCurrentWorkingDirectory(drive));
removeDriveInPlace(processed, drive);
}
// We may have picked up a new batch of backslashes above.
processed.replaceAllChar('\\', '/');
// Now we have the full path name if this is absolute, otherwise
// we're looking at a relative path name. In any case the last
// component is the file name if it isn't empty, ".", or "..".
// Process the ".." segments and eliminate meaningless ones
// as we go through.
Array_<string> segmentsInReverse;
bool isFinalSegment = true; // first time around might be the fileName
int numDotDotsSeen = 0;
while (!processed.empty()) {
string component;
removeLastPathComponentInPlace(processed, component);
if (component == "..")
++numDotDotsSeen;
else if (!component.empty() && component != ".") {
if (numDotDotsSeen)
--numDotDotsSeen; // skip component
else if (isFinalSegment) fileName = component;
else segmentsInReverse.push_back(component);
}
isFinalSegment = false;
}
// Now we can put together the canonicalized directory.
if (isAbsolutePath) {
if (!drive.empty())
directory = drive + ":";
directory += "/";
}
for (int i = (int)segmentsInReverse.size()-1; i >= 0; --i)
directory += segmentsInReverse[i] + "/";
// Fix the slashes.
makeNativeSlashesInPlace(directory);
// If there is a .extension, strip it off.
string::size_type lastDot = fileName.rfind('.');
if (lastDot != string::npos) {
extension = fileName.substr(lastDot);
fileName.erase(lastDot);
}
}
bool Pathname::fileExists(const std::string& fileName) {
std::ifstream f(fileName.c_str());
return f.good();
// File is closed by destruction of f.
}
string Pathname::getDefaultInstallDir() {
string installDir;
#ifdef _WIN32
installDir = getEnvironmentVariable("ProgramFiles");
if (!installDir.empty()) {
makeNativeSlashesInPlace(installDir);
addFinalSeparatorInPlace(installDir);
} else
installDir = "c:\\Program Files\\";
#else
installDir = "/usr/local/";
#endif
return installDir;
}
string Pathname::addDirectoryOffset(const string& base, const string& offset) {
string cleanOffset = beginsWithPathSeparator(offset)
? offset.substr(1) : offset; // remove leading path separator
addFinalSeparatorInPlace(cleanOffset); // add trailing / if non-empty
string result = base;
addFinalSeparatorInPlace(result);
result += cleanOffset;
return result;
}
string Pathname::getInstallDir(const std::string& envInstallDir,
const std::string& offsetFromDefaultInstallDir)
{ std::string installDir = getEnvironmentVariable(envInstallDir);
if (!installDir.empty()) {
makeNativeSlashesInPlace(installDir);
addFinalSeparatorInPlace(installDir);
} else
installDir = addDirectoryOffset(getDefaultInstallDir(), offsetFromDefaultInstallDir);
return installDir;
}
string Pathname::getThisExecutablePath() {
char buf[2048];
#if defined(_WIN32)
const DWORD nBytes = GetModuleFileName((HMODULE)0, (LPTSTR)buf, sizeof(buf));
buf[0] = (char)tolower(buf[0]); // drive name
#elif defined(__APPLE__)
uint32_t sz = (uint32_t)sizeof(buf);
int status = _NSGetExecutablePath(buf, &sz);
assert(status==0); // non-zero means path longer than buf, sz says what's needed
#else // Linux
// This isn't automatically null terminated.
const size_t nBytes = readlink("/proc/self/exe", buf, sizeof(buf));
buf[nBytes] = '\0';
#endif
return string(buf);
}
string Pathname::getThisExecutableDirectory() {
string path = getThisExecutablePath();
string component;
removeLastPathComponentInPlace(path, component);
path += MyPathSeparator;
return path;
}
string Pathname::getCurrentDriveLetter() {
#ifdef _WIN32
const int which = _getdrive();
return string() + (char)('a' + which-1);
#else
return string();
#endif
}
string Pathname::getCurrentDrive() {
#ifdef _WIN32
return getCurrentDriveLetter() + ":";
#else
return string();
#endif
}
string Pathname::getCurrentWorkingDirectory(const string& drive) {
char buf[2048];
#ifdef _WIN32
const int which = drive.empty() ? 0 : (tolower(drive[0]) - 'a') + 1;
assert(which >= 0);
if (which != 0) {
// Make sure this drive exists.
const ULONG mask = _getdrives();
if (!(mask & (1<<(which-1))))
return getRootDirectory(drive);
}
_getdcwd(which, buf, sizeof(buf));
buf[0] = (char)tolower(buf[0]); // drive letter
#else
char* bufp = getcwd(buf, sizeof(buf));
SimTK_ERRCHK_ALWAYS(bufp != 0,
"Pathname::getCurrentWorkingDirectory()",
"Buffer is not big enough to store current working directory.");
#endif
string cwd(buf);
if (cwd.size() && cwd[cwd.size()-1] != MyPathSeparator)
cwd += MyPathSeparator;
return cwd;
}
string Pathname::getRootDirectory(const string& drive) {
#ifdef _WIN32
if (drive.empty())
return getCurrentDrive() + getPathSeparator();
return String(drive[0]).toLower() + ":" + getPathSeparator();
#else
return getPathSeparator();
#endif
}
bool Pathname::environmentVariableExists(const string& name) {
return getenv(name.c_str()) != 0;
}
string Pathname::getEnvironmentVariable(const string& name) {
char* value;
value = getenv(name.c_str());
return value ? string(value) : string();
}
<|endoftext|> |
<commit_before>/**********************************************************************
*
* FILE: ConvexPlanarOccluder.cpp
*
* DESCRIPTION: Read/Write osg::ConvexPlanarOccluder in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerator
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 23.4.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "Object.h"
#include "ConvexPlanarOccluder.h"
#include "ConvexPlanarPolygon.h"
using namespace ive;
void ConvexPlanarOccluder::write(DataOutputStream* out){
// Write ConvexPlanarOccluder's identification.
out->writeInt(IVECONVEXPLANAROCCLUDER);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("ConvexPlanarOccluder::write(): Could not cast this osg::ConvexPlanarOccluder to an osg::Object.");
// Write ConvexPlanarOccluder's properties.
// Write planar polygon occluder.
out->writeInt((int)&getOccluder());
if(&getOccluder())
((ive::ConvexPlanarPolygon*)(&getOccluder()))->write(out);
// Write hole list.
HoleList holeList = getHoleList();
int size = holeList.size();
out->writeInt(size);
for(int i=0; i<size; i++){
((ive::ConvexPlanarPolygon*)(&holeList[i]))->write(out);
}
}
void ConvexPlanarOccluder::read(DataInputStream* in){
// Peek on ConvexPlanarOccluder's identification.
int id = in->peekInt();
if(id == IVECONVEXPLANAROCCLUDER){
// Read ConvexPlanarOccluder's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("ConvexPlanarOccluder::read(): Could not cast this osg::ConvexPlanarOccluder to an osg::Object.");
// Read ConvexPlanarOccluder's properties
// Read planar polygon occluder.
if(in->readInt()){
osg::ConvexPlanarPolygon* cpp = new osg::ConvexPlanarPolygon();
((ive::ConvexPlanarPolygon*)(cpp))->read(in);
setOccluder(*cpp);
}
// Read hole list.
int size = in->readInt();
for(int i=0; i<size; i++){
osg::ConvexPlanarPolygon* cpp = new osg::ConvexPlanarPolygon();
((ive::ConvexPlanarPolygon*)(cpp))->read(in);
addHole(*cpp);
}
}
else{
throw Exception("ConvexPlanarOccluder::read(): Expected ConvexPlanarOccluder identification.");
}
}
<commit_msg>Fix for 64bit build.<commit_after>/**********************************************************************
*
* FILE: ConvexPlanarOccluder.cpp
*
* DESCRIPTION: Read/Write osg::ConvexPlanarOccluder in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerator
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 23.4.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "Object.h"
#include "ConvexPlanarOccluder.h"
#include "ConvexPlanarPolygon.h"
using namespace ive;
void ConvexPlanarOccluder::write(DataOutputStream* out){
// Write ConvexPlanarOccluder's identification.
out->writeInt(IVECONVEXPLANAROCCLUDER);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("ConvexPlanarOccluder::write(): Could not cast this osg::ConvexPlanarOccluder to an osg::Object.");
// Write ConvexPlanarOccluder's properties.
// Write planar polygon occluder.
((ive::ConvexPlanarPolygon*)(&getOccluder()))->write(out);
// Write hole list.
HoleList holeList = getHoleList();
int size = holeList.size();
out->writeInt(size);
for(int i=0; i<size; i++){
((ive::ConvexPlanarPolygon*)(&holeList[i]))->write(out);
}
}
void ConvexPlanarOccluder::read(DataInputStream* in){
// Peek on ConvexPlanarOccluder's identification.
int id = in->peekInt();
if(id == IVECONVEXPLANAROCCLUDER){
// Read ConvexPlanarOccluder's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("ConvexPlanarOccluder::read(): Could not cast this osg::ConvexPlanarOccluder to an osg::Object.");
// Read ConvexPlanarOccluder's properties
// Read planar polygon occluder.
osg::ConvexPlanarPolygon* cpp = &getOccluder();
((ive::ConvexPlanarPolygon*)(cpp))->read(in);
// Read hole list.
int size = in->readInt();
for(int i=0; i<size; i++){
osg::ConvexPlanarPolygon* cpp = new osg::ConvexPlanarPolygon();
((ive::ConvexPlanarPolygon*)(cpp))->read(in);
addHole(*cpp);
}
}
else{
throw Exception("ConvexPlanarOccluder::read(): Expected ConvexPlanarOccluder identification.");
}
}
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "InputParameters.h"
#include "MultiMooseEnum.h"
#include "gtest/gtest.h"
TEST(InputParameters, checkControlParamPrivateError)
{
try
{
InputParameters params = emptyInputParameters();
params.addPrivateParam<Real>("private", 1);
params.declareControllable("private");
params.checkParams("");
FAIL() << "checkParams failed to catch private control param";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("private parameter '' marked controllable") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
// This tests for the bug https://github.com/idaholab/moose/issues/8586.
// It makes sure that range-checked input file parameters comparison functions
// do absolute floating point comparisons instead of using a default epsilon.
TEST(InputParameters, checkRangeCheckedParam)
{
try
{
InputParameters params = emptyInputParameters();
params.addRangeCheckedParam<Real>("p", 1.000000000000001, "p = 1", "Some doc");
params.checkParams("");
FAIL() << "range checked input param failed to catch 1.000000000000001 != 1";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Range check failed for param") != std::string::npos)
<< "range check failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkControlParamTypeError)
{
try
{
InputParameters params = emptyInputParameters();
params.addParam<PostprocessorName>("pp_name", "make_it_valid", "Some doc");
params.declareControllable("pp_name");
params.checkParams("");
FAIL() << "checkParams failed to catch invalid control param type";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("non-controllable type") != std::string::npos)
<< "failed with unexpected error:" << msg;
}
}
TEST(InputParameters, checkControlParamValidError)
{
try
{
InputParameters params = emptyInputParameters();
params.declareControllable("not_valid");
params.checkParams("");
FAIL() << "checkParams failed to catch non existing control param";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("cannot be marked as controllable") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkSuppressedError)
{
try
{
InputParameters params = emptyInputParameters();
params.suppressParameter<int>("nonexistent");
FAIL() << "failed to error on supression of nonexisting parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Unable to suppress nonexistent parameter") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkSetDocString)
{
InputParameters params = emptyInputParameters();
params.addParam<Real>("little_guy", "What about that little guy?");
params.setDocString("little_guy", "That little guy, I wouldn't worry about that little_guy.");
ASSERT_TRUE(params.getDocString("little_guy")
.find("That little guy, I wouldn't worry about that little_guy.") !=
std::string::npos)
<< "retrieved doc string has unexpected value '" << params.getDocString("little_guy") << "'";
}
TEST(InputParameters, checkSetDocStringError)
{
try
{
InputParameters params = emptyInputParameters();
params.setDocString("little_guy", "That little guy, I wouldn't worry about that little_guy.");
FAIL() << "failed to error on attempt to set non-existing parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Unable to set the documentation string (using setDocString)") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
void
testBadParamName(const std::string & name)
{
try
{
InputParameters params = emptyInputParameters();
params.addParam<bool>(name, "Doc");
FAIL() << "failed to error on attempt to set invalid parameter name";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Invalid parameter name") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
/// Just make sure we don't allow invalid parameter names
TEST(InputParameters, checkParamName)
{
testBadParamName("p 0");
testBadParamName("p-0");
testBadParamName("p!0");
}
TEST(InputParameters, applyParameter)
{
InputParameters p1 = emptyInputParameters();
p1.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=0 bar=1", "foo"), "testing");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
InputParameters p2 = emptyInputParameters();
p2.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=42 bar=43", "foo"), "testing");
EXPECT_TRUE(p2.get<MultiMooseEnum>("enum").contains("foo"));
p2.set<MultiMooseEnum>("enum") = "bar";
p1.applyParameter(p2, "enum");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
}
TEST(InputParameters, applyParameters)
{
// First enum
InputParameters p1 = emptyInputParameters();
p1.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=0 bar=1", "foo"), "testing");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
// Second enum
InputParameters p2 = emptyInputParameters();
p2.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=42 bar=43", "foo"), "testing");
EXPECT_TRUE(p2.get<MultiMooseEnum>("enum").contains("foo"));
EXPECT_FALSE(p2.get<MultiMooseEnum>("enum").contains("bar"));
// Change second and apply to first
p2.set<MultiMooseEnum>("enum") = "bar";
p1.applyParameters(p2);
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("foo"));
// Change back first (in "quiet_mode") then reapply second, first should change again
p1.set<MultiMooseEnum>("enum", true) = "foo";
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
p1.applyParameters(p2);
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("foo"));
// Change back first then reapply second, first should not change
p1.set<MultiMooseEnum>("enum") = "foo";
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
p1.applyParameters(p2);
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
}
TEST(InputParameters, applyParametersPrivateOverride)
{
InputParameters p1 = emptyInputParameters();
p1.addPrivateParam<bool>("_flag", true);
EXPECT_TRUE(p1.get<bool>("_flag"));
InputParameters p2 = emptyInputParameters();
p2.addPrivateParam<bool>("_flag", false);
EXPECT_FALSE(p2.get<bool>("_flag"));
p1.applySpecificParameters(p2, {"_flag"}, true);
EXPECT_FALSE(p1.get<bool>("_flag"));
}
TEST(InputParameters, makeParamRequired)
{
InputParameters params = emptyInputParameters();
params.addParam<Real>("good_param", "documentation");
params.addParam<Real>("wrong_param_type", "documentation");
// Require existing parameter with the appropriate type
EXPECT_FALSE(params.isParamRequired("good_param"));
params.makeParamRequired<Real>("good_param");
EXPECT_TRUE(params.isParamRequired("good_param"));
// Require existing parameter with the wrong type
try
{
params.makeParamRequired<PostprocessorName>("wrong_param_type");
FAIL() << "failed to error on attempt to change a parameter type when making it required";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Unable to require nonexistent parameter: wrong_param_type") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
// Require non-existing parameter
try
{
params.makeParamRequired<PostprocessorName>("wrong_param_name");
FAIL() << "failed to error on attempt to require a non-existent parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Unable to require nonexistent parameter: wrong_param_name") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
<commit_msg>Unit tests for defaulted PPs (#14525)<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "InputParameters.h"
#include "MultiMooseEnum.h"
#include "gtest/gtest.h"
TEST(InputParameters, checkControlParamPrivateError)
{
try
{
InputParameters params = emptyInputParameters();
params.addPrivateParam<Real>("private", 1);
params.declareControllable("private");
params.checkParams("");
FAIL() << "checkParams failed to catch private control param";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("private parameter '' marked controllable") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
// This tests for the bug https://github.com/idaholab/moose/issues/8586.
// It makes sure that range-checked input file parameters comparison functions
// do absolute floating point comparisons instead of using a default epsilon.
TEST(InputParameters, checkRangeCheckedParam)
{
try
{
InputParameters params = emptyInputParameters();
params.addRangeCheckedParam<Real>("p", 1.000000000000001, "p = 1", "Some doc");
params.checkParams("");
FAIL() << "range checked input param failed to catch 1.000000000000001 != 1";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Range check failed for param") != std::string::npos)
<< "range check failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkControlParamTypeError)
{
try
{
InputParameters params = emptyInputParameters();
params.addParam<PostprocessorName>("pp_name", "make_it_valid", "Some doc");
params.declareControllable("pp_name");
params.checkParams("");
FAIL() << "checkParams failed to catch invalid control param type";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("non-controllable type") != std::string::npos)
<< "failed with unexpected error:" << msg;
}
}
TEST(InputParameters, checkControlParamValidError)
{
try
{
InputParameters params = emptyInputParameters();
params.declareControllable("not_valid");
params.checkParams("");
FAIL() << "checkParams failed to catch non existing control param";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("cannot be marked as controllable") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkSuppressedError)
{
try
{
InputParameters params = emptyInputParameters();
params.suppressParameter<int>("nonexistent");
FAIL() << "failed to error on supression of nonexisting parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Unable to suppress nonexistent parameter") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
TEST(InputParameters, checkSetDocString)
{
InputParameters params = emptyInputParameters();
params.addParam<Real>("little_guy", "What about that little guy?");
params.setDocString("little_guy", "That little guy, I wouldn't worry about that little_guy.");
ASSERT_TRUE(params.getDocString("little_guy")
.find("That little guy, I wouldn't worry about that little_guy.") !=
std::string::npos)
<< "retrieved doc string has unexpected value '" << params.getDocString("little_guy") << "'";
}
TEST(InputParameters, checkSetDocStringError)
{
try
{
InputParameters params = emptyInputParameters();
params.setDocString("little_guy", "That little guy, I wouldn't worry about that little_guy.");
FAIL() << "failed to error on attempt to set non-existing parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Unable to set the documentation string (using setDocString)") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
void
testBadParamName(const std::string & name)
{
try
{
InputParameters params = emptyInputParameters();
params.addParam<bool>(name, "Doc");
FAIL() << "failed to error on attempt to set invalid parameter name";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Invalid parameter name") != std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
/// Just make sure we don't allow invalid parameter names
TEST(InputParameters, checkParamName)
{
testBadParamName("p 0");
testBadParamName("p-0");
testBadParamName("p!0");
}
TEST(InputParameters, applyParameter)
{
InputParameters p1 = emptyInputParameters();
p1.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=0 bar=1", "foo"), "testing");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
InputParameters p2 = emptyInputParameters();
p2.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=42 bar=43", "foo"), "testing");
EXPECT_TRUE(p2.get<MultiMooseEnum>("enum").contains("foo"));
p2.set<MultiMooseEnum>("enum") = "bar";
p1.applyParameter(p2, "enum");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
}
TEST(InputParameters, applyParameters)
{
// First enum
InputParameters p1 = emptyInputParameters();
p1.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=0 bar=1", "foo"), "testing");
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
// Second enum
InputParameters p2 = emptyInputParameters();
p2.addParam<MultiMooseEnum>("enum", MultiMooseEnum("foo=42 bar=43", "foo"), "testing");
EXPECT_TRUE(p2.get<MultiMooseEnum>("enum").contains("foo"));
EXPECT_FALSE(p2.get<MultiMooseEnum>("enum").contains("bar"));
// Change second and apply to first
p2.set<MultiMooseEnum>("enum") = "bar";
p1.applyParameters(p2);
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("foo"));
// Change back first (in "quiet_mode") then reapply second, first should change again
p1.set<MultiMooseEnum>("enum", true) = "foo";
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
p1.applyParameters(p2);
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("foo"));
// Change back first then reapply second, first should not change
p1.set<MultiMooseEnum>("enum") = "foo";
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
p1.applyParameters(p2);
EXPECT_FALSE(p1.get<MultiMooseEnum>("enum").contains("bar"));
EXPECT_TRUE(p1.get<MultiMooseEnum>("enum").contains("foo"));
}
TEST(InputParameters, applyParametersPrivateOverride)
{
InputParameters p1 = emptyInputParameters();
p1.addPrivateParam<bool>("_flag", true);
EXPECT_TRUE(p1.get<bool>("_flag"));
InputParameters p2 = emptyInputParameters();
p2.addPrivateParam<bool>("_flag", false);
EXPECT_FALSE(p2.get<bool>("_flag"));
p1.applySpecificParameters(p2, {"_flag"}, true);
EXPECT_FALSE(p1.get<bool>("_flag"));
}
TEST(InputParameters, makeParamRequired)
{
InputParameters params = emptyInputParameters();
params.addParam<Real>("good_param", "documentation");
params.addParam<Real>("wrong_param_type", "documentation");
// Require existing parameter with the appropriate type
EXPECT_FALSE(params.isParamRequired("good_param"));
params.makeParamRequired<Real>("good_param");
EXPECT_TRUE(params.isParamRequired("good_param"));
// Require existing parameter with the wrong type
try
{
params.makeParamRequired<PostprocessorName>("wrong_param_type");
FAIL() << "failed to error on attempt to change a parameter type when making it required";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Unable to require nonexistent parameter: wrong_param_type") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
// Require non-existing parameter
try
{
params.makeParamRequired<PostprocessorName>("wrong_param_name");
FAIL() << "failed to error on attempt to require a non-existent parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
EXPECT_TRUE(msg.find("Unable to require nonexistent parameter: wrong_param_name") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
}
TEST(InputParameters, setPPandVofPP)
{
// programmatically set default value of PPName parameter
InputParameters p1 = emptyInputParameters();
p1.addParam<std::vector<PostprocessorName>>("pp_name", "testing");
p1.set<std::vector<PostprocessorName>>("pp_name") = {"first", "second", "third"};
// check if we have a vector of pps
EXPECT_TRUE(!p1.isSinglePostprocessor("pp_name")) << "Failed to detect vector of PPs";
// check what happens if default value is requested
/*
try
{
p1.hasDefaultPostprocessorValue("pp_name", 2);
FAIL() << "failed to error on supression of nonexisting parameter";
}
catch (const std::exception & e)
{
std::string msg(e.what());
ASSERT_TRUE(msg.find("Attempting to access _have_default_postprocessor_val") !=
std::string::npos)
<< "failed with unexpected error: " << msg;
}
*/
// EXPECT_EQ(p1.getDefaultPostprocessorValue("pp_name"), 1);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017, Randolph Voorhies, Shane Grant
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 cereal 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 RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CEREAL_TEST_DEFER_H_
#define CEREAL_TEST_DEFER_H_
#include "common.hpp"
struct DeferNode;
struct DeferRelation
{
std::shared_ptr<DeferNode> node;
int x;
std::string y;
template <class Archive>
void serialize( Archive & ar )
{
ar( node, x, y );
}
bool operator==( DeferRelation const & other ) const;
};
struct DeferNode
{
DeferNode() = default;
DeferNode( size_t id_, std::mt19937 & gen ) :
id(id_),
w(random_value<long>(gen)),
iser{random_value<int>(gen), random_value<int>(gen)},
ispl{random_value<int>(gen), random_value<int>(gen)},
eser{random_value<int>(gen), random_value<int>(gen)},
espl{random_value<int>(gen), random_value<int>(gen)},
relations(),
z(random_value<char>(gen))
{ }
size_t id;
long w;
StructInternalSerialize iser;
StructInternalSplit ispl;
StructExternalSerialize eser;
StructExternalSplit espl;
std::vector<DeferRelation> relations;
char z;
template <class Archive>
void serialize( Archive & ar )
{
ar( id, w,
cereal::defer( iser ),
cereal::defer( ispl ),
cereal::defer( eser ),
cereal::defer( espl ),
cereal::defer( relations ),
z );
}
bool operator==( DeferNode const & other ) const
{
bool relationsEqual = true;
if( relations.size() == other.relations.size() )
for( size_t i = 0; i < relations.size(); ++i )
relationsEqual &= relations[i] == other.relations[i];
else
relationsEqual = false;
return id == other.id && w == other.w &&
iser == other.iser && ispl == other.ispl &&
eser == other.eser && espl == other.espl &&
relationsEqual;
}
};
inline std::ostream& operator<<(std::ostream& os, DeferRelation const & s)
{
os << "[node(id): " << (s.node ? std::to_string(s.node->id) : "null") << " x: " << s.x << " y: " << s.y << "]";
return os;
}
bool DeferRelation::operator==( DeferRelation const & other ) const
{
return x == other.x && y == other.y && node->id == other.node->id;
}
inline std::ostream& operator<<(std::ostream& os, DeferNode const & s)
{
os << "[id: " << s.id << " w " << s.w << " iser " << s.iser;
os << " ispl " << s.ispl << " eser " << s.eser << " espl " << s.espl;
os << " relations (size: " << s.relations.size() << "): ";
for( auto & r : s.relations )
os << r;
os << " z " << s.z << "]";
return os;
}
template <class IArchive, class OArchive> inline
void test_defer()
{
std::random_device rd;
std::mt19937 gen(rd());
for(int ii=0; ii<100; ++ii)
{
size_t id = 0;
std::vector<std::shared_ptr<DeferNode>> o_nodes0(1);
for( auto & node : o_nodes0 )
node = std::make_shared<DeferNode>(id++, gen);
std::vector<std::shared_ptr<DeferNode>> o_nodes1(1);
for( auto & node : o_nodes1 )
node = std::make_shared<DeferNode>(id++, gen);
std::shuffle( o_nodes1.begin(), o_nodes1.end(), gen );
for( auto & node : o_nodes0 )
{
node->relations.resize( random_index( 0, 100, gen ) );
for( auto & r : node->relations )
r = {o_nodes0[random_index(0, o_nodes0.size() - 1, gen)],
random_value<int>(gen), random_basic_string<char>(gen)};
}
for( auto & node : o_nodes1 )
{
node->relations.resize( random_index( 0, 100, gen ) );
for( auto & r : node->relations )
r = {o_nodes0[random_index(0, o_nodes0.size() - 1, gen)],
random_value<int>(gen), random_basic_string<char>(gen)};
}
std::ostringstream os;
{
OArchive oar(os);
oar( o_nodes0 );
oar( o_nodes1 );
oar.serializeDeferments();
// TODO: throw exception if deferments not done when destructor fires
}
decltype(o_nodes0) i_nodes0;
decltype(o_nodes1) i_nodes1;
std::istringstream is(os.str());
{
IArchive iar(is);
iar( i_nodes0 );
iar( i_nodes1 );
iar.serializeDeferments();
}
check_ptr_collection(o_nodes0, i_nodes0);
check_ptr_collection(o_nodes1, i_nodes1);
}
}
#endif // CEREAL_TEST_DEFER_H_
<commit_msg>make msvc12 happy<commit_after>/*
Copyright (c) 2017, Randolph Voorhies, Shane Grant
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 cereal 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 RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CEREAL_TEST_DEFER_H_
#define CEREAL_TEST_DEFER_H_
#include "common.hpp"
struct DeferNode;
struct DeferRelation
{
std::shared_ptr<DeferNode> node;
int x;
std::string y;
template <class Archive>
void serialize( Archive & ar )
{
ar( node, x, y );
}
bool operator==( DeferRelation const & other ) const;
};
struct DeferNode
{
DeferNode() = default;
DeferNode( size_t id_, std::mt19937 & gen ) :
id(id_),
w(random_value<long>(gen)),
iser{random_value<int>(gen), random_value<int>(gen)},
ispl{random_value<int>(gen), random_value<int>(gen)},
eser{random_value<int>(gen), random_value<int>(gen)},
espl{random_value<int>(gen), random_value<int>(gen)},
relations(),
z(random_value<char>(gen))
{ }
size_t id;
long w;
StructInternalSerialize iser;
StructInternalSplit ispl;
StructExternalSerialize eser;
StructExternalSplit espl;
std::vector<DeferRelation> relations;
char z;
template <class Archive>
void serialize( Archive & ar )
{
ar( id, w,
cereal::defer( iser ),
cereal::defer( ispl ),
cereal::defer( eser ),
cereal::defer( espl ),
cereal::defer( relations ),
z );
}
bool operator==( DeferNode const & other ) const
{
bool relationsEqual = true;
if( relations.size() == other.relations.size() )
for( size_t i = 0; i < relations.size(); ++i )
relationsEqual &= relations[i] == other.relations[i];
else
relationsEqual = false;
return id == other.id && w == other.w &&
iser == other.iser && ispl == other.ispl &&
eser == other.eser && espl == other.espl &&
relationsEqual;
}
};
inline std::ostream& operator<<(std::ostream& os, DeferRelation const & s)
{
os << "[node(id): " << (s.node ? std::to_string(s.node->id) : "null") << " x: " << s.x << " y: " << s.y << "]";
return os;
}
bool DeferRelation::operator==( DeferRelation const & other ) const
{
return x == other.x && y == other.y && node->id == other.node->id;
}
inline std::ostream& operator<<(std::ostream& os, DeferNode const & s)
{
os << "[id: " << s.id << " w " << s.w << " iser " << s.iser;
os << " ispl " << s.ispl << " eser " << s.eser << " espl " << s.espl;
os << " relations (size: " << s.relations.size() << "): ";
for( auto & r : s.relations )
os << r;
os << " z " << s.z << "]";
return os;
}
template <class IArchive, class OArchive> inline
void test_defer()
{
std::random_device rd;
std::mt19937 gen(rd());
for(int ii=0; ii<100; ++ii)
{
size_t id = 0;
std::vector<std::shared_ptr<DeferNode>> o_nodes0(1);
for( auto & node : o_nodes0 )
node = std::make_shared<DeferNode>(id++, gen);
std::vector<std::shared_ptr<DeferNode>> o_nodes1(1);
for( auto & node : o_nodes1 )
node = std::make_shared<DeferNode>(id++, gen);
std::shuffle( o_nodes1.begin(), o_nodes1.end(), gen );
for( auto & node : o_nodes0 )
{
node->relations.resize( random_index( 0, 100, gen ) );
for (auto & r : node->relations)
{
r = { o_nodes0[random_index( 0, o_nodes0.size() - 1, gen )],
random_value<int>( gen ), random_basic_string<char>( gen ) };
}
}
for( auto & node : o_nodes1 )
{
node->relations.resize( random_index( 0, 100, gen ) );
for (auto & r : node->relations)
{
r = { o_nodes0[random_index( 0, o_nodes0.size() - 1, gen )],
random_value<int>( gen ), random_basic_string<char>( gen ) };
}
}
std::ostringstream os;
{
OArchive oar(os);
oar( o_nodes0 );
oar( o_nodes1 );
oar.serializeDeferments();
// TODO: throw exception if deferments not done when destructor fires
}
decltype(o_nodes0) i_nodes0;
decltype(o_nodes1) i_nodes1;
std::istringstream is(os.str());
{
IArchive iar(is);
iar( i_nodes0 );
iar( i_nodes1 );
iar.serializeDeferments();
}
check_ptr_collection(o_nodes0, i_nodes0);
check_ptr_collection(o_nodes1, i_nodes1);
}
}
#endif // CEREAL_TEST_DEFER_H_
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sdr/contact/viewcontactofsdrpathobj.hxx>
#include <svx/svdopath.hxx>
#include <svx/sdr/primitive2d/sdrattributecreator.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <sdr/primitive2d/sdrpathprimitive2d.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>
namespace sdr
{
namespace contact
{
ViewContactOfSdrPathObj::ViewContactOfSdrPathObj(SdrPathObj& rPathObj)
: ViewContactOfTextObj(rPathObj)
{
}
ViewContactOfSdrPathObj::~ViewContactOfSdrPathObj()
{
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfSdrPathObj::createViewIndependentPrimitive2DSequence() const
{
const SfxItemSet& rItemSet = GetPathObj().GetMergedItemSet();
const drawinglayer::attribute::SdrLineFillShadowTextAttribute aAttribute(
drawinglayer::primitive2d::createNewSdrLineFillShadowTextAttribute(
rItemSet,
GetPathObj().getText(0),
false));
basegfx::B2DPolyPolygon aUnitPolyPolygon(GetPathObj().GetPathPoly());
Point aGridOff = GetPathObj().GetGridOffset();
// Hack for calc, transform position of object according
// to current zoom so as objects relative position to grid
// appears stable
aUnitPolyPolygon.transform( basegfx::tools::createTranslateB2DHomMatrix( aGridOff.X(), aGridOff.Y() ) );
sal_uInt32 nPolyCount(aUnitPolyPolygon.count());
sal_uInt32 nPointCount(0);
for(sal_uInt32 a(0); a < nPolyCount; a++)
{
nPointCount += aUnitPolyPolygon.getB2DPolygon(a).count();
}
if(!nPointCount)
{
OSL_FAIL("PolyPolygon object without geometry detected, this should not be created (!)");
basegfx::B2DPolygon aFallbackLine;
aFallbackLine.append(basegfx::B2DPoint(0.0, 0.0));
aFallbackLine.append(basegfx::B2DPoint(1000.0, 1000.0));
aUnitPolyPolygon = basegfx::B2DPolyPolygon(aFallbackLine);
nPolyCount = 1;
}
// prepare object transformation and unit polygon (direct model data)
basegfx::B2DHomMatrix aObjectMatrix;
const bool bIsLine(
!aUnitPolyPolygon.areControlPointsUsed()
&& 1 == nPolyCount
&& 2 == aUnitPolyPolygon.getB2DPolygon(0).count());
if(bIsLine)
{
// special handling for single line mode (2 points)
const basegfx::B2DPolygon aSubPolygon(aUnitPolyPolygon.getB2DPolygon(0));
const basegfx::B2DPoint aStart(aSubPolygon.getB2DPoint(0));
const basegfx::B2DPoint aEnd(aSubPolygon.getB2DPoint(1));
const basegfx::B2DVector aLine(aEnd - aStart);
// #i102548# create new unit polygon for line (horizontal)
basegfx::B2DPolygon aNewPolygon;
aNewPolygon.append(basegfx::B2DPoint(0.0, 0.0));
aNewPolygon.append(basegfx::B2DPoint(1.0, 0.0));
aUnitPolyPolygon.setB2DPolygon(0, aNewPolygon);
// #i102548# fill objectMatrix with rotation and offset (no shear for lines)
aObjectMatrix = basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix(
aLine.getLength(), 1.0,
0.0,
atan2(aLine.getY(), aLine.getX()),
aStart.getX(), aStart.getY());
}
else
{
// #i102548# create unscaled, unsheared, unrotated and untranslated polygon
// (unit polygon) by creating the object matrix and back-transforming the polygon
const basegfx::B2DRange aObjectRange(basegfx::tools::getRange(aUnitPolyPolygon));
const GeoStat& rGeoStat(GetPathObj().GetGeoStat());
const double fWidth(aObjectRange.getWidth());
const double fHeight(aObjectRange.getHeight());
const double fScaleX(basegfx::fTools::equalZero(fWidth) ? 1.0 : fWidth);
const double fScaleY(basegfx::fTools::equalZero(fHeight) ? 1.0 : fHeight);
aObjectMatrix = basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix(
fScaleX, fScaleY,
rGeoStat.nShearAngle ? tan((36000 - rGeoStat.nShearAngle) * F_PI18000) : 0.0,
rGeoStat.nRotationAngle ? (36000 - rGeoStat.nRotationAngle) * F_PI18000 : 0.0,
aObjectRange.getMinX(), aObjectRange.getMinY());
// create unit polygon from object's absolute path
basegfx::B2DHomMatrix aInverse(aObjectMatrix);
aInverse.invert();
aUnitPolyPolygon.transform(aInverse);
}
// create primitive. Always create primitives to allow the decomposition of
// SdrPathPrimitive2D to create needed invisible elements for HitTest and/or BoundRect
const drawinglayer::primitive2d::Primitive2DReference xReference(
new drawinglayer::primitive2d::SdrPathPrimitive2D(
aObjectMatrix,
aAttribute,
aUnitPolyPolygon));
return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}
} // end of namespace contact
} // end of namespace sdr
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>refactor ensuring polygon has at least a line in it<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sdr/contact/viewcontactofsdrpathobj.hxx>
#include <svx/svdopath.hxx>
#include <svx/sdr/primitive2d/sdrattributecreator.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <sdr/primitive2d/sdrpathprimitive2d.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>
namespace sdr
{
namespace contact
{
ViewContactOfSdrPathObj::ViewContactOfSdrPathObj(SdrPathObj& rPathObj)
: ViewContactOfTextObj(rPathObj)
{
}
ViewContactOfSdrPathObj::~ViewContactOfSdrPathObj()
{
}
static sal_uInt32 ensureGeometry(basegfx::B2DPolyPolygon& rUnitPolyPolygon)
{
sal_uInt32 nPolyCount(rUnitPolyPolygon.count());
sal_uInt32 nPointCount(0);
for(sal_uInt32 a(0); a < nPolyCount; a++)
{
nPointCount += rUnitPolyPolygon.getB2DPolygon(a).count();
}
if(!nPointCount)
{
OSL_FAIL("PolyPolygon object without geometry detected, this should not be created (!)");
basegfx::B2DPolygon aFallbackLine;
aFallbackLine.append(basegfx::B2DPoint(0.0, 0.0));
aFallbackLine.append(basegfx::B2DPoint(1000.0, 1000.0));
rUnitPolyPolygon = basegfx::B2DPolyPolygon(aFallbackLine);
nPolyCount = 1;
}
return nPolyCount;
}
drawinglayer::primitive2d::Primitive2DSequence ViewContactOfSdrPathObj::createViewIndependentPrimitive2DSequence() const
{
const SfxItemSet& rItemSet = GetPathObj().GetMergedItemSet();
const drawinglayer::attribute::SdrLineFillShadowTextAttribute aAttribute(
drawinglayer::primitive2d::createNewSdrLineFillShadowTextAttribute(
rItemSet,
GetPathObj().getText(0),
false));
basegfx::B2DPolyPolygon aUnitPolyPolygon(GetPathObj().GetPathPoly());
Point aGridOff = GetPathObj().GetGridOffset();
// Hack for calc, transform position of object according
// to current zoom so as objects relative position to grid
// appears stable
aUnitPolyPolygon.transform( basegfx::tools::createTranslateB2DHomMatrix( aGridOff.X(), aGridOff.Y() ) );
sal_uInt32 nPolyCount(ensureGeometry(aUnitPolyPolygon));
// prepare object transformation and unit polygon (direct model data)
basegfx::B2DHomMatrix aObjectMatrix;
const bool bIsLine(
!aUnitPolyPolygon.areControlPointsUsed()
&& 1 == nPolyCount
&& 2 == aUnitPolyPolygon.getB2DPolygon(0).count());
if(bIsLine)
{
// special handling for single line mode (2 points)
const basegfx::B2DPolygon aSubPolygon(aUnitPolyPolygon.getB2DPolygon(0));
const basegfx::B2DPoint aStart(aSubPolygon.getB2DPoint(0));
const basegfx::B2DPoint aEnd(aSubPolygon.getB2DPoint(1));
const basegfx::B2DVector aLine(aEnd - aStart);
// #i102548# create new unit polygon for line (horizontal)
basegfx::B2DPolygon aNewPolygon;
aNewPolygon.append(basegfx::B2DPoint(0.0, 0.0));
aNewPolygon.append(basegfx::B2DPoint(1.0, 0.0));
aUnitPolyPolygon.setB2DPolygon(0, aNewPolygon);
// #i102548# fill objectMatrix with rotation and offset (no shear for lines)
aObjectMatrix = basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix(
aLine.getLength(), 1.0,
0.0,
atan2(aLine.getY(), aLine.getX()),
aStart.getX(), aStart.getY());
}
else
{
// #i102548# create unscaled, unsheared, unrotated and untranslated polygon
// (unit polygon) by creating the object matrix and back-transforming the polygon
const basegfx::B2DRange aObjectRange(basegfx::tools::getRange(aUnitPolyPolygon));
const GeoStat& rGeoStat(GetPathObj().GetGeoStat());
const double fWidth(aObjectRange.getWidth());
const double fHeight(aObjectRange.getHeight());
const double fScaleX(basegfx::fTools::equalZero(fWidth) ? 1.0 : fWidth);
const double fScaleY(basegfx::fTools::equalZero(fHeight) ? 1.0 : fHeight);
aObjectMatrix = basegfx::tools::createScaleShearXRotateTranslateB2DHomMatrix(
fScaleX, fScaleY,
rGeoStat.nShearAngle ? tan((36000 - rGeoStat.nShearAngle) * F_PI18000) : 0.0,
rGeoStat.nRotationAngle ? (36000 - rGeoStat.nRotationAngle) * F_PI18000 : 0.0,
aObjectRange.getMinX(), aObjectRange.getMinY());
// create unit polygon from object's absolute path
basegfx::B2DHomMatrix aInverse(aObjectMatrix);
aInverse.invert();
aUnitPolyPolygon.transform(aInverse);
}
// create primitive. Always create primitives to allow the decomposition of
// SdrPathPrimitive2D to create needed invisible elements for HitTest and/or BoundRect
const drawinglayer::primitive2d::Primitive2DReference xReference(
new drawinglayer::primitive2d::SdrPathPrimitive2D(
aObjectMatrix,
aAttribute,
aUnitPolyPolygon));
return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);
}
} // end of namespace contact
} // end of namespace sdr
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "mock/serializer_filestream.hpp"
#include "buffer_cache/buffer_cache.hpp"
#include "perfmon/core.hpp"
namespace mock {
// Maybe we should have just used a blob for this.
serializer_file_read_stream_t::serializer_file_read_stream_t(serializer_t *serializer)
: known_size_(-1), position_(0) {
mirrored_cache_config_t config;
cache_.init(new cache_t(serializer, config, &get_global_perfmon_collection()));
if (cache_->contains_block(0)) {
// SAMRSI: Call a different txn constructor, instead of passing a NULL disk_ack_signal?
transaction_t txn(cache_.get(), rwi_read, 0, repli_timestamp_t::invalid, order_token_t::ignore, NULL);
buf_lock_t bufzero(&txn, 0, rwi_read);
const void *data = bufzero.get_data_read();
known_size_ = *static_cast<const int64_t *>(data);
guarantee(known_size_ >= 0);
}
}
serializer_file_read_stream_t::~serializer_file_read_stream_t() { }
MUST_USE int64_t serializer_file_read_stream_t::read(void *p, int64_t n) {
if (known_size_ == -1) {
return -1;
}
guarantee(n >= 0);
const int64_t real_size = known_size_ + sizeof(int64_t);
const int64_t real_position = position_ + sizeof(int64_t);
if (real_position == real_size || n == 0) {
return 0;
}
const block_size_t block_size = cache_->get_block_size();
const int64_t block_number = real_position / block_size.value();
const int64_t block_offset = real_position % block_size.value();
const int64_t s = std::min(real_position + n, real_size);
const int64_t end_block_offset = (s < block_size.value() * (block_number + 1)) ? s % block_size.value() : block_size.value();
const int64_t num_copied = end_block_offset - block_offset;
rassert(num_copied > 0);
if (block_number >= MAX_BLOCK_ID) {
return -1;
}
// SAMRSI: Call a different txn constructor, instead of passing a NULL disk_ack_signal?
transaction_t txn(cache_.get(), rwi_read, 0, repli_timestamp_t::invalid, order_token_t::ignore, NULL);
buf_lock_t block(&txn, block_number, rwi_read);
const char *data = static_cast<const char *>(block.get_data_read());
memcpy(p, data + block_offset, num_copied);
return num_copied;
}
serializer_file_write_stream_t::serializer_file_write_stream_t(serializer_t *serializer) : size_(0) {
cache_t::create(serializer);
mirrored_cache_config_t config;
cache_.init(new cache_t(serializer, config, &get_global_perfmon_collection()));
// SAMRSI: Pass the disk_ack_signal as a parameter?
sync_callback_t disk_ack_signal;
{
transaction_t txn(cache_.get(), rwi_write, 1, repli_timestamp_t::invalid, order_token_t::ignore, &disk_ack_signal);
// Hold the size block during writes, to lock out other writers.
buf_lock_t z(&txn, 0, rwi_write);
int64_t *p = static_cast<int64_t *>(z.get_data_write());
*p = 0;
for (block_id_t i = 1; i < MAX_BLOCK_ID && cache_->contains_block(i); ++i) {
buf_lock_t b(&txn, i, rwi_write);
b.mark_deleted();
}
}
// SAMRSI: Wait here?
disk_ack_signal.wait();
}
serializer_file_write_stream_t::~serializer_file_write_stream_t() { }
MUST_USE int64_t serializer_file_write_stream_t::write(const void *p, int64_t n) {
const char *chp = static_cast<const char *>(p);
const int block_size = cache_->get_block_size().value();
// SAMRSI: Construct a disk_ack_signal here? As a parameter? (No, we can't.) Wait on the
// signal? Construct and wait on the disk ack signal as configured by a boolean parameter
// to the serializer_file_write_stream constructor?
sync_callback_t disk_ack_signal;
transaction_t txn(cache_.get(), rwi_write, 2 + n / block_size, repli_timestamp_t::invalid, order_token_t::ignore, &disk_ack_signal);
// Hold the size block during writes, to lock out other writers.
buf_lock_t z(&txn, 0, rwi_write);
int64_t *const size_ptr = static_cast<int64_t *>(z.get_data_write());
guarantee(*size_ptr == size_);
int64_t offset = size_ + sizeof(int64_t);
const int64_t end_offset = offset + n;
while (offset < end_offset) {
int64_t block_id = offset / block_size;
guarantee(block_id <= MAX_BLOCK_ID);
if (block_id >= MAX_BLOCK_ID) {
return -1;
}
buf_lock_t block;
buf_lock_t *b = &z;
if (block_id > 0) {
buf_lock_t tmp(&txn, block_id, rwi_write);
block.swap(tmp);
b = █
}
const int64_t block_offset = offset % block_size;
const int64_t end_block_offset = end_offset / block_size == block_id ? end_offset % block_size : block_size;
char *const buf = static_cast<char *>(b->get_data_write());
const int64_t num_written = end_block_offset - block_offset;
guarantee(num_written > 0);
memcpy(buf + block_offset, chp, num_written);
offset += num_written;
}
size_ += n;
*size_ptr = size_;
return n;
}
} // namespace mock
<commit_msg>Handled a couple how-to-construct-the-transaction disk_ack_signals in serializer_filestream.cc.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "mock/serializer_filestream.hpp"
#include "buffer_cache/buffer_cache.hpp"
#include "perfmon/core.hpp"
namespace mock {
// Maybe we should have just used a blob for this.
serializer_file_read_stream_t::serializer_file_read_stream_t(serializer_t *serializer)
: known_size_(-1), position_(0) {
mirrored_cache_config_t config;
cache_.init(new cache_t(serializer, config, &get_global_perfmon_collection()));
if (cache_->contains_block(0)) {
transaction_t txn(cache_.get(), rwi_read, order_token_t::ignore);
buf_lock_t bufzero(&txn, 0, rwi_read);
const void *data = bufzero.get_data_read();
known_size_ = *static_cast<const int64_t *>(data);
guarantee(known_size_ >= 0);
}
}
serializer_file_read_stream_t::~serializer_file_read_stream_t() { }
MUST_USE int64_t serializer_file_read_stream_t::read(void *p, int64_t n) {
if (known_size_ == -1) {
return -1;
}
guarantee(n >= 0);
const int64_t real_size = known_size_ + sizeof(int64_t);
const int64_t real_position = position_ + sizeof(int64_t);
if (real_position == real_size || n == 0) {
return 0;
}
const block_size_t block_size = cache_->get_block_size();
const int64_t block_number = real_position / block_size.value();
const int64_t block_offset = real_position % block_size.value();
const int64_t s = std::min(real_position + n, real_size);
const int64_t end_block_offset = (s < block_size.value() * (block_number + 1)) ? s % block_size.value() : block_size.value();
const int64_t num_copied = end_block_offset - block_offset;
rassert(num_copied > 0);
if (block_number >= MAX_BLOCK_ID) {
return -1;
}
transaction_t txn(cache_.get(), rwi_read, order_token_t::ignore);
buf_lock_t block(&txn, block_number, rwi_read);
const char *data = static_cast<const char *>(block.get_data_read());
memcpy(p, data + block_offset, num_copied);
return num_copied;
}
serializer_file_write_stream_t::serializer_file_write_stream_t(serializer_t *serializer) : size_(0) {
cache_t::create(serializer);
mirrored_cache_config_t config;
cache_.init(new cache_t(serializer, config, &get_global_perfmon_collection()));
// SAMRSI: Pass the disk_ack_signal as a parameter?
sync_callback_t disk_ack_signal;
{
transaction_t txn(cache_.get(), rwi_write, 1, repli_timestamp_t::invalid, order_token_t::ignore, &disk_ack_signal);
// Hold the size block during writes, to lock out other writers.
buf_lock_t z(&txn, 0, rwi_write);
int64_t *p = static_cast<int64_t *>(z.get_data_write());
*p = 0;
for (block_id_t i = 1; i < MAX_BLOCK_ID && cache_->contains_block(i); ++i) {
buf_lock_t b(&txn, i, rwi_write);
b.mark_deleted();
}
}
// SAMRSI: Wait here?
disk_ack_signal.wait();
}
serializer_file_write_stream_t::~serializer_file_write_stream_t() { }
MUST_USE int64_t serializer_file_write_stream_t::write(const void *p, int64_t n) {
const char *chp = static_cast<const char *>(p);
const int block_size = cache_->get_block_size().value();
// SAMRSI: Construct a disk_ack_signal here? As a parameter? (No, we can't.) Wait on the
// signal? Construct and wait on the disk ack signal as configured by a boolean parameter
// to the serializer_file_write_stream constructor?
sync_callback_t disk_ack_signal;
transaction_t txn(cache_.get(), rwi_write, 2 + n / block_size, repli_timestamp_t::invalid, order_token_t::ignore, &disk_ack_signal);
// Hold the size block during writes, to lock out other writers.
buf_lock_t z(&txn, 0, rwi_write);
int64_t *const size_ptr = static_cast<int64_t *>(z.get_data_write());
guarantee(*size_ptr == size_);
int64_t offset = size_ + sizeof(int64_t);
const int64_t end_offset = offset + n;
while (offset < end_offset) {
int64_t block_id = offset / block_size;
guarantee(block_id <= MAX_BLOCK_ID);
if (block_id >= MAX_BLOCK_ID) {
return -1;
}
buf_lock_t block;
buf_lock_t *b = &z;
if (block_id > 0) {
buf_lock_t tmp(&txn, block_id, rwi_write);
block.swap(tmp);
b = █
}
const int64_t block_offset = offset % block_size;
const int64_t end_block_offset = end_offset / block_size == block_id ? end_offset % block_size : block_size;
char *const buf = static_cast<char *>(b->get_data_write());
const int64_t num_written = end_block_offset - block_offset;
guarantee(num_written > 0);
memcpy(buf + block_offset, chp, num_written);
offset += num_written;
}
size_ += n;
*size_ptr = size_;
return n;
}
} // namespace mock
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/lite/delegates/xnnpack/reduce_tester.h"
#include <array>
#include <cstdint>
#include <functional>
#include <numeric>
#include <random>
#include <vector>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/version.h"
namespace tflite {
namespace xnnpack {
void ReduceTester::Test(tflite::BuiltinOperator reduce_op,
TfLiteDelegate* delegate) const {
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto input_rng = std::bind(
std::uniform_real_distribution<float>(-15.0f, 15.0f), std::ref(rng));
std::vector<char> buffer = CreateTfLiteModel(reduce_op);
const Model* model = GetModel(buffer.data());
std::unique_ptr<Interpreter> delegate_interpreter;
ASSERT_EQ(
InterpreterBuilder(model, ::tflite::ops::builtin::BuiltinOpResolver())(
&delegate_interpreter),
kTfLiteOk);
std::unique_ptr<Interpreter> default_interpreter;
ASSERT_EQ(
InterpreterBuilder(model, ::tflite::ops::builtin::BuiltinOpResolver())(
&default_interpreter),
kTfLiteOk);
ASSERT_TRUE(delegate_interpreter);
ASSERT_TRUE(default_interpreter);
ASSERT_EQ(delegate_interpreter->inputs().size(), 1);
ASSERT_EQ(default_interpreter->inputs().size(), 1);
ASSERT_EQ(delegate_interpreter->outputs().size(), 1);
ASSERT_EQ(default_interpreter->outputs().size(), 1);
ASSERT_EQ(delegate_interpreter->AllocateTensors(), kTfLiteOk);
ASSERT_EQ(default_interpreter->AllocateTensors(), kTfLiteOk);
ASSERT_EQ(delegate_interpreter->ModifyGraphWithDelegate(delegate), kTfLiteOk);
float* default_input_data = default_interpreter->typed_tensor<float>(
default_interpreter->inputs()[0]);
std::generate(default_input_data, default_input_data + InputSize(),
std::ref(input_rng));
float* delegate_input_data = delegate_interpreter->typed_tensor<float>(
delegate_interpreter->inputs()[0]);
std::copy(default_input_data, default_input_data + InputSize(),
delegate_input_data);
ASSERT_EQ(default_interpreter->Invoke(), kTfLiteOk);
ASSERT_EQ(delegate_interpreter->Invoke(), kTfLiteOk);
float* default_output_data = default_interpreter->typed_tensor<float>(
default_interpreter->outputs()[0]);
float* delegate_output_data = delegate_interpreter->typed_tensor<float>(
delegate_interpreter->outputs()[0]);
const int32_t output_size = OutputSize();
for (size_t i = 0; i < output_size; i++) {
ASSERT_NEAR(
default_output_data[i], delegate_output_data[i],
std::numeric_limits<float>::epsilon() *
std::max(std::abs(default_output_data[i]) * RelativeTolerance(),
1.0f));
}
}
std::vector<char> ReduceTester::CreateTfLiteModel(
tflite::BuiltinOperator reduce_op) const {
flatbuffers::FlatBufferBuilder builder;
flatbuffers::Offset<OperatorCode> operator_code =
CreateOperatorCode(builder, reduce_op);
const std::array<flatbuffers::Offset<Buffer>, 2> buffers{{
CreateBuffer(builder, builder.CreateVector({})),
CreateBuffer(builder, builder.CreateVector(
reinterpret_cast<const uint8_t*>(Axes().data()),
sizeof(int32_t) * Axes().size())),
}};
const std::vector<int32_t> output_shape = OutputShape();
const std::array<int32_t, 1> axes_shape{
{static_cast<int32_t>(Axes().size())}};
const std::array<flatbuffers::Offset<Tensor>, 3> tensors{{
CreateTensor(builder,
builder.CreateVector<int32_t>(InputShape().data(),
InputShape().size()),
TensorType_FLOAT32),
CreateTensor(
builder,
builder.CreateVector<int32_t>(axes_shape.data(), axes_shape.size()),
TensorType_INT32, /*buffer=*/1),
CreateTensor(builder,
builder.CreateVector<int32_t>(output_shape.data(),
output_shape.size()),
TensorType_FLOAT32),
}};
const flatbuffers::Offset<ReducerOptions> reducer_options =
CreateReducerOptions(builder, KeepDims());
const std::array<int32_t, 2> op_inputs{{0, 1}};
const std::array<int32_t, 1> op_outputs{{2}};
flatbuffers::Offset<Operator> op = CreateOperator(
builder, /*opcode_index=*/0,
builder.CreateVector<int32_t>(op_inputs.data(), op_inputs.size()),
builder.CreateVector<int32_t>(op_outputs.data(), op_outputs.size()),
tflite::BuiltinOptions_ReducerOptions, reducer_options.Union());
const std::array<int32_t, 1> subgraph_inputs{{0}};
const std::array<int32_t, 1> subgraph_outputs{{2}};
flatbuffers::Offset<SubGraph> subgraph = CreateSubGraph(
builder, builder.CreateVector(tensors.data(), tensors.size()),
builder.CreateVector<int32_t>(subgraph_inputs.data(),
subgraph_inputs.size()),
builder.CreateVector<int32_t>(subgraph_outputs.data(),
subgraph_outputs.size()),
builder.CreateVector(&op, 1));
flatbuffers::Offset<flatbuffers::String> description =
builder.CreateString("Reduce model");
flatbuffers::Offset<Model> model_buffer = CreateModel(
builder, TFLITE_SCHEMA_VERSION, builder.CreateVector(&operator_code, 1),
builder.CreateVector(&subgraph, 1), description,
builder.CreateVector(buffers.data(), buffers.size()));
builder.Finish(model_buffer);
return std::vector<char>(builder.GetBufferPointer(),
builder.GetBufferPointer() + builder.GetSize());
}
int32_t ReduceTester::ComputeSize(const std::vector<int32_t>& shape) {
return std::accumulate(shape.cbegin(), shape.cend(), 1,
std::multiplies<int32_t>());
}
} // namespace xnnpack
} // namespace tflite
<commit_msg>Avoid numerical stability issues in MEAN test<commit_after>/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/lite/delegates/xnnpack/reduce_tester.h"
#include <array>
#include <cstdint>
#include <functional>
#include <numeric>
#include <random>
#include <vector>
#include <gtest/gtest.h>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/version.h"
namespace tflite {
namespace xnnpack {
void ReduceTester::Test(tflite::BuiltinOperator reduce_op,
TfLiteDelegate* delegate) const {
std::random_device random_device;
auto rng = std::mt19937(random_device());
auto input_rng =
std::bind(std::uniform_real_distribution<float>(), std::ref(rng));
std::vector<char> buffer = CreateTfLiteModel(reduce_op);
const Model* model = GetModel(buffer.data());
std::unique_ptr<Interpreter> delegate_interpreter;
ASSERT_EQ(
InterpreterBuilder(model, ::tflite::ops::builtin::BuiltinOpResolver())(
&delegate_interpreter),
kTfLiteOk);
std::unique_ptr<Interpreter> default_interpreter;
ASSERT_EQ(
InterpreterBuilder(model, ::tflite::ops::builtin::BuiltinOpResolver())(
&default_interpreter),
kTfLiteOk);
ASSERT_TRUE(delegate_interpreter);
ASSERT_TRUE(default_interpreter);
ASSERT_EQ(delegate_interpreter->inputs().size(), 1);
ASSERT_EQ(default_interpreter->inputs().size(), 1);
ASSERT_EQ(delegate_interpreter->outputs().size(), 1);
ASSERT_EQ(default_interpreter->outputs().size(), 1);
ASSERT_EQ(delegate_interpreter->AllocateTensors(), kTfLiteOk);
ASSERT_EQ(default_interpreter->AllocateTensors(), kTfLiteOk);
ASSERT_EQ(delegate_interpreter->ModifyGraphWithDelegate(delegate), kTfLiteOk);
float* default_input_data = default_interpreter->typed_tensor<float>(
default_interpreter->inputs()[0]);
std::generate(default_input_data, default_input_data + InputSize(),
std::ref(input_rng));
float* delegate_input_data = delegate_interpreter->typed_tensor<float>(
delegate_interpreter->inputs()[0]);
std::copy(default_input_data, default_input_data + InputSize(),
delegate_input_data);
ASSERT_EQ(default_interpreter->Invoke(), kTfLiteOk);
ASSERT_EQ(delegate_interpreter->Invoke(), kTfLiteOk);
float* default_output_data = default_interpreter->typed_tensor<float>(
default_interpreter->outputs()[0]);
float* delegate_output_data = delegate_interpreter->typed_tensor<float>(
delegate_interpreter->outputs()[0]);
const int32_t output_size = OutputSize();
for (size_t i = 0; i < output_size; i++) {
ASSERT_NEAR(
default_output_data[i], delegate_output_data[i],
std::numeric_limits<float>::epsilon() *
std::max(std::abs(default_output_data[i]) * RelativeTolerance(),
1.0f));
}
}
std::vector<char> ReduceTester::CreateTfLiteModel(
tflite::BuiltinOperator reduce_op) const {
flatbuffers::FlatBufferBuilder builder;
flatbuffers::Offset<OperatorCode> operator_code =
CreateOperatorCode(builder, reduce_op);
const std::array<flatbuffers::Offset<Buffer>, 2> buffers{{
CreateBuffer(builder, builder.CreateVector({})),
CreateBuffer(builder, builder.CreateVector(
reinterpret_cast<const uint8_t*>(Axes().data()),
sizeof(int32_t) * Axes().size())),
}};
const std::vector<int32_t> output_shape = OutputShape();
const std::array<int32_t, 1> axes_shape{
{static_cast<int32_t>(Axes().size())}};
const std::array<flatbuffers::Offset<Tensor>, 3> tensors{{
CreateTensor(builder,
builder.CreateVector<int32_t>(InputShape().data(),
InputShape().size()),
TensorType_FLOAT32),
CreateTensor(
builder,
builder.CreateVector<int32_t>(axes_shape.data(), axes_shape.size()),
TensorType_INT32, /*buffer=*/1),
CreateTensor(builder,
builder.CreateVector<int32_t>(output_shape.data(),
output_shape.size()),
TensorType_FLOAT32),
}};
const flatbuffers::Offset<ReducerOptions> reducer_options =
CreateReducerOptions(builder, KeepDims());
const std::array<int32_t, 2> op_inputs{{0, 1}};
const std::array<int32_t, 1> op_outputs{{2}};
flatbuffers::Offset<Operator> op = CreateOperator(
builder, /*opcode_index=*/0,
builder.CreateVector<int32_t>(op_inputs.data(), op_inputs.size()),
builder.CreateVector<int32_t>(op_outputs.data(), op_outputs.size()),
tflite::BuiltinOptions_ReducerOptions, reducer_options.Union());
const std::array<int32_t, 1> subgraph_inputs{{0}};
const std::array<int32_t, 1> subgraph_outputs{{2}};
flatbuffers::Offset<SubGraph> subgraph = CreateSubGraph(
builder, builder.CreateVector(tensors.data(), tensors.size()),
builder.CreateVector<int32_t>(subgraph_inputs.data(),
subgraph_inputs.size()),
builder.CreateVector<int32_t>(subgraph_outputs.data(),
subgraph_outputs.size()),
builder.CreateVector(&op, 1));
flatbuffers::Offset<flatbuffers::String> description =
builder.CreateString("Reduce model");
flatbuffers::Offset<Model> model_buffer = CreateModel(
builder, TFLITE_SCHEMA_VERSION, builder.CreateVector(&operator_code, 1),
builder.CreateVector(&subgraph, 1), description,
builder.CreateVector(buffers.data(), buffers.size()));
builder.Finish(model_buffer);
return std::vector<char>(builder.GetBufferPointer(),
builder.GetBufferPointer() + builder.GetSize());
}
int32_t ReduceTester::ComputeSize(const std::vector<int32_t>& shape) {
return std::accumulate(shape.cbegin(), shape.cend(), 1,
std::multiplies<int32_t>());
}
} // namespace xnnpack
} // namespace tflite
<|endoftext|> |
<commit_before>
// Copyright (c) 2014-2015 Dims dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "common/setResponseVisitor.h"
#include "common/events.h"
#include "common/authenticationProvider.h"
#include "common/requests.h"
#include "common/communicationProtocol.h"
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include "monitor/provideInfoAction.h"
#include "monitor/monitorRequests.h"
#include "monitor/filters.h"
#include "monitor/reputationTracer.h"
namespace monitor
{
unsigned int const LoopTime = 20000;//milisec
struct CProvideInfo;
struct CAskForInfo;
struct CAskForInfoEvent : boost::statechart::event< CAskForInfoEvent >
{
};
struct CProvideInfoEvent : boost::statechart::event< CProvideInfoEvent >
{
};
struct CInit : boost::statechart::state< CInit, CProvideInfoAction >
{
CInit( my_context ctx ) : my_base( ctx )
{}
typedef boost::mpl::list<
boost::statechart::transition< CProvideInfoEvent, CProvideInfo >,
boost::statechart::transition< CAskForInfoEvent, CAskForInfo >
> reactions;
};
struct CProvideInfo : boost::statechart::state< CProvideInfo, CProvideInfoAction >
{
CProvideInfo( my_context ctx ) : my_base( ctx )
{
}
boost::statechart::result react( common::CAckEvent const & _promptAck )
{
context< CProvideInfoAction >().setExit();
return discard_event();
}
boost::statechart::result react( common::CMessageResult const & _messageResult )
{
common::CMessage orginalMessage;
if ( !common::CommunicationProtocol::unwindMessage( _messageResult.m_message, orginalMessage, GetTime(), _messageResult.m_pubKey ) )
assert( !"service it somehow" );
common::CInfoRequestData requestedInfo;
common::convertPayload( orginalMessage, requestedInfo );
context< CProvideInfoAction >().forgetRequests();
m_id = _messageResult.m_message.m_header.m_id;
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Ack
, context< CProvideInfoAction >().getActionKey()
, _messageResult.m_message.m_header.m_id
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload( common::CAck() );
context< CProvideInfoAction >().addRequest( request );
context< CProvideInfoAction >().addRequest(
new common::CTimeEventRequest(
LoopTime
, new CMediumClassFilter( common::CMediumKinds::Time ) ) );
if ( requestedInfo.m_kind == (int)common::CInfoKind::IsAddmited )
{
CPubKey pubKey;
CReputationTracker::getInstance()->getNodeToKey( context< CProvideInfoAction >().getNodeIndicator(), pubKey );
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Result
, context< CProvideInfoAction >().getActionKey()
, context< CProvideInfoAction >().getInfoRequestKey()
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload(
common::CResult( CReputationTracker::getInstance()->isAddmitedMonitor( pubKey ) ? 1 : 0 ) );
context< CProvideInfoAction >().addRequest( request );
}
else if ( requestedInfo.m_kind == (int)common::CInfoKind::IsRegistered )
{
CPubKey pubKey;
CReputationTracker::getInstance()->getNodeToKey( context< CProvideInfoAction >().getNodeIndicator(), pubKey );
common::CTrackerData trackerData;
CPubKey monitorPubKey;
CReputationTracker::getInstance()->checkForTracker( pubKey, trackerData, monitorPubKey );
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::ValidRegistration
, context< CProvideInfoAction >().getActionKey()
, context< CProvideInfoAction >().getInfoRequestKey()
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload(
common::CValidRegistration(
monitorPubKey
, trackerData.m_contractTime
, trackerData.m_networkTime ) );
context< CProvideInfoAction >().addRequest( request );
}
return discard_event();
}
boost::statechart::result react( common::CAvailableCoinsData const & _availableCoins )
{
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Balance
, context< CProvideInfoAction >().getActionKey()
, m_id
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload( common::CBalance( _availableCoins.m_availableCoins ) );
context< CProvideInfoAction >().addRequest( request );
return discard_event();
}
boost::statechart::result react( common::CTimeEvent const & _timeEvent )
{
context< CProvideInfoAction >().forgetRequests();
context< CProvideInfoAction >().setExit();
return discard_event();
}
typedef boost::mpl::list<
boost::statechart::custom_reaction< common::CMessageResult >,
boost::statechart::custom_reaction< common::CAckEvent >,
boost::statechart::custom_reaction< common::CAvailableCoinsData >,
boost::statechart::custom_reaction< common::CTimeEvent >
> reactions;
uint256 m_id;
};
struct CAskForInfo : boost::statechart::state< CAskForInfo, CProvideInfoAction >
{
CAskForInfo( my_context ctx ) : my_base( ctx )
{
context< CProvideInfoAction >().addRequest( new common::CInfoAskRequest(
context< CProvideInfoAction >().getInfo()
, context< CProvideInfoAction >().getActionKey()
, new CMediumClassFilter( common::CMediumKinds::Monitors, 1 ) ) );
context< CProvideInfoAction >().addRequest(
new common::CTimeEventRequest(
LoopTime
, new CMediumClassFilter( common::CMediumKinds::Time ) ) );
}
boost::statechart::result react( common::CAckEvent const & _promptAck )
{
return discard_event();
}
boost::statechart::result react( common::CTimeEvent const & _timeEvent )
{
context< CProvideInfoAction >().forgetRequests();
context< CProvideInfoAction >().setExit();
return discard_event();
}
boost::statechart::result react( common::CMessageResult const & _messageResult )
{
common::CMessage orginalMessage;
if ( !common::CommunicationProtocol::unwindMessage( _messageResult.m_message, orginalMessage, GetTime(), _messageResult.m_pubKey ) )
assert( !"service it somehow" );
context< CProvideInfoAction >().addRequest(
new common::CAckRequest(
context< CProvideInfoAction >().getActionKey()
, _messageResult.m_message.m_header.m_id
, new CSpecificMediumFilter( _messageResult.m_nodeIndicator ) ) );
if ( ( common::CPayloadKind::Enum )orginalMessage.m_header.m_payloadKind == common::CPayloadKind::Result )
{
common::CResult result;
common::convertPayload( orginalMessage, result );
context< CProvideInfoAction >().setResult( result );
}
}
typedef boost::mpl::list<
boost::statechart::custom_reaction< common::CTimeEvent >,
boost::statechart::custom_reaction< common::CMessageResult >,
boost::statechart::custom_reaction< common::CAckEvent >
> reactions;
};
struct CMonitorStop : boost::statechart::state< CMonitorStop, CProvideInfoAction >
{
CMonitorStop( my_context ctx ) : my_base( ctx )
{
}
};
CProvideInfoAction::CProvideInfoAction( uint256 const & _id, uint256 const & _actionKey, uintptr_t _nodeIndicator )
: common::CScheduleAbleAction( _actionKey )
, m_infoRequestKey( _id )
, m_nodeIndicator( _nodeIndicator )
{
initiate();
}
CProvideInfoAction::CProvideInfoAction( common::CInfoKind::Enum _infoKind )
: m_infoKind( _infoKind )
{
initiate();
}
void
CProvideInfoAction::accept( common::CSetResponseVisitor & _visitor )
{
_visitor.visit( *this );
}
uintptr_t
CProvideInfoAction::getNodeIndicator() const
{
return m_nodeIndicator;
}
}
<commit_msg>small fix<commit_after>
// Copyright (c) 2014-2015 Dims dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "common/setResponseVisitor.h"
#include "common/events.h"
#include "common/authenticationProvider.h"
#include "common/requests.h"
#include "common/communicationProtocol.h"
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include "monitor/provideInfoAction.h"
#include "monitor/monitorRequests.h"
#include "monitor/filters.h"
#include "monitor/reputationTracer.h"
namespace monitor
{
unsigned int const LoopTime = 20000;//milisec
struct CProvideInfo;
struct CAskForInfo;
struct CAskForInfoEvent : boost::statechart::event< CAskForInfoEvent >
{
};
struct CProvideInfoEvent : boost::statechart::event< CProvideInfoEvent >
{
};
struct CInit : boost::statechart::state< CInit, CProvideInfoAction >
{
CInit( my_context ctx ) : my_base( ctx )
{}
typedef boost::mpl::list<
boost::statechart::transition< CProvideInfoEvent, CProvideInfo >,
boost::statechart::transition< CAskForInfoEvent, CAskForInfo >
> reactions;
};
struct CProvideInfo : boost::statechart::state< CProvideInfo, CProvideInfoAction >
{
CProvideInfo( my_context ctx ) : my_base( ctx )
{
}
boost::statechart::result react( common::CAckEvent const & _promptAck )
{
context< CProvideInfoAction >().setExit();
return discard_event();
}
boost::statechart::result react( common::CMessageResult const & _messageResult )
{
common::CMessage orginalMessage;
if ( !common::CommunicationProtocol::unwindMessage( _messageResult.m_message, orginalMessage, GetTime(), _messageResult.m_pubKey ) )
assert( !"service it somehow" );
common::CInfoRequestData requestedInfo;
common::convertPayload( orginalMessage, requestedInfo );
context< CProvideInfoAction >().forgetRequests();
m_id = _messageResult.m_message.m_header.m_id;
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Ack
, context< CProvideInfoAction >().getActionKey()
, _messageResult.m_message.m_header.m_id
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload( common::CAck() );
context< CProvideInfoAction >().addRequest( request );
context< CProvideInfoAction >().addRequest(
new common::CTimeEventRequest(
LoopTime
, new CMediumClassFilter( common::CMediumKinds::Time ) ) );
if ( requestedInfo.m_kind == (int)common::CInfoKind::IsAddmited )
{
CPubKey pubKey;
CReputationTracker::getInstance()->getNodeToKey( context< CProvideInfoAction >().getNodeIndicator(), pubKey );
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Result
, context< CProvideInfoAction >().getActionKey()
, context< CProvideInfoAction >().getInfoRequestKey()
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload(
common::CResult( CReputationTracker::getInstance()->isAddmitedMonitor( pubKey ) ? 1 : 0 ) );
context< CProvideInfoAction >().addRequest( request );
}
else if ( requestedInfo.m_kind == (int)common::CInfoKind::IsRegistered )
{
CPubKey pubKey;
CReputationTracker::getInstance()->getNodeToKey( context< CProvideInfoAction >().getNodeIndicator(), pubKey );
common::CTrackerData trackerData;
CPubKey monitorPubKey;
CReputationTracker::getInstance()->checkForTracker( pubKey, trackerData, monitorPubKey );
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::ValidRegistration
, context< CProvideInfoAction >().getActionKey()
, context< CProvideInfoAction >().getInfoRequestKey()
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload(
common::CValidRegistration(
monitorPubKey
, trackerData.m_contractTime
, trackerData.m_networkTime ) );
context< CProvideInfoAction >().addRequest( request );
}
return discard_event();
}
boost::statechart::result react( common::CAvailableCoinsData const & _availableCoins )
{
common::CSendMessageRequest * request =
new common::CSendMessageRequest(
common::CPayloadKind::Balance
, context< CProvideInfoAction >().getActionKey()
, m_id
, new CSpecificMediumFilter( context< CProvideInfoAction >().getNodeIndicator() ) );
request->addPayload( common::CBalance( _availableCoins.m_availableCoins ) );
context< CProvideInfoAction >().addRequest( request );
return discard_event();
}
boost::statechart::result react( common::CTimeEvent const & _timeEvent )
{
context< CProvideInfoAction >().forgetRequests();
context< CProvideInfoAction >().setExit();
return discard_event();
}
typedef boost::mpl::list<
boost::statechart::custom_reaction< common::CMessageResult >,
boost::statechart::custom_reaction< common::CAckEvent >,
boost::statechart::custom_reaction< common::CAvailableCoinsData >,
boost::statechart::custom_reaction< common::CTimeEvent >
> reactions;
uint256 m_id;
};
struct CAskForInfo : boost::statechart::state< CAskForInfo, CProvideInfoAction >
{
CAskForInfo( my_context ctx ) : my_base( ctx )
{
context< CProvideInfoAction >().addRequest( new common::CInfoAskRequest(
context< CProvideInfoAction >().getInfo()
, context< CProvideInfoAction >().getActionKey()
, new CMediumClassFilter( common::CMediumKinds::Monitors, 1 ) ) );
context< CProvideInfoAction >().addRequest(
new common::CTimeEventRequest(
LoopTime
, new CMediumClassFilter( common::CMediumKinds::Time ) ) );
}
boost::statechart::result react( common::CAckEvent const & _promptAck )
{
return discard_event();
}
boost::statechart::result react( common::CTimeEvent const & _timeEvent )
{
context< CProvideInfoAction >().forgetRequests();
context< CProvideInfoAction >().setExit();
return discard_event();
}
boost::statechart::result react( common::CMessageResult const & _messageResult )
{
common::CMessage orginalMessage;
if ( !common::CommunicationProtocol::unwindMessage( _messageResult.m_message, orginalMessage, GetTime(), _messageResult.m_pubKey ) )
assert( !"service it somehow" );
context< CProvideInfoAction >().addRequest(
new common::CAckRequest(
context< CProvideInfoAction >().getActionKey()
, _messageResult.m_message.m_header.m_id
, new CSpecificMediumFilter( _messageResult.m_nodeIndicator ) ) );
if ( ( common::CPayloadKind::Enum )orginalMessage.m_header.m_payloadKind == common::CPayloadKind::Result )
{
common::CResult result;
common::convertPayload( orginalMessage, result );
context< CProvideInfoAction >().setResult( result );
}
}
typedef boost::mpl::list<
boost::statechart::custom_reaction< common::CTimeEvent >,
boost::statechart::custom_reaction< common::CMessageResult >,
boost::statechart::custom_reaction< common::CAckEvent >
> reactions;
};
struct CMonitorStop : boost::statechart::state< CMonitorStop, CProvideInfoAction >
{
CMonitorStop( my_context ctx ) : my_base( ctx )
{
}
};
CProvideInfoAction::CProvideInfoAction( uint256 const & _id, uint256 const & _actionKey, uintptr_t _nodeIndicator )
: common::CScheduleAbleAction( _actionKey )
, m_infoRequestKey( _id )
, m_nodeIndicator( _nodeIndicator )
{
initiate();
process_event( CProvideInfoEvent() );
}
CProvideInfoAction::CProvideInfoAction( common::CInfoKind::Enum _infoKind )
: m_infoKind( _infoKind )
{
initiate();
process_event( CAskForInfoEvent() );
}
void
CProvideInfoAction::accept( common::CSetResponseVisitor & _visitor )
{
_visitor.visit( *this );
}
uintptr_t
CProvideInfoAction::getNodeIndicator() const
{
return m_nodeIndicator;
}
}
<|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 2017 ScyllaDB
*/
#include "util/alloc_failure_injector.hh"
namespace seastar {
namespace memory {
thread_local alloc_failure_injector the_alloc_failure_injector;
void alloc_failure_injector::fail() {
_failed = true;
cancel();
_on_alloc_failure();
}
}
}
<commit_msg>alloc_failure_injector: Log backtrace of failures<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 2017 ScyllaDB
*/
#include "util/alloc_failure_injector.hh"
#include "util/backtrace.hh"
#include "util/log.hh"
namespace seastar {
namespace memory {
static logger log("failure_injector");
thread_local alloc_failure_injector the_alloc_failure_injector;
void alloc_failure_injector::fail() {
_failed = true;
cancel();
if (log.is_enabled(log_level::trace)) {
log.trace("Failing at {}", current_backtrace());
}
_on_alloc_failure();
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qmediarecorder.h>
#include <qmediarecordercontrol.h>
#include <qmediaobject_p.h>
#include <qmediaservice.h>
#include <qmediaserviceprovider.h>
#include <qaudioencodercontrol.h>
#include <qvideoencodercontrol.h>
#include <qmediaformatcontrol.h>
#include <QtCore/qdebug.h>
#include <QtCore/qurl.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qmetaobject.h>
#include <QtMultimedia/QAudioFormat>
QTM_BEGIN_NAMESPACE
/*!
\class QMediaRecorder
\ingroup multimedia
\preliminary
\brief The QMediaRecorder class is used for the recording of media content.
The QMediaRecorder class is a high level media recording class.
It's not intended to be used alone but for accessing the media
recording functions of other media objects, like QRadioTuner,
or QAudioCaptureSource.
If the radio is used as a source, recording
is only possible when the source is in appropriate state
\code
// Audio only recording
audioSource = new QAudioCaptureSource;
recorder = new QMediaRecorder(audioSource);
QAudioEncoderSettings audioSettings;
audioSettings.setCodec("audio/vorbis");
audioSettings.setQuality(QtMedia::HighQuality);
recorder->setEncodingSettings(audioSettings);
recorder->setOutputLocation(QUrl::fromLocalFile(fileName));
recorder->record();
\endcode
\sa
*/
class QMediaRecorderPrivate : public QMediaObjectPrivate
{
Q_DECLARE_NON_CONST_PUBLIC(QMediaRecorder)
public:
QMediaRecorderPrivate();
void initControls();
QMediaRecorderControl *control;
QMediaFormatControl *formatControl;
QAudioEncoderControl *audioControl;
QVideoEncoderControl *videoControl;
QMediaRecorder::State state;
QMediaRecorder::Error error;
QString errorString;
void _q_stateChanged(QMediaRecorder::State state);
void _q_error(int error, const QString &errorString);
};
QMediaRecorderPrivate::QMediaRecorderPrivate():
control(0),
formatControl(0),
audioControl(0),
videoControl(0),
state(QMediaRecorder::StoppedState),
error(QMediaRecorder::NoError)
{
}
void QMediaRecorderPrivate::initControls()
{
Q_Q(QMediaRecorder);
if (!service)
return;
control = qobject_cast<QMediaRecorderControl*>(service->control(QMediaRecorderControl_iid));
formatControl = qobject_cast<QMediaFormatControl *>(service->control(QMediaFormatControl_iid));
audioControl = qobject_cast<QAudioEncoderControl *>(service->control(QAudioEncoderControl_iid));
videoControl = qobject_cast<QVideoEncoderControl *>(service->control(QVideoEncoderControl_iid));
if (control) {
q->connect(control, SIGNAL(stateChanged(QMediaRecorder::State)),
q, SLOT(_q_stateChanged(QMediaRecorder::State)));
q->connect(control, SIGNAL(error(int,QString)),
q, SLOT(_q_error(int,QString)));
}
}
#define ENUM_NAME(c,e,v) (c::staticMetaObject.enumerator(c::staticMetaObject.indexOfEnumerator(e)).valueToKey((v)))
void QMediaRecorderPrivate::_q_stateChanged(QMediaRecorder::State ps)
{
Q_Q(QMediaRecorder);
if (ps == QMediaRecorder::RecordingState)
q->addPropertyWatch("duration");
else
q->removePropertyWatch("duration");
// qDebug() << "Recorder state changed:" << ENUM_NAME(QMediaRecorder,"State",ps);
if (state != ps) {
emit q->stateChanged(ps);
}
state = ps;
}
void QMediaRecorderPrivate::_q_error(int error, const QString &errorString)
{
Q_Q(QMediaRecorder);
this->error = QMediaRecorder::Error(error);
this->errorString = errorString;
emit q->error(this->error);
}
/*!
Constructs a media recorder which records the media produced by \a mediaObject.
The \a parent is passed to QMediaObject.
*/
QMediaRecorder::QMediaRecorder(QMediaObject *mediaObject, QObject *parent):
QMediaObject(*new QMediaRecorderPrivate, parent, mediaObject->service())
{
Q_D(QMediaRecorder);
d->initControls();
}
/*!
Destroys a media recorder object.
*/
QMediaRecorder::~QMediaRecorder()
{
}
/*!
\property QMediaRecorder::outputLocation
\brief the destination location of media content.
Setting the location can fail for example when the service supports
only local file system locations while the network url was passed,
or the service doesn't support media recording.
*/
QUrl QMediaRecorder::outputLocation() const
{
return d_func()->control ? d_func()->control->outputLocation() : QUrl();
}
bool QMediaRecorder::setOutputLocation(const QUrl &location)
{
Q_D(QMediaRecorder);
return d->control ? d->control->setOutputLocation(location) : false;
}
/*!
Return the current media recorder state.
\sa QMediaRecorder::State
*/
QMediaRecorder::State QMediaRecorder::state() const
{
return d_func()->control ? QMediaRecorder::State(d_func()->control->state()) : StoppedState;
}
/*!
Returns the current error state.
\sa errorString()
*/
QMediaRecorder::Error QMediaRecorder::error() const
{
return d_func()->error;
}
/*!
Returns a string describing the current error state.
\sa error()
*/
QString QMediaRecorder::errorString() const
{
return d_func()->errorString;
}
/*!
\property QMediaRecorder::duration
\brief the recorded media duration in milliseconds.
*/
qint64 QMediaRecorder::duration() const
{
return d_func()->control ? d_func()->control->duration() : 0;
}
/*!
Returns a list of MIME types of supported container formats.
*/
QStringList QMediaRecorder::supportedFormats() const
{
return d_func()->formatControl ?
d_func()->formatControl->supportedFormats() : QStringList();
}
/*!
Returns a description of a container format \a mimeType.
*/
QString QMediaRecorder::formatDescription(const QString &mimeType) const
{
return d_func()->formatControl ?
d_func()->formatControl->formatDescription(mimeType) : QString();
}
/*!
Returns the MIME type of the selected container format.
*/
QString QMediaRecorder::format() const
{
return d_func()->formatControl ?
d_func()->formatControl->format() : QString();
}
/*!
Returns a list of supported audio codecs.
*/
QStringList QMediaRecorder::supportedAudioCodecs() const
{
return d_func()->audioControl ?
d_func()->audioControl->supportedAudioCodecs() : QStringList();
}
/*!
Returns a description of an audio \a codec.
*/
QString QMediaRecorder::audioCodecDescription(const QString &codec) const
{
return d_func()->audioControl ?
d_func()->audioControl->codecDescription(codec) : QString();
}
/*!
Returns a list of supported audio sample rates.
If non null audio \a settings parameter is passed,
the returned list is reduced to sample rates supported with partial settings applied.
It can be used for example to query the list of sample rates, supported by specific audio codec.
If the encoder supports arbitrary sample rates within the supported rates range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
*/
QList<int> QMediaRecorder::supportedAudioSampleRates(const QAudioEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->audioControl ?
d_func()->audioControl->supportedSampleRates(settings, continuous) : QList<int>();
}
/*!
Returns a list of resolutions video can be encoded at. An empty list is returned if the video
encoder supports arbitrary resolutions within the minimum and maximum range.
If non null video \a settings parameter is passed,
the returned list is reduced to resolution supported with partial settings like video codec or framerate applied.
If the encoder supports arbitrary resolutions within the supported range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
\sa QVideoEncoderSettings::resolution()
*/
QList<QSize> QMediaRecorder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->videoControl ?
d_func()->videoControl->supportedResolutions(settings, continuous) : QList<QSize>();
}
/*!
Returns a list of frame rates video can be encoded at.
If non null video \a settings parameter is passed,
the returned list is reduced to frame rates supported with partial settings like video codec or resolution applied.
If the encoder supports arbitrary frame rates within the supported range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
\sa QVideoEncoderSettings::frameRate()
*/
QList<qreal> QMediaRecorder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->videoControl ?
d_func()->videoControl->supportedFrameRates(settings, continuous) : QList<qreal>();
}
/*!
Returns a list of supported video codecs.
*/
QStringList QMediaRecorder::supportedVideoCodecs() const
{
return d_func()->videoControl ?
d_func()->videoControl->supportedVideoCodecs() : QStringList();
}
/*!
Returns a description of a video \a codec.
\sa setEncodingSettings()
*/
QString QMediaRecorder::videoCodecDescription(const QString &codec) const
{
return d_func()->videoControl ?
d_func()->videoControl->videoCodecDescription(codec) : QString();
}
/*!
Returns the audio encoder settings being used.
\sa setEncodingSettings()
*/
QAudioEncoderSettings QMediaRecorder::audioSettings() const
{
return d_func()->audioControl ?
d_func()->audioControl->audioSettings() : QAudioEncoderSettings();
}
/*!
Returns the video encoder settings being used.
\sa setEncodingSettings()
*/
QVideoEncoderSettings QMediaRecorder::videoSettings() const
{
return d_func()->videoControl ?
d_func()->videoControl->videoSettings() : QVideoEncoderSettings();
}
/*!
Sets the \a audio and \a video encoder settings and container \a format MIME type.
It's only possible to change setttings when the encoder
is in the QMediaEncoder::StoppedState state.
If some parameters are not specified, or null settings are passed,
the encoder choose the default encoding parameters, depending on
media source properties.
But while setEncodingSettings is optional, the backend can preload
encoding pipeline to improve recording startup time.
\sa audioSettings(), videoSettings(), format()
*/
void QMediaRecorder::setEncodingSettings(const QAudioEncoderSettings &audio,
const QVideoEncoderSettings &video,
const QString &format)
{
Q_D(QMediaRecorder);
if (d->audioControl)
d->audioControl->setAudioSettings(audio);
if (d->videoControl)
d->videoControl->setVideoSettings(video);
if (d->formatControl)
d->formatControl->setFormat(format);
if (d->control)
d->control->applySettings();
}
/*!
Start recording.
This is an asynchronous call, with signal
stateCahnged(QMediaRecorder::RecordingState) being emited
when recording started, otherwise error() signal is emited.
*/
void QMediaRecorder::record()
{
Q_D(QMediaRecorder);
// reset error
d->error = NoError;
d->errorString = QString();
if (d->control)
d->control->record();
}
/*!
Pause recording.
*/
void QMediaRecorder::pause()
{
Q_D(QMediaRecorder);
if (d->control)
d->control->pause();
}
/*!
Stop recording.
*/
void QMediaRecorder::stop()
{
Q_D(QMediaRecorder);
if (d->control)
d->control->stop();
}
/*!
\enum QMediaRecorder::State
\value StoppedState The recorder is not active.
\value RecordingState The recorder is currently active and producing data.
\value PausedState The recorder is paused.
*/
/*!
\enum QMediaRecorder::Error
\value NoError No Errors.
\value ResourceError Device is not ready or not available.
\value FormatError Current format is not supported.
*/
/*!
\fn QMediaRecorder::stateChanged(State state)
Signals that a media recorder's \a state has changed.
*/
/*!
\fn QMediaRecorder::durationChanged(qint64 duration)
Signals that the \a duration of the recorded media has changed.
*/
/*!
\fn QMediaRecorder::error(QMediaRecorder::Error error)
Signals that an \a error has occurred.
*/
#include "moc_qmediarecorder.cpp"
QTM_END_NAMESPACE
<commit_msg>Documentation fix.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qmediarecorder.h>
#include <qmediarecordercontrol.h>
#include <qmediaobject_p.h>
#include <qmediaservice.h>
#include <qmediaserviceprovider.h>
#include <qaudioencodercontrol.h>
#include <qvideoencodercontrol.h>
#include <qmediaformatcontrol.h>
#include <QtCore/qdebug.h>
#include <QtCore/qurl.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qmetaobject.h>
#include <QtMultimedia/QAudioFormat>
QTM_BEGIN_NAMESPACE
/*!
\class QMediaRecorder
\ingroup multimedia
\preliminary
\brief The QMediaRecorder class is used for the recording of media content.
The QMediaRecorder class is a high level media recording class.
It's not intended to be used alone but for accessing the media
recording functions of other media objects, like QRadioTuner,
or QAudioCaptureSource.
If the radio is used as a source, recording
is only possible when the source is in appropriate state
\code
// Audio only recording
audioSource = new QAudioCaptureSource;
recorder = new QMediaRecorder(audioSource);
QAudioEncoderSettings audioSettings;
audioSettings.setCodec("audio/vorbis");
audioSettings.setQuality(QtMedia::HighQuality);
recorder->setEncodingSettings(audioSettings);
recorder->setOutputLocation(QUrl::fromLocalFile(fileName));
recorder->record();
\endcode
\sa
*/
class QMediaRecorderPrivate : public QMediaObjectPrivate
{
Q_DECLARE_NON_CONST_PUBLIC(QMediaRecorder)
public:
QMediaRecorderPrivate();
void initControls();
QMediaRecorderControl *control;
QMediaFormatControl *formatControl;
QAudioEncoderControl *audioControl;
QVideoEncoderControl *videoControl;
QMediaRecorder::State state;
QMediaRecorder::Error error;
QString errorString;
void _q_stateChanged(QMediaRecorder::State state);
void _q_error(int error, const QString &errorString);
};
QMediaRecorderPrivate::QMediaRecorderPrivate():
control(0),
formatControl(0),
audioControl(0),
videoControl(0),
state(QMediaRecorder::StoppedState),
error(QMediaRecorder::NoError)
{
}
void QMediaRecorderPrivate::initControls()
{
Q_Q(QMediaRecorder);
if (!service)
return;
control = qobject_cast<QMediaRecorderControl*>(service->control(QMediaRecorderControl_iid));
formatControl = qobject_cast<QMediaFormatControl *>(service->control(QMediaFormatControl_iid));
audioControl = qobject_cast<QAudioEncoderControl *>(service->control(QAudioEncoderControl_iid));
videoControl = qobject_cast<QVideoEncoderControl *>(service->control(QVideoEncoderControl_iid));
if (control) {
q->connect(control, SIGNAL(stateChanged(QMediaRecorder::State)),
q, SLOT(_q_stateChanged(QMediaRecorder::State)));
q->connect(control, SIGNAL(error(int,QString)),
q, SLOT(_q_error(int,QString)));
}
}
#define ENUM_NAME(c,e,v) (c::staticMetaObject.enumerator(c::staticMetaObject.indexOfEnumerator(e)).valueToKey((v)))
void QMediaRecorderPrivate::_q_stateChanged(QMediaRecorder::State ps)
{
Q_Q(QMediaRecorder);
if (ps == QMediaRecorder::RecordingState)
q->addPropertyWatch("duration");
else
q->removePropertyWatch("duration");
// qDebug() << "Recorder state changed:" << ENUM_NAME(QMediaRecorder,"State",ps);
if (state != ps) {
emit q->stateChanged(ps);
}
state = ps;
}
void QMediaRecorderPrivate::_q_error(int error, const QString &errorString)
{
Q_Q(QMediaRecorder);
this->error = QMediaRecorder::Error(error);
this->errorString = errorString;
emit q->error(this->error);
}
/*!
Constructs a media recorder which records the media produced by \a mediaObject.
The \a parent is passed to QMediaObject.
*/
QMediaRecorder::QMediaRecorder(QMediaObject *mediaObject, QObject *parent):
QMediaObject(*new QMediaRecorderPrivate, parent, mediaObject->service())
{
Q_D(QMediaRecorder);
d->initControls();
}
/*!
Destroys a media recorder object.
*/
QMediaRecorder::~QMediaRecorder()
{
}
/*!
\property QMediaRecorder::outputLocation
\brief the destination location of media content.
Setting the location can fail for example when the service supports
only local file system locations while the network url was passed,
or the service doesn't support media recording.
*/
QUrl QMediaRecorder::outputLocation() const
{
return d_func()->control ? d_func()->control->outputLocation() : QUrl();
}
bool QMediaRecorder::setOutputLocation(const QUrl &location)
{
Q_D(QMediaRecorder);
return d->control ? d->control->setOutputLocation(location) : false;
}
/*!
Return the current media recorder state.
\sa QMediaRecorder::State
*/
QMediaRecorder::State QMediaRecorder::state() const
{
return d_func()->control ? QMediaRecorder::State(d_func()->control->state()) : StoppedState;
}
/*!
Returns the current error state.
\sa errorString()
*/
QMediaRecorder::Error QMediaRecorder::error() const
{
return d_func()->error;
}
/*!
Returns a string describing the current error state.
\sa error()
*/
QString QMediaRecorder::errorString() const
{
return d_func()->errorString;
}
/*!
\property QMediaRecorder::duration
\brief the recorded media duration in milliseconds.
*/
qint64 QMediaRecorder::duration() const
{
return d_func()->control ? d_func()->control->duration() : 0;
}
/*!
Returns a list of MIME types of supported container formats.
*/
QStringList QMediaRecorder::supportedFormats() const
{
return d_func()->formatControl ?
d_func()->formatControl->supportedFormats() : QStringList();
}
/*!
Returns a description of a container format \a mimeType.
*/
QString QMediaRecorder::formatDescription(const QString &mimeType) const
{
return d_func()->formatControl ?
d_func()->formatControl->formatDescription(mimeType) : QString();
}
/*!
Returns the MIME type of the selected container format.
*/
QString QMediaRecorder::format() const
{
return d_func()->formatControl ?
d_func()->formatControl->format() : QString();
}
/*!
Returns a list of supported audio codecs.
*/
QStringList QMediaRecorder::supportedAudioCodecs() const
{
return d_func()->audioControl ?
d_func()->audioControl->supportedAudioCodecs() : QStringList();
}
/*!
Returns a description of an audio \a codec.
*/
QString QMediaRecorder::audioCodecDescription(const QString &codec) const
{
return d_func()->audioControl ?
d_func()->audioControl->codecDescription(codec) : QString();
}
/*!
Returns a list of supported audio sample rates.
If non null audio \a settings parameter is passed,
the returned list is reduced to sample rates supported with partial settings applied.
It can be used for example to query the list of sample rates, supported by specific audio codec.
If the encoder supports arbitrary sample rates within the supported rates range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
*/
QList<int> QMediaRecorder::supportedAudioSampleRates(const QAudioEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->audioControl ?
d_func()->audioControl->supportedSampleRates(settings, continuous) : QList<int>();
}
/*!
Returns a list of resolutions video can be encoded at.
If non null video \a settings parameter is passed,
the returned list is reduced to resolution supported with partial settings like video codec or framerate applied.
If the encoder supports arbitrary resolutions within the supported range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
\sa QVideoEncoderSettings::resolution()
*/
QList<QSize> QMediaRecorder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->videoControl ?
d_func()->videoControl->supportedResolutions(settings, continuous) : QList<QSize>();
}
/*!
Returns a list of frame rates video can be encoded at.
If non null video \a settings parameter is passed,
the returned list is reduced to frame rates supported with partial settings like video codec or resolution applied.
If the encoder supports arbitrary frame rates within the supported range,
*\a continuous is set to true, otherwise *\a continuous is set to false.
\sa QVideoEncoderSettings::frameRate()
*/
QList<qreal> QMediaRecorder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
return d_func()->videoControl ?
d_func()->videoControl->supportedFrameRates(settings, continuous) : QList<qreal>();
}
/*!
Returns a list of supported video codecs.
*/
QStringList QMediaRecorder::supportedVideoCodecs() const
{
return d_func()->videoControl ?
d_func()->videoControl->supportedVideoCodecs() : QStringList();
}
/*!
Returns a description of a video \a codec.
\sa setEncodingSettings()
*/
QString QMediaRecorder::videoCodecDescription(const QString &codec) const
{
return d_func()->videoControl ?
d_func()->videoControl->videoCodecDescription(codec) : QString();
}
/*!
Returns the audio encoder settings being used.
\sa setEncodingSettings()
*/
QAudioEncoderSettings QMediaRecorder::audioSettings() const
{
return d_func()->audioControl ?
d_func()->audioControl->audioSettings() : QAudioEncoderSettings();
}
/*!
Returns the video encoder settings being used.
\sa setEncodingSettings()
*/
QVideoEncoderSettings QMediaRecorder::videoSettings() const
{
return d_func()->videoControl ?
d_func()->videoControl->videoSettings() : QVideoEncoderSettings();
}
/*!
Sets the \a audio and \a video encoder settings and container \a format MIME type.
It's only possible to change setttings when the encoder
is in the QMediaEncoder::StoppedState state.
If some parameters are not specified, or null settings are passed,
the encoder choose the default encoding parameters, depending on
media source properties.
But while setEncodingSettings is optional, the backend can preload
encoding pipeline to improve recording startup time.
\sa audioSettings(), videoSettings(), format()
*/
void QMediaRecorder::setEncodingSettings(const QAudioEncoderSettings &audio,
const QVideoEncoderSettings &video,
const QString &format)
{
Q_D(QMediaRecorder);
if (d->audioControl)
d->audioControl->setAudioSettings(audio);
if (d->videoControl)
d->videoControl->setVideoSettings(video);
if (d->formatControl)
d->formatControl->setFormat(format);
if (d->control)
d->control->applySettings();
}
/*!
Start recording.
This is an asynchronous call, with signal
stateCahnged(QMediaRecorder::RecordingState) being emited
when recording started, otherwise error() signal is emited.
*/
void QMediaRecorder::record()
{
Q_D(QMediaRecorder);
// reset error
d->error = NoError;
d->errorString = QString();
if (d->control)
d->control->record();
}
/*!
Pause recording.
*/
void QMediaRecorder::pause()
{
Q_D(QMediaRecorder);
if (d->control)
d->control->pause();
}
/*!
Stop recording.
*/
void QMediaRecorder::stop()
{
Q_D(QMediaRecorder);
if (d->control)
d->control->stop();
}
/*!
\enum QMediaRecorder::State
\value StoppedState The recorder is not active.
\value RecordingState The recorder is currently active and producing data.
\value PausedState The recorder is paused.
*/
/*!
\enum QMediaRecorder::Error
\value NoError No Errors.
\value ResourceError Device is not ready or not available.
\value FormatError Current format is not supported.
*/
/*!
\fn QMediaRecorder::stateChanged(State state)
Signals that a media recorder's \a state has changed.
*/
/*!
\fn QMediaRecorder::durationChanged(qint64 duration)
Signals that the \a duration of the recorded media has changed.
*/
/*!
\fn QMediaRecorder::error(QMediaRecorder::Error error)
Signals that an \a error has occurred.
*/
#include "moc_qmediarecorder.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>#include "hdfs_file.h"
#include "hdfs_utils.h"
using namespace std;
PyObject* FileClass_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
FileInfo *self;
self = (FileInfo *)type->tp_alloc(type, 0);
if (self != NULL) {
self->fs = NULL;
self->file = NULL;
self->flags = 0;
self->buff_size = 0;
self->replication = 1;
self->blocksize = 0;
self->readline_chunk_size = 16 * 1024; // 16 KB
#ifdef HADOOP_LIBHDFS_V1
self->stream_type = 0;
#endif
}
return (PyObject *)self;
}
#ifdef HADOOP_LIBHDFS_V1
bool hdfsFileIsOpenForWrite(FileInfo *f){
return f->stream_type == OUTPUT;
}
bool hdfsFileIsOpenForRead(FileInfo *f){
return f->stream_type == INPUT;
}
#endif
void FileClass_dealloc(FileInfo* self)
{
self->file = NULL;
self->ob_type->tp_free((PyObject*)self);
}
int FileClass_init(FileInfo *self, PyObject *args, PyObject *kwds)
{
if (! PyArg_ParseTuple(args, "OO", &(self->fs), &(self->file))) {
return -1;
}
return 0;
}
int FileClass_init_internal(FileInfo *self, hdfsFS fs, hdfsFile file)
{
self->fs = fs;
self->file = file;
return 0;
}
PyObject* FileClass_close(FileInfo* self){
int result = hdfsCloseFile(self->fs, self->file);
if (result < 0) {
return PyErr_SetFromErrno(PyExc_IOError);
}
else
return PyBool_FromLong(1);
}
PyObject* FileClass_mode(FileInfo* self){
return FileClass_get_mode(self);
}
PyObject* FileClass_get_mode(FileInfo *self){
return PyLong_FromLong(self->flags);
}
PyObject* FileClass_available(FileInfo *self){
int available = hdfsAvailable(self->fs, self->file);
if (available < 0)
return PyErr_SetFromErrno(PyExc_IOError);
else
return PyLong_FromLong(available);
}
static int _ensure_open_for_reading(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForRead(self)){
#else
if(!hdfsFileIsOpenForRead(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in READ ('r') mode");
return 0; // False
}
return 1; // True
}
static Py_ssize_t _read_into_str(FileInfo *self, char* buf, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return -1;
}
tSize bytes_read = hdfsRead(self->fs, self->file, buf, nbytes);
if (bytes_read < 0) { // error
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _read_new_pystr(FileInfo* self, Py_ssize_t nbytes) {
if (nbytes < 0) { // read entire file
nbytes = hdfsAvailable(self->fs, self->file);
if (nbytes < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
// Allocate an uninitialized string object.
// We then access and directly modify the string's internal memory. This is
// ok until we release this string "into the wild".
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _read_into_str(self, PyString_AS_STRING(retval), nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
/*
* Seek to `pos` and read `nbytes` bytes into a the provided buffer.
*
* \return: Number of bytes read. In case of error this function sets
* the appropriate Python exception and returns -1.
*/
static Py_ssize_t _pread_into_str(FileInfo *self, char* buffer, Py_ssize_t pos, Py_ssize_t nbytes) {
Py_ssize_t orig_position = hdfsTell(self->fs, self->file);
if (orig_position < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, pos) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
tSize bytes_read = _read_into_str(self, buffer, nbytes);
if (bytes_read < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, orig_position) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _pread_new_pystr(FileInfo* self, Py_ssize_t pos, Py_ssize_t nbytes) {
if (nbytes < 0) { // read entire file
nbytes = hdfsAvailable(self->fs, self->file);
if (nbytes < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
// Allocate an uninitialized string object.
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _pread_into_str(self, PyString_AS_STRING(retval), pos, nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
PyObject* FileClass_read(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "n", &(nbytes)))
return NULL;
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
else if (nbytes == 0) {
return PyString_FromString("");
}
// else nbytes > 0
return _read_new_pystr(self, nbytes);
}
PyObject* FileClass_read_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "w*", &buffer))
return NULL;
Py_ssize_t bytes_read = _read_into_str(self, (char*)buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_pread(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t position;
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nn", &position, &nbytes))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
if (nbytes == 0)
return PyString_FromString("");
// else
return _pread_new_pystr(self, position, nbytes);
}
PyObject* FileClass_pread_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
Py_ssize_t position;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nw*", &position, &buffer))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
Py_ssize_t bytes_read = _pread_into_str(self, (char*)buffer.buf, position, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_seek(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset position;
if (! PyArg_ParseTuple(args, "n", &position))
return NULL;
int result = hdfsSeek(self->fs, self->file, position);
return Py_BuildValue("i", result);
}
PyObject* FileClass_tell(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset offset = hdfsTell(self->fs, self->file);
return Py_BuildValue("n", offset);
}
PyObject* FileClass_write(FileInfo* self, PyObject *args, PyObject *kwds)
{
char* buffer;
int buffer_length;
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return NULL;
}
if (! PyArg_ParseTuple(args, "s#", &buffer, &buffer_length))
return NULL;
int written = hdfsWrite(self->fs, self->file, buffer, buffer_length);
return Py_BuildValue("i", written);
}
PyObject* FileClass_write_chunk(FileInfo* self, PyObject *args, PyObject *kwds)
{
char* buffer;
int buffer_length;
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return NULL;
}
if (! PyArg_ParseTuple(args, "s#", &buffer, &buffer_length))
return NULL;
int written = hdfsWrite(self->fs, self->file, buffer, buffer_length);
return Py_BuildValue("i", written);
}
PyObject* FileClass_flush(FileInfo *self){
int result = hdfsFlush(self->fs, self->file);
return Py_BuildValue("i", result);
}
<commit_msg>Raise IOError on pos < 0 in hdfs_file.seek, like a Python file<commit_after>#include "hdfs_file.h"
#include "hdfs_utils.h"
using namespace std;
PyObject* FileClass_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
FileInfo *self;
self = (FileInfo *)type->tp_alloc(type, 0);
if (self != NULL) {
self->fs = NULL;
self->file = NULL;
self->flags = 0;
self->buff_size = 0;
self->replication = 1;
self->blocksize = 0;
self->readline_chunk_size = 16 * 1024; // 16 KB
#ifdef HADOOP_LIBHDFS_V1
self->stream_type = 0;
#endif
}
return (PyObject *)self;
}
#ifdef HADOOP_LIBHDFS_V1
bool hdfsFileIsOpenForWrite(FileInfo *f){
return f->stream_type == OUTPUT;
}
bool hdfsFileIsOpenForRead(FileInfo *f){
return f->stream_type == INPUT;
}
#endif
void FileClass_dealloc(FileInfo* self)
{
self->file = NULL;
self->ob_type->tp_free((PyObject*)self);
}
int FileClass_init(FileInfo *self, PyObject *args, PyObject *kwds)
{
if (! PyArg_ParseTuple(args, "OO", &(self->fs), &(self->file))) {
return -1;
}
return 0;
}
int FileClass_init_internal(FileInfo *self, hdfsFS fs, hdfsFile file)
{
self->fs = fs;
self->file = file;
return 0;
}
PyObject* FileClass_close(FileInfo* self){
int result = hdfsCloseFile(self->fs, self->file);
if (result < 0) {
return PyErr_SetFromErrno(PyExc_IOError);
}
else
return PyBool_FromLong(1);
}
PyObject* FileClass_mode(FileInfo* self){
return FileClass_get_mode(self);
}
PyObject* FileClass_get_mode(FileInfo *self){
return PyLong_FromLong(self->flags);
}
PyObject* FileClass_available(FileInfo *self){
int available = hdfsAvailable(self->fs, self->file);
if (available < 0)
return PyErr_SetFromErrno(PyExc_IOError);
else
return PyLong_FromLong(available);
}
static int _ensure_open_for_reading(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForRead(self)){
#else
if(!hdfsFileIsOpenForRead(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in READ ('r') mode");
return 0; // False
}
return 1; // True
}
static Py_ssize_t _read_into_str(FileInfo *self, char* buf, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return -1;
}
tSize bytes_read = hdfsRead(self->fs, self->file, buf, nbytes);
if (bytes_read < 0) { // error
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _read_new_pystr(FileInfo* self, Py_ssize_t nbytes) {
if (nbytes < 0) { // read entire file
nbytes = hdfsAvailable(self->fs, self->file);
if (nbytes < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
// Allocate an uninitialized string object.
// We then access and directly modify the string's internal memory. This is
// ok until we release this string "into the wild".
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _read_into_str(self, PyString_AS_STRING(retval), nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
/*
* Seek to `pos` and read `nbytes` bytes into a the provided buffer.
*
* \return: Number of bytes read. In case of error this function sets
* the appropriate Python exception and returns -1.
*/
static Py_ssize_t _pread_into_str(FileInfo *self, char* buffer, Py_ssize_t pos, Py_ssize_t nbytes) {
Py_ssize_t orig_position = hdfsTell(self->fs, self->file);
if (orig_position < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, pos) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
tSize bytes_read = _read_into_str(self, buffer, nbytes);
if (bytes_read < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, orig_position) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _pread_new_pystr(FileInfo* self, Py_ssize_t pos, Py_ssize_t nbytes) {
if (nbytes < 0) { // read entire file
nbytes = hdfsAvailable(self->fs, self->file);
if (nbytes < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
// Allocate an uninitialized string object.
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _pread_into_str(self, PyString_AS_STRING(retval), pos, nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
PyObject* FileClass_read(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "n", &(nbytes)))
return NULL;
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
else if (nbytes == 0) {
return PyString_FromString("");
}
// else nbytes > 0
return _read_new_pystr(self, nbytes);
}
PyObject* FileClass_read_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "w*", &buffer))
return NULL;
Py_ssize_t bytes_read = _read_into_str(self, (char*)buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_pread(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t position;
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nn", &position, &nbytes))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
if (nbytes == 0)
return PyString_FromString("");
// else
return _pread_new_pystr(self, position, nbytes);
}
PyObject* FileClass_pread_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
Py_ssize_t position;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nw*", &position, &buffer))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
Py_ssize_t bytes_read = _pread_into_str(self, (char*)buffer.buf, position, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_seek(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset position;
if (! PyArg_ParseTuple(args, "n", &position))
return NULL;
if (position < 0) {
// raise an IOError like a regular python file
errno = EINVAL;
PyErr_SetFromErrno(PyExc_IOError);
errno = 0;
return NULL;
}
int result = hdfsSeek(self->fs, self->file, position);
return Py_BuildValue("i", result);
}
PyObject* FileClass_tell(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset offset = hdfsTell(self->fs, self->file);
return Py_BuildValue("n", offset);
}
PyObject* FileClass_write(FileInfo* self, PyObject *args, PyObject *kwds)
{
char* buffer;
int buffer_length;
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return NULL;
}
if (! PyArg_ParseTuple(args, "s#", &buffer, &buffer_length))
return NULL;
int written = hdfsWrite(self->fs, self->file, buffer, buffer_length);
return Py_BuildValue("i", written);
}
PyObject* FileClass_write_chunk(FileInfo* self, PyObject *args, PyObject *kwds)
{
char* buffer;
int buffer_length;
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return NULL;
}
if (! PyArg_ParseTuple(args, "s#", &buffer, &buffer_length))
return NULL;
int written = hdfsWrite(self->fs, self->file, buffer, buffer_length);
return Py_BuildValue("i", written);
}
PyObject* FileClass_flush(FileInfo *self){
int result = hdfsFlush(self->fs, self->file);
return Py_BuildValue("i", result);
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "HelperDefinitions.h"
namespace helper
{
StringW to_wide( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_wide(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return L"";
}
}
String8 to_utf8( const StringW &str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const StringW &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
#if (_MSC_VER == 1900 || _MSC_VER == 1910) //bug-workaround (VC_2015)
String8 to_utf8( const String16 &str )
{
std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> converter;
try
{
auto p = reinterpret_cast<const int16_t *>( str.data() );
return converter.to_bytes( p, p + str.size() );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String16 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String8 to_utf8( const String32 &str )
{
std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> converter;
try
{
auto p = reinterpret_cast<const int32_t *>( str.data() );
return converter.to_bytes( p, p + str.size() );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String32 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String16 to_utf16( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> converter;
try
{
auto p = converter.from_bytes( str );
return String16( reinterpret_cast<const char16_t *>( p.data() ) );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf16(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return u"";
}
}
String32 to_utf32( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> converter;
try
{
auto p = converter.from_bytes( str );
return String32( reinterpret_cast<const char32_t *>( p.data() ) );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf32(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return U"";
}
}
#else
String8 to_utf8( const String16 &str )
{
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String16 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String8 to_utf8( const String32 &str )
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String32 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String16 to_utf16( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf16(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return u"";
}
}
String32 to_utf32( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf32(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return U"";
}
}
#endif
template<>
std::string int_to_hex( s8 i )
{
std::stringstream stream;
stream << std::setfill( '0' ) << std::setw( 2 )
<< std::hex << static_cast<int>( i );
return stream.str();
}
template<>
std::string int_to_hex( u8 i )
{
std::stringstream stream;
stream << std::setfill( '0' ) << std::setw( 2 )
<< std::hex << static_cast<int>( i );
return stream.str();
}
inline void log( const String8 &text, LogLevel level )
{
logMultiline( text + '\n', level );
}
inline void logMultiline( const String8 &text, LogLevel level )
{
static std::recursive_mutex mx;
std::lock_guard<std::recursive_mutex> lock( mx );
#ifdef _WIN32
OutputDebugStringW( to_wide( String8( level == LogLevel::Debug ? "D" : level == LogLevel::Information ? "I" : level == LogLevel::Warning ? "W" : level == LogLevel::Error ? "E" : "UKN" ) + "/ " + text ).c_str() );
HANDLE consoleHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if( level == LogLevel::Debug ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_GREEN | FOREGROUND_INTENSITY );
else if( level == LogLevel::Information ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
else if( level == LogLevel::Warning )SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY );
else if( level == LogLevel::Error ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_INTENSITY );
#endif // _WIN32
if( level == LogLevel::Error || level == LogLevel::Warning )
{
std::wcerr << to_wide( text );
}
else
{
std::wcout << to_wide( text );
}
#ifdef _WIN32
SetConsoleTextAttribute( consoleHandle, 7 );//Reset color
#endif // _WIN32
}
fs::path resolve( const fs::path &p, const fs::path &base )
{
fs::path ret;
fs::path absolute = fs::absolute( p, base );
for( fs::path::iterator it = absolute.begin() ; it != absolute.end() ; it++ )
{
if( *it == ".." )
{//Go one dir backwars
if( fs::is_symlink( ret ) )
{//Check for symlinks
ret /= *it;
}
else if( ret.filename() == ".." )
{//Multiple ..s'
ret /= *it;
}
// Otherwise it should be safe to resolve the parent
else
ret = ret.parent_path();
}
else if( *it == "." );//Ignore
else
{//Normal dirs
ret /= *it;
}
}
return ret;
}
}
<commit_msg>Fixed bug with newer visual studio compiler<commit_after>#include "stdafx.h"
#include "HelperDefinitions.h"
namespace helper
{
StringW to_wide( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_wide(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return L"";
}
}
String8 to_utf8( const StringW &str )
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const StringW &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
#if (_MSC_VER >= 1900 && _MSC_VER <= 1911) //bug-workaround (VC_2015+)
String8 to_utf8( const String16 &str )
{
std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> converter;
try
{
auto p = reinterpret_cast<const int16_t *>( str.data() );
return converter.to_bytes( p, p + str.size() );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String16 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String8 to_utf8( const String32 &str )
{
std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> converter;
try
{
auto p = reinterpret_cast<const int32_t *>( str.data() );
return converter.to_bytes( p, p + str.size() );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String32 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String16 to_utf16( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<int16_t>, int16_t> converter;
try
{
auto p = converter.from_bytes( str );
return String16( reinterpret_cast<const char16_t *>( p.data() ) );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf16(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return u"";
}
}
String32 to_utf32( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<int32_t>, int32_t> converter;
try
{
auto p = converter.from_bytes( str );
return String32( reinterpret_cast<const char32_t *>( p.data() ) );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf32(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return U"";
}
}
#else
String8 to_utf8( const String16 &str )
{
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String16 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String8 to_utf8( const String32 &str )
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
try
{
return converter.to_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf8(const String32 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return "";
}
}
String16 to_utf16( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf16(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return u"";
}
}
String32 to_utf32( const String8 &str )
{
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
try
{
return converter.from_bytes( str );
}
catch( std::range_error error )
{
log( "Conversation failure 'to_utf32(const String8 &)'. Message: " + String8( error.what() ), LogLevel::Warning );
return U"";
}
}
#endif
template<>
std::string int_to_hex( s8 i )
{
std::stringstream stream;
stream << std::setfill( '0' ) << std::setw( 2 )
<< std::hex << static_cast<int>( i );
return stream.str();
}
template<>
std::string int_to_hex( u8 i )
{
std::stringstream stream;
stream << std::setfill( '0' ) << std::setw( 2 )
<< std::hex << static_cast<int>( i );
return stream.str();
}
inline void log( const String8 &text, LogLevel level )
{
logMultiline( text + '\n', level );
}
inline void logMultiline( const String8 &text, LogLevel level )
{
static std::recursive_mutex mx;
std::lock_guard<std::recursive_mutex> lock( mx );
#ifdef _WIN32
OutputDebugStringW( to_wide( String8( level == LogLevel::Debug ? "D" : level == LogLevel::Information ? "I" : level == LogLevel::Warning ? "W" : level == LogLevel::Error ? "E" : "UKN" ) + "/ " + text ).c_str() );
HANDLE consoleHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if( level == LogLevel::Debug ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_GREEN | FOREGROUND_INTENSITY );
else if( level == LogLevel::Information ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
else if( level == LogLevel::Warning )SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY );
else if( level == LogLevel::Error ) SetConsoleTextAttribute( consoleHandle, FOREGROUND_RED | FOREGROUND_INTENSITY );
#endif // _WIN32
if( level == LogLevel::Error || level == LogLevel::Warning )
{
std::wcerr << to_wide( text );
}
else
{
std::wcout << to_wide( text );
}
#ifdef _WIN32
SetConsoleTextAttribute( consoleHandle, 7 );//Reset color
#endif // _WIN32
}
fs::path resolve( const fs::path &p, const fs::path &base )
{
fs::path ret;
fs::path absolute = fs::absolute( p, base );
for( fs::path::iterator it = absolute.begin() ; it != absolute.end() ; it++ )
{
if( *it == ".." )
{//Go one dir backwars
if( fs::is_symlink( ret ) )
{//Check for symlinks
ret /= *it;
}
else if( ret.filename() == ".." )
{//Multiple ..s'
ret /= *it;
}
// Otherwise it should be safe to resolve the parent
else
ret = ret.parent_path();
}
else if( *it == "." );//Ignore
else
{//Normal dirs
ret /= *it;
}
}
return ret;
}
}
<|endoftext|> |
<commit_before>#include <HTTPClient.h>
#include <ESP32WebServer.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include "PacmanServer.h"
PacmanServer::PacmanServer(String registerUrl, String algorithmUrl, String name, int serverPort)
:server(serverPort),
gameStatus(PLAYING),
quarantaine(0),
score(0),
lives(3)
{
int httpCode = 0;
//register to server
do
{
http.begin(registerUrl);
String message = "{ \"name\": \"" + name + "\" }";
httpCode = http.POST(message);
} while (httpCode != HTTP_CODE_OK);
DynamicJsonBuffer jsonBuffer;
String registrationResponse = http.getString();
http.end();
//set local variables
JsonObject& root = jsonBuffer.parseObject(registrationResponse);
if (root["type"] == "pacman")
{
character = PACMAN;
}
else
{
character = GHOST;
}
//start connection with algorithmserver
http.begin(algorithmUrl);
http.setReuse(true);
http.addHeader("Content-Type", "application/json");
http.POST(registrationResponse);
//setting up server on device
server.begin();
server.on("/event/location", std::bind(&PacmanServer::event_location, this));
server.on("/event/location_error", std::bind(&PacmanServer::event_location_error, this));
server.on("/event/food", std::bind(&PacmanServer::event_food, this));
server.on("/event/cherry", std::bind(&PacmanServer::event_cherry, this));
server.on("/event/energizer", std::bind(&PacmanServer::event_energizer, this));
server.on("/event/cherry_spawned", std::bind(&PacmanServer::event_cherry_spawned, this));
server.on("/event/collision", std::bind(&PacmanServer::event_collision, this));
server.on("/event/quarantine", std::bind(&PacmanServer::event_quarantine, this));
server.on("/event/game_over", std::bind(&PacmanServer::event_game_over, this));
server.on("/event/game_won", std::bind(&PacmanServer::event_game_won, this));
}
PacmanServer::~PacmanServer()
{
http.end();
server.close();
}
void PacmanServer::handleEvents()
{
server.handleClient();
}
void PacmanServer::setLocation(int x_pixel, int y_pixel)
{
posX= 5* x_pixel;
posY= 5* y_pixel;
}
Role PacmanServer::getRole()
{
return character;
}
int PacmanServer::getScore()
{
return score;
}
int PacmanServer::getLives()
{
return lives;
}
bool PacmanServer::inQuarantaine()
{
if (millis() > quarantaine)
{
return false;
}
else
{
return true;
}
}
Status PacmanServer::getGameStatus()
{
return gameStatus;
}
void PacmanServer::event_location()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "{\"x\":" + String(posX) + ",\"y\":"+String(posY)+"}");
}
void PacmanServer::event_location_error()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_food()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_cherry()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_energizer()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_cherry_spawned()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_collision()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_quarantine()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
quarantaine = millis() + 10000;
}
void PacmanServer::event_game_over()
{
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(server.arg(0));
lives = root["lives"];
score = root["score"];
server.send(200, "application/json; charset=utf-8", "");
gameStatus = LOST;
}
void PacmanServer::event_game_won()
{
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(server.arg(0));
lives = root["lives"];
score = root["score"];
server.send(200, "application/json; charset=utf-8", "");
gameStatus = WON;
}<commit_msg>Jsonbuffersize definition added<commit_after>#include <HTTPClient.h>
#include <ESP32WebServer.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include "PacmanServer.h"
PacmanServer::PacmanServer(String registerUrl, String algorithmUrl, String name, int serverPort)
:server(serverPort),
gameStatus(PLAYING),
quarantaine(0),
score(0),
lives(3)
{
int httpCode = 0;
//register to server
do
{
http.begin(registerUrl);
String message = "{ \"name\": \"" + name + "\" }";
httpCode = http.POST(message);
} while (httpCode != HTTP_CODE_OK);
const size_t bufferSize = JSON_ARRAY_SIZE(4) + JSON_ARRAY_SIZE(62) + 66*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + 1180;
DynamicJsonBuffer jsonBuffer(bufferSize);
String registrationResponse = http.getString();
http.end();
//set local variables
JsonObject& root = jsonBuffer.parseObject(registrationResponse);
if (root["type"] == "pacman")
{
character = PACMAN;
}
else
{
character = GHOST;
}
//start connection with algorithmserver
http.begin(algorithmUrl);
http.setReuse(true);
http.addHeader("Content-Type", "application/json");
http.POST(registrationResponse);
//setting up server on device
server.begin();
server.on("/event/location", std::bind(&PacmanServer::event_location, this));
server.on("/event/location_error", std::bind(&PacmanServer::event_location_error, this));
server.on("/event/food", std::bind(&PacmanServer::event_food, this));
server.on("/event/cherry", std::bind(&PacmanServer::event_cherry, this));
server.on("/event/energizer", std::bind(&PacmanServer::event_energizer, this));
server.on("/event/cherry_spawned", std::bind(&PacmanServer::event_cherry_spawned, this));
server.on("/event/collision", std::bind(&PacmanServer::event_collision, this));
server.on("/event/quarantine", std::bind(&PacmanServer::event_quarantine, this));
server.on("/event/game_over", std::bind(&PacmanServer::event_game_over, this));
server.on("/event/game_won", std::bind(&PacmanServer::event_game_won, this));
}
PacmanServer::~PacmanServer()
{
http.end();
server.close();
}
void PacmanServer::handleEvents()
{
server.handleClient();
}
void PacmanServer::setLocation(int x_pixel, int y_pixel)
{
posX= 5* x_pixel;
posY= 5* y_pixel;
}
Role PacmanServer::getRole()
{
return character;
}
int PacmanServer::getScore()
{
return score;
}
int PacmanServer::getLives()
{
return lives;
}
bool PacmanServer::inQuarantaine()
{
if (millis() > quarantaine)
{
return false;
}
else
{
return true;
}
}
Status PacmanServer::getGameStatus()
{
return gameStatus;
}
void PacmanServer::event_location()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "{\"x\":" + String(posX) + ",\"y\":"+String(posY)+"}");
}
void PacmanServer::event_location_error()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_food()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_cherry()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_energizer()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_cherry_spawned()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_collision()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
}
void PacmanServer::event_quarantine()
{
http.addHeader("Content-Type", "application/json");
http.POST(server.arg(0));
server.send(200, "application/json; charset=utf-8", "");
quarantaine = millis() + 10000;
}
void PacmanServer::event_game_over()
{
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(server.arg(0));
lives = root["lives"];
score = root["score"];
server.send(200, "application/json; charset=utf-8", "");
gameStatus = LOST;
}
void PacmanServer::event_game_won()
{
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(server.arg(0));
lives = root["lives"];
score = root["score"];
server.send(200, "application/json; charset=utf-8", "");
gameStatus = WON;
}<|endoftext|> |
<commit_before>// Copyright 2017 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 <memory>
#include "gtest/gtest.h"
#include "ray/common/test_util.h"
#include "ray/gcs/pubsub/gcs_pub_sub.h"
namespace ray {
class GcsPubSubTest : public ::testing::Test {
public:
GcsPubSubTest() { TestSetupUtil::StartUpRedisServers(std::vector<int>()); }
virtual ~GcsPubSubTest() { TestSetupUtil::ShutDownRedisServers(); }
protected:
virtual void SetUp() override {
thread_io_service_.reset(new std::thread([this] {
std::unique_ptr<boost::asio::io_service::work> work(
new boost::asio::io_service::work(io_service_));
io_service_.run();
}));
gcs::RedisClientOptions redis_client_options(
"127.0.0.1", TEST_REDIS_SERVER_PORTS.front(), "", true);
client_ = std::make_shared<gcs::RedisClient>(redis_client_options);
RAY_CHECK_OK(client_->Connect(io_service_));
pub_sub_ = std::make_shared<gcs::GcsPubSub>(client_);
}
virtual void TearDown() override {
client_->Disconnect();
io_service_.stop();
thread_io_service_->join();
thread_io_service_.reset();
pub_sub_.reset();
// Note: If we immediately reset client_ after io_service_ stop, because client_ still
// has thread executing logic, such as unsubscribe's callback, the problem of heap
// used after free will occur.
client_.reset();
}
void Subscribe(const std::string &channel, const std::string &id,
std::vector<std::string> &result) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [&result](const std::string &id, const std::string &data) {
result.push_back(data);
};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, id, subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
}
void SubscribeAll(const std::string &channel,
std::vector<std::pair<std::string, std::string>> &result) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [&result](const std::string &id, const std::string &data) {
result.push_back(std::make_pair(id, data));
};
RAY_CHECK_OK((pub_sub_->SubscribeAll(channel, subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
}
bool Unsubscribe(const std::string &channel, const std::string &id) {
return pub_sub_->Unsubscribe(channel, id).ok();
}
bool Publish(const std::string &channel, const std::string &id,
const std::string &data) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
RAY_CHECK_OK((pub_sub_->Publish(channel, id, data, done)));
return WaitReady(promise.get_future(), timeout_ms_);
}
bool WaitReady(std::future<bool> future, const std::chrono::milliseconds &timeout_ms) {
auto status = future.wait_for(timeout_ms);
return status == std::future_status::ready && future.get();
}
template <typename Data>
void WaitPendingDone(const std::vector<Data> &data, int expected_count) {
auto condition = [&data, expected_count]() {
RAY_CHECK((int)data.size() <= expected_count)
<< "Expected " << expected_count << " data " << data.size();
return (int)data.size() == expected_count;
};
EXPECT_TRUE(WaitForCondition(condition, timeout_ms_.count()));
}
std::shared_ptr<gcs::RedisClient> client_;
const std::chrono::milliseconds timeout_ms_{60000};
std::shared_ptr<gcs::GcsPubSub> pub_sub_;
private:
boost::asio::io_service io_service_;
std::unique_ptr<std::thread> thread_io_service_;
};
TEST_F(GcsPubSubTest, TestPubSubApi) {
std::string channel("channel");
std::string id("id");
std::string data("data");
std::vector<std::pair<std::string, std::string>> all_result;
SubscribeAll(channel, all_result);
std::vector<std::string> result;
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 1);
WaitPendingDone(all_result, 1);
Unsubscribe(channel, id);
Publish(channel, id, data);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_EQ(result.size(), 1);
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 2);
WaitPendingDone(all_result, 3);
}
TEST_F(GcsPubSubTest, TestManyPubsub) {
std::string channel("channel");
std::string id("id");
std::string data("data");
std::vector<std::pair<std::string, std::string>> all_result;
SubscribeAll(channel, all_result);
// Test many concurrent subscribes and unsubscribes.
for (int i = 0; i < 1000; i++) {
auto subscribe = [](const std::string &id, const std::string &data) {};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, id, subscribe, nullptr)));
RAY_CHECK_OK((pub_sub_->Unsubscribe(channel, id)));
}
for (int i = 0; i < 1000; i++) {
std::vector<std::string> result;
// Use the synchronous subscribe to make sure our SUBSCRIBE message reaches
// Redis before the PUBLISH.
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 1);
WaitPendingDone(all_result, i + 1);
RAY_CHECK_OK((pub_sub_->Unsubscribe(channel, id)));
}
}
TEST_F(GcsPubSubTest, TestMultithreading) {
std::string channel("channel");
auto sub_message_count = std::make_shared<std::atomic<int>>(0);
auto sub_finished_count = std::make_shared<std::atomic<int>>(0);
int size = 5;
std::vector<std::unique_ptr<std::thread>> threads;
threads.resize(size);
for (int index = 0; index < size; ++index) {
std::stringstream ss;
ss << index;
auto id = ss.str();
threads[index].reset(
new std::thread([this, sub_message_count, sub_finished_count, id, channel] {
auto subscribe = [sub_message_count](const std::string &id,
const std::string &data) {
++(*sub_message_count);
};
auto on_done = [sub_finished_count](const Status &status) {
RAY_CHECK_OK(status);
++(*sub_finished_count);
};
RAY_CHECK_OK(pub_sub_->Subscribe(channel, id, subscribe, on_done));
}));
}
auto sub_finished_condition = [sub_finished_count, size]() {
return sub_finished_count->load() == size;
};
EXPECT_TRUE(WaitForCondition(sub_finished_condition, timeout_ms_.count()));
for (auto &thread : threads) {
thread->join();
thread.reset();
}
std::string data("data");
for (int index = 0; index < size; ++index) {
std::stringstream ss;
ss << index;
auto id = ss.str();
threads[index].reset(new std::thread([this, channel, id, data] {
RAY_CHECK_OK(pub_sub_->Publish(channel, id, data, nullptr));
}));
}
auto sub_message_condition = [sub_message_count, size]() {
return sub_message_count->load() == size;
};
EXPECT_TRUE(WaitForCondition(sub_message_condition, timeout_ms_.count()));
for (auto &thread : threads) {
thread->join();
thread.reset();
}
}
TEST_F(GcsPubSubTest, TestPubSubWithTableData) {
std::string channel("channel");
std::string data("data");
std::vector<std::string> result;
int size = 1000;
for (int index = 0; index < size; ++index) {
ObjectID object_id = ObjectID::FromRandom();
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [this, channel, &result](const std::string &id,
const std::string &data) {
RAY_CHECK_OK(pub_sub_->Unsubscribe(channel, id));
result.push_back(data);
};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, object_id.Hex(), subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
RAY_CHECK_OK((pub_sub_->Publish(channel, object_id.Hex(), data, nullptr)));
}
WaitPendingDone(result, size);
}
} // namespace ray
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
RAY_CHECK(argc == 4);
ray::TEST_REDIS_SERVER_EXEC_PATH = argv[1];
ray::TEST_REDIS_CLIENT_EXEC_PATH = argv[2];
ray::TEST_REDIS_MODULE_LIBRARY_PATH = argv[3];
return RUN_ALL_TESTS();
}
<commit_msg>[Tests]lock vector to avoid potential flaky test (#9656)<commit_after>// Copyright 2017 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 <memory>
#include "gtest/gtest.h"
#include "ray/common/test_util.h"
#include "ray/gcs/pubsub/gcs_pub_sub.h"
namespace ray {
class GcsPubSubTest : public ::testing::Test {
public:
GcsPubSubTest() { TestSetupUtil::StartUpRedisServers(std::vector<int>()); }
virtual ~GcsPubSubTest() { TestSetupUtil::ShutDownRedisServers(); }
protected:
virtual void SetUp() override {
thread_io_service_.reset(new std::thread([this] {
std::unique_ptr<boost::asio::io_service::work> work(
new boost::asio::io_service::work(io_service_));
io_service_.run();
}));
gcs::RedisClientOptions redis_client_options(
"127.0.0.1", TEST_REDIS_SERVER_PORTS.front(), "", true);
client_ = std::make_shared<gcs::RedisClient>(redis_client_options);
RAY_CHECK_OK(client_->Connect(io_service_));
pub_sub_ = std::make_shared<gcs::GcsPubSub>(client_);
}
virtual void TearDown() override {
client_->Disconnect();
io_service_.stop();
thread_io_service_->join();
thread_io_service_.reset();
pub_sub_.reset();
// Note: If we immediately reset client_ after io_service_ stop, because client_ still
// has thread executing logic, such as unsubscribe's callback, the problem of heap
// used after free will occur.
client_.reset();
}
void Subscribe(const std::string &channel, const std::string &id,
std::vector<std::string> &result) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [this, &result](const std::string &id, const std::string &data) {
absl::MutexLock lock(&vector_mutex_);
result.push_back(data);
};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, id, subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
}
void SubscribeAll(const std::string &channel,
std::vector<std::pair<std::string, std::string>> &result) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [this, &result](const std::string &id, const std::string &data) {
absl::MutexLock lock(&vector_mutex_);
result.push_back(std::make_pair(id, data));
};
RAY_CHECK_OK((pub_sub_->SubscribeAll(channel, subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
}
bool Unsubscribe(const std::string &channel, const std::string &id) {
return pub_sub_->Unsubscribe(channel, id).ok();
}
bool Publish(const std::string &channel, const std::string &id,
const std::string &data) {
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
RAY_CHECK_OK((pub_sub_->Publish(channel, id, data, done)));
return WaitReady(promise.get_future(), timeout_ms_);
}
bool WaitReady(std::future<bool> future, const std::chrono::milliseconds &timeout_ms) {
auto status = future.wait_for(timeout_ms);
return status == std::future_status::ready && future.get();
}
template <typename Data>
void WaitPendingDone(const std::vector<Data> &data, int expected_count) {
auto condition = [this, &data, expected_count]() {
absl::MutexLock lock(&vector_mutex_);
RAY_CHECK((int)data.size() <= expected_count)
<< "Expected " << expected_count << " data " << data.size();
return (int)data.size() == expected_count;
};
EXPECT_TRUE(WaitForCondition(condition, timeout_ms_.count()));
}
std::shared_ptr<gcs::RedisClient> client_;
const std::chrono::milliseconds timeout_ms_{60000};
std::shared_ptr<gcs::GcsPubSub> pub_sub_;
absl::Mutex vector_mutex_;
private:
boost::asio::io_service io_service_;
std::unique_ptr<std::thread> thread_io_service_;
};
TEST_F(GcsPubSubTest, TestPubSubApi) {
std::string channel("channel");
std::string id("id");
std::string data("data");
std::vector<std::pair<std::string, std::string>> all_result;
SubscribeAll(channel, all_result);
std::vector<std::string> result;
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 1);
WaitPendingDone(all_result, 1);
Unsubscribe(channel, id);
Publish(channel, id, data);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_EQ(result.size(), 1);
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 2);
WaitPendingDone(all_result, 3);
}
TEST_F(GcsPubSubTest, TestManyPubsub) {
std::string channel("channel");
std::string id("id");
std::string data("data");
std::vector<std::pair<std::string, std::string>> all_result;
SubscribeAll(channel, all_result);
// Test many concurrent subscribes and unsubscribes.
for (int i = 0; i < 1000; i++) {
auto subscribe = [](const std::string &id, const std::string &data) {};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, id, subscribe, nullptr)));
RAY_CHECK_OK((pub_sub_->Unsubscribe(channel, id)));
}
for (int i = 0; i < 1000; i++) {
std::vector<std::string> result;
// Use the synchronous subscribe to make sure our SUBSCRIBE message reaches
// Redis before the PUBLISH.
Subscribe(channel, id, result);
Publish(channel, id, data);
WaitPendingDone(result, 1);
WaitPendingDone(all_result, i + 1);
RAY_CHECK_OK((pub_sub_->Unsubscribe(channel, id)));
}
}
TEST_F(GcsPubSubTest, TestMultithreading) {
std::string channel("channel");
auto sub_message_count = std::make_shared<std::atomic<int>>(0);
auto sub_finished_count = std::make_shared<std::atomic<int>>(0);
int size = 5;
std::vector<std::unique_ptr<std::thread>> threads;
threads.resize(size);
for (int index = 0; index < size; ++index) {
std::stringstream ss;
ss << index;
auto id = ss.str();
threads[index].reset(
new std::thread([this, sub_message_count, sub_finished_count, id, channel] {
auto subscribe = [sub_message_count](const std::string &id,
const std::string &data) {
++(*sub_message_count);
};
auto on_done = [sub_finished_count](const Status &status) {
RAY_CHECK_OK(status);
++(*sub_finished_count);
};
RAY_CHECK_OK(pub_sub_->Subscribe(channel, id, subscribe, on_done));
}));
}
auto sub_finished_condition = [sub_finished_count, size]() {
return sub_finished_count->load() == size;
};
EXPECT_TRUE(WaitForCondition(sub_finished_condition, timeout_ms_.count()));
for (auto &thread : threads) {
thread->join();
thread.reset();
}
std::string data("data");
for (int index = 0; index < size; ++index) {
std::stringstream ss;
ss << index;
auto id = ss.str();
threads[index].reset(new std::thread([this, channel, id, data] {
RAY_CHECK_OK(pub_sub_->Publish(channel, id, data, nullptr));
}));
}
auto sub_message_condition = [sub_message_count, size]() {
return sub_message_count->load() == size;
};
EXPECT_TRUE(WaitForCondition(sub_message_condition, timeout_ms_.count()));
for (auto &thread : threads) {
thread->join();
thread.reset();
}
}
TEST_F(GcsPubSubTest, TestPubSubWithTableData) {
std::string channel("channel");
std::string data("data");
std::vector<std::string> result;
int size = 1000;
for (int index = 0; index < size; ++index) {
ObjectID object_id = ObjectID::FromRandom();
std::promise<bool> promise;
auto done = [&promise](const Status &status) { promise.set_value(status.ok()); };
auto subscribe = [this, channel, &result](const std::string &id,
const std::string &data) {
RAY_CHECK_OK(pub_sub_->Unsubscribe(channel, id));
absl::MutexLock lock(&vector_mutex_);
result.push_back(data);
};
RAY_CHECK_OK((pub_sub_->Subscribe(channel, object_id.Hex(), subscribe, done)));
WaitReady(promise.get_future(), timeout_ms_);
RAY_CHECK_OK((pub_sub_->Publish(channel, object_id.Hex(), data, nullptr)));
}
WaitPendingDone(result, size);
}
} // namespace ray
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
RAY_CHECK(argc == 4);
ray::TEST_REDIS_SERVER_EXEC_PATH = argv[1];
ray::TEST_REDIS_CLIENT_EXEC_PATH = argv[2];
ray::TEST_REDIS_MODULE_LIBRARY_PATH = argv[3];
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <[email protected]> *
* Raphael Hiesgen <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#include <sstream>
#include <iostream>
#include <stdexcept>
#include "cppa/cppa.hpp"
#include "cppa/opencl/command_dispatcher.hpp"
using namespace std;
namespace cppa { namespace opencl {
struct command_dispatcher::worker {
command_dispatcher* m_parent;
typedef command_ptr job_ptr;
job_queue* m_job_queue;
thread m_thread;
job_ptr m_dummy;
worker(command_dispatcher* parent, job_queue* jq, job_ptr dummy)
: m_parent(parent), m_job_queue(jq), m_dummy(dummy) { }
void start() {
m_thread = thread(&command_dispatcher::worker_loop, this);
}
worker(const worker&) = delete;
worker& operator=(const worker&) = delete;
void operator()() {
job_ptr job;
for (;;) {
/*
* todo:
* manage device usage
* wait for device
*/
// adopt reference count of job queue
job.adopt(m_job_queue->pop());
if(job != m_dummy) {
try {
cl_command_queue cmd_q =
m_parent->m_devices.front().cmd_queue.get();
job->enqueue(cmd_q);
}
catch (exception& e) {
cerr << e.what() << endl;
}
}
else {
cout << "worker done" << endl;
return;
}
}
}
};
void command_dispatcher::worker_loop(command_dispatcher::worker* w) {
(*w)();
}
void command_dispatcher::supervisor_loop(command_dispatcher* scheduler,
job_queue* jq, command_ptr m_dummy) {
unique_ptr<command_dispatcher::worker> worker;
worker.reset(new command_dispatcher::worker(scheduler, jq, m_dummy));
worker->start();
worker->m_thread.join();
worker.reset();
cout << "supervisor done" << endl;
}
void command_dispatcher::initialize() {
m_dummy = make_counted<command_dummy>();
cl_int err{0};
/* find up to two available platforms */
vector<cl_platform_id> ids(2);
cl_uint number_of_platforms;
err = clGetPlatformIDs(ids.size(), ids.data(), &number_of_platforms);
if (err != CL_SUCCESS) {
throw logic_error("[!!!] clGetPlatformIDs: '"
+ get_opencl_error(err)
+ "'.");
}
else if (number_of_platforms < 1) {
throw logic_error("[!!!] clGetPlatformIDs: 'no platforms found'.");
}
/* find gpu devices on our platform */
int pid{0};
cl_uint num_devices{0};
// cout << "Currently only looking for cpu devices!" << endl;
cl_device_type dev_type{CL_DEVICE_TYPE_GPU};
err = clGetDeviceIDs(ids[pid], dev_type, 0, NULL, &num_devices);
if (err == CL_DEVICE_NOT_FOUND) {
cout << "NO GPU DEVICES FOUND! LOOKING FOR CPU DEVICES NOW ..." << endl;
dev_type = CL_DEVICE_TYPE_CPU;
err = clGetDeviceIDs(ids[pid], dev_type, 0, NULL, &num_devices);
}
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clGetDeviceIDs: '"
+ get_opencl_error(err)
+ "'.");
}
vector<cl_device_id> devices(num_devices);
err = clGetDeviceIDs(ids[pid], dev_type, num_devices, devices.data(), NULL);
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clGetDeviceIDs: '"
+ get_opencl_error(err)
+ "'.");
}
/* create a context */
m_context.adopt(clCreateContext(0, 1, devices.data(), NULL, NULL, &err));
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clCreateContext: '"
+ get_opencl_error(err)
+ "'.");
}
for (auto& d : devices) {
device_ptr device;
device.adopt(d);
unsigned id{++dev_id_gen};
command_queue_ptr cmd_queue;
cmd_queue.adopt(clCreateCommandQueue(m_context.get(),
device.get(),
CL_QUEUE_PROFILING_ENABLE,
&err));
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clCreateCommandQueue (" << id << "): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
size_t return_size{0};
size_t max_work_group_size{0};
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t),
&max_work_group_size,
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_GROUP_SIZE): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
cl_uint max_work_item_dimensions = 0;
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
sizeof(cl_uint),
&max_work_item_dimensions,
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
vector<size_t> max_work_items_per_dim(max_work_item_dimensions);
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_ITEM_SIZES,
sizeof(size_t)*max_work_item_dimensions,
max_work_items_per_dim.data(),
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_ITEM_SIZES): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
device_info dev_info{id,
cmd_queue,
device,
max_work_group_size,
max_work_item_dimensions,
move(max_work_items_per_dim)};
m_devices.push_back(move(dev_info));
}
m_supervisor = thread(&command_dispatcher::supervisor_loop,
this,
&m_job_queue,
m_dummy);
}
void command_dispatcher::destroy() {
m_dummy->ref(); // reference of m_job_queue
m_job_queue.push_back(m_dummy.get());
m_supervisor.join();
delete this;
}
void command_dispatcher::dispose() {
delete this;
}
} } // namespace cppa::opencl
<commit_msg>added clFlush after enqueue<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <[email protected]> *
* Raphael Hiesgen <[email protected]> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#include <sstream>
#include <iostream>
#include <stdexcept>
#include "cppa/cppa.hpp"
#include "cppa/opencl/command_dispatcher.hpp"
using namespace std;
namespace cppa { namespace opencl {
struct command_dispatcher::worker {
command_dispatcher* m_parent;
typedef command_ptr job_ptr;
job_queue* m_job_queue;
thread m_thread;
job_ptr m_dummy;
worker(command_dispatcher* parent, job_queue* jq, job_ptr dummy)
: m_parent(parent), m_job_queue(jq), m_dummy(dummy) { }
void start() {
m_thread = thread(&command_dispatcher::worker_loop, this);
}
worker(const worker&) = delete;
worker& operator=(const worker&) = delete;
void operator()() {
job_ptr job;
for (;;) {
/*
* todo:
* manage device usage
* wait for device
*/
// adopt reference count of job queue
job.adopt(m_job_queue->pop());
if(job != m_dummy) {
try {
cl_command_queue cmd_q =
m_parent->m_devices.front().cmd_queue.get();
job->enqueue(cmd_q);
cl_int err{clFlush(cmd_q)};
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clFlush: '"
+ get_opencl_error(err)
+ "'.");
}
}
catch (exception& e) {
cerr << e.what() << endl;
}
}
else {
cout << "worker done" << endl;
return;
}
}
}
};
void command_dispatcher::worker_loop(command_dispatcher::worker* w) {
(*w)();
}
void command_dispatcher::supervisor_loop(command_dispatcher* scheduler,
job_queue* jq, command_ptr m_dummy) {
unique_ptr<command_dispatcher::worker> worker;
worker.reset(new command_dispatcher::worker(scheduler, jq, m_dummy));
worker->start();
worker->m_thread.join();
worker.reset();
cout << "supervisor done" << endl;
}
void command_dispatcher::initialize() {
m_dummy = make_counted<command_dummy>();
cl_int err{0};
/* find up to two available platforms */
vector<cl_platform_id> ids(2);
cl_uint number_of_platforms;
err = clGetPlatformIDs(ids.size(), ids.data(), &number_of_platforms);
if (err != CL_SUCCESS) {
throw logic_error("[!!!] clGetPlatformIDs: '"
+ get_opencl_error(err)
+ "'.");
}
else if (number_of_platforms < 1) {
throw logic_error("[!!!] clGetPlatformIDs: 'no platforms found'.");
}
/* find gpu devices on our platform */
int pid{0};
cl_uint num_devices{0};
// cout << "Currently only looking for cpu devices!" << endl;
cl_device_type dev_type{CL_DEVICE_TYPE_GPU};
err = clGetDeviceIDs(ids[pid], dev_type, 0, NULL, &num_devices);
if (err == CL_DEVICE_NOT_FOUND) {
cout << "NO GPU DEVICES FOUND! LOOKING FOR CPU DEVICES NOW ..." << endl;
dev_type = CL_DEVICE_TYPE_CPU;
err = clGetDeviceIDs(ids[pid], dev_type, 0, NULL, &num_devices);
}
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clGetDeviceIDs: '"
+ get_opencl_error(err)
+ "'.");
}
vector<cl_device_id> devices(num_devices);
err = clGetDeviceIDs(ids[pid], dev_type, num_devices, devices.data(), NULL);
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clGetDeviceIDs: '"
+ get_opencl_error(err)
+ "'.");
}
/* create a context */
m_context.adopt(clCreateContext(0, 1, devices.data(), NULL, NULL, &err));
if (err != CL_SUCCESS) {
throw runtime_error("[!!!] clCreateContext: '"
+ get_opencl_error(err)
+ "'.");
}
for (auto& d : devices) {
device_ptr device;
device.adopt(d);
unsigned id{++dev_id_gen};
command_queue_ptr cmd_queue;
cmd_queue.adopt(clCreateCommandQueue(m_context.get(),
device.get(),
CL_QUEUE_PROFILING_ENABLE,
&err));
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clCreateCommandQueue (" << id << "): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
size_t return_size{0};
size_t max_work_group_size{0};
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t),
&max_work_group_size,
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_GROUP_SIZE): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
cl_uint max_work_item_dimensions = 0;
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
sizeof(cl_uint),
&max_work_item_dimensions,
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
vector<size_t> max_work_items_per_dim(max_work_item_dimensions);
err = clGetDeviceInfo(device.get(),
CL_DEVICE_MAX_WORK_ITEM_SIZES,
sizeof(size_t)*max_work_item_dimensions,
max_work_items_per_dim.data(),
&return_size);
if (err != CL_SUCCESS) {
ostringstream oss;
oss << "[!!!] clGetDeviceInfo ("
<< id
<< ":CL_DEVICE_MAX_WORK_ITEM_SIZES): '"
<< get_opencl_error(err) << "'.";
throw runtime_error(oss.str());
}
device_info dev_info{id,
cmd_queue,
device,
max_work_group_size,
max_work_item_dimensions,
move(max_work_items_per_dim)};
m_devices.push_back(move(dev_info));
}
m_supervisor = thread(&command_dispatcher::supervisor_loop,
this,
&m_job_queue,
m_dummy);
}
void command_dispatcher::destroy() {
m_dummy->ref(); // reference of m_job_queue
m_job_queue.push_back(m_dummy.get());
m_supervisor.join();
delete this;
}
void command_dispatcher::dispose() {
delete this;
}
} } // namespace cppa::opencl
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QDeclarativeView>
#include <QApplication>
#include <QLibraryInfo>
#include <QDir>
#include <QDebug>
#include <QProcess>
#include <QFile>
#ifdef Q_OS_SYMBIAN
// In Symbian OS test data is located in applications private dir
#define QT_TEST_SOURCE_DIR "."
#endif
enum Mode { Record, RecordNoVisuals, RecordSnapshot, Play, TestVisuals, RemoveVisuals, UpdateVisuals, UpdatePlatformVisuals, Test };
static QString testdir;
class tst_qmlvisual : public QObject
{
Q_OBJECT
public:
tst_qmlvisual();
static QString toTestScript(const QString &, Mode=Test);
static QString viewer();
static QStringList findQmlFiles(const QDir &d);
private slots:
void visual_data();
void visual();
private:
QString qmlruntime;
};
tst_qmlvisual::tst_qmlvisual()
{
qmlruntime = viewer();
}
QString tst_qmlvisual::viewer()
{
QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);
QString qmlruntime;
#if defined(Q_WS_MAC)
qmlruntime = QDir(binaries).absoluteFilePath("QMLViewer.app/Contents/MacOS/QMLViewer");
#elif defined(Q_WS_WIN) || defined(Q_WS_S60)
qmlruntime = QDir(binaries).absoluteFilePath("qmlviewer.exe");
#else
qmlruntime = QDir(binaries).absoluteFilePath("qmlviewer");
#endif
return qmlruntime;
}
void tst_qmlvisual::visual_data()
{
QTest::addColumn<QString>("file");
QTest::addColumn<QString>("testdata");
QStringList files;
files << findQmlFiles(QDir(QT_TEST_SOURCE_DIR));
if (qgetenv("QMLVISUAL_ALL") != "1") {
#if defined(Q_WS_MAC)
//Text on Mac varies per version. Only check the text on 10.6
if(QSysInfo::MacintoshVersion != QSysInfo::MV_10_6)
foreach(const QString &str, files.filter(QRegExp(".*text.*")))
files.removeAll(str);
#endif
#if defined(Q_WS_QWS)
//We don't want QWS test results to mire down the CI system
files.clear();
//Needs at least one test data or it fails anyways
files << QT_TEST_SOURCE_DIR "/selftest_noimages/selftest_noimages.qml";
#endif
}
foreach (const QString &file, files) {
QString testdata = toTestScript(file);
if (testdata.isEmpty())
continue;
QTest::newRow(file.toLatin1().constData()) << file << testdata;
}
}
void tst_qmlvisual::visual()
{
QFETCH(QString, file);
QFETCH(QString, testdata);
QStringList arguments;
#ifdef Q_WS_MAC
arguments << "-no-opengl";
#endif
arguments << "-script" << testdata
<< "-scriptopts" << "play,testimages,testerror,testskip,exitoncomplete,exitonfailure"
<< file;
#ifdef Q_WS_QWS
arguments << "-qws";
#endif
QProcess p;
p.start(qmlruntime, arguments);
bool finished = p.waitForFinished();
QByteArray output = p.readAllStandardOutput() + p.readAllStandardError();
QVERIFY2(finished, output.data());
if (p.exitCode() != 0)
qDebug() << output;
QCOMPARE(p.exitStatus(), QProcess::NormalExit);
QCOMPARE(p.exitCode(), 0);
}
QString tst_qmlvisual::toTestScript(const QString &file, Mode mode)
{
if (!file.endsWith(".qml"))
return QString();
int index = file.lastIndexOf(QDir::separator());
if (index == -1)
index = file.lastIndexOf('/');
if (index == -1)
return QString();
const char* platformsuffix=0; // platforms with different fonts
#if defined(Q_WS_MACX)
platformsuffix = "-MAC";
#elif defined(Q_WS_X11)
platformsuffix = "-X11";
#elif defined(Q_WS_WIN32)
platformsuffix = "-WIN";
#elif defined(Q_WS_QWS)
platformsuffix = "-QWS";
#elif defined(Q_WS_S60)
platformsuffix = "-S60";
#endif
QString testdata = file.left(index + 1) +
QString("data");
QString testname = file.mid(index + 1, file.length() - index - 5);
if (platformsuffix && (mode == UpdatePlatformVisuals || QFile::exists(testdata+QLatin1String(platformsuffix)+QDir::separator()+testname+".qml"))) {
QString platformdir = testdata + QLatin1String(platformsuffix);
if (mode == UpdatePlatformVisuals) {
if (!QDir().mkpath(platformdir)) {
qFatal("Cannot make path %s", qPrintable(platformdir));
}
// Copy from base
QDir dir(testdata,testname+".*");
dir.setFilter(QDir::Files);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFile in(list.at(i).filePath());
if (!in.open(QIODevice::ReadOnly)) {
qFatal("Cannot open file %s: %s", qPrintable(in.fileName()), qPrintable(in.errorString()));
}
QFile out(platformdir + QDir::separator() + list.at(i).fileName());
if (!out.open(QIODevice::WriteOnly)) {
qFatal("Cannot open file %s: %s", qPrintable(out.fileName()), qPrintable(out.errorString()));
}
out.write(in.readAll());
}
}
testdata = platformdir;
}
testdata += QDir::separator() + testname;
return testdata;
}
QStringList tst_qmlvisual::findQmlFiles(const QDir &d)
{
QStringList rv;
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
foreach (const QString &file, files) {
if (file.at(0).isLower()) {
rv << d.absoluteFilePath(file);
}
}
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
if (dir.left(4) == "data")
continue;
QDir sub = d;
sub.cd(dir);
rv << findQmlFiles(sub);
}
return rv;
}
void action(Mode mode, const QString &file)
{
Q_ASSERT(mode != Test);
QString testdata = tst_qmlvisual::toTestScript(file,mode);
QStringList arguments;
#ifdef Q_WS_MAC
arguments << "-no-opengl";
#endif
switch (mode) {
case Test:
// Don't run qml
break;
case Record:
arguments << "-script" << testdata
<< "-scriptopts" << "record,testimages,saveonexit"
<< file;
break;
case RecordNoVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "record,saveonexit"
<< file;
break;
case RecordSnapshot:
arguments << "-script" << testdata
<< "-scriptopts" << "record,testimages,snapshot,saveonexit"
<< file;
break;
case Play:
arguments << "-script" << testdata
<< "-scriptopts" << "play,testimages,testerror,testskip,exitoncomplete"
<< file;
break;
case TestVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play"
<< file;
break;
case UpdateVisuals:
case UpdatePlatformVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play,record,testimages,exitoncomplete,saveonexit"
<< file;
break;
case RemoveVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play,record,exitoncomplete,saveonexit"
<< file;
break;
}
if (!arguments.isEmpty()) {
QProcess p;
p.setProcessChannelMode(QProcess::ForwardedChannels);
p.start(tst_qmlvisual::viewer(), arguments);
p.waitForFinished();
}
}
void usage()
{
fprintf(stderr, "\n");
fprintf(stderr, "QML related options\n");
fprintf(stderr, " -listtests : list all the tests seen by tst_qmlvisual, and then exit immediately\n");
fprintf(stderr, " -record file : record new test data for file\n");
fprintf(stderr, " -recordnovisuals file : record new test data for file, but ignore visuals\n");
fprintf(stderr, " -recordsnapshot file : record new snapshot for file (like record but only records a single frame and then exits)\n");
fprintf(stderr, " -play file : playback test data for file, printing errors\n");
fprintf(stderr, " -testvisuals file : playback test data for file, without errors\n");
fprintf(stderr, " -updatevisuals file : playback test data for file, accept new visuals for file\n");
fprintf(stderr, " -updateplatformvisuals file : playback test data for file, accept new visuals for file only on current platform (MacOSX/Win32/X11/QWS/S60)\n");
fprintf(stderr, "\n"
"Visual tests are recordings of manual interactions with a QML test,\n"
"that can then be run automatically. To record a new test, run:\n"
"\n"
" tst_qmlvisual -record yourtestdir/yourtest.qml\n"
"\n"
"This records everything you do (try to keep it short).\n"
"To play back a test, run:\n"
"\n"
" tst_qmlvisual -play yourtestdir/yourtest.qml\n"
"\n"
"Your test may include QML code to test itself, reporting any error to an\n"
"'error' property on the root object - the test will fail if this property\n"
"gets set to anything non-empty.\n"
"\n"
"If your test changes slightly but is still correct (check with -play), you\n"
"can update the visuals by running:\n"
"\n"
" tst_qmlvisual -updatevisuals yourtestdir/yourtest.qml\n"
"\n"
"If your test includes platform-sensitive visuals (eg. text in system fonts),\n"
"you should create platform-specific visuals, using -updateplatformvisuals\n"
"instead.\n"
"\n"
"If you ONLY wish to use the 'error' property, you can record your test with\n"
"-recordnovisuals, or discard existing visuals with -removevisuals; the test\n"
"will then only fail on a syntax error, crash, or non-empty 'error' property.\n"
"\n"
"If your test has anything set to the 'skip' property on the root object then\n"
"test failures will be ignored. This allows for an opt-out of automated\n"
"aggregation of test results. The value of the 'skip' property (usually a\n"
"string) will then be printed to stdout when the test is run as part of the\n"
"message saying the test has been skipped.\n"
);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Mode mode = Test;
QString file;
bool showHelp = false;
int newArgc = 1;
char **newArgv = new char*[argc];
newArgv[0] = argv[0];
for (int ii = 1; ii < argc; ++ii) {
QString arg(argv[ii]);
if (arg == "-play" && (ii + 1) < argc) {
mode = Play;
file = argv[++ii];
} else if (arg == "-record" && (ii + 1) < argc) {
mode = Record;
file = argv[++ii];
} else if (arg == "-recordnovisuals" && (ii + 1) < argc) {
mode = RecordNoVisuals;
file = argv[++ii];
} else if (arg == "-recordsnapshot" && (ii + 1) < argc) {
mode = RecordSnapshot;
file = argv[++ii];
} else if (arg == "-testvisuals" && (ii + 1) < argc) {
mode = TestVisuals;
file = argv[++ii];
} else if (arg == "-removevisuals" && (ii + 1) < argc) {
mode = RemoveVisuals;
file = argv[++ii];
} else if (arg == "-updatevisuals" && (ii + 1) < argc) {
mode = UpdateVisuals;
file = argv[++ii];
} else if (arg == "-updateplatformvisuals" && (ii + 1) < argc) {
mode = UpdatePlatformVisuals;
file = argv[++ii];
} else {
newArgv[newArgc++] = argv[ii];
}
if (arg == "-help" || arg == "-?" || arg == "--help") {
atexit(usage);
showHelp = true;
}
if (arg == "-listtests") {
QStringList list = tst_qmlvisual::findQmlFiles(QDir(QT_TEST_SOURCE_DIR));
foreach (QString test, list) {
qWarning() << qPrintable(test);
}
return 0;
}
}
if (mode == Test || showHelp) {
tst_qmlvisual tc;
return QTest::qExec(&tc, newArgc, newArgv);
} else {
if (!file.endsWith(QLatin1String(".qml"))) {
qWarning() << "Error: Invalid file name (must end in .qml)";
return -1;
}
QDir d = QDir::current();
QString absFile = d.absoluteFilePath(file);
if (!QFile::exists(absFile)) {
qWarning() << "Error: File does not exist";
return -1;
}
action(mode, absFile);
return 0;
}
}
#include "tst_qmlvisual.moc"
<commit_msg>Remove redundant Q_ASSERT from qmlvisual autotest.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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 [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QDeclarativeView>
#include <QApplication>
#include <QLibraryInfo>
#include <QDir>
#include <QDebug>
#include <QProcess>
#include <QFile>
#ifdef Q_OS_SYMBIAN
// In Symbian OS test data is located in applications private dir
#define QT_TEST_SOURCE_DIR "."
#endif
enum Mode { Record, RecordNoVisuals, RecordSnapshot, Play, TestVisuals, RemoveVisuals, UpdateVisuals, UpdatePlatformVisuals, Test };
static QString testdir;
class tst_qmlvisual : public QObject
{
Q_OBJECT
public:
tst_qmlvisual();
static QString toTestScript(const QString &, Mode=Test);
static QString viewer();
static QStringList findQmlFiles(const QDir &d);
private slots:
void visual_data();
void visual();
private:
QString qmlruntime;
};
tst_qmlvisual::tst_qmlvisual()
{
qmlruntime = viewer();
}
QString tst_qmlvisual::viewer()
{
QString binaries = QLibraryInfo::location(QLibraryInfo::BinariesPath);
QString qmlruntime;
#if defined(Q_WS_MAC)
qmlruntime = QDir(binaries).absoluteFilePath("QMLViewer.app/Contents/MacOS/QMLViewer");
#elif defined(Q_WS_WIN) || defined(Q_WS_S60)
qmlruntime = QDir(binaries).absoluteFilePath("qmlviewer.exe");
#else
qmlruntime = QDir(binaries).absoluteFilePath("qmlviewer");
#endif
return qmlruntime;
}
void tst_qmlvisual::visual_data()
{
QTest::addColumn<QString>("file");
QTest::addColumn<QString>("testdata");
QStringList files;
files << findQmlFiles(QDir(QT_TEST_SOURCE_DIR));
if (qgetenv("QMLVISUAL_ALL") != "1") {
#if defined(Q_WS_MAC)
//Text on Mac varies per version. Only check the text on 10.6
if(QSysInfo::MacintoshVersion != QSysInfo::MV_10_6)
foreach(const QString &str, files.filter(QRegExp(".*text.*")))
files.removeAll(str);
#endif
#if defined(Q_WS_QWS)
//We don't want QWS test results to mire down the CI system
files.clear();
//Needs at least one test data or it fails anyways
files << QT_TEST_SOURCE_DIR "/selftest_noimages/selftest_noimages.qml";
#endif
}
foreach (const QString &file, files) {
QString testdata = toTestScript(file);
if (testdata.isEmpty())
continue;
QTest::newRow(file.toLatin1().constData()) << file << testdata;
}
}
void tst_qmlvisual::visual()
{
QFETCH(QString, file);
QFETCH(QString, testdata);
QStringList arguments;
#ifdef Q_WS_MAC
arguments << "-no-opengl";
#endif
arguments << "-script" << testdata
<< "-scriptopts" << "play,testimages,testerror,testskip,exitoncomplete,exitonfailure"
<< file;
#ifdef Q_WS_QWS
arguments << "-qws";
#endif
QProcess p;
p.start(qmlruntime, arguments);
bool finished = p.waitForFinished();
QByteArray output = p.readAllStandardOutput() + p.readAllStandardError();
QVERIFY2(finished, output.data());
if (p.exitCode() != 0)
qDebug() << output;
QCOMPARE(p.exitStatus(), QProcess::NormalExit);
QCOMPARE(p.exitCode(), 0);
}
QString tst_qmlvisual::toTestScript(const QString &file, Mode mode)
{
if (!file.endsWith(".qml"))
return QString();
int index = file.lastIndexOf(QDir::separator());
if (index == -1)
index = file.lastIndexOf('/');
if (index == -1)
return QString();
const char* platformsuffix=0; // platforms with different fonts
#if defined(Q_WS_MACX)
platformsuffix = "-MAC";
#elif defined(Q_WS_X11)
platformsuffix = "-X11";
#elif defined(Q_WS_WIN32)
platformsuffix = "-WIN";
#elif defined(Q_WS_QWS)
platformsuffix = "-QWS";
#elif defined(Q_WS_S60)
platformsuffix = "-S60";
#endif
QString testdata = file.left(index + 1) +
QString("data");
QString testname = file.mid(index + 1, file.length() - index - 5);
if (platformsuffix && (mode == UpdatePlatformVisuals || QFile::exists(testdata+QLatin1String(platformsuffix)+QDir::separator()+testname+".qml"))) {
QString platformdir = testdata + QLatin1String(platformsuffix);
if (mode == UpdatePlatformVisuals) {
if (!QDir().mkpath(platformdir)) {
qFatal("Cannot make path %s", qPrintable(platformdir));
}
// Copy from base
QDir dir(testdata,testname+".*");
dir.setFilter(QDir::Files);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFile in(list.at(i).filePath());
if (!in.open(QIODevice::ReadOnly)) {
qFatal("Cannot open file %s: %s", qPrintable(in.fileName()), qPrintable(in.errorString()));
}
QFile out(platformdir + QDir::separator() + list.at(i).fileName());
if (!out.open(QIODevice::WriteOnly)) {
qFatal("Cannot open file %s: %s", qPrintable(out.fileName()), qPrintable(out.errorString()));
}
out.write(in.readAll());
}
}
testdata = platformdir;
}
testdata += QDir::separator() + testname;
return testdata;
}
QStringList tst_qmlvisual::findQmlFiles(const QDir &d)
{
QStringList rv;
QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"),
QDir::Files);
foreach (const QString &file, files) {
if (file.at(0).isLower()) {
rv << d.absoluteFilePath(file);
}
}
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QString &dir, dirs) {
if (dir.left(4) == "data")
continue;
QDir sub = d;
sub.cd(dir);
rv << findQmlFiles(sub);
}
return rv;
}
void action(Mode mode, const QString &file)
{
QString testdata = tst_qmlvisual::toTestScript(file,mode);
QStringList arguments;
#ifdef Q_WS_MAC
arguments << "-no-opengl";
#endif
switch (mode) {
case Test:
// Don't run qml
break;
case Record:
arguments << "-script" << testdata
<< "-scriptopts" << "record,testimages,saveonexit"
<< file;
break;
case RecordNoVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "record,saveonexit"
<< file;
break;
case RecordSnapshot:
arguments << "-script" << testdata
<< "-scriptopts" << "record,testimages,snapshot,saveonexit"
<< file;
break;
case Play:
arguments << "-script" << testdata
<< "-scriptopts" << "play,testimages,testerror,testskip,exitoncomplete"
<< file;
break;
case TestVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play"
<< file;
break;
case UpdateVisuals:
case UpdatePlatformVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play,record,testimages,exitoncomplete,saveonexit"
<< file;
break;
case RemoveVisuals:
arguments << "-script" << testdata
<< "-scriptopts" << "play,record,exitoncomplete,saveonexit"
<< file;
break;
}
if (!arguments.isEmpty()) {
QProcess p;
p.setProcessChannelMode(QProcess::ForwardedChannels);
p.start(tst_qmlvisual::viewer(), arguments);
p.waitForFinished();
}
}
void usage()
{
fprintf(stderr, "\n");
fprintf(stderr, "QML related options\n");
fprintf(stderr, " -listtests : list all the tests seen by tst_qmlvisual, and then exit immediately\n");
fprintf(stderr, " -record file : record new test data for file\n");
fprintf(stderr, " -recordnovisuals file : record new test data for file, but ignore visuals\n");
fprintf(stderr, " -recordsnapshot file : record new snapshot for file (like record but only records a single frame and then exits)\n");
fprintf(stderr, " -play file : playback test data for file, printing errors\n");
fprintf(stderr, " -testvisuals file : playback test data for file, without errors\n");
fprintf(stderr, " -updatevisuals file : playback test data for file, accept new visuals for file\n");
fprintf(stderr, " -updateplatformvisuals file : playback test data for file, accept new visuals for file only on current platform (MacOSX/Win32/X11/QWS/S60)\n");
fprintf(stderr, "\n"
"Visual tests are recordings of manual interactions with a QML test,\n"
"that can then be run automatically. To record a new test, run:\n"
"\n"
" tst_qmlvisual -record yourtestdir/yourtest.qml\n"
"\n"
"This records everything you do (try to keep it short).\n"
"To play back a test, run:\n"
"\n"
" tst_qmlvisual -play yourtestdir/yourtest.qml\n"
"\n"
"Your test may include QML code to test itself, reporting any error to an\n"
"'error' property on the root object - the test will fail if this property\n"
"gets set to anything non-empty.\n"
"\n"
"If your test changes slightly but is still correct (check with -play), you\n"
"can update the visuals by running:\n"
"\n"
" tst_qmlvisual -updatevisuals yourtestdir/yourtest.qml\n"
"\n"
"If your test includes platform-sensitive visuals (eg. text in system fonts),\n"
"you should create platform-specific visuals, using -updateplatformvisuals\n"
"instead.\n"
"\n"
"If you ONLY wish to use the 'error' property, you can record your test with\n"
"-recordnovisuals, or discard existing visuals with -removevisuals; the test\n"
"will then only fail on a syntax error, crash, or non-empty 'error' property.\n"
"\n"
"If your test has anything set to the 'skip' property on the root object then\n"
"test failures will be ignored. This allows for an opt-out of automated\n"
"aggregation of test results. The value of the 'skip' property (usually a\n"
"string) will then be printed to stdout when the test is run as part of the\n"
"message saying the test has been skipped.\n"
);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Mode mode = Test;
QString file;
bool showHelp = false;
int newArgc = 1;
char **newArgv = new char*[argc];
newArgv[0] = argv[0];
for (int ii = 1; ii < argc; ++ii) {
QString arg(argv[ii]);
if (arg == "-play" && (ii + 1) < argc) {
mode = Play;
file = argv[++ii];
} else if (arg == "-record" && (ii + 1) < argc) {
mode = Record;
file = argv[++ii];
} else if (arg == "-recordnovisuals" && (ii + 1) < argc) {
mode = RecordNoVisuals;
file = argv[++ii];
} else if (arg == "-recordsnapshot" && (ii + 1) < argc) {
mode = RecordSnapshot;
file = argv[++ii];
} else if (arg == "-testvisuals" && (ii + 1) < argc) {
mode = TestVisuals;
file = argv[++ii];
} else if (arg == "-removevisuals" && (ii + 1) < argc) {
mode = RemoveVisuals;
file = argv[++ii];
} else if (arg == "-updatevisuals" && (ii + 1) < argc) {
mode = UpdateVisuals;
file = argv[++ii];
} else if (arg == "-updateplatformvisuals" && (ii + 1) < argc) {
mode = UpdatePlatformVisuals;
file = argv[++ii];
} else {
newArgv[newArgc++] = argv[ii];
}
if (arg == "-help" || arg == "-?" || arg == "--help") {
atexit(usage);
showHelp = true;
}
if (arg == "-listtests") {
QStringList list = tst_qmlvisual::findQmlFiles(QDir(QT_TEST_SOURCE_DIR));
foreach (QString test, list) {
qWarning() << qPrintable(test);
}
return 0;
}
}
if (mode == Test || showHelp) {
tst_qmlvisual tc;
return QTest::qExec(&tc, newArgc, newArgv);
} else {
if (!file.endsWith(QLatin1String(".qml"))) {
qWarning() << "Error: Invalid file name (must end in .qml)";
return -1;
}
QDir d = QDir::current();
QString absFile = d.absoluteFilePath(file);
if (!QFile::exists(absFile)) {
qWarning() << "Error: File does not exist";
return -1;
}
action(mode, absFile);
return 0;
}
}
#include "tst_qmlvisual.moc"
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmldebugclient.h"
#include "../../../../../src/plugins/qmltooling/shared/qpacketprotocol.h"
#include <QtCore/qdebug.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qtimer.h>
#include <QtNetwork/qnetworkproxy.h>
const int protocolVersion = 1;
const QString serverId = QLatin1String("QDeclarativeDebugServer");
const QString clientId = QLatin1String("QDeclarativeDebugClient");
class QQmlDebugClientPrivate
{
public:
QQmlDebugClientPrivate();
QString name;
QQmlDebugConnection *connection;
};
class QQmlDebugConnectionPrivate : public QObject
{
Q_OBJECT
public:
QQmlDebugConnectionPrivate(QQmlDebugConnection *c);
QQmlDebugConnection *q;
QPacketProtocol *protocol;
QIODevice *device;
QEventLoop handshakeEventLoop;
QTimer handshakeTimer;
bool gotHello;
QHash <QString, float> serverPlugins;
QHash<QString, QQmlDebugClient *> plugins;
void advertisePlugins();
void connectDeviceSignals();
public Q_SLOTS:
void connected();
void readyRead();
void deviceAboutToClose();
void handshakeTimeout();
};
QQmlDebugConnectionPrivate::QQmlDebugConnectionPrivate(QQmlDebugConnection *c)
: QObject(c), q(c), protocol(0), device(0), gotHello(false)
{
protocol = new QPacketProtocol(q, this);
QObject::connect(c, SIGNAL(connected()), this, SLOT(connected()));
QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
handshakeTimer.setSingleShot(true);
handshakeTimer.setInterval(3000);
connect(&handshakeTimer, SIGNAL(timeout()), SLOT(handshakeTimeout()));
}
void QQmlDebugConnectionPrivate::advertisePlugins()
{
if (!q->isConnected())
return;
QPacket pack;
pack << serverId << 1 << plugins.keys();
protocol->send(pack);
q->flush();
}
void QQmlDebugConnectionPrivate::connected()
{
QPacket pack;
pack << serverId << 0 << protocolVersion << plugins.keys()
<< q->m_dataStreamVersion;
protocol->send(pack);
q->flush();
}
void QQmlDebugConnectionPrivate::readyRead()
{
if (!gotHello) {
QPacket pack = protocol->read();
QString name;
pack >> name;
bool validHello = false;
if (name == clientId) {
int op = -1;
pack >> op;
if (op == 0) {
int version = -1;
pack >> version;
if (version == protocolVersion) {
QStringList pluginNames;
QList<float> pluginVersions;
pack >> pluginNames;
if (!pack.isEmpty())
pack >> pluginVersions;
const int pluginNamesSize = pluginNames.size();
const int pluginVersionsSize = pluginVersions.size();
for (int i = 0; i < pluginNamesSize; ++i) {
float pluginVersion = 1.0;
if (i < pluginVersionsSize)
pluginVersion = pluginVersions.at(i);
serverPlugins.insert(pluginNames.at(i), pluginVersion);
}
pack >> q->m_dataStreamVersion;
validHello = true;
}
}
}
if (!validHello) {
qWarning("QQmlDebugConnection: Invalid hello message");
QObject::disconnect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
return;
}
gotHello = true;
QHash<QString, QQmlDebugClient *>::Iterator iter = plugins.begin();
for (; iter != plugins.end(); ++iter) {
QQmlDebugClient::State newState = QQmlDebugClient::Unavailable;
if (serverPlugins.contains(iter.key()))
newState = QQmlDebugClient::Enabled;
iter.value()->stateChanged(newState);
}
handshakeTimer.stop();
handshakeEventLoop.quit();
}
while (protocol->packetsAvailable()) {
QPacket pack = protocol->read();
QString name;
pack >> name;
if (name == clientId) {
int op = -1;
pack >> op;
if (op == 1) {
// Service Discovery
QHash<QString, float> oldServerPlugins = serverPlugins;
serverPlugins.clear();
QStringList pluginNames;
QList<float> pluginVersions;
pack >> pluginNames;
if (!pack.isEmpty())
pack >> pluginVersions;
const int pluginNamesSize = pluginNames.size();
const int pluginVersionsSize = pluginVersions.size();
for (int i = 0; i < pluginNamesSize; ++i) {
float pluginVersion = 1.0;
if (i < pluginVersionsSize)
pluginVersion = pluginVersions.at(i);
serverPlugins.insert(pluginNames.at(i), pluginVersion);
}
QHash<QString, QQmlDebugClient *>::Iterator iter = plugins.begin();
for (; iter != plugins.end(); ++iter) {
const QString pluginName = iter.key();
QQmlDebugClient::State newSate = QQmlDebugClient::Unavailable;
if (serverPlugins.contains(pluginName))
newSate = QQmlDebugClient::Enabled;
if (oldServerPlugins.contains(pluginName)
!= serverPlugins.contains(pluginName)) {
iter.value()->stateChanged(newSate);
}
}
} else {
qWarning() << "QQmlDebugConnection: Unknown control message id" << op;
}
} else {
QByteArray message;
pack >> message;
QHash<QString, QQmlDebugClient *>::Iterator iter =
plugins.find(name);
if (iter == plugins.end()) {
qWarning() << "QQmlDebugConnection: Message received for missing plugin" << name;
} else {
(*iter)->messageReceived(message);
}
}
}
}
void QQmlDebugConnectionPrivate::deviceAboutToClose()
{
// This is nasty syntax but we want to emit our own aboutToClose signal (by calling QIODevice::close())
// without calling the underlying device close fn as that would cause an infinite loop
q->QIODevice::close();
}
void QQmlDebugConnectionPrivate::handshakeTimeout()
{
if (!gotHello) {
qWarning() << "Qml Debug Client: Did not get handshake answer in time";
handshakeEventLoop.quit();
}
}
QQmlDebugConnection::QQmlDebugConnection(QObject *parent)
: QIODevice(parent), d(new QQmlDebugConnectionPrivate(this)),
m_dataStreamVersion(QDataStream::Qt_5_0)
{
}
QQmlDebugConnection::~QQmlDebugConnection()
{
QHash<QString, QQmlDebugClient*>::iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
iter.value()->d->connection = 0;
iter.value()->stateChanged(QQmlDebugClient::NotConnected);
}
}
void QQmlDebugConnection::setDataStreamVersion(int dataStreamVersion)
{
m_dataStreamVersion = dataStreamVersion;
}
int QQmlDebugConnection::dataStreamVersion()
{
return m_dataStreamVersion;
}
bool QQmlDebugConnection::isConnected() const
{
return state() == QAbstractSocket::ConnectedState;
}
qint64 QQmlDebugConnection::readData(char *data, qint64 maxSize)
{
return d->device->read(data, maxSize);
}
qint64 QQmlDebugConnection::writeData(const char *data, qint64 maxSize)
{
return d->device->write(data, maxSize);
}
qint64 QQmlDebugConnection::bytesAvailable() const
{
return d->device->bytesAvailable();
}
bool QQmlDebugConnection::isSequential() const
{
return true;
}
void QQmlDebugConnection::close()
{
if (isOpen()) {
QIODevice::close();
d->device->close();
emit stateChanged(QAbstractSocket::UnconnectedState);
QHash<QString, QQmlDebugClient*>::iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
iter.value()->stateChanged(QQmlDebugClient::NotConnected);
}
}
}
bool QQmlDebugConnection::waitForConnected(int msecs)
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (!socket)
return false;
if (!socket->waitForConnected(msecs))
return false;
// wait for handshake
d->handshakeTimer.start();
d->handshakeEventLoop.exec();
return d->gotHello;
}
QString QQmlDebugConnection::stateString() const
{
QString state;
if (isConnected())
state = "Connected";
else
state = "Not connected";
if (d->gotHello)
state += ", got hello";
else
state += ", did not get hello!";
return state;
}
QAbstractSocket::SocketState QQmlDebugConnection::state() const
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (socket)
return socket->state();
return QAbstractSocket::UnconnectedState;
}
void QQmlDebugConnection::flush()
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (socket) {
socket->flush();
return;
}
}
void QQmlDebugConnection::connectToHost(const QString &hostName, quint16 port)
{
QTcpSocket *socket = new QTcpSocket(d);
socket->setProxy(QNetworkProxy::NoProxy);
d->device = socket;
d->connectDeviceSignals();
d->gotHello = false;
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(error(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(connected()), this, SIGNAL(connected()));
socket->connectToHost(hostName, port);
QIODevice::open(ReadWrite | Unbuffered);
}
void QQmlDebugConnectionPrivate::connectDeviceSignals()
{
connect(device, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
connect(device, SIGNAL(readyRead()), q, SIGNAL(readyRead()));
connect(device, SIGNAL(aboutToClose()), this, SLOT(deviceAboutToClose()));
}
//
QQmlDebugClientPrivate::QQmlDebugClientPrivate()
: connection(0)
{
}
QQmlDebugClient::QQmlDebugClient(const QString &name,
QQmlDebugConnection *parent)
: QObject(parent),
d(new QQmlDebugClientPrivate)
{
d->name = name;
d->connection = parent;
if (!d->connection)
return;
if (d->connection->d->plugins.contains(name)) {
qWarning() << "QQmlDebugClient: Conflicting plugin name" << name;
d->connection = 0;
} else {
d->connection->d->plugins.insert(name, this);
d->connection->d->advertisePlugins();
}
}
QQmlDebugClient::~QQmlDebugClient()
{
if (d->connection && d->connection->d) {
d->connection->d->plugins.remove(d->name);
d->connection->d->advertisePlugins();
}
delete d;
}
QString QQmlDebugClient::name() const
{
return d->name;
}
float QQmlDebugClient::serviceVersion() const
{
if (d->connection->d->serverPlugins.contains(d->name))
return d->connection->d->serverPlugins.value(d->name);
return -1;
}
QQmlDebugClient::State QQmlDebugClient::state() const
{
if (!d->connection
|| !d->connection->isConnected()
|| !d->connection->d->gotHello)
return NotConnected;
if (d->connection->d->serverPlugins.contains(d->name))
return Enabled;
return Unavailable;
}
QString QQmlDebugClient::stateString() const
{
switch (state()) {
case NotConnected: return QLatin1String("Not connected");
case Unavailable: return QLatin1String("Unavailable");
case Enabled: return QLatin1String("Enabled");
}
}
void QQmlDebugClient::sendMessage(const QByteArray &message)
{
if (state() != Enabled)
return;
QPacket pack;
pack << d->name << message;
d->connection->d->protocol->send(pack);
d->connection->flush();
}
void QQmlDebugClient::stateChanged(State)
{
}
void QQmlDebugClient::messageReceived(const QByteArray &)
{
}
#include <qqmldebugclient.moc>
<commit_msg>qqmldebugclient.cpp: Fix warning about missing return.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qqmldebugclient.h"
#include "../../../../../src/plugins/qmltooling/shared/qpacketprotocol.h"
#include <QtCore/qdebug.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qtimer.h>
#include <QtNetwork/qnetworkproxy.h>
const int protocolVersion = 1;
const QString serverId = QLatin1String("QDeclarativeDebugServer");
const QString clientId = QLatin1String("QDeclarativeDebugClient");
class QQmlDebugClientPrivate
{
public:
QQmlDebugClientPrivate();
QString name;
QQmlDebugConnection *connection;
};
class QQmlDebugConnectionPrivate : public QObject
{
Q_OBJECT
public:
QQmlDebugConnectionPrivate(QQmlDebugConnection *c);
QQmlDebugConnection *q;
QPacketProtocol *protocol;
QIODevice *device;
QEventLoop handshakeEventLoop;
QTimer handshakeTimer;
bool gotHello;
QHash <QString, float> serverPlugins;
QHash<QString, QQmlDebugClient *> plugins;
void advertisePlugins();
void connectDeviceSignals();
public Q_SLOTS:
void connected();
void readyRead();
void deviceAboutToClose();
void handshakeTimeout();
};
QQmlDebugConnectionPrivate::QQmlDebugConnectionPrivate(QQmlDebugConnection *c)
: QObject(c), q(c), protocol(0), device(0), gotHello(false)
{
protocol = new QPacketProtocol(q, this);
QObject::connect(c, SIGNAL(connected()), this, SLOT(connected()));
QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
handshakeTimer.setSingleShot(true);
handshakeTimer.setInterval(3000);
connect(&handshakeTimer, SIGNAL(timeout()), SLOT(handshakeTimeout()));
}
void QQmlDebugConnectionPrivate::advertisePlugins()
{
if (!q->isConnected())
return;
QPacket pack;
pack << serverId << 1 << plugins.keys();
protocol->send(pack);
q->flush();
}
void QQmlDebugConnectionPrivate::connected()
{
QPacket pack;
pack << serverId << 0 << protocolVersion << plugins.keys()
<< q->m_dataStreamVersion;
protocol->send(pack);
q->flush();
}
void QQmlDebugConnectionPrivate::readyRead()
{
if (!gotHello) {
QPacket pack = protocol->read();
QString name;
pack >> name;
bool validHello = false;
if (name == clientId) {
int op = -1;
pack >> op;
if (op == 0) {
int version = -1;
pack >> version;
if (version == protocolVersion) {
QStringList pluginNames;
QList<float> pluginVersions;
pack >> pluginNames;
if (!pack.isEmpty())
pack >> pluginVersions;
const int pluginNamesSize = pluginNames.size();
const int pluginVersionsSize = pluginVersions.size();
for (int i = 0; i < pluginNamesSize; ++i) {
float pluginVersion = 1.0;
if (i < pluginVersionsSize)
pluginVersion = pluginVersions.at(i);
serverPlugins.insert(pluginNames.at(i), pluginVersion);
}
pack >> q->m_dataStreamVersion;
validHello = true;
}
}
}
if (!validHello) {
qWarning("QQmlDebugConnection: Invalid hello message");
QObject::disconnect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
return;
}
gotHello = true;
QHash<QString, QQmlDebugClient *>::Iterator iter = plugins.begin();
for (; iter != plugins.end(); ++iter) {
QQmlDebugClient::State newState = QQmlDebugClient::Unavailable;
if (serverPlugins.contains(iter.key()))
newState = QQmlDebugClient::Enabled;
iter.value()->stateChanged(newState);
}
handshakeTimer.stop();
handshakeEventLoop.quit();
}
while (protocol->packetsAvailable()) {
QPacket pack = protocol->read();
QString name;
pack >> name;
if (name == clientId) {
int op = -1;
pack >> op;
if (op == 1) {
// Service Discovery
QHash<QString, float> oldServerPlugins = serverPlugins;
serverPlugins.clear();
QStringList pluginNames;
QList<float> pluginVersions;
pack >> pluginNames;
if (!pack.isEmpty())
pack >> pluginVersions;
const int pluginNamesSize = pluginNames.size();
const int pluginVersionsSize = pluginVersions.size();
for (int i = 0; i < pluginNamesSize; ++i) {
float pluginVersion = 1.0;
if (i < pluginVersionsSize)
pluginVersion = pluginVersions.at(i);
serverPlugins.insert(pluginNames.at(i), pluginVersion);
}
QHash<QString, QQmlDebugClient *>::Iterator iter = plugins.begin();
for (; iter != plugins.end(); ++iter) {
const QString pluginName = iter.key();
QQmlDebugClient::State newSate = QQmlDebugClient::Unavailable;
if (serverPlugins.contains(pluginName))
newSate = QQmlDebugClient::Enabled;
if (oldServerPlugins.contains(pluginName)
!= serverPlugins.contains(pluginName)) {
iter.value()->stateChanged(newSate);
}
}
} else {
qWarning() << "QQmlDebugConnection: Unknown control message id" << op;
}
} else {
QByteArray message;
pack >> message;
QHash<QString, QQmlDebugClient *>::Iterator iter =
plugins.find(name);
if (iter == plugins.end()) {
qWarning() << "QQmlDebugConnection: Message received for missing plugin" << name;
} else {
(*iter)->messageReceived(message);
}
}
}
}
void QQmlDebugConnectionPrivate::deviceAboutToClose()
{
// This is nasty syntax but we want to emit our own aboutToClose signal (by calling QIODevice::close())
// without calling the underlying device close fn as that would cause an infinite loop
q->QIODevice::close();
}
void QQmlDebugConnectionPrivate::handshakeTimeout()
{
if (!gotHello) {
qWarning() << "Qml Debug Client: Did not get handshake answer in time";
handshakeEventLoop.quit();
}
}
QQmlDebugConnection::QQmlDebugConnection(QObject *parent)
: QIODevice(parent), d(new QQmlDebugConnectionPrivate(this)),
m_dataStreamVersion(QDataStream::Qt_5_0)
{
}
QQmlDebugConnection::~QQmlDebugConnection()
{
QHash<QString, QQmlDebugClient*>::iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
iter.value()->d->connection = 0;
iter.value()->stateChanged(QQmlDebugClient::NotConnected);
}
}
void QQmlDebugConnection::setDataStreamVersion(int dataStreamVersion)
{
m_dataStreamVersion = dataStreamVersion;
}
int QQmlDebugConnection::dataStreamVersion()
{
return m_dataStreamVersion;
}
bool QQmlDebugConnection::isConnected() const
{
return state() == QAbstractSocket::ConnectedState;
}
qint64 QQmlDebugConnection::readData(char *data, qint64 maxSize)
{
return d->device->read(data, maxSize);
}
qint64 QQmlDebugConnection::writeData(const char *data, qint64 maxSize)
{
return d->device->write(data, maxSize);
}
qint64 QQmlDebugConnection::bytesAvailable() const
{
return d->device->bytesAvailable();
}
bool QQmlDebugConnection::isSequential() const
{
return true;
}
void QQmlDebugConnection::close()
{
if (isOpen()) {
QIODevice::close();
d->device->close();
emit stateChanged(QAbstractSocket::UnconnectedState);
QHash<QString, QQmlDebugClient*>::iterator iter = d->plugins.begin();
for (; iter != d->plugins.end(); ++iter) {
iter.value()->stateChanged(QQmlDebugClient::NotConnected);
}
}
}
bool QQmlDebugConnection::waitForConnected(int msecs)
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (!socket)
return false;
if (!socket->waitForConnected(msecs))
return false;
// wait for handshake
d->handshakeTimer.start();
d->handshakeEventLoop.exec();
return d->gotHello;
}
QString QQmlDebugConnection::stateString() const
{
QString state;
if (isConnected())
state = "Connected";
else
state = "Not connected";
if (d->gotHello)
state += ", got hello";
else
state += ", did not get hello!";
return state;
}
QAbstractSocket::SocketState QQmlDebugConnection::state() const
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (socket)
return socket->state();
return QAbstractSocket::UnconnectedState;
}
void QQmlDebugConnection::flush()
{
QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(d->device);
if (socket) {
socket->flush();
return;
}
}
void QQmlDebugConnection::connectToHost(const QString &hostName, quint16 port)
{
QTcpSocket *socket = new QTcpSocket(d);
socket->setProxy(QNetworkProxy::NoProxy);
d->device = socket;
d->connectDeviceSignals();
d->gotHello = false;
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(error(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(connected()), this, SIGNAL(connected()));
socket->connectToHost(hostName, port);
QIODevice::open(ReadWrite | Unbuffered);
}
void QQmlDebugConnectionPrivate::connectDeviceSignals()
{
connect(device, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
connect(device, SIGNAL(readyRead()), q, SIGNAL(readyRead()));
connect(device, SIGNAL(aboutToClose()), this, SLOT(deviceAboutToClose()));
}
//
QQmlDebugClientPrivate::QQmlDebugClientPrivate()
: connection(0)
{
}
QQmlDebugClient::QQmlDebugClient(const QString &name,
QQmlDebugConnection *parent)
: QObject(parent),
d(new QQmlDebugClientPrivate)
{
d->name = name;
d->connection = parent;
if (!d->connection)
return;
if (d->connection->d->plugins.contains(name)) {
qWarning() << "QQmlDebugClient: Conflicting plugin name" << name;
d->connection = 0;
} else {
d->connection->d->plugins.insert(name, this);
d->connection->d->advertisePlugins();
}
}
QQmlDebugClient::~QQmlDebugClient()
{
if (d->connection && d->connection->d) {
d->connection->d->plugins.remove(d->name);
d->connection->d->advertisePlugins();
}
delete d;
}
QString QQmlDebugClient::name() const
{
return d->name;
}
float QQmlDebugClient::serviceVersion() const
{
if (d->connection->d->serverPlugins.contains(d->name))
return d->connection->d->serverPlugins.value(d->name);
return -1;
}
QQmlDebugClient::State QQmlDebugClient::state() const
{
if (!d->connection
|| !d->connection->isConnected()
|| !d->connection->d->gotHello)
return NotConnected;
if (d->connection->d->serverPlugins.contains(d->name))
return Enabled;
return Unavailable;
}
QString QQmlDebugClient::stateString() const
{
switch (state()) {
case NotConnected: return QLatin1String("Not connected");
case Unavailable: return QLatin1String("Unavailable");
case Enabled: return QLatin1String("Enabled");
}
return QLatin1String("Invalid");
}
void QQmlDebugClient::sendMessage(const QByteArray &message)
{
if (state() != Enabled)
return;
QPacket pack;
pack << d->name << message;
d->connection->d->protocol->send(pack);
d->connection->flush();
}
void QQmlDebugClient::stateChanged(State)
{
}
void QQmlDebugClient::messageReceived(const QByteArray &)
{
}
#include <qqmldebugclient.moc>
<|endoftext|> |
<commit_before>/*
* SMARTCARDPP
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL) or the BSD License (see LICENSE.BSD).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*
*/
#include "common.h"
#include "SCError.h"
SCError::SCError(long err) : runtime_error("smart card API error"),error(err)
{
std::ostringstream buf;
switch(err & 0xFFFFFFFF)
{
case 0x80100017 : //SCARD_E_READER_UNAVAILABLE
buf << "No smart card readers"; break;
case 0x80100069 : //SCARD_W_REMOVED_CARD
buf << "No card in specified reader"; break;
case 0x80100011 : //SCARD_E_INVALID_VALUE .. needs trapping
buf << "Another application is using the card"; break;
case 0x8010000b : //SCARD_E_SHARING_VIOLATION
buf << "The smart card cannot be accessed because of other connections outstanding"; break;
case 0x8010000f : //SCARD_E_PROTO_MISMATCH
buf << "The requested protocols are incompatible with the protocol currently in use with the smart card"; break;
case 0x8010001D : // SCARD_E_NO_SERVICE
buf << "Smart card manager (PC/SC service) is not running"; break;
case 0x80100066 : // SCARD_W_UNRESPONSIVE_CARD
buf << "The card is not responding to reset"; break;
default:
buf << "exception:'" << runtime_error::what() <<
"' code:'0x" <<std::hex << std::setfill('0') <<
std::setw(8) << error << "'";
}
desc = buf.str();
}
void SCError::check(long err, int cid, int tid)
{
if(err)
SCardLog::writeMessage("[%i:%i][%s:%d] ERROR CODE RECIEVED 0x%08X", cid, tid, __FUNC__, __LINE__, err);
if((int)err == SCARD_W_RESET_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_RESET_CARD", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_NOT_TRANSACTED)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NOT_TRANSACTED", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_NO_SMARTCARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_SMARTCARD", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_W_REMOVED_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_REMOVED_CARD", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_W_UNRESPONSIVE_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNRESPONSIVE_CARD", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_E_NO_READERS_AVAILABLE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_READERS_AVAILABLE", cid, tid, __FUNC__, __LINE__, err);
throw NoReadersAvailible();
}
else if((int)err == ERROR_NO_MEDIA_IN_DRIVE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] ERROR_NO_MEDIA_IN_DRIVE", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_E_READER_UNAVAILABLE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_READER_UNAVAILABLE", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_E_SHARING_VIOLATION)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_SHARING_VIOLATION", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_TIMEOUT)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_TIMEOUT", cid, tid, __FUNC__, __LINE__, err);
return;
}
if (err)
{
throw SCError(err);
}
}
<commit_msg>#23996 Try again on SCARD_W_UNRESPONSIVE_CARD error<commit_after>/*
* SMARTCARDPP
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL) or the BSD License (see LICENSE.BSD).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*
*/
#include "common.h"
#include "SCError.h"
SCError::SCError(long err) : runtime_error("smart card API error"),error(err)
{
std::ostringstream buf;
switch(err & 0xFFFFFFFF)
{
case 0x80100017 : //SCARD_E_READER_UNAVAILABLE
buf << "No smart card readers"; break;
case 0x80100069 : //SCARD_W_REMOVED_CARD
buf << "No card in specified reader"; break;
case 0x80100011 : //SCARD_E_INVALID_VALUE .. needs trapping
buf << "Another application is using the card"; break;
case 0x8010000b : //SCARD_E_SHARING_VIOLATION
buf << "The smart card cannot be accessed because of other connections outstanding"; break;
case 0x8010000f : //SCARD_E_PROTO_MISMATCH
buf << "The requested protocols are incompatible with the protocol currently in use with the smart card"; break;
case 0x8010001D : // SCARD_E_NO_SERVICE
buf << "Smart card manager (PC/SC service) is not running"; break;
case 0x80100066 : // SCARD_W_UNRESPONSIVE_CARD
buf << "The card is not responding to reset"; break;
default:
buf << "exception:'" << runtime_error::what() <<
"' code:'0x" <<std::hex << std::setfill('0') <<
std::setw(8) << error << "'";
}
desc = buf.str();
}
void SCError::check(long err, int cid, int tid)
{
if(err)
SCardLog::writeMessage("[%i:%i][%s:%d] ERROR CODE RECIEVED 0x%08X", cid, tid, __FUNC__, __LINE__, err);
if((int)err == SCARD_W_RESET_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_RESET_CARD", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_NOT_TRANSACTED)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NOT_TRANSACTED", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_NO_SMARTCARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_SMARTCARD", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_W_REMOVED_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_REMOVED_CARD", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_W_UNRESPONSIVE_CARD)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_W_UNRESPONSIVE_CARD", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_NO_READERS_AVAILABLE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_NO_READERS_AVAILABLE", cid, tid, __FUNC__, __LINE__, err);
throw NoReadersAvailible();
}
else if((int)err == ERROR_NO_MEDIA_IN_DRIVE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] ERROR_NO_MEDIA_IN_DRIVE", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_E_READER_UNAVAILABLE)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_READER_UNAVAILABLE", cid, tid, __FUNC__, __LINE__, err);
throw NoCardInReaderError();
}
else if((int)err == SCARD_E_SHARING_VIOLATION)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_SHARING_VIOLATION", cid, tid, __FUNC__, __LINE__, err);
throw CardResetError();
}
else if((int)err == SCARD_E_TIMEOUT)
{
SCardLog::writeMessage("[%i:%i][%s:%d] SCARD_E_TIMEOUT", cid, tid, __FUNC__, __LINE__, err);
return;
}
if (err)
{
throw SCError(err);
}
}
<|endoftext|> |
<commit_before>#ifndef _SPATIAL_MATH_TEST_INL_
#define _SPATIAL_MATH_TEST_INL_
//#include "SM_Calc.h"
#include "sm_const.h"
#include <float.h>
#include <algorithm>
namespace sm
{
inline
bool is_between(float bound0, float bound1, float test)
{
if (bound0 < bound1) {
return test < bound1 + FLT_EPSILON && test > bound0 - FLT_EPSILON;
} else {
return test < bound0 + FLT_EPSILON && test > bound1 - FLT_EPSILON;
}
}
inline
bool is_point_at_line_left(const vec2& v, const vec2& s, const vec2& e)
{
return (v.y - s.y) * (e.x - s.x) - (v.x - s.x) * (e.y - s.y) > FLT_EPSILON;
}
inline
bool is_point_in_rect(const vec2& v, const rect& r)
{
return v.x > r.xmin && v.x < r.xmax
&& v.y > r.ymin && v.y < r.ymax;
}
inline
bool is_point_in_area(const vec2& v, const std::vector<vec2>& area)
{
bool odd_nodes = false;
for (int i = 0, n = area.size(), j = n - 1; i < n; ++i)
{
if ((area[i].y < v.y && area[j].y >= v.y ||
area[j].y < v.y && area[i].y >= v.y) &&
(area[i].x <= v.x || area[j].x <= v.x))
{
odd_nodes ^= (area[i].x + (v.y - area[i].y) / (area[j].y - area[i].y) * (area[j].x - area[i].x) < v.x);
}
j = i;
}
return odd_nodes;
}
inline
bool is_point_in_circle(const vec2& v, const vec2& center, float radius)
{
return (v - center).LengthSquared() < radius * radius;
}
inline
bool is_point_in_convex(const vec2& pos, const std::vector<vec2>& convex)
{
if (convex.size() < 3) {
return false;
}
int count = 0;
for (int i = 0, n = convex.size(); i < n; ++i)
{
vec2 s = convex[i],
e = i == convex.size() - 1 ? convex[0] : convex[i + 1];
if (is_point_at_line_left(pos, s, e)) {
++count;
}
}
return count == convex.size() || count == 0;
}
inline
bool is_point_intersect_polyline(const vec2& point, const std::vector<vec2>& polyline)
{
rect r(point, SM_LARGE_EPSILON, SM_LARGE_EPSILON);
return is_rect_intersect_polyline(r, polyline, true);
}
inline
bool is_segment_intersect_segment(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1)
{
return is_point_at_line_left(s0, s1, e1) != is_point_at_line_left(e0, s1, e1)
&& is_point_at_line_left(s1, s0, e0) != is_point_at_line_left(e1, s0, e0);
}
inline
bool is_rect_contain_point(const rect& r, const vec2& v)
{
return v.x >= r.xmin && v.x <= r.xmax
&& v.y >= r.ymin && v.y <= r.ymax;
}
inline
bool is_rect_contain_rect(const rect& r0, const rect& r1)
{
return r1.xmin >= r0.xmin && r1.xmax <= r0.xmax
&& r1.ymin >= r0.ymin && r1.ymax <= r0.ymax;
}
inline
bool is_rect_intersect_rect(const rect& r0, const rect& r1)
{
return !(r0.xmin >= r1.xmax || r0.xmax <= r1.xmin || r0.ymin >= r1.ymax || r0.ymax <= r1.ymin);
}
inline
bool is_rect_intersect_polyline(const rect& r, const std::vector<vec2>& poly, bool loop)
{
if (poly.size() < 2) return false;
for (size_t i = 0, n = poly.size() - 1; i < n; ++i)
{
if (is_rect_intersect_segment(r, poly[i], poly[i+1]))
return true;
}
if (loop && is_rect_intersect_segment(r, poly[poly.size() - 1], poly[0]))
return true;
return false;
}
inline
bool is_rect_intersect_polygon(const rect& rect, const std::vector<vec2>& poly)
{
if (poly.size() < 3) {
return false;
}
if (is_point_in_area(rect.Center(), poly) || is_point_in_rect(poly[0], rect)) {
return true;
}
std::vector<vec2> poly2;
poly2.push_back(vec2(rect.xmin, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymax));
poly2.push_back(vec2(rect.xmin, rect.ymax));
return is_polygon_intersect_polygon(poly, poly2);
}
inline
bool is_ray_intersect_triangle(const vec3& ray_ori, const vec3& ray_dir,
const vec3& tri0, const vec3& tri1,
const vec3& tri2, vec3& out)
{
// Idea: Tomas Moeller and Ben Trumbore
// in Fast, Minimum Storage Ray/Triangle Intersection
// Find vectors for two edges sharing vert0
vec3 edge1 = tri1 - tri0,
edge2 = tri2 - tri0;
// Begin calculating determinant - also used to calculate U parameter
vec3 pvec = ray_dir.Cross(edge2);
// If determinant is near zero, ray lies in sm_plane of triangle
float det = edge1.Dot(pvec);
// *** Culling branch ***
/*if (det < FLT_EPSILON)
return NULL;
// Calculate distance from vert0 to ray origin
struct sm_vec3 tvec;
sm_vec3_vector(&tvec, rayOrig, &vert0);
// Calculate U parameter and test bounds
float u = sm_vec3_dot(&tvec, &pvec);
if (u < 0 || u > det)
return NULL;
// Prepare to test V parameter
struct sm_vec3 qvec;
sm_vec3_cross(&qvec, &tvec, &edge1);
// Calculate V parameter and test bounds
float v = sm_vec3_dot(rayDir, &qvec);
if (v < 0 || u + v > det)
return NULL;
// Calculate t, scale parameters, ray intersects triangle
float t = sm_vec3_dot(&edge2, &qvec) / det;*/
// *** Non-culling branch ***
if (det > -FLT_EPSILON && det < FLT_EPSILON) {
return false;
}
float inv_det = 1.0f / det;
// Calculate distance from vert0 to ray origin
vec3 tvec = ray_ori - tri0;
// Calculate U parameter and test bounds
float u = tvec.Dot(pvec) * inv_det;
if (u < 0.0f || u > 1.0f) {
return false;
}
// Prepare to test V parameter
vec3 qvec = tvec.Cross(tri1);
// Calculate V parameter and test bounds
float v = ray_dir.Dot(qvec) * inv_det;
if (v < 0.0f || u + v > 1.0f) {
return false;
}
// Calculate t, ray intersects triangle
float t = tri2.Dot(qvec) * inv_det;
// Calculate intersection point and test ray length and direction
out.x = ray_ori.x + ray_dir.x * t;
out.y = ray_ori.y + ray_dir.y * t;
out.z = ray_ori.z + ray_dir.z * t;
vec3 vec = out - ray_ori;
if (vec.Dot(ray_dir) < 0 ||
vec.Length() > ray_dir.Length()) {
return false;
}
return true;
}
inline
bool is_ray_intersect_aabb(const vec3& ray_ori, const vec3& ray_dir,
const vec3& aabb_min, const vec3& aabb_max)
{
// SLAB based optimized ray/AABB intersection routine
// Idea taken from http://ompf.org/ray/
float l1 = (aabb_min.x - ray_ori.x) / ray_dir.x;
float l2 = (aabb_max.x - ray_ori.x) / ray_dir.x;
float lmin = std::min(l1, l2);
float lmax = std::max(l1, l2);
l1 = (aabb_min.y - ray_ori.y) / ray_dir.y;
l2 = (aabb_max.y - ray_ori.y) / ray_dir.y;
lmin = std::max(std::min(l1, l2), lmin);
lmax = std::min(std::max(l1, l2), lmax);
l1 = (aabb_min.z - ray_ori.z) / ray_dir.z;
l2 = (aabb_max.z - ray_ori.z) / ray_dir.z;
lmin = std::max(std::min(l1, l2), lmin);
lmax = std::min(std::max(l1, l2), lmax);
if ((lmax >= 0.0f) & (lmax >= lmin)) {
// Consider length
vec3 ray_dst(ray_ori.x + ray_dir.x , ray_ori.y + ray_dir.y , ray_ori.z + ray_dir.z),
ray_min(std::min(ray_dst.x, ray_ori.x), std::min(ray_dst.y, ray_ori.y), std::min(ray_dst.z, ray_ori.z)),
ray_max(std::max(ray_dst.x, ray_ori.x), std::max(ray_dst.y, ray_ori.y), std::max(ray_dst.z, ray_ori.z));
return
(ray_min.x < aabb_max.x) && (ray_max.x > aabb_min.x) &&
(ray_min.y < aabb_max.y) && (ray_max.y > aabb_min.y) &&
(ray_min.z < aabb_max.z) && (ray_max.z > aabb_min.z);
} else {
return false;
}
}
}
#endif // _SPATIAL_MATH_TEST_INL_<commit_msg>fix compile warning<commit_after>#ifndef _SPATIAL_MATH_TEST_INL_
#define _SPATIAL_MATH_TEST_INL_
//#include "SM_Calc.h"
#include "sm_const.h"
#include <float.h>
#include <algorithm>
namespace sm
{
inline
bool is_between(float bound0, float bound1, float test)
{
if (bound0 < bound1) {
return test < bound1 + FLT_EPSILON && test > bound0 - FLT_EPSILON;
} else {
return test < bound0 + FLT_EPSILON && test > bound1 - FLT_EPSILON;
}
}
inline
bool is_point_at_line_left(const vec2& v, const vec2& s, const vec2& e)
{
return (v.y - s.y) * (e.x - s.x) - (v.x - s.x) * (e.y - s.y) > FLT_EPSILON;
}
inline
bool is_point_in_rect(const vec2& v, const rect& r)
{
return v.x > r.xmin && v.x < r.xmax
&& v.y > r.ymin && v.y < r.ymax;
}
inline
bool is_point_in_area(const vec2& v, const std::vector<vec2>& area)
{
bool odd_nodes = false;
for (int i = 0, n = area.size(), j = n - 1; i < n; ++i)
{
if (((area[i].y < v.y && area[j].y >= v.y) ||
(area[j].y < v.y && area[i].y >= v.y)) &&
(area[i].x <= v.x || area[j].x <= v.x))
{
odd_nodes ^= (area[i].x + (v.y - area[i].y) / (area[j].y - area[i].y) * (area[j].x - area[i].x) < v.x);
}
j = i;
}
return odd_nodes;
}
inline
bool is_point_in_circle(const vec2& v, const vec2& center, float radius)
{
return (v - center).LengthSquared() < radius * radius;
}
inline
bool is_point_in_convex(const vec2& pos, const std::vector<vec2>& convex)
{
if (convex.size() < 3) {
return false;
}
int count = 0;
for (int i = 0, n = convex.size(); i < n; ++i)
{
vec2 s = convex[i],
e = i == convex.size() - 1 ? convex[0] : convex[i + 1];
if (is_point_at_line_left(pos, s, e)) {
++count;
}
}
return count == convex.size() || count == 0;
}
inline
bool is_point_intersect_polyline(const vec2& point, const std::vector<vec2>& polyline)
{
rect r(point, SM_LARGE_EPSILON, SM_LARGE_EPSILON);
return is_rect_intersect_polyline(r, polyline, true);
}
inline
bool is_segment_intersect_segment(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1)
{
return is_point_at_line_left(s0, s1, e1) != is_point_at_line_left(e0, s1, e1)
&& is_point_at_line_left(s1, s0, e0) != is_point_at_line_left(e1, s0, e0);
}
inline
bool is_rect_contain_point(const rect& r, const vec2& v)
{
return v.x >= r.xmin && v.x <= r.xmax
&& v.y >= r.ymin && v.y <= r.ymax;
}
inline
bool is_rect_contain_rect(const rect& r0, const rect& r1)
{
return r1.xmin >= r0.xmin && r1.xmax <= r0.xmax
&& r1.ymin >= r0.ymin && r1.ymax <= r0.ymax;
}
inline
bool is_rect_intersect_rect(const rect& r0, const rect& r1)
{
return !(r0.xmin >= r1.xmax || r0.xmax <= r1.xmin || r0.ymin >= r1.ymax || r0.ymax <= r1.ymin);
}
inline
bool is_rect_intersect_polyline(const rect& r, const std::vector<vec2>& poly, bool loop)
{
if (poly.size() < 2) return false;
for (size_t i = 0, n = poly.size() - 1; i < n; ++i)
{
if (is_rect_intersect_segment(r, poly[i], poly[i+1]))
return true;
}
if (loop && is_rect_intersect_segment(r, poly[poly.size() - 1], poly[0]))
return true;
return false;
}
inline
bool is_rect_intersect_polygon(const rect& rect, const std::vector<vec2>& poly)
{
if (poly.size() < 3) {
return false;
}
if (is_point_in_area(rect.Center(), poly) || is_point_in_rect(poly[0], rect)) {
return true;
}
std::vector<vec2> poly2;
poly2.push_back(vec2(rect.xmin, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymax));
poly2.push_back(vec2(rect.xmin, rect.ymax));
return is_polygon_intersect_polygon(poly, poly2);
}
inline
bool is_ray_intersect_triangle(const vec3& ray_ori, const vec3& ray_dir,
const vec3& tri0, const vec3& tri1,
const vec3& tri2, vec3& out)
{
// Idea: Tomas Moeller and Ben Trumbore
// in Fast, Minimum Storage Ray/Triangle Intersection
// Find vectors for two edges sharing vert0
vec3 edge1 = tri1 - tri0,
edge2 = tri2 - tri0;
// Begin calculating determinant - also used to calculate U parameter
vec3 pvec = ray_dir.Cross(edge2);
// If determinant is near zero, ray lies in sm_plane of triangle
float det = edge1.Dot(pvec);
// *** Culling branch ***
/*if (det < FLT_EPSILON)
return NULL;
// Calculate distance from vert0 to ray origin
struct sm_vec3 tvec;
sm_vec3_vector(&tvec, rayOrig, &vert0);
// Calculate U parameter and test bounds
float u = sm_vec3_dot(&tvec, &pvec);
if (u < 0 || u > det)
return NULL;
// Prepare to test V parameter
struct sm_vec3 qvec;
sm_vec3_cross(&qvec, &tvec, &edge1);
// Calculate V parameter and test bounds
float v = sm_vec3_dot(rayDir, &qvec);
if (v < 0 || u + v > det)
return NULL;
// Calculate t, scale parameters, ray intersects triangle
float t = sm_vec3_dot(&edge2, &qvec) / det;*/
// *** Non-culling branch ***
if (det > -FLT_EPSILON && det < FLT_EPSILON) {
return false;
}
float inv_det = 1.0f / det;
// Calculate distance from vert0 to ray origin
vec3 tvec = ray_ori - tri0;
// Calculate U parameter and test bounds
float u = tvec.Dot(pvec) * inv_det;
if (u < 0.0f || u > 1.0f) {
return false;
}
// Prepare to test V parameter
vec3 qvec = tvec.Cross(tri1);
// Calculate V parameter and test bounds
float v = ray_dir.Dot(qvec) * inv_det;
if (v < 0.0f || u + v > 1.0f) {
return false;
}
// Calculate t, ray intersects triangle
float t = tri2.Dot(qvec) * inv_det;
// Calculate intersection point and test ray length and direction
out.x = ray_ori.x + ray_dir.x * t;
out.y = ray_ori.y + ray_dir.y * t;
out.z = ray_ori.z + ray_dir.z * t;
vec3 vec = out - ray_ori;
if (vec.Dot(ray_dir) < 0 ||
vec.Length() > ray_dir.Length()) {
return false;
}
return true;
}
inline
bool is_ray_intersect_aabb(const vec3& ray_ori, const vec3& ray_dir,
const vec3& aabb_min, const vec3& aabb_max)
{
// SLAB based optimized ray/AABB intersection routine
// Idea taken from http://ompf.org/ray/
float l1 = (aabb_min.x - ray_ori.x) / ray_dir.x;
float l2 = (aabb_max.x - ray_ori.x) / ray_dir.x;
float lmin = std::min(l1, l2);
float lmax = std::max(l1, l2);
l1 = (aabb_min.y - ray_ori.y) / ray_dir.y;
l2 = (aabb_max.y - ray_ori.y) / ray_dir.y;
lmin = std::max(std::min(l1, l2), lmin);
lmax = std::min(std::max(l1, l2), lmax);
l1 = (aabb_min.z - ray_ori.z) / ray_dir.z;
l2 = (aabb_max.z - ray_ori.z) / ray_dir.z;
lmin = std::max(std::min(l1, l2), lmin);
lmax = std::min(std::max(l1, l2), lmax);
if ((lmax >= 0.0f) & (lmax >= lmin)) {
// Consider length
vec3 ray_dst(ray_ori.x + ray_dir.x , ray_ori.y + ray_dir.y , ray_ori.z + ray_dir.z),
ray_min(std::min(ray_dst.x, ray_ori.x), std::min(ray_dst.y, ray_ori.y), std::min(ray_dst.z, ray_ori.z)),
ray_max(std::max(ray_dst.x, ray_ori.x), std::max(ray_dst.y, ray_ori.y), std::max(ray_dst.z, ray_ori.z));
return
(ray_min.x < aabb_max.x) && (ray_max.x > aabb_min.x) &&
(ray_min.y < aabb_max.y) && (ray_max.y > aabb_min.y) &&
(ray_min.z < aabb_max.z) && (ray_max.z > aabb_min.z);
} else {
return false;
}
}
}
#endif // _SPATIAL_MATH_TEST_INL_<|endoftext|> |
<commit_before>#include "Strategy.h"
void CPUBase::copy_to(const LabelData *in, cl::Context *, cl::Program *,
cl::CommandQueue *) {
l = *in;
}
LabelData CPUBase::copy_from() { return std::move(l); }
void CPUOnePass::execute() {
size_t nr = 2;
for (size_t y = 0; y < l.height; ++y) {
for (size_t x = 0; x < l.width; ++x) {
if (l.data[l.width * y + x] == 1) {
mark_explore(x, y, &l, 1, nr);
++nr;
}
}
}
}
void GPUBase::copy_to(const LabelData *l, cl::Context *c, cl::Program *p,
cl::CommandQueue *q) {
queue = q;
program = p;
width = l->width;
height = l->height;
cl_int err;
auto size = width * height * sizeof(LABELTYPE);
buf = new cl::Buffer(*c, CL_MEM_READ_WRITE, size, nullptr, &err);
CHECKERR
/**
* TODO: check if blocking read does this correctly itself
*/
cl::Event event;
err = queue->enqueueWriteBuffer(*buf, CL_FALSE, 0, size, l->data, 0, &event);
event.wait();
}
void GPUNeighbourPropagation::execute() {
cl_int err;
cl::Kernel kernel(*program, "label_with_id", &err);
CHECKERR
err = kernel.setArg(0, *buf);
CHECKERR
err = kernel.setArg(1, (cl_int)width);
CHECKERR
cl::Event event;
err = queue->enqueueNDRangeKernel(kernel, cl::NullRange,
cl::NDRange(width, height),
cl::NDRange(1, 1), NULL, &event);
CHECKERR
event.wait();
}
LabelData GPUBase::copy_from() {
LabelData ret(width, height);
auto size = width * height * sizeof(LABELTYPE);
queue->enqueueReadBuffer(*buf, CL_TRUE, 0, size, ret.data);
delete buf;
return ret;
}
<commit_msg>Blocking write seems to actually write, and not defer till later<commit_after>#include "Strategy.h"
void CPUBase::copy_to(const LabelData *in, cl::Context *, cl::Program *,
cl::CommandQueue *) {
l = *in;
}
LabelData CPUBase::copy_from() { return std::move(l); }
void CPUOnePass::execute() {
size_t nr = 2;
for (size_t y = 0; y < l.height; ++y) {
for (size_t x = 0; x < l.width; ++x) {
if (l.data[l.width * y + x] == 1) {
mark_explore(x, y, &l, 1, nr);
++nr;
}
}
}
}
void GPUBase::copy_to(const LabelData *l, cl::Context *c, cl::Program *p,
cl::CommandQueue *q) {
queue = q;
program = p;
width = l->width;
height = l->height;
cl_int err;
auto size = width * height * sizeof(LABELTYPE);
buf = new cl::Buffer(*c, CL_MEM_READ_WRITE, size, nullptr, &err);
CHECKERR
err = queue->enqueueWriteBuffer(*buf, CL_TRUE, 0, size, l->data);
}
void GPUNeighbourPropagation::execute() {
cl_int err;
cl::Kernel kernel(*program, "label_with_id", &err);
CHECKERR
err = kernel.setArg(0, *buf);
CHECKERR
err = kernel.setArg(1, (cl_int)width);
CHECKERR
cl::Event event;
err = queue->enqueueNDRangeKernel(kernel, cl::NullRange,
cl::NDRange(width, height),
cl::NDRange(1, 1), NULL, &event);
CHECKERR
event.wait();
}
LabelData GPUBase::copy_from() {
LabelData ret(width, height);
auto size = width * height * sizeof(LABELTYPE);
queue->enqueueReadBuffer(*buf, CL_TRUE, 0, size, ret.data);
delete buf;
return ret;
}
<|endoftext|> |
<commit_before>#include "state_comp.hpp"
#include <core/ecs/serializer_impl.hpp>
namespace mo {
namespace sys {
namespace state {
using namespace unit_literals;
struct State_comp::Persisted_state {
bool delete_dead;
Persisted_state(const State_comp& c)
: delete_dead(c._delete_dead) {}
};
sf2_structDef(State_comp::Persisted_state,
sf2_member(delete_dead)
)
void State_comp::load(ecs::Entity_state& state) {
auto s = state.read_to(Persisted_state{*this});
_delete_dead = s.delete_dead;
}
void State_comp::store(ecs::Entity_state& state) {
state.write_from(Persisted_state{*this});
}
namespace {
Time required_time_for(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return 0_s;
case Entity_state::walking: return 0.1_s;
case Entity_state::attacking_melee: return 0.1_s;
case Entity_state::attacking_range: return 0.1_s;
case Entity_state::interacting: return 0.1_s;
case Entity_state::taking: return 0.5_s;
case Entity_state::change_weapon: return 0.5_s;
case Entity_state::damaged: return 0.1_s;
case Entity_state::healed: return 0.1_s;
case Entity_state::dead: return 0_s;
case Entity_state::dying: return 2.0_s;
case Entity_state::resurrected: return 0.1_s;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
bool is_background(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return true;
case Entity_state::walking: return true;
case Entity_state::attacking_melee: return false;
case Entity_state::attacking_range: return false;
case Entity_state::interacting: return false;
case Entity_state::taking: return true;
case Entity_state::change_weapon: return true;
case Entity_state::damaged: return false;
case Entity_state::healed: return false;
case Entity_state::dead: return true;
case Entity_state::dying: return false;
case Entity_state::resurrected: return false;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
int priority(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return 0;
case Entity_state::walking: return 1;
case Entity_state::attacking_melee: return 3;
case Entity_state::attacking_range: return 3;
case Entity_state::interacting: return 2;
case Entity_state::taking: return 2;
case Entity_state::change_weapon: return 3;
case Entity_state::damaged: return 4;
case Entity_state::healed: return 2;
case Entity_state::dead: return 10;
case Entity_state::dying: return 10;
case Entity_state::resurrected: return 5;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
Entity_state get_next(Entity_state state)noexcept {
switch(state) {
case Entity_state::dying:
return Entity_state::dead;
default:
return Entity_state::idle;
}
}
}
void State_comp::state(Entity_state s, float magnitude)noexcept {
INVARIANT(magnitude>=0 && magnitude<=1, "magnitude is out of range: "+util::to_string(magnitude));
auto& cstate = _state_primary.left>0_s ? _state_primary : _state_background;
if(priority(cstate.s)>priority(s) && cstate.left>0_s)
return;
auto& state = is_background(s) ? _state_background : _state_primary;
state.s=s;
state.magnitude=magnitude;
state.left=required_time_for(s);
}
auto State_comp::update(Time dt)noexcept -> util::maybe<State_data&> {
if(_state_background.left>0_s) {
_state_background.left-=dt;
// time is up, lets idle
if(_state_background.left<=0_s) {
state(get_next(_state_background.s));
}
}
if(_state_primary.left>0_s) {
_state_primary.left-=dt;
if(_state_primary.left<=0_s) {
state(get_next(_state_primary.s));
}
}
auto& cstate = _state_primary.left>0_s ? _state_primary : _state_background;
if(cstate!=_state_last) {
_state_last = cstate;
return util::justPtr(&cstate);
}
return util::nothing();
}
}
}
}
<commit_msg>fixed undead zombies (& others)<commit_after>#include "state_comp.hpp"
#include <core/ecs/serializer_impl.hpp>
namespace mo {
namespace sys {
namespace state {
using namespace unit_literals;
struct State_comp::Persisted_state {
bool delete_dead;
Persisted_state(const State_comp& c)
: delete_dead(c._delete_dead) {}
};
sf2_structDef(State_comp::Persisted_state,
sf2_member(delete_dead)
)
void State_comp::load(ecs::Entity_state& state) {
auto s = state.read_to(Persisted_state{*this});
_delete_dead = s.delete_dead;
}
void State_comp::store(ecs::Entity_state& state) {
state.write_from(Persisted_state{*this});
}
namespace {
Time required_time_for(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return 0_s;
case Entity_state::walking: return 0.1_s;
case Entity_state::attacking_melee: return 0.1_s;
case Entity_state::attacking_range: return 0.1_s;
case Entity_state::interacting: return 0.1_s;
case Entity_state::taking: return 0.5_s;
case Entity_state::change_weapon: return 0.5_s;
case Entity_state::damaged: return 0.1_s;
case Entity_state::healed: return 0.1_s;
case Entity_state::dead: return 0_s;
case Entity_state::dying: return 2.0_s;
case Entity_state::resurrected: return 0.1_s;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
bool is_background(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return true;
case Entity_state::walking: return true;
case Entity_state::attacking_melee: return false;
case Entity_state::attacking_range: return false;
case Entity_state::interacting: return false;
case Entity_state::taking: return true;
case Entity_state::change_weapon: return true;
case Entity_state::damaged: return false;
case Entity_state::healed: return false;
case Entity_state::dead: return true;
case Entity_state::dying: return false;
case Entity_state::resurrected: return false;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
int priority(Entity_state state)noexcept {
switch(state) {
case Entity_state::idle: return 0;
case Entity_state::walking: return 1;
case Entity_state::attacking_melee: return 3;
case Entity_state::attacking_range: return 3;
case Entity_state::interacting: return 2;
case Entity_state::taking: return 2;
case Entity_state::change_weapon: return 3;
case Entity_state::damaged: return 4;
case Entity_state::healed: return 2;
case Entity_state::dead: return 10;
case Entity_state::dying: return 10;
case Entity_state::resurrected: return 5;
}
INVARIANT(false, "Unexpected state "<<static_cast<int>(state));
}
Entity_state get_next(Entity_state state)noexcept {
switch(state) {
case Entity_state::dying:
return Entity_state::dead;
case Entity_state::dead:
return Entity_state::dead;
default:
return Entity_state::idle;
}
}
}
void State_comp::state(Entity_state s, float magnitude)noexcept {
INVARIANT(magnitude>=0 && magnitude<=1, "magnitude is out of range: "+util::to_string(magnitude));
auto& cstate = _state_primary.left>0_s ? _state_primary : _state_background;
if(priority(cstate.s)>priority(s) && cstate.left>0_s)
return;
auto& state = is_background(s) ? _state_background : _state_primary;
state.s=s;
state.magnitude=magnitude;
state.left=required_time_for(s);
}
auto State_comp::update(Time dt)noexcept -> util::maybe<State_data&> {
if(_state_background.left>0_s) {
_state_background.left-=dt;
// time is up, lets idle
if(_state_background.left<=0_s) {
state(get_next(_state_background.s));
}
}
if(_state_primary.left>0_s) {
_state_primary.left-=dt;
if(_state_primary.left<=0_s) {
state(get_next(_state_primary.s));
}
}
auto& cstate = _state_primary.left>0_s ? _state_primary : _state_background;
if(cstate!=_state_last) {
_state_last = cstate;
return util::justPtr(&cstate);
}
return util::nothing();
}
}
}
}
<|endoftext|> |
<commit_before>#include <uv.h>
#include <dbt.h>
#include <iostream>
#include <iomanip>
#include <atlstr.h>
// Include Windows headers
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include <Setupapi.h>
#include "detection.h"
#include "deviceList.h"
using namespace std;
/**********************************
* Local defines
**********************************/
#define VID_TAG "VID_"
#define PID_TAG "PID_"
#define LIBRARY_NAME ("setupapi.dll")
#define DllImport __declspec( dllimport )
/**********************************
* Local typedefs
**********************************/
/**********************************
* Local Variables
**********************************/
GUID GUID_DEVINTERFACE_USB_DEVICE = { 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED};
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE deviceChangedEvent;
ListResultItem_t* currentDevice;
bool isAdded;
bool isRunning = false;
HINSTANCE hinstLib;
typedef BOOL (WINAPI *_SetupDiEnumDeviceInfo) (HDEVINFO DeviceInfoSet, DWORD MemberIndex, PSP_DEVINFO_DATA DeviceInfoData);
typedef HDEVINFO (WINAPI *_SetupDiGetClassDevs) (const GUID *ClassGuid, PCTSTR Enumerator, HWND hwndParent, DWORD Flags);
typedef BOOL (WINAPI *_SetupDiDestroyDeviceInfoList) (HDEVINFO DeviceInfoSet);
typedef BOOL (WINAPI *_SetupDiGetDeviceInstanceId) (HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, PTSTR DeviceInstanceId, DWORD DeviceInstanceIdSize, PDWORD RequiredSize);
typedef BOOL (WINAPI *_SetupDiGetDeviceRegistryProperty) (HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD PropertyRegDataType, PBYTE PropertyBuffer, DWORD PropertyBufferSize, PDWORD RequiredSize);
_SetupDiEnumDeviceInfo DllSetupDiEnumDeviceInfo;
_SetupDiGetClassDevs DllSetupDiGetClassDevs;
_SetupDiDestroyDeviceInfoList DllSetupDiDestroyDeviceInfoList;
_SetupDiGetDeviceInstanceId DllSetupDiGetDeviceInstanceId;
_SetupDiGetDeviceRegistryProperty DllSetupDiGetDeviceRegistryProperty;
/**********************************
* Local Helper Functions protoypes
**********************************/
void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam, DeviceState_t state);
DWORD WINAPI ListenerThread( LPVOID lpParam );
void BuildInitialDeviceList();
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void ExtractDeviceInfo(HDEVINFO hDevInfo, SP_DEVINFO_DATA* pspDevInfoData, TCHAR* buf, DWORD buffSize, ListResultItem_t* resultItem);
/**********************************
* Public Functions
**********************************/
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(deviceChangedEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
if(isAdded)
{
NotifyAdded(currentDevice);
}
else
{
NotifyRemoved(currentDevice);
delete currentDevice;
}
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
}
void LoadFunctions()
{
bool success = true;
hinstLib = LoadLibrary(LIBRARY_NAME);
success = (hinstLib == NULL) ? false : true;
if (hinstLib != NULL)
{
DllSetupDiEnumDeviceInfo = (_SetupDiEnumDeviceInfo) GetProcAddress(hinstLib, "SetupDiEnumDeviceInfo");
success = (DllSetupDiEnumDeviceInfo == NULL) ? false : true;
DllSetupDiGetClassDevs = (_SetupDiGetClassDevs) GetProcAddress(hinstLib, "SetupDiGetClassDevsA");
success = (DllSetupDiGetClassDevs == NULL) ? false : true;
DllSetupDiDestroyDeviceInfoList = (_SetupDiDestroyDeviceInfoList) GetProcAddress(hinstLib, "SetupDiDestroyDeviceInfoList");
success = (DllSetupDiDestroyDeviceInfoList == NULL) ? false : true;
DllSetupDiGetDeviceInstanceId = (_SetupDiGetDeviceInstanceId) GetProcAddress(hinstLib, "SetupDiGetDeviceInstanceIdA");
success = (DllSetupDiGetDeviceInstanceId == NULL) ? false : true;
DllSetupDiGetDeviceRegistryProperty = (_SetupDiGetDeviceRegistryProperty) GetProcAddress(hinstLib, "SetupDiGetDeviceRegistryPropertyA");
success = (DllSetupDiGetDeviceRegistryProperty == NULL) ? false : true;
}
if(!success)
{
printf("Could not load library functions from dll -> abort (Check if %s is available)\r\n", LIBRARY_NAME);
exit(1);
}
}
void Start()
{
isRunning = true;
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
void Stop()
{
isRunning = false;
SetEvent(deviceChangedEvent);
// ExitThread(threadHandle);
}
void InitDetection()
{
LoadFunctions();
deviceChangedEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
BuildInitialDeviceList();
Start();
}
void EIO_Find(uv_work_t* req)
{
ListBaton* data = static_cast<ListBaton*>(req->data);
CreateFilteredList(&data->results, data->vid, data->pid);
}
/**********************************
* Local Functions
**********************************/
void ToUpper(char * buf)
{
char* c = buf;
while (*c != '\0')
{
*c = toupper((unsigned char)*c);
c++;
}
}
void extractVidPid(char * buf, ListResultItem_t * item)
{
if(buf == NULL)
{
return;
}
ToUpper(buf);
char* string;
char* temp;
char* pidStr, *vidStr;
int vid = 0;
int pid = 0;
string = new char[strlen(buf) + 1];
memcpy(string, buf, strlen(buf) + 1);
vidStr = strstr(string, VID_TAG);
pidStr = strstr(string, PID_TAG);
if(vidStr != NULL)
{
temp = (char*) (vidStr + strlen(VID_TAG));
temp[4] = '\0';
vid = strtol (temp, NULL, 16);
}
if(pidStr != NULL)
{
temp = (char*) (pidStr + strlen(PID_TAG));
temp[4] = '\0';
pid = strtol (temp, NULL, 16);
}
item->vendorId = vid;
item->productId = pid;
delete string;
}
LRESULT CALLBACK DetectCallback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_DEVICECHANGE)
{
if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam )
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
PDEV_BROADCAST_DEVICEINTERFACE pDevInf;
if(pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
UpdateDevice(pDevInf, wParam, (DBT_DEVICEARRIVAL == wParam) ? DeviceState_Connect : DeviceState_Disconnect);
}
}
}
return 1;
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
const char *className = "ListnerThread";
WNDCLASSA wincl = {0};
wincl.hInstance = GetModuleHandle(0);
wincl.lpszClassName = className;
wincl.lpfnWndProc = DetectCallback;
if (!RegisterClassA(&wincl))
{
DWORD le = GetLastError();
printf("RegisterClassA() failed [Error: %x]\r\n", le);
return 1;
}//if
HWND hwnd = CreateWindowExA(WS_EX_TOPMOST, className, className, 0, 0, 0, 0, 0, NULL, 0, 0, 0);
if (!hwnd)
{
DWORD le = GetLastError();
printf("CreateWindowExA() failed [Error: %x]\r\n", le);
return 1;
}//if
DEV_BROADCAST_DEVICEINTERFACE_A notifyFilter = {0};
notifyFilter.dbcc_size = sizeof(notifyFilter);
notifyFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
notifyFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
HDEVNOTIFY hDevNotify = RegisterDeviceNotificationA(hwnd, ¬ifyFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if (!hDevNotify)
{
DWORD le = GetLastError();
printf("RegisterDeviceNotificationA() failed [Error: %x]\r\n", le);
return 1;
}//if
MSG msg;
for (;;) // ctrl-c to exit ;)
{
BOOL bRet = GetMessage(&msg, hwnd, 0, 0);
if ((bRet == 0) || (bRet == -1))
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}//while
return 0;
}
void BuildInitialDeviceList()
{
TCHAR buf[MAX_PATH];
DWORD dwFlag = (DIGCF_ALLCLASSES | DIGCF_PRESENT);
HDEVINFO hDevInfo = DllSetupDiGetClassDevs(NULL, "USB", NULL, dwFlag);
if( INVALID_HANDLE_VALUE == hDevInfo )
{
return;
}
SP_DEVINFO_DATA* pspDevInfoData = (SP_DEVINFO_DATA*) HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVINFO_DATA));
pspDevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; DllSetupDiEnumDeviceInfo(hDevInfo, i, pspDevInfoData); i++)
{
DWORD nSize=0 ;
if ( !DllSetupDiGetDeviceInstanceId(hDevInfo, pspDevInfoData, buf, sizeof(buf), &nSize) )
{
break;
}
DeviceItem_t* item = new DeviceItem_t();
item->deviceState = DeviceState_Connect;
DWORD DataT;
DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, MAX_PATH, &nSize);
AddItemToList(buf, item);
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, &item->deviceParams);
}
if ( pspDevInfoData )
{
HeapFree(GetProcessHeap(), 0, pspDevInfoData);
}
if(hDevInfo)
{
DllSetupDiDestroyDeviceInfoList(hDevInfo);
}
}
void ExtractDeviceInfo(HDEVINFO hDevInfo, SP_DEVINFO_DATA* pspDevInfoData, TCHAR* buf, DWORD buffSize, ListResultItem_t* resultItem)
{
DWORD DataT;
DWORD nSize;
static int dummy = 1;
resultItem->locationId = 0;
resultItem->deviceAddress = dummy++;
// device found
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_FRIENDLYNAME, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->deviceName = buf;
}
else if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_DEVICEDESC, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->deviceName = buf;
}
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_MFG, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->manufacturer = buf;
}
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
// Use this to extract VID / PID
extractVidPid(buf, resultItem);
}
}
void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam, DeviceState_t state)
{
// dbcc_name:
// \\?\USB#Vid_04e8&Pid_503b#0002F9A9828E0F06#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
// convert to
// USB\Vid_04e8&Pid_503b\0002F9A9828E0F06
CString szDevId = pDevInf->dbcc_name+4;
int idx = szDevId.ReverseFind(_T('#'));
szDevId.Truncate(idx);
szDevId.Replace(_T('#'), _T('\\'));
szDevId.MakeUpper();
CString szClass;
idx = szDevId.Find(_T('\\'));
szClass = szDevId.Left(idx);
// if we are adding device, we only need present devices
// otherwise, we need all devices
DWORD dwFlag = DBT_DEVICEARRIVAL != wParam ? DIGCF_ALLCLASSES : (DIGCF_ALLCLASSES | DIGCF_PRESENT);
HDEVINFO hDevInfo = DllSetupDiGetClassDevs(NULL, szClass, NULL, dwFlag);
if( INVALID_HANDLE_VALUE == hDevInfo )
{
return;
}
SP_DEVINFO_DATA* pspDevInfoData = (SP_DEVINFO_DATA*) HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVINFO_DATA));
pspDevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; DllSetupDiEnumDeviceInfo(hDevInfo, i, pspDevInfoData); i++)
{
DWORD nSize=0 ;
TCHAR buf[MAX_PATH];
if ( !DllSetupDiGetDeviceInstanceId(hDevInfo, pspDevInfoData, buf, sizeof(buf), &nSize) )
{
break;
}
if ( szDevId == buf )
{
DWORD DataT;
DWORD nSize;
DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, MAX_PATH, &nSize);
if(state == DeviceState_Connect)
{
DeviceItem_t* device = new DeviceItem_t();
AddItemToList(buf, device);
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, &device->deviceParams);
currentDevice = &device->deviceParams;
isAdded = true;
}
else
{
ListResultItem_t* item = NULL;
if(IsItemAlreadyStored(buf))
{
DeviceItem_t* deviceItem = GetItemFromList(buf);
if(deviceItem)
{
item = CopyElement(&deviceItem->deviceParams);
}
RemoveItemFromList(deviceItem);
delete deviceItem;
}
if(item == NULL)
{
item = new ListResultItem_t();
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, item);
}
currentDevice = item;
isAdded = false;
}
break;
}
}
if ( pspDevInfoData )
{
HeapFree(GetProcessHeap(), 0, pspDevInfoData);
}
if(hDevInfo)
{
DllSetupDiDestroyDeviceInfoList(hDevInfo);
}
SetEvent(deviceChangedEvent);
}<commit_msg>unique listener thread name<commit_after>#include <uv.h>
#include <dbt.h>
#include <iostream>
#include <iomanip>
#include <atlstr.h>
// Include Windows headers
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include <Setupapi.h>
#include "detection.h"
#include "deviceList.h"
using namespace std;
/**********************************
* Local defines
**********************************/
#define VID_TAG "VID_"
#define PID_TAG "PID_"
#define LIBRARY_NAME ("setupapi.dll")
#define DllImport __declspec( dllimport )
/**********************************
* Local typedefs
**********************************/
/**********************************
* Local Variables
**********************************/
GUID GUID_DEVINTERFACE_USB_DEVICE = { 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED};
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE deviceChangedEvent;
ListResultItem_t* currentDevice;
bool isAdded;
bool isRunning = false;
HINSTANCE hinstLib;
typedef BOOL (WINAPI *_SetupDiEnumDeviceInfo) (HDEVINFO DeviceInfoSet, DWORD MemberIndex, PSP_DEVINFO_DATA DeviceInfoData);
typedef HDEVINFO (WINAPI *_SetupDiGetClassDevs) (const GUID *ClassGuid, PCTSTR Enumerator, HWND hwndParent, DWORD Flags);
typedef BOOL (WINAPI *_SetupDiDestroyDeviceInfoList) (HDEVINFO DeviceInfoSet);
typedef BOOL (WINAPI *_SetupDiGetDeviceInstanceId) (HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, PTSTR DeviceInstanceId, DWORD DeviceInstanceIdSize, PDWORD RequiredSize);
typedef BOOL (WINAPI *_SetupDiGetDeviceRegistryProperty) (HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD PropertyRegDataType, PBYTE PropertyBuffer, DWORD PropertyBufferSize, PDWORD RequiredSize);
_SetupDiEnumDeviceInfo DllSetupDiEnumDeviceInfo;
_SetupDiGetClassDevs DllSetupDiGetClassDevs;
_SetupDiDestroyDeviceInfoList DllSetupDiDestroyDeviceInfoList;
_SetupDiGetDeviceInstanceId DllSetupDiGetDeviceInstanceId;
_SetupDiGetDeviceRegistryProperty DllSetupDiGetDeviceRegistryProperty;
/**********************************
* Local Helper Functions protoypes
**********************************/
void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam, DeviceState_t state);
DWORD WINAPI ListenerThread( LPVOID lpParam );
void BuildInitialDeviceList();
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void ExtractDeviceInfo(HDEVINFO hDevInfo, SP_DEVINFO_DATA* pspDevInfoData, TCHAR* buf, DWORD buffSize, ListResultItem_t* resultItem);
/**********************************
* Public Functions
**********************************/
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(deviceChangedEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
if(isAdded)
{
NotifyAdded(currentDevice);
}
else
{
NotifyRemoved(currentDevice);
delete currentDevice;
}
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
}
void LoadFunctions()
{
bool success = true;
hinstLib = LoadLibrary(LIBRARY_NAME);
success = (hinstLib == NULL) ? false : true;
if (hinstLib != NULL)
{
DllSetupDiEnumDeviceInfo = (_SetupDiEnumDeviceInfo) GetProcAddress(hinstLib, "SetupDiEnumDeviceInfo");
success = (DllSetupDiEnumDeviceInfo == NULL) ? false : true;
DllSetupDiGetClassDevs = (_SetupDiGetClassDevs) GetProcAddress(hinstLib, "SetupDiGetClassDevsA");
success = (DllSetupDiGetClassDevs == NULL) ? false : true;
DllSetupDiDestroyDeviceInfoList = (_SetupDiDestroyDeviceInfoList) GetProcAddress(hinstLib, "SetupDiDestroyDeviceInfoList");
success = (DllSetupDiDestroyDeviceInfoList == NULL) ? false : true;
DllSetupDiGetDeviceInstanceId = (_SetupDiGetDeviceInstanceId) GetProcAddress(hinstLib, "SetupDiGetDeviceInstanceIdA");
success = (DllSetupDiGetDeviceInstanceId == NULL) ? false : true;
DllSetupDiGetDeviceRegistryProperty = (_SetupDiGetDeviceRegistryProperty) GetProcAddress(hinstLib, "SetupDiGetDeviceRegistryPropertyA");
success = (DllSetupDiGetDeviceRegistryProperty == NULL) ? false : true;
}
if(!success)
{
printf("Could not load library functions from dll -> abort (Check if %s is available)\r\n", LIBRARY_NAME);
exit(1);
}
}
void Start()
{
isRunning = true;
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
void Stop()
{
isRunning = false;
SetEvent(deviceChangedEvent);
// ExitThread(threadHandle);
}
void InitDetection()
{
LoadFunctions();
deviceChangedEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
BuildInitialDeviceList();
Start();
}
void EIO_Find(uv_work_t* req)
{
ListBaton* data = static_cast<ListBaton*>(req->data);
CreateFilteredList(&data->results, data->vid, data->pid);
}
/**********************************
* Local Functions
**********************************/
void ToUpper(char * buf)
{
char* c = buf;
while (*c != '\0')
{
*c = toupper((unsigned char)*c);
c++;
}
}
void extractVidPid(char * buf, ListResultItem_t * item)
{
if(buf == NULL)
{
return;
}
ToUpper(buf);
char* string;
char* temp;
char* pidStr, *vidStr;
int vid = 0;
int pid = 0;
string = new char[strlen(buf) + 1];
memcpy(string, buf, strlen(buf) + 1);
vidStr = strstr(string, VID_TAG);
pidStr = strstr(string, PID_TAG);
if(vidStr != NULL)
{
temp = (char*) (vidStr + strlen(VID_TAG));
temp[4] = '\0';
vid = strtol (temp, NULL, 16);
}
if(pidStr != NULL)
{
temp = (char*) (pidStr + strlen(PID_TAG));
temp[4] = '\0';
pid = strtol (temp, NULL, 16);
}
item->vendorId = vid;
item->productId = pid;
delete string;
}
LRESULT CALLBACK DetectCallback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_DEVICECHANGE)
{
if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam )
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
PDEV_BROADCAST_DEVICEINTERFACE pDevInf;
if(pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
UpdateDevice(pDevInf, wParam, (DBT_DEVICEARRIVAL == wParam) ? DeviceState_Connect : DeviceState_Disconnect);
}
}
}
return 1;
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
const char *className = "ListnerThreadUsbDetection";
WNDCLASSA wincl = {0};
wincl.hInstance = GetModuleHandle(0);
wincl.lpszClassName = className;
wincl.lpfnWndProc = DetectCallback;
if (!RegisterClassA(&wincl))
{
DWORD le = GetLastError();
printf("RegisterClassA() failed [Error: %x]\r\n", le);
return 1;
}//if
HWND hwnd = CreateWindowExA(WS_EX_TOPMOST, className, className, 0, 0, 0, 0, 0, NULL, 0, 0, 0);
if (!hwnd)
{
DWORD le = GetLastError();
printf("CreateWindowExA() failed [Error: %x]\r\n", le);
return 1;
}//if
DEV_BROADCAST_DEVICEINTERFACE_A notifyFilter = {0};
notifyFilter.dbcc_size = sizeof(notifyFilter);
notifyFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
notifyFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
HDEVNOTIFY hDevNotify = RegisterDeviceNotificationA(hwnd, ¬ifyFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
if (!hDevNotify)
{
DWORD le = GetLastError();
printf("RegisterDeviceNotificationA() failed [Error: %x]\r\n", le);
return 1;
}//if
MSG msg;
for (;;) // ctrl-c to exit ;)
{
BOOL bRet = GetMessage(&msg, hwnd, 0, 0);
if ((bRet == 0) || (bRet == -1))
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}//while
return 0;
}
void BuildInitialDeviceList()
{
TCHAR buf[MAX_PATH];
DWORD dwFlag = (DIGCF_ALLCLASSES | DIGCF_PRESENT);
HDEVINFO hDevInfo = DllSetupDiGetClassDevs(NULL, "USB", NULL, dwFlag);
if( INVALID_HANDLE_VALUE == hDevInfo )
{
return;
}
SP_DEVINFO_DATA* pspDevInfoData = (SP_DEVINFO_DATA*) HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVINFO_DATA));
pspDevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; DllSetupDiEnumDeviceInfo(hDevInfo, i, pspDevInfoData); i++)
{
DWORD nSize=0 ;
if ( !DllSetupDiGetDeviceInstanceId(hDevInfo, pspDevInfoData, buf, sizeof(buf), &nSize) )
{
break;
}
DeviceItem_t* item = new DeviceItem_t();
item->deviceState = DeviceState_Connect;
DWORD DataT;
DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, MAX_PATH, &nSize);
AddItemToList(buf, item);
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, &item->deviceParams);
}
if ( pspDevInfoData )
{
HeapFree(GetProcessHeap(), 0, pspDevInfoData);
}
if(hDevInfo)
{
DllSetupDiDestroyDeviceInfoList(hDevInfo);
}
}
void ExtractDeviceInfo(HDEVINFO hDevInfo, SP_DEVINFO_DATA* pspDevInfoData, TCHAR* buf, DWORD buffSize, ListResultItem_t* resultItem)
{
DWORD DataT;
DWORD nSize;
static int dummy = 1;
resultItem->locationId = 0;
resultItem->deviceAddress = dummy++;
// device found
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_FRIENDLYNAME, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->deviceName = buf;
}
else if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_DEVICEDESC, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->deviceName = buf;
}
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_MFG, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
resultItem->manufacturer = buf;
}
if ( DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, buffSize, &nSize) )
{
// Use this to extract VID / PID
extractVidPid(buf, resultItem);
}
}
void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam, DeviceState_t state)
{
// dbcc_name:
// \\?\USB#Vid_04e8&Pid_503b#0002F9A9828E0F06#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
// convert to
// USB\Vid_04e8&Pid_503b\0002F9A9828E0F06
CString szDevId = pDevInf->dbcc_name+4;
int idx = szDevId.ReverseFind(_T('#'));
szDevId.Truncate(idx);
szDevId.Replace(_T('#'), _T('\\'));
szDevId.MakeUpper();
CString szClass;
idx = szDevId.Find(_T('\\'));
szClass = szDevId.Left(idx);
// if we are adding device, we only need present devices
// otherwise, we need all devices
DWORD dwFlag = DBT_DEVICEARRIVAL != wParam ? DIGCF_ALLCLASSES : (DIGCF_ALLCLASSES | DIGCF_PRESENT);
HDEVINFO hDevInfo = DllSetupDiGetClassDevs(NULL, szClass, NULL, dwFlag);
if( INVALID_HANDLE_VALUE == hDevInfo )
{
return;
}
SP_DEVINFO_DATA* pspDevInfoData = (SP_DEVINFO_DATA*) HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVINFO_DATA));
pspDevInfoData->cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; DllSetupDiEnumDeviceInfo(hDevInfo, i, pspDevInfoData); i++)
{
DWORD nSize=0 ;
TCHAR buf[MAX_PATH];
if ( !DllSetupDiGetDeviceInstanceId(hDevInfo, pspDevInfoData, buf, sizeof(buf), &nSize) )
{
break;
}
if ( szDevId == buf )
{
DWORD DataT;
DWORD nSize;
DllSetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData, SPDRP_HARDWAREID, &DataT, (PBYTE)buf, MAX_PATH, &nSize);
if(state == DeviceState_Connect)
{
DeviceItem_t* device = new DeviceItem_t();
AddItemToList(buf, device);
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, &device->deviceParams);
currentDevice = &device->deviceParams;
isAdded = true;
}
else
{
ListResultItem_t* item = NULL;
if(IsItemAlreadyStored(buf))
{
DeviceItem_t* deviceItem = GetItemFromList(buf);
if(deviceItem)
{
item = CopyElement(&deviceItem->deviceParams);
}
RemoveItemFromList(deviceItem);
delete deviceItem;
}
if(item == NULL)
{
item = new ListResultItem_t();
ExtractDeviceInfo(hDevInfo, pspDevInfoData, buf, MAX_PATH, item);
}
currentDevice = item;
isAdded = false;
}
break;
}
}
if ( pspDevInfoData )
{
HeapFree(GetProcessHeap(), 0, pspDevInfoData);
}
if(hDevInfo)
{
DllSetupDiDestroyDeviceInfoList(hDevInfo);
}
SetEvent(deviceChangedEvent);
}<|endoftext|> |
<commit_before>/*
* Copyright 2012 Steven Gribble
*
* This file is part of the UW CSE 333 course project sequence
* (333proj).
*
* 333proj is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 333proj is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 333proj. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <memory>
extern "C" {
#include "libhw2/fileparser.h"
}
#include "./HttpUtils.h"
#include "./FileReader.h"
namespace hw4 {
bool FileReader::ReadFile(std::string *str) {
std::string fullfile = basedir_ + "/" + fname_;
// Read the file into memory, and store the file contents in the
// output parameter "str." Be careful to handle binary data
// correctly; i.e., you probably want to use the two-argument
// constructor to std::string (the one that includes a length as a
// second argument).
//
// You might find ::ReadFile() from HW2's fileparser.h useful
// here. Be careful, though; remember that it uses malloc to
// allocate memory, so you'll need to use free() to free up that
// memory. Alternatively, you can use a unique_ptr with a malloc/free
// deleter to automatically manage this for you; see the comment in
// HttpUtils.h above the MallocDeleter class for details.
// MISSING:
HWSize_t size;
std::unique_ptr<char, MallocDeleter<char> > ptr { ::ReadFile(fullfile.c_str(), &size) };
*str = std::string(ptr.get(), size);
return true;
}
} // namespace hw4
<commit_msg>CSE333: FileReader done<commit_after>/*
* Copyright 2012 Steven Gribble
*
* This file is part of the UW CSE 333 course project sequence
* (333proj).
*
* 333proj is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 333proj is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 333proj. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <memory>
extern "C" {
#include "libhw2/fileparser.h"
}
#include "./HttpUtils.h"
#include "./FileReader.h"
namespace hw4 {
bool FileReader::ReadFile(std::string *str) {
std::string fullfile = basedir_ + "/" + fname_;
// Read the file into memory, and store the file contents in the
// output parameter "str." Be careful to handle binary data
// correctly; i.e., you probably want to use the two-argument
// constructor to std::string (the one that includes a length as a
// second argument).
//
// You might find ::ReadFile() from HW2's fileparser.h useful
// here. Be careful, though; remember that it uses malloc to
// allocate memory, so you'll need to use free() to free up that
// memory. Alternatively, you can use a unique_ptr with a malloc/free
// deleter to automatically manage this for you; see the comment in
// HttpUtils.h above the MallocDeleter class for details.
// MISSING:
HWSize_t size;
std::unique_ptr<char, MallocDeleter<char> > ptr { ::ReadFile(fullfile.c_str(), &size) };
if (ptr.get() == nullptr) return false;
*str = std::string(ptr.get(), size);
return true;
}
} // namespace hw4
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: atkwindow.cxx,v $
* $Revision: 1.7 $
*
* 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_vcl.hxx"
#include <plugins/gtk/gtkframe.hxx>
#include <vcl/window.hxx>
#include "atkwindow.hxx"
#include "atkregistry.hxx"
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::uno;
extern "C" {
static void (* window_real_initialize) (AtkObject *obj, gpointer data) = NULL;
static void (* window_real_finalize) (GObject *obj) = NULL;
static G_CONST_RETURN gchar* (* window_real_get_name) (AtkObject *accessible) = NULL;
static gint
ooo_window_wrapper_clear_focus(gpointer)
{
atk_focus_tracker_notify( NULL );
return FALSE;
}
/*****************************************************************************/
static gboolean
ooo_window_wrapper_real_focus_gtk (GtkWidget *, GdkEventFocus *)
{
g_idle_add( ooo_window_wrapper_clear_focus, NULL );
return FALSE;
}
/*****************************************************************************/
static void
ooo_window_wrapper_real_initialize(AtkObject *obj, gpointer data)
{
window_real_initialize(obj, data);
GtkSalFrame *pFrame = GtkSalFrame::getFromWindow( GTK_WINDOW( data ) );
if( pFrame )
{
Window *pWindow = pFrame->GetWindow();
if( pWindow )
{
Reference< XAccessible > xAccessible( pWindow->GetAccessible(true) );
ooo_wrapper_registry_add( xAccessible, obj );
g_object_set_data( G_OBJECT(obj), "ooo:registry-key", xAccessible.get() );
}
}
/* GetAtkRole returns ATK_ROLE_INVALID for all non VCL windows, i.e.
* native Gtk+ file picker etc.
*/
AtkRole newRole = GtkSalFrame::GetAtkRole( GTK_WINDOW( data ) );
if( newRole != ATK_ROLE_INVALID )
obj->role = newRole;
if( obj->role == ATK_ROLE_TOOL_TIP )
{
/* HACK: Avoid endless loop when get_name is called from
* gail_window_new() context, which leads to the code path
* showing up in wrapper_factory_create_accessible with no
* accessible assigned to the GtkWindow yet.
*/
g_object_set_data( G_OBJECT( data ), "ooo:tooltip-accessible", obj );
}
g_signal_connect_after( GTK_WIDGET( data ), "focus-out-event",
G_CALLBACK (ooo_window_wrapper_real_focus_gtk),
NULL);
}
/*****************************************************************************/
static G_CONST_RETURN gchar*
ooo_window_wrapper_real_get_name(AtkObject *accessible)
{
G_CONST_RETURN gchar* name = NULL;
if( accessible->role == ATK_ROLE_TOOL_TIP )
{
AtkObject *child = atk_object_ref_accessible_child(accessible, 0);
if( child )
{
name = atk_object_get_name(child);
g_object_unref(child);
}
return name;
}
return window_real_get_name(accessible);
}
/*****************************************************************************/
static void
ooo_window_wrapper_real_finalize (GObject *obj)
{
ooo_wrapper_registry_remove( (XAccessible *) g_object_get_data( obj, "ooo:registry-key" ));
window_real_finalize( obj );
}
/*****************************************************************************/
static void
ooo_window_wrapper_class_init (AtkObjectClass *klass, gpointer)
{
AtkObjectClass *atk_class;
GObjectClass *gobject_class;
gpointer data;
/*
* Patch the gobject vtable of GailWindow to refer to our instance of
* "initialize" and "get_name".
*/
data = g_type_class_peek_parent( klass );
atk_class = ATK_OBJECT_CLASS (data);
window_real_initialize = atk_class->initialize;
atk_class->initialize = ooo_window_wrapper_real_initialize;
window_real_get_name = atk_class->get_name;
atk_class->get_name = ooo_window_wrapper_real_get_name;
gobject_class = G_OBJECT_CLASS (data);
window_real_finalize = gobject_class->finalize;
gobject_class->finalize = ooo_window_wrapper_real_finalize;
}
} // extern "C"
/*****************************************************************************/
GType
ooo_window_wrapper_get_type (void)
{
static GType type = 0;
if (!type)
{
GType parent_type = g_type_from_name( "GailWindow" );
if( ! parent_type )
{
g_warning( "Unknown type: GailWindow" );
parent_type = ATK_TYPE_OBJECT;
}
GTypeQuery type_query;
g_type_query( parent_type, &type_query );
static const GTypeInfo typeInfo =
{
type_query.class_size,
(GBaseInitFunc) NULL,
(GBaseFinalizeFunc) NULL,
(GClassInitFunc) ooo_window_wrapper_class_init,
(GClassFinalizeFunc) NULL,
NULL,
type_query.instance_size,
0,
(GInstanceInitFunc) NULL,
NULL
} ;
type = g_type_register_static (parent_type, "OOoWindowAtkObject", &typeInfo, (GTypeFlags)0) ;
}
return type;
}
void restore_gail_window_vtable (void)
{
AtkObjectClass *atk_class;
gpointer data;
GType type = g_type_from_name( "GailWindow" );
if( type == G_TYPE_INVALID )
return;
data = g_type_class_peek( type );
atk_class = ATK_OBJECT_CLASS (data);
atk_class->initialize = window_real_initialize;
atk_class->get_name = window_real_get_name;
}
<commit_msg>INTEGRATION: CWS uaa06 (1.7.20); FILE MERGED 2008/05/16 05:20:58 obr 1.7.20.2: #i87426# replace FILLER role with option pane again for dialogs and alerts 2008/05/08 12:39:09 obr 1.7.20.1: #i87426# repaired broken a11y hierarchy of a number of dialogs<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: atkwindow.cxx,v $
* $Revision: 1.8 $
*
* 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_vcl.hxx"
#include <plugins/gtk/gtkframe.hxx>
#include <vcl/window.hxx>
#include "atkwindow.hxx"
#include "atkwrapper.hxx"
#include "atkregistry.hxx"
#include <com/sun/star/accessibility/AccessibleRole.hpp>
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::uno;
extern "C" {
static void (* window_real_initialize) (AtkObject *obj, gpointer data) = NULL;
static void (* window_real_finalize) (GObject *obj) = NULL;
static G_CONST_RETURN gchar* (* window_real_get_name) (AtkObject *accessible) = NULL;
static void
init_from_window( AtkObject *accessible, Window *pWindow )
{
static AtkRole aDefaultRole = ATK_ROLE_INVALID;
// Special role for sub-menu and combo-box popups that are exposed directly
// by their parents already.
if( aDefaultRole == ATK_ROLE_INVALID )
aDefaultRole = atk_role_register( "redundant object" );
AtkRole role = aDefaultRole;
// Determine the appropriate role for the GtkWindow
switch( pWindow->GetAccessibleRole() )
{
case AccessibleRole::ALERT:
role = ATK_ROLE_ALERT;
break;
case AccessibleRole::DIALOG:
role = ATK_ROLE_DIALOG;
break;
case AccessibleRole::FRAME:
role = ATK_ROLE_FRAME;
break;
/* Ignore window objects for sub-menus, combo- and list boxes,
* which are exposed as children of their parents.
*/
case AccessibleRole::WINDOW:
{
USHORT type = WINDOW_WINDOW;
bool parentIsMenuFloatingWindow = false;
Window *pParent = pWindow->GetParent();
if( pParent ) {
type = pParent->GetType();
parentIsMenuFloatingWindow = ( TRUE == pParent->IsMenuFloatingWindow() );
}
if( (WINDOW_LISTBOX != type) && (WINDOW_COMBOBOX != type) &&
(WINDOW_MENUBARWINDOW != type) && ! parentIsMenuFloatingWindow )
{
role = ATK_ROLE_WINDOW;
}
}
break;
default:
{
Window *pChild = pWindow->GetChild( 0 );
if( pChild )
{
if( WINDOW_HELPTEXTWINDOW == pChild->GetType() )
{
role = ATK_ROLE_TOOL_TIP;
pChild->SetAccessibleRole( AccessibleRole::LABEL );
accessible->name = g_strdup( rtl::OUStringToOString( pChild->GetText(), RTL_TEXTENCODING_UTF8 ).getStr() );
}
}
break;
}
}
accessible->role = role;
}
/*****************************************************************************/
static gint
ooo_window_wrapper_clear_focus(gpointer)
{
atk_focus_tracker_notify( NULL );
return FALSE;
}
/*****************************************************************************/
static gboolean
ooo_window_wrapper_real_focus_gtk (GtkWidget *, GdkEventFocus *)
{
g_idle_add( ooo_window_wrapper_clear_focus, NULL );
return FALSE;
}
/*****************************************************************************/
static void
ooo_window_wrapper_real_initialize(AtkObject *obj, gpointer data)
{
window_real_initialize(obj, data);
GtkSalFrame *pFrame = GtkSalFrame::getFromWindow( GTK_WINDOW( data ) );
if( pFrame )
{
Window *pWindow = pFrame->GetWindow();
if( pWindow )
{
init_from_window( obj, pWindow );
Reference< XAccessible > xAccessible( pWindow->GetAccessible(true) );
/* We need the wrapper object for the top-level XAccessible to be
* in the wrapper registry when atk traverses the hierachy up on
* focus events
*/
if( WINDOW_BORDERWINDOW == pWindow->GetType() )
{
ooo_wrapper_registry_add( xAccessible, obj );
g_object_set_data( G_OBJECT(obj), "ooo:atk-wrapper-key", xAccessible.get() );
}
else
{
AtkObject *child = atk_object_wrapper_new( xAccessible, obj );
child->role = ATK_ROLE_FILLER;
if( (ATK_ROLE_DIALOG == obj->role) || (ATK_ROLE_ALERT == obj->role) )
child->role = ATK_ROLE_OPTION_PANE;
ooo_wrapper_registry_add( xAccessible, child );
}
}
}
g_signal_connect_after( GTK_WIDGET( data ), "focus-out-event",
G_CALLBACK (ooo_window_wrapper_real_focus_gtk),
NULL);
}
/*****************************************************************************/
static void
ooo_window_wrapper_real_finalize (GObject *obj)
{
ooo_wrapper_registry_remove( (XAccessible *) g_object_get_data( obj, "ooo:atk-wrapper-key" ));
window_real_finalize( obj );
}
/*****************************************************************************/
static void
ooo_window_wrapper_class_init (AtkObjectClass *klass, gpointer)
{
AtkObjectClass *atk_class;
GObjectClass *gobject_class;
gpointer data;
/*
* Patch the gobject vtable of GailWindow to refer to our instance of
* "initialize" and "get_name".
*/
data = g_type_class_peek_parent( klass );
atk_class = ATK_OBJECT_CLASS (data);
window_real_initialize = atk_class->initialize;
atk_class->initialize = ooo_window_wrapper_real_initialize;
gobject_class = G_OBJECT_CLASS (data);
window_real_finalize = gobject_class->finalize;
gobject_class->finalize = ooo_window_wrapper_real_finalize;
}
} // extern "C"
/*****************************************************************************/
GType
ooo_window_wrapper_get_type (void)
{
static GType type = 0;
if (!type)
{
GType parent_type = g_type_from_name( "GailWindow" );
if( ! parent_type )
{
g_warning( "Unknown type: GailWindow" );
parent_type = ATK_TYPE_OBJECT;
}
GTypeQuery type_query;
g_type_query( parent_type, &type_query );
static const GTypeInfo typeInfo =
{
type_query.class_size,
(GBaseInitFunc) NULL,
(GBaseFinalizeFunc) NULL,
(GClassInitFunc) ooo_window_wrapper_class_init,
(GClassFinalizeFunc) NULL,
NULL,
type_query.instance_size,
0,
(GInstanceInitFunc) NULL,
NULL
} ;
type = g_type_register_static (parent_type, "OOoWindowAtkObject", &typeInfo, (GTypeFlags)0) ;
}
return type;
}
void restore_gail_window_vtable (void)
{
AtkObjectClass *atk_class;
gpointer data;
GType type = g_type_from_name( "GailWindow" );
if( type == G_TYPE_INVALID )
return;
data = g_type_class_peek( type );
atk_class = ATK_OBJECT_CLASS (data);
atk_class->initialize = window_real_initialize;
atk_class->get_name = window_real_get_name;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "ParserWorker.h"
#include "Parser.h"
#include "Media.h"
#include "Folder.h"
namespace medialibrary
{
namespace parser
{
Worker::Worker()
: m_parserCb( nullptr )
, m_stopParser( false )
, m_paused( false )
, m_idle( true )
{
}
void Worker::start()
{
// Ensure we don't start multiple times.
assert( m_threads.size() == 0 );
for ( auto i = 0u; i < m_service->nbThreads(); ++i )
m_threads.emplace_back( &Worker::mainloop, this );
}
void Worker::pause()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = true;
}
void Worker::resume()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = false;
m_cond.notify_all();
}
void Worker::signalStop()
{
for ( auto& t : m_threads )
{
if ( t.joinable() )
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_cond.notify_all();
m_stopParser = true;
}
}
}
void Worker::stop()
{
for ( auto& t : m_threads )
{
if ( t.joinable() )
t.join();
}
}
void Worker::parse( std::shared_ptr<Task> t )
{
// Avoid flickering from idle/not idle when not many tasks are running.
// The thread calling parse for the next parser step might not have
// something left to do and would turn idle, potentially causing all
// services to be idle for a very short time, until this parser
// thread awakes/starts, causing the global parser idle state to be
// restored back to false.
// Since we are queuing a task, we already know that this thread is
// not idle
setIdle( false );
if ( m_threads.size() == 0 )
{
// Since the thread isn't started, no need to lock the mutex before pushing the task
m_tasks.push( std::move( t ) );
start();
}
else
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_tasks.push( std::move( t ) );
}
m_cond.notify_all();
}
}
bool Worker::initialize( MediaLibrary* ml, IParserCb* parserCb,
std::shared_ptr<IParserService> service )
{
m_ml = ml;
m_service = std::move( service );
m_parserCb = parserCb;
// Run the service specific initializer
return m_service->initialize( ml );
}
bool Worker::isIdle() const
{
return m_idle;
}
void Worker::flush()
{
std::unique_lock<compat::Mutex> lock( m_lock );
assert( m_paused == true || m_threads.empty() == true );
m_idleCond.wait( lock, [this]() {
return m_idle == true;
});
while ( m_tasks.empty() == false )
m_tasks.pop();
m_service->onFlushing();
}
void Worker::restart()
{
m_service->onRestarted();
}
void Worker::mainloop()
{
// It would be unsafe to call name() at the end of this function, since
// we might stop the thread during ParserService destruction. This implies
// that the underlying service has been deleted already.
std::string serviceName = m_service->name();
LOG_INFO("Entering ParserService [", serviceName, "] thread");
setIdle( false );
while ( m_stopParser == false )
{
std::shared_ptr<Task> task;
{
std::unique_lock<compat::Mutex> lock( m_lock );
if ( m_tasks.empty() == true || m_paused == true )
{
LOG_DEBUG( "Halting ParserService [", serviceName, "] mainloop" );
setIdle( true );
m_idleCond.notify_all();
m_cond.wait( lock, [this]() {
return ( m_tasks.empty() == false && m_paused == false )
|| m_stopParser == true;
});
LOG_DEBUG( "Resuming ParserService [", serviceName, "] mainloop" );
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
break;
setIdle( false );
}
// Otherwise it's safe to assume we have at least one element.
LOG_DEBUG('[', serviceName, "] has ", m_tasks.size(), " tasks remaining" );
task = std::move( m_tasks.front() );
m_tasks.pop();
}
// Special case to restore uncompleted tasks from a parser thread
if ( task == nullptr )
{
restoreTasks();
continue;
}
if ( task->isStepCompleted( m_service->targetedStep() ) == true )
{
LOG_DEBUG( "Skipping completed task [", serviceName, "] on ", task->item().mrl() );
m_parserCb->done( std::move( task ), Status::Success );
continue;
}
Status status;
try
{
LOG_DEBUG( "Executing ", serviceName, " task on ", task->item().mrl() );
auto chrono = std::chrono::steady_clock::now();
auto file = std::static_pointer_cast<File>( task->item().file() );
auto media = std::static_pointer_cast<Media>( task->item().media() );
if ( file != nullptr && file->isRemovable() )
{
auto folder = Folder::fetch( m_ml, file->folderId() );
if ( folder->isPresent() == false )
{
LOG_DEBUG( "Postponing parsing of ", file->rawMrl(),
" until the device containing it gets mounted back" );
m_parserCb->done( std::move( task ), Status::TemporaryUnavailable );
continue;
}
}
task->startParserStep();
status = m_service->run( task->item() );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG( "Done executing ", serviceName, " task on ", task->item().mrl(), " in ",
std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(),
"ms. Result: ",
static_cast<std::underlying_type_t<parser::Status>>( status ) );
}
catch ( const fs::DeviceRemovedException& )
{
LOG_ERROR( "Parsing of ", task->item().mrl(), " was interrupted "
"due to its containing device being unmounted" );
status = Status::TemporaryUnavailable;
}
catch ( const std::exception& ex )
{
LOG_ERROR( "Caught an exception during ", task->item().mrl(), " [", serviceName, "] parsing: ", ex.what() );
status = Status::Fatal;
}
if ( handleServiceResult( *task, status ) == false )
status = Status::Fatal;
m_parserCb->done( std::move( task ), status );
}
LOG_INFO("Exiting ParserService [", serviceName, "] thread");
setIdle( true );
}
void Worker::setIdle(bool isIdle)
{
// Calling the idleChanged callback will trigger a call to isIdle, so set the value before
// invoking it, otherwise we have an incoherent state.
if ( m_idle != isIdle )
{
m_idle = isIdle;
m_parserCb->onIdleChanged( isIdle );
}
}
bool Worker::handleServiceResult( Task& task, Status status )
{
if ( status == Status::Success )
{
task.markStepCompleted( m_service->targetedStep() );
// We don't want to save the extraction step in database, as restarting a
// task with extraction completed but analysis uncompleted wouldn't run
// the extraction again, causing the analysis to run with no info.
if ( m_service->targetedStep() != Step::MetadataExtraction )
return task.saveParserStep();
// We don't want to reset the entire retry count, as we would be stuck in
// a "loop" in case the metadata analysis fails (we'd always reset the retry
// count to zero, then fail, then run the extraction again, reset the retry,
// fail the analysis, and so on.
// We can't not increment the retry count for metadata extraction, since
// in case a file makes (lib)VLC crash, we would always try again, and
// therefor we would keep on crashing.
// However we don't want to just increment the retry count, since it
// would reach the maximum value too quickly (extraction would set retry
// count to 1, analysis to 2, and in case of failure, next run would set
// it over 3, while we only tried 2 times. Instead we just decrement it
// when the extraction step succeeds
return task.decrementRetryCount();
}
else if ( status == Status::Completed )
{
task.markStepCompleted( Step::Completed );
return task.saveParserStep();
}
else if ( status == Status::Discarded )
{
return Task::destroy( m_ml, task.id() );
}
return true;
}
void Worker::restoreTasks()
{
auto tasks = Task::fetchUncompleted( m_ml );
if ( tasks.size() > 0 )
LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" );
else
LOG_DEBUG( "No task to resume." );
for ( auto& t : tasks )
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
}
if ( t->restoreLinkedEntities() == false )
continue;
m_parserCb->parse( std::move( t ) );
}
}
}
}
<commit_msg>parser: Fix unlikely race condition during start/stop<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "ParserWorker.h"
#include "Parser.h"
#include "Media.h"
#include "Folder.h"
namespace medialibrary
{
namespace parser
{
Worker::Worker()
: m_parserCb( nullptr )
, m_stopParser( false )
, m_paused( false )
, m_idle( true )
{
}
void Worker::start()
{
// Ensure we don't start multiple times.
assert( m_threads.size() == 0 );
for ( auto i = 0u; i < m_service->nbThreads(); ++i )
m_threads.emplace_back( &Worker::mainloop, this );
}
void Worker::pause()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = true;
}
void Worker::resume()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = false;
m_cond.notify_all();
}
void Worker::signalStop()
{
for ( auto& t : m_threads )
{
if ( t.joinable() )
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_cond.notify_all();
m_stopParser = true;
}
}
}
void Worker::stop()
{
for ( auto& t : m_threads )
{
if ( t.joinable() )
t.join();
}
}
void Worker::parse( std::shared_ptr<Task> t )
{
// Avoid flickering from idle/not idle when not many tasks are running.
// The thread calling parse for the next parser step might not have
// something left to do and would turn idle, potentially causing all
// services to be idle for a very short time, until this parser
// thread awakes/starts, causing the global parser idle state to be
// restored back to false.
// Since we are queuing a task, we already know that this thread is
// not idle
setIdle( false );
// Even if no threads appear to be started, we need to lock this in case
// we're currently doing a stop/start
{
std::lock_guard<compat::Mutex> lock( m_lock );
if ( m_threads.size() == 0 )
{
m_tasks.push( std::move( t ) );
start();
return;
}
m_tasks.push( std::move( t ) );
}
m_cond.notify_all();
}
bool Worker::initialize( MediaLibrary* ml, IParserCb* parserCb,
std::shared_ptr<IParserService> service )
{
m_ml = ml;
m_service = std::move( service );
m_parserCb = parserCb;
// Run the service specific initializer
return m_service->initialize( ml );
}
bool Worker::isIdle() const
{
return m_idle;
}
void Worker::flush()
{
std::unique_lock<compat::Mutex> lock( m_lock );
assert( m_paused == true || m_threads.empty() == true );
m_idleCond.wait( lock, [this]() {
return m_idle == true;
});
while ( m_tasks.empty() == false )
m_tasks.pop();
m_service->onFlushing();
}
void Worker::restart()
{
m_service->onRestarted();
}
void Worker::mainloop()
{
// It would be unsafe to call name() at the end of this function, since
// we might stop the thread during ParserService destruction. This implies
// that the underlying service has been deleted already.
std::string serviceName = m_service->name();
LOG_INFO("Entering ParserService [", serviceName, "] thread");
setIdle( false );
while ( m_stopParser == false )
{
std::shared_ptr<Task> task;
{
std::unique_lock<compat::Mutex> lock( m_lock );
if ( m_tasks.empty() == true || m_paused == true )
{
LOG_DEBUG( "Halting ParserService [", serviceName, "] mainloop" );
setIdle( true );
m_idleCond.notify_all();
m_cond.wait( lock, [this]() {
return ( m_tasks.empty() == false && m_paused == false )
|| m_stopParser == true;
});
LOG_DEBUG( "Resuming ParserService [", serviceName, "] mainloop" );
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
break;
setIdle( false );
}
// Otherwise it's safe to assume we have at least one element.
LOG_DEBUG('[', serviceName, "] has ", m_tasks.size(), " tasks remaining" );
task = std::move( m_tasks.front() );
m_tasks.pop();
}
// Special case to restore uncompleted tasks from a parser thread
if ( task == nullptr )
{
restoreTasks();
continue;
}
if ( task->isStepCompleted( m_service->targetedStep() ) == true )
{
LOG_DEBUG( "Skipping completed task [", serviceName, "] on ", task->item().mrl() );
m_parserCb->done( std::move( task ), Status::Success );
continue;
}
Status status;
try
{
LOG_DEBUG( "Executing ", serviceName, " task on ", task->item().mrl() );
auto chrono = std::chrono::steady_clock::now();
auto file = std::static_pointer_cast<File>( task->item().file() );
auto media = std::static_pointer_cast<Media>( task->item().media() );
if ( file != nullptr && file->isRemovable() )
{
auto folder = Folder::fetch( m_ml, file->folderId() );
if ( folder->isPresent() == false )
{
LOG_DEBUG( "Postponing parsing of ", file->rawMrl(),
" until the device containing it gets mounted back" );
m_parserCb->done( std::move( task ), Status::TemporaryUnavailable );
continue;
}
}
task->startParserStep();
status = m_service->run( task->item() );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG( "Done executing ", serviceName, " task on ", task->item().mrl(), " in ",
std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(),
"ms. Result: ",
static_cast<std::underlying_type_t<parser::Status>>( status ) );
}
catch ( const fs::DeviceRemovedException& )
{
LOG_ERROR( "Parsing of ", task->item().mrl(), " was interrupted "
"due to its containing device being unmounted" );
status = Status::TemporaryUnavailable;
}
catch ( const std::exception& ex )
{
LOG_ERROR( "Caught an exception during ", task->item().mrl(), " [", serviceName, "] parsing: ", ex.what() );
status = Status::Fatal;
}
if ( handleServiceResult( *task, status ) == false )
status = Status::Fatal;
m_parserCb->done( std::move( task ), status );
}
LOG_INFO("Exiting ParserService [", serviceName, "] thread");
setIdle( true );
}
void Worker::setIdle(bool isIdle)
{
// Calling the idleChanged callback will trigger a call to isIdle, so set the value before
// invoking it, otherwise we have an incoherent state.
if ( m_idle != isIdle )
{
m_idle = isIdle;
m_parserCb->onIdleChanged( isIdle );
}
}
bool Worker::handleServiceResult( Task& task, Status status )
{
if ( status == Status::Success )
{
task.markStepCompleted( m_service->targetedStep() );
// We don't want to save the extraction step in database, as restarting a
// task with extraction completed but analysis uncompleted wouldn't run
// the extraction again, causing the analysis to run with no info.
if ( m_service->targetedStep() != Step::MetadataExtraction )
return task.saveParserStep();
// We don't want to reset the entire retry count, as we would be stuck in
// a "loop" in case the metadata analysis fails (we'd always reset the retry
// count to zero, then fail, then run the extraction again, reset the retry,
// fail the analysis, and so on.
// We can't not increment the retry count for metadata extraction, since
// in case a file makes (lib)VLC crash, we would always try again, and
// therefor we would keep on crashing.
// However we don't want to just increment the retry count, since it
// would reach the maximum value too quickly (extraction would set retry
// count to 1, analysis to 2, and in case of failure, next run would set
// it over 3, while we only tried 2 times. Instead we just decrement it
// when the extraction step succeeds
return task.decrementRetryCount();
}
else if ( status == Status::Completed )
{
task.markStepCompleted( Step::Completed );
return task.saveParserStep();
}
else if ( status == Status::Discarded )
{
return Task::destroy( m_ml, task.id() );
}
return true;
}
void Worker::restoreTasks()
{
auto tasks = Task::fetchUncompleted( m_ml );
if ( tasks.size() > 0 )
LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" );
else
LOG_DEBUG( "No task to resume." );
for ( auto& t : tasks )
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
}
if ( t->restoreLinkedEntities() == false )
continue;
m_parserCb->parse( std::move( t ) );
}
}
}
}
<|endoftext|> |
<commit_before>#ifndef VEXCL_BACKEND_CUDA_CONTEXT_HPP
#define VEXCL_BACKEND_CUDA_CONTEXT_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <[email protected]>
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.
*/
/**
* \file vexcl/backend/cuda/context.hpp
* \author Denis Demidov <[email protected]>
* \brief CUDA device enumeration and context initialization.
*/
#include <vector>
#include <tuple>
#include <iostream>
#include <memory>
#include <cuda.h>
namespace vex {
namespace backend {
/// The CUDA backend.
namespace cuda {
inline CUresult do_init() {
static const CUresult rc = cuInit(0);
return rc;
}
namespace detail {
template <class Handle>
struct deleter_impl;
template <>
struct deleter_impl<CUcontext> {
static void dispose(CUcontext context) {
cuda_check( cuCtxSetCurrent(context) );
cuda_check( cuCtxSynchronize() );
cuda_check( cuCtxDestroy(context) );
}
};
template <>
struct deleter_impl<CUmodule> {
static void dispose(CUmodule module) {
cuda_check( cuModuleUnload(module) );
}
};
template <>
struct deleter_impl<CUstream> {
static void dispose(CUstream stream) {
cuda_check( cuStreamDestroy(stream) );
}
};
// Knows how to dispose of various CUDA handles.
struct deleter {
deleter(CUcontext ctx) : ctx(ctx) {}
template <class Handle>
void operator()(Handle handle) const {
if (ctx) cuda_check( cuCtxSetCurrent(ctx) );
deleter_impl<Handle>::dispose(handle);
}
CUcontext ctx;
};
}
/// Wrapper around CUdevice.
class device {
public:
/// Empty constructor.
device() {}
/// Constructor.
device(CUdevice d) : d(d) {}
/// Returns raw CUdevice handle.
CUdevice raw() const { return d; }
/// Returns raw CUdevice handle.
operator CUdevice() const { return d; }
/// Returns name of the device.
std::string name() const {
char name[256];
cuda_check( cuDeviceGetName(name, 256, d) );
return name;
}
/// Returns device compute capability as a tuple of major and minor version numbers.
std::tuple<int, int> compute_capability() const {
int major, minor;
cuda_check( cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, d) );
cuda_check( cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, d) );
return std::make_tuple(major, minor);
}
/// Returns of multiprocessors on the device.
size_t multiprocessor_count() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, d) );
return n;
}
/// Returns maximum number of threads per block.
size_t max_threads_per_block() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, d) );
return n;
}
/// Returns maximum amount of shared memory available to a thread block in bytes.
size_t max_shared_memory_per_block() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, d) );
return n;
}
size_t warp_size() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_WARP_SIZE, d) );
return n;
}
private:
CUdevice d;
};
/// Wrapper around CUcontext.
class context {
public:
/// Empty constructor.
context() {}
/// Creates a CUDA context.
context(device dev, unsigned flags = 0)
: c( create(dev, flags), detail::deleter(0) )
{
cuda_check( do_init() );
}
/// Returns raw CUcontext handle.
CUcontext raw() const {
return c.get();
}
/// Returns raw CUcontext handle.
operator CUcontext() const {
return c.get();
}
/// Binds the context to the calling CPU thread.
void set_current() const {
cuda_check( cuCtxSetCurrent( c.get() ) );
}
private:
std::shared_ptr<std::remove_pointer<CUcontext>::type> c;
static CUcontext create(device dev, unsigned flags) {
CUcontext h = 0;
cuda_check( cuCtxCreate(&h, flags, dev.raw()) );
return h;
}
};
/// Command queue creation flags.
/**
* typedef'ed to cl_command_queue_properties in the OpenCL backend and to
* unsigned in the CUDA backend. See OpenCL/CUDA documentation for the possible
* values.
*/
typedef unsigned command_queue_properties;
/// Command queue.
/** With the CUDA backend, this is a wrapper around CUstream. */
class command_queue {
public:
/// Empty constructor.
command_queue() {}
/// Create command queue for the given context and device.
command_queue(const vex::backend::context &ctx, vex::backend::device dev, unsigned flags)
: ctx(ctx), dev(dev), s( create(ctx, flags), detail::deleter(ctx.raw()) ), f(flags)
{ }
/// Blocks until all previously queued commands in command_queue are issued to the associated device and have completed.
void finish() const {
ctx.set_current();
cuda_check( cuStreamSynchronize( s.get() ) );
}
/// Returns the context associated with the command queue.
vex::backend::context context() const {
return ctx;
}
/// Returns the device associated with the command queue.
vex::backend::device device() const {
return dev;
}
/// Returns command_queue_properties specified at creation.
unsigned flags() const {
return f;
}
/// Returns raw CUstream handle for the command queue.
CUstream raw() const {
return s.get();
}
/// Returns raw CUstream handle for the command queue.
operator CUstream() const {
return s.get();
}
private:
vex::backend::context ctx;
vex::backend::device dev;
std::shared_ptr<std::remove_pointer<CUstream>::type> s;
unsigned f;
static CUstream create(const vex::backend::context &ctx, unsigned flags = 0) {
ctx.set_current();
CUstream s;
cuda_check( cuStreamCreate(&s, flags) );
return s;
}
};
/// CUmodule wrapper.
struct program {
public:
program() {}
program(vex::backend::context c, CUmodule m)
: c(c), m(m, detail::deleter(c.raw()))
{}
CUmodule raw() const {
return m.get();
}
operator CUmodule() const {
return m.get();
}
private:
vex::backend::context c;
std::shared_ptr<std::remove_pointer<CUmodule>::type> m;
};
/// Binds the specified CUDA context to the calling CPU thread.
inline void select_context(const command_queue &q) {
q.context().set_current();
}
/// Raw device handle.
typedef CUdevice device_id;
/// Returns device associated with the given queue.
inline device get_device(const command_queue &q) {
return q.device();
}
/// Returns id of the device associated with the given queue.
inline device_id get_device_id(const command_queue &q) {
return q.device().raw();
}
/// Launch grid size.
struct ndrange {
size_t x, y, z;
ndrange(size_t x = 1, size_t y = 1, size_t z = 1)
: x(x), y(y), z(z) {}
};
typedef CUcontext context_id;
/// Returns raw context id for the given queue.
inline context_id get_context_id(const command_queue &q) {
return q.context().raw();
}
/// Returns context for the given queue.
inline context get_context(const command_queue &q) {
return q.context();
}
/// Compares contexts by raw ids.
struct compare_contexts {
bool operator()(const context &a, const context &b) const {
return a.raw() < b.raw();
}
};
/// Compares queues by raw ids.
struct compare_queues {
bool operator()(const command_queue &a, const command_queue &b) const {
return a.raw() < b.raw();
}
};
/// Create command queue on the same context and device as the given one.
inline command_queue duplicate_queue(const command_queue &q) {
return command_queue(q.context(), q.device(), q.flags());
}
/// Checks if the compute device is CPU.
/**
* Always returns false with the CUDA backend.
*/
inline bool is_cpu(const command_queue&) {
return false;
}
/// Select devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of devices satisfying the provided filter.
*/
template<class DevFilter>
std::vector<device> device_list(DevFilter&& filter) {
cuda_check( do_init() );
std::vector<device> device;
int ndev;
cuda_check( cuDeviceGetCount(&ndev) );
for(int d = 0; d < ndev; ++d) {
try {
CUdevice dev;
cuda_check( cuDeviceGet(&dev, d) );
if (!filter(dev)) continue;
device.push_back(dev);
} catch(const error&) { }
}
return device;
}
/// Create command queues on devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \param properties Command queue properties.
*
* \returns list of queues accociated with selected devices.
* \see device_list
*/
template<class DevFilter>
std::pair< std::vector<context>, std::vector<command_queue> >
queue_list(DevFilter &&filter, unsigned queue_flags = 0)
{
cuda_check( do_init() );
std::vector<context> ctx;
std::vector<command_queue> queue;
int ndev;
cuda_check( cuDeviceGetCount(&ndev) );
for(int d = 0; d < ndev; ++d) {
try {
CUdevice dev;
cuda_check( cuDeviceGet(&dev, d) );
if (!filter(dev)) continue;
context c(dev);
command_queue q(c, dev, queue_flags);
ctx.push_back(c);
queue.push_back(q);
} catch(const error&) { }
}
return std::make_pair(ctx, queue);
}
} // namespace cuda
} // namespace backend
} // namespace vex
namespace std {
/// Output device name to stream.
inline std::ostream& operator<<(std::ostream &os, const vex::backend::cuda::device &d)
{
return os << d.name();
}
/// Output device name to stream.
inline std::ostream& operator<<(std::ostream &os, const vex::backend::cuda::command_queue &q)
{
return os << q.device();
}
} // namespace std
#endif
<commit_msg>:retab!<commit_after>#ifndef VEXCL_BACKEND_CUDA_CONTEXT_HPP
#define VEXCL_BACKEND_CUDA_CONTEXT_HPP
/*
The MIT License
Copyright (c) 2012-2018 Denis Demidov <[email protected]>
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.
*/
/**
* \file vexcl/backend/cuda/context.hpp
* \author Denis Demidov <[email protected]>
* \brief CUDA device enumeration and context initialization.
*/
#include <vector>
#include <tuple>
#include <iostream>
#include <memory>
#include <cuda.h>
namespace vex {
namespace backend {
/// The CUDA backend.
namespace cuda {
inline CUresult do_init() {
static const CUresult rc = cuInit(0);
return rc;
}
namespace detail {
template <class Handle>
struct deleter_impl;
template <>
struct deleter_impl<CUcontext> {
static void dispose(CUcontext context) {
cuda_check( cuCtxSetCurrent(context) );
cuda_check( cuCtxSynchronize() );
cuda_check( cuCtxDestroy(context) );
}
};
template <>
struct deleter_impl<CUmodule> {
static void dispose(CUmodule module) {
cuda_check( cuModuleUnload(module) );
}
};
template <>
struct deleter_impl<CUstream> {
static void dispose(CUstream stream) {
cuda_check( cuStreamDestroy(stream) );
}
};
// Knows how to dispose of various CUDA handles.
struct deleter {
deleter(CUcontext ctx) : ctx(ctx) {}
template <class Handle>
void operator()(Handle handle) const {
if (ctx) cuda_check( cuCtxSetCurrent(ctx) );
deleter_impl<Handle>::dispose(handle);
}
CUcontext ctx;
};
}
/// Wrapper around CUdevice.
class device {
public:
/// Empty constructor.
device() {}
/// Constructor.
device(CUdevice d) : d(d) {}
/// Returns raw CUdevice handle.
CUdevice raw() const { return d; }
/// Returns raw CUdevice handle.
operator CUdevice() const { return d; }
/// Returns name of the device.
std::string name() const {
char name[256];
cuda_check( cuDeviceGetName(name, 256, d) );
return name;
}
/// Returns device compute capability as a tuple of major and minor version numbers.
std::tuple<int, int> compute_capability() const {
int major, minor;
cuda_check( cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, d) );
cuda_check( cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, d) );
return std::make_tuple(major, minor);
}
/// Returns of multiprocessors on the device.
size_t multiprocessor_count() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, d) );
return n;
}
/// Returns maximum number of threads per block.
size_t max_threads_per_block() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, d) );
return n;
}
/// Returns maximum amount of shared memory available to a thread block in bytes.
size_t max_shared_memory_per_block() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, d) );
return n;
}
size_t warp_size() const {
int n;
cuda_check( cuDeviceGetAttribute(&n, CU_DEVICE_ATTRIBUTE_WARP_SIZE, d) );
return n;
}
private:
CUdevice d;
};
/// Wrapper around CUcontext.
class context {
public:
/// Empty constructor.
context() {}
/// Creates a CUDA context.
context(device dev, unsigned flags = 0)
: c( create(dev, flags), detail::deleter(0) )
{
cuda_check( do_init() );
}
/// Returns raw CUcontext handle.
CUcontext raw() const {
return c.get();
}
/// Returns raw CUcontext handle.
operator CUcontext() const {
return c.get();
}
/// Binds the context to the calling CPU thread.
void set_current() const {
cuda_check( cuCtxSetCurrent( c.get() ) );
}
private:
std::shared_ptr<std::remove_pointer<CUcontext>::type> c;
static CUcontext create(device dev, unsigned flags) {
CUcontext h = 0;
cuda_check( cuCtxCreate(&h, flags, dev.raw()) );
return h;
}
};
/// Command queue creation flags.
/**
* typedef'ed to cl_command_queue_properties in the OpenCL backend and to
* unsigned in the CUDA backend. See OpenCL/CUDA documentation for the possible
* values.
*/
typedef unsigned command_queue_properties;
/// Command queue.
/** With the CUDA backend, this is a wrapper around CUstream. */
class command_queue {
public:
/// Empty constructor.
command_queue() {}
/// Create command queue for the given context and device.
command_queue(const vex::backend::context &ctx, vex::backend::device dev, unsigned flags)
: ctx(ctx), dev(dev), s( create(ctx, flags), detail::deleter(ctx.raw()) ), f(flags)
{ }
/// Blocks until all previously queued commands in command_queue are issued to the associated device and have completed.
void finish() const {
ctx.set_current();
cuda_check( cuStreamSynchronize( s.get() ) );
}
/// Returns the context associated with the command queue.
vex::backend::context context() const {
return ctx;
}
/// Returns the device associated with the command queue.
vex::backend::device device() const {
return dev;
}
/// Returns command_queue_properties specified at creation.
unsigned flags() const {
return f;
}
/// Returns raw CUstream handle for the command queue.
CUstream raw() const {
return s.get();
}
/// Returns raw CUstream handle for the command queue.
operator CUstream() const {
return s.get();
}
private:
vex::backend::context ctx;
vex::backend::device dev;
std::shared_ptr<std::remove_pointer<CUstream>::type> s;
unsigned f;
static CUstream create(const vex::backend::context &ctx, unsigned flags = 0) {
ctx.set_current();
CUstream s;
cuda_check( cuStreamCreate(&s, flags) );
return s;
}
};
/// CUmodule wrapper.
struct program {
public:
program() {}
program(vex::backend::context c, CUmodule m)
: c(c), m(m, detail::deleter(c.raw()))
{}
CUmodule raw() const {
return m.get();
}
operator CUmodule() const {
return m.get();
}
private:
vex::backend::context c;
std::shared_ptr<std::remove_pointer<CUmodule>::type> m;
};
/// Binds the specified CUDA context to the calling CPU thread.
inline void select_context(const command_queue &q) {
q.context().set_current();
}
/// Raw device handle.
typedef CUdevice device_id;
/// Returns device associated with the given queue.
inline device get_device(const command_queue &q) {
return q.device();
}
/// Returns id of the device associated with the given queue.
inline device_id get_device_id(const command_queue &q) {
return q.device().raw();
}
/// Launch grid size.
struct ndrange {
size_t x, y, z;
ndrange(size_t x = 1, size_t y = 1, size_t z = 1)
: x(x), y(y), z(z) {}
};
typedef CUcontext context_id;
/// Returns raw context id for the given queue.
inline context_id get_context_id(const command_queue &q) {
return q.context().raw();
}
/// Returns context for the given queue.
inline context get_context(const command_queue &q) {
return q.context();
}
/// Compares contexts by raw ids.
struct compare_contexts {
bool operator()(const context &a, const context &b) const {
return a.raw() < b.raw();
}
};
/// Compares queues by raw ids.
struct compare_queues {
bool operator()(const command_queue &a, const command_queue &b) const {
return a.raw() < b.raw();
}
};
/// Create command queue on the same context and device as the given one.
inline command_queue duplicate_queue(const command_queue &q) {
return command_queue(q.context(), q.device(), q.flags());
}
/// Checks if the compute device is CPU.
/**
* Always returns false with the CUDA backend.
*/
inline bool is_cpu(const command_queue&) {
return false;
}
/// Select devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \returns list of devices satisfying the provided filter.
*/
template<class DevFilter>
std::vector<device> device_list(DevFilter&& filter) {
cuda_check( do_init() );
std::vector<device> device;
int ndev;
cuda_check( cuDeviceGetCount(&ndev) );
for(int d = 0; d < ndev; ++d) {
try {
CUdevice dev;
cuda_check( cuDeviceGet(&dev, d) );
if (!filter(dev)) continue;
device.push_back(dev);
} catch(const error&) { }
}
return device;
}
/// Create command queues on devices by given criteria.
/**
* \param filter Device filter functor. Functors may be combined with logical
* operators.
* \param properties Command queue properties.
*
* \returns list of queues accociated with selected devices.
* \see device_list
*/
template<class DevFilter>
std::pair< std::vector<context>, std::vector<command_queue> >
queue_list(DevFilter &&filter, unsigned queue_flags = 0)
{
cuda_check( do_init() );
std::vector<context> ctx;
std::vector<command_queue> queue;
int ndev;
cuda_check( cuDeviceGetCount(&ndev) );
for(int d = 0; d < ndev; ++d) {
try {
CUdevice dev;
cuda_check( cuDeviceGet(&dev, d) );
if (!filter(dev)) continue;
context c(dev);
command_queue q(c, dev, queue_flags);
ctx.push_back(c);
queue.push_back(q);
} catch(const error&) { }
}
return std::make_pair(ctx, queue);
}
} // namespace cuda
} // namespace backend
} // namespace vex
namespace std {
/// Output device name to stream.
inline std::ostream& operator<<(std::ostream &os, const vex::backend::cuda::device &d)
{
return os << d.name();
}
/// Output device name to stream.
inline std::ostream& operator<<(std::ostream &os, const vex::backend::cuda::command_queue &q)
{
return os << q.device();
}
} // namespace std
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/touchui/touch_factory.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XIproto.h>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "ui/base/x/x11_util.h"
namespace {
// The X cursor is hidden if it is idle for kCursorIdleSeconds seconds.
int kCursorIdleSeconds = 5;
// Given the TouchParam, return the correspoding valuator index using
// the X device information through Atom name matching.
char FindTPValuator(Display* display,
XIDeviceInfo* info,
views::TouchFactory::TouchParam touch_param) {
// Lookup table for mapping TouchParam to Atom string used in X.
// A full set of Atom strings can be found at xserver-properties.h.
// For Slot ID, See this chromeos revision: http://git.chromium.org/gitweb/?
// p=chromiumos/overlays/chromiumos-overlay.git;
// a=commit;h=9164d0a75e48c4867e4ef4ab51f743ae231c059a
static struct {
views::TouchFactory::TouchParam tp;
const char* atom;
} kTouchParamAtom[] = {
{ views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" },
{ views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" },
{ views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" },
{ views::TouchFactory::TP_SLOT_ID, "Abs MT Slot ID" },
{ views::TouchFactory::TP_TRACKING_ID, "Abs MT Tracking ID" },
{ views::TouchFactory::TP_LAST_ENTRY, NULL },
};
const char* atom_tp = NULL;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) {
if (touch_param == kTouchParamAtom[i].tp) {
atom_tp = kTouchParamAtom[i].atom;
break;
}
}
if (!atom_tp)
return -1;
for (int i = 0; i < info->num_classes; i++) {
if (info->classes[i]->type != XIValuatorClass)
continue;
XIValuatorClassInfo* v =
reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]);
const char* atom = XGetAtomName(display, v->label);
if (atom && strcmp(atom, atom_tp) == 0)
return v->number;
}
return -1;
}
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
views::TouchFactory* factory = static_cast<views::TouchFactory*>(data);
if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG)
return true;
factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
guint realize_signal_id = 0;
guint realize_hook_id = 0;
void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) {
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET,
&realize_signal_id, NULL, FALSE);
realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0,
GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL);
g_type_class_unref(klass);
}
void RemoveGtkWidgetRealizeNotifier() {
if (realize_signal_id != 0)
g_signal_remove_emission_hook(realize_signal_id, realize_hook_id);
realize_signal_id = 0;
realize_hook_id = 0;
}
} // namespace
namespace views {
// static
TouchFactory* TouchFactory::GetInstance() {
return Singleton<TouchFactory>::get();
}
TouchFactory::TouchFactory()
: is_cursor_visible_(true),
cursor_timer_(),
pointer_device_lookup_(),
touch_device_list_(),
slots_used_() {
char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
XColor black;
black.red = black.green = black.blue = 0;
Display* display = ui::GetXDisplay();
Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(),
nodata, 8, 8);
invisible_cursor_ = XCreatePixmapCursor(display, blank, blank,
&black, &black, 0, 0);
arrow_cursor_ = XCreateFontCursor(display, XC_arrow);
SetCursorVisible(false, false);
UpdateDeviceList(display);
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Make sure the list of devices is kept up-to-date by listening for
// XI_HierarchyChanged event on the root window.
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_HierarchyChanged);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1);
}
TouchFactory::~TouchFactory() {
SetCursorVisible(true, false);
Display* display = ui::GetXDisplay();
XFreeCursor(display, invisible_cursor_);
XFreeCursor(display, arrow_cursor_);
RemoveGtkWidgetRealizeNotifier();
}
void TouchFactory::UpdateDeviceList(Display* display) {
// Detect touch devices.
// NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
// not provide enough information to detect a touch device. As a result, the
// old version of query function (XListInputDevices) is used instead.
// If XInput2 is not supported, this will return null (with count of -1) so
// we assume there cannot be any touch devices.
int count = 0;
touch_device_lookup_.reset();
touch_device_list_.clear();
XDeviceInfo* devlist = XListInputDevices(display, &count);
for (int i = 0; i < count; i++) {
if (devlist[i].type) {
const char* devtype = XGetAtomName(display, devlist[i].type);
if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) {
touch_device_lookup_[devlist[i].id] = true;
touch_device_list_.push_back(devlist[i].id);
}
}
}
if (devlist)
XFreeDeviceList(devlist);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of pointer devices we care about.
// It should not be necessary to select for slave devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a
// 'mouse event' or a 'touch event'.
// However, on some desktops, some events from a master pointer are
// not delivered to the client. So we select for slave devices instead.
// If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
// is possible), then the device is detected as a floating device, and a
// floating device is not connected to a master device. So it is necessary to
// also select on the floating devices.
pointer_device_lookup_.reset();
XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XIFloatingSlave || devinfo->use == XISlavePointer) {
pointer_device_lookup_[devinfo->deviceid] = true;
}
}
XIFreeDeviceInfo(devices);
SetupValuator();
}
bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
DCHECK_EQ(GenericEvent, xev->type);
XGenericEventCookie* cookie = &xev->xcookie;
if (cookie->evtype != XI_ButtonPress &&
cookie->evtype != XI_ButtonRelease &&
cookie->evtype != XI_Motion)
return true;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
return pointer_device_lookup_[xiev->sourceid];
}
void TouchFactory::SetupXI2ForXWindow(Window window) {
// Setup mask for mouse events. It is possible that a device is loaded/plugged
// in after we have setup XInput2 on a window. In such cases, we need to
// either resetup XInput2 for the window, so that we get events from the new
// device, or we need to listen to events from all devices, and then filter
// the events from uninteresting devices. We do the latter because that's
// simpler.
Display* display = ui::GetXDisplay();
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, window, &evmask, 1);
XFlush(display);
}
void TouchFactory::SetTouchDeviceList(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_.push_back(*iter);
}
SetupValuator();
}
bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
return deviceid < touch_device_lookup_.size() ?
touch_device_lookup_[deviceid] : false;
}
bool TouchFactory::IsSlotUsed(int slot) const {
CHECK_LT(slot, kMaxTouchPoints);
return slots_used_[slot];
}
void TouchFactory::SetSlotUsed(int slot, bool used) {
CHECK_LT(slot, kMaxTouchPoints);
slots_used_[slot] = used;
}
bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) {
if (touch_device_list_.empty())
return true;
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
bool success = true;
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
evmask.deviceid = *iter;
Status status = XIGrabDevice(display, *iter, window, CurrentTime, None,
GrabModeAsync, GrabModeAsync, False, &evmask);
success = success && status == GrabSuccess;
}
return success;
}
bool TouchFactory::UngrabTouchDevices(Display* display) {
bool success = true;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
Status status = XIUngrabDevice(display, *iter, CurrentTime);
success = success && status == GrabSuccess;
}
return success;
}
void TouchFactory::SetCursorVisible(bool show, bool start_timer) {
// The cursor is going to be shown. Reset the timer for hiding it.
if (show && start_timer) {
cursor_timer_.Stop();
cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds),
this, &TouchFactory::HideCursorForInactivity);
} else {
cursor_timer_.Stop();
}
if (show == is_cursor_visible_)
return;
is_cursor_visible_ = show;
Display* display = ui::GetXDisplay();
Window window = DefaultRootWindow(display);
if (is_cursor_visible_) {
XDefineCursor(display, window, arrow_cursor_);
} else {
XDefineCursor(display, window, invisible_cursor_);
}
}
void TouchFactory::SetupValuator() {
memset(valuator_lookup_, -1, sizeof(valuator_lookup_));
Display* display = ui::GetXDisplay();
int ndevice;
XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice);
for (int i = 0; i < ndevice; i++) {
XIDeviceInfo* info = info_list + i;
if (!IsTouchDevice(info->deviceid))
continue;
for (int i = 0; i < TP_LAST_ENTRY; i++) {
TouchParam tp = static_cast<TouchParam>(i);
valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp);
}
}
if (info_list)
XIFreeDeviceInfo(info_list);
}
bool TouchFactory::ExtractTouchParam(const XEvent& xev,
TouchParam tp,
float* value) {
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data);
if (xiev->sourceid >= kMaxDeviceNum)
return false;
int v = valuator_lookup_[xiev->sourceid][tp];
if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) {
*value = xiev->valuators.values[v];
return true;
}
return false;
}
} // namespace views
<commit_msg>Fix a crash when list of devices is NULL (e.g. over VNC/NX sessions).<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 "views/touchui/touch_factory.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XIproto.h>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "ui/base/x/x11_util.h"
namespace {
// The X cursor is hidden if it is idle for kCursorIdleSeconds seconds.
int kCursorIdleSeconds = 5;
// Given the TouchParam, return the correspoding valuator index using
// the X device information through Atom name matching.
char FindTPValuator(Display* display,
XIDeviceInfo* info,
views::TouchFactory::TouchParam touch_param) {
// Lookup table for mapping TouchParam to Atom string used in X.
// A full set of Atom strings can be found at xserver-properties.h.
// For Slot ID, See this chromeos revision: http://git.chromium.org/gitweb/?
// p=chromiumos/overlays/chromiumos-overlay.git;
// a=commit;h=9164d0a75e48c4867e4ef4ab51f743ae231c059a
static struct {
views::TouchFactory::TouchParam tp;
const char* atom;
} kTouchParamAtom[] = {
{ views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" },
{ views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" },
{ views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" },
{ views::TouchFactory::TP_SLOT_ID, "Abs MT Slot ID" },
{ views::TouchFactory::TP_TRACKING_ID, "Abs MT Tracking ID" },
{ views::TouchFactory::TP_LAST_ENTRY, NULL },
};
const char* atom_tp = NULL;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) {
if (touch_param == kTouchParamAtom[i].tp) {
atom_tp = kTouchParamAtom[i].atom;
break;
}
}
if (!atom_tp)
return -1;
for (int i = 0; i < info->num_classes; i++) {
if (info->classes[i]->type != XIValuatorClass)
continue;
XIValuatorClassInfo* v =
reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]);
const char* atom = XGetAtomName(display, v->label);
if (atom && strcmp(atom, atom_tp) == 0)
return v->number;
}
return -1;
}
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
views::TouchFactory* factory = static_cast<views::TouchFactory*>(data);
if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG)
return true;
factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
guint realize_signal_id = 0;
guint realize_hook_id = 0;
void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) {
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET,
&realize_signal_id, NULL, FALSE);
realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0,
GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL);
g_type_class_unref(klass);
}
void RemoveGtkWidgetRealizeNotifier() {
if (realize_signal_id != 0)
g_signal_remove_emission_hook(realize_signal_id, realize_hook_id);
realize_signal_id = 0;
realize_hook_id = 0;
}
} // namespace
namespace views {
// static
TouchFactory* TouchFactory::GetInstance() {
return Singleton<TouchFactory>::get();
}
TouchFactory::TouchFactory()
: is_cursor_visible_(true),
cursor_timer_(),
pointer_device_lookup_(),
touch_device_list_(),
slots_used_() {
char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
XColor black;
black.red = black.green = black.blue = 0;
Display* display = ui::GetXDisplay();
Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(),
nodata, 8, 8);
invisible_cursor_ = XCreatePixmapCursor(display, blank, blank,
&black, &black, 0, 0);
arrow_cursor_ = XCreateFontCursor(display, XC_arrow);
SetCursorVisible(false, false);
UpdateDeviceList(display);
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Make sure the list of devices is kept up-to-date by listening for
// XI_HierarchyChanged event on the root window.
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_HierarchyChanged);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1);
}
TouchFactory::~TouchFactory() {
SetCursorVisible(true, false);
Display* display = ui::GetXDisplay();
XFreeCursor(display, invisible_cursor_);
XFreeCursor(display, arrow_cursor_);
RemoveGtkWidgetRealizeNotifier();
}
void TouchFactory::UpdateDeviceList(Display* display) {
// Detect touch devices.
// NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
// not provide enough information to detect a touch device. As a result, the
// old version of query function (XListInputDevices) is used instead.
// If XInput2 is not supported, this will return null (with count of -1) so
// we assume there cannot be any touch devices.
int count = 0;
touch_device_lookup_.reset();
touch_device_list_.clear();
XDeviceInfo* devlist = XListInputDevices(display, &count);
for (int i = 0; i < count; i++) {
if (devlist[i].type) {
const char* devtype = XGetAtomName(display, devlist[i].type);
if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) {
touch_device_lookup_[devlist[i].id] = true;
touch_device_list_.push_back(devlist[i].id);
}
}
}
if (devlist)
XFreeDeviceList(devlist);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of pointer devices we care about.
// It should not be necessary to select for slave devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a
// 'mouse event' or a 'touch event'.
// However, on some desktops, some events from a master pointer are
// not delivered to the client. So we select for slave devices instead.
// If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
// is possible), then the device is detected as a floating device, and a
// floating device is not connected to a master device. So it is necessary to
// also select on the floating devices.
pointer_device_lookup_.reset();
XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XIFloatingSlave || devinfo->use == XISlavePointer) {
pointer_device_lookup_[devinfo->deviceid] = true;
}
}
if (devices)
XIFreeDeviceInfo(devices);
SetupValuator();
}
bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
DCHECK_EQ(GenericEvent, xev->type);
XGenericEventCookie* cookie = &xev->xcookie;
if (cookie->evtype != XI_ButtonPress &&
cookie->evtype != XI_ButtonRelease &&
cookie->evtype != XI_Motion)
return true;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
return pointer_device_lookup_[xiev->sourceid];
}
void TouchFactory::SetupXI2ForXWindow(Window window) {
// Setup mask for mouse events. It is possible that a device is loaded/plugged
// in after we have setup XInput2 on a window. In such cases, we need to
// either resetup XInput2 for the window, so that we get events from the new
// device, or we need to listen to events from all devices, and then filter
// the events from uninteresting devices. We do the latter because that's
// simpler.
Display* display = ui::GetXDisplay();
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, window, &evmask, 1);
XFlush(display);
}
void TouchFactory::SetTouchDeviceList(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_.push_back(*iter);
}
SetupValuator();
}
bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
return deviceid < touch_device_lookup_.size() ?
touch_device_lookup_[deviceid] : false;
}
bool TouchFactory::IsSlotUsed(int slot) const {
CHECK_LT(slot, kMaxTouchPoints);
return slots_used_[slot];
}
void TouchFactory::SetSlotUsed(int slot, bool used) {
CHECK_LT(slot, kMaxTouchPoints);
slots_used_[slot] = used;
}
bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) {
if (touch_device_list_.empty())
return true;
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
bool success = true;
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
evmask.deviceid = *iter;
Status status = XIGrabDevice(display, *iter, window, CurrentTime, None,
GrabModeAsync, GrabModeAsync, False, &evmask);
success = success && status == GrabSuccess;
}
return success;
}
bool TouchFactory::UngrabTouchDevices(Display* display) {
bool success = true;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
Status status = XIUngrabDevice(display, *iter, CurrentTime);
success = success && status == GrabSuccess;
}
return success;
}
void TouchFactory::SetCursorVisible(bool show, bool start_timer) {
// The cursor is going to be shown. Reset the timer for hiding it.
if (show && start_timer) {
cursor_timer_.Stop();
cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds),
this, &TouchFactory::HideCursorForInactivity);
} else {
cursor_timer_.Stop();
}
if (show == is_cursor_visible_)
return;
is_cursor_visible_ = show;
Display* display = ui::GetXDisplay();
Window window = DefaultRootWindow(display);
if (is_cursor_visible_) {
XDefineCursor(display, window, arrow_cursor_);
} else {
XDefineCursor(display, window, invisible_cursor_);
}
}
void TouchFactory::SetupValuator() {
memset(valuator_lookup_, -1, sizeof(valuator_lookup_));
Display* display = ui::GetXDisplay();
int ndevice;
XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice);
for (int i = 0; i < ndevice; i++) {
XIDeviceInfo* info = info_list + i;
if (!IsTouchDevice(info->deviceid))
continue;
for (int i = 0; i < TP_LAST_ENTRY; i++) {
TouchParam tp = static_cast<TouchParam>(i);
valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp);
}
}
if (info_list)
XIFreeDeviceInfo(info_list);
}
bool TouchFactory::ExtractTouchParam(const XEvent& xev,
TouchParam tp,
float* value) {
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data);
if (xiev->sourceid >= kMaxDeviceNum)
return false;
int v = valuator_lookup_[xiev->sourceid][tp];
if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) {
*value = xiev->valuators.values[v];
return true;
}
return false;
}
} // namespace views
<|endoftext|> |
<commit_before>/***********************************************************************
created: 7/2/2008
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 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 "CEGUISamplesConfig.h"
#include "CEGuiBaseApplication.h"
#include "SamplesFramework.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Image.h"
#include "CEGUI/Font.h"
#include "CEGUI/Scheme.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/ScriptModule.h"
#include "CEGUI/XMLParser.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RenderTarget.h"
#include "CEGUI/AnimationManager.h"
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#ifdef __APPLE__
# include <Carbon/Carbon.h>
#endif
// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
#define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif
/***********************************************************************
Static / Const data
*************************************************************************/
const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH";
SamplesFrameworkBase* CEGuiBaseApplication::d_sampleApp(0);
//----------------------------------------------------------------------------//
CEGuiBaseApplication::CEGuiBaseApplication() :
d_quitting(false),
d_renderer(0),
d_imageCodec(0),
d_resourceProvider(0),
d_logoGeometry(0),
d_FPSGeometry(0),
d_FPSElapsed(0.0f),
d_FPSFrames(0),
d_FPSValue(0),
d_spinLogo(false)
{
}
//----------------------------------------------------------------------------//
CEGuiBaseApplication::~CEGuiBaseApplication()
{
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::renderSingleFrame(const float elapsed)
{
CEGUI::System& gui_system(CEGUI::System::getSingleton());
gui_system.injectTimePulse(elapsed);
d_sampleApp->update(static_cast<float>(elapsed));
updateFPS(elapsed);
updateLogo(elapsed);
beginRendering(elapsed);
CEGUI::Renderer* gui_renderer(gui_system.getRenderer());
gui_renderer->beginRendering();
d_sampleApp->renderGUIContexts();
gui_renderer->endRendering();
CEGUI::WindowManager::getSingleton().cleanDeadPool();
endRendering();
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::execute(SamplesFrameworkBase* sampleApp)
{
d_sampleApp = sampleApp;
if (!d_renderer)
throw CEGUI::InvalidRequestException("CEGuiBaseApplication::run: "
"Base application subclass did not create Renderer!");
// start up CEGUI system using objects created in subclass constructor.
CEGUI::System::create(*d_renderer, d_resourceProvider, 0, d_imageCodec);
// initialise resource system
initialiseResourceGroupDirectories();
initialiseDefaultResourceGroups();
const CEGUI::Rectf scrn(CEGUI::Vector2f(0, 0), d_renderer->getDisplaySize());
// setup for FPS value
d_FPSGeometry = &d_renderer->createGeometryBuffer();
d_FPSGeometry->setClippingRegion(scrn);
positionFPS();
// setup for spinning logo
d_logoGeometry = &d_renderer->createGeometryBuffer();
d_logoGeometry->setPivot(CEGUI::Vector3f(91.5f, 44.5f, 0));
positionLogo();
// create logo imageset and draw the image (we only ever draw this once)
CEGUI::ImageManager::getSingleton().addFromImageFile("cegui_logo",
"logo.png");
CEGUI::ImageManager::getSingleton().get("cegui_logo").render(
*d_logoGeometry, CEGUI::Rectf(0, 0, 183, 89), 0, CEGUI::ColourRect(0xFFFFFFFF));
// clearing this queue actually makes sure it's created(!)
CEGUI::System::getSingleton().getDefaultGUIContext().clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
CEGUI::System::getSingleton().getDefaultGUIContext().
subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::sampleBrowserOverlayHandler,
this));
// subscribe handler to reposition logo when window is sized.
CEGUI::System::getSingleton().subscribeEvent(
CEGUI::System::EventDisplaySizeChanged,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::resizeHandler,
this));
const CEGUI::Rectf& area(CEGUI::System::getSingleton().getRenderer()->
getDefaultRenderTarget().getArea());
d_sampleApp->setApplicationWindowSize(static_cast<int>(area.getWidth()),
static_cast<int>(area.getHeight()));
run();
cleanup();
destroyWindow();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::cleanup()
{
CEGUI::ImageManager::getSingleton().destroy("cegui_logo");
d_renderer->destroyGeometryBuffer(*d_logoGeometry);
d_renderer->destroyGeometryBuffer(*d_FPSGeometry);
CEGUI::System::destroy();
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::initialiseResourceGroupDirectories()
{
// initialise the required dirs for the DefaultResourceProvider
CEGUI::DefaultResourceProvider* rp =
static_cast<CEGUI::DefaultResourceProvider*>
(CEGUI::System::getSingleton().getResourceProvider());
const char* dataPathPrefix = getDataPathPrefix();
char resourcePath[PATH_MAX];
// for each resource type, set a resource group directory
sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
rp->setResourceGroupDirectory("schemes", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
rp->setResourceGroupDirectory("imagesets", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
rp->setResourceGroupDirectory("fonts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
rp->setResourceGroupDirectory("layouts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
rp->setResourceGroupDirectory("looknfeels", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
rp->setResourceGroupDirectory("lua_scripts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
rp->setResourceGroupDirectory("schemas", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/");
rp->setResourceGroupDirectory("animations", resourcePath);
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::initialiseDefaultResourceGroups()
{
// set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::AnimationManager::setDefaultResourceGroup("animations");
// setup default group for validation schemas
CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
parser->setProperty("SchemaDefaultResourceGroup", "schemas");
}
//----------------------------------------------------------------------------//
const char* CEGuiBaseApplication::getDataPathPrefix() const
{
static char dataPathPrefix[PATH_MAX];
#ifdef __APPLE__
CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
CFSTR("datafiles"),
0, 0);
CFURLGetFileSystemRepresentation(datafilesURL, true,
reinterpret_cast<UInt8*>(dataPathPrefix),
PATH_MAX);
CFRelease(datafilesURL);
#else
char* envDataPath = 0;
// get data path from environment var
envDataPath = getenv(DATAPATH_VAR_NAME);
// set data path prefix / base directory. This will
// be either from an environment variable, or from
// a compiled in default based on original configure
// options
if (envDataPath != 0)
strcpy(dataPathPrefix, envDataPath);
else
strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);
#endif
return dataPathPrefix;
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::sampleBrowserOverlayHandler(const CEGUI::EventArgs& args)
{
if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
return false;
// draw the logo
d_logoGeometry->draw();
// draw FPS value
d_FPSGeometry->draw();
return true;
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::sampleOverlayHandler(const CEGUI::EventArgs& args)
{
if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
return false;
// draw FPS value
d_FPSGeometry->draw();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::updateFPS(const float elapsed)
{
// another frame
++d_FPSFrames;
if ((d_FPSElapsed += elapsed) >= 1.0f)
{
if (d_FPSFrames != d_FPSValue)
{
d_FPSValue = d_FPSFrames;
CEGUI::Font* fnt = CEGUI::System::getSingleton().getDefaultGUIContext().getDefaultFont();
if (!fnt)
return;
// update FPS imagery
char fps_textbuff[16];
sprintf(fps_textbuff , "FPS: %d", d_FPSValue);
d_FPSGeometry->reset();
fnt->drawText(*d_FPSGeometry, fps_textbuff, CEGUI::Vector2f(0, 0), 0,
CEGUI::Colour(0xFFFFFFFF));
}
// reset counter state
d_FPSFrames = 0;
float modValue = 1.f;
d_FPSElapsed = std::modf(d_FPSElapsed, &modValue);
}
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::updateLogo(const float elapsed)
{
if (!d_spinLogo)
return;
static float rot = 0.0f;
d_logoGeometry->setRotation(CEGUI::Quaternion::eulerAnglesDegrees(rot, 0, 0));
rot = fmodf(rot + 180.0f * elapsed, 360.0f);
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::positionLogo()
{
const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea());
d_logoGeometry->setClippingRegion(scrn);
d_logoGeometry->setTranslation(
CEGUI::Vector3f(10.0f, scrn.getSize().d_height - 89.0f, 0.0f));
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::positionFPS()
{
const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea());
d_FPSGeometry->setClippingRegion(scrn);
d_FPSGeometry->setTranslation(
CEGUI::Vector3f(scrn.getSize().d_width - 120.0f, 0.0f, 0.0f));
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::resizeHandler(const CEGUI::EventArgs& /*args*/)
{
// clear FPS geometry and see that it gets recreated in the next frame
d_FPSGeometry->reset();
d_FPSValue = 0;
const CEGUI::Rectf& area(CEGUI::System::getSingleton().getRenderer()->
getDefaultRenderTarget().getArea());
d_sampleApp->handleNewWindowSize(area.getWidth(), area.getHeight());
positionLogo();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::registerSampleOverlayHandler(CEGUI::GUIContext* gui_context)
{
// clearing this queue actually makes sure it's created(!)
gui_context->clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
gui_context->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::sampleOverlayHandler,
this));
}
//----------------------------------------------------------------------------//<commit_msg>MOD: Minor change in CEGuiBaseApplication to retrieve Font directly<commit_after>/***********************************************************************
created: 7/2/2008
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 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 "CEGUISamplesConfig.h"
#include "CEGuiBaseApplication.h"
#include "SamplesFramework.h"
#include "CEGUI/System.h"
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Image.h"
#include "CEGUI/Font.h"
#include "CEGUI/Scheme.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/ScriptModule.h"
#include "CEGUI/XMLParser.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RenderTarget.h"
#include "CEGUI/AnimationManager.h"
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#ifdef __APPLE__
# include <Carbon/Carbon.h>
#endif
// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
#define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif
/***********************************************************************
Static / Const data
*************************************************************************/
const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH";
SamplesFrameworkBase* CEGuiBaseApplication::d_sampleApp(0);
//----------------------------------------------------------------------------//
CEGuiBaseApplication::CEGuiBaseApplication() :
d_quitting(false),
d_renderer(0),
d_imageCodec(0),
d_resourceProvider(0),
d_logoGeometry(0),
d_FPSGeometry(0),
d_FPSElapsed(0.0f),
d_FPSFrames(0),
d_FPSValue(0),
d_spinLogo(false)
{
}
//----------------------------------------------------------------------------//
CEGuiBaseApplication::~CEGuiBaseApplication()
{
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::renderSingleFrame(const float elapsed)
{
CEGUI::System& gui_system(CEGUI::System::getSingleton());
gui_system.injectTimePulse(elapsed);
d_sampleApp->update(static_cast<float>(elapsed));
updateFPS(elapsed);
updateLogo(elapsed);
beginRendering(elapsed);
CEGUI::Renderer* gui_renderer(gui_system.getRenderer());
gui_renderer->beginRendering();
d_sampleApp->renderGUIContexts();
gui_renderer->endRendering();
CEGUI::WindowManager::getSingleton().cleanDeadPool();
endRendering();
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::execute(SamplesFrameworkBase* sampleApp)
{
d_sampleApp = sampleApp;
if (!d_renderer)
throw CEGUI::InvalidRequestException("CEGuiBaseApplication::run: "
"Base application subclass did not create Renderer!");
// start up CEGUI system using objects created in subclass constructor.
CEGUI::System::create(*d_renderer, d_resourceProvider, 0, d_imageCodec);
// initialise resource system
initialiseResourceGroupDirectories();
initialiseDefaultResourceGroups();
const CEGUI::Rectf scrn(CEGUI::Vector2f(0, 0), d_renderer->getDisplaySize());
// setup for FPS value
d_FPSGeometry = &d_renderer->createGeometryBuffer();
d_FPSGeometry->setClippingRegion(scrn);
positionFPS();
// setup for spinning logo
d_logoGeometry = &d_renderer->createGeometryBuffer();
d_logoGeometry->setPivot(CEGUI::Vector3f(91.5f, 44.5f, 0));
positionLogo();
// create logo imageset and draw the image (we only ever draw this once)
CEGUI::ImageManager::getSingleton().addFromImageFile("cegui_logo",
"logo.png");
CEGUI::ImageManager::getSingleton().get("cegui_logo").render(
*d_logoGeometry, CEGUI::Rectf(0, 0, 183, 89), 0, CEGUI::ColourRect(0xFFFFFFFF));
// clearing this queue actually makes sure it's created(!)
CEGUI::System::getSingleton().getDefaultGUIContext().clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
CEGUI::System::getSingleton().getDefaultGUIContext().
subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::sampleBrowserOverlayHandler,
this));
// subscribe handler to reposition logo when window is sized.
CEGUI::System::getSingleton().subscribeEvent(
CEGUI::System::EventDisplaySizeChanged,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::resizeHandler,
this));
const CEGUI::Rectf& area(CEGUI::System::getSingleton().getRenderer()->
getDefaultRenderTarget().getArea());
d_sampleApp->setApplicationWindowSize(static_cast<int>(area.getWidth()),
static_cast<int>(area.getHeight()));
run();
cleanup();
destroyWindow();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::cleanup()
{
CEGUI::ImageManager::getSingleton().destroy("cegui_logo");
d_renderer->destroyGeometryBuffer(*d_logoGeometry);
d_renderer->destroyGeometryBuffer(*d_FPSGeometry);
CEGUI::System::destroy();
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::initialiseResourceGroupDirectories()
{
// initialise the required dirs for the DefaultResourceProvider
CEGUI::DefaultResourceProvider* rp =
static_cast<CEGUI::DefaultResourceProvider*>
(CEGUI::System::getSingleton().getResourceProvider());
const char* dataPathPrefix = getDataPathPrefix();
char resourcePath[PATH_MAX];
// for each resource type, set a resource group directory
sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
rp->setResourceGroupDirectory("schemes", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
rp->setResourceGroupDirectory("imagesets", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
rp->setResourceGroupDirectory("fonts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
rp->setResourceGroupDirectory("layouts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
rp->setResourceGroupDirectory("looknfeels", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
rp->setResourceGroupDirectory("lua_scripts", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
rp->setResourceGroupDirectory("schemas", resourcePath);
sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/");
rp->setResourceGroupDirectory("animations", resourcePath);
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::initialiseDefaultResourceGroups()
{
// set the default resource groups to be used
CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
CEGUI::Font::setDefaultResourceGroup("fonts");
CEGUI::Scheme::setDefaultResourceGroup("schemes");
CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
CEGUI::WindowManager::setDefaultResourceGroup("layouts");
CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
CEGUI::AnimationManager::setDefaultResourceGroup("animations");
// setup default group for validation schemas
CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
parser->setProperty("SchemaDefaultResourceGroup", "schemas");
}
//----------------------------------------------------------------------------//
const char* CEGuiBaseApplication::getDataPathPrefix() const
{
static char dataPathPrefix[PATH_MAX];
#ifdef __APPLE__
CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
CFSTR("datafiles"),
0, 0);
CFURLGetFileSystemRepresentation(datafilesURL, true,
reinterpret_cast<UInt8*>(dataPathPrefix),
PATH_MAX);
CFRelease(datafilesURL);
#else
char* envDataPath = 0;
// get data path from environment var
envDataPath = getenv(DATAPATH_VAR_NAME);
// set data path prefix / base directory. This will
// be either from an environment variable, or from
// a compiled in default based on original configure
// options
if (envDataPath != 0)
strcpy(dataPathPrefix, envDataPath);
else
strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);
#endif
return dataPathPrefix;
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::sampleBrowserOverlayHandler(const CEGUI::EventArgs& args)
{
if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
return false;
// draw the logo
d_logoGeometry->draw();
// draw FPS value
d_FPSGeometry->draw();
return true;
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::sampleOverlayHandler(const CEGUI::EventArgs& args)
{
if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY)
return false;
// draw FPS value
d_FPSGeometry->draw();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::updateFPS(const float elapsed)
{
// another frame
++d_FPSFrames;
if ((d_FPSElapsed += elapsed) >= 1.0f)
{
if (d_FPSFrames != d_FPSValue)
{
d_FPSValue = d_FPSFrames;
CEGUI::Font* fnt = &CEGUI::FontManager::getSingleton().get("DejaVuSans-12");
if (!fnt)
return;
// update FPS imagery
char fps_textbuff[16];
sprintf(fps_textbuff , "FPS: %d", d_FPSValue);
d_FPSGeometry->reset();
fnt->drawText(*d_FPSGeometry, fps_textbuff, CEGUI::Vector2f(0, 0), 0,
CEGUI::Colour(0xFFFFFFFF));
}
// reset counter state
d_FPSFrames = 0;
float modValue = 1.f;
d_FPSElapsed = std::modf(d_FPSElapsed, &modValue);
}
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::updateLogo(const float elapsed)
{
if (!d_spinLogo)
return;
static float rot = 0.0f;
d_logoGeometry->setRotation(CEGUI::Quaternion::eulerAnglesDegrees(rot, 0, 0));
rot = fmodf(rot + 180.0f * elapsed, 360.0f);
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::positionLogo()
{
const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea());
d_logoGeometry->setClippingRegion(scrn);
d_logoGeometry->setTranslation(
CEGUI::Vector3f(10.0f, scrn.getSize().d_height - 89.0f, 0.0f));
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::positionFPS()
{
const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea());
d_FPSGeometry->setClippingRegion(scrn);
d_FPSGeometry->setTranslation(
CEGUI::Vector3f(scrn.getSize().d_width - 120.0f, 0.0f, 0.0f));
}
//----------------------------------------------------------------------------//
bool CEGuiBaseApplication::resizeHandler(const CEGUI::EventArgs& /*args*/)
{
// clear FPS geometry and see that it gets recreated in the next frame
d_FPSGeometry->reset();
d_FPSValue = 0;
const CEGUI::Rectf& area(CEGUI::System::getSingleton().getRenderer()->
getDefaultRenderTarget().getArea());
d_sampleApp->handleNewWindowSize(area.getWidth(), area.getHeight());
positionLogo();
return true;
}
//----------------------------------------------------------------------------//
void CEGuiBaseApplication::registerSampleOverlayHandler(CEGUI::GUIContext* gui_context)
{
// clearing this queue actually makes sure it's created(!)
gui_context->clearGeometry(CEGUI::RQ_OVERLAY);
// subscribe handler to render overlay items
gui_context->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted,
CEGUI::Event::Subscriber(&CEGuiBaseApplication::sampleOverlayHandler,
this));
}
//----------------------------------------------------------------------------//<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h" //https://github.com/kinasmith/Sleepy
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 0;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 60000;
const uint16_t REC_INTERVAL = (60000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
struct Measurement {
uint32_t time;
int16_t tc1;
int16_t tc2;
int16_t tc3;
};
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
//Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!"); flash.eraseChip();
tc1.begin(); tc2.begin(); tc3.begin();
tc1.setThermocoupleType(MAX31856_TCTYPE_E);
tc2.setThermocoupleType(MAX31856_TCTYPE_E);
tc3.setThermocoupleType(MAX31856_TCTYPE_E);
DEBUGln("--Thermocouples are engaged");
}
void loop()
{
if(sentMeasurement) {
DEBUG("sleep - sleeping for "); DEBUG(REC_INTERVAL); DEBUG(" seconds"); DEBUGln();
DEBUGFlush();
radio.sleep();
count++;
for(int i = 0; i < REC_MIN; i++)
Sleepy::loseSomeTime(REC_MS);
//===========|| MCU WAKES UP HERE
//===========|| RESET TIMER VALUES
sentMeasurement = 0;
current_time = millis();
stop_saved_time = current_time;
h_saved_time = current_time;
log_saved_time = current_time;
h_interval = 0;
} else {
current_time = millis();
if(stop_saved_time + stop_time > current_time) {
if (h_saved_time + h_interval < current_time){
if(h_status == 0) { //if it is off, turn it on
// digitalWrite(HEATER_EN, HIGH);
h_interval = h_pulse_on; //wait for ON time
h_status = 1;
DEBUG("Heater - On for "); DEBUG(h_interval/1000); DEBUGln("s");
} else if(h_status == 1) {//if heat is on....turn it off
// digitalWrite(HEATER_EN, LOW);
h_interval = h_pulse_off; //wait for OFF time
h_status = 0;
DEBUG("Heater - Off for "); DEBUG(h_interval/1000); DEBUGln("s");
}
h_saved_time = current_time;
}
if(log_saved_time + log_interval < current_time) {
Measurement thisMeasurement;
thisMeasurement.time = 2500;
thisMeasurement.tc1 = 15;
thisMeasurement.tc2 = 72;
thisMeasurement.tc3 = 345;
delay(500);
if(flash.writeAnything(FLASH_ADDR, thisMeasurement)) {
DEBUGln("--> Data Written");
}
FLASH_ADDR += sizeof(thisMeasurement);
DEBUGln(FLASH_ADDR);
log_saved_time = current_time;
}
} else {
DEBUGln("SEND MEASUREMENTS");
sentMeasurement = 1;
}
}
}
/**
* [getTime description]
* @return [description]
*/
bool getTime() {
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<commit_msg>everything is STILL FUCKED<commit_after>#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include "Sleepy.h" //https://github.com/kinasmith/Sleepy
#include "RFM69_ATC.h"
#include "SPIFlash_Marzogh.h"
#include <EEPROM.h>
#include "Adafruit_MAX31856.h"
#define NODEID 11
#define GATEWAYID 0
#define FREQUENCY RF69_433MHZ //frequency of radio
#define ATC_RSSI -70 //ideal Signal Strength of trasmission
#define ACK_WAIT_TIME 100 // # of ms to wait for an ack
#define ACK_RETRIES 10 // # of attempts before giving up
#define SERIAL_BAUD 9600 // Serial comms rate
#define FLASH_CAPACITY 524288
#define LED 9
#define LED2 A0
#define N_SEL_1 A1
#define N_SEL_2 A2
#define N_SEL_4 A3
#define BAT_V A7
#define BAT_EN 3
#define HEATER_EN 4
#define TC1_CS 7
#define TC2_CS 6
#define TC3_CS 5
#define FLASH_CS 8
#define RFM_CS 10
#define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space
#ifdef SERIAL_EN
#define DEBUG(input) {Serial.print(input); delay(1);}
#define DEBUGln(input) {Serial.println(input); delay(1);}
#define DEBUGFlush() { Serial.flush(); }
#else
#define DEBUG(input);
#define DEBUGln(input);
#define DEBUGFlush();
#endif
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
/*==============|| FUNCTIONS ||==============*/
bool getTime();
void Blink(uint8_t);
void sendFromFlash();
void writeToFlash();
uint8_t setAddress();
float getBatteryVoltage(uint8_t pin, uint8_t en);
bool saveEEPROMTime();
uint32_t getEEPROMTime();
void takeMeasurements();
/*==============|| RFM69 ||==============*/
RFM69_ATC radio; //init radio
uint8_t NETWORKID = 100; //base network address
uint8_t attempt_cnt = 0;
bool HANDSHAKE_SENT;
/*==============|| MEMORY ||==============*/
SPIFlash_Marzogh flash(8);
uint32_t FLASH_ADDR = 100;
uint16_t EEPROM_ADDR = 0;
/*==============|| THERMOCOUPLE ||==============*/
Adafruit_MAX31856 tc1 = Adafruit_MAX31856(TC1_CS);
Adafruit_MAX31856 tc2 = Adafruit_MAX31856(TC2_CS);
Adafruit_MAX31856 tc3 = Adafruit_MAX31856(TC3_CS);
/*==============|| UTIL ||==============*/
bool LED_STATE;
uint16_t count = 0;
uint8_t sentMeasurement = 0;
/*==============|| INTERVAL ||==============*/
const uint8_t REC_MIN = 1; //record interval in minutes
const uint16_t REC_MS = 30000;
const uint16_t REC_INTERVAL = (30000*REC_MIN)/1000; //record interval in seconds
/*==============|| DATA ||==============*/
//Data structure for transmitting the Timestamp from datalogger to sensor (4 bytes)
struct TimeStamp {
uint32_t timestamp;
};
TimeStamp theTimeStamp; //creates global instantiation of this
//Data structure for storing data locally (12 bytes)
struct Data {
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
//Data Structure for transmitting data packets to datalogger (16 bytes)
struct Payload {
uint32_t timestamp;
uint16_t count;
int16_t tc1;
int16_t tc2;
int16_t tc3;
int16_t brd_tmp;
int16_t bat_v;
};
Payload thePayload;
struct Measurement {
uint32_t time;
int16_t tc1;
int16_t tc2;
int16_t tc3;
};
uint32_t current_time;
uint32_t stop_saved_time = 0;
uint32_t log_saved_time = 0;
uint32_t h_saved_time = 0;
uint16_t h_interval = 0;
uint16_t log_interval = 1000;
uint16_t h_pulse_on = 6000;
uint32_t h_pulse_off = 30 * 60000L;
uint16_t stop_time = 30000;
uint8_t h_status = 0;
void setup()
{
#ifdef SERIAL_EN
Serial.begin(SERIAL_BAUD);
#endif
randomSeed(analogRead(A4)); //set random seed
NETWORKID += setAddress();
radio.initialize(FREQUENCY,NODEID,NETWORKID);
radio.setHighPower();
radio.encrypt(null);
radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point
DEBUG("--Transmitting on Network: "); DEBUG(NETWORKID); DEBUG(", as Node: "); DEBUGln(NODEID);
pinMode(LED, OUTPUT);
//Ping the datalogger. If it's alive, it will return the current time. If not, wait and try again.
digitalWrite(LED, HIGH); //write LED high to signal attempting connection
while(!getTime()) { //this saves time to the struct which holds the time globally
radio.sleep();
DEBUGFlush();
delay(10000);
}
digitalWrite(LED, LOW); //write low to signal success
DEBUG("--Time is: "); DEBUG(theTimeStamp.timestamp); DEBUGln("--");
DEBUG("--Flash Mem: ");
flash.begin();
uint16_t _name = flash.getChipName();
uint32_t capacity = flash.getCapacity();
DEBUG("W25X"); DEBUG(_name); DEBUG("** ");
DEBUG("capacity: "); DEBUG(capacity); DEBUGln(" bytes");
DEBUGln("Erasing Chip!");
while(!flash.eraseChip()) {
DEBUGln("Erasing Chip!");
}
tc1.begin(); tc2.begin(); tc3.begin();
tc1.setThermocoupleType(MAX31856_TCTYPE_E);
tc2.setThermocoupleType(MAX31856_TCTYPE_E);
tc3.setThermocoupleType(MAX31856_TCTYPE_E);
DEBUGln("--Thermocouples are engaged");
}
void loop()
{
if(sentMeasurement) {
DEBUG("sleep - sleeping for "); DEBUG(REC_INTERVAL); DEBUG(" seconds"); DEBUGln();
DEBUGFlush();
radio.sleep();
count++;
for(int i = 0; i < REC_MIN; i++)
Sleepy::loseSomeTime(REC_MS);
//===========|| MCU WAKES UP HERE
//===========|| RESET TIMER VALUES
sentMeasurement = 0;
current_time = millis();
stop_saved_time = current_time;
h_saved_time = current_time;
log_saved_time = current_time;
h_interval = 0;
} else {
current_time = millis();
if(stop_saved_time + stop_time > current_time) {
if (h_saved_time + h_interval < current_time){
if(h_status == 0) { //if it is off, turn it on
digitalWrite(HEATER_EN, HIGH);
h_interval = h_pulse_on; //wait for ON time
h_status = 1;
DEBUG("Heater - On for "); DEBUG(h_interval/1000); DEBUGln("s");
} else if(h_status == 1) {//if heat is on....turn it off
digitalWrite(HEATER_EN, LOW);
h_interval = h_pulse_off; //wait for OFF time
h_status = 0;
DEBUG("Heater - Off for "); DEBUG(h_interval/1000); DEBUGln("s");
}
h_saved_time = current_time;
}
if(log_saved_time + log_interval < current_time) {
// Measurement thisMeasurement;
// thisMeasurement.time = 2500;
// thisMeasurement.tc1 = 15;
// thisMeasurement.tc2 = 72;
// thisMeasurement.tc3 = 345;
delay(500);
if(flash.writeAnything(FLASH_ADDR, FLASH_ADDR)) {
DEBUGln("--> Data Written");
}
FLASH_ADDR += sizeof(FLASH_ADDR);
DEBUGln(FLASH_ADDR);
log_saved_time = current_time;
}
} else {
DEBUGln("SEND MEASUREMENTS");
sentMeasurement = 1;
}
}
}
/**
* [getTime description]
* @return [description]
*/
bool getTime() {
LED_STATE = true;
digitalWrite(LED, LED_STATE);
//Get the current timestamp from the datalogger
bool TIME_RECIEVED = false;
if(!HANDSHAKE_SENT) { //Send request for time to the Datalogger
DEBUG("time - ");
if (radio.sendWithRetry(GATEWAYID, "t", 1)) {
DEBUG("snd . . ");
HANDSHAKE_SENT = true;
}
else {
DEBUGln("failed . . . no ack");
return false; //if there is no response, returns false and exits function
}
}
while(!TIME_RECIEVED && HANDSHAKE_SENT) { //Wait for the time to be returned
if (radio.receiveDone()) {
if (radio.DATALEN == sizeof(theTimeStamp)) { //check to make sure it's the right size
theTimeStamp = *(TimeStamp*)radio.DATA; //save data
DEBUG(" rcv - "); DEBUG('['); DEBUG(radio.SENDERID); DEBUG("] ");
DEBUG(theTimeStamp.timestamp);
DEBUG(" [RX_RSSI:"); DEBUG(radio.RSSI); DEBUG("]");
DEBUGln();
TIME_RECIEVED = true;
LED_STATE = false;
digitalWrite(LED, LED_STATE);
}
if (radio.ACKRequested()) radio.sendACK();
}
}
HANDSHAKE_SENT = false;
return true;
}
/**
* [Blink description]
* @param t [description]
*/
void Blink(uint8_t t) {
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
LED_STATE = !LED_STATE;
digitalWrite(LED, LED_STATE);
delay(t);
}
/**
* [setAddress description]
* @return [description]
*/
uint8_t setAddress() {
//sets network address based on which solder jumpers are closed
uint8_t addr01, addr02, addr03;
pinMode(N_SEL_1, INPUT_PULLUP);
pinMode(N_SEL_2, INPUT_PULLUP);
pinMode(N_SEL_4, INPUT_PULLUP);
addr01 = !digitalRead(N_SEL_1);
addr02 = !digitalRead(N_SEL_2) * 2;
addr03 = !digitalRead(N_SEL_4) * 4;
pinMode(N_SEL_1, OUTPUT);
pinMode(N_SEL_2, OUTPUT);
pinMode(N_SEL_4, OUTPUT);
digitalWrite(N_SEL_1, HIGH);
digitalWrite(N_SEL_2, HIGH);
digitalWrite(N_SEL_4, HIGH);
uint8_t addr = addr01 | addr02 | addr03;
return addr;
}
<|endoftext|> |
<commit_before>#ifndef ROBOCUP2DSIM_ENGINE_PHYSICS_HXX
#define ROBOCUP2DSIM_ENGINE_PHYSICS_HXX
#include <utility>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <robocup2Dsim/runtime/resource.hh>
namespace robocup2Dsim {
namespace engine {
template <class contact_category_t>
contact_config<contact_category_t>::contact_config(
contact_result initial,
contact_result from_same_entity)
:
config_(initial == contact_result::collide
? std::numeric_limits<decltype(b2Filter::categoryBits)>::max()
: std::numeric_limits<decltype(b2Filter::categoryBits)>::min()),
from_same_entity_(from_same_entity)
{ }
template <class contact_category_t>
decltype(b2Filter::categoryBits) contact_config<contact_category_t>::to_uint() const
{
return config_.to_ulong();
}
template <class contact_category_t>
contact_result contact_config<contact_category_t>::get_from_same_entity_config() const
{
return from_same_entity_;
}
template <class contact_category_t>
contact_result contact_config<contact_category_t>::get(contact_category_type category) const
{
return config_[static_cast<category_underlying_type>(category)]
? contact_result::collide
: contact_result::pass_over;
}
template <class contact_category_t>
void contact_config<contact_category_t>::set(contact_category_type category, contact_result contact)
{
switch (contact)
{
case contact_result::collide:
{
config_.set(static_cast<category_underlying_type>(category), true);
break;
}
case contact_result::pass_over:
{
config_.set(static_cast<category_underlying_type>(category), false);
break;
}
default:
{
break;
}
}
}
namespace {
using namespace robocup2Dsim::engine;
namespace rru = robocup2Dsim::runtime;
void set_fixture_data(physics::fixture_def& def, rru::ecs_db::entity_id_type entity_id, physics::fixture_id_type fixture_id)
{
std::uintptr_t data = fixture_id;
data <<= std::numeric_limits<rru::ecs_db::entity_id_type>::digits;
data |= entity_id;
def.userData = reinterpret_cast<void*>(data);
}
rru::ecs_db::entity_id_type get_entity_id(const b2Fixture& fixture)
{
std::uintptr_t mask = 0U;
mask |= std::numeric_limits<rru::ecs_db::entity_id_type>::max();
return reinterpret_cast<std::uintptr_t>(fixture.GetUserData()) & mask;
}
physics::fixture_id_type get_fixture_id(const b2Fixture& fixture)
{
std::uintptr_t mask = 0U;
mask |= std::numeric_limits<physics::fixture_id_type>::max();
std::uintptr_t raw_data = reinterpret_cast<std::uintptr_t>(fixture.GetUserData());
return (raw_data >> std::numeric_limits<rru::ecs_db::entity_id_type>::digits) & mask;
}
template <typename collision_func_t, typename separation_func_t>
struct contact_listener : public b2ContactListener
{
typedef collision_func_t collision_func_type;
typedef separation_func_t separation_func_type;
contact_listener(collision_func_type&& collision, separation_func_t&& separation);
virtual void BeginContact(b2Contact* contact);
virtual void EndContact(b2Contact* contact);
collision_func_t on_collision;
separation_func_t on_separation;
};
template <typename c, typename s>
contact_listener<c, s>::contact_listener(collision_func_type&& collision, separation_func_type&& separation)
:
on_collision(std::forward<collision_func_type>(collision)),
on_separation(std::forward<separation_func_type>(separation))
{ }
template <typename c, typename s>
void contact_listener<c, s>::BeginContact(b2Contact* contact)
{
if (contact)
{
physics::contact_participant participant_a{
get_entity_id(*(contact->GetFixtureA())),
get_fixture_id(*(contact->GetFixtureA())),
*(contact->GetFixtureA()->GetBody())};
physics::contact_participant participant_b{
get_entity_id(*(contact->GetFixtureB())),
get_fixture_id(*(contact->GetFixtureB())),
*(contact->GetFixtureB()->GetBody())};
on_collision(participant_a, participant_b);
}
}
template <typename c, typename s>
void contact_listener<c, s>::EndContact(b2Contact* contact)
{
if (contact)
{
physics::contact_participant participant_a{
get_entity_id(*(contact->GetFixtureA())),
get_fixture_id(*(contact->GetFixtureA())),
*(contact->GetFixtureA()->GetBody())};
physics::contact_participant participant_b{
get_entity_id(*(contact->GetFixtureB())),
get_fixture_id(*(contact->GetFixtureB())),
*(contact->GetFixtureB()->GetBody())};
on_separation(participant_a, participant_b);
}
}
} // anonyous namespace
template <class contact_category_t>
typename physics::fixture_def physics::make_fixture_def(
robocup2Dsim::runtime::ecs_db::entity_id_type entity_id,
fixture_id_type fixture_id,
contact_category_t category,
const contact_config<contact_category_t>& contact)
{
fixture_def result;
result.filter.categoryBits = 1U << static_cast<typename contact_config<contact_category_t>::category_underlying_type>(category);
result.filter.maskBits = contact.to_uint();
if (contact.get_from_same_entity_config() == contact_result::pass_over)
{
result.filter.groupIndex = entity_id * -1;
}
set_fixture_data(result, entity_id, fixture_id);
return result;
}
template <class joint_t, class def_t>
void physics::make_joint(const def_t& def)
{
joint_t* result = static_cast<joint_t*>(world_.CreateJoint(&def));
for (const fixture* fix = result->GetBodyA()->GetFixtureList(); fix != nullptr; fix = fix->GetNext())
{
if (fix != nullptr)
{
result->SetUserData(reinterpret_cast<void*>(static_cast<std::uintptr_t>(get_entity_id(*fix))));
break;
}
}
}
template <typename collision_func_t, typename separation_func_t>
void physics::step(float time_step, collision_func_t&& on_collision, separation_func_t&& on_separation)
{
contact_listener<collision_func_t, separation_func_t> listener(
std::forward<collision_func_t>(on_collision),
std::forward<separation_func_t>(on_separation));
world_.SetContactListener(&listener);
world_.Step(time_step, solver_conf_.velocity_iteration_limit, solver_conf_.position_iteration_limit);
world_.SetContactListener(nullptr);
}
} // namespace engine
} // namespace robocup2Dsim
#endif
<commit_msg>fixed a defect where fixtures from the same entity were colliding when the entity ID is 0 because groupIndex cannot be 0 when pass over is desired<commit_after>#ifndef ROBOCUP2DSIM_ENGINE_PHYSICS_HXX
#define ROBOCUP2DSIM_ENGINE_PHYSICS_HXX
#include <utility>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <robocup2Dsim/runtime/resource.hh>
namespace robocup2Dsim {
namespace engine {
template <class contact_category_t>
contact_config<contact_category_t>::contact_config(
contact_result initial,
contact_result from_same_entity)
:
config_(initial == contact_result::collide
? std::numeric_limits<decltype(b2Filter::categoryBits)>::max()
: std::numeric_limits<decltype(b2Filter::categoryBits)>::min()),
from_same_entity_(from_same_entity)
{ }
template <class contact_category_t>
decltype(b2Filter::categoryBits) contact_config<contact_category_t>::to_uint() const
{
return config_.to_ulong();
}
template <class contact_category_t>
contact_result contact_config<contact_category_t>::get_from_same_entity_config() const
{
return from_same_entity_;
}
template <class contact_category_t>
contact_result contact_config<contact_category_t>::get(contact_category_type category) const
{
return config_[static_cast<category_underlying_type>(category)]
? contact_result::collide
: contact_result::pass_over;
}
template <class contact_category_t>
void contact_config<contact_category_t>::set(contact_category_type category, contact_result contact)
{
switch (contact)
{
case contact_result::collide:
{
config_.set(static_cast<category_underlying_type>(category), true);
break;
}
case contact_result::pass_over:
{
config_.set(static_cast<category_underlying_type>(category), false);
break;
}
default:
{
break;
}
}
}
namespace {
using namespace robocup2Dsim::engine;
namespace rru = robocup2Dsim::runtime;
void set_fixture_data(physics::fixture_def& def, rru::ecs_db::entity_id_type entity_id, physics::fixture_id_type fixture_id)
{
std::uintptr_t data = fixture_id;
data <<= std::numeric_limits<rru::ecs_db::entity_id_type>::digits;
data |= entity_id;
def.userData = reinterpret_cast<void*>(data);
}
rru::ecs_db::entity_id_type get_entity_id(const b2Fixture& fixture)
{
std::uintptr_t mask = 0U;
mask |= std::numeric_limits<rru::ecs_db::entity_id_type>::max();
return reinterpret_cast<std::uintptr_t>(fixture.GetUserData()) & mask;
}
physics::fixture_id_type get_fixture_id(const b2Fixture& fixture)
{
std::uintptr_t mask = 0U;
mask |= std::numeric_limits<physics::fixture_id_type>::max();
std::uintptr_t raw_data = reinterpret_cast<std::uintptr_t>(fixture.GetUserData());
return (raw_data >> std::numeric_limits<rru::ecs_db::entity_id_type>::digits) & mask;
}
template <typename collision_func_t, typename separation_func_t>
struct contact_listener : public b2ContactListener
{
typedef collision_func_t collision_func_type;
typedef separation_func_t separation_func_type;
contact_listener(collision_func_type&& collision, separation_func_t&& separation);
virtual void BeginContact(b2Contact* contact);
virtual void EndContact(b2Contact* contact);
collision_func_t on_collision;
separation_func_t on_separation;
};
template <typename c, typename s>
contact_listener<c, s>::contact_listener(collision_func_type&& collision, separation_func_type&& separation)
:
on_collision(std::forward<collision_func_type>(collision)),
on_separation(std::forward<separation_func_type>(separation))
{ }
template <typename c, typename s>
void contact_listener<c, s>::BeginContact(b2Contact* contact)
{
if (contact)
{
physics::contact_participant participant_a{
get_entity_id(*(contact->GetFixtureA())),
get_fixture_id(*(contact->GetFixtureA())),
*(contact->GetFixtureA()->GetBody())};
physics::contact_participant participant_b{
get_entity_id(*(contact->GetFixtureB())),
get_fixture_id(*(contact->GetFixtureB())),
*(contact->GetFixtureB()->GetBody())};
on_collision(participant_a, participant_b);
}
}
template <typename c, typename s>
void contact_listener<c, s>::EndContact(b2Contact* contact)
{
if (contact)
{
physics::contact_participant participant_a{
get_entity_id(*(contact->GetFixtureA())),
get_fixture_id(*(contact->GetFixtureA())),
*(contact->GetFixtureA()->GetBody())};
physics::contact_participant participant_b{
get_entity_id(*(contact->GetFixtureB())),
get_fixture_id(*(contact->GetFixtureB())),
*(contact->GetFixtureB()->GetBody())};
on_separation(participant_a, participant_b);
}
}
static constexpr std::uint16_t group_index_offset = 1U;
} // anonyous namespace
template <class contact_category_t>
typename physics::fixture_def physics::make_fixture_def(
robocup2Dsim::runtime::ecs_db::entity_id_type entity_id,
fixture_id_type fixture_id,
contact_category_t category,
const contact_config<contact_category_t>& contact)
{
fixture_def result;
result.filter.categoryBits = 1U << static_cast<typename contact_config<contact_category_t>::category_underlying_type>(category);
result.filter.maskBits = contact.to_uint();
if (contact.get_from_same_entity_config() == contact_result::pass_over)
{
// to achieve pass over the groupIndex cannot be 0
result.filter.groupIndex = (entity_id + group_index_offset) * -1;
}
set_fixture_data(result, entity_id, fixture_id);
return result;
}
template <class joint_t, class def_t>
void physics::make_joint(const def_t& def)
{
joint_t* result = static_cast<joint_t*>(world_.CreateJoint(&def));
for (const fixture* fix = result->GetBodyA()->GetFixtureList(); fix != nullptr; fix = fix->GetNext())
{
if (fix != nullptr)
{
result->SetUserData(reinterpret_cast<void*>(static_cast<std::uintptr_t>(get_entity_id(*fix))));
break;
}
}
}
template <typename collision_func_t, typename separation_func_t>
void physics::step(float time_step, collision_func_t&& on_collision, separation_func_t&& on_separation)
{
contact_listener<collision_func_t, separation_func_t> listener(
std::forward<collision_func_t>(on_collision),
std::forward<separation_func_t>(on_separation));
world_.SetContactListener(&listener);
world_.Step(time_step, solver_conf_.velocity_iteration_limit, solver_conf_.position_iteration_limit);
world_.SetContactListener(nullptr);
}
} // namespace engine
} // namespace robocup2Dsim
#endif
<|endoftext|> |
<commit_before>#include "Element.h"
#include <iostream>
using namespace Eigen;
using namespace std;
namespace DrakeCollision {
Element::Element(const Isometry3d& T_element_to_local)
: DrakeShapes::Element(T_element_to_local) {
id = (ElementId) this;
}
Element::Element(const DrakeShapes::Geometry& geometry,
const Isometry3d& T_element_to_local)
: DrakeShapes::Element(geometry, T_element_to_local) {
id = (ElementId) this;
}
Element::Element(const Element& other)
: DrakeShapes::Element(other),
id(reinterpret_cast<ElementId>(this)),
body_(other.body_), is_static_(other.is_static_) {}
Element* Element::clone() const { return new Element(*this); }
ElementId Element::getId() const { return id; }
const RigidBody* Element::get_body() const { return body_; }
void Element::set_body(const RigidBody *body) { body_ = body; }
ostream& operator<<(ostream& out, const Element& ee) {
out << "DrakeCollision::Element:\n"
<< " - id = " << ee.id << "\n"
<< " - T_element_to_world =\n"
<< ee.T_element_to_world.matrix() << "\n"
<< " - T_element_to_local =\n"
<< ee.T_element_to_local.matrix() << "\n"
<< " - geometry = " << *ee.geometry << std::endl;
return out;
}
} // namespace DrakeCollision
<commit_msg>Fixes initialization order in Element constructor<commit_after>#include "Element.h"
#include <iostream>
using namespace Eigen;
using namespace std;
namespace DrakeCollision {
Element::Element(const Isometry3d& T_element_to_local)
: DrakeShapes::Element(T_element_to_local) {
id = (ElementId) this;
}
Element::Element(const DrakeShapes::Geometry& geometry,
const Isometry3d& T_element_to_local)
: DrakeShapes::Element(geometry, T_element_to_local) {
id = (ElementId) this;
}
Element::Element(const Element& other)
: DrakeShapes::Element(other),
id(reinterpret_cast<ElementId>(this)),
is_static_(other.is_static_), body_(other.body_) {}
Element* Element::clone() const { return new Element(*this); }
ElementId Element::getId() const { return id; }
const RigidBody* Element::get_body() const { return body_; }
void Element::set_body(const RigidBody *body) { body_ = body; }
ostream& operator<<(ostream& out, const Element& ee) {
out << "DrakeCollision::Element:\n"
<< " - id = " << ee.id << "\n"
<< " - T_element_to_world =\n"
<< ee.T_element_to_world.matrix() << "\n"
<< " - T_element_to_local =\n"
<< ee.T_element_to_local.matrix() << "\n"
<< " - geometry = " << *ee.geometry << std::endl;
return out;
}
} // namespace DrakeCollision
<|endoftext|> |
<commit_before>#/*##########################################################################
#
# The fisx library for X-Ray Fluorescence
#
# Copyright (c) 2014-2016 European Synchrotron Radiation Facility
#
# This file is part of the fisx X-ray developed by V.A. Sole
#
# 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 "fisx_detector.h"
#include <math.h>
#include <stdexcept>
namespace fisx
{
Detector::Detector(const std::string & name, const double & density, const double & thickness, \
const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
this->diameter = 0.0;
this->distance = 10.0;
this->escapePeakEnergyThreshold = 0.010,
this->escapePeakIntensityThreshold = 1.0e-7;
this->escapePeakNThreshold = 4;
this->escapePeakAlphaIn = 90.;
this->escapePeakCache.clear();
}
void Detector::setMaterial(const std::string & materialName)
{
this->escapePeakCache.clear();
this->Layer::setMaterial(materialName);
}
void Detector::setMaterial(const Material & material)
{
this->escapePeakCache.clear();
this->Layer::setMaterial(material);
}
void Detector::setMinimumEscapePeakEnergy(const double & energy)
{
this->escapePeakEnergyThreshold = energy;
this->escapePeakCache.clear();
}
void Detector::setMinimumEscapePeakIntensity(const double & intensity)
{
this->escapePeakIntensityThreshold = intensity;
this->escapePeakCache.clear();
}
void Detector::setMaximumNumberOfEscapePeaks(const int & nPeaks)
{
this->escapePeakNThreshold = nPeaks;
this->escapePeakCache.clear();
}
void Detector::clearEscapePeakCache()
{
this->escapePeakCache.clear();
}
double Detector::getActiveArea() const
{
double pi;
pi = acos(-1.0);
return (0.25 * pi) * (this->diameter * this->diameter);
}
void Detector::setActiveArea(const double & area)
{
double pi;
pi = acos(-1.0);
if (area < 0)
{
throw std::invalid_argument("Negative detector area");
}
this->diameter = 2.0 * sqrt(area/pi);
}
void Detector::setDiameter(const double & diameter)
{
if (diameter < 0)
{
throw std::invalid_argument("Negative detector diameter");
}
this->diameter = diameter;
}
void Detector::setDistance(const double & distance)
{
if (distance <= 0)
{
throw std::invalid_argument("Negative detector distance");
}
this->distance = distance;
}
const double & Detector::getDiameter() const
{
return this->diameter;
}
const double & Detector::getDistance() const
{
return this->distance;
}
std::map<std::string, std::map<std::string, double> > Detector::getEscape(const double & energy,
const Elements & elementsLibrary,
const std::string & label,
const int & update)
{
if (update != 0)
this->escapePeakCache.clear();
if (false) //(label.size())
{
if (this->escapePeakCache.find(label) == this->escapePeakCache.end())
{
// calculate it
this->escapePeakCache[label] = elementsLibrary.getEscape(this->getComposition(elementsLibrary), \
energy, \
this->escapePeakEnergyThreshold, \
this->escapePeakIntensityThreshold, \
this->escapePeakNThreshold, \
this->escapePeakAlphaIn,
this->getThickness());
}
return this->escapePeakCache[label];
}
else
{
return elementsLibrary.getEscape(this->getComposition(elementsLibrary), \
energy, \
this->escapePeakEnergyThreshold, \
this->escapePeakIntensityThreshold, \
this->escapePeakNThreshold, \
this->escapePeakAlphaIn,
this->getThickness());
}
}
} // namespace fisx
<commit_msg>Ignore detector cache and thickness in escape calculation.<commit_after>#/*##########################################################################
#
# The fisx library for X-Ray Fluorescence
#
# Copyright (c) 2014-2016 European Synchrotron Radiation Facility
#
# This file is part of the fisx X-ray developed by V.A. Sole
#
# 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 "fisx_detector.h"
#include <math.h>
#include <stdexcept>
namespace fisx
{
Detector::Detector(const std::string & name, const double & density, const double & thickness, \
const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
this->diameter = 0.0;
this->distance = 10.0;
this->escapePeakEnergyThreshold = 0.010,
this->escapePeakIntensityThreshold = 1.0e-7;
this->escapePeakNThreshold = 4;
this->escapePeakAlphaIn = 90.;
this->escapePeakCache.clear();
}
void Detector::setMaterial(const std::string & materialName)
{
this->escapePeakCache.clear();
this->Layer::setMaterial(materialName);
}
void Detector::setMaterial(const Material & material)
{
this->escapePeakCache.clear();
this->Layer::setMaterial(material);
}
void Detector::setMinimumEscapePeakEnergy(const double & energy)
{
this->escapePeakEnergyThreshold = energy;
this->escapePeakCache.clear();
}
void Detector::setMinimumEscapePeakIntensity(const double & intensity)
{
this->escapePeakIntensityThreshold = intensity;
this->escapePeakCache.clear();
}
void Detector::setMaximumNumberOfEscapePeaks(const int & nPeaks)
{
this->escapePeakNThreshold = nPeaks;
this->escapePeakCache.clear();
}
void Detector::clearEscapePeakCache()
{
this->escapePeakCache.clear();
}
double Detector::getActiveArea() const
{
double pi;
pi = acos(-1.0);
return (0.25 * pi) * (this->diameter * this->diameter);
}
void Detector::setActiveArea(const double & area)
{
double pi;
pi = acos(-1.0);
if (area < 0)
{
throw std::invalid_argument("Negative detector area");
}
this->diameter = 2.0 * sqrt(area/pi);
}
void Detector::setDiameter(const double & diameter)
{
if (diameter < 0)
{
throw std::invalid_argument("Negative detector diameter");
}
this->diameter = diameter;
}
void Detector::setDistance(const double & distance)
{
if (distance <= 0)
{
throw std::invalid_argument("Negative detector distance");
}
this->distance = distance;
}
const double & Detector::getDiameter() const
{
return this->diameter;
}
const double & Detector::getDistance() const
{
return this->distance;
}
std::map<std::string, std::map<std::string, double> > Detector::getEscape(const double & energy,
const Elements & elementsLibrary,
const std::string & label,
const int & update)
{
if (update != 0)
this->escapePeakCache.clear();
if (false) //(label.size())
{
if (this->escapePeakCache.find(label) == this->escapePeakCache.end())
{
// calculate it
this->escapePeakCache[label] = elementsLibrary.getEscape(this->getComposition(elementsLibrary), \
energy, \
this->escapePeakEnergyThreshold, \
this->escapePeakIntensityThreshold, \
this->escapePeakNThreshold, \
this->escapePeakAlphaIn,
0);
}
return this->escapePeakCache[label];
}
else
{
return elementsLibrary.getEscape(this->getComposition(elementsLibrary), \
energy, \
this->escapePeakEnergyThreshold, \
this->escapePeakIntensityThreshold, \
this->escapePeakNThreshold, \
this->escapePeakAlphaIn,
0);
}
}
} // namespace fisx
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "ast.h"
void
ast_type_specifier::print(void) const
{
if (structure) {
structure->print();
} else {
printf("%s ", type_name);
}
if (array_specifier) {
array_specifier->print();
}
}
bool
ast_fully_specified_type::has_qualifiers() const
{
return this->qualifier.flags.i != 0;
}
bool ast_type_qualifier::has_interpolation() const
{
return this->flags.q.smooth
|| this->flags.q.flat
|| this->flags.q.noperspective;
}
bool
ast_type_qualifier::has_layout() const
{
return this->flags.q.origin_upper_left
|| this->flags.q.pixel_center_integer
|| this->flags.q.depth_any
|| this->flags.q.depth_greater
|| this->flags.q.depth_less
|| this->flags.q.depth_unchanged
|| this->flags.q.std140
|| this->flags.q.shared
|| this->flags.q.column_major
|| this->flags.q.row_major
|| this->flags.q.packed
|| this->flags.q.explicit_location
|| this->flags.q.explicit_index
|| this->flags.q.explicit_binding
|| this->flags.q.explicit_offset;
}
bool
ast_type_qualifier::has_storage() const
{
return this->flags.q.constant
|| this->flags.q.attribute
|| this->flags.q.varying
|| this->flags.q.in
|| this->flags.q.out
|| this->flags.q.uniform;
}
bool
ast_type_qualifier::has_auxiliary_storage() const
{
return this->flags.q.centroid
|| this->flags.q.sample;
}
const char*
ast_type_qualifier::interpolation_string() const
{
if (this->flags.q.smooth)
return "smooth";
else if (this->flags.q.flat)
return "flat";
else if (this->flags.q.noperspective)
return "noperspective";
else
return NULL;
}
bool
ast_type_qualifier::merge_qualifier(YYLTYPE *loc,
_mesa_glsl_parse_state *state,
ast_type_qualifier q)
{
ast_type_qualifier ubo_mat_mask;
ubo_mat_mask.flags.i = 0;
ubo_mat_mask.flags.q.row_major = 1;
ubo_mat_mask.flags.q.column_major = 1;
ast_type_qualifier ubo_layout_mask;
ubo_layout_mask.flags.i = 0;
ubo_layout_mask.flags.q.std140 = 1;
ubo_layout_mask.flags.q.packed = 1;
ubo_layout_mask.flags.q.shared = 1;
ast_type_qualifier ubo_binding_mask;
ubo_binding_mask.flags.i = 0;
ubo_binding_mask.flags.q.explicit_binding = 1;
ubo_binding_mask.flags.q.explicit_offset = 1;
/* Uniform block layout qualifiers get to overwrite each
* other (rightmost having priority), while all other
* qualifiers currently don't allow duplicates.
*/
if ((this->flags.i & q.flags.i & ~(ubo_mat_mask.flags.i |
ubo_layout_mask.flags.i |
ubo_binding_mask.flags.i)) != 0) {
_mesa_glsl_error(loc, state,
"duplicate layout qualifiers used");
return false;
}
if (q.flags.q.prim_type) {
if (this->flags.q.prim_type && this->prim_type != q.prim_type) {
_mesa_glsl_error(loc, state,
"conflicting primitive type qualifiers used");
return false;
}
this->prim_type = q.prim_type;
}
if (q.flags.q.max_vertices) {
if (this->flags.q.max_vertices && this->max_vertices != q.max_vertices) {
_mesa_glsl_error(loc, state,
"geometry shader set conflicting max_vertices "
"(%d and %d)", this->max_vertices, q.max_vertices);
return false;
}
this->max_vertices = q.max_vertices;
}
if ((q.flags.i & ubo_mat_mask.flags.i) != 0)
this->flags.i &= ~ubo_mat_mask.flags.i;
if ((q.flags.i & ubo_layout_mask.flags.i) != 0)
this->flags.i &= ~ubo_layout_mask.flags.i;
for (int i = 0; i < 3; i++) {
if (q.flags.q.local_size & (1 << i)) {
if ((this->flags.q.local_size & (1 << i)) &&
this->local_size[i] != q.local_size[i]) {
_mesa_glsl_error(loc, state,
"compute shader set conflicting values for "
"local_size_%c (%d and %d)", 'x' + i,
this->local_size[i], q.local_size[i]);
return false;
}
this->local_size[i] = q.local_size[i];
}
}
this->flags.i |= q.flags.i;
if (q.flags.q.explicit_location)
this->location = q.location;
if (q.flags.q.explicit_index)
this->index = q.index;
if (q.flags.q.explicit_binding)
this->binding = q.binding;
if (q.flags.q.explicit_offset)
this->offset = q.offset;
if (q.precision != ast_precision_none)
this->precision = q.precision;
if (q.flags.q.explicit_image_format) {
this->image_format = q.image_format;
this->image_base_type = q.image_base_type;
}
return true;
}
bool
ast_type_qualifier::merge_in_qualifier(YYLTYPE *loc,
_mesa_glsl_parse_state *state,
ast_type_qualifier q,
ast_node* &node)
{
void *mem_ctx = state;
bool create_gs_ast = false;
bool create_cs_ast = false;
ast_type_qualifier valid_in_mask;
valid_in_mask.flags.i = 0;
switch (state->stage) {
case MESA_SHADER_GEOMETRY:
if (q.flags.q.prim_type) {
/* Make sure this is a valid input primitive type. */
switch (q.prim_type) {
case GL_POINTS:
case GL_LINES:
case GL_LINES_ADJACENCY:
case GL_TRIANGLES:
case GL_TRIANGLES_ADJACENCY:
break;
default:
_mesa_glsl_error(loc, state,
"invalid geometry shader input primitive type");
break;
}
}
create_gs_ast |=
q.flags.q.prim_type &&
!state->in_qualifier->flags.q.prim_type;
valid_in_mask.flags.q.prim_type = 1;
valid_in_mask.flags.q.invocations = 1;
break;
case MESA_SHADER_FRAGMENT:
if (q.flags.q.early_fragment_tests) {
state->early_fragment_tests = true;
} else {
_mesa_glsl_error(loc, state, "invalid input layout qualifier");
}
break;
case MESA_SHADER_COMPUTE:
create_cs_ast |=
q.flags.q.local_size != 0 &&
state->in_qualifier->flags.q.local_size == 0;
valid_in_mask.flags.q.local_size = 1;
break;
default:
_mesa_glsl_error(loc, state,
"input layout qualifiers only valid in "
"geometry, fragment and compute shaders");
break;
}
/* Generate an error when invalid input layout qualifiers are used. */
if ((q.flags.i & ~valid_in_mask.flags.i) != 0) {
_mesa_glsl_error(loc, state,
"invalid input layout qualifiers used");
return false;
}
/* Input layout qualifiers can be specified multiple
* times in separate declarations, as long as they match.
*/
if (this->flags.q.prim_type) {
if (q.flags.q.prim_type &&
this->prim_type != q.prim_type) {
_mesa_glsl_error(loc, state,
"conflicting input primitive types specified");
}
} else if (q.flags.q.prim_type) {
state->in_qualifier->flags.q.prim_type = 1;
state->in_qualifier->prim_type = q.prim_type;
}
if (this->flags.q.invocations &&
q.flags.q.invocations &&
this->invocations != q.invocations) {
_mesa_glsl_error(loc, state,
"conflicting invocations counts specified");
return false;
} else if (q.flags.q.invocations) {
this->flags.q.invocations = 1;
this->invocations = q.invocations;
}
if (create_gs_ast) {
node = new(mem_ctx) ast_gs_input_layout(*loc, q.prim_type);
} else if (create_cs_ast) {
/* Infer a local_size of 1 for every unspecified dimension */
unsigned local_size[3];
for (int i = 0; i < 3; i++) {
if (q.flags.q.local_size & (1 << i))
local_size[i] = q.local_size[i];
else
local_size[i] = 1;
}
node = new(mem_ctx) ast_cs_input_layout(*loc, local_size);
}
return true;
}
<commit_msg>glsl/cs: Fix local_size_y and local_size_z<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "ast.h"
void
ast_type_specifier::print(void) const
{
if (structure) {
structure->print();
} else {
printf("%s ", type_name);
}
if (array_specifier) {
array_specifier->print();
}
}
bool
ast_fully_specified_type::has_qualifiers() const
{
return this->qualifier.flags.i != 0;
}
bool ast_type_qualifier::has_interpolation() const
{
return this->flags.q.smooth
|| this->flags.q.flat
|| this->flags.q.noperspective;
}
bool
ast_type_qualifier::has_layout() const
{
return this->flags.q.origin_upper_left
|| this->flags.q.pixel_center_integer
|| this->flags.q.depth_any
|| this->flags.q.depth_greater
|| this->flags.q.depth_less
|| this->flags.q.depth_unchanged
|| this->flags.q.std140
|| this->flags.q.shared
|| this->flags.q.column_major
|| this->flags.q.row_major
|| this->flags.q.packed
|| this->flags.q.explicit_location
|| this->flags.q.explicit_index
|| this->flags.q.explicit_binding
|| this->flags.q.explicit_offset;
}
bool
ast_type_qualifier::has_storage() const
{
return this->flags.q.constant
|| this->flags.q.attribute
|| this->flags.q.varying
|| this->flags.q.in
|| this->flags.q.out
|| this->flags.q.uniform;
}
bool
ast_type_qualifier::has_auxiliary_storage() const
{
return this->flags.q.centroid
|| this->flags.q.sample;
}
const char*
ast_type_qualifier::interpolation_string() const
{
if (this->flags.q.smooth)
return "smooth";
else if (this->flags.q.flat)
return "flat";
else if (this->flags.q.noperspective)
return "noperspective";
else
return NULL;
}
bool
ast_type_qualifier::merge_qualifier(YYLTYPE *loc,
_mesa_glsl_parse_state *state,
ast_type_qualifier q)
{
ast_type_qualifier ubo_mat_mask;
ubo_mat_mask.flags.i = 0;
ubo_mat_mask.flags.q.row_major = 1;
ubo_mat_mask.flags.q.column_major = 1;
ast_type_qualifier ubo_layout_mask;
ubo_layout_mask.flags.i = 0;
ubo_layout_mask.flags.q.std140 = 1;
ubo_layout_mask.flags.q.packed = 1;
ubo_layout_mask.flags.q.shared = 1;
ast_type_qualifier ubo_binding_mask;
ubo_binding_mask.flags.i = 0;
ubo_binding_mask.flags.q.explicit_binding = 1;
ubo_binding_mask.flags.q.explicit_offset = 1;
/* Uniform block layout qualifiers get to overwrite each
* other (rightmost having priority), while all other
* qualifiers currently don't allow duplicates.
*/
if ((this->flags.i & q.flags.i & ~(ubo_mat_mask.flags.i |
ubo_layout_mask.flags.i |
ubo_binding_mask.flags.i)) != 0) {
_mesa_glsl_error(loc, state,
"duplicate layout qualifiers used");
return false;
}
if (q.flags.q.prim_type) {
if (this->flags.q.prim_type && this->prim_type != q.prim_type) {
_mesa_glsl_error(loc, state,
"conflicting primitive type qualifiers used");
return false;
}
this->prim_type = q.prim_type;
}
if (q.flags.q.max_vertices) {
if (this->flags.q.max_vertices && this->max_vertices != q.max_vertices) {
_mesa_glsl_error(loc, state,
"geometry shader set conflicting max_vertices "
"(%d and %d)", this->max_vertices, q.max_vertices);
return false;
}
this->max_vertices = q.max_vertices;
}
if ((q.flags.i & ubo_mat_mask.flags.i) != 0)
this->flags.i &= ~ubo_mat_mask.flags.i;
if ((q.flags.i & ubo_layout_mask.flags.i) != 0)
this->flags.i &= ~ubo_layout_mask.flags.i;
for (int i = 0; i < 3; i++) {
if (q.flags.q.local_size & (1 << i)) {
if ((this->flags.q.local_size & (1 << i)) &&
this->local_size[i] != q.local_size[i]) {
_mesa_glsl_error(loc, state,
"compute shader set conflicting values for "
"local_size_%c (%d and %d)", 'x' + i,
this->local_size[i], q.local_size[i]);
return false;
}
this->local_size[i] = q.local_size[i];
}
}
this->flags.i |= q.flags.i;
if (q.flags.q.explicit_location)
this->location = q.location;
if (q.flags.q.explicit_index)
this->index = q.index;
if (q.flags.q.explicit_binding)
this->binding = q.binding;
if (q.flags.q.explicit_offset)
this->offset = q.offset;
if (q.precision != ast_precision_none)
this->precision = q.precision;
if (q.flags.q.explicit_image_format) {
this->image_format = q.image_format;
this->image_base_type = q.image_base_type;
}
return true;
}
bool
ast_type_qualifier::merge_in_qualifier(YYLTYPE *loc,
_mesa_glsl_parse_state *state,
ast_type_qualifier q,
ast_node* &node)
{
void *mem_ctx = state;
bool create_gs_ast = false;
bool create_cs_ast = false;
ast_type_qualifier valid_in_mask;
valid_in_mask.flags.i = 0;
switch (state->stage) {
case MESA_SHADER_GEOMETRY:
if (q.flags.q.prim_type) {
/* Make sure this is a valid input primitive type. */
switch (q.prim_type) {
case GL_POINTS:
case GL_LINES:
case GL_LINES_ADJACENCY:
case GL_TRIANGLES:
case GL_TRIANGLES_ADJACENCY:
break;
default:
_mesa_glsl_error(loc, state,
"invalid geometry shader input primitive type");
break;
}
}
create_gs_ast |=
q.flags.q.prim_type &&
!state->in_qualifier->flags.q.prim_type;
valid_in_mask.flags.q.prim_type = 1;
valid_in_mask.flags.q.invocations = 1;
break;
case MESA_SHADER_FRAGMENT:
if (q.flags.q.early_fragment_tests) {
state->early_fragment_tests = true;
} else {
_mesa_glsl_error(loc, state, "invalid input layout qualifier");
}
break;
case MESA_SHADER_COMPUTE:
create_cs_ast |=
q.flags.q.local_size != 0 &&
state->in_qualifier->flags.q.local_size == 0;
valid_in_mask.flags.q.local_size = 7;
break;
default:
_mesa_glsl_error(loc, state,
"input layout qualifiers only valid in "
"geometry, fragment and compute shaders");
break;
}
/* Generate an error when invalid input layout qualifiers are used. */
if ((q.flags.i & ~valid_in_mask.flags.i) != 0) {
_mesa_glsl_error(loc, state,
"invalid input layout qualifiers used");
return false;
}
/* Input layout qualifiers can be specified multiple
* times in separate declarations, as long as they match.
*/
if (this->flags.q.prim_type) {
if (q.flags.q.prim_type &&
this->prim_type != q.prim_type) {
_mesa_glsl_error(loc, state,
"conflicting input primitive types specified");
}
} else if (q.flags.q.prim_type) {
state->in_qualifier->flags.q.prim_type = 1;
state->in_qualifier->prim_type = q.prim_type;
}
if (this->flags.q.invocations &&
q.flags.q.invocations &&
this->invocations != q.invocations) {
_mesa_glsl_error(loc, state,
"conflicting invocations counts specified");
return false;
} else if (q.flags.q.invocations) {
this->flags.q.invocations = 1;
this->invocations = q.invocations;
}
if (create_gs_ast) {
node = new(mem_ctx) ast_gs_input_layout(*loc, q.prim_type);
} else if (create_cs_ast) {
/* Infer a local_size of 1 for every unspecified dimension */
unsigned local_size[3];
for (int i = 0; i < 3; i++) {
if (q.flags.q.local_size & (1 << i))
local_size[i] = q.local_size[i];
else
local_size[i] = 1;
}
node = new(mem_ctx) ast_cs_input_layout(*loc, local_size);
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: [email protected] (Keith Ray)
#include <gtest/internal/gtest-filepath.h>
#include <gtest/internal/gtest-port.h>
#include <stdlib.h>
#ifdef _WIN32_WCE
#include <windows.h>
#elif defined(GTEST_OS_WINDOWS)
#include <direct.h>
#include <io.h>
#include <sys/stat.h>
#elif defined(GTEST_OS_SYMBIAN)
// Symbian OpenC has PATH_MAX in sys/syslimits.h
#include <sys/syslimits.h>
#include <unistd.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif // _WIN32_WCE or _WIN32
#include <gtest/internal/gtest-string.h>
namespace testing {
namespace internal {
#ifdef GTEST_OS_WINDOWS
const char kPathSeparator = '\\';
const char kPathSeparatorString[] = "\\";
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
#else
const char kCurrentDirectoryString[] = ".\\";
#endif // _WIN32_WCE
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif defined(GTEST_OS_WINDOWS)
char cwd[_MAX_PATH + 1] = {};
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
char cwd[PATH_MAX + 1] = {};
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#endif
}
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension));
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
return FilePath(String(pathname_.c_str(), pathname_.GetLength() - 4));
}
return *this;
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return last_sep ? FilePath(String(last_sep + 1)) : *this;
}
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return FilePath(last_sep ? String(c_str(), last_sep + 1 - c_str())
: String(kCurrentDirectoryString));
}
// Helper functions for naming files in a directory for xml output.
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension) {
FilePath dir(directory.RemoveTrailingPathSeparator());
if (number == 0) {
return FilePath(String::Format("%s%c%s.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), extension));
}
return FilePath(String::Format("%s%c%s_%d.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), number, extension));
}
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#ifdef GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
return attributes != kInvalidFileAttributes;
#else
struct _stat file_stat = {};
return _stat(pathname_.c_str(), &file_stat) == 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
return stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS
}
// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#ifdef GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this :
RemoveTrailingPathSeparator());
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true;
}
#else
struct _stat file_stat = {};
result = _stat(path.c_str(), &file_stat) == 0 &&
(_S_IFDIR & file_stat.st_mode) != 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
result = stat(pathname_.c_str(), &file_stat) == 0 &&
S_ISDIR(file_stat.st_mode);
#endif // GTEST_OS_WINDOWS
return result;
}
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
#ifdef GTEST_OS_WINDOWS
const char* const name = pathname_.c_str();
return pathname_.GetLength() == 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' &&
name[2] == kPathSeparator;
#else
return pathname_ == kPathSeparatorString;
#endif
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension) {
FilePath full_pathname;
int number = 0;
do {
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
} while (full_pathname.FileOrDirectoryExists());
return full_pathname;
}
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
return pathname_.EndsWith(kPathSeparatorString);
}
// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
if (!this->IsDirectory()) {
return false;
}
if (pathname_.GetLength() == 0 || this->DirectoryExists()) {
return true;
}
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#ifdef GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
delete [] unicode;
#else
int result = _mkdir(pathname_.c_str());
#endif // !WIN32_WCE
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // _WIN32
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return pathname_.EndsWith(kPathSeparatorString)
? FilePath(String(pathname_.c_str(), pathname_.GetLength() - 1))
: *this;
}
// Normalize removes any redundant separators that might be in the pathname.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
if (pathname_.c_str() == NULL) {
pathname_ = "";
return;
}
const char* src = pathname_.c_str();
char* const dest = new char[pathname_.GetLength() + 1];
char* dest_ptr = dest;
memset(dest_ptr, 0, pathname_.GetLength() + 1);
while (*src != '\0') {
*dest_ptr++ = *src;
if (*src != kPathSeparator)
src++;
else
while (*src == kPathSeparator)
src++;
}
*dest_ptr = '\0';
pathname_ = dest;
delete[] dest;
}
} // namespace internal
} // namespace testing
<commit_msg>On some Linux distros, you need to explicitly #include <limits.h> to get the definition of PATH_MAX. This patch adds it in the appropriate place.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: [email protected] (Keith Ray)
#include <gtest/internal/gtest-filepath.h>
#include <gtest/internal/gtest-port.h>
#include <stdlib.h>
#ifdef _WIN32_WCE
#include <windows.h>
#elif defined(GTEST_OS_WINDOWS)
#include <direct.h>
#include <io.h>
#include <sys/stat.h>
#elif defined(GTEST_OS_SYMBIAN)
// Symbian OpenC has PATH_MAX in sys/syslimits.h
#include <sys/syslimits.h>
#include <unistd.h>
#else
#include <limits.h>
#include <sys/stat.h>
#include <unistd.h>
#endif // _WIN32_WCE or _WIN32
#include <gtest/internal/gtest-string.h>
namespace testing {
namespace internal {
#ifdef GTEST_OS_WINDOWS
const char kPathSeparator = '\\';
const char kPathSeparatorString[] = "\\";
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
#else
const char kCurrentDirectoryString[] = ".\\";
#endif // _WIN32_WCE
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
#ifdef _WIN32_WCE
// Windows CE doesn't have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif defined(GTEST_OS_WINDOWS)
char cwd[_MAX_PATH + 1] = {};
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
char cwd[PATH_MAX + 1] = {};
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#endif
}
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension));
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
return FilePath(String(pathname_.c_str(), pathname_.GetLength() - 4));
}
return *this;
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return last_sep ? FilePath(String(last_sep + 1)) : *this;
}
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return FilePath(last_sep ? String(c_str(), last_sep + 1 - c_str())
: String(kCurrentDirectoryString));
}
// Helper functions for naming files in a directory for xml output.
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension) {
FilePath dir(directory.RemoveTrailingPathSeparator());
if (number == 0) {
return FilePath(String::Format("%s%c%s.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), extension));
}
return FilePath(String::Format("%s%c%s_%d.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), number, extension));
}
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#ifdef GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
return attributes != kInvalidFileAttributes;
#else
struct _stat file_stat = {};
return _stat(pathname_.c_str(), &file_stat) == 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
return stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS
}
// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#ifdef GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this :
RemoveTrailingPathSeparator());
#ifdef _WIN32_WCE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true;
}
#else
struct _stat file_stat = {};
result = _stat(path.c_str(), &file_stat) == 0 &&
(_S_IFDIR & file_stat.st_mode) != 0;
#endif // _WIN32_WCE
#else
struct stat file_stat = {};
result = stat(pathname_.c_str(), &file_stat) == 0 &&
S_ISDIR(file_stat.st_mode);
#endif // GTEST_OS_WINDOWS
return result;
}
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
#ifdef GTEST_OS_WINDOWS
const char* const name = pathname_.c_str();
return pathname_.GetLength() == 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' &&
name[2] == kPathSeparator;
#else
return pathname_ == kPathSeparatorString;
#endif
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension) {
FilePath full_pathname;
int number = 0;
do {
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
} while (full_pathname.FileOrDirectoryExists());
return full_pathname;
}
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
return pathname_.EndsWith(kPathSeparatorString);
}
// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
if (!this->IsDirectory()) {
return false;
}
if (pathname_.GetLength() == 0 || this->DirectoryExists()) {
return true;
}
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#ifdef GTEST_OS_WINDOWS
#ifdef _WIN32_WCE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
delete [] unicode;
#else
int result = _mkdir(pathname_.c_str());
#endif // !WIN32_WCE
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // _WIN32
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return pathname_.EndsWith(kPathSeparatorString)
? FilePath(String(pathname_.c_str(), pathname_.GetLength() - 1))
: *this;
}
// Normalize removes any redundant separators that might be in the pathname.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
if (pathname_.c_str() == NULL) {
pathname_ = "";
return;
}
const char* src = pathname_.c_str();
char* const dest = new char[pathname_.GetLength() + 1];
char* dest_ptr = dest;
memset(dest_ptr, 0, pathname_.GetLength() + 1);
while (*src != '\0') {
*dest_ptr++ = *src;
if (*src != kPathSeparator)
src++;
else
while (*src == kPathSeparator)
src++;
}
*dest_ptr = '\0';
pathname_ = dest;
delete[] dest;
}
} // namespace internal
} // namespace testing
<|endoftext|> |
<commit_before>//
// Created by dar on 1/25/16.
//
#include "GuiButton.h"
GuiButton::GuiButton(double x, double y, double width, double height) {
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
bool GuiButton::onClick(int action, float x, float y) {
if (onClickListener == NULL) return false;
return onClickListener(action, x, y);
}
void GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
this->onClickListener = onClickListener;
}<commit_msg>Added comments<commit_after>//
// Created by dar on 1/25/16.
//
#include "GuiButton.h"
GuiButton::GuiButton(double x, double y, double width, double height) { //TODO add some "placement" flag (TOP-RIGHT, MIDDLE-RIGHT, BOTTOM-RIGHT, etc.)
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
bool GuiButton::onClick(int action, float x, float y) {
if (onClickListener == NULL) return false;
return onClickListener(action, x, y);
}
void GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
this->onClickListener = onClickListener;
}<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld, Ash Berlin
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 "flusspferd/io/file_class.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include <boost/scoped_array.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace flusspferd;
using namespace flusspferd::io;
class file_class::impl {
public:
std::fstream stream;
static void create(char const *name, boost::optional<int> mode);
static bool exists(char const *name);
};
file_class::file_class(object const &obj, call_context &x)
: stream_base(obj, 0), p(new impl)
{
set_streambuf(p->stream.rdbuf());
if (!x.arg.empty()) {
string name = x.arg[0].to_string();
open(name.c_str());
}
register_native_method("open", &file_class::open);
register_native_method("close", &file_class::close);
}
file_class::~file_class()
{}
void file_class::class_info::augment_constructor(object constructor) {
create_native_function(constructor, "create", &impl::create);
}
object file_class::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object(flusspferd::get_prototype<stream_base>());
create_native_method(proto, "open", 1);
create_native_method(proto, "close", 0);
create_native_method(proto, "exists", 0);
return proto;
}
void file_class::open(char const *name) {
security &sec = security::get();
if (!sec.check_path(name, security::READ_WRITE))
throw exception("Could not open file (security)");
p->stream.open(name);
define_property("fileName", string(name),
permanent_property | read_only_property );
if (!p->stream)
// TODO: Include some sort of system error message here
throw exception("Could not open file");
}
void file_class::close() {
p->stream.close();
delete_property("fileName");
}
void file_class::impl::create(char const *name, boost::optional<int> mode) {
security &sec = security::get();
if (!sec.check_path(name, security::CREATE))
throw exception("Could not create file (security)");
if (creat(name, mode.get_value_or(0666)) < 0)
throw exception("Could not create file");
}
bool file_class::impl::exists(char const *name) {
return boost::filesystem::exists(name);
}
<commit_msg>IO/File: exists doesn't belong on prototype (And this time remove it from the proto not the ctor)<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld, Ash Berlin
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 "flusspferd/io/file_class.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include <boost/scoped_array.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace flusspferd;
using namespace flusspferd::io;
class file_class::impl {
public:
std::fstream stream;
static void create(char const *name, boost::optional<int> mode);
static bool exists(char const *name);
};
file_class::file_class(object const &obj, call_context &x)
: stream_base(obj, 0), p(new impl)
{
set_streambuf(p->stream.rdbuf());
if (!x.arg.empty()) {
string name = x.arg[0].to_string();
open(name.c_str());
}
register_native_method("open", &file_class::open);
register_native_method("close", &file_class::close);
}
file_class::~file_class()
{}
void file_class::class_info::augment_constructor(object constructor) {
create_native_function(constructor, "create", &impl::create);
create_native_function(constructor, "exists", &impl::exists);
}
object file_class::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object(flusspferd::get_prototype<stream_base>());
create_native_method(proto, "open", 1);
create_native_method(proto, "close", 0);
return proto;
}
void file_class::open(char const *name) {
security &sec = security::get();
if (!sec.check_path(name, security::READ_WRITE))
throw exception("Could not open file (security)");
p->stream.open(name);
define_property("fileName", string(name),
permanent_property | read_only_property );
if (!p->stream)
// TODO: Include some sort of system error message here
throw exception("Could not open file");
}
void file_class::close() {
p->stream.close();
delete_property("fileName");
}
void file_class::impl::create(char const *name, boost::optional<int> mode) {
security &sec = security::get();
if (!sec.check_path(name, security::CREATE))
throw exception("Could not create file (security)");
if (creat(name, mode.get_value_or(0666)) < 0)
throw exception("Could not create file");
}
bool file_class::impl::exists(char const *name) {
return boost::filesystem::exists(name);
}
<|endoftext|> |
<commit_before>#include "keymap_manager.hh"
#include "array_view.hh"
#include "assert.hh"
#include <algorithm>
namespace Kakoune
{
void KeymapManager::map_key(Key key, KeymapMode mode,
KeyList mapping, String docstring)
{
m_mapping[KeyAndMode{key, mode}] = {std::move(mapping), std::move(docstring)};
}
void KeymapManager::unmap_key(Key key, KeymapMode mode)
{
m_mapping.unordered_remove(KeyAndMode{key, mode});
}
bool KeymapManager::is_mapped(Key key, KeymapMode mode) const
{
return m_mapping.find(KeyAndMode{key, mode}) != m_mapping.end() or
(m_parent and m_parent->is_mapped(key, mode));
}
const KeymapManager::KeyMapInfo&
KeymapManager::get_mapping(Key key, KeymapMode mode) const
{
auto it = m_mapping.find(KeyAndMode{key, mode});
if (it != m_mapping.end())
return it->value;
kak_assert(m_parent);
return m_parent->get_mapping(key, mode);
}
KeymapManager::KeyList KeymapManager::get_mapped_keys(KeymapMode mode) const
{
KeyList res;
if (m_parent)
res = m_parent->get_mapped_keys(mode);
for (auto& map : m_mapping)
{
if (map.key.second == mode)
res.emplace_back(map.key.first);
}
std::sort(res.begin(), res.end());
res.erase(std::unique(res.begin(), res.end()), res.end());
return res;
}
}
<commit_msg>Preserve order of definition of mappings when listing them<commit_after>#include "keymap_manager.hh"
#include "array_view.hh"
#include "assert.hh"
#include <algorithm>
namespace Kakoune
{
void KeymapManager::map_key(Key key, KeymapMode mode,
KeyList mapping, String docstring)
{
m_mapping[KeyAndMode{key, mode}] = {std::move(mapping), std::move(docstring)};
}
void KeymapManager::unmap_key(Key key, KeymapMode mode)
{
m_mapping.remove(KeyAndMode{key, mode});
}
bool KeymapManager::is_mapped(Key key, KeymapMode mode) const
{
return m_mapping.find(KeyAndMode{key, mode}) != m_mapping.end() or
(m_parent and m_parent->is_mapped(key, mode));
}
const KeymapManager::KeyMapInfo&
KeymapManager::get_mapping(Key key, KeymapMode mode) const
{
auto it = m_mapping.find(KeyAndMode{key, mode});
if (it != m_mapping.end())
return it->value;
kak_assert(m_parent);
return m_parent->get_mapping(key, mode);
}
KeymapManager::KeyList KeymapManager::get_mapped_keys(KeymapMode mode) const
{
KeyList res;
if (m_parent)
res = m_parent->get_mapped_keys(mode);
for (auto& map : m_mapping)
{
if (map.key.second == mode and not contains(res, map.key.first))
res.emplace_back(map.key.first);
}
return res;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002 William Lachance ([email protected])
* Copyright (C) 2002-2004 Marc Maurer ([email protected])
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwps.sourceforge.net
*/
#include <string.h>
#include "libwps_internal.h"
#include "WPSHeader.h"
using namespace libwps;
WPSHeader::WPSHeader(RVNGInputStreamPtr &input, RVNGInputStreamPtr &fileInput, uint8_t majorVersion, WPSKind kind, WPSCreator creator) :
m_input(input), m_fileInput(fileInput), m_majorVersion(majorVersion), m_kind(kind), m_creator(creator),
m_needEncodingFlag(false)
{
}
WPSHeader::~WPSHeader()
{
}
/**
* So far, we have identified three categories of Works documents.
*
* Works documents versions 3 and later use a MS OLE container, so we detect
* their type by checking for OLE stream names. Works version 2 is like
* Works 3 without OLE, so those two types use the same parser.
*
*/
WPSHeader *WPSHeader::constructHeader(RVNGInputStreamPtr &input)
{
if (!input->isStructured())
{
input->seek(0, librevenge::RVNG_SEEK_SET);
uint8_t val[6];
for (int i=0; i<6; ++i) val[i] = libwps::readU8(input);
if (val[0] < 6 && val[1] == 0xFE)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v2 format detected\n"));
return new WPSHeader(input, input, 2);
}
// works1 dos file begin by 2054
if ((val[0] == 0xFF || val[0] == 0x20) && val[1]==0x54)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works wks database\n"));
return new WPSHeader(input, input, 1, WPS_DATABASE);
}
if (val[0] == 0xFF && val[1] == 0 && val[2]==2)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works wks detected\n"));
return new WPSHeader(input, input, 3, WPS_SPREADSHEET);
}
if (val[0] == 00 && val[1] == 0 && val[2]==2)
{
if (val[3]==0 && (val[4]==0x20 || val[4]==0x21) && val[5]==0x51)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Quattro Pro wq1 or wq2 detected\n"));
return new WPSHeader(input, input, 2, WPS_SPREADSHEET, WPS_QUATTRO_PRO);
}
WPS_DEBUG_MSG(("WPSHeader::constructHeader: potential Lotus|Microsft Works|Quattro Pro spreadsheet detected\n"));
return new WPSHeader(input, input, 2, WPS_SPREADSHEET);
}
if (val[0] == 00 && val[1] == 0x0 && val[2]==0x1a)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Lotus spreadsheet detected\n"));
return new WPSHeader(input, input, 101, WPS_SPREADSHEET, WPS_LOTUS);
}
if ((val[0] == 0x31 || val[0] == 0x32) && val[1] == 0xbe && val[2] == 0 && val[3] == 0 && val[4] == 0 && val[5] == 0xab)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Write detected\n"));
return new WPSHeader(input, input, 3, WPS_TEXT, WPS_MSWRITE);
}
return 0;
}
RVNGInputStreamPtr document_mn0(input->getSubStreamByName("MN0"));
if (document_mn0)
{
// can be a mac or a pc document
// each must contains a MM Ole which begins by 0x444e: Mac or 0x4e44: PC
RVNGInputStreamPtr document_mm(input->getSubStreamByName("MM"));
if (document_mm && libwps::readU16(document_mm) == 0x4e44)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works Mac v4 format detected\n"));
return 0;
}
// now, look if this is a database document
uint16_t fileMagic=libwps::readU16(document_mn0);
if (fileMagic == 0x54FF)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works Database format detected\n"));
return new WPSHeader(document_mn0, input, 4, WPS_DATABASE);
}
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v4 format detected\n"));
return new WPSHeader(document_mn0, input, 4);
}
RVNGInputStreamPtr document_contents(input->getSubStreamByName("CONTENTS"));
if (document_contents)
{
/* check the Works 2000/7/8 format magic */
document_contents->seek(0, librevenge::RVNG_SEEK_SET);
char fileMagic[8];
for (int i=0; i<7 && !document_contents->isEnd(); i++)
fileMagic[i] = char(libwps::readU8(document_contents.get()));
fileMagic[7] = '\0';
/* Works 7/8 */
if (0 == strcmp(fileMagic, "CHNKWKS"))
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v8 (maybe 7) format detected\n"));
return new WPSHeader(document_contents, input, 8);
}
/* Works 2000 */
if (0 == strcmp(fileMagic, "CHNKINK"))
{
return new WPSHeader(document_contents, input, 5);
}
}
return NULL;
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<commit_msg>avoid use of uninitialized value in comparison<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002 William Lachance ([email protected])
* Copyright (C) 2002-2004 Marc Maurer ([email protected])
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwps.sourceforge.net
*/
#include <string.h>
#include "libwps_internal.h"
#include "WPSHeader.h"
using namespace libwps;
WPSHeader::WPSHeader(RVNGInputStreamPtr &input, RVNGInputStreamPtr &fileInput, uint8_t majorVersion, WPSKind kind, WPSCreator creator) :
m_input(input), m_fileInput(fileInput), m_majorVersion(majorVersion), m_kind(kind), m_creator(creator),
m_needEncodingFlag(false)
{
}
WPSHeader::~WPSHeader()
{
}
/**
* So far, we have identified three categories of Works documents.
*
* Works documents versions 3 and later use a MS OLE container, so we detect
* their type by checking for OLE stream names. Works version 2 is like
* Works 3 without OLE, so those two types use the same parser.
*
*/
WPSHeader *WPSHeader::constructHeader(RVNGInputStreamPtr &input)
{
if (!input->isStructured())
{
input->seek(0, librevenge::RVNG_SEEK_SET);
uint8_t val[6];
for (int i=0; i<6; ++i) val[i] = libwps::readU8(input);
if (val[0] < 6 && val[1] == 0xFE)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v2 format detected\n"));
return new WPSHeader(input, input, 2);
}
// works1 dos file begin by 2054
if ((val[0] == 0xFF || val[0] == 0x20) && val[1]==0x54)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works wks database\n"));
return new WPSHeader(input, input, 1, WPS_DATABASE);
}
if (val[0] == 0xFF && val[1] == 0 && val[2]==2)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works wks detected\n"));
return new WPSHeader(input, input, 3, WPS_SPREADSHEET);
}
if (val[0] == 00 && val[1] == 0 && val[2]==2)
{
if (val[3]==0 && (val[4]==0x20 || val[4]==0x21) && val[5]==0x51)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Quattro Pro wq1 or wq2 detected\n"));
return new WPSHeader(input, input, 2, WPS_SPREADSHEET, WPS_QUATTRO_PRO);
}
WPS_DEBUG_MSG(("WPSHeader::constructHeader: potential Lotus|Microsft Works|Quattro Pro spreadsheet detected\n"));
return new WPSHeader(input, input, 2, WPS_SPREADSHEET);
}
if (val[0] == 00 && val[1] == 0x0 && val[2]==0x1a)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Lotus spreadsheet detected\n"));
return new WPSHeader(input, input, 101, WPS_SPREADSHEET, WPS_LOTUS);
}
if ((val[0] == 0x31 || val[0] == 0x32) && val[1] == 0xbe && val[2] == 0 && val[3] == 0 && val[4] == 0 && val[5] == 0xab)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Write detected\n"));
return new WPSHeader(input, input, 3, WPS_TEXT, WPS_MSWRITE);
}
return 0;
}
RVNGInputStreamPtr document_mn0(input->getSubStreamByName("MN0"));
if (document_mn0)
{
// can be a mac or a pc document
// each must contains a MM Ole which begins by 0x444e: Mac or 0x4e44: PC
RVNGInputStreamPtr document_mm(input->getSubStreamByName("MM"));
if (document_mm && libwps::readU16(document_mm) == 0x4e44)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works Mac v4 format detected\n"));
return 0;
}
// now, look if this is a database document
uint16_t fileMagic=libwps::readU16(document_mn0);
if (fileMagic == 0x54FF)
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works Database format detected\n"));
return new WPSHeader(document_mn0, input, 4, WPS_DATABASE);
}
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v4 format detected\n"));
return new WPSHeader(document_mn0, input, 4);
}
RVNGInputStreamPtr document_contents(input->getSubStreamByName("CONTENTS"));
if (document_contents)
{
/* check the Works 2000/7/8 format magic */
document_contents->seek(0, librevenge::RVNG_SEEK_SET);
char fileMagic[8];
int i = 0;
for (; i<7 && !document_contents->isEnd(); i++)
fileMagic[i] = char(libwps::readU8(document_contents.get()));
fileMagic[i] = '\0';
/* Works 7/8 */
if (0 == strcmp(fileMagic, "CHNKWKS"))
{
WPS_DEBUG_MSG(("WPSHeader::constructHeader: Microsoft Works v8 (maybe 7) format detected\n"));
return new WPSHeader(document_contents, input, 8);
}
/* Works 2000 */
if (0 == strcmp(fileMagic, "CHNKINK"))
{
return new WPSHeader(document_contents, input, 5);
}
}
return NULL;
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<|endoftext|> |
<commit_before>/*
A minimal FIPS-140 application.
Written by Jack Lloyd ([email protected]), on December 16-19, 2003
This file is in the public domain
*/
#include <botan/botan.h>
#include <botan/fips140.h>
using namespace Botan;
#include <iostream>
#include <fstream>
int main(int, char* argv[])
{
const std::string EDC_SUFFIX = ".edc";
try {
LibraryInitializer init; /* automatically does startup self tests */
// you can also do self tests on demand, like this:
if(!FIPS140::passes_self_tests())
throw Self_Test_Failure("FIPS-140 startup tests");
/*
Here, we just check argv[0] and assume that it works. You can use
various extremely nonportable APIs on some Unices (dladdr, to name one)
to find out the real name (I presume there are similiarly hairy ways of
doing it on Windows). We then assume the EDC (Error Detection Code, aka
a hash) is stored in argv[0].edc
Remember: argv[0] can be easily spoofed. Don't trust it for real.
You can also do various nasty things and find out the path of the
shared library you are linked with, and check that hash.
*/
std::string exe_path = argv[0];
std::string edc_path = exe_path + EDC_SUFFIX;
std::ifstream edc_file(edc_path.c_str());
std::string edc;
std::getline(edc_file, edc);
std::cout << "Our EDC is " << edc << std::endl;
bool good = FIPS140::good_edc(exe_path, edc);
if(good)
std::cout << "Our EDC matches" << std::endl;
else
std::cout << "Our EDC is bad" << std::endl;
}
catch(std::exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
<commit_msg>Drop the fips140 example, doesn't build after recent changes and it's more or less useless in any case.<commit_after><|endoftext|> |
<commit_before>/**
* @example clariusStreaming.cpp
*/
#include <FAST/Streamers/ClariusStreamer.hpp>
#include <FAST/Visualization/SimpleWindow.hpp>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Tools/CommandLineParser.hpp>
using namespace fast;
int main(int argc, char**argv) {
CommandLineParser parser("Clarius streaming example");
parser.parse(argc, argv);
auto streamer = ClariusStreamer::create();
auto renderer = ImageRenderer::create()
->connect(streamer);
auto window = SimpleWindow2D::create()
->connect(renderer);
window->getView()->setAutoUpdateCamera(true);
window->run();
}<commit_msg>Added possibility of setting ip and port in clariusStreaming example<commit_after>/**
* @example clariusStreaming.cpp
*/
#include <FAST/Streamers/ClariusStreamer.hpp>
#include <FAST/Visualization/SimpleWindow.hpp>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Tools/CommandLineParser.hpp>
using namespace fast;
int main(int argc, char**argv) {
CommandLineParser parser("Clarius streaming example");
parser.addVariable("port", "5858", "Port to use for clarius connection");
parser.addVariable("ip", "192.168.1.1", "Address to use for clarius connection");
parser.parse(argc, argv);
auto streamer = ClariusStreamer::create(parser.get("ip"), parser.get<int>("port"));
auto renderer = ImageRenderer::create()
->connect(streamer);
auto window = SimpleWindow2D::create()
->connect(renderer);
window->getView()->setAutoUpdateCamera(true);
window->run();
}<|endoftext|> |
<commit_before>/*******************************************************************************
* benchmarks/prefix_doubling/prefix_doubling.cpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <thrill/api/allgather.hpp>
#include <thrill/api/cache.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/distribute.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/merge.hpp>
#include <thrill/api/prefixsum.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/multiway_merge.hpp>
#include <algorithm>
#include <limits>
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
bool debug_print = false;
bool debug = true;
using namespace thrill; // NOLINT
using thrill::common::RingBuffer;
//! A pair (index, t=T[index]).
template <typename AlphabetType>
struct IndexOneMer {
size_t index;
AlphabetType t;
friend std::ostream& operator << (std::ostream& os, const IndexOneMer& iom) {
return os << '[' << iom.index << ',' << iom.t << ']';
}
} THRILL_ATTRIBUTE_PACKED;
//! A pair (rank, index)
struct RankIndex {
size_t rank;
size_t index;
friend std::ostream& operator << (std::ostream& os, const RankIndex& ri) {
return os << '(' << ri.index << '|' << ri.rank << ')';
}
} THRILL_ATTRIBUTE_PACKED;
//! A triple (rank_1, rank_2, index)
struct RankRankIndex {
size_t rank1;
size_t rank2;
size_t index;
friend std::ostream& operator << (std::ostream& os, const RankRankIndex& rri) {
return os << "( i: " << rri.index << "| r1: " << rri.rank1 << "| r2: " << rri.rank2 << ")";
}
} THRILL_ATTRIBUTE_PACKED;
template <typename InputDIA>
DIA<size_t> PrefixDoubling(Context& ctx, const InputDIA& input_dia, size_t input_size) {
using Char = typename InputDIA::ValueType;
using IndexOneMer = ::IndexOneMer<Char>;
auto one_mers_sorted =
input_dia
.template FlatWindow<IndexOneMer>(
2,
[input_size](size_t index, const RingBuffer<Char>& rb, auto emit) {
emit(IndexOneMer {index, rb[0]});
if(index == input_size - 2) emit(IndexOneMer {index + 1, rb[1]});
})
.Sort([](const IndexOneMer& a, const IndexOneMer& b) {
return a.t < b.t;
}).Keep();
if(debug_print)
one_mers_sorted.Print("one_mers_sorted");
DIA<size_t> sa =
one_mers_sorted
.Map([](const IndexOneMer& iom) {
return iom.index;
}).Collapse();
if (debug_print)
sa.Print("sa");
DIA<size_t> rebucket;
DIA<size_t> rebucket_final =
one_mers_sorted
.template FlatWindow<size_t>(
2,
[input_size](size_t index, const RingBuffer<IndexOneMer>& rb, auto emit) {
if (index == 0) emit(0);
if (rb[0].t == rb[1].t) emit(0);
else emit(index + 1);
if (index == input_size - 2) {
if (rb[0].t == rb[1].t) emit(0);
else emit(index + 2);
}
})
.PrefixSum([](const size_t a, const size_t b) {
return a > b ? a : b;
});
if (debug_print)
rebucket_final.Print("rebucket_final");
uint8_t shifted_exp = 1;
while(true) {
DIA<RankIndex> isa =
sa
.Zip(
rebucket_final,
[](size_t sa, size_t rb) {
return RankIndex {sa, rb};
})
.Sort([](const RankIndex& a, const RankIndex& b) {
return a.rank < b.rank;
});
if (debug_print)
isa.Print("isa");
LOG << "Computed the ISA";
size_t shift_by = 1 << shifted_exp++;
LOG << "Shift the ISA by " << shift_by << " positions";
DIA<RankRankIndex> triple_sorted =
isa
.template FlatWindow<RankRankIndex>(
shift_by,
[input_size, shift_by](size_t index, const RingBuffer<RankIndex>& rb, auto emit) {
emit(RankRankIndex {rb[0].index, rb[shift_by - 1].index, rb[0].rank});
if(index == input_size - shift_by)
for(size_t i = 1; i < input_size - index; ++i)
emit(RankRankIndex {rb[i].index, 0, rb[i].rank});
}
)
.Sort([](const RankRankIndex& a, const RankRankIndex& b) {
if (a.rank1 == b.rank1) {
if (a.rank2 == b.rank2) return a.index < b.index;
else return a.rank2 < b.rank2;
} else return a.rank1 < b.rank1;
});
LOG << "Sorted the triples";
size_t non_singletons =
triple_sorted
.template FlatWindow<uint8_t>(
2,
[](size_t /*index*/, const RingBuffer<RankRankIndex>& rb, auto emit) {
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
}
).Size();
LOG << "Computed the number of non singletons";
sa =
triple_sorted
.Map([](const RankRankIndex& rri) { return rri.index;
}).Collapse();
if (debug_print)
sa.Print("sa");
// If each suffix is unique regarding their 2h-prefix, we have computed
// the suffix array and can return it.
if (non_singletons == 0)
return sa;
rebucket_final =
triple_sorted
.template FlatWindow<size_t>(
2,
[input_size](size_t index, const RingBuffer<RankRankIndex>& rb, auto emit) {
if (index == 0) emit(0);
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
else
emit(index + 1);
if (index == input_size - 2) {
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
else
emit(index + 2);
}
})
.PrefixSum([](const size_t a, const size_t b) {
return a > b ? a : b;
});
if (debug_print)
rebucket_final.Print("rebucket_final");
LOG << "Rebucket the partial SA";
}
}
/*!
* Class to encapsulate all
*/
class StartPrefixDoubling
{
public:
StartPrefixDoubling(
Context& ctx,
const std::string& input_path, const std::string& output_path,
bool text_output_flag,
bool check_flag,
bool input_verbatim)
: ctx_(ctx),
input_path_(input_path), output_path_(output_path),
text_output_flag_(text_output_flag),
check_flag_(check_flag),
input_verbatim_(input_verbatim) { }
void Run() {
if (input_verbatim_) {
// take path as verbatim text
std::vector<uint8_t> input_vec(input_path_.begin(), input_path_.end());
auto input_dia = Distribute<uint8_t>(ctx_, input_vec);
if (debug_print) input_dia.Print("input");
StartPrefixDoublingInput(input_dia, input_vec.size());
}
else {
auto input_dia = ReadBinary<uint8_t>(ctx_, input_path_);
size_t input_size = input_dia.Size();
StartPrefixDoublingInput(input_dia, input_size);
}
}
template <typename InputDIA>
void StartPrefixDoublingInput(const InputDIA& input_dia, uint64_t input_size) {
auto suffix_array = PrefixDoubling(ctx_, input_dia, input_size);
if (output_path_.size()) {
suffix_array.WriteBinary(output_path_);
}
if (check_flag_) {
LOG1 << "checking suffix array...";
//if (!CheckSA(input_dia, suffix_array)) {
// throw std::runtime_error("Suffix array is invalid!");
//}
//else {
// LOG1 << "okay.";
//}
}
}
protected:
Context& ctx_;
std::string input_path_;
std::string output_path_;
bool text_output_flag_;
bool check_flag_;
bool input_verbatim_;
};
int main(int argc, char* argv[]) {
common::CmdlineParser cp;
cp.SetDescription("A prefix doubling suffix array construction algorithm.");
cp.SetAuthor("Florian Kurpicz <[email protected]>");
std::string input_path, output_path;
bool text_output_flag = false;
bool check_flag = false;
bool input_verbatim = false;
cp.AddParamString("input", input_path,
"Path to input file (or verbatim text).\n"
" The special inputs 'random' and 'unary' generate "
"such text on-the-fly.");
cp.AddFlag('c', "check", check_flag,
"Check suffix array for correctness.");
cp.AddFlag('t', "text", text_output_flag,
"Print out suffix array in readable text.");
cp.AddString('o', "output", output_path,
"Output suffix array to given path.");
cp.AddFlag('v', "verbatim", input_verbatim,
"Consider \"input\" as verbatim text to construct "
"suffix array on.");
cp.AddFlag('d', "debug", debug_print,
"Print debug info.");
// process command line
if (!cp.Process(argc, argv))
return -1;
return Run(
[&](Context& ctx) {
return StartPrefixDoubling(ctx,
input_path, output_path,
text_output_flag,
check_flag,
input_verbatim).Run();
});
}
/******************************************************************************/
<commit_msg>Renamed rebucket_final to rebucket<commit_after>/*******************************************************************************
* benchmarks/prefix_doubling/prefix_doubling.cpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <thrill/api/allgather.hpp>
#include <thrill/api/cache.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/distribute.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/merge.hpp>
#include <thrill/api/prefixsum.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/multiway_merge.hpp>
#include <algorithm>
#include <limits>
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
bool debug_print = false;
bool debug = true;
using namespace thrill; // NOLINT
using thrill::common::RingBuffer;
//! A pair (index, t=T[index]).
template <typename AlphabetType>
struct IndexOneMer {
size_t index;
AlphabetType t;
friend std::ostream& operator << (std::ostream& os, const IndexOneMer& iom) {
return os << '[' << iom.index << ',' << iom.t << ']';
}
} THRILL_ATTRIBUTE_PACKED;
//! A pair (rank, index)
struct RankIndex {
size_t rank;
size_t index;
friend std::ostream& operator << (std::ostream& os, const RankIndex& ri) {
return os << '(' << ri.index << '|' << ri.rank << ')';
}
} THRILL_ATTRIBUTE_PACKED;
//! A triple (rank_1, rank_2, index)
struct RankRankIndex {
size_t rank1;
size_t rank2;
size_t index;
friend std::ostream& operator << (std::ostream& os, const RankRankIndex& rri) {
return os << "( i: " << rri.index << "| r1: " << rri.rank1 << "| r2: " << rri.rank2 << ")";
}
} THRILL_ATTRIBUTE_PACKED;
template <typename InputDIA>
DIA<size_t> PrefixDoubling(Context& ctx, const InputDIA& input_dia, size_t input_size) {
using Char = typename InputDIA::ValueType;
using IndexOneMer = ::IndexOneMer<Char>;
auto one_mers_sorted =
input_dia
.template FlatWindow<IndexOneMer>(
2,
[input_size](size_t index, const RingBuffer<Char>& rb, auto emit) {
emit(IndexOneMer {index, rb[0]});
if(index == input_size - 2) emit(IndexOneMer {index + 1, rb[1]});
})
.Sort([](const IndexOneMer& a, const IndexOneMer& b) {
return a.t < b.t;
}).Keep();
if(debug_print)
one_mers_sorted.Print("one_mers_sorted");
DIA<size_t> sa =
one_mers_sorted
.Map([](const IndexOneMer& iom) {
return iom.index;
}).Collapse();
if (debug_print)
sa.Print("sa");
DIA<size_t> rebucket =
one_mers_sorted
.template FlatWindow<size_t>(
2,
[input_size](size_t index, const RingBuffer<IndexOneMer>& rb, auto emit) {
if (index == 0) emit(0);
if (rb[0].t == rb[1].t) emit(0);
else emit(index + 1);
if (index == input_size - 2) {
if (rb[0].t == rb[1].t) emit(0);
else emit(index + 2);
}
})
.PrefixSum([](const size_t a, const size_t b) {
return a > b ? a : b;
});
if (debug_print)
rebucket.Print("rebucket");
uint8_t shifted_exp = 1;
while(true) {
DIA<RankIndex> isa =
sa
.Zip(
rebucket,
[](size_t sa, size_t rb) {
return RankIndex {sa, rb};
})
.Sort([](const RankIndex& a, const RankIndex& b) {
return a.rank < b.rank;
});
if (debug_print)
isa.Print("isa");
LOG << "Computed the ISA";
size_t shift_by = 1 << shifted_exp++;
LOG << "Shift the ISA by " << shift_by << " positions";
DIA<RankRankIndex> triple_sorted =
isa
.template FlatWindow<RankRankIndex>(
shift_by,
[input_size, shift_by](size_t index, const RingBuffer<RankIndex>& rb, auto emit) {
emit(RankRankIndex {rb[0].index, rb[shift_by - 1].index, rb[0].rank});
if(index == input_size - shift_by)
for(size_t i = 1; i < input_size - index; ++i)
emit(RankRankIndex {rb[i].index, 0, rb[i].rank});
}
)
.Sort([](const RankRankIndex& a, const RankRankIndex& b) {
if (a.rank1 == b.rank1) {
if (a.rank2 == b.rank2) return a.index < b.index;
else return a.rank2 < b.rank2;
} else return a.rank1 < b.rank1;
});
LOG << "Sorted the triples";
size_t non_singletons =
triple_sorted
.template FlatWindow<uint8_t>(
2,
[](size_t /*index*/, const RingBuffer<RankRankIndex>& rb, auto emit) {
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
}
).Size();
LOG << "Computed the number of non singletons";
sa =
triple_sorted
.Map([](const RankRankIndex& rri) { return rri.index;
}).Collapse();
if (debug_print)
sa.Print("sa");
// If each suffix is unique regarding their 2h-prefix, we have computed
// the suffix array and can return it.
if (non_singletons == 0)
return sa;
rebucket =
triple_sorted
.template FlatWindow<size_t>(
2,
[input_size](size_t index, const RingBuffer<RankRankIndex>& rb, auto emit) {
if (index == 0) emit(0);
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
else
emit(index + 1);
if (index == input_size - 2) {
if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
emit(0);
else
emit(index + 2);
}
})
.PrefixSum([](const size_t a, const size_t b) {
return a > b ? a : b;
});
if (debug_print)
rebucket.Print("rebucket");
LOG << "Rebucket the partial SA";
}
}
/*!
* Class to encapsulate all
*/
class StartPrefixDoubling
{
public:
StartPrefixDoubling(
Context& ctx,
const std::string& input_path, const std::string& output_path,
bool text_output_flag,
bool check_flag,
bool input_verbatim)
: ctx_(ctx),
input_path_(input_path), output_path_(output_path),
text_output_flag_(text_output_flag),
check_flag_(check_flag),
input_verbatim_(input_verbatim) { }
void Run() {
if (input_verbatim_) {
// take path as verbatim text
std::vector<uint8_t> input_vec(input_path_.begin(), input_path_.end());
auto input_dia = Distribute<uint8_t>(ctx_, input_vec);
if (debug_print) input_dia.Print("input");
StartPrefixDoublingInput(input_dia, input_vec.size());
}
else {
auto input_dia = ReadBinary<uint8_t>(ctx_, input_path_);
size_t input_size = input_dia.Size();
StartPrefixDoublingInput(input_dia, input_size);
}
}
template <typename InputDIA>
void StartPrefixDoublingInput(const InputDIA& input_dia, uint64_t input_size) {
auto suffix_array = PrefixDoubling(ctx_, input_dia, input_size);
if (output_path_.size()) {
suffix_array.WriteBinary(output_path_);
}
if (check_flag_) {
LOG1 << "checking suffix array...";
//if (!CheckSA(input_dia, suffix_array)) {
// throw std::runtime_error("Suffix array is invalid!");
//}
//else {
// LOG1 << "okay.";
//}
}
}
protected:
Context& ctx_;
std::string input_path_;
std::string output_path_;
bool text_output_flag_;
bool check_flag_;
bool input_verbatim_;
};
int main(int argc, char* argv[]) {
common::CmdlineParser cp;
cp.SetDescription("A prefix doubling suffix array construction algorithm.");
cp.SetAuthor("Florian Kurpicz <[email protected]>");
std::string input_path, output_path;
bool text_output_flag = false;
bool check_flag = false;
bool input_verbatim = false;
cp.AddParamString("input", input_path,
"Path to input file (or verbatim text).\n"
" The special inputs 'random' and 'unary' generate "
"such text on-the-fly.");
cp.AddFlag('c', "check", check_flag,
"Check suffix array for correctness.");
cp.AddFlag('t', "text", text_output_flag,
"Print out suffix array in readable text.");
cp.AddString('o', "output", output_path,
"Output suffix array to given path.");
cp.AddFlag('v', "verbatim", input_verbatim,
"Consider \"input\" as verbatim text to construct "
"suffix array on.");
cp.AddFlag('d', "debug", debug_print,
"Print debug info.");
// process command line
if (!cp.Process(argc, argv))
return -1;
return Run(
[&](Context& ctx) {
return StartPrefixDoubling(ctx,
input_path, output_path,
text_output_flag,
check_flag,
input_verbatim).Run();
});
}
/******************************************************************************/
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/fileapi/Blob.h"
#include "core/dom/ScriptExecutionContext.h"
#include "core/fileapi/BlobURL.h"
#include "core/fileapi/File.h"
#include "core/fileapi/ThreadableBlobRegistry.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/platform/HistogramSupport.h"
namespace WebCore {
namespace {
// Used in histograms to see when we can actually deprecate the prefixed slice.
enum SliceHistogramEnum {
SliceWithoutPrefix,
SliceWithPrefix,
SliceHistogramEnumMax,
};
} // namespace
Blob::Blob()
: m_size(0)
{
ScriptWrappable::init(this);
OwnPtr<BlobData> blobData = BlobData::create();
// Create a new internal URL and register it with the provided blob data.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release());
}
Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
: m_type(blobData->contentType())
, m_size(size)
{
ASSERT(blobData);
ScriptWrappable::init(this);
// Create a new internal URL and register it with the provided blob data.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData);
}
Blob::Blob(const KURL& srcURL, const String& type, long long size)
: m_type(type)
, m_size(size)
{
ScriptWrappable::init(this);
// Create a new internal URL and register it with the same blob data as the source URL.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL);
}
Blob::~Blob()
{
ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
}
PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
{
// When we slice a file for the first time, we obtain a snapshot of the file by capturing its current size and modification time.
// The modification time will be used to verify if the file has been changed or not, when the underlying data are accessed.
long long size;
double modificationTime;
if (isFile()) {
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
toFile(this)->captureSnapshot(size, modificationTime);
} else {
ASSERT(m_size != -1);
size = m_size;
}
// Convert the negative value that is used to select from the end.
if (start < 0)
start = start + size;
if (end < 0)
end = end + size;
// Clamp the range if it exceeds the size limit.
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if (start >= size) {
start = 0;
end = 0;
} else if (end < start)
end = start;
else if (end > size)
end = size;
long long length = end - start;
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
if (isFile()) {
if (!toFile(this)->fileSystemURL().isEmpty())
blobData->appendURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
else
blobData->appendFile(toFile(this)->path(), start, length, modificationTime);
} else
blobData->appendBlob(m_internalURL, start, length);
return Blob::create(blobData.release(), length);
}
} // namespace WebCore
<commit_msg>Clean up no longer used enum and inclusion for collecting Blob histogram.<commit_after>/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/fileapi/Blob.h"
#include "core/dom/ScriptExecutionContext.h"
#include "core/fileapi/BlobURL.h"
#include "core/fileapi/File.h"
#include "core/fileapi/ThreadableBlobRegistry.h"
#include "core/inspector/ScriptCallStack.h"
namespace WebCore {
Blob::Blob()
: m_size(0)
{
ScriptWrappable::init(this);
OwnPtr<BlobData> blobData = BlobData::create();
// Create a new internal URL and register it with the provided blob data.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release());
}
Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
: m_type(blobData->contentType())
, m_size(size)
{
ASSERT(blobData);
ScriptWrappable::init(this);
// Create a new internal URL and register it with the provided blob data.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData);
}
Blob::Blob(const KURL& srcURL, const String& type, long long size)
: m_type(type)
, m_size(size)
{
ScriptWrappable::init(this);
// Create a new internal URL and register it with the same blob data as the source URL.
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL);
}
Blob::~Blob()
{
ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
}
PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
{
// When we slice a file for the first time, we obtain a snapshot of the file by capturing its current size and modification time.
// The modification time will be used to verify if the file has been changed or not, when the underlying data are accessed.
long long size;
double modificationTime;
if (isFile()) {
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
toFile(this)->captureSnapshot(size, modificationTime);
} else {
ASSERT(m_size != -1);
size = m_size;
}
// Convert the negative value that is used to select from the end.
if (start < 0)
start = start + size;
if (end < 0)
end = end + size;
// Clamp the range if it exceeds the size limit.
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if (start >= size) {
start = 0;
end = 0;
} else if (end < start)
end = start;
else if (end > size)
end = size;
long long length = end - start;
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
if (isFile()) {
if (!toFile(this)->fileSystemURL().isEmpty())
blobData->appendURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
else
blobData->appendFile(toFile(this)->path(), start, length, modificationTime);
} else
blobData->appendBlob(m_internalURL, start, length);
return Blob::create(blobData.release(), length);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>
#include "base/arena_allocator.hpp"
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace principia {
namespace base {
using ::testing::Eq;
using ::testing::Ge;
class ArenaAllocatorTest : public ::testing::Test {
protected:
ArenaAllocatorTest() : allocator_(&arena_) {
arena_.Init(google::protobuf::ArenaOptions());
}
google::protobuf::Arena arena_;
ArenaAllocator<std::string> allocator_;
};
TEST_F(ArenaAllocatorTest, Container) {
EXPECT_THAT(arena_.SpaceUsed(), Eq(0));
std::vector<std::string, ArenaAllocator<std::string>> v(1000, allocator_);
EXPECT_THAT(arena_.SpaceUsed(), Ge(1000 * sizeof(std::string)));
}
TEST_F(ArenaAllocatorTest, ContainerAndString) {
EXPECT_THAT(arena_.SpaceUsed(), Eq(0));
using S = std::basic_string<char,
std::char_traits<char>,
ArenaAllocator<char>>;
ArenaAllocator<char> allocator1(&arena_);
ArenaAllocator<S> allocator2(&arena_);
std::vector<S, ArenaAllocator<S>> v(1000, S("foo", allocator1), allocator2);
EXPECT_THAT(arena_.SpaceUsed(), Ge(1000 * (sizeof(std::string) + 4)));
}
} // namespace base
} // namespace principia
<commit_msg>Lint.<commit_after>
#include "base/arena_allocator.hpp"
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace principia {
namespace base {
using ::testing::Eq;
using ::testing::Ge;
class ArenaAllocatorTest : public ::testing::Test {
protected:
ArenaAllocatorTest() : allocator_(&arena_) {
arena_.Init(google::protobuf::ArenaOptions());
}
google::protobuf::Arena arena_;
ArenaAllocator<std::string> allocator_;
};
TEST_F(ArenaAllocatorTest, Container) {
EXPECT_THAT(arena_.SpaceUsed(), Eq(0));
std::vector<std::string, ArenaAllocator<std::string>> v(1000, allocator_);
EXPECT_THAT(arena_.SpaceUsed(), Ge(1000 * sizeof(std::string)));
}
TEST_F(ArenaAllocatorTest, ContainerAndString) {
EXPECT_THAT(arena_.SpaceUsed(), Eq(0));
using S = std::basic_string<char,
std::char_traits<char>,
ArenaAllocator<char>>;
ArenaAllocator<char> allocator1(&arena_);
ArenaAllocator<S> allocator2(&arena_);
std::vector<S, ArenaAllocator<S>> v(1000, S("foo", allocator1), allocator2);
EXPECT_THAT(arena_.SpaceUsed(), Ge(1000 * (sizeof(std::string) + 4)));
}
} // namespace base
} // namespace principia
<|endoftext|> |
<commit_before>//
// CPM.hpp
// Clock Signal
//
// Created by Thomas Harte on 10/08/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef Storage_Disk_Parsers_CPM_hpp
#define Storage_Disk_Parsers_CPM_hpp
#include "../Disk.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace Storage {
namespace Disk {
namespace CPM {
struct ParameterBlock {
int sectors_per_track;
int block_size;
int first_sector;
int logic_extents_per_physical;
uint16_t catalogue_allocation_bitmap;
int reserved_tracks;
};
struct File {
uint8_t user_number;
std::string name;
std::string type;
bool read_only;
bool system;
std::vector<uint8_t> data;
};
struct Catalogue {
std::vector<File> files;
};
std::unique_ptr<Catalogue> GetCatalogue(const std::shared_ptr<Storage::Disk::Disk> &disk, const ParameterBlock ¶meters);
}
}
}
#endif /* Storage_Disk_Parsers_CPM_hpp */
<commit_msg>Killed logic_extents_per_physical, since I don't know how to handle it, and instituted tracks, to allow a decision about short versus long allocation units.<commit_after>//
// CPM.hpp
// Clock Signal
//
// Created by Thomas Harte on 10/08/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef Storage_Disk_Parsers_CPM_hpp
#define Storage_Disk_Parsers_CPM_hpp
#include "../Disk.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace Storage {
namespace Disk {
namespace CPM {
struct ParameterBlock {
int sectors_per_track;
int tracks;
int block_size;
int first_sector;
uint16_t catalogue_allocation_bitmap;
int reserved_tracks;
};
struct File {
uint8_t user_number;
std::string name;
std::string type;
bool read_only;
bool system;
std::vector<uint8_t> data;
};
struct Catalogue {
std::vector<File> files;
};
std::unique_ptr<Catalogue> GetCatalogue(const std::shared_ptr<Storage::Disk::Disk> &disk, const ParameterBlock ¶meters);
}
}
}
#endif /* Storage_Disk_Parsers_CPM_hpp */
<|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.
//
// This file contains intentional memory errors, some of which may lead to
// crashes if the test is ran without special memory testing tools. We use these
// errors to verify the sanity of the tools.
#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
const base::subtle::Atomic32 kMagicValue = 42;
// Helper for memory accesses that can potentially corrupt memory or cause a
// crash during a native run.
#ifdef ADDRESS_SANITIZER
#define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
#else
#define HARMFUL_ACCESS(action,error_regexp) \
do { if (RunningOnValgrind()) { action; } } while (0)
#endif
void ReadUninitializedValue(char *ptr) {
// The || in the conditional is to prevent clang from optimizing away the
// jump -- valgrind only catches jumps and conditional moves, but clang uses
// the borrow flag if the condition is just `*ptr == '\0'`.
if (*ptr == '\0' || *ptr == 64) {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
char c = ptr[-2];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
char c = ptr[size + 1];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = kMagicValue;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = kMagicValue;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*2 bytes to the left");
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*1 bytes to the right");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*1 bytes to the left");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*0 bytes to the right");
}
} // namespace
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
// Use after delete.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
// Use after free.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int;
(void) foo;
delete [] foo;
}
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
class ReleaseStoreThread : public PlatformThread::Delegate {
public:
explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
~ReleaseStoreThread() {}
void ThreadMain() {
base::subtle::Release_Store(value_, kMagicValue);
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
base::subtle::Atomic32 *value_;
};
class AcquireLoadThread : public PlatformThread::Delegate {
public:
explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
~AcquireLoadThread() {}
void ThreadMain() {
// Wait for the other thread to make Release_Store
PlatformThread::Sleep(100);
base::subtle::Acquire_Load(value_);
}
private:
base::subtle::Atomic32 *value_;
};
void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Create(0, d1, &a);
PlatformThread::Create(0, d2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
}
} // namespace
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AnnotateBenignRace) {
bool shared = false;
ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AtomicsAreIgnored) {
base::subtle::Atomic32 shared = 0;
ReleaseStoreThread thread1(&shared);
AcquireLoadThread thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_EQ(kMagicValue, shared);
}
} // namespace base
<commit_msg>Add a sanity test that crashes under ASan. This should be used to check that the tests are built correctly. Review URL: http://codereview.chromium.org/8240010<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.
//
// This file contains intentional memory errors, some of which may lead to
// crashes if the test is ran without special memory testing tools. We use these
// errors to verify the sanity of the tools.
#include "base/atomicops.h"
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
const base::subtle::Atomic32 kMagicValue = 42;
// Helper for memory accesses that can potentially corrupt memory or cause a
// crash during a native run.
#ifdef ADDRESS_SANITIZER
#define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
#else
#define HARMFUL_ACCESS(action,error_regexp) \
do { if (RunningOnValgrind()) { action; } } while (0)
#endif
void ReadUninitializedValue(char *ptr) {
// The || in the conditional is to prevent clang from optimizing away the
// jump -- valgrind only catches jumps and conditional moves, but clang uses
// the borrow flag if the condition is just `*ptr == '\0'`.
if (*ptr == '\0' || *ptr == 64) {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
char c = ptr[-2];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
char c = ptr[size + 1];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = kMagicValue;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = kMagicValue;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*2 bytes to the left");
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*1 bytes to the right");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
"heap-buffer-overflow.*1 bytes to the left");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
"heap-buffer-overflow.*0 bytes to the right");
}
} // namespace
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
// Use after delete.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
// Use after free.
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
#ifndef ADDRESS_SANITIZER
// This test may corrupt memory if not run under Valgrind or compiled with
// AddressSanitizer.
if (!RunningOnValgrind())
return;
#endif
// Without the |volatile|, clang optimizes away the next two lines.
int* volatile foo = new int;
(void) foo;
delete [] foo;
}
#ifdef ADDRESS_SANITIZER
TEST(ToolsSanityTest, DISABLED_AddressSanitizerCrashTest) {
// Intentionally crash to make sure AddressSanitizer is running.
// This test should not be ran on bots.
int* volatile zero = NULL;
*zero = 0;
}
#endif
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
class ReleaseStoreThread : public PlatformThread::Delegate {
public:
explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
~ReleaseStoreThread() {}
void ThreadMain() {
base::subtle::Release_Store(value_, kMagicValue);
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
base::subtle::Atomic32 *value_;
};
class AcquireLoadThread : public PlatformThread::Delegate {
public:
explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
~AcquireLoadThread() {}
void ThreadMain() {
// Wait for the other thread to make Release_Store
PlatformThread::Sleep(100);
base::subtle::Acquire_Load(value_);
}
private:
base::subtle::Atomic32 *value_;
};
void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Create(0, d1, &a);
PlatformThread::Create(0, d2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
}
} // namespace
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AnnotateBenignRace) {
bool shared = false;
ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AtomicsAreIgnored) {
base::subtle::Atomic32 shared = 0;
ReleaseStoreThread thread1(&shared);
AcquireLoadThread thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_EQ(kMagicValue, shared);
}
} // namespace base
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XTDataObject.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:26:38 $
*
* 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 _XTDATAOBJECT_HXX_
#define _XTDATAOBJECT_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif
#ifndef _DATAFORMATTRANSLATOR_HXX_
#include "DataFmtTransl.hxx"
#endif
#ifndef _FETCLIST_HXX_
#include "FEtcList.hxx"
#endif
#include <windows.h>
#include <ole2.h>
#include <objidl.h>
/*--------------------------------------------------------------------------
- the function principle of the windows clipboard:
a data provider offers all formats he can deliver on the clipboard
a clipboard client ask for the available formats on the clipboard
and decides if there is a format he can use
if there is one, he requests the data in this format
- This class inherits from IDataObject an so can be placed on the
OleClipboard. The class wrapps a transferable object which is the
original DataSource
- DataFlavors offerd by this transferable will be translated into
appropriate clipboard formats
- if the transferable contains text data always text and unicodetext
will be offered or vice versa
- text data will be automaticaly converted between text und unicode text
- although the transferable may support text in different charsets
(codepages) only text in one codepage can be offered by the clipboard
----------------------------------------------------------------------------*/
class CStgTransferHelper;
class CXTDataObject : public IDataObject
{
public:
CXTDataObject( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager,
const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& aXTransferable );
//-----------------------------------------------------------------
// ole interface implementation
//-----------------------------------------------------------------
//IUnknown interface methods
STDMETHODIMP QueryInterface(REFIID iid, LPVOID* ppvObject);
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
// IDataObject interface methods
STDMETHODIMP GetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP GetDataHere( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP QueryGetData( LPFORMATETC pFormatetc );
STDMETHODIMP GetCanonicalFormatEtc( LPFORMATETC pFormatectIn, LPFORMATETC pFormatetcOut );
STDMETHODIMP SetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium, BOOL fRelease );
STDMETHODIMP EnumFormatEtc( DWORD dwDirection, IEnumFORMATETC** ppenumFormatetc );
STDMETHODIMP DAdvise( LPFORMATETC pFormatetc, DWORD advf, LPADVISESINK pAdvSink, DWORD* pdwConnection );
STDMETHODIMP DUnadvise( DWORD dwConnection );
STDMETHODIMP EnumDAdvise( LPENUMSTATDATA* ppenumAdvise );
operator IDataObject*( );
private:
com::sun::star::datatransfer::DataFlavor SAL_CALL formatEtcToDataFlavor( const FORMATETC& aFormatEtc ) const;
void SAL_CALL renderDataAndSetupStgMedium( const sal_Int8* lpStorage,
const FORMATETC& fetc,
sal_uInt32 nInitStgSize,
sal_uInt32 nBytesToTransfer,
STGMEDIUM& stgmedium );
void SAL_CALL renderLocaleAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderUnicodeAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderAnyDataAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
HRESULT SAL_CALL renderSynthesizedFormatAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedUnicodeAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedTextAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedHtmlAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL setupStgMedium( const FORMATETC& fetc,
CStgTransferHelper& stgTransHlp,
STGMEDIUM& stgmedium );
void validateFormatEtc( LPFORMATETC lpFormatEtc ) const;
void SAL_CALL invalidateStgMedium( STGMEDIUM& stgmedium ) const;
HRESULT SAL_CALL translateStgExceptionCode( HRESULT hr ) const;
inline void SAL_CALL InitializeFormatEtcContainer( );
private:
LONG m_nRefCnt;
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_SrvMgr;
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > m_XTransferable;
CFormatEtcContainer m_FormatEtcContainer;
sal_Bool m_bFormatEtcContainerInitialized;
CDataFormatTranslator m_DataFormatTranslator;
CFormatRegistrar m_FormatRegistrar;
};
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
class CEnumFormatEtc : public IEnumFORMATETC
{
public:
CEnumFormatEtc( LPUNKNOWN lpUnkOuter, const CFormatEtcContainer& aFormatEtcContainer );
// IUnknown
STDMETHODIMP QueryInterface( REFIID iid, LPVOID* ppvObject );
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
//IEnumFORMATETC
STDMETHODIMP Next( ULONG nRequested, LPFORMATETC lpDest, ULONG* lpFetched );
STDMETHODIMP Skip( ULONG celt );
STDMETHODIMP Reset( );
STDMETHODIMP Clone( IEnumFORMATETC** ppenum );
private:
LONG m_nRefCnt;
LPUNKNOWN m_lpUnkOuter;
CFormatEtcContainer m_FormatEtcContainer;
};
typedef CEnumFormatEtc *PCEnumFormatEtc;
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.11.4); FILE MERGED 2006/03/09 20:31:57 pl 1.11.4.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XTDataObject.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2006-06-20 06:06:42 $
*
* 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 _XTDATAOBJECT_HXX_
#define _XTDATAOBJECT_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif
#ifndef _DATAFORMATTRANSLATOR_HXX_
#include "DataFmtTransl.hxx"
#endif
#ifndef _FETCLIST_HXX_
#include "FEtcList.hxx"
#endif
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#include <windows.h>
#include <ole2.h>
#include <objidl.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
/*--------------------------------------------------------------------------
- the function principle of the windows clipboard:
a data provider offers all formats he can deliver on the clipboard
a clipboard client ask for the available formats on the clipboard
and decides if there is a format he can use
if there is one, he requests the data in this format
- This class inherits from IDataObject an so can be placed on the
OleClipboard. The class wrapps a transferable object which is the
original DataSource
- DataFlavors offerd by this transferable will be translated into
appropriate clipboard formats
- if the transferable contains text data always text and unicodetext
will be offered or vice versa
- text data will be automaticaly converted between text und unicode text
- although the transferable may support text in different charsets
(codepages) only text in one codepage can be offered by the clipboard
----------------------------------------------------------------------------*/
class CStgTransferHelper;
class CXTDataObject : public IDataObject
{
public:
CXTDataObject( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager,
const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& aXTransferable );
virtual ~CXTDataObject() {}
//-----------------------------------------------------------------
// ole interface implementation
//-----------------------------------------------------------------
//IUnknown interface methods
STDMETHODIMP QueryInterface(REFIID iid, LPVOID* ppvObject);
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
// IDataObject interface methods
STDMETHODIMP GetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP GetDataHere( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium );
STDMETHODIMP QueryGetData( LPFORMATETC pFormatetc );
STDMETHODIMP GetCanonicalFormatEtc( LPFORMATETC pFormatectIn, LPFORMATETC pFormatetcOut );
STDMETHODIMP SetData( LPFORMATETC pFormatetc, LPSTGMEDIUM pmedium, BOOL fRelease );
STDMETHODIMP EnumFormatEtc( DWORD dwDirection, IEnumFORMATETC** ppenumFormatetc );
STDMETHODIMP DAdvise( LPFORMATETC pFormatetc, DWORD advf, LPADVISESINK pAdvSink, DWORD* pdwConnection );
STDMETHODIMP DUnadvise( DWORD dwConnection );
STDMETHODIMP EnumDAdvise( LPENUMSTATDATA* ppenumAdvise );
operator IDataObject*( );
private:
com::sun::star::datatransfer::DataFlavor SAL_CALL formatEtcToDataFlavor( const FORMATETC& aFormatEtc ) const;
void SAL_CALL renderDataAndSetupStgMedium( const sal_Int8* lpStorage,
const FORMATETC& fetc,
sal_uInt32 nInitStgSize,
sal_uInt32 nBytesToTransfer,
STGMEDIUM& stgmedium );
void SAL_CALL renderLocaleAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderUnicodeAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderAnyDataAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
HRESULT SAL_CALL renderSynthesizedFormatAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedUnicodeAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedTextAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL renderSynthesizedHtmlAndSetupStgMedium( FORMATETC& fetc, STGMEDIUM& stgmedium );
void SAL_CALL setupStgMedium( const FORMATETC& fetc,
CStgTransferHelper& stgTransHlp,
STGMEDIUM& stgmedium );
void validateFormatEtc( LPFORMATETC lpFormatEtc ) const;
void SAL_CALL invalidateStgMedium( STGMEDIUM& stgmedium ) const;
HRESULT SAL_CALL translateStgExceptionCode( HRESULT hr ) const;
inline void SAL_CALL InitializeFormatEtcContainer( );
private:
LONG m_nRefCnt;
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_SrvMgr;
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > m_XTransferable;
CFormatEtcContainer m_FormatEtcContainer;
sal_Bool m_bFormatEtcContainerInitialized;
CDataFormatTranslator m_DataFormatTranslator;
CFormatRegistrar m_FormatRegistrar;
};
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
class CEnumFormatEtc : public IEnumFORMATETC
{
public:
CEnumFormatEtc( LPUNKNOWN lpUnkOuter, const CFormatEtcContainer& aFormatEtcContainer );
virtual ~CEnumFormatEtc() {}
// IUnknown
STDMETHODIMP QueryInterface( REFIID iid, LPVOID* ppvObject );
STDMETHODIMP_( ULONG ) AddRef( );
STDMETHODIMP_( ULONG ) Release( );
//IEnumFORMATETC
STDMETHODIMP Next( ULONG nRequested, LPFORMATETC lpDest, ULONG* lpFetched );
STDMETHODIMP Skip( ULONG celt );
STDMETHODIMP Reset( );
STDMETHODIMP Clone( IEnumFORMATETC** ppenum );
private:
LONG m_nRefCnt;
LPUNKNOWN m_lpUnkOuter;
CFormatEtcContainer m_FormatEtcContainer;
};
typedef CEnumFormatEtc *PCEnumFormatEtc;
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
}
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
void ReadUninitializedValue(char *ptr) {
if (*ptr == true) {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
LOG(INFO) << "Reading a byte out of bounds: " << ptr[-2];
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
LOG(INFO) << "Reading a byte out of bounds: " << ptr[size + 1];
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = 42;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = 42;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
ReadValueOutOfArrayBoundsLeft(ptr);
ReadValueOutOfArrayBoundsRight(ptr, size);
WriteValueOutOfArrayBoundsLeft(ptr);
WriteValueOutOfArrayBoundsRight(ptr, size);
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
foo[5] = 0; // Use after delete. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
foo[5] = 0; // Use after free. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
int *foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
int *foo = new int;
delete [] foo;
}
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Delegate *thread1 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Delegate *thread2 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Create(0, thread1, &a);
PlatformThread::Create(0, thread2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
EXPECT_TRUE(shared);
delete thread1;
delete thread2;
}
<commit_msg>Quick-fix the compliation error on Windows TBR=phajdan.jr,glider Review URL: http://codereview.chromium.org/3413032<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// We use caps here just to ensure that the method name doesn't interfere with
// the wildcarded suppressions.
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() {}
void ThreadMain() {
*value_ = true;
// Sleep for a few milliseconds so the two threads are more likely to live
// simultaneously. Otherwise we may miss the report due to mutex
// lock/unlock's inside thread creation code in pure-happens-before mode...
PlatformThread::Sleep(100);
}
private:
bool *value_;
};
}
// A memory leak detector should report an error in this test.
TEST(ToolsSanityTest, MemoryLeak) {
int *leak = new int[256]; // Leak some memory intentionally.
leak[4] = 1; // Make sure the allocated memory is used.
}
void ReadUninitializedValue(char *ptr) {
if (*ptr == '\0') {
(*ptr)++;
} else {
(*ptr)--;
}
}
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
LOG(INFO) << "Reading a byte out of bounds: " << ptr[-2];
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
LOG(INFO) << "Reading a byte out of bounds: " << ptr[size + 1];
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = 42;
}
// This is harmless if you run it under Valgrind thanks to redzones.
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = 42;
}
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
ReadValueOutOfArrayBoundsLeft(ptr);
ReadValueOutOfArrayBoundsRight(ptr, size);
WriteValueOutOfArrayBoundsLeft(ptr);
WriteValueOutOfArrayBoundsRight(ptr, size);
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = new char[10];
MakeSomeErrors(foo, 10);
delete [] foo;
foo[5] = 0; // Use after delete. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
char *foo = reinterpret_cast<char*>(malloc(10));
MakeSomeErrors(foo, 10);
free(foo);
foo[5] = 0; // Use after free. This won't break anything under Valgrind.
}
TEST(ToolsSanityTest, ArrayDeletedWithoutBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
int *foo = new int[10];
delete foo;
}
TEST(ToolsSanityTest, SingleElementDeletedWithBraces) {
// This test may corrupt memory if not run under Valgrind.
if (!RunningOnValgrind())
return;
int *foo = new int;
delete [] foo;
}
// A data race detector should report an error in this test.
TEST(ToolsSanityTest, DataRace) {
bool shared = false;
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Delegate *thread1 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Delegate *thread2 =
new TOOLS_SANITY_TEST_CONCURRENT_THREAD(&shared);
PlatformThread::Create(0, thread1, &a);
PlatformThread::Create(0, thread2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
EXPECT_TRUE(shared);
delete thread1;
delete thread2;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"
#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#include <QTextEdit>
#include <QPushButton>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#include <qtextedit.h>
#include <qpushbutton.h>
#endif
#include <iostream>
#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif
namespace sofa
{
namespace gui
{
namespace qt
{
SofaPluginManager::SofaPluginManager()
{
// SIGNAL / SLOTS CONNECTIONS
this->connect(buttonAdd, SIGNAL(clicked() ), this, SLOT( addLibrary() ));
this->connect(buttonRemove, SIGNAL(clicked() ), this, SLOT( removeLibrary() ));
#ifdef SOFA_QT4
this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));
#else
this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateComponentList(QListViewItem*) ));
this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateDescription(QListViewItem*) ));
#endif
//read the plugin list in the settings
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
// int size = settings.beginReadArray("plugins");
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
listPlugins->clear();
typedef void (*componentLoader)();
typedef char* (*componentStr)();
for (int i=1 ; i<=size; i++)
{
// settings.setArrayIndex(i);
QString titi;
titi = titi.setNum(i);
settings.beginGroup(titi);
QString sfile = settings.readEntry("/location");
settings.endGroup();
//load the plugin libs
QLibrary lib(sfile);
componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
//fill the list view
if (componentLoaderFunc && componentNameFunc)
{
componentLoaderFunc();
QString sname(componentNameFunc());
Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
item->setSelectable(true);
}
}
// settings.endArray();
settings.endGroup();
}
void SofaPluginManager::addLibrary()
{
//get the lib to load
QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog", "Choose the component library to load" );
if(sfile=="")
return;
//try to load the lib
QLibrary lib(sfile);
if (!lib.load())
std::cout<<"Error loading library " << sfile.latin1() <<std::endl;
//get the functions
typedef void (*componentLoader)();
typedef char* (*componentStr)();
componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
if (componentLoaderFunc && componentNameFunc)
{
//fill the list view
componentLoaderFunc();
QString sname(componentNameFunc());
Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
item->setSelectable(true);
//add to the settings (to record it)
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
QString titi;
titi = titi.setNum(size+1);
settings.beginGroup(titi);
settings.writeEntry("/location", sfile);
settings.endGroup();
settings.writeEntry("/size", size+1);
settings.endGroup();
}
else
{
QMessageBox * mbox = new QMessageBox(this,"library loading error");
mbox->setText("Unable to load this library");
mbox->show();
}
}
void SofaPluginManager::removeLibrary()
{
//get the selected item
Q3ListViewItem * curItem = listPlugins->selectedItem();
QString location = curItem->text(1); //get the location value
//remove it from the list view
listPlugins->removeItem(curItem);
//remove it from the settings
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
for (int i=1 ; i<=size; i++)
{
QString titi;
titi = titi.setNum(i);
settings.beginGroup(titi);
QString sfile = settings.readEntry("/location");
if (sfile == location)
settings.removeEntry("/location");
settings.endGroup();
}
settings.endGroup();
}
void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
//update the component list when an item is selected
listComponents->clear();
QString location = curItem->text(1); //get the location value
QLibrary lib(location);
typedef char* (*componentStr)();
componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
if(componentListFunc)
{
QString cpts( componentListFunc() );
cpts.replace(", ","\n");
cpts.replace(",","\n");
listComponents->setText(cpts);
}
}
void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
//update the component list when an item is selected
description->clear();
QString location = curItem->text(1); //get the location value
QLibrary lib(location);
typedef char* (*componentStr)();
componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
if(componentDescFunc)
{
description->setText(QString(componentDescFunc()));
}
}
}
}
}
<commit_msg>r4171/sofa-dev : CHANGE: minor changes in the API of the SofaPluginManager<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "SofaPluginManager.h"
#include "FileManagement.h"
#ifdef SOFA_QT4
//#include <Q3Header>
//#include <Q3PopupMenu>
#include <QMessageBox>
#include <QLibrary>
#include <QSettings>
#include <QTextEdit>
#include <QPushButton>
#else
//#include <qheader.h>
//#include <qpopupmenu.h>
#include <qmessagebox.h>
#include <qlibrary.h>
#include <qsettings.h>
#include <qtextedit.h>
#include <qpushbutton.h>
#endif
#include <iostream>
#ifndef SOFA_QT4
typedef QListViewItem Q3ListViewItem;
#endif
namespace sofa
{
namespace gui
{
namespace qt
{
SofaPluginManager::SofaPluginManager()
{
// SIGNAL / SLOTS CONNECTIONS
this->connect(buttonAdd, SIGNAL(clicked() ), this, SLOT( addLibrary() ));
this->connect(buttonRemove, SIGNAL(clicked() ), this, SLOT( removeLibrary() ));
#ifdef SOFA_QT4
this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));
this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));
#else
this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateComponentList(QListViewItem*) ));
this->connect(listPlugins, SIGNAL(selectionChanged(QListViewItem*) ), this, SLOT(updateDescription(QListViewItem*) ));
#endif
//read the plugin list in the settings
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
// int size = settings.beginReadArray("plugins");
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
listPlugins->clear();
typedef void (*componentLoader)();
typedef const char* (*componentStr)();
for (int i=1 ; i<=size; i++)
{
// settings.setArrayIndex(i);
QString titi;
titi = titi.setNum(i);
settings.beginGroup(titi);
QString sfile = settings.readEntry("/location");
settings.endGroup();
//load the plugin libs
QLibrary lib(sfile);
componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
//fill the list view
if (componentLoaderFunc && componentNameFunc)
{
componentLoaderFunc();
QString sname(componentNameFunc());
Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
item->setSelectable(true);
}
}
// settings.endArray();
settings.endGroup();
}
void SofaPluginManager::addLibrary()
{
//get the lib to load
QString sfile = getOpenFileName ( this, NULL, "dynamic library (*.dll *.so *.dylib)", "load library dialog", "Choose the component library to load" );
if(sfile=="")
return;
//try to load the lib
QLibrary lib(sfile);
if (!lib.load())
std::cout<<"Error loading library " << sfile.latin1() <<std::endl;
//get the functions
typedef void (*componentLoader)();
typedef const char* (*componentStr)();
componentLoader componentLoaderFunc = (componentLoader) lib.resolve("initExternalModule");
componentStr componentNameFunc = (componentStr) lib.resolve("getModuleName");
if (componentLoaderFunc && componentNameFunc)
{
//fill the list view
componentLoaderFunc();
QString sname(componentNameFunc());
Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile);
item->setSelectable(true);
//add to the settings (to record it)
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
QString titi;
titi = titi.setNum(size+1);
settings.beginGroup(titi);
settings.writeEntry("/location", sfile);
settings.endGroup();
settings.writeEntry("/size", size+1);
settings.endGroup();
}
else
{
QMessageBox * mbox = new QMessageBox(this,"library loading error");
mbox->setText("Unable to load this library");
mbox->show();
}
}
void SofaPluginManager::removeLibrary()
{
//get the selected item
Q3ListViewItem * curItem = listPlugins->selectedItem();
QString location = curItem->text(1); //get the location value
//remove it from the list view
listPlugins->removeItem(curItem);
//remove it from the settings
QSettings settings;
settings.setPath( "SOFA-FRAMEWORK", "SOFA",QSettings::User);
settings.beginGroup("/plugins");
int size = settings.readNumEntry("/size");
for (int i=1 ; i<=size; i++)
{
QString titi;
titi = titi.setNum(i);
settings.beginGroup(titi);
QString sfile = settings.readEntry("/location");
if (sfile == location)
settings.removeEntry("/location");
settings.endGroup();
}
settings.endGroup();
}
void SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)
{
//update the component list when an item is selected
listComponents->clear();
QString location = curItem->text(1); //get the location value
QLibrary lib(location);
typedef const char* (*componentStr)();
componentStr componentListFunc = (componentStr) lib.resolve("getModuleComponentList");
if(componentListFunc)
{
QString cpts( componentListFunc() );
cpts.replace(", ","\n");
cpts.replace(",","\n");
listComponents->setText(cpts);
}
}
void SofaPluginManager::updateDescription(Q3ListViewItem* curItem)
{
//update the component list when an item is selected
description->clear();
QString location = curItem->text(1); //get the location value
QLibrary lib(location);
typedef const char* (*componentStr)();
componentStr componentDescFunc = (componentStr) lib.resolve("getModuleDescription");
if(componentDescFunc)
{
description->setText(QString(componentDescFunc()));
}
}
}
}
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_FINITEVOLUME_HH
#define DUNE_GDT_MAPPER_FINITEVOLUME_HH
#include <type_traits>
#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>
#include "../../mapper/interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
// forward, to be used in the traits
template <class GridViewImp, int rangeDim = 1, int rangeDimCols = 1>
class FiniteVolume;
template <class GridViewImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
static_assert(rangeDim >= 1, "Really?");
static_assert(rangeDimCols >= 1, "Really?");
public:
typedef GridViewImp GridViewType;
typedef FiniteVolume<GridViewType, rangeDim, rangeDimCols> derived_type;
typedef typename GridViewImp::IndexSet BackendType;
};
template <class GridViewImp>
class FiniteVolume<GridViewImp, 1, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>>
{
typedef MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>> InterfaceType;
public:
typedef FiniteVolumeTraits<GridViewImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
typedef typename Traits::BackendType BackendType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
FiniteVolume(const GridViewType& grid_view)
: backend_(grid_view.indexSet())
{
}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return backend_.size(0);
}
size_t numDofs(const EntityType& /*entity*/) const
{
return 1;
}
size_t maxNumDofs() const
{
return 1;
}
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
if (ret.size() < 1)
ret.resize(1);
ret[0] = mapToGlobal(entity, 0);
} // ... globalIndices(...)
using InterfaceType::globalIndices;
size_t mapToGlobal(const EntityType& entity, const size_t&
#ifndef NDEBUG
localIndex
#else
/*localIndex*/
#endif
) const
{
assert(localIndex == 0);
return backend_.index(entity);
} // ... mapToGlobal(...)
private:
const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >
template <class GridViewImp, int rangeDim>
class FiniteVolume<GridViewImp, rangeDim, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>>
{
typedef MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
static const unsigned int dimRange = rangeDim;
public:
typedef FiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
typedef typename Traits::BackendType BackendType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
FiniteVolume(const GridViewType& grid_view)
: backend_(grid_view.indexSet())
{
}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return dimRange * backend_.size(0);
}
size_t numDofs(const EntityType& /*entity*/) const
{
return dimRange;
}
size_t maxNumDofs() const
{
return dimRange;
}
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
if (ret.size() < dimRange)
ret.resize(dimRange);
const size_t base = dimRange * backend_.index(entity);
for (size_t ii = 0; ii < dimRange; ++ii)
ret[ii] = base + ii;
} // ... globalIndices(...)
using InterfaceType::globalIndices;
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
assert(localIndex < dimRange);
return (dimRange * backend_.index(entity)) + localIndex;
} // ... mapToGlobal(...)
private:
const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_FINITEVOLUME_HH
<commit_msg>[playground.mapper.finitevolume] use UNUSED_UNLESS_DEBUG<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_FINITEVOLUME_HH
#define DUNE_GDT_MAPPER_FINITEVOLUME_HH
#include <type_traits>
#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/debug.hh>
#include "../../mapper/interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
// forward, to be used in the traits
template <class GridViewImp, int rangeDim = 1, int rangeDimCols = 1>
class FiniteVolume;
template <class GridViewImp, int rangeDim, int rangeDimCols>
class FiniteVolumeTraits
{
static_assert(rangeDim >= 1, "Really?");
static_assert(rangeDimCols >= 1, "Really?");
public:
typedef GridViewImp GridViewType;
typedef FiniteVolume<GridViewType, rangeDim, rangeDimCols> derived_type;
typedef typename GridViewImp::IndexSet BackendType;
};
template <class GridViewImp>
class FiniteVolume<GridViewImp, 1, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>>
{
typedef MapperInterface<FiniteVolumeTraits<GridViewImp, 1, 1>> InterfaceType;
public:
typedef FiniteVolumeTraits<GridViewImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
typedef typename Traits::BackendType BackendType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
FiniteVolume(const GridViewType& grid_view)
: backend_(grid_view.indexSet())
{
}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return backend_.size(0);
}
size_t numDofs(const EntityType& /*entity*/) const
{
return 1;
}
size_t maxNumDofs() const
{
return 1;
}
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
if (ret.size() < 1)
ret.resize(1);
ret[0] = mapToGlobal(entity, 0);
} // ... globalIndices(...)
using InterfaceType::globalIndices;
size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
{
assert(localIndex == 0);
return backend_.index(entity);
} // ... mapToGlobal(...)
private:
const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >
template <class GridViewImp, int rangeDim>
class FiniteVolume<GridViewImp, rangeDim, 1> : public MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>>
{
typedef MapperInterface<FiniteVolumeTraits<GridViewImp, rangeDim, 1>> InterfaceType;
static const unsigned int dimRange = rangeDim;
public:
typedef FiniteVolumeTraits<GridViewImp, rangeDim, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
typedef typename Traits::BackendType BackendType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
FiniteVolume(const GridViewType& grid_view)
: backend_(grid_view.indexSet())
{
}
const BackendType& backend() const
{
return backend_;
}
size_t size() const
{
return dimRange * backend_.size(0);
}
size_t numDofs(const EntityType& /*entity*/) const
{
return dimRange;
}
size_t maxNumDofs() const
{
return dimRange;
}
void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
{
if (ret.size() < dimRange)
ret.resize(dimRange);
const size_t base = dimRange * backend_.index(entity);
for (size_t ii = 0; ii < dimRange; ++ii)
ret[ii] = base + ii;
} // ... globalIndices(...)
using InterfaceType::globalIndices;
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
assert(localIndex < dimRange);
return (dimRange * backend_.index(entity)) + localIndex;
} // ... mapToGlobal(...)
private:
const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_FINITEVOLUME_HH
<|endoftext|> |
<commit_before>// Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <muduo/net/TcpServer.h>
#include <muduo/base/Logging.h>
#include <muduo/net/Acceptor.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/SocketsOps.h>
#include <boost/bind.hpp>
#include <stdio.h> // snprintf
using namespace muduo;
using namespace muduo::net;
TcpServer::TcpServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg)
: loop_(CHECK_NOTNULL(loop)),
hostport_(listenAddr.toIpPort()),
name_(nameArg),
acceptor_(new Acceptor(loop, listenAddr)),
threadPool_(new EventLoopThreadPool(loop)),
connectionCallback_(defaultConnectionCallback),
messageCallback_(defaultMessageCallback),
started_(false),
nextConnId_(1)
{
acceptor_->setNewConnectionCallback(
boost::bind(&TcpServer::newConnection, this, _1, _2));
}
TcpServer::~TcpServer()
{
loop_->assertInLoopThread();
LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing";
for (ConnectionMap::iterator it(connections_.begin());
it != connections_.end(); ++it)
{
TcpConnectionPtr conn = it->second;
it->second.reset();
conn->getLoop()->runInLoop(
boost::bind(&TcpConnection::connectDestroyed, conn));
conn.reset();
}
}
void TcpServer::setThreadNum(int numThreads)
{
assert(0 <= numThreads);
threadPool_->setThreadNum(numThreads);
}
void TcpServer::start()
{
if (!started_)
{
started_ = true;
threadPool_->start(threadInitCallback_);
}
if (!acceptor_->listenning())
{
loop_->runInLoop(
boost::bind(&Acceptor::listen, get_pointer(acceptor_)));
}
}
void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
loop_->assertInLoopThread();
EventLoop* ioLoop = threadPool_->getNextLoop();
char buf[32];
snprintf(buf, sizeof buf, ":%s#%d", hostport_.c_str(), nextConnId_);
++nextConnId_;
string connName = name_ + buf;
LOG_INFO << "TcpServer::newConnection [" << name_
<< "] - new connection [" << connName
<< "] from " << peerAddr.toIpPort();
InetAddress localAddr(sockets::getLocalAddr(sockfd));
// FIXME poll with zero timeout to double confirm the new connection
// FIXME use make_shared if necessary
TcpConnectionPtr conn(new TcpConnection(ioLoop,
connName,
sockfd,
localAddr,
peerAddr));
connections_[connName] = conn;
conn->setConnectionCallback(connectionCallback_);
conn->setMessageCallback(messageCallback_);
conn->setWriteCompleteCallback(writeCompleteCallback_);
conn->setCloseCallback(
boost::bind(&TcpServer::removeConnection, this, _1)); // FIXME: unsafe
ioLoop->runInLoop(boost::bind(&TcpConnection::connectEstablished, conn));
}
void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
// FIXME: unsafe
loop_->runInLoop(boost::bind(&TcpServer::removeConnectionInLoop, this, conn));
}
void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
loop_->assertInLoopThread();
LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
<< "] - connection " << conn->name();
size_t n = connections_.erase(conn->name());
(void)n;
assert(n == 1);
EventLoop* ioLoop = conn->getLoop();
ioLoop->queueInLoop(
boost::bind(&TcpConnection::connectDestroyed, conn));
if (!ioLoop->isInLoopThread())
{
ioLoop->wakeup();
}
}
<commit_msg>remove unnecessary code<commit_after>// Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <muduo/net/TcpServer.h>
#include <muduo/base/Logging.h>
#include <muduo/net/Acceptor.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/SocketsOps.h>
#include <boost/bind.hpp>
#include <stdio.h> // snprintf
using namespace muduo;
using namespace muduo::net;
TcpServer::TcpServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg)
: loop_(CHECK_NOTNULL(loop)),
hostport_(listenAddr.toIpPort()),
name_(nameArg),
acceptor_(new Acceptor(loop, listenAddr)),
threadPool_(new EventLoopThreadPool(loop)),
connectionCallback_(defaultConnectionCallback),
messageCallback_(defaultMessageCallback),
started_(false),
nextConnId_(1)
{
acceptor_->setNewConnectionCallback(
boost::bind(&TcpServer::newConnection, this, _1, _2));
}
TcpServer::~TcpServer()
{
loop_->assertInLoopThread();
LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing";
for (ConnectionMap::iterator it(connections_.begin());
it != connections_.end(); ++it)
{
TcpConnectionPtr conn = it->second;
it->second.reset();
conn->getLoop()->runInLoop(
boost::bind(&TcpConnection::connectDestroyed, conn));
conn.reset();
}
}
void TcpServer::setThreadNum(int numThreads)
{
assert(0 <= numThreads);
threadPool_->setThreadNum(numThreads);
}
void TcpServer::start()
{
if (!started_)
{
started_ = true;
threadPool_->start(threadInitCallback_);
}
if (!acceptor_->listenning())
{
loop_->runInLoop(
boost::bind(&Acceptor::listen, get_pointer(acceptor_)));
}
}
void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
{
loop_->assertInLoopThread();
EventLoop* ioLoop = threadPool_->getNextLoop();
char buf[32];
snprintf(buf, sizeof buf, ":%s#%d", hostport_.c_str(), nextConnId_);
++nextConnId_;
string connName = name_ + buf;
LOG_INFO << "TcpServer::newConnection [" << name_
<< "] - new connection [" << connName
<< "] from " << peerAddr.toIpPort();
InetAddress localAddr(sockets::getLocalAddr(sockfd));
// FIXME poll with zero timeout to double confirm the new connection
// FIXME use make_shared if necessary
TcpConnectionPtr conn(new TcpConnection(ioLoop,
connName,
sockfd,
localAddr,
peerAddr));
connections_[connName] = conn;
conn->setConnectionCallback(connectionCallback_);
conn->setMessageCallback(messageCallback_);
conn->setWriteCompleteCallback(writeCompleteCallback_);
conn->setCloseCallback(
boost::bind(&TcpServer::removeConnection, this, _1)); // FIXME: unsafe
ioLoop->runInLoop(boost::bind(&TcpConnection::connectEstablished, conn));
}
void TcpServer::removeConnection(const TcpConnectionPtr& conn)
{
// FIXME: unsafe
loop_->runInLoop(boost::bind(&TcpServer::removeConnectionInLoop, this, conn));
}
void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn)
{
loop_->assertInLoopThread();
LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_
<< "] - connection " << conn->name();
size_t n = connections_.erase(conn->name());
(void)n;
assert(n == 1);
EventLoop* ioLoop = conn->getLoop();
ioLoop->queueInLoop(
boost::bind(&TcpConnection::connectDestroyed, conn));
}
<|endoftext|> |
<commit_before>#include "realrepoclient.h"
//#define _LONG_DEBUG
#include "dbg.h"
#include <unistd.h>
#include <QDataStream>
#include <QByteArray>
#include <QStringList>
RealRepoClient::RealRepoClient( QObject *parent) : QObject(parent)
{
dbg;
socket = new QTcpSocket(this);
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
socket->abort();
blockSize = 0;
m_error = -1;
socket->connectToHost("127.0.0.1", 6666);
if (!socket->waitForConnected(5*1000)) {
// emit socket->error(socket->error(), socket->errorString());
qDebug() << "nya kawaii" << endl;
return;
}
m_error = socket->error();
}
RealRepoClient::~RealRepoClient()
{
dbg;
socket->disconnectFromHost();
socket->waitForDisconnected();
}
QString RealRepoClient::sendData( QString data )
{
dbg;
if( socket->state() != QAbstractSocket::ConnectedState )
return "";
//QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(id).arg(name);
qDebug() << "[CLIENT]: sending" << data;
//int bytes =
socket->write(data.toUtf8());
// qDebug() << "written " << bytes << " bytes";
//bool res =
socket->waitForReadyRead();
// qDebug() << "ready - " << res;
QByteArray req = socket->readAll();
qDebug() << "[CLIENT]: recvd" << req;
return QString(req);
}
void RealRepoClient::displayError(QAbstractSocket::SocketError socketError)
{
dbg;
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
qDebug() << "QAbstractSocket::RemoteHostClosedError";
break;
case QAbstractSocket::ConnectionRefusedError:
qDebug() << "ConnectionRefusedError";
break;
default:
qDebug() << socket->errorString();
break;
}
m_error = socketError;
}
int RealRepoClient::setName( int type, int id, QString name )
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_NAME).arg(type).arg(id).arg(name);
return sendData(data).toInt();
}
void RealRepoClient::setPosition( int type, int id, int /*parent*/, int x, int y)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
QString resp = sendData(data);
// qDebug() << "recvd" << resp;
}
int RealRepoClient::setPropValue( int type, int id, QString name, QString value)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_PROPERTY).arg(type).arg(id).arg(name).arg(value);
QString resp = sendData(data);
return resp.toInt();
}
QString RealRepoClient::getPropValue( int type, int id, QString name )
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_GET_PROPERTY).arg(type).arg(id).arg(name);
QString resp = sendData(data);
return resp;
}
int RealRepoClient::createEntity(int type, QString name)
{
dbg;
QString data = QString("%1\t%2\t%3\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name);
// qDebug() << "requesting for" << type << name;
QString resp = sendData(data);
return resp.toInt();
// qDebug() << "recvd" << resp;
}
int RealRepoClient::createEntity(int type, QString name, int parent)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name).arg(parent);
QString resp = sendData(data);
return resp.toInt();
// qDebug() << "recvd" << resp;
}
int RealRepoClient::getTypesCount()
{
dbg;
return sendData(QString::number(CMD_GET_TYPES_COUNT)).toInt();
}
QIntList RealRepoClient::getAllTypes()
{
dbg;
QString res = sendData(QString::number(CMD_GET_ALL_TYPES));
QIntList list;
foreach( QString str, res.split('\t') )
list += str.toInt();
return list;
}
TypeInfo RealRepoClient::getTypeInfo( int arg )
{
dbg;
TypeInfo info;
QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(arg);
QString resp = sendData(cmd);
int id = resp.section("\t",0,0).toInt();
if( id == INVALID_ID ){
// handle error
// return info;
}
// qDebug() << "recvd info " << resp;
info.fromString(resp);
return info;
}
int RealRepoClient::getLastError()
{
dbg;
return m_error;
}
QString RealRepoClient::getObjectsByType( int type )
{
QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECTS_BY_TYPE).arg(type);
QString resp = sendData(cmd);
return resp;
}
QIntList RealRepoClient::getObjectsListByType( int type )
{
QString resp = getObjectsByType(type);
QIntList list;
foreach( QString str, resp.split('\t') )
list += str.toInt();
return list;
}
QString RealRepoClient::getObjectData(int id )
{
QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECT_DATA).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getChildren( int type, int id )
{
QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_CHILDREN).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getPosition( int type, int id )
{
QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_POSITION).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
int RealRepoClient::setPosition(int type, int id, int x, int y )
{
QString cmd = QString("%1\t%2\t%3\t%4\t%5").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
QString resp = sendData(cmd);
return resp.toInt();
}
int RealRepoClient::setConfiguration( int type, int id, QString conf)
{
dbg;
QString cmd = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_CONFIGURATION).arg(type).arg(id).arg(conf);
QString resp = sendData(cmd);
return resp.toInt();
}
QString RealRepoClient::getConfiguration( int type, int id)
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_CONFIGURATION).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getEntireObject( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_ENTIRE_OBJECT).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
RealObject* RealRepoClient::getObjectById( int type, int id )
{
dbg;
QString data = getEntireObject(type,id);
RealObject *obj = new RealObject(); // really awful way to do that. need to think it over
// TODO: add RealObject( const QString& ) constructor to make it creat itself
obj->setTypeId(data.section("\t",0,0).toInt());
obj->setId(data.section("\t",1,1).toInt());
obj->setVisibility(true);
obj->setName(data.section("\t",3,3));
obj->setConfiguration(data.section("\t",4,4));
int childCount = data.section("\t",5,5).toInt();
int counter = 6;
for( int i=0; i<childCount; i++){
obj->addChildElement(data.section("\t",counter,counter).toInt());
counter++;
}
int linksCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<linksCount; i++){
obj->addLink(data.section("\t",counter,counter).toInt());
counter++;
}
int propsCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<propsCount; i++ ){
QString pair = data.section("\t",counter,counter);
obj->setProperty(pair.section(";",0,0), pair.section(";",1,1));
counter++;
}
return obj; // implement copy constructor
}
RealLink* RealRepoClient::getLinkById( int type, int id )
{
dbg;
QString data = getEntireObject(type,id);
RealLink *link = new RealLink(); // really awful way to do that. need to think it over
// TODO: add RealLink( const QString& ) constructor to make it creat itself
link->setTypeId(data.section("\t",0,0).toInt());
link->setId(data.section("\t",1,1).toInt());
link->setName(data.section("\t",3,3));
int fromCount = data.section("\t",4,4).toInt();
int counter = 5;
if( fromCount > 0 )
link->setFromId(data.section("\t",counter,counter).toInt());
else
link->setFromId(-1);
counter += fromCount;
int toCount = data.section("\t",counter,counter).toInt();
counter++;
if( toCount > 0 )
link->setToId(data.section("\t",counter,counter).toInt());
else
link->setToId(-1);
counter += toCount;
int propsCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<propsCount; i++ ){
QString pair = data.section("\t",counter,counter);
link->setProperty(pair.section(";",0,0), pair.section(";",1,1));
counter++;
}
return link; // implement copy constructor
}
QString RealRepoClient::getLinksByObject( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_LINKS_BY_OBJECT).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getObjectsByLink( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_OBJECTS_BY_LINK).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QIntList RealRepoClient::getTypesByMetatype( const MetaType arg )
{
dbg;
QString cmd = QString("%1\t%2\t").arg(CMD_GET_TYPES_BY_METATYPE).arg(arg);
QString resp = sendData(cmd);
QIntList list;
foreach( QString str, resp.split('\t') )
list += str.toInt();
return list;
}
RealType* RealRepoClient::getTypeById( const int id )
{
dbg;
QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(id);
QString data = sendData(cmd);
RealType * type = new RealType();
// FIXME: add RealType( const QString& ) constructor to make it create itself
type->loadFromString(data);
return type; // that suxx really hard :D
}
<commit_msg>Make error message more meaningful, not just 'nya kawaii'<commit_after>#include "realrepoclient.h"
//#define _LONG_DEBUG
#include "dbg.h"
#include <unistd.h>
#include <QDataStream>
#include <QByteArray>
#include <QStringList>
RealRepoClient::RealRepoClient( QObject *parent) : QObject(parent)
{
dbg;
socket = new QTcpSocket(this);
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
socket->abort();
blockSize = 0;
m_error = -1;
socket->connectToHost("127.0.0.1", 6666);
if (!socket->waitForConnected(5*1000)) {
// emit socket->error(socket->error(), socket->errorString());
qDebug() << "cannot connect to the server" << endl;
return;
}
m_error = socket->error();
}
RealRepoClient::~RealRepoClient()
{
dbg;
socket->disconnectFromHost();
socket->waitForDisconnected();
}
QString RealRepoClient::sendData( QString data )
{
dbg;
if( socket->state() != QAbstractSocket::ConnectedState )
return "";
//QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(id).arg(name);
qDebug() << "[CLIENT]: sending" << data;
//int bytes =
socket->write(data.toUtf8());
// qDebug() << "written " << bytes << " bytes";
//bool res =
socket->waitForReadyRead();
// qDebug() << "ready - " << res;
QByteArray req = socket->readAll();
qDebug() << "[CLIENT]: recvd" << req;
return QString(req);
}
void RealRepoClient::displayError(QAbstractSocket::SocketError socketError)
{
dbg;
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
qDebug() << "QAbstractSocket::RemoteHostClosedError";
break;
case QAbstractSocket::ConnectionRefusedError:
qDebug() << "ConnectionRefusedError";
break;
default:
qDebug() << socket->errorString();
break;
}
m_error = socketError;
}
int RealRepoClient::setName( int type, int id, QString name )
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_NAME).arg(type).arg(id).arg(name);
return sendData(data).toInt();
}
void RealRepoClient::setPosition( int type, int id, int /*parent*/, int x, int y)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
QString resp = sendData(data);
// qDebug() << "recvd" << resp;
}
int RealRepoClient::setPropValue( int type, int id, QString name, QString value)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_SET_PROPERTY).arg(type).arg(id).arg(name).arg(value);
QString resp = sendData(data);
return resp.toInt();
}
QString RealRepoClient::getPropValue( int type, int id, QString name )
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t%5\t").arg(CMD_GET_PROPERTY).arg(type).arg(id).arg(name);
QString resp = sendData(data);
return resp;
}
int RealRepoClient::createEntity(int type, QString name)
{
dbg;
QString data = QString("%1\t%2\t%3\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name);
// qDebug() << "requesting for" << type << name;
QString resp = sendData(data);
return resp.toInt();
// qDebug() << "recvd" << resp;
}
int RealRepoClient::createEntity(int type, QString name, int parent)
{
dbg;
QString data = QString("%1\t%2\t%3\t%4\t").arg(CMD_CREATE_ENTITY).arg(type).arg(name).arg(parent);
QString resp = sendData(data);
return resp.toInt();
// qDebug() << "recvd" << resp;
}
int RealRepoClient::getTypesCount()
{
dbg;
return sendData(QString::number(CMD_GET_TYPES_COUNT)).toInt();
}
QIntList RealRepoClient::getAllTypes()
{
dbg;
QString res = sendData(QString::number(CMD_GET_ALL_TYPES));
QIntList list;
foreach( QString str, res.split('\t') )
list += str.toInt();
return list;
}
TypeInfo RealRepoClient::getTypeInfo( int arg )
{
dbg;
TypeInfo info;
QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(arg);
QString resp = sendData(cmd);
int id = resp.section("\t",0,0).toInt();
if( id == INVALID_ID ){
// handle error
// return info;
}
// qDebug() << "recvd info " << resp;
info.fromString(resp);
return info;
}
int RealRepoClient::getLastError()
{
dbg;
return m_error;
}
QString RealRepoClient::getObjectsByType( int type )
{
QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECTS_BY_TYPE).arg(type);
QString resp = sendData(cmd);
return resp;
}
QIntList RealRepoClient::getObjectsListByType( int type )
{
QString resp = getObjectsByType(type);
QIntList list;
foreach( QString str, resp.split('\t') )
list += str.toInt();
return list;
}
QString RealRepoClient::getObjectData(int id )
{
QString cmd = QString("%1\t%2").arg(CMD_GET_OBJECT_DATA).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getChildren( int type, int id )
{
QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_CHILDREN).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getPosition( int type, int id )
{
QString cmd = QString("%1\t%2\t%3").arg(CMD_GET_POSITION).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
int RealRepoClient::setPosition(int type, int id, int x, int y )
{
QString cmd = QString("%1\t%2\t%3\t%4\t%5").arg(CMD_SET_POSITION).arg(type).arg(id).arg(x).arg(y);
QString resp = sendData(cmd);
return resp.toInt();
}
int RealRepoClient::setConfiguration( int type, int id, QString conf)
{
dbg;
QString cmd = QString("%1\t%2\t%3\t%4\t").arg(CMD_SET_CONFIGURATION).arg(type).arg(id).arg(conf);
QString resp = sendData(cmd);
return resp.toInt();
}
QString RealRepoClient::getConfiguration( int type, int id)
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_CONFIGURATION).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getEntireObject( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_ENTIRE_OBJECT).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
RealObject* RealRepoClient::getObjectById( int type, int id )
{
dbg;
QString data = getEntireObject(type,id);
RealObject *obj = new RealObject(); // really awful way to do that. need to think it over
// TODO: add RealObject( const QString& ) constructor to make it creat itself
obj->setTypeId(data.section("\t",0,0).toInt());
obj->setId(data.section("\t",1,1).toInt());
obj->setVisibility(true);
obj->setName(data.section("\t",3,3));
obj->setConfiguration(data.section("\t",4,4));
int childCount = data.section("\t",5,5).toInt();
int counter = 6;
for( int i=0; i<childCount; i++){
obj->addChildElement(data.section("\t",counter,counter).toInt());
counter++;
}
int linksCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<linksCount; i++){
obj->addLink(data.section("\t",counter,counter).toInt());
counter++;
}
int propsCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<propsCount; i++ ){
QString pair = data.section("\t",counter,counter);
obj->setProperty(pair.section(";",0,0), pair.section(";",1,1));
counter++;
}
return obj; // implement copy constructor
}
RealLink* RealRepoClient::getLinkById( int type, int id )
{
dbg;
QString data = getEntireObject(type,id);
RealLink *link = new RealLink(); // really awful way to do that. need to think it over
// TODO: add RealLink( const QString& ) constructor to make it creat itself
link->setTypeId(data.section("\t",0,0).toInt());
link->setId(data.section("\t",1,1).toInt());
link->setName(data.section("\t",3,3));
int fromCount = data.section("\t",4,4).toInt();
int counter = 5;
if( fromCount > 0 )
link->setFromId(data.section("\t",counter,counter).toInt());
else
link->setFromId(-1);
counter += fromCount;
int toCount = data.section("\t",counter,counter).toInt();
counter++;
if( toCount > 0 )
link->setToId(data.section("\t",counter,counter).toInt());
else
link->setToId(-1);
counter += toCount;
int propsCount = data.section("\t",counter,counter).toInt();
counter++;
for( int i=0; i<propsCount; i++ ){
QString pair = data.section("\t",counter,counter);
link->setProperty(pair.section(";",0,0), pair.section(";",1,1));
counter++;
}
return link; // implement copy constructor
}
QString RealRepoClient::getLinksByObject( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_LINKS_BY_OBJECT).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QString RealRepoClient::getObjectsByLink( int type, int id )
{
dbg;
QString cmd = QString("%1\t%2\t%3\t").arg(CMD_GET_OBJECTS_BY_LINK).arg(type).arg(id);
QString resp = sendData(cmd);
return resp;
}
QIntList RealRepoClient::getTypesByMetatype( const MetaType arg )
{
dbg;
QString cmd = QString("%1\t%2\t").arg(CMD_GET_TYPES_BY_METATYPE).arg(arg);
QString resp = sendData(cmd);
QIntList list;
foreach( QString str, resp.split('\t') )
list += str.toInt();
return list;
}
RealType* RealRepoClient::getTypeById( const int id )
{
dbg;
QString cmd = QString("%1\t%2").arg(CMD_GET_TYPE_INFO).arg(id);
QString data = sendData(cmd);
RealType * type = new RealType();
// FIXME: add RealType( const QString& ) constructor to make it create itself
type->loadFromString(data);
return type; // that suxx really hard :D
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.