text
stringlengths 54
60.6k
|
|---|
<commit_before>/* Copyright 2016 Carnegie Mellon University
*
* 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 "scanner/video/software/software_video_decoder.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/frame.h"
#include "libavutil/error.h"
#include "libavutil/opt.h"
}
#include <cassert>
namespace scanner {
///////////////////////////////////////////////////////////////////////////////
/// SoftwareVideoDecoder
SoftwareVideoDecoder::SoftwareVideoDecoder(int device_id)
: codec_(nullptr),
cc_(nullptr),
reset_context_(true),
sws_context_(nullptr)
{
av_init_packet(&packet_);
codec_ = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec_) {
fprintf(stderr, "could not find h264 decoder\n");
exit(EXIT_FAILURE);
}
cc_ = avcodec_alloc_context3(codec_);
if (!cc_) {
fprintf(stderr, "could not alloc codec context");
exit(EXIT_FAILURE);
}
if (avcodec_open2(cc_, codec_, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
assert(false);
}
}
SoftwareVideoDecoder::~SoftwareVideoDecoder() {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 53, 0)
avcodec_free_context(&cc_);
#else
avcodec_close(cc_);
av_freep(&cc_);
#endif
for (AVFrame* frame : frame_pool_) {
av_frame_free(&frame);
}
for (AVFrame* frame : decoded_frame_queue_) {
av_frame_free(&frame);
}
}
void SoftwareVideoDecoder::configure(const DatasetItemMetadata& metadata) {
metadata_ = metadata;
reset_context_ = true;
}
bool SoftwareVideoDecoder::feed(
const char* encoded_buffer,
size_t encoded_size,
bool discontinuity)
{
if (av_new_packet(&packet_, encoded_size) < 0) {
fprintf(stderr, "could not allocated packet for feeding into decoder\n");
assert(false);
}
memcpy(packet_.data, encoded_buffer, encoded_size);
uint8_t* orig_data = packet_.data;
int orig_size = packet_.size;
while (packet_.size > 0) {
// Get frame from pool of allocated frames to decode video into
if (frame_pool_.empty()) {
// Create a new frame if our pool is empty
frame_pool_.push_back(av_frame_alloc());
}
AVFrame* frame = frame_pool_.back();
frame_pool_.pop_back();
int got_picture = 0;
int consumed_length =
avcodec_decode_video2(cc_, frame, &got_picture, &packet_);
if (consumed_length < 0) {
char err_msg[256];
av_strerror(consumed_length, err_msg, 256);
fprintf(stderr, "Error while decoding frame (%d): %s\n",
consumed_length, err_msg);
assert(false);
}
if (got_picture) {
if (frame->buf[0] == NULL) {
// Must copy packet as data is stored statically
AVFrame* cloned_frame = av_frame_clone(frame);
if (cloned_frame == NULL) {
fprintf(stderr, "could not clone frame\n");
assert(false);
}
decoded_frame_queue_.push_back(cloned_frame);
av_frame_free(&frame);
} else {
// Frame is reference counted so we can just take it directly
decoded_frame_queue_.push_back(frame);
}
}
packet_.data += consumed_length;
packet_.size -= consumed_length;
}
packet_.data = orig_data;
packet_.size = orig_size;
av_packet_unref(&packet_);
return decoded_frame_queue_.size() > 0;
}
bool SoftwareVideoDecoder::discard_frame() {
AVFrame* frame = decoded_frame_queue_.front();
decoded_frame_queue_.pop_front();
av_frame_unref(frame);
frame_pool_.push_back(frame);
return decoded_frame_queue_.size() > 0;
}
bool SoftwareVideoDecoder::get_frame(
char* decoded_buffer,
size_t decoded_size)
{
int64_t size_left = decoded_size;
AVFrame* frame = decoded_frame_queue_.front();
decoded_frame_queue_.pop_front();
if (reset_context_) {
AVPixelFormat decoder_pixel_format = cc_->pix_fmt;
sws_context_ = sws_getCachedContext(
sws_context_,
metadata_.width,
metadata_.height,
decoder_pixel_format,
metadata_.width,
metadata_.height,
AV_PIX_FMT_RGB24,
SWS_BICUBIC,
NULL,
NULL,
NULL);
}
//int avpicture_get_size(AV_PIX_FMT_RGB24, width2, height2);
for (int i = 0; i < 3; ++i) {
for (int line = 0; line < frame->height; ++line) {
memcpy(decoded_buffer,
frame->data[i] + frame->linesize[i] * line,
std::min(size_left, static_cast<int64_t>(frame->width)));
decoded_buffer += frame->width;
size_left -= frame->width;
if (size_left <= 0) {
line = frame->height;
i = 3;
}
}
}
av_frame_unref(frame);
frame_pool_.push_back(frame);
return decoded_frame_queue_.size() > 0;
}
int SoftwareVideoDecoder::decoded_frames_buffered() {
return decoded_frame_queue_.size();
}
void SoftwareVideoDecoder::wait_until_frames_copied() {
}
}
<commit_msg>Output RGB24 from software decoder<commit_after>/* Copyright 2016 Carnegie Mellon University
*
* 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 "scanner/video/software/software_video_decoder.h"
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
#include "libavutil/frame.h"
#include "libavutil/error.h"
#include "libavutil/opt.h"
}
#include <cassert>
namespace scanner {
///////////////////////////////////////////////////////////////////////////////
/// SoftwareVideoDecoder
SoftwareVideoDecoder::SoftwareVideoDecoder(int device_id)
: codec_(nullptr),
cc_(nullptr),
reset_context_(true),
sws_context_(nullptr)
{
av_init_packet(&packet_);
codec_ = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec_) {
fprintf(stderr, "could not find h264 decoder\n");
exit(EXIT_FAILURE);
}
cc_ = avcodec_alloc_context3(codec_);
if (!cc_) {
fprintf(stderr, "could not alloc codec context");
exit(EXIT_FAILURE);
}
if (avcodec_open2(cc_, codec_, NULL) < 0) {
fprintf(stderr, "could not open codec\n");
assert(false);
}
}
SoftwareVideoDecoder::~SoftwareVideoDecoder() {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 53, 0)
avcodec_free_context(&cc_);
#else
avcodec_close(cc_);
av_freep(&cc_);
#endif
for (AVFrame* frame : frame_pool_) {
av_frame_free(&frame);
}
for (AVFrame* frame : decoded_frame_queue_) {
av_frame_free(&frame);
}
}
void SoftwareVideoDecoder::configure(const DatasetItemMetadata& metadata) {
metadata_ = metadata;
reset_context_ = true;
}
bool SoftwareVideoDecoder::feed(
const char* encoded_buffer,
size_t encoded_size,
bool discontinuity)
{
if (av_new_packet(&packet_, encoded_size) < 0) {
fprintf(stderr, "could not allocated packet for feeding into decoder\n");
assert(false);
}
memcpy(packet_.data, encoded_buffer, encoded_size);
uint8_t* orig_data = packet_.data;
int orig_size = packet_.size;
while (packet_.size > 0) {
// Get frame from pool of allocated frames to decode video into
if (frame_pool_.empty()) {
// Create a new frame if our pool is empty
frame_pool_.push_back(av_frame_alloc());
}
AVFrame* frame = frame_pool_.back();
frame_pool_.pop_back();
int got_picture = 0;
int consumed_length =
avcodec_decode_video2(cc_, frame, &got_picture, &packet_);
if (consumed_length < 0) {
char err_msg[256];
av_strerror(consumed_length, err_msg, 256);
fprintf(stderr, "Error while decoding frame (%d): %s\n",
consumed_length, err_msg);
assert(false);
}
if (got_picture) {
if (frame->buf[0] == NULL) {
// Must copy packet as data is stored statically
AVFrame* cloned_frame = av_frame_clone(frame);
if (cloned_frame == NULL) {
fprintf(stderr, "could not clone frame\n");
assert(false);
}
decoded_frame_queue_.push_back(cloned_frame);
av_frame_free(&frame);
} else {
// Frame is reference counted so we can just take it directly
decoded_frame_queue_.push_back(frame);
}
}
packet_.data += consumed_length;
packet_.size -= consumed_length;
}
packet_.data = orig_data;
packet_.size = orig_size;
av_packet_unref(&packet_);
return decoded_frame_queue_.size() > 0;
}
bool SoftwareVideoDecoder::discard_frame() {
AVFrame* frame = decoded_frame_queue_.front();
decoded_frame_queue_.pop_front();
av_frame_unref(frame);
frame_pool_.push_back(frame);
return decoded_frame_queue_.size() > 0;
}
bool SoftwareVideoDecoder::get_frame(
char* decoded_buffer,
size_t decoded_size)
{
int64_t size_left = decoded_size;
AVFrame* frame = decoded_frame_queue_.front();
decoded_frame_queue_.pop_front();
if (reset_context_) {
AVPixelFormat decoder_pixel_format = cc_->pix_fmt;
sws_context_ = sws_getCachedContext(
sws_context_,
metadata_.width,
metadata_.height,
decoder_pixel_format,
metadata_.width,
metadata_.height,
AV_PIX_FMT_RGB24,
SWS_BICUBIC,
NULL,
NULL,
NULL);
}
if (sws_context_ == NULL) {
fprintf(stderr, "Could not get sws_context for rgb conversion\n");
exit(EXIT_FAILURE);
}
uint8_t* out_slices[4];
int out_linesizes[4];
int required_size = av_image_fill_arrays(
out_slices,
out_linesizes,
reinterpret_cast<uint8_t*>(decoded_buffer),
AV_PIX_FMT_RGB24,
metadata_.width,
metadata_.height,
1);
if (required_size < 0) {
fprintf(stderr, "Error in av_image_fill_arrays\n");
exit(EXIT_FAILURE);
}
if (required_size > decoded_size) {
fprintf(stderr, "Decode buffer not large enough for image\n");
exit(EXIT_FAILURE);
}
if (sws_scale(sws_context_,
frame->data,
frame->linesize,
0,
frame->height,
out_slices,
out_linesizes) < 0)
{
fprintf(stderr, "sws_scale failed\n");
exit(EXIT_FAILURE);
}
av_frame_unref(frame);
frame_pool_.push_back(frame);
return decoded_frame_queue_.size() > 0;
}
int SoftwareVideoDecoder::decoded_frames_buffered() {
return decoded_frame_queue_.size();
}
void SoftwareVideoDecoder::wait_until_frames_copied() {
}
}
<|endoftext|>
|
<commit_before>#ifndef _4fac367e_60d1_4c71_8690_910625d21ebd
#define _4fac367e_60d1_4c71_8690_910625d21ebd
namespace fn{
namespace fn_ {
template<typename T, size_t N_>
class Ring
{
auto static const N = N_ + 1;
size_t p0 = 0;
size_t p1 = 0;
struct T_mem { uint8_t mem[sizeof(T)]; };
T_mem data[N];
public:
Ring(Ring const&) = delete;
Ring() {}
Ring(Ring&& o)
{
T* tmp;
while((tmp = o.pop())){
new (push()) T(fn_::move(*tmp));
tmp->~T();
}
};
bool empty() const { return p0 == p1; }
bool full() const { return (p0+1) % N == p1; }
T* push()
{
if(!full()){
auto const p = p0;
p0 = (p0 + 1) % N;
return reinterpret_cast<T*>(data+p);
}
return nullptr;
}
T* pop()
{
if(!empty()){
auto const p = p1;
p1 = (p1 + 1) % N;
return reinterpret_cast<T*>(data+p);
}
return nullptr;
}
template<typename F>
void remove_if(F f)
{
auto from = p1;
auto to = p1;
while(from < p0){
if(from != to){
reinterpret_cast<T*>(data+to)->~T();
new (data+to) T(fn_::move(*reinterpret_cast<T*>(data+from)));
reinterpret_cast<T*>(data+from)->~T();
}
if(!f(*reinterpret_cast<T*>(data+from))){
to = (to + 1) % N;
}
from = (from + 1) % N;
}
p0 = to;
}
};
}
template<typename T, size_t N>
struct Channel
{
class Sender;
class Receiver
{
friend struct Channel;
Receiver() {}
optional<Sender&> tx;
public:
Receiver(Receiver const&) = delete;
Receiver(Receiver&& o):
tx(fn_::move(o.tx)),
queue(fn_::move(o.queue))
{
tx >>[&](Sender& tx){
tx.rx = *this;
};
}
optional<T> recv()
{
auto const p = queue.pop();
if(p){
optional<T> tmp(fn_::move(*p));
p->~T();
return tmp;
}
return {};
}
template<typename F>
void remove_if(F f)
{
queue.remove_if(f);
}
fn_::Ring<T,N> queue;
};
class Sender
{
friend struct Channel;
optional<Receiver&> rx;
Sender(Receiver& rx):
rx(rx)
{
rx.tx = *this;
}
public:
Sender(Sender const&) = delete;
Sender(Sender&& o):
rx(fn_::move(o.rx))
{
o.rx = {};
}
bool send(T v)
{
return rx >>[&](Receiver& rx){
auto const p = rx.queue.push();
if(p){
new (p) T(fn_::move(v));
return true;
}
return false;
} | false;
}
};
Channel():
tx(rx)
{}
Receiver rx;
Sender tx;
};
}
#endif
<commit_msg>channel: add synchronization via mutex<commit_after>#ifndef _4fac367e_60d1_4c71_8690_910625d21ebd
#define _4fac367e_60d1_4c71_8690_910625d21ebd
#include <mutex>
#include <memory>
namespace fn{
namespace fn_ {
template<typename T, size_t N_>
class Ring
{
auto static const N = N_ + 1;
size_t p0 = 0;
size_t p1 = 0;
struct T_mem { uint8_t mem[sizeof(T)]; };
T_mem data[N];
public:
Ring(Ring const&) = delete;
Ring() {}
Ring operator==(Ring&& o)
{
T* tmp;
while((tmp = o.pop())){
new (push()) T(fn_::move(*tmp));
tmp->~T();
}
};
bool empty() const { return p0 == p1; }
bool full() const { return (p0+1) % N == p1; }
T* push()
{
if(!full()){
auto const p = p0;
p0 = (p0 + 1) % N;
return reinterpret_cast<T*>(data+p);
}
return nullptr;
}
T* pop()
{
if(!empty()){
auto const p = p1;
p1 = (p1 + 1) % N;
return reinterpret_cast<T*>(data+p);
}
return nullptr;
}
template<typename F>
void remove_if(F f)
{
auto from = p1;
auto to = p1;
while(from < p0){
if(from != to){
reinterpret_cast<T*>(data+to)->~T();
new (data+to) T(fn_::move(*reinterpret_cast<T*>(data+from)));
reinterpret_cast<T*>(data+from)->~T();
}
if(!f(*reinterpret_cast<T*>(data+from))){
to = (to + 1) % N;
}
from = (from + 1) % N;
}
p0 = to;
}
};
template<typename Mutex>
struct Guard
{
Mutex& mutex;
Guard(Mutex& mutex): mutex(mutex) { mutex.lock(); }
~Guard() { mutex.unlock(); }
};
template<typename Mutex>
auto guard(Mutex& mutex) -> Guard<Mutex> { return {mutex}; }
}
template<typename T, size_t N>
struct Channel
{
class Sender;
class Receiver
{
friend struct Channel;
Receiver() {}
optional<Sender&> tx;
std::shared_ptr<std::mutex> mutex;
public:
Receiver(Receiver const&) = delete;
Receiver(Receiver&& o):
mutex(fn_::move(o.mutex))
{
if(!mutex){ return; }
auto guard = fn_::guard(*mutex);
tx = fn_::move(o.tx);
queue = fn_::move(o.queue);
tx >>[&](Sender& tx){
tx.rx = *this;
};
}
optional<T> recv()
{
if(!mutex){ return {}; }
auto guard = fn_::guard(*mutex);
auto const p = queue.pop();
if(p){
optional<T> tmp(fn_::move(*p));
p->~T();
return tmp;
}
return {};
}
template<typename F>
void remove_if(F f)
{
if(!mutex){ return; }
auto guard = fn_::guard(*mutex);
queue.remove_if(f);
}
fn_::Ring<T,N> queue;
};
class Sender
{
friend struct Channel;
optional<Receiver&> rx;
std::shared_ptr<std::mutex> mutex;
Sender(Receiver& rx):
rx(rx)
{
rx.tx = *this;
}
public:
Sender(Sender const&) = delete;
Sender(Sender&& o):
mutex(fn_::move(o.mutex))
{
if(!mutex){ return; }
auto guard = fn_::guard(*mutex);
rx = fn_::move(o.rx);
o.rx = {};
}
bool send(T v)
{
if(!mutex){ return false; }
auto guard = fn_::guard(*mutex);
return rx >>[&](Receiver& rx){
auto const p = rx.queue.push();
if(p){
new (p) T(fn_::move(v));
return true;
}
return false;
} | false;
}
};
Channel():
tx(rx)
{
tx.mutex = rx.mutex = std::make_shared<std::mutex>();
}
Receiver rx;
Sender tx;
};
}
#endif
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include "strategy.h"
#include "strategy_evaluator.h"
#include "strategy_evaluation_context.h"
#include "estimator.h"
#include "resource_weights.h"
#include <vector>
#include <set>
#include "small_set.h"
#include "debug.h"
Strategy::Strategy(eval_fn_t time_fn_,
eval_fn_t energy_cost_fn_,
eval_fn_t data_cost_fn_,
void *strategy_arg_,
void *default_chooser_arg_)
: time_fn((typesafe_eval_fn_t) time_fn_),
energy_cost_fn((typesafe_eval_fn_t) energy_cost_fn_),
data_cost_fn((typesafe_eval_fn_t) data_cost_fn_),
strategy_arg(strategy_arg_),
default_chooser_arg(default_chooser_arg_)
{
assert(time_fn != energy_cost_fn);
assert(time_fn != data_cost_fn);
assert(energy_cost_fn != data_cost_fn);
collectEstimators();
setEvalFnLookupArray();
}
void
Strategy::setEvalFnLookupArray()
{
fns[TIME_FN] = time_fn;
fns[ENERGY_FN] = energy_cost_fn;
fns[DATA_FN] = data_cost_fn;
}
/* fake context that just collects all the estimators
* that the given strategy uses. */
class EstimatorCollector : public StrategyEvaluationContext {
Strategy *strategy;
public:
EstimatorCollector(Strategy *s) : strategy(s) {}
virtual double getAdjustedEstimatorValue(Estimator *estimator) {
strategy->addEstimator(estimator);
return estimator->getEstimate();
}
};
void
Strategy::collectEstimators()
{
// run all the eval functions and add all their estimators
// to this strategy.
EstimatorCollector collector(this);
if (time_fn) {
(void)time_fn(&collector, strategy_arg, default_chooser_arg);
}
if (energy_cost_fn) {
(void)energy_cost_fn(&collector, strategy_arg, default_chooser_arg);
}
if (data_cost_fn) {
(void)data_cost_fn(&collector, strategy_arg, default_chooser_arg);
}
}
void
Strategy::addEstimator(Estimator *estimator)
{
estimators.insert(estimator);
}
void
Strategy::getAllEstimators(StrategyEvaluator *evaluator)
{
for (small_set<Estimator*>::const_iterator it = estimators.begin();
it != estimators.end(); ++it) {
Estimator *estimator = *it;
evaluator->addEstimator(estimator);
}
}
bool
Strategy::usesEstimator(Estimator *estimator)
{
return (estimators.count(estimator) != 0);
}
double
Strategy::calculateTime(StrategyEvaluator *evaluator, void *chooser_arg)
{
return evaluator->expectedValue(this, time_fn, strategy_arg, chooser_arg);
}
double
Strategy::calculateCost(StrategyEvaluator *evaluator, void *chooser_arg)
{
double energy_cost = 0.0, data_cost = 0.0;
if (energy_cost_fn) {
energy_cost = evaluator->expectedValue(this, energy_cost_fn,
strategy_arg, chooser_arg);
}
if (data_cost_fn) {
data_cost = evaluator->expectedValue(this, data_cost_fn,
strategy_arg, chooser_arg);
}
double energy_weight = get_energy_cost_weight();
double data_weight = get_data_cost_weight();
dbgprintf(" Raw energy cost: %f energy weight: %f Weighted energy cost: %f\n",
energy_cost, energy_weight, energy_cost * energy_weight);
dbgprintf(" Raw data cost: %f data weight: %f Weighted data cost: %f\n",
data_cost, data_weight, data_cost * data_weight);
return ((energy_cost * energy_weight) + (data_cost * data_weight));
}
bool
Strategy::isRedundant()
{
return !child_strategies.empty();
}
double
redundant_strategy_minimum_time(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double best_time = DBL_MAX;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
double time = child->time_fn(ctx, child->strategy_arg, chooser_arg);
if (time < best_time) {
best_time = time;
}
}
return best_time;
}
double
redundant_strategy_total_energy_cost(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double total_cost = 0.0;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
if (child->energy_cost_fn) {
double cost = child->energy_cost_fn(ctx, child->strategy_arg, chooser_arg);
total_cost += cost;
}
}
return total_cost;
}
double
redundant_strategy_total_data_cost(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double total_cost = 0.0;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
if (child->data_cost_fn) {
double cost = child->data_cost_fn(ctx, child->strategy_arg, chooser_arg);
total_cost += cost;
}
}
return total_cost;
}
Strategy::Strategy(const instruments_strategy_t strategies[],
size_t num_strategies)
: time_fn(redundant_strategy_minimum_time),
energy_cost_fn(redundant_strategy_total_energy_cost),
data_cost_fn(redundant_strategy_total_data_cost),
strategy_arg(this), default_chooser_arg(NULL)
{
for (size_t i = 0; i < num_strategies; ++i) {
this->child_strategies.push_back((Strategy *) strategies[i]);
}
collectEstimators();
setEvalFnLookupArray();
}
const std::vector<Strategy *>&
Strategy::getChildStrategies()
{
return child_strategies;
}
bool
Strategy::childrenAreDisjoint()
{
std::set<Estimator *> all_estimators;
for (size_t i = 0; i < child_strategies.size(); ++i) {
Strategy *child = child_strategies[i];
for (small_set<Estimator*>::const_iterator it = child->estimators.begin();
it != child->estimators.end(); ++it) {
if (all_estimators.count(*it) > 0) {
return false;
}
all_estimators.insert(*it);
}
}
return true;
}
typesafe_eval_fn_t
Strategy::getEvalFn(eval_fn_type_t type)
{
return fns[type];
}
std::vector<Estimator *>
Strategy::getEstimators()
{
return std::vector<Estimator *>(estimators.begin(), estimators.end());
}
<commit_msg>Made the cost display more concise.<commit_after>#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include "strategy.h"
#include "strategy_evaluator.h"
#include "strategy_evaluation_context.h"
#include "estimator.h"
#include "resource_weights.h"
#include <vector>
#include <set>
#include "small_set.h"
#include "debug.h"
Strategy::Strategy(eval_fn_t time_fn_,
eval_fn_t energy_cost_fn_,
eval_fn_t data_cost_fn_,
void *strategy_arg_,
void *default_chooser_arg_)
: time_fn((typesafe_eval_fn_t) time_fn_),
energy_cost_fn((typesafe_eval_fn_t) energy_cost_fn_),
data_cost_fn((typesafe_eval_fn_t) data_cost_fn_),
strategy_arg(strategy_arg_),
default_chooser_arg(default_chooser_arg_)
{
assert(time_fn != energy_cost_fn);
assert(time_fn != data_cost_fn);
assert(energy_cost_fn != data_cost_fn);
collectEstimators();
setEvalFnLookupArray();
}
void
Strategy::setEvalFnLookupArray()
{
fns[TIME_FN] = time_fn;
fns[ENERGY_FN] = energy_cost_fn;
fns[DATA_FN] = data_cost_fn;
}
/* fake context that just collects all the estimators
* that the given strategy uses. */
class EstimatorCollector : public StrategyEvaluationContext {
Strategy *strategy;
public:
EstimatorCollector(Strategy *s) : strategy(s) {}
virtual double getAdjustedEstimatorValue(Estimator *estimator) {
strategy->addEstimator(estimator);
return estimator->getEstimate();
}
};
void
Strategy::collectEstimators()
{
// run all the eval functions and add all their estimators
// to this strategy.
EstimatorCollector collector(this);
if (time_fn) {
(void)time_fn(&collector, strategy_arg, default_chooser_arg);
}
if (energy_cost_fn) {
(void)energy_cost_fn(&collector, strategy_arg, default_chooser_arg);
}
if (data_cost_fn) {
(void)data_cost_fn(&collector, strategy_arg, default_chooser_arg);
}
}
void
Strategy::addEstimator(Estimator *estimator)
{
estimators.insert(estimator);
}
void
Strategy::getAllEstimators(StrategyEvaluator *evaluator)
{
for (small_set<Estimator*>::const_iterator it = estimators.begin();
it != estimators.end(); ++it) {
Estimator *estimator = *it;
evaluator->addEstimator(estimator);
}
}
bool
Strategy::usesEstimator(Estimator *estimator)
{
return (estimators.count(estimator) != 0);
}
double
Strategy::calculateTime(StrategyEvaluator *evaluator, void *chooser_arg)
{
return evaluator->expectedValue(this, time_fn, strategy_arg, chooser_arg);
}
double
Strategy::calculateCost(StrategyEvaluator *evaluator, void *chooser_arg)
{
double energy_cost = 0.0, data_cost = 0.0;
if (energy_cost_fn) {
energy_cost = evaluator->expectedValue(this, energy_cost_fn,
strategy_arg, chooser_arg);
}
if (data_cost_fn) {
data_cost = evaluator->expectedValue(this, data_cost_fn,
strategy_arg, chooser_arg);
}
double energy_weight = get_energy_cost_weight();
double data_weight = get_data_cost_weight();
dbgprintf(" Energy cost: %f * %f = %f\n",
energy_cost, energy_weight, energy_cost * energy_weight);
dbgprintf(" Data cost: %f * %f = %f\n",
data_cost, data_weight, data_cost * data_weight);
return ((energy_cost * energy_weight) + (data_cost * data_weight));
}
bool
Strategy::isRedundant()
{
return !child_strategies.empty();
}
double
redundant_strategy_minimum_time(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double best_time = DBL_MAX;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
double time = child->time_fn(ctx, child->strategy_arg, chooser_arg);
if (time < best_time) {
best_time = time;
}
}
return best_time;
}
double
redundant_strategy_total_energy_cost(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double total_cost = 0.0;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
if (child->energy_cost_fn) {
double cost = child->energy_cost_fn(ctx, child->strategy_arg, chooser_arg);
total_cost += cost;
}
}
return total_cost;
}
double
redundant_strategy_total_data_cost(StrategyEvaluationContext *ctx, void *arg, void *chooser_arg)
{
Strategy *parent = (Strategy *) arg;
double total_cost = 0.0;
for (size_t i = 0; i < parent->child_strategies.size(); ++i) {
Strategy *child = parent->child_strategies[i];
if (child->data_cost_fn) {
double cost = child->data_cost_fn(ctx, child->strategy_arg, chooser_arg);
total_cost += cost;
}
}
return total_cost;
}
Strategy::Strategy(const instruments_strategy_t strategies[],
size_t num_strategies)
: time_fn(redundant_strategy_minimum_time),
energy_cost_fn(redundant_strategy_total_energy_cost),
data_cost_fn(redundant_strategy_total_data_cost),
strategy_arg(this), default_chooser_arg(NULL)
{
for (size_t i = 0; i < num_strategies; ++i) {
this->child_strategies.push_back((Strategy *) strategies[i]);
}
collectEstimators();
setEvalFnLookupArray();
}
const std::vector<Strategy *>&
Strategy::getChildStrategies()
{
return child_strategies;
}
bool
Strategy::childrenAreDisjoint()
{
std::set<Estimator *> all_estimators;
for (size_t i = 0; i < child_strategies.size(); ++i) {
Strategy *child = child_strategies[i];
for (small_set<Estimator*>::const_iterator it = child->estimators.begin();
it != child->estimators.end(); ++it) {
if (all_estimators.count(*it) > 0) {
return false;
}
all_estimators.insert(*it);
}
}
return true;
}
typesafe_eval_fn_t
Strategy::getEvalFn(eval_fn_type_t type)
{
return fns[type];
}
std::vector<Estimator *>
Strategy::getEstimators()
{
return std::vector<Estimator *>(estimators.begin(), estimators.end());
}
<|endoftext|>
|
<commit_before>#include "nlnscg.h"
namespace utils {
nlnscg::nlnscg(unsigned n, const vec& metric)
: n(n), metric(metric), k(0), g2(0), p( vec::Zero(n) ) {
}
void nlnscg::operator()(vec& x) {
if( k > 0 ) {
g = old - x;
const real tmp = metric.size() ? g.dot( metric.cwiseProduct(g) ) : g.dot(g);
real beta = 0;
if(g2) {
beta = tmp / g2;
if( beta <= 1 ) {
x += beta * p;
p = beta * p - g;
} else {
p.setZero();
}
}
g2 = tmp;
}
old = x;
++k;
}
}
<commit_msg>[Compliant] fixing a warning<commit_after>#include "nlnscg.h"
namespace utils {
nlnscg::nlnscg(unsigned n, const vec& metric)
: n(n), metric(metric), k(0), p( vec::Zero(n) ), g2(0) {
}
void nlnscg::operator()(vec& x) {
if( k > 0 ) {
g = old - x;
const real tmp = metric.size() ? g.dot( metric.cwiseProduct(g) ) : g.dot(g);
real beta = 0;
if(g2) {
beta = tmp / g2;
if( beta <= 1 ) {
x += beta * p;
p = beta * p - g;
} else {
p.setZero();
}
}
g2 = tmp;
}
old = x;
++k;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Linux gcc4.4 fix: stop crashing when loading flash. sizeof(bool) is 1 byte in opt mode. We pass a pointer to a bool to a function expecting a void*. It writes 4 bytes of data to the pointer, rather than 1 byte. This corrupts the stack bordering the bool stack variable, thereby manifesting itself as a crash. In particular, we were overwriting a spilled register (which stored an object pointer) with 3 bytes worth of zeros. After returning from the function, we called into the object, which now had the wrong pointer. BUG=http://crbug.com/20045<commit_after><|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "CoreStringUtils.h"
#include <QTextStream>
QString QStringFromWCharArray(const wchar_t *string, int size)
{
QString qstr;
if (sizeof(wchar_t) == sizeof(QChar))
return qstr.fromUtf16((const ushort *)string, size);
else
return qstr.fromUcs4((uint *)string, size);
}
int QStringToWCharArray(const QString &qstr, wchar_t *array)
{
if (sizeof(wchar_t) == sizeof(QChar))
{
memcpy(array, qstr.utf16(), sizeof(wchar_t)*qstr.length());
return qstr.length();
}
else
{
wchar_t *a = array;
const unsigned short *uc = qstr.utf16();
for (int i = 0; i < qstr.length(); ++i)
{
uint u = uc[i];
if (QChar(u).isHighSurrogate() && i + 1 < qstr.length())
{
ushort low = uc[i+1];
if (QChar(low).isLowSurrogate())
{
u = QChar::surrogateToUcs4(u, low);
++i;
}
}
*a = wchar_t(u);
++a;
}
return a - array;
}
}
std::wstring QStringToWString(const QString &qstr)
{
if (qstr.length() == 0)
return L"";
std::wstring str;
str.resize(qstr.length());
str.resize(QStringToWCharArray(qstr, &(*str.begin())));
return str;
}
QString WStringToQString(const std::wstring &str)
{
if (str.length() == 0)
return "";
return QStringFromWCharArray(str.data(), str.size());
}
std::wstring ToWString(const std::string &str)
{
std::wstring w_str(str.length(), L' ');
std::copy(str.begin(), str.end(), w_str.begin());
return w_str;
}
std::string BufferToString(const std::vector<s8>& buffer)
{
if (!buffer.empty())
return std::string((const char*)&buffer[0], buffer.size());
else
return std::string();
}
std::vector<s8> StringToBuffer(const std::string& str)
{
std::vector<s8> ret;
ret.resize(str.size());
if (str.size())
memcpy(&ret[0], &str[0], str.size());
return ret;
}
QByteArray RemoveLines(const QByteArray &data, QStringList linePrefixes, uint *removedLineCount)
{
if (removedLineCount != 0)
*removedLineCount = 0;
QByteArray result;
QTextStream out(&result, QIODevice::WriteOnly);
QTextStream in(data, QIODevice::ReadOnly);
while (!in.atEnd())
{
QString line = in.readLine();
bool found = false;
foreach(const QString &commentPrefix, linePrefixes)
{
found = line.simplified().startsWith(commentPrefix, Qt::CaseSensitive);
if (found)
break;
}
if (!found)
{
// readLine() removes end-of-line characters, preserve them.
out << line;
if (!in.atEnd())
out << endl;
}
else if (removedLineCount != 0)
*removedLineCount += 1;
}
return result;
}
StringVector SplitString(const std::string& str, char separator)
{
std::vector<std::string> vec;
unsigned pos = 0;
while(pos < str.length())
{
unsigned start = pos;
while(start < str.length())
{
if (str[start] == separator)
break;
start++;
}
if (start == str.length())
{
vec.push_back(str.substr(pos));
break;
}
unsigned end = start;
while(end < str.length())
{
if (str[end] != separator)
break;
end++;
}
vec.push_back(str.substr(pos, start - pos));
pos = end;
}
return vec;
}
std::string ReplaceSubstring(const std::string &str, const std::string &replace_this, const std::string &replace_with)
{
std::string ret = str;
ReplaceSubstringInplace(ret, replace_this, replace_with);
return ret;
}
std::string ReplaceChar(const std::string& str, char replace_this, char replace_with)
{
std::string ret = str;
ReplaceCharInplace(ret, replace_this, replace_with);
return ret;
}
void ReplaceSubstringInplace(std::string &str, const std::string &replace_this, const std::string &replace_with)
{
std::size_t index = str.find(replace_this, 0);
while(index != std::string::npos)
{
str.replace(index, replace_this.length(), replace_with);
index = str.find(replace_this, 0);
}
}
void ReplaceCharInplace(std::string& str, char replace_this, char replace_with)
{
for(uint i = 0; i < str.length(); ++i)
if (str[i] == replace_this) str[i] = replace_with;
}
uint ComputeHash(const std::string& str)
{
uint ret = 0;
if (!str.length())
return ret;
const char* cstr = str.c_str();
while(*cstr)
{
// Note: calculate case-insensitive hash
char c = *cstr;
ret = tolower(c) + (ret << 6) + (ret << 16) - ret;
++cstr;
}
return ret;
}
bool ParseBool(QString value)
{
value = value.trimmed().toLower();
if (value.isEmpty())
return false;
if (value == "1")
return true;
if (value == "on")
return true;
if (value == "true")
return true;
return false;
}
<commit_msg>CoreStringUtils::RemoveLines: Fix bug that left out the last endl from the file.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "CoreStringUtils.h"
#include <QTextStream>
QString QStringFromWCharArray(const wchar_t *string, int size)
{
QString qstr;
if (sizeof(wchar_t) == sizeof(QChar))
return qstr.fromUtf16((const ushort *)string, size);
else
return qstr.fromUcs4((uint *)string, size);
}
int QStringToWCharArray(const QString &qstr, wchar_t *array)
{
if (sizeof(wchar_t) == sizeof(QChar))
{
memcpy(array, qstr.utf16(), sizeof(wchar_t)*qstr.length());
return qstr.length();
}
else
{
wchar_t *a = array;
const unsigned short *uc = qstr.utf16();
for (int i = 0; i < qstr.length(); ++i)
{
uint u = uc[i];
if (QChar(u).isHighSurrogate() && i + 1 < qstr.length())
{
ushort low = uc[i+1];
if (QChar(low).isLowSurrogate())
{
u = QChar::surrogateToUcs4(u, low);
++i;
}
}
*a = wchar_t(u);
++a;
}
return a - array;
}
}
std::wstring QStringToWString(const QString &qstr)
{
if (qstr.length() == 0)
return L"";
std::wstring str;
str.resize(qstr.length());
str.resize(QStringToWCharArray(qstr, &(*str.begin())));
return str;
}
QString WStringToQString(const std::wstring &str)
{
if (str.length() == 0)
return "";
return QStringFromWCharArray(str.data(), str.size());
}
std::wstring ToWString(const std::string &str)
{
std::wstring w_str(str.length(), L' ');
std::copy(str.begin(), str.end(), w_str.begin());
return w_str;
}
std::string BufferToString(const std::vector<s8>& buffer)
{
if (!buffer.empty())
return std::string((const char*)&buffer[0], buffer.size());
else
return std::string();
}
std::vector<s8> StringToBuffer(const std::string& str)
{
std::vector<s8> ret;
ret.resize(str.size());
if (str.size())
memcpy(&ret[0], &str[0], str.size());
return ret;
}
QByteArray RemoveLines(const QByteArray &data, QStringList linePrefixes, uint *removedLineCount)
{
if (removedLineCount != 0)
*removedLineCount = 0;
QByteArray result;
QTextStream out(&result, QIODevice::WriteOnly);
QTextStream in(data, QIODevice::ReadOnly);
while (!in.atEnd())
{
QString line = in.readLine();
bool found = false;
foreach(const QString &commentPrefix, linePrefixes)
{
found = line.simplified().startsWith(commentPrefix, Qt::CaseSensitive);
if (found)
break;
}
if (!found)
{
// readLine() removes end-of-line characters, preserve them.
out << line << endl;
}
else if (removedLineCount != 0)
*removedLineCount += 1;
}
return result;
}
StringVector SplitString(const std::string& str, char separator)
{
std::vector<std::string> vec;
unsigned pos = 0;
while(pos < str.length())
{
unsigned start = pos;
while(start < str.length())
{
if (str[start] == separator)
break;
start++;
}
if (start == str.length())
{
vec.push_back(str.substr(pos));
break;
}
unsigned end = start;
while(end < str.length())
{
if (str[end] != separator)
break;
end++;
}
vec.push_back(str.substr(pos, start - pos));
pos = end;
}
return vec;
}
std::string ReplaceSubstring(const std::string &str, const std::string &replace_this, const std::string &replace_with)
{
std::string ret = str;
ReplaceSubstringInplace(ret, replace_this, replace_with);
return ret;
}
std::string ReplaceChar(const std::string& str, char replace_this, char replace_with)
{
std::string ret = str;
ReplaceCharInplace(ret, replace_this, replace_with);
return ret;
}
void ReplaceSubstringInplace(std::string &str, const std::string &replace_this, const std::string &replace_with)
{
std::size_t index = str.find(replace_this, 0);
while(index != std::string::npos)
{
str.replace(index, replace_this.length(), replace_with);
index = str.find(replace_this, 0);
}
}
void ReplaceCharInplace(std::string& str, char replace_this, char replace_with)
{
for(uint i = 0; i < str.length(); ++i)
if (str[i] == replace_this) str[i] = replace_with;
}
uint ComputeHash(const std::string& str)
{
uint ret = 0;
if (!str.length())
return ret;
const char* cstr = str.c_str();
while(*cstr)
{
// Note: calculate case-insensitive hash
char c = *cstr;
ret = tolower(c) + (ret << 6) + (ret << 16) - ret;
++cstr;
}
return ret;
}
bool ParseBool(QString value)
{
value = value.trimmed().toLower();
if (value.isEmpty())
return false;
if (value == "1")
return true;
if (value == "on")
return true;
if (value == "true")
return true;
return false;
}
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------------//
/// Copyright (c) 2017 by Milos Tosic. All Rights Reserved. ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause ///
//--------------------------------------------------------------------------//
#include <rbase_pch.h>
namespace rtm {
char toNoop(char _ch)
{
return _ch;
}
bool isUpper(char _ch)
{
return _ch >= 'A' && _ch <= 'Z';
}
bool isLower(char _ch)
{
return _ch >= 'a' && _ch <= 'z';
}
char toLower(char _ch)
{
return _ch + (isUpper(_ch) ? 0x20 : 0);
}
char toUpper(char _ch)
{
return _ch - (isLower(_ch) ? 0x20 : 0);
}
char *strdup(const char* _str)
{
size_t len = strlen(_str);
char* ret = new char[len + 1];
strcpy(ret, _str);
return ret;
}
} // namespace rtm
<commit_msg>Cleanup<commit_after>//--------------------------------------------------------------------------//
/// Copyright (c) 2017 by Milos Tosic. All Rights Reserved. ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause ///
//--------------------------------------------------------------------------//
#include <rbase_pch.h>
namespace rtm {
char toNoop(char _ch)
{
return _ch;
}
bool isUpper(char _ch)
{
return _ch >= 'A' && _ch <= 'Z';
}
bool isLower(char _ch)
{
return _ch >= 'a' && _ch <= 'z';
}
char toLower(char _ch)
{
return _ch + (isUpper(_ch) ? 0x20 : 0);
}
char toUpper(char _ch)
{
return _ch - (isLower(_ch) ? 0x20 : 0);
}
char *strdup(const char* _str)
{
size_t len = strlen(_str);
char* ret = new char[len + 1];
strcpy(ret, _str);
return ret;
}
} // namespace rtm
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006, 2007, 2008 Apple 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:
* 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "EventHandler.h"
#include "ChromiumDataObject.h"
#include "ClipboardChromium.h"
#include "Cursor.h"
#include "FloatPoint.h"
#include "FocusController.h"
#include "FrameView.h"
#include "Frame.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "MouseEventWithHitTestResults.h"
#include "Page.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformWheelEvent.h"
#include "RenderWidget.h"
#include "SelectionController.h"
#include "NotImplemented.h"
namespace WebCore {
const double EventHandler::TextDragDelay = 0.0;
bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
{
// If we're clicking into a frame that is selected, the frame will appear
// greyed out even though we're clicking on the selection. This looks
// really strange (having the whole frame be greyed out), so we deselect the
// selection.
IntPoint p = m_frame->view()->windowToContents(mev.event().pos());
if (m_frame->selection()->contains(p)) {
VisiblePosition visiblePos(
mev.targetNode()->renderer()->positionForPoint(mev.localPoint()));
Selection newSelection(visiblePos);
if (m_frame->shouldChangeSelection(newSelection))
m_frame->selection()->setSelection(newSelection);
}
subframe->eventHandler()->handleMousePressEvent(mev.event());
return true;
}
bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe, HitTestResult* hoveredNode)
{
if (m_mouseDownMayStartDrag && !m_mouseDownWasInSubframe)
return false;
subframe->eventHandler()->handleMouseMoveEvent(mev.event(), hoveredNode);
return true;
}
bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
{
subframe->eventHandler()->handleMouseReleaseEvent(mev.event());
return true;
}
bool EventHandler::passWheelEventToWidget(PlatformWheelEvent& wheelEvent, Widget* widget)
{
if (!widget) {
// We can sometimes get a null widget! EventHandlerMac handles a null
// widget by returning false, so we do the same.
return false;
}
if (!widget->isFrameView()) {
// Probably a plugin widget. They will receive the event via an
// EventTargetNode dispatch when this returns false.
return false;
}
return static_cast<FrameView*>(widget)->frame()->eventHandler()->handleWheelEvent(wheelEvent);
}
bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event)
{
// Figure out which view to send the event to.
if (!event.targetNode() || !event.targetNode()->renderer() || !event.targetNode()->renderer()->isWidget())
return false;
return passMouseDownEventToWidget(static_cast<RenderWidget*>(event.targetNode()->renderer())->widget());
}
bool EventHandler::passMouseDownEventToWidget(Widget* widget)
{
notImplemented();
return false;
}
bool EventHandler::tabsToAllControls(KeyboardEvent*) const
{
return true;
}
bool EventHandler::eventActivatedView(const PlatformMouseEvent& event) const
{
// TODO(darin): Apple's EventHandlerWin.cpp does the following:
// return event.activatedWebView();
return false;
}
PassRefPtr<Clipboard> EventHandler::createDraggingClipboard() const
{
RefPtr<ChromiumDataObject> dataObject = ChromiumDataObject::create();
return ClipboardChromium::create(true, dataObject.get(), ClipboardWritable);
}
void EventHandler::focusDocumentView()
{
Page* page = m_frame->page();
if (!page)
return;
page->focusController()->setFocusedFrame(m_frame);
}
bool EventHandler::passWidgetMouseDownEventToWidget(RenderWidget* renderWidget)
{
return passMouseDownEventToWidget(renderWidget->widget());
}
unsigned EventHandler::accessKeyModifiers()
{
return PlatformKeyboardEvent::AltKey;
}
}
<commit_msg>add drag delay for mac In upstream WebKit, this is split out by platform specific files.<commit_after>/*
* Copyright (C) 2006, 2007, 2008 Apple 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:
* 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "EventHandler.h"
#include "ChromiumDataObject.h"
#include "ClipboardChromium.h"
#include "Cursor.h"
#include "FloatPoint.h"
#include "FocusController.h"
#include "FrameView.h"
#include "Frame.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "MouseEventWithHitTestResults.h"
#include "Page.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformWheelEvent.h"
#include "RenderWidget.h"
#include "SelectionController.h"
#include "NotImplemented.h"
namespace WebCore {
#if PLATFORM(DARWIN)
const double EventHandler::TextDragDelay = 0.15;
#else
const double EventHandler::TextDragDelay = 0.0;
#endif
bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
{
// If we're clicking into a frame that is selected, the frame will appear
// greyed out even though we're clicking on the selection. This looks
// really strange (having the whole frame be greyed out), so we deselect the
// selection.
IntPoint p = m_frame->view()->windowToContents(mev.event().pos());
if (m_frame->selection()->contains(p)) {
VisiblePosition visiblePos(
mev.targetNode()->renderer()->positionForPoint(mev.localPoint()));
Selection newSelection(visiblePos);
if (m_frame->shouldChangeSelection(newSelection))
m_frame->selection()->setSelection(newSelection);
}
subframe->eventHandler()->handleMousePressEvent(mev.event());
return true;
}
bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe, HitTestResult* hoveredNode)
{
if (m_mouseDownMayStartDrag && !m_mouseDownWasInSubframe)
return false;
subframe->eventHandler()->handleMouseMoveEvent(mev.event(), hoveredNode);
return true;
}
bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
{
subframe->eventHandler()->handleMouseReleaseEvent(mev.event());
return true;
}
bool EventHandler::passWheelEventToWidget(PlatformWheelEvent& wheelEvent, Widget* widget)
{
if (!widget) {
// We can sometimes get a null widget! EventHandlerMac handles a null
// widget by returning false, so we do the same.
return false;
}
if (!widget->isFrameView()) {
// Probably a plugin widget. They will receive the event via an
// EventTargetNode dispatch when this returns false.
return false;
}
return static_cast<FrameView*>(widget)->frame()->eventHandler()->handleWheelEvent(wheelEvent);
}
bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event)
{
// Figure out which view to send the event to.
if (!event.targetNode() || !event.targetNode()->renderer() || !event.targetNode()->renderer()->isWidget())
return false;
return passMouseDownEventToWidget(static_cast<RenderWidget*>(event.targetNode()->renderer())->widget());
}
bool EventHandler::passMouseDownEventToWidget(Widget* widget)
{
notImplemented();
return false;
}
bool EventHandler::tabsToAllControls(KeyboardEvent*) const
{
return true;
}
bool EventHandler::eventActivatedView(const PlatformMouseEvent& event) const
{
// TODO(darin): Apple's EventHandlerWin.cpp does the following:
// return event.activatedWebView();
return false;
}
PassRefPtr<Clipboard> EventHandler::createDraggingClipboard() const
{
RefPtr<ChromiumDataObject> dataObject = ChromiumDataObject::create();
return ClipboardChromium::create(true, dataObject.get(), ClipboardWritable);
}
void EventHandler::focusDocumentView()
{
Page* page = m_frame->page();
if (!page)
return;
page->focusController()->setFocusedFrame(m_frame);
}
bool EventHandler::passWidgetMouseDownEventToWidget(RenderWidget* renderWidget)
{
return passMouseDownEventToWidget(renderWidget->widget());
}
unsigned EventHandler::accessKeyModifiers()
{
return PlatformKeyboardEvent::AltKey;
}
}
<|endoftext|>
|
<commit_before>#include "glincludes.h"
#include <osg/GLExtensions>
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray = nullptr;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = nullptr;
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
PFNGLBUFFERDATAPROC glBufferData = nullptr;
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor = nullptr;
PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced = nullptr;
PFNGLPATCHPARAMETERIPROC glPatchParameteri = nullptr;
PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings = nullptr;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
PFNGLBINDBUFFERBASEPROC glBindBufferBase = nullptr;
PFNGLGENQUERIESPROC glGenQueries = nullptr;
PFNGLBEGINQUERYPROC glBeginQuery = nullptr;
PFNGLENDQUERYPROC glEndQuery = nullptr;
PFNGLDELETEQUERIESPROC glDeleteQueries = nullptr;
PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv = nullptr;
PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback = nullptr;
PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback = nullptr;
PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData = nullptr;
#define LOADGLFUNC(funcname, type) funcname = reinterpret_cast<type>(osg::getGLExtensionFuncPtr(#funcname))
void glFuncsInit()
{
glGenBuffers = reinterpret_cast<PFNGLGENBUFFERSPROC>(osg::getGLExtensionFuncPtr("glGenBuffers"));
glBufferData = reinterpret_cast<PFNGLBUFFERDATAPROC>(osg::getGLExtensionFuncPtr("glBufferData"));
glDeleteBuffers = reinterpret_cast<PFNGLDELETEBUFFERSPROC>(osg::getGLExtensionFuncPtr("glDeleteBuffers"));
glGenVertexArrays = reinterpret_cast<PFNGLGENVERTEXARRAYSPROC>(osg::getGLExtensionFuncPtr("glGenVertexArrays"));
glBindBuffer = reinterpret_cast<PFNGLBINDBUFFERPROC>(osg::getGLExtensionFuncPtr("glBindBuffer"));
glVertexAttribPointer = reinterpret_cast<PFNGLVERTEXATTRIBPOINTERPROC>(osg::getGLExtensionFuncPtr("glVertexAttribPointer"));
glEnableVertexAttribArray = reinterpret_cast<PFNGLENABLEVERTEXATTRIBARRAYPROC>(osg::getGLExtensionFuncPtr("glEnableVertexAttribArray"));
glDisableVertexAttribArray = reinterpret_cast<PFNGLDISABLEVERTEXATTRIBARRAYPROC>(osg::getGLExtensionFuncPtr("glDisableVertexAttribArray"));
glBindVertexArray = reinterpret_cast<PFNGLBINDVERTEXARRAYPROC>(osg::getGLExtensionFuncPtr("glBindVertexArray"));
glBindFramebuffer = reinterpret_cast<PFNGLBINDFRAMEBUFFERPROC>(osg::getGLExtensionFuncPtr("glBindFramebuffer"));
glVertexAttribDivisor = reinterpret_cast<PFNGLVERTEXATTRIBDIVISORPROC>(osg::getGLExtensionFuncPtr("glVertexAttribDivisor"));
glDrawArraysInstanced = reinterpret_cast<PFNGLDRAWARRAYSINSTANCEDPROC>(osg::getGLExtensionFuncPtr("glDrawArraysInstanced"));
glPatchParameteri = reinterpret_cast<PFNGLPATCHPARAMETERIPROC>(osg::getGLExtensionFuncPtr("glPatchParameteri"));
glTransformFeedbackVaryings = reinterpret_cast<PFNGLTRANSFORMFEEDBACKVARYINGSPROC>(osg::getGLExtensionFuncPtr("glTransformFeedbackVaryings"));
glDeleteVertexArrays = reinterpret_cast<PFNGLDELETEVERTEXARRAYSPROC>(osg::getGLExtensionFuncPtr("glDeleteVertexArrays"));
glBindBufferBase = reinterpret_cast<PFNGLBINDBUFFERBASEPROC>(osg::getGLExtensionFuncPtr("glBindBufferBase"));
LOADGLFUNC(glGenQueries, PFNGLGENQUERIESPROC);
LOADGLFUNC(glBeginQuery, PFNGLBEGINQUERYPROC);
LOADGLFUNC(glEndQuery, PFNGLENDQUERYPROC);
LOADGLFUNC(glDeleteQueries, PFNGLDELETEQUERIESPROC);
LOADGLFUNC(glBeginTransformFeedback, PFNGLBEGINTRANSFORMFEEDBACKPROC);
LOADGLFUNC(glEndTransformFeedback, PFNGLENDTRANSFORMFEEDBACKPROC);
LOADGLFUNC(glGetQueryObjectiv, PFNGLGETQUERYOBJECTIVPROC);
LOADGLFUNC(glGetBufferSubData, PFNGLGETBUFFERSUBDATAPROC);
}
<commit_msg>Not finding a gl function will output error message with the function name in the console before crash.<commit_after>#include "glincludes.h"
#include <osg/GLExtensions>
#include <iostream>
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray = nullptr;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = nullptr;
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
PFNGLBUFFERDATAPROC glBufferData = nullptr;
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor = nullptr;
PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced = nullptr;
PFNGLPATCHPARAMETERIPROC glPatchParameteri = nullptr;
PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings = nullptr;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
PFNGLBINDBUFFERBASEPROC glBindBufferBase = nullptr;
PFNGLGENQUERIESPROC glGenQueries = nullptr;
PFNGLBEGINQUERYPROC glBeginQuery = nullptr;
PFNGLENDQUERYPROC glEndQuery = nullptr;
PFNGLDELETEQUERIESPROC glDeleteQueries = nullptr;
PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv = nullptr;
PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback = nullptr;
PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback = nullptr;
PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData = nullptr;
#define LOADGLFUNC(funcname, type) funcname = reinterpret_cast<type>(osg::getGLExtensionFuncPtr(#funcname)); \
if (funcname == nullptr) std::cerr << "Cant find function " #funcname ", program will self-destruct" << std::endl
void glFuncsInit()
{
LOADGLFUNC(glGenBuffers, PFNGLGENBUFFERSPROC);
LOADGLFUNC(glBufferData, PFNGLBUFFERDATAPROC);
LOADGLFUNC(glDeleteBuffers, PFNGLDELETEBUFFERSPROC);
LOADGLFUNC(glGenVertexArrays, PFNGLGENVERTEXARRAYSPROC);
LOADGLFUNC(glBindBuffer, PFNGLBINDBUFFERPROC);
LOADGLFUNC(glVertexAttribPointer, PFNGLVERTEXATTRIBPOINTERPROC);
LOADGLFUNC(glEnableVertexAttribArray, PFNGLENABLEVERTEXATTRIBARRAYPROC);
LOADGLFUNC(glDisableVertexAttribArray, PFNGLDISABLEVERTEXATTRIBARRAYPROC);
LOADGLFUNC(glBindVertexArray, PFNGLBINDVERTEXARRAYPROC);
LOADGLFUNC(glBindFramebuffer, PFNGLBINDFRAMEBUFFERPROC);
LOADGLFUNC(glVertexAttribDivisor, PFNGLVERTEXATTRIBDIVISORPROC);
LOADGLFUNC(glDrawArraysInstanced, PFNGLDRAWARRAYSINSTANCEDPROC);
LOADGLFUNC(glPatchParameteri, PFNGLPATCHPARAMETERIPROC);
LOADGLFUNC(glTransformFeedbackVaryings, PFNGLTRANSFORMFEEDBACKVARYINGSPROC);
LOADGLFUNC(glDeleteVertexArrays, PFNGLDELETEVERTEXARRAYSPROC);
LOADGLFUNC(glBindBufferBase, PFNGLBINDBUFFERBASEPROC);
LOADGLFUNC(glGenQueries, PFNGLGENQUERIESPROC);
LOADGLFUNC(glBeginQuery, PFNGLBEGINQUERYPROC);
LOADGLFUNC(glEndQuery, PFNGLENDQUERYPROC);
LOADGLFUNC(glDeleteQueries, PFNGLDELETEQUERIESPROC);
LOADGLFUNC(glBeginTransformFeedback, PFNGLBEGINTRANSFORMFEEDBACKPROC);
LOADGLFUNC(glEndTransformFeedback, PFNGLENDTRANSFORMFEEDBACKPROC);
LOADGLFUNC(glGetQueryObjectiv, PFNGLGETQUERYOBJECTIVPROC);
LOADGLFUNC(glGetBufferSubData, PFNGLGETBUFFERSUBDATAPROC);
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "RenderControllerBinding.h"
#include "GafferScene/RenderController.h"
#include "GafferBindings/SignalBinding.h"
#include "Gaffer/Context.h"
#include "IECorePython/RefCountedBinding.h"
using namespace boost::python;
using namespace Imath;
using namespace IECoreScenePreview;
using namespace Gaffer;
using namespace GafferBindings;
using namespace GafferScene;
namespace
{
ScenePlugPtr getScene( RenderController &r )
{
return const_cast<ScenePlug *>( r.getScene() );
}
ContextPtr getContext( RenderController &r )
{
return const_cast<Context *>( r.getContext() );
}
void update( RenderController &r )
{
IECorePython::ScopedGILRelease gilRelease;
r.update();
}
void updateMatchingPaths( RenderController &r, const IECore::PathMatcher &pathsToUpdate )
{
IECorePython::ScopedGILRelease gilRelease;
r.updateMatchingPaths( pathsToUpdate );
}
} // namespace
void GafferSceneModule::bindRenderController()
{
scope s = class_<RenderController, boost::noncopyable>( "RenderController", no_init )
.def( init<ConstScenePlugPtr, ConstContextPtr, RendererPtr>() )
.def( "renderer", &RenderController::renderer, return_value_policy<IECorePython::CastToIntrusivePtr>() )
.def( "setScene", &RenderController::setScene )
.def( "getScene", &getScene )
.def( "setContext", &RenderController::setContext )
.def( "getContext", &getContext )
.def( "setExpandedPaths", &RenderController::setExpandedPaths )
.def( "getExpandedPaths", &RenderController::getExpandedPaths, return_value_policy<copy_const_reference>() )
.def( "setMinimumExpansionDepth", &RenderController::setMinimumExpansionDepth )
.def( "getMinimumExpansionDepth", &RenderController::getMinimumExpansionDepth )
.def( "updateRequiredSignal", &RenderController::updateRequiredSignal, return_internal_reference<1>() )
.def( "update", &update )
.def( "updateMatchingPaths", &updateMatchingPaths )
;
SignalClass<RenderController::UpdateRequiredSignal>( "UpdateRequiredSignal" );
}
<commit_msg>RenderControllerBinding : Add missing GIL releases<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "RenderControllerBinding.h"
#include "GafferScene/RenderController.h"
#include "GafferBindings/SignalBinding.h"
#include "Gaffer/Context.h"
#include "IECorePython/RefCountedBinding.h"
using namespace boost::python;
using namespace Imath;
using namespace IECoreScenePreview;
using namespace Gaffer;
using namespace GafferBindings;
using namespace GafferScene;
namespace
{
void setScene( RenderController &r, const ScenePlug &scene )
{
IECorePython::ScopedGILRelease gilRelease;
r.setScene( &scene );
}
ScenePlugPtr getScene( RenderController &r )
{
return const_cast<ScenePlug *>( r.getScene() );
}
void setContext( RenderController &r, Gaffer::Context &c )
{
IECorePython::ScopedGILRelease gilRelease;
r.setContext( &c );
}
ContextPtr getContext( RenderController &r )
{
return const_cast<Context *>( r.getContext() );
}
void setExpandedPaths( RenderController &r, const IECore::PathMatcher &expandedPaths )
{
IECorePython::ScopedGILRelease gilRelease;
r.setExpandedPaths( expandedPaths );
}
void setMinimumExpansionDepth( RenderController &r, size_t depth )
{
IECorePython::ScopedGILRelease gilRelease;
r.setMinimumExpansionDepth( depth );
}
void update( RenderController &r )
{
IECorePython::ScopedGILRelease gilRelease;
r.update();
}
void updateMatchingPaths( RenderController &r, const IECore::PathMatcher &pathsToUpdate )
{
IECorePython::ScopedGILRelease gilRelease;
r.updateMatchingPaths( pathsToUpdate );
}
} // namespace
void GafferSceneModule::bindRenderController()
{
scope s = class_<RenderController, boost::noncopyable>( "RenderController", no_init )
.def( init<ConstScenePlugPtr, ConstContextPtr, RendererPtr>() )
.def( "renderer", &RenderController::renderer, return_value_policy<IECorePython::CastToIntrusivePtr>() )
.def( "setScene", &setScene )
.def( "getScene", &getScene )
.def( "setContext", &setContext )
.def( "getContext", &getContext )
.def( "setExpandedPaths", &setExpandedPaths )
.def( "getExpandedPaths", &RenderController::getExpandedPaths, return_value_policy<copy_const_reference>() )
.def( "setMinimumExpansionDepth", &setMinimumExpansionDepth )
.def( "getMinimumExpansionDepth", &RenderController::getMinimumExpansionDepth )
.def( "updateRequiredSignal", &RenderController::updateRequiredSignal, return_internal_reference<1>() )
.def( "update", &update )
.def( "updateMatchingPaths", &updateMatchingPaths )
;
SignalClass<RenderController::UpdateRequiredSignal>( "UpdateRequiredSignal" );
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <grp.h>
#include <paths.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "debugger.h"
#include "jni_internal.h"
#include "JniConstants.h"
#include "JNIHelp.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "thread.h"
#if defined(HAVE_PRCTL)
#include <sys/prctl.h>
#endif
namespace art {
static pid_t gSystemServerPid = 0;
static void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
ScopedUtfChars command(env, javaCommand);
if (command.c_str() == NULL) {
return;
}
const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
execv(_PATH_BSHELL, const_cast<char**>(argp));
exit(127);
}
// This signal handler is for zygote mode, since the zygote must reap its children
static void SigChldHandler(int /*signal_number*/) {
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
// Log process-death status that we care about. In general it is
// not safe to call LOG(...) from a signal handler because of
// possible reentrancy. However, we know a priori that the
// current implementation of LOG() is safe to call from a SIGCHLD
// handler in the zygote process. If the LOG() implementation
// changes its locking strategy or its use of syscalls within the
// lazy-init critical section, its use here may become unsafe.
if (WIFEXITED(status)) {
if (WEXITSTATUS(status)) {
LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
} else if (false) {
LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
}
} else if (WIFSIGNALED(status)) {
if (WTERMSIG(status) != SIGKILL) {
LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
} else if (false) {
LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
}
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG(INFO) << "Process " << pid << " dumped core";
}
#endif /* ifdef WCOREDUMP */
}
// If the just-crashed process is the system_server, bring down zygote
// so that it is restarted by init and system server will be restarted
// from there.
if (pid == gSystemServerPid) {
LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
kill(getpid(), SIGKILL);
}
}
if (pid < 0) {
PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
}
}
// Configures the SIGCHLD handler for the zygote process. This is configured
// very late, because earlier in the runtime we may fork() and exec()
// other processes, and we want to waitpid() for those rather than
// have them be harvested immediately.
//
// This ends up being called repeatedly before each fork(), but there's
// no real harm in that.
static void SetSigChldHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigChldHandler;
int err = sigaction(SIGCHLD, &sa, NULL);
if (err < 0) {
PLOG(WARNING) << "Error setting SIGCHLD handler";
}
}
// Sets the SIGCHLD handler back to default behavior in zygote children.
static void UnsetSigChldHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
int err = sigaction(SIGCHLD, &sa, NULL);
if (err < 0) {
PLOG(WARNING) << "Error unsetting SIGCHLD handler";
}
}
// Calls POSIX setgroups() using the int[] object as an argument.
// A NULL argument is tolerated.
static int SetGids(JNIEnv* env, jintArray javaGids) {
if (javaGids == NULL) {
return 0;
}
COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
ScopedIntArrayRO gids(env, javaGids);
if (gids.get() == NULL) {
return -1;
}
return setgroups(gids.size(), (const gid_t *) &gids[0]);
}
// Sets the resource limits via setrlimit(2) for the values in the
// two-dimensional array of integers that's passed in. The second dimension
// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
// treated as an empty array.
//
// -1 is returned on error.
static int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
if (javaRlimits == NULL) {
return 0;
}
rlimit rlim;
memset(&rlim, 0, sizeof(rlim));
for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
if (javaRlimit.size() != 3) {
LOG(ERROR) << "rlimits array must have a second dimension of size 3";
return -1;
}
rlim.rlim_cur = javaRlimit[1];
rlim.rlim_max = javaRlimit[2];
int err = setrlimit(javaRlimit[0], &rlim);
if (err < 0) {
return -1;
}
}
return 0;
}
#if defined(HAVE_ANDROID_OS)
static void SetCapabilities(int64_t permitted, int64_t effective) {
__user_cap_header_struct capheader;
__user_cap_data_struct capdata;
memset(&capheader, 0, sizeof(capheader));
memset(&capdata, 0, sizeof(capdata));
capheader.version = _LINUX_CAPABILITY_VERSION;
capheader.pid = 0;
capdata.effective = effective;
capdata.permitted = permitted;
if (capset(&capheader, &capdata) != 0) {
PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
}
}
#else
static void SetCapabilities(int64_t, int64_t) {}
#endif
static void EnableDebugFeatures(uint32_t debug_flags) {
// Must match values in dalvik.system.Zygote.
enum {
DEBUG_ENABLE_DEBUGGER = 1,
DEBUG_ENABLE_CHECKJNI = 1 << 1,
DEBUG_ENABLE_ASSERT = 1 << 2,
DEBUG_ENABLE_SAFEMODE = 1 << 3,
DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
};
if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
Runtime* runtime = Runtime::Current();
JavaVMExt* vm = runtime->GetJavaVM();
if (!vm->check_jni) {
LOG(DEBUG) << "Late-enabling -Xcheck:jni";
vm->SetCheckJniEnabled(true);
// There's only one thread running at this point, so only one JNIEnv to fix up.
Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
} else {
LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
}
debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
}
if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
gLogVerbosity.third_party_jni = true;
debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
}
Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
#ifdef HAVE_ANDROID_OS
if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
/* To let a non-privileged gdbserver attach to this
* process, we must set its dumpable bit flag. However
* we are not interested in generating a coredump in
* case of a crash, so also set the coredump size to 0
* to disable that
*/
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
} else {
rlimit rl;
rl.rlim_cur = 0;
rl.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rl) < 0) {
PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
}
}
}
#endif
debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
// These two are for backwards compatibility with Dalvik.
debug_flags &= ~DEBUG_ENABLE_ASSERT;
debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
if (debug_flags != 0) {
LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
}
}
#ifdef HAVE_ANDROID_OS
extern "C" int gMallocLeakZygoteChild;
#endif
// Utility routine to fork zygote and specialize the child process.
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
jint debug_flags, jobjectArray javaRlimits,
jlong permittedCapabilities, jlong effectiveCapabilities) {
Runtime* runtime = Runtime::Current();
CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
LOG(FATAL) << "pre-fork heap failed";
}
SetSigChldHandler();
// Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
Thread* self = Thread::Current();
// dvmDumpLoaderStats("zygote"); // TODO: ?
pid_t pid = fork();
if (pid == 0) {
// The child process
#ifdef HAVE_ANDROID_OS
gMallocLeakZygoteChild = 1;
// keep caps across UID change, unless we're staying root */
if (uid != 0) {
int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
if (err < 0) {
PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
}
}
#endif // HAVE_ANDROID_OS
int err = SetGids(env, javaGids);
if (err < 0) {
PLOG(FATAL) << "setgroups failed";
}
err = SetRLimits(env, javaRlimits);
if (err < 0) {
PLOG(FATAL) << "setrlimit failed";
}
err = setgid(gid);
if (err < 0) {
PLOG(FATAL) << "setgid(" << gid << ") failed";
}
err = setuid(uid);
if (err < 0) {
PLOG(FATAL) << "setuid(" << uid << ") failed";
}
SetCapabilities(permittedCapabilities, effectiveCapabilities);
// Our system thread ID, etc, has changed so reset Thread state.
self->InitAfterFork();
EnableDebugFeatures(debug_flags);
UnsetSigChldHandler();
runtime->DidForkFromZygote();
} else if (pid > 0) {
// the parent process
}
return pid;
}
static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
jint debug_flags, jobjectArray rlimits) {
return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
}
static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint debug_flags, jobjectArray rlimits,
jlong permittedCapabilities, jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities);
if (pid > 0) {
// The zygote process checks whether the child process has died or not.
LOG(INFO) << "System server process " << pid << " has been created";
gSystemServerPid = pid;
// There is a slight window that the system server process has crashed
// but it went unnoticed because we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
}
}
return pid;
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
//NATIVE_METHOD(Zygote, nativeFork, "()I"),
NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
};
void register_dalvik_system_Zygote(JNIEnv* env) {
jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
}
} // namespace art
<commit_msg>Add a reminder that we need to track a change in master.<commit_after>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <grp.h>
#include <paths.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "cutils/sched_policy.h"
#include "debugger.h"
#include "jni_internal.h"
#include "JniConstants.h"
#include "JNIHelp.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "thread.h"
#if defined(HAVE_PRCTL)
#include <sys/prctl.h>
#endif
namespace art {
static pid_t gSystemServerPid = 0;
static void Zygote_nativeExecShell(JNIEnv* env, jclass, jstring javaCommand) {
ScopedUtfChars command(env, javaCommand);
if (command.c_str() == NULL) {
return;
}
const char* argp[] = {_PATH_BSHELL, "-c", command.c_str(), NULL};
LOG(INFO) << "Exec: " << argp[0] << ' ' << argp[1] << ' ' << argp[2];
execv(_PATH_BSHELL, const_cast<char**>(argp));
exit(127);
}
// This signal handler is for zygote mode, since the zygote must reap its children
static void SigChldHandler(int /*signal_number*/) {
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
// Log process-death status that we care about. In general it is
// not safe to call LOG(...) from a signal handler because of
// possible reentrancy. However, we know a priori that the
// current implementation of LOG() is safe to call from a SIGCHLD
// handler in the zygote process. If the LOG() implementation
// changes its locking strategy or its use of syscalls within the
// lazy-init critical section, its use here may become unsafe.
if (WIFEXITED(status)) {
if (WEXITSTATUS(status)) {
LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
} else if (false) {
LOG(INFO) << "Process " << pid << " exited cleanly (" << WEXITSTATUS(status) << ")";
}
} else if (WIFSIGNALED(status)) {
if (WTERMSIG(status) != SIGKILL) {
LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
} else if (false) {
LOG(INFO) << "Process " << pid << " terminated by signal (" << WTERMSIG(status) << ")";
}
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG(INFO) << "Process " << pid << " dumped core";
}
#endif /* ifdef WCOREDUMP */
}
// If the just-crashed process is the system_server, bring down zygote
// so that it is restarted by init and system server will be restarted
// from there.
if (pid == gSystemServerPid) {
LOG(ERROR) << "Exit zygote because system server (" << pid << ") has terminated";
kill(getpid(), SIGKILL);
}
}
if (pid < 0) {
PLOG(WARNING) << "Zygote SIGCHLD error in waitpid";
}
}
// Configures the SIGCHLD handler for the zygote process. This is configured
// very late, because earlier in the runtime we may fork() and exec()
// other processes, and we want to waitpid() for those rather than
// have them be harvested immediately.
//
// This ends up being called repeatedly before each fork(), but there's
// no real harm in that.
static void SetSigChldHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SigChldHandler;
int err = sigaction(SIGCHLD, &sa, NULL);
if (err < 0) {
PLOG(WARNING) << "Error setting SIGCHLD handler";
}
}
// Sets the SIGCHLD handler back to default behavior in zygote children.
static void UnsetSigChldHandler() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_DFL;
int err = sigaction(SIGCHLD, &sa, NULL);
if (err < 0) {
PLOG(WARNING) << "Error unsetting SIGCHLD handler";
}
}
// Calls POSIX setgroups() using the int[] object as an argument.
// A NULL argument is tolerated.
static int SetGids(JNIEnv* env, jintArray javaGids) {
if (javaGids == NULL) {
return 0;
}
COMPILE_ASSERT(sizeof(gid_t) == sizeof(jint), sizeof_gid_and_jint_are_differerent);
ScopedIntArrayRO gids(env, javaGids);
if (gids.get() == NULL) {
return -1;
}
return setgroups(gids.size(), (const gid_t *) &gids[0]);
}
// Sets the resource limits via setrlimit(2) for the values in the
// two-dimensional array of integers that's passed in. The second dimension
// contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is
// treated as an empty array.
//
// -1 is returned on error.
static int SetRLimits(JNIEnv* env, jobjectArray javaRlimits) {
if (javaRlimits == NULL) {
return 0;
}
rlimit rlim;
memset(&rlim, 0, sizeof(rlim));
for (int i = 0; i < env->GetArrayLength(javaRlimits); i++) {
ScopedLocalRef<jobject> javaRlimitObject(env, env->GetObjectArrayElement(javaRlimits, i));
ScopedIntArrayRO javaRlimit(env, reinterpret_cast<jintArray>(javaRlimitObject.get()));
if (javaRlimit.size() != 3) {
LOG(ERROR) << "rlimits array must have a second dimension of size 3";
return -1;
}
rlim.rlim_cur = javaRlimit[1];
rlim.rlim_max = javaRlimit[2];
int err = setrlimit(javaRlimit[0], &rlim);
if (err < 0) {
return -1;
}
}
return 0;
}
#if defined(HAVE_ANDROID_OS)
static void SetCapabilities(int64_t permitted, int64_t effective) {
__user_cap_header_struct capheader;
__user_cap_data_struct capdata;
memset(&capheader, 0, sizeof(capheader));
memset(&capdata, 0, sizeof(capdata));
capheader.version = _LINUX_CAPABILITY_VERSION;
capheader.pid = 0;
capdata.effective = effective;
capdata.permitted = permitted;
if (capset(&capheader, &capdata) != 0) {
PLOG(FATAL) << "capset(" << permitted << ", " << effective << ") failed";
}
}
#else
static void SetCapabilities(int64_t, int64_t) {}
#endif
static void EnableDebugFeatures(uint32_t debug_flags) {
// Must match values in dalvik.system.Zygote.
enum {
DEBUG_ENABLE_DEBUGGER = 1,
DEBUG_ENABLE_CHECKJNI = 1 << 1,
DEBUG_ENABLE_ASSERT = 1 << 2,
DEBUG_ENABLE_SAFEMODE = 1 << 3,
DEBUG_ENABLE_JNI_LOGGING = 1 << 4,
};
if ((debug_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
Runtime* runtime = Runtime::Current();
JavaVMExt* vm = runtime->GetJavaVM();
if (!vm->check_jni) {
LOG(DEBUG) << "Late-enabling -Xcheck:jni";
vm->SetCheckJniEnabled(true);
// There's only one thread running at this point, so only one JNIEnv to fix up.
Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
} else {
LOG(DEBUG) << "Not late-enabling -Xcheck:jni (already on)";
}
debug_flags &= ~DEBUG_ENABLE_CHECKJNI;
}
if ((debug_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
gLogVerbosity.third_party_jni = true;
debug_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
}
Dbg::SetJdwpAllowed((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0);
#ifdef HAVE_ANDROID_OS
if ((debug_flags & DEBUG_ENABLE_DEBUGGER) != 0) {
/* To let a non-privileged gdbserver attach to this
* process, we must set its dumpable bit flag. However
* we are not interested in generating a coredump in
* case of a crash, so also set the coredump size to 0
* to disable that
*/
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
PLOG(ERROR) << "could not set dumpable bit flag for pid " << getpid();
} else {
rlimit rl;
rl.rlim_cur = 0;
rl.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rl) < 0) {
PLOG(ERROR) << "could not disable core file generation for pid " << getpid();
}
}
}
#endif
debug_flags &= ~DEBUG_ENABLE_DEBUGGER;
// These two are for backwards compatibility with Dalvik.
debug_flags &= ~DEBUG_ENABLE_ASSERT;
debug_flags &= ~DEBUG_ENABLE_SAFEMODE;
if (debug_flags != 0) {
LOG(ERROR) << StringPrintf("Unknown bits set in debug_flags: %#x", debug_flags);
}
}
#ifdef HAVE_ANDROID_OS
extern "C" int gMallocLeakZygoteChild;
#endif
// Utility routine to fork zygote and specialize the child process.
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
jint debug_flags, jobjectArray javaRlimits,
jlong permittedCapabilities, jlong effectiveCapabilities) {
Runtime* runtime = Runtime::Current();
CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
if (false) { // TODO: do we need do anything special like !dvmGcPreZygoteFork()?
LOG(FATAL) << "pre-fork heap failed";
}
SetSigChldHandler();
// Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
Thread* self = Thread::Current();
// dvmDumpLoaderStats("zygote"); // TODO: ?
pid_t pid = fork();
if (pid == 0) {
// The child process
#ifdef HAVE_ANDROID_OS
gMallocLeakZygoteChild = 1;
// keep caps across UID change, unless we're staying root */
if (uid != 0) {
int err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
if (err < 0) {
PLOG(FATAL) << "cannot PR_SET_KEEPCAPS";
}
}
#endif // HAVE_ANDROID_OS
int err = SetGids(env, javaGids);
if (err < 0) {
PLOG(FATAL) << "setgroups failed";
}
err = SetRLimits(env, javaRlimits);
if (err < 0) {
PLOG(FATAL) << "setrlimit failed";
}
err = setgid(gid);
if (err < 0) {
PLOG(FATAL) << "setgid(" << gid << ") failed";
}
err = setuid(uid);
if (err < 0) {
PLOG(FATAL) << "setuid(" << uid << ") failed";
}
SetCapabilities(permittedCapabilities, effectiveCapabilities);
#if 1
UNIMPLEMENTED(WARNING) << "enable this code when cutils/sched_policy.h has SP_DEFAULT";
#else
err = set_sched_policy(0, SP_DEFAULT);
if (err < 0) {
errno = -err;
PLOG(FATAL) << "set_sched_policy(0, SP_DEFAULT) failed";
}
#endif
// Our system thread ID, etc, has changed so reset Thread state.
self->InitAfterFork();
EnableDebugFeatures(debug_flags);
UnsetSigChldHandler();
runtime->DidForkFromZygote();
} else if (pid > 0) {
// the parent process
}
return pid;
}
static jint Zygote_nativeForkAndSpecialize(JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
jint debug_flags, jobjectArray rlimits) {
return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, 0, 0);
}
static jint Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint debug_flags, jobjectArray rlimits,
jlong permittedCapabilities, jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities);
if (pid > 0) {
// The zygote process checks whether the child process has died or not.
LOG(INFO) << "System server process " << pid << " has been created";
gSystemServerPid = pid;
// There is a slight window that the system server process has crashed
// but it went unnoticed because we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
LOG(FATAL) << "System server process " << pid << " has died. Restarting Zygote!";
}
}
return pid;
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Zygote, nativeExecShell, "(Ljava/lang/String;)V"),
//NATIVE_METHOD(Zygote, nativeFork, "()I"),
NATIVE_METHOD(Zygote, nativeForkAndSpecialize, "(II[II[[I)I"),
NATIVE_METHOD(Zygote, nativeForkSystemServer, "(II[II[[IJJ)I"),
};
void register_dalvik_system_Zygote(JNIEnv* env) {
jniRegisterNativeMethods(env, "dalvik/system/Zygote", gMethods, NELEM(gMethods));
}
} // namespace art
<|endoftext|>
|
<commit_before>#include "nan.h"
#include "marker-index.h"
using namespace v8;
using std::set;
class MarkerIndexWrapper : public Nan::ObjectWrap {
public:
static void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> constructorTemplate =
Nan::New<FunctionTemplate>(New);
constructorTemplate->SetClassName(
Nan::New<String>("MarkerIndex").ToLocalChecked());
constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("generateRandomNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(GenerateRandomNumber)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("insert").ToLocalChecked(), Nan::New<FunctionTemplate>(Insert)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("getStart").ToLocalChecked(), Nan::New<FunctionTemplate>(GetStart)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("getEnd").ToLocalChecked(), Nan::New<FunctionTemplate>(GetEnd)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findIntersecting").ToLocalChecked(), Nan::New<FunctionTemplate>(FindIntersecting)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findContaining").ToLocalChecked(), Nan::New<FunctionTemplate>(FindContaining)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findContainedIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindContainedIn)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findStartingIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindStartingIn)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findEndingIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindEndingIn)->GetFunction());
row_key.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked()));
column_key.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked()));
module->Set(Nan::New("exports").ToLocalChecked(),
constructorTemplate->GetFunction());
}
private:
static Nan::Persistent<String> row_key;
static Nan::Persistent<String> column_key;
static Nan::Persistent<String> set_key;
static void New(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *marker_index = new MarkerIndexWrapper(Local<Number>::Cast(info[0]));
marker_index->Wrap(info.This());
}
static void GenerateRandomNumber(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
int random = wrapper->marker_index.GenerateRandomNumber();
info.GetReturnValue().Set(Nan::New<v8::Number>(random));
}
static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) {
Local<Object> object;
if (!maybe_object.ToLocal(&object)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_key)));
Local<Integer> row;
if (!maybe_row.ToLocal(&row)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_key)));
Local<Integer> column;
if (!maybe_column.ToLocal(&column)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
return Nan::Just(Point(
static_cast<unsigned>(row->Int32Value()),
static_cast<unsigned>(column->Int32Value())
));
}
static Local<Object> PointToJS(const Point &point) {
Local<Object> result = Nan::New<Object>();
result->Set(Nan::New(row_key), Nan::New<Integer>(point.row));
result->Set(Nan::New(column_key), Nan::New<Integer>(point.column));
return result;
}
static Local<Array> MarkerIdsToJS(const set<MarkerId> marker_ids) {
Local<Array> result_array = Nan::New<Array>(marker_ids.size());
uint32_t index = 0;
for (auto marker_ids_iter = marker_ids.begin(); marker_ids_iter != marker_ids.end(); marker_ids_iter++) {
result_array->Set(index++, Nan::New<Integer>(*marker_ids_iter));
}
return result_array;
}
static Nan::Maybe<MarkerId> MarkerIdFromJS(Nan::MaybeLocal<Integer> maybe_id) {
Local<Integer> id;
if (!maybe_id.ToLocal(&id)) {
Nan::ThrowTypeError("Expected an integer marker id.");
return Nan::Nothing<MarkerId>();
}
return Nan::Just<MarkerId>(static_cast<MarkerId>(id->Uint32Value()));
}
static void Insert(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[1]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[2]));
if (id.IsJust() && start.IsJust() && end.IsJust()) {
wrapper->marker_index.Insert(id.FromJust(), start.FromJust(), end.FromJust());
}
}
static void GetStart(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
if (id.IsJust()) {
Point result = wrapper->marker_index.GetStart(id.FromJust());
info.GetReturnValue().Set(PointToJS(result));
}
}
static void GetEnd(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
if (id.IsJust()) {
Point result = wrapper->marker_index.GetEnd(id.FromJust());
info.GetReturnValue().Set(PointToJS(result));
}
}
static void FindIntersecting(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindIntersecting(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindContaining(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindContaining(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindContainedIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindContainedIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindStartingIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindStartingIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindEndingIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindEndingIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
MarkerIndexWrapper(v8::Local<v8::Number> seed) :
marker_index{static_cast<unsigned>(seed->Int32Value())} {}
MarkerIndex marker_index;
};
Nan::Persistent<String> MarkerIndexWrapper::row_key;
Nan::Persistent<String> MarkerIndexWrapper::column_key;
Nan::Persistent<String> MarkerIndexWrapper::set_key;
NODE_MODULE(marker_index, MarkerIndexWrapper::Init)
<commit_msg>Remove unused variable<commit_after>#include "nan.h"
#include "marker-index.h"
using namespace v8;
using std::set;
class MarkerIndexWrapper : public Nan::ObjectWrap {
public:
static void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> constructorTemplate =
Nan::New<FunctionTemplate>(New);
constructorTemplate->SetClassName(
Nan::New<String>("MarkerIndex").ToLocalChecked());
constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("generateRandomNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(GenerateRandomNumber)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("insert").ToLocalChecked(), Nan::New<FunctionTemplate>(Insert)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("getStart").ToLocalChecked(), Nan::New<FunctionTemplate>(GetStart)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("getEnd").ToLocalChecked(), Nan::New<FunctionTemplate>(GetEnd)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findIntersecting").ToLocalChecked(), Nan::New<FunctionTemplate>(FindIntersecting)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findContaining").ToLocalChecked(), Nan::New<FunctionTemplate>(FindContaining)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findContainedIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindContainedIn)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findStartingIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindStartingIn)->GetFunction());
constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("_findEndingIn").ToLocalChecked(), Nan::New<FunctionTemplate>(FindEndingIn)->GetFunction());
row_key.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked()));
column_key.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked()));
module->Set(Nan::New("exports").ToLocalChecked(),
constructorTemplate->GetFunction());
}
private:
static Nan::Persistent<String> row_key;
static Nan::Persistent<String> column_key;
static void New(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *marker_index = new MarkerIndexWrapper(Local<Number>::Cast(info[0]));
marker_index->Wrap(info.This());
}
static void GenerateRandomNumber(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
int random = wrapper->marker_index.GenerateRandomNumber();
info.GetReturnValue().Set(Nan::New<v8::Number>(random));
}
static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) {
Local<Object> object;
if (!maybe_object.ToLocal(&object)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_key)));
Local<Integer> row;
if (!maybe_row.ToLocal(&row)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_key)));
Local<Integer> column;
if (!maybe_column.ToLocal(&column)) {
Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties.");
return Nan::Nothing<Point>();
}
return Nan::Just(Point(
static_cast<unsigned>(row->Int32Value()),
static_cast<unsigned>(column->Int32Value())
));
}
static Local<Object> PointToJS(const Point &point) {
Local<Object> result = Nan::New<Object>();
result->Set(Nan::New(row_key), Nan::New<Integer>(point.row));
result->Set(Nan::New(column_key), Nan::New<Integer>(point.column));
return result;
}
static Local<Array> MarkerIdsToJS(const set<MarkerId> marker_ids) {
Local<Array> result_array = Nan::New<Array>(marker_ids.size());
uint32_t index = 0;
for (auto marker_ids_iter = marker_ids.begin(); marker_ids_iter != marker_ids.end(); marker_ids_iter++) {
result_array->Set(index++, Nan::New<Integer>(*marker_ids_iter));
}
return result_array;
}
static Nan::Maybe<MarkerId> MarkerIdFromJS(Nan::MaybeLocal<Integer> maybe_id) {
Local<Integer> id;
if (!maybe_id.ToLocal(&id)) {
Nan::ThrowTypeError("Expected an integer marker id.");
return Nan::Nothing<MarkerId>();
}
return Nan::Just<MarkerId>(static_cast<MarkerId>(id->Uint32Value()));
}
static void Insert(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[1]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[2]));
if (id.IsJust() && start.IsJust() && end.IsJust()) {
wrapper->marker_index.Insert(id.FromJust(), start.FromJust(), end.FromJust());
}
}
static void GetStart(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
if (id.IsJust()) {
Point result = wrapper->marker_index.GetStart(id.FromJust());
info.GetReturnValue().Set(PointToJS(result));
}
}
static void GetEnd(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<MarkerId> id = MarkerIdFromJS(Nan::To<Integer>(info[0]));
if (id.IsJust()) {
Point result = wrapper->marker_index.GetEnd(id.FromJust());
info.GetReturnValue().Set(PointToJS(result));
}
}
static void FindIntersecting(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindIntersecting(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindContaining(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindContaining(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindContainedIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindContainedIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindStartingIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindStartingIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
static void FindEndingIn(const Nan::FunctionCallbackInfo<Value> &info) {
MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This());
Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0]));
Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1]));
if (start.IsJust() && end.IsJust()) {
set<MarkerId> result = wrapper->marker_index.FindEndingIn(start.FromJust(), end.FromJust());
info.GetReturnValue().Set(MarkerIdsToJS(result));
}
}
MarkerIndexWrapper(v8::Local<v8::Number> seed) :
marker_index{static_cast<unsigned>(seed->Int32Value())} {}
MarkerIndex marker_index;
};
Nan::Persistent<String> MarkerIndexWrapper::row_key;
Nan::Persistent<String> MarkerIndexWrapper::column_key;
NODE_MODULE(marker_index, MarkerIndexWrapper::Init)
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/PrimitiveEvaluator.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
using namespace IECore;
using namespace boost::python;
namespace IECore
{
struct PrimitiveEvaluatorHelper
{
static PrimitiveEvaluatorPtr create( PrimitivePtr primitive )
{
return PrimitiveEvaluator::create( primitive );
}
static float signedDistance( PrimitiveEvaluator &evaluator, const Imath::V3f &p )
{
float distance = 0.0;
bool success = evaluator.signedDistance( p, distance );
if ( !success )
{
}
return distance;
}
static bool closestPoint( PrimitiveEvaluator &evaluator, const Imath::V3f &p, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.closestPoint( p, result );
}
static bool pointAtUV( PrimitiveEvaluator &evaluator, const Imath::V2f &uv, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.pointAtUV( uv, result );
}
static bool intersectionPoint( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.intersectionPoint( origin, direction, result );
}
static bool intersectionPointMaxDist( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, const PrimitiveEvaluator::ResultPtr &result, float maxDist )
{
evaluator.validateResult( result );
return evaluator.intersectionPoint( origin, direction, result, maxDist );
}
static list intersectionPoints( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction )
{
std::vector< PrimitiveEvaluator::ResultPtr > results;
evaluator.intersectionPoints( origin, direction, results );
list result;
for ( std::vector< PrimitiveEvaluator::ResultPtr >::const_iterator it = results.begin(); it != results.end(); ++it)
{
result.append( *it );
}
return result;
}
static list intersectionPoints( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, float maxDistance )
{
std::vector< PrimitiveEvaluator::ResultPtr > results;
evaluator.intersectionPoints( origin, direction, results, maxDistance );
list result;
for ( std::vector< PrimitiveEvaluator::ResultPtr >::const_iterator it = results.begin(); it != results.end(); ++it)
{
result.append( *it );
}
return result;
}
};
void bindPrimitiveEvaluator()
{
list (*intersectionPoints)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &) = &PrimitiveEvaluatorHelper::intersectionPoints;
list (*intersectionPointsMaxDist)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, float) = &PrimitiveEvaluatorHelper::intersectionPoints;
bool (*intersectionPoint)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, const PrimitiveEvaluator::ResultPtr &) = &PrimitiveEvaluatorHelper::intersectionPoint;
bool (*intersectionPointMaxDist)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, const PrimitiveEvaluator::ResultPtr &, float ) = &PrimitiveEvaluatorHelper::intersectionPointMaxDist;
object p = RunTimeTypedClass<PrimitiveEvaluator>()
.def( "create", &PrimitiveEvaluatorHelper::create ).staticmethod("create")
.def( "createResult", &PrimitiveEvaluator::createResult )
.def( "validateResult", &PrimitiveEvaluator::validateResult )
.def( "signedDistance", &PrimitiveEvaluatorHelper::signedDistance )
.def( "closestPoint", &PrimitiveEvaluatorHelper::closestPoint )
.def( "pointAtUV", &PrimitiveEvaluatorHelper::pointAtUV )
.def( "intersectionPoint", intersectionPoint )
.def( "intersectionPoint", intersectionPointMaxDist )
.def( "intersectionPoints", intersectionPoints )
.def( "intersectionPoints", intersectionPointsMaxDist )
.def( "primitive", &PrimitiveEvaluator::primitive )
.def( "volume", &PrimitiveEvaluator::volume )
.def( "centerOfGravity", &PrimitiveEvaluator::centerOfGravity )
.def( "surfaceArea", &PrimitiveEvaluator::surfaceArea )
;
{
scope ps( p );
RefCountedClass<PrimitiveEvaluator::Result, RefCounted>( "Result" )
.def( "point", &PrimitiveEvaluator::Result::point )
.def( "normal", &PrimitiveEvaluator::Result::normal )
.def( "uv", &PrimitiveEvaluator::Result::uv )
.def( "uTangent", &PrimitiveEvaluator::Result::uTangent )
.def( "vTangent", &PrimitiveEvaluator::Result::vTangent )
.def( "vectorPrimVar", &PrimitiveEvaluator::Result::vectorPrimVar )
.def( "floatPrimVar", &PrimitiveEvaluator::Result::floatPrimVar )
.def( "intPrimVar", &PrimitiveEvaluator::Result::intPrimVar )
.def( "stringPrimVar", &PrimitiveEvaluator::Result::stringPrimVar, return_value_policy<copy_const_reference>() )
.def( "colorPrimVar", &PrimitiveEvaluator::Result::colorPrimVar )
.def( "halfPrimVar", &PrimitiveEvaluator::Result::halfPrimVar )
;
}
}
}
<commit_msg>fixing primitive() bindings.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/PrimitiveEvaluator.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
using namespace IECore;
using namespace boost::python;
namespace IECore
{
struct PrimitiveEvaluatorHelper
{
static PrimitiveEvaluatorPtr create( PrimitivePtr primitive )
{
return PrimitiveEvaluator::create( primitive );
}
static float signedDistance( PrimitiveEvaluator &evaluator, const Imath::V3f &p )
{
float distance = 0.0;
bool success = evaluator.signedDistance( p, distance );
if ( !success )
{
}
return distance;
}
static bool closestPoint( PrimitiveEvaluator &evaluator, const Imath::V3f &p, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.closestPoint( p, result );
}
static bool pointAtUV( PrimitiveEvaluator &evaluator, const Imath::V2f &uv, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.pointAtUV( uv, result );
}
static bool intersectionPoint( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, const PrimitiveEvaluator::ResultPtr &result )
{
evaluator.validateResult( result );
return evaluator.intersectionPoint( origin, direction, result );
}
static bool intersectionPointMaxDist( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, const PrimitiveEvaluator::ResultPtr &result, float maxDist )
{
evaluator.validateResult( result );
return evaluator.intersectionPoint( origin, direction, result, maxDist );
}
static list intersectionPoints( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction )
{
std::vector< PrimitiveEvaluator::ResultPtr > results;
evaluator.intersectionPoints( origin, direction, results );
list result;
for ( std::vector< PrimitiveEvaluator::ResultPtr >::const_iterator it = results.begin(); it != results.end(); ++it)
{
result.append( *it );
}
return result;
}
static list intersectionPoints( PrimitiveEvaluator& evaluator, const Imath::V3f &origin, const Imath::V3f &direction, float maxDistance )
{
std::vector< PrimitiveEvaluator::ResultPtr > results;
evaluator.intersectionPoints( origin, direction, results, maxDistance );
list result;
for ( std::vector< PrimitiveEvaluator::ResultPtr >::const_iterator it = results.begin(); it != results.end(); ++it)
{
result.append( *it );
}
return result;
}
static PrimitivePtr primitive( PrimitiveEvaluator &evaluator )
{
return evaluator.primitive()->copy();
}
};
void bindPrimitiveEvaluator()
{
list (*intersectionPoints)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &) = &PrimitiveEvaluatorHelper::intersectionPoints;
list (*intersectionPointsMaxDist)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, float) = &PrimitiveEvaluatorHelper::intersectionPoints;
bool (*intersectionPoint)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, const PrimitiveEvaluator::ResultPtr &) = &PrimitiveEvaluatorHelper::intersectionPoint;
bool (*intersectionPointMaxDist)(PrimitiveEvaluator&, const Imath::V3f &, const Imath::V3f &, const PrimitiveEvaluator::ResultPtr &, float ) = &PrimitiveEvaluatorHelper::intersectionPointMaxDist;
object p = RunTimeTypedClass<PrimitiveEvaluator>()
.def( "create", &PrimitiveEvaluatorHelper::create ).staticmethod("create")
.def( "createResult", &PrimitiveEvaluator::createResult )
.def( "validateResult", &PrimitiveEvaluator::validateResult )
.def( "signedDistance", &PrimitiveEvaluatorHelper::signedDistance )
.def( "closestPoint", &PrimitiveEvaluatorHelper::closestPoint )
.def( "pointAtUV", &PrimitiveEvaluatorHelper::pointAtUV )
.def( "intersectionPoint", intersectionPoint )
.def( "intersectionPoint", intersectionPointMaxDist )
.def( "intersectionPoints", intersectionPoints )
.def( "intersectionPoints", intersectionPointsMaxDist )
.def( "primitive", &PrimitiveEvaluatorHelper::primitive )
.def( "volume", &PrimitiveEvaluator::volume )
.def( "centerOfGravity", &PrimitiveEvaluator::centerOfGravity )
.def( "surfaceArea", &PrimitiveEvaluator::surfaceArea )
;
{
scope ps( p );
RefCountedClass<PrimitiveEvaluator::Result, RefCounted>( "Result" )
.def( "point", &PrimitiveEvaluator::Result::point )
.def( "normal", &PrimitiveEvaluator::Result::normal )
.def( "uv", &PrimitiveEvaluator::Result::uv )
.def( "uTangent", &PrimitiveEvaluator::Result::uTangent )
.def( "vTangent", &PrimitiveEvaluator::Result::vTangent )
.def( "vectorPrimVar", &PrimitiveEvaluator::Result::vectorPrimVar )
.def( "floatPrimVar", &PrimitiveEvaluator::Result::floatPrimVar )
.def( "intPrimVar", &PrimitiveEvaluator::Result::intPrimVar )
.def( "stringPrimVar", &PrimitiveEvaluator::Result::stringPrimVar, return_value_policy<copy_const_reference>() )
.def( "colorPrimVar", &PrimitiveEvaluator::Result::colorPrimVar )
.def( "halfPrimVar", &PrimitiveEvaluator::Result::halfPrimVar )
;
}
}
}
<|endoftext|>
|
<commit_before>/*
* NetworkServer.cpp
*
* Created on: 07.04.2016
* Author: Marc Hartung
*/
#include "../../include/network_impl/NetworkServer.hpp"
namespace NetOff
{
NetworkServer::NetworkServer()
: NetworkMember(),
_tcpsock(nullptr)
{
}
NetworkServer::~NetworkServer()
{
killSocket(_tcpsock);
}
bool NetworkServer::initialize(const int& port)
{
IPaddress ip;
if (SDLNet_ResolveHost(&ip, NULL, port) == -1)
{
return false;
}
_tcpsock = SDLNet_TCP_Open(&ip);
if (!_tcpsock)
{
return false;
}
_socket = SDLNet_TCP_Accept(_tcpsock);
unsigned times = 0;
while (_socket == NULL && times++ <= _numMaxSleeps)
{
SDL_Delay (_sleepTime);
_socket = SDLNet_TCP_Accept(_tcpsock);
}
if (_socket == nullptr)
{
return false;
}
return true;
}
void NetworkServer::deinitialize()
{
killSocket(_tcpsock);
killSocket(_socket);
}
} /* namespace NetOff */
<commit_msg>- SDLnet_Init() was missing, add some messages<commit_after>/*
* NetworkServer.cpp
*
* Created on: 07.04.2016
* Author: Marc Hartung
*/
#include "../../include/network_impl/NetworkServer.hpp"
#include <iostream>
namespace NetOff
{
NetworkServer::NetworkServer()
: NetworkMember(),
_tcpsock(nullptr)
{
}
NetworkServer::~NetworkServer()
{
killSocket(_tcpsock);
}
bool NetworkServer::initialize(const int& port)
{
IPaddress ip;
SDLNet_Init();
if (SDLNet_ResolveHost(&ip, NULL, port) == -1)
{
std::cout << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
return false;
}
_tcpsock = SDLNet_TCP_Open(&ip);
if (!_tcpsock)
{
std::cout<<"SDLNet_TCP_Open: "<< SDLNet_GetError()<<std::endl;
return false;
}
_socket = SDLNet_TCP_Accept(_tcpsock);
unsigned times = 0;
while (_socket == NULL && times++ <= _numMaxSleeps)
{
SDL_Delay (_sleepTime);
std::cout << "wait for client on host " << ip.host << " and port " << port<<std::endl;
_socket = SDLNet_TCP_Accept(_tcpsock);
}
if (_socket == nullptr)
{
return false;
}
return true;
}
void NetworkServer::deinitialize()
{
killSocket(_tcpsock);
killSocket(_socket);
}
} /* namespace NetOff */
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "planner/abstract_plan.h"
#include "planner/drop_plan.h"
#include "planner/seq_scan_plan.h"
#include "common/logger.h"
#include <memory>
namespace peloton {
namespace planner {
class AbstractPlan;
}
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
std::shared_ptr<planner::AbstractPlan> plan_tree;
// Base Case
if (parse_tree.get() == nullptr)
return plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch (parse_item_node_type) {
case PARSE_NODE_TYPE_DROP: {
std::unique_ptr<planner::AbstractPlan> child_DropPlan(
new planner::DropPlan("department-table"));
child_plan = std::move(child_DropPlan);
}
break;
case PARSE_NODE_TYPE_SCAN: {
std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan(
new planner::SeqScanPlan());
child_plan = std::move(child_SeqScanPlan);
}
break;
default:
LOG_INFO("Unsupported Parse Node Type");
}
if (child_plan != nullptr) {
if (plan_tree != nullptr)
plan_tree->AddChild(std::move(child_plan));
else
plan_tree = std::move(child_plan);
}
// Recurse
auto children = parse_tree->GetChildren();
for (auto child : children) {
auto child_parse = BuildPlanTree(child);
child_plan = std::move(child_parse);
}
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<commit_msg>Modification<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "planner/abstract_plan.h"
#include "planner/drop_plan.h"
#include "planner/seq_scan_plan.h"
#include "common/logger.h"
#include <memory>
namespace peloton {
namespace planner {
class AbstractPlan;
}
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
std::shared_ptr<planner::AbstractPlan> plan_tree;
// Base Case
if (parse_tree.get() == nullptr)
return plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch (parse_item_node_type) {
case PARSE_NODE_TYPE_DROP: {
std::unique_ptr<planner::AbstractPlan> child_DropPlan(
new planner::DropPlan("department-table"));
child_plan = std::move(child_DropPlan);
}
break;
case PARSE_NODE_TYPE_SCAN: {
std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan(
new planner::SeqScanPlan());
child_plan = std::move(child_SeqScanPlan);
}
break;
default:
LOG_INFO("Unsupported Parse Node Type");
}
if (child_plan != nullptr) {
if (plan_tree != nullptr)
plan_tree->AddChild(std::move(child_plan));
else
plan_tree = std::move(child_plan);
}
// Recurse
auto &children = parse_tree->GetChildren();
for (auto &child : children) {
std::shared_ptr<planner::AbstractPlan> child_parse = BuildPlanTree(child);
child_plan = std::move(child_parse);
}
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<|endoftext|>
|
<commit_before>/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* LRL V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: trajectory_composite.cpp 22 2004-09-21 08:58:54Z eaertbellocal $
* $Name: $
****************************************************************************/
#include "trajectory_composite.hpp"
#include "path_composite.hpp"
namespace KDL {
using namespace std;
Trajectory_Composite::Trajectory_Composite():duration(0.0)
{
path = new Path_Composite(); // FreeCAD change
}
double Trajectory_Composite::Duration() const{
return duration;
}
Frame Trajectory_Composite::Pos(double time) const {
// not optimal, could be done in log(#elem)
// or one could buffer the last segment and start looking from there.
unsigned int i;
double previoustime;
Trajectory* traj;
if (time < 0) {
return vt[0]->Pos(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Pos(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Pos(traj->Duration());
}
Twist Trajectory_Composite::Vel(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Vel(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Vel(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Vel(traj->Duration());
}
Twist Trajectory_Composite::Acc(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Acc(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Acc(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Acc(traj->Duration());
}
void Trajectory_Composite::Add(Trajectory* elem) {
vt.insert(vt.end(),elem);
duration += elem->Duration();
vd.insert(vd.end(),duration);
path->Add(elem->GetPath(),false); // FreeCAD change
}
void Trajectory_Composite::Destroy() {
VectorTraj::iterator it;
for (it=vt.begin();it!=vt.end();it++) {
delete *it;
}
vt.erase(vt.begin(),vt.end());
vd.erase(vd.begin(),vd.end());
delete path; // FreeCAD change
}
Trajectory_Composite::~Trajectory_Composite() {
Destroy();
}
void Trajectory_Composite::Write(ostream& os) const {
os << "COMPOSITE[ " << vt.size() << endl;
unsigned int i;
for (i=0;i<vt.size();i++) {
vt[i]->Write(os);
}
os << "]" << endl;
}
Trajectory* Trajectory_Composite::Clone() const{
Trajectory_Composite* comp = new Trajectory_Composite();
for (unsigned int i = 0; i < vt.size(); ++i) {
comp->Add(vt[i]->Clone());
}
return comp;
}
// FreeCAD change
Path* Trajectory_Composite::GetPath()
{
return path;
}
VelocityProfile* Trajectory_Composite::GetProfile()
{
return 0;
}
}
<commit_msg>nullify path on destruction and check if adding new trajectories<commit_after>/*****************************************************************************
* \author
* Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven
*
* \version
* LRL V0.2
*
* \par History
* - $log$
*
* \par Release
* $Id: trajectory_composite.cpp 22 2004-09-21 08:58:54Z eaertbellocal $
* $Name: $
****************************************************************************/
#include "trajectory_composite.hpp"
#include "path_composite.hpp"
namespace KDL {
using namespace std;
Trajectory_Composite::Trajectory_Composite():duration(0.0)
{
path = new Path_Composite(); // FreeCAD change
}
double Trajectory_Composite::Duration() const{
return duration;
}
Frame Trajectory_Composite::Pos(double time) const {
// not optimal, could be done in log(#elem)
// or one could buffer the last segment and start looking from there.
unsigned int i;
double previoustime;
Trajectory* traj;
if (time < 0) {
return vt[0]->Pos(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Pos(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Pos(traj->Duration());
}
Twist Trajectory_Composite::Vel(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Vel(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Vel(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Vel(traj->Duration());
}
Twist Trajectory_Composite::Acc(double time) const {
// not optimal, could be done in log(#elem)
unsigned int i;
Trajectory* traj;
double previoustime;
if (time < 0) {
return vt[0]->Acc(0);
}
previoustime = 0;
for (i=0;i<vt.size();i++) {
if (time < vd[i]) {
return vt[i]->Acc(time-previoustime);
}
previoustime = vd[i];
}
traj = vt[vt.size()-1];
return traj->Acc(traj->Duration());
}
void Trajectory_Composite::Add(Trajectory* elem) {
vt.insert(vt.end(),elem);
duration += elem->Duration();
vd.insert(vd.end(),duration);
if (path)
path->Add(elem->GetPath(),false); // FreeCAD change
}
void Trajectory_Composite::Destroy() {
VectorTraj::iterator it;
for (it=vt.begin();it!=vt.end();it++) {
delete *it;
}
vt.erase(vt.begin(),vt.end());
vd.erase(vd.begin(),vd.end());
delete path; // FreeCAD change
path = nullptr; // FreeCAD change
}
Trajectory_Composite::~Trajectory_Composite() {
Destroy();
}
void Trajectory_Composite::Write(ostream& os) const {
os << "COMPOSITE[ " << vt.size() << endl;
unsigned int i;
for (i=0;i<vt.size();i++) {
vt[i]->Write(os);
}
os << "]" << endl;
}
Trajectory* Trajectory_Composite::Clone() const{
Trajectory_Composite* comp = new Trajectory_Composite();
for (unsigned int i = 0; i < vt.size(); ++i) {
comp->Add(vt[i]->Clone());
}
return comp;
}
// FreeCAD change
Path* Trajectory_Composite::GetPath()
{
return path;
}
VelocityProfile* Trajectory_Composite::GetProfile()
{
return 0;
}
}
<|endoftext|>
|
<commit_before>#include <limits.h> // UINT32_MAX
#include <stddef.h> // size_t
#include <time.h>
#include "u_rand.h"
namespace u {
static constexpr size_t kSize = 624;
static constexpr size_t kPeriod = 397;
static constexpr size_t kDiff = kSize - kPeriod;
static constexpr uint32_t kMatrix[2] = { 0, 0x9908B0DF };
// State for Mersenne Twister
static struct state {
uint32_t mt[kSize];
size_t index;
state() {
union {
time_t t;
uint32_t u;
} seed = { time(nullptr) };
mt[0] = seed.u;
index = 0;
for (size_t i = 0; i < kSize; ++i)
mt[i] = 0x6C078965 * (mt[i-1] ^ mt[i-1] >> 30) + i;
}
} gState;
#define gMT (gState.mt)
#define gIndex (gState.index)
static inline uint32_t m32(uint32_t x) {
return 0x80000000 & x;
}
static inline uint32_t l31(uint32_t x) {
return 0x7FFFFFFF & x;
}
static inline bool odd(uint32_t x) {
return x & 1; // Check if number is odd
}
static inline void generateNumbers() {
size_t y;
size_t i;
// i = [0 ... 226]
for (i = 0; i < kDiff; ++i) {
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i+kPeriod] ^ (y>>1) ^ kMatrix[odd(y)];
++i;
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i+kPeriod] ^ (y>>1) ^ kMatrix[odd(y)];
}
auto unroll = [&y, &i]() {
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i-kDiff] ^ (y>>1) ^ kMatrix[odd(y)];
++i;
};
// i = [227 ... 622]
for (i = kDiff; i < kSize-1; ) {
for (size_t j = 0; j < 11; j++)
unroll();
}
// i = [623]
y = m32(gMT[kSize-1]) | l31(gMT[kSize-1]);
gMT[kSize-1] = gMT[kPeriod-1] ^ (y>>1) ^ kMatrix[odd(y)];
}
uint32_t randu() {
if (gIndex == 0)
generateNumbers();
uint32_t y = gMT[gIndex];
// Tempering
y ^= y >> 11;
y ^= y << 7 & 0x9D2C5680;
y ^= y << 15 & 0xEFC60000;
y ^= y >> 18;
if (++gIndex == kSize)
gIndex = 0;
return y;
}
float randf() {
return float(randu()) / UINT32_MAX;
}
}
<commit_msg>Fix bug<commit_after>#include <limits.h> // UINT32_MAX
#include <stddef.h> // size_t
#include <time.h>
#include "u_rand.h"
namespace u {
static constexpr size_t kSize = 624;
static constexpr size_t kPeriod = 397;
static constexpr size_t kDiff = kSize - kPeriod;
static constexpr uint32_t kMatrix[2] = { 0, 0x9908B0DF };
// State for Mersenne Twister
static struct state {
uint32_t mt[kSize];
size_t index;
state() {
union {
time_t t;
uint32_t u;
} seed = { time(nullptr) };
mt[0] = seed.u;
index = 0;
for (size_t i = 1; i < kSize; ++i)
mt[i] = 0x6C078965 * (mt[i-1] ^ mt[i-1] >> 30) + i;
}
} gState;
#define gMT (gState.mt)
#define gIndex (gState.index)
static inline uint32_t m32(uint32_t x) {
return 0x80000000 & x;
}
static inline uint32_t l31(uint32_t x) {
return 0x7FFFFFFF & x;
}
static inline bool odd(uint32_t x) {
return x & 1; // Check if number is odd
}
static inline void generateNumbers() {
size_t y;
size_t i;
// i = [0 ... 226]
for (i = 0; i < kDiff; ++i) {
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i+kPeriod] ^ (y>>1) ^ kMatrix[odd(y)];
++i;
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i+kPeriod] ^ (y>>1) ^ kMatrix[odd(y)];
}
auto unroll = [&y, &i]() {
y = m32(gMT[i]) | l31(gMT[i+1]);
gMT[i] = gMT[i-kDiff] ^ (y>>1) ^ kMatrix[odd(y)];
++i;
};
// i = [227 ... 622]
for (i = kDiff; i < kSize-1; ) {
for (size_t j = 0; j < 11; j++)
unroll();
}
// i = [623]
y = m32(gMT[kSize-1]) | l31(gMT[kSize-1]);
gMT[kSize-1] = gMT[kPeriod-1] ^ (y>>1) ^ kMatrix[odd(y)];
}
uint32_t randu() {
if (gIndex == 0)
generateNumbers();
uint32_t y = gMT[gIndex];
// Tempering
y ^= y >> 11;
y ^= y << 7 & 0x9D2C5680;
y ^= y << 15 & 0xEFC60000;
y ^= y >> 18;
if (++gIndex == kSize)
gIndex = 0;
return y;
}
float randf() {
return float(randu()) / UINT32_MAX;
}
}
<|endoftext|>
|
<commit_before>#include <osgParticle/ParticleSystem>
#include <vector>
#include <osg/Drawable>
#include <osg/CopyOp>
#include <osg/State>
#include <osg/Matrix>
#include <osg/GL>
#include <osg/StateSet>
#include <osg/Texture2D>
#include <osg/BlendFunc>
#include <osg/TexEnv>
#include <osg/Material>
#include <osg/Notify>
#include <osgDB/ReadFile>
osgParticle::ParticleSystem::ParticleSystem()
: osg::Drawable(),
_def_bbox(osg::Vec3(-10, -10, -10), osg::Vec3(10, 10, 10)),
_alignment(BILLBOARD),
_align_X_axis(1, 0, 0),
_align_Y_axis(0, 1, 0),
_doublepass(false),
_frozen(false),
_bmin(0, 0, 0),
_bmax(0, 0, 0),
_reset_bounds_flag(false),
_bounds_computed(false),
_def_ptemp(Particle()),
_last_frame(0),
_freeze_on_cull(false),
_detail(1),
_draw_count(0)
{
// we don't support display lists because particle systems
// are dynamic, and they always changes between frames
setSupportsDisplayList(false);
}
osgParticle::ParticleSystem::ParticleSystem(const ParticleSystem& copy, const osg::CopyOp& copyop)
: osg::Drawable(copy, copyop),
_def_bbox(copy._def_bbox),
_alignment(copy._alignment),
_align_X_axis(copy._align_X_axis),
_align_Y_axis(copy._align_Y_axis),
_doublepass(copy._doublepass),
_frozen(copy._frozen),
_bmin(copy._bmin),
_bmax(copy._bmax),
_reset_bounds_flag(copy._reset_bounds_flag),
_bounds_computed(copy._bounds_computed),
_def_ptemp(copy._def_ptemp),
_last_frame(copy._last_frame),
_freeze_on_cull(copy._freeze_on_cull),
_detail(copy._detail),
_draw_count(0)
{
}
osgParticle::ParticleSystem::~ParticleSystem()
{
}
void osgParticle::ParticleSystem::update(double dt)
{
// reset bounds
_reset_bounds_flag = true;
for(unsigned int i=0; i<_particles.size(); ++i)
{
Particle& particle = _particles[i];
if (particle.isAlive())
{
if (particle.update(dt))
{
update_bounds(particle.getPosition(), particle.getCurrentSize());
}
else
{
reuseParticle(i);
}
}
}
// force recomputing of bounding box on next frame
dirtyBound();
}
void osgParticle::ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo) const
{
osg::State& state = *renderInfo.getState();
OpenThreads::ScopedReadLock lock(_readWriteMutex);
// update the frame count, so other objects can detect when
// this particle system is culled
_last_frame = state.getFrameStamp()->getFrameNumber();
// get the current modelview matrix
osg::Matrix modelview = state.getModelViewMatrix();
if (_alignment == BILLBOARD)
state.applyModelViewMatrix(0);
// set up depth mask for first rendering pass
glPushAttrib(GL_DEPTH_BUFFER_BIT);
glDepthMask(GL_FALSE);
// render, first pass
single_pass_render(state, modelview);
// restore depth mask settings
glPopAttrib();
// render, second pass
if (_doublepass) {
// set up color mask for second rendering pass
glPushAttrib(GL_COLOR_BUFFER_BIT);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
// render the particles onto the depth buffer
single_pass_render(state, modelview);
// restore color mask settings
glPopAttrib();
}
}
void osgParticle::ParticleSystem::setDefaultAttributes(const std::string& texturefile, bool emissive_particles, bool lighting, int texture_unit)
{
osg::StateSet *stateset = new osg::StateSet;
stateset->setMode(GL_LIGHTING, lighting? osg::StateAttribute::ON: osg::StateAttribute::OFF);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
osg::Material *material = new osg::Material;
material->setSpecular(osg::Material::FRONT, osg::Vec4(0, 0, 0, 1));
material->setEmission(osg::Material::FRONT, osg::Vec4(0, 0, 0, 1));
material->setColorMode(lighting? osg::Material::AMBIENT_AND_DIFFUSE : osg::Material::OFF);
stateset->setAttributeAndModes(material, osg::StateAttribute::ON);
if (!texturefile.empty()) {
osg::Texture2D *texture = new osg::Texture2D;
texture->setImage(osgDB::readImageFile(texturefile));
texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR);
texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::MIRROR);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::MIRROR);
stateset->setTextureAttributeAndModes(texture_unit, texture, osg::StateAttribute::ON);
osg::TexEnv *texenv = new osg::TexEnv;
texenv->setMode(osg::TexEnv::MODULATE);
stateset->setTextureAttribute(texture_unit, texenv);
}
osg::BlendFunc *blend = new osg::BlendFunc;
if (emissive_particles) {
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE);
} else {
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
}
stateset->setAttributeAndModes(blend, osg::StateAttribute::ON);
setStateSet(stateset);
}
void osgParticle::ParticleSystem::single_pass_render(osg::State& /*state*/, const osg::Matrix& modelview) const
{
_draw_count = 0;
if (_particles.size() <= 0) return;
Particle_vector::const_iterator i;
Particle_vector::const_iterator i0 = _particles.begin();
Particle_vector::const_iterator end = _particles.end();
i0->beginRender();
float scale = sqrtf(static_cast<float>(_detail));
for (i=i0; i<end; i+=_detail) {
if (i->isAlive()) {
if (i->getShape() != i0->getShape()) {
i0->endRender();
i->beginRender();
i0 = i;
}
++_draw_count;
switch (_alignment) {
case BILLBOARD:
i->render(modelview.preMult(i->getPosition()), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0), scale);
break;
case FIXED:
i->render(i->getPosition(), _align_X_axis, _align_Y_axis, scale);
break;
default: ;
}
}
}
i0->endRender();
}
osg::BoundingBox osgParticle::ParticleSystem::computeBound() const
{
if (!_bounds_computed)
{
return _def_bbox;
} else
{
return osg::BoundingBox(_bmin,_bmax);
}
}
<commit_msg>Refactor the rendering code to not use iterators, instead using indices as means of avoiding using < and += on STL iterators that have shown to be problematic under Windows<commit_after>#include <osgParticle/ParticleSystem>
#include <vector>
#include <osg/Drawable>
#include <osg/CopyOp>
#include <osg/State>
#include <osg/Matrix>
#include <osg/GL>
#include <osg/StateSet>
#include <osg/Texture2D>
#include <osg/BlendFunc>
#include <osg/TexEnv>
#include <osg/Material>
#include <osg/Notify>
#include <osgDB/ReadFile>
osgParticle::ParticleSystem::ParticleSystem()
: osg::Drawable(),
_def_bbox(osg::Vec3(-10, -10, -10), osg::Vec3(10, 10, 10)),
_alignment(BILLBOARD),
_align_X_axis(1, 0, 0),
_align_Y_axis(0, 1, 0),
_doublepass(false),
_frozen(false),
_bmin(0, 0, 0),
_bmax(0, 0, 0),
_reset_bounds_flag(false),
_bounds_computed(false),
_def_ptemp(Particle()),
_last_frame(0),
_freeze_on_cull(false),
_detail(1),
_draw_count(0)
{
// we don't support display lists because particle systems
// are dynamic, and they always changes between frames
setSupportsDisplayList(false);
}
osgParticle::ParticleSystem::ParticleSystem(const ParticleSystem& copy, const osg::CopyOp& copyop)
: osg::Drawable(copy, copyop),
_def_bbox(copy._def_bbox),
_alignment(copy._alignment),
_align_X_axis(copy._align_X_axis),
_align_Y_axis(copy._align_Y_axis),
_doublepass(copy._doublepass),
_frozen(copy._frozen),
_bmin(copy._bmin),
_bmax(copy._bmax),
_reset_bounds_flag(copy._reset_bounds_flag),
_bounds_computed(copy._bounds_computed),
_def_ptemp(copy._def_ptemp),
_last_frame(copy._last_frame),
_freeze_on_cull(copy._freeze_on_cull),
_detail(copy._detail),
_draw_count(0)
{
}
osgParticle::ParticleSystem::~ParticleSystem()
{
}
void osgParticle::ParticleSystem::update(double dt)
{
// reset bounds
_reset_bounds_flag = true;
for(unsigned int i=0; i<_particles.size(); ++i)
{
Particle& particle = _particles[i];
if (particle.isAlive())
{
if (particle.update(dt))
{
update_bounds(particle.getPosition(), particle.getCurrentSize());
}
else
{
reuseParticle(i);
}
}
}
// force recomputing of bounding box on next frame
dirtyBound();
}
void osgParticle::ParticleSystem::drawImplementation(osg::RenderInfo& renderInfo) const
{
osg::State& state = *renderInfo.getState();
OpenThreads::ScopedReadLock lock(_readWriteMutex);
// update the frame count, so other objects can detect when
// this particle system is culled
_last_frame = state.getFrameStamp()->getFrameNumber();
// get the current modelview matrix
osg::Matrix modelview = state.getModelViewMatrix();
if (_alignment == BILLBOARD)
state.applyModelViewMatrix(0);
// set up depth mask for first rendering pass
glPushAttrib(GL_DEPTH_BUFFER_BIT);
glDepthMask(GL_FALSE);
// render, first pass
single_pass_render(state, modelview);
// restore depth mask settings
glPopAttrib();
// render, second pass
if (_doublepass) {
// set up color mask for second rendering pass
glPushAttrib(GL_COLOR_BUFFER_BIT);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
// render the particles onto the depth buffer
single_pass_render(state, modelview);
// restore color mask settings
glPopAttrib();
}
}
void osgParticle::ParticleSystem::setDefaultAttributes(const std::string& texturefile, bool emissive_particles, bool lighting, int texture_unit)
{
osg::StateSet *stateset = new osg::StateSet;
stateset->setMode(GL_LIGHTING, lighting? osg::StateAttribute::ON: osg::StateAttribute::OFF);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
osg::Material *material = new osg::Material;
material->setSpecular(osg::Material::FRONT, osg::Vec4(0, 0, 0, 1));
material->setEmission(osg::Material::FRONT, osg::Vec4(0, 0, 0, 1));
material->setColorMode(lighting? osg::Material::AMBIENT_AND_DIFFUSE : osg::Material::OFF);
stateset->setAttributeAndModes(material, osg::StateAttribute::ON);
if (!texturefile.empty()) {
osg::Texture2D *texture = new osg::Texture2D;
texture->setImage(osgDB::readImageFile(texturefile));
texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR);
texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR);
texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::MIRROR);
texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::MIRROR);
stateset->setTextureAttributeAndModes(texture_unit, texture, osg::StateAttribute::ON);
osg::TexEnv *texenv = new osg::TexEnv;
texenv->setMode(osg::TexEnv::MODULATE);
stateset->setTextureAttribute(texture_unit, texenv);
}
osg::BlendFunc *blend = new osg::BlendFunc;
if (emissive_particles) {
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE);
} else {
blend->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
}
stateset->setAttributeAndModes(blend, osg::StateAttribute::ON);
setStateSet(stateset);
}
void osgParticle::ParticleSystem::single_pass_render(osg::State& /*state*/, const osg::Matrix& modelview) const
{
_draw_count = 0;
if (_particles.size() <= 0) return;
float scale = sqrtf(static_cast<float>(_detail));
const Particle* startParticle = &_particles[0];
startParticle->beginRender();
for(unsigned int i=0; i<_particles.size(); i+=_detail)
{
const Particle* currentParticle = &_particles[i];
if (currentParticle->isAlive())
{
if (currentParticle->getShape() != startParticle->getShape());
{
startParticle->endRender();
currentParticle->beginRender();
startParticle = currentParticle;
}
++_draw_count;
switch (_alignment) {
case BILLBOARD:
currentParticle->render(modelview.preMult(currentParticle->getPosition()), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0), scale);
break;
case FIXED:
currentParticle->render(currentParticle->getPosition(), _align_X_axis, _align_Y_axis, scale);
break;
default:;
}
}
}
startParticle->endRender();
}
osg::BoundingBox osgParticle::ParticleSystem::computeBound() const
{
if (!_bounds_computed)
{
return _def_bbox;
} else
{
return osg::BoundingBox(_bmin,_bmax);
}
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
_applicationUsage = osg::ApplicationUsage::instance();
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
CameraGroup::setView(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
_frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}
<commit_msg>Added environmental variable usage to OsgCameraGroup.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
static osg::ApplicationUsageProxy OsgCameraGroup_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"PRODUCER_CAMERA_CONFIG_FILE <filename>","specify the default producer camera config to use when opening osgProducer based applications.");
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
_applicationUsage = osg::ApplicationUsage::instance();
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
CameraGroup::setView(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
_frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
static osg::ApplicationUsageProxy OsgCameraGroup_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"PRODUCER_CAMERA_CONFIG_FILE <filename>","specify the default producer camera config to use when opening osgProducer based applications.");
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
Producer::RenderSurface *rs = cam->getRenderSurface();
if (rs->getWindowName()==" *** RenderSurface *** ")
{
rs->setWindowName(arguments.getApplicationName());
}
}
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
// set up the time and frame counter.
_frameNumber = 0;
_start_tick = _timer.tick();
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
_applicationUsage = osg::ApplicationUsage::instance();
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
setViewByMatrix(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::sync()
{
CameraGroup::sync();
// set the frame stamp for the new frame.
double time_since_start = _timer.delta_s(_start_tick,_timer.tick());
_frameStamp->setFrameNumber(_frameNumber++);
_frameStamp->setReferenceTime(time_since_start);
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
}
<commit_msg>Added check for camera's sharing the same RenderSurface, if so switches off multi-threading of cull and draw.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
static osg::ApplicationUsageProxy OsgCameraGroup_e1(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE,"PRODUCER_CAMERA_CONFIG_FILE <filename>","specify the default producer camera config to use when opening osgProducer based applications.");
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
Producer::RenderSurface *rs = cam->getRenderSurface();
if (rs->getWindowName()==" *** RenderSurface *** ")
{
rs->setWindowName(arguments.getApplicationName());
}
}
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
// set up the time and frame counter.
_frameNumber = 0;
_start_tick = _timer.tick();
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
_applicationUsage = osg::ApplicationUsage::instance();
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
else
{
std::set<RenderSurface*> renderSurfaceSet;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
renderSurfaceSet.insert(cam->getRenderSurface());
}
if (renderSurfaceSet.size()!=_cfg->getNumberOfCameras())
{
// camera's must be sharing a RenderSurface, so we need to ensure that we're
// running single threaded, to avoid OpenGL threading issues.
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw to avoid"<<std::endl;
osg::notify(osg::INFO)<<" threading problems when camera's share a RenderSurface."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
setViewByMatrix(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::sync()
{
CameraGroup::sync();
// set the frame stamp for the new frame.
double time_since_start = _timer.delta_s(_start_tick,_timer.tick());
_frameStamp->setFrameNumber(_frameNumber++);
_frameStamp->setReferenceTime(time_since_start);
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
}
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2013, 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 main.cxx
*
* An application for updating the firmware of a remote node on the bus.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/Crc.hxx"
#include "utils/FileUtils.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/DatagramCan.hxx"
#include "nmranet/BootloaderClient.hxx"
#include "nmranet/If.hxx"
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet/NodeInitializeFlow.hxx"
#include "utils/socket_listener.hxx"
#include "freertos/bootloader_hal.h"
NO_THREAD nt;
Executor<1> g_executor(nt);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
static const nmranet::NodeID NODE_ID = 0x05010101181FULL;
nmranet::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2);
nmranet::InitializeFlow g_init_flow{&g_service};
nmranet::CanDatagramService g_datagram_can(&g_if_can, 10, 2);
static nmranet::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can);
nmranet::DefaultNode g_node(&g_if_can, NODE_ID);
namespace nmranet
{
Pool *const g_incoming_datagram_allocator = mainBufferPool;
}
int port = 12021;
const char *host = "localhost";
const char *device_path = nullptr;
const char *filename = nullptr;
uint64_t destination_nodeid = 0;
uint64_t destination_alias = 0;
int memory_space_id = nmranet::MemoryConfigDefs::SPACE_FIRMWARE;
const char *checksum_algorithm = nullptr;
bool request_reboot = false;
bool request_reboot_after = true;
bool skip_pip = false;
void usage(const char *e)
{
fprintf(stderr,
"Usage: %s ([-i destination_host] [-p port] | [-d device_path]) [-s "
"memory_space_id] [-c csum_algo] [-r] [-t] [-x] (-n nodeid | -a "
"alias) -f filename\n",
e);
fprintf(stderr, "Connects to an openlcb bus and performs the "
"bootloader protocol on openlcb node with id nodeid with "
"the contents of a given file.\n");
fprintf(stderr,
"The bus connection will be through an OpenLCB HUB on "
"destination_host:port with OpenLCB over TCP "
"(in GridConnect format) protocol, or through the CAN-USB device "
"(also in GridConnect protocol) found at device_path. Device takes "
"precedence over TCP host:port specification.");
fprintf(stderr, "The default target is localhost:12021.\n");
fprintf(stderr, "nodeid should be a 12-char hex string with 0x prefix and "
"no separators, like '-b 0x05010101141F'\n");
fprintf(stderr, "alias should be a 3-char hex string with 0x prefix and no "
"separators, like '-a 0x3F9'\n");
fprintf(stderr, "memory_space_id defines which memory space to write the "
"data into. Default is '-s 0xF0'.\n");
fprintf(stderr, "csum_algo defines the checksum algorithm to use. If "
"omitted, no checksumming is done before writing the "
"data.\n");
fprintf(stderr,
"-r request the target to enter bootloader mode before sending data\n");
fprintf(stderr, "Unless -t is specified the target will be rebooted after "
"flashing complete.\n");
fprintf(stderr, "-x skips the PIP request and uses streams.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:rtd:n:a:s:f:c:x")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
case 'p':
port = atoi(optarg);
break;
case 'i':
host = optarg;
break;
case 'd':
device_path = optarg;
break;
case 'f':
filename = optarg;
break;
case 'n':
destination_nodeid = strtoll(optarg, nullptr, 16);
break;
case 'a':
destination_alias = strtoul(optarg, nullptr, 16);
break;
case 's':
memory_space_id = strtol(optarg, nullptr, 16);
break;
case 'c':
checksum_algorithm = optarg;
break;
case 'r':
request_reboot = true;
break;
case 'x':
skip_pip = true;
break;
case 't':
request_reboot_after = false;
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
if (!filename || (!destination_nodeid && !destination_alias))
{
usage(argv[0]);
}
}
nmranet::BootloaderClient bootloader_client(
&g_node, &g_datagram_can, &g_if_can);
nmranet::BootloaderResponse response;
void maybe_checksum(string *firmware)
{
if (!checksum_algorithm)
return;
string algo = checksum_algorithm;
if (algo == "tiva123")
{
struct app_header hdr;
memset(&hdr, 0, sizeof(hdr));
// magic constant that comes from the size of the interrupt table. The
// actual target has this in memory_map.ld.
uint32_t offset = 0x270;
if (firmware->size() < offset + sizeof(hdr))
{
fprintf(stderr, "Failed to checksum: firmware too small.\n");
exit(1);
}
if (memcmp(&hdr, &(*firmware)[offset], sizeof(hdr)))
{
fprintf(stderr,
"Failed to checksum: location of checksum is not empty.\n");
exit(1);
}
hdr.app_size = firmware->size();
crc3_crc16_ibm(
&(*firmware)[8], (offset - 8) & ~3, (uint16_t *)hdr.checksum_pre);
crc3_crc16_ibm(&(*firmware)[offset + sizeof(hdr)],
(firmware->size() - offset - sizeof(hdr)) & ~3,
(uint16_t *)hdr.checksum_post);
memcpy(&(*firmware)[offset], &hdr, sizeof(hdr));
printf("Checksummed firmware with algorithm tiva123\n");
uint32_t reset_handler;
memcpy(&reset_handler, firmware->data() + 52, 4);
if (!reset_handler) {
fprintf(stderr,
"Firmware does not contain any entry vector at offset 52.\n");
exit(1);
}
}
else
{
fprintf(stderr,
"Unknown checksumming algo %s. Known algorithms are: tiva123.\n",
checksum_algorithm);
exit(1);
}
}
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
int conn_fd = 0;
if (device_path)
{
conn_fd = ::open(device_path, O_RDWR);
}
else
{
conn_fd = ConnectSocket(host, port);
}
HASSERT(conn_fd >= 0);
create_gc_port_for_can_hub(&can_hub0, conn_fd);
g_if_can.add_addressed_message_support();
// Bootstraps the alias allocation process.
g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc());
g_executor.start_thread("g_executor", 0, 1024);
usleep(400000);
SyncNotifiable n;
BarrierNotifiable bn(&n);
Buffer<nmranet::BootloaderRequest> *b;
mainBufferPool->alloc(&b);
b->set_done(&bn);
b->data()->dst.alias = destination_alias;
b->data()->dst.id = destination_nodeid;
b->data()->memory_space = memory_space_id;
b->data()->offset = 0;
b->data()->response = &response;
b->data()->request_reboot = request_reboot ? 1 : 0;
b->data()->request_reboot_after = request_reboot_after ? 1 : 0;
b->data()->skip_pip = skip_pip ? 1 : 0;
b->data()->data = read_file_to_string(filename);
printf("Read %" PRIdPTR
" bytes from file %s. Writing to memory space 0x%02x\n",
b->data()->data.size(), filename, memory_space_id);
maybe_checksum(&b->data()->data);
bootloader_client.send(b);
n.wait_for_notification();
printf("Result: %04x %s\n", response.error_code,
response.error_details.c_str());
return 0;
}
<commit_msg>Adds missing cmdline option.<commit_after>/** \copyright
* Copyright (c) 2013, 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 main.cxx
*
* An application for updating the firmware of a remote node on the bus.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <unistd.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/Crc.hxx"
#include "utils/FileUtils.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/DatagramCan.hxx"
#include "nmranet/BootloaderClient.hxx"
#include "nmranet/If.hxx"
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet/NodeInitializeFlow.hxx"
#include "utils/socket_listener.hxx"
#include "freertos/bootloader_hal.h"
NO_THREAD nt;
Executor<1> g_executor(nt);
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
static const nmranet::NodeID NODE_ID = 0x05010101181FULL;
nmranet::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2);
nmranet::InitializeFlow g_init_flow{&g_service};
nmranet::CanDatagramService g_datagram_can(&g_if_can, 10, 2);
static nmranet::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can);
nmranet::DefaultNode g_node(&g_if_can, NODE_ID);
namespace nmranet
{
Pool *const g_incoming_datagram_allocator = mainBufferPool;
}
int port = 12021;
const char *host = "localhost";
const char *device_path = nullptr;
const char *filename = nullptr;
uint64_t destination_nodeid = 0;
uint64_t destination_alias = 0;
int memory_space_id = nmranet::MemoryConfigDefs::SPACE_FIRMWARE;
const char *checksum_algorithm = nullptr;
bool request_reboot = false;
bool request_reboot_after = true;
bool skip_pip = false;
void usage(const char *e)
{
fprintf(stderr,
"Usage: %s ([-i destination_host] [-p port] | [-d device_path]) [-s "
"memory_space_id] [-c csum_algo] [-r] [-t] [-x] (-n nodeid | -a "
"alias) -f filename\n",
e);
fprintf(stderr, "Connects to an openlcb bus and performs the "
"bootloader protocol on openlcb node with id nodeid with "
"the contents of a given file.\n");
fprintf(stderr,
"The bus connection will be through an OpenLCB HUB on "
"destination_host:port with OpenLCB over TCP "
"(in GridConnect format) protocol, or through the CAN-USB device "
"(also in GridConnect protocol) found at device_path. Device takes "
"precedence over TCP host:port specification.");
fprintf(stderr, "The default target is localhost:12021.\n");
fprintf(stderr, "nodeid should be a 12-char hex string with 0x prefix and "
"no separators, like '-b 0x05010101141F'\n");
fprintf(stderr, "alias should be a 3-char hex string with 0x prefix and no "
"separators, like '-a 0x3F9'\n");
fprintf(stderr, "memory_space_id defines which memory space to write the "
"data into. Default is '-s 0xF0'.\n");
fprintf(stderr, "csum_algo defines the checksum algorithm to use. If "
"omitted, no checksumming is done before writing the "
"data.\n");
fprintf(stderr,
"-r request the target to enter bootloader mode before sending data\n");
fprintf(stderr, "Unless -t is specified the target will be rebooted after "
"flashing complete.\n");
fprintf(stderr, "-x skips the PIP request and uses streams.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:i:rtd:n:a:s:f:c:x")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
case 'p':
port = atoi(optarg);
break;
case 'i':
host = optarg;
break;
case 'd':
device_path = optarg;
break;
case 'f':
filename = optarg;
break;
case 'n':
destination_nodeid = strtoll(optarg, nullptr, 16);
break;
case 'a':
destination_alias = strtoul(optarg, nullptr, 16);
break;
case 's':
memory_space_id = strtol(optarg, nullptr, 16);
break;
case 'c':
checksum_algorithm = optarg;
break;
case 'r':
request_reboot = true;
break;
case 'x':
skip_pip = true;
break;
case 't':
request_reboot_after = false;
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
if (!filename || (!destination_nodeid && !destination_alias))
{
usage(argv[0]);
}
}
nmranet::BootloaderClient bootloader_client(
&g_node, &g_datagram_can, &g_if_can);
nmranet::BootloaderResponse response;
void maybe_checksum(string *firmware)
{
if (!checksum_algorithm)
return;
string algo = checksum_algorithm;
if (algo == "tiva123")
{
struct app_header hdr;
memset(&hdr, 0, sizeof(hdr));
// magic constant that comes from the size of the interrupt table. The
// actual target has this in memory_map.ld.
uint32_t offset = 0x270;
if (firmware->size() < offset + sizeof(hdr))
{
fprintf(stderr, "Failed to checksum: firmware too small.\n");
exit(1);
}
if (memcmp(&hdr, &(*firmware)[offset], sizeof(hdr)))
{
fprintf(stderr,
"Failed to checksum: location of checksum is not empty.\n");
exit(1);
}
hdr.app_size = firmware->size();
crc3_crc16_ibm(
&(*firmware)[8], (offset - 8) & ~3, (uint16_t *)hdr.checksum_pre);
crc3_crc16_ibm(&(*firmware)[offset + sizeof(hdr)],
(firmware->size() - offset - sizeof(hdr)) & ~3,
(uint16_t *)hdr.checksum_post);
memcpy(&(*firmware)[offset], &hdr, sizeof(hdr));
printf("Checksummed firmware with algorithm tiva123\n");
uint32_t reset_handler;
memcpy(&reset_handler, firmware->data() + 52, 4);
if (!reset_handler) {
fprintf(stderr,
"Firmware does not contain any entry vector at offset 52.\n");
exit(1);
}
}
else
{
fprintf(stderr,
"Unknown checksumming algo %s. Known algorithms are: tiva123.\n",
checksum_algorithm);
exit(1);
}
}
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
int conn_fd = 0;
if (device_path)
{
conn_fd = ::open(device_path, O_RDWR);
}
else
{
conn_fd = ConnectSocket(host, port);
}
HASSERT(conn_fd >= 0);
create_gc_port_for_can_hub(&can_hub0, conn_fd);
g_if_can.add_addressed_message_support();
// Bootstraps the alias allocation process.
g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc());
g_executor.start_thread("g_executor", 0, 1024);
usleep(400000);
SyncNotifiable n;
BarrierNotifiable bn(&n);
Buffer<nmranet::BootloaderRequest> *b;
mainBufferPool->alloc(&b);
b->set_done(&bn);
b->data()->dst.alias = destination_alias;
b->data()->dst.id = destination_nodeid;
b->data()->memory_space = memory_space_id;
b->data()->offset = 0;
b->data()->response = &response;
b->data()->request_reboot = request_reboot ? 1 : 0;
b->data()->request_reboot_after = request_reboot_after ? 1 : 0;
b->data()->skip_pip = skip_pip ? 1 : 0;
b->data()->data = read_file_to_string(filename);
printf("Read %" PRIdPTR
" bytes from file %s. Writing to memory space 0x%02x\n",
b->data()->data.size(), filename, memory_space_id);
maybe_checksum(&b->data()->data);
bootloader_client.send(b);
n.wait_for_notification();
printf("Result: %04x %s\n", response.error_code,
response.error_details.c_str());
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* 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 AUTHOR ``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 AUTHOR 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 <QtCrypto>
#include <QtTest/QtTest>
class TLSUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testCipherList();
private:
QCA::Initializer* m_init;
};
void TLSUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void TLSUnitTest::cleanupTestCase()
{
delete m_init;
}
void TLSUnitTest::testCipherList()
{
if(!QCA::isSupported("tls", "qca-openssl"))
QWARN("TLS not supported for qca-openssl");
else {
QStringList cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::TLS_v1, "qca-openssl");
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_IDEA_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") );
cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v3, "qca-openssl");
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_IDEA_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") );
cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v2, "qca-openssl");
QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_64_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
}
}
QTEST_MAIN(TLSUnitTest)
#include "tlsunittest.moc"
<commit_msg>It looks like it is pretty common to compile openssl without support for IDEA (presumably because of patents).<commit_after>/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* 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 AUTHOR ``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 AUTHOR 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 <QtCrypto>
#include <QtTest/QtTest>
class TLSUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testCipherList();
private:
QCA::Initializer* m_init;
};
void TLSUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void TLSUnitTest::cleanupTestCase()
{
delete m_init;
}
void TLSUnitTest::testCipherList()
{
if(!QCA::isSupported("tls", "qca-openssl"))
QWARN("TLS not supported for qca-openssl");
else {
QStringList cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::TLS_v1, "qca-openssl");
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") );
QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") );
cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v3, "qca-openssl");
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") );
QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") );
QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") );
cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v2, "qca-openssl");
QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_64_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") );
QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
}
}
QTEST_MAIN(TLSUnitTest)
#include "tlsunittest.moc"
<|endoftext|>
|
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "syntaxSupport.h"
QStringList Custom_Syntax::availableRules(){
QStringList avail;
avail << "C++";
avail << "Python";
avail << "reST";
return avail;
}
QStringList Custom_Syntax::knownColors(){
//Note: All these colors should be prefixed with "colors/" when accessing them from the settings file
QStringList avail;
//Standard colors
avail << "keyword" << "altkeyword" << "class" << "text" << "function" << "comment";
//Bracket/parenthesis/brace matching
avail << "bracket-found" << "bracket-missing";
return avail;
}
void Custom_Syntax::SetupDefaultColors(QSettings *settings){
if(!settings->contains("colors/keyword")){settings->setValue("colors/keyword", QColor(Qt::blue).name() ); }
if(!settings->contains("colors/altkeyword")){settings->setValue("colors/altkeyword", QColor(Qt::darkBlue).name() ); }
if(!settings->contains("colors/class")){settings->setValue("colors/class", QColor(Qt::darkRed).name() ); }
if(!settings->contains("colors/text")){settings->setValue("colors/text", QColor(Qt::darkMagenta).name() ); }
if(!settings->contains("colors/function")){settings->setValue("colors/function", QColor(Qt::darkCyan).name() ); }
if(!settings->contains("colors/comment")){settings->setValue("colors/comment", QColor(Qt::darkGreen).name() ); }
if(!settings->contains("colors/bracket-found")){settings->setValue("colors/bracket-found", QColor(Qt::green).name() ); }
if(!settings->contains("colors/bracket-missing")){settings->setValue("colors/bracket-missing", QColor(Qt::red).name() ); }
if(!settings->contains("colors/preprocessor")){settings->setValue("colors/preprocessor", QColor(Qt::darkYellow).name() ); }
}
QString Custom_Syntax::ruleForFile(QString filename){
QString suffix = filename.section(".",-1);
if(suffix=="cpp" || suffix=="hpp" || suffix=="c" || suffix=="h"){ return "C++"; }
else if(suffix=="py" || suffix=="pyc"){ return "Python"; }
else if(suffix=="rst"){ return "reST"; }
return "";
}
void Custom_Syntax::loadRules(QString type){
//NOTE: the "multiLineComment
lasttype = type;
rules.clear();
splitrules.clear();
if(type=="C++"){
//Keywords (standard C/C++/Qt definitions)
QStringList keywords;
keywords << "char" << "class" << "const" << "double" << "enum" << "explicit" << "friend" << "inline" \
<< "int" << "long" << "namespace" << "operator" << "private" << "protected" << "public" \
<< "short" << "signals" << "signed" << "slots" << "static" << "struct" << "template" \
<< "typedef" << "typename" << "union" << "unsigned" << "virtual" << "void" << "volatile";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Class Names
rule.format.setForeground( QColor(settings->value("colors/class").toString()) );
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp("\".*\"");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Proprocessor commands
rule.format.setForeground( QColor(settings->value("colors/preprocessor").toString()) );
rule.pattern = QRegExp("^#[^\n]*");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("//[^\n]*");
rules << rule;
//Comment (multi-line)
SyntaxRuleSplit srule;
srule.format = rule.format; //re-use the single-line comment format
srule.startPattern = QRegExp("/\\*");
srule.endPattern = QRegExp("\\*/");
splitrules << srule;
}else if(type=="Python"){
//Keywords
QStringList keywords;
keywords << "and" << "as" << "assert" << "break" << "class" << "continue" << "def" << "del" \
<< "elif" << "else" << "except" << "exec" << "finally" << "for" << "from" \
<< "global" << "if" << "import" << "in" << "is" << "lambda" << "not" \
<< "or" << "pass" << "print" << "raise" << "return" << "try" << "while" << "with" << "yield";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Class Names
//rule.format.setForeground(Qt::darkMagenta);
//rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
//rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp("\".*\"");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("#[^\n]*");
rules << rule;
//Comment (multi-line)
//SyntaxRuleSplit srule;
//srule.format = rule.format; //re-use the single-line comment format
//srule.startPattern = QRegExp("/\\*");
//srule.endPattern = QRegExp("\\*/");
//splitrules << srule;
}else if(type=="reST"){
//Keywords
QStringList keywords;
keywords << "emphasis" << "strong" << "literal" << "subscript" << "superscript" << "title-reference";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Directives
keywords.clear();
keywords << "image" << "figure" << "contents" << "container" << "rubric" << "topic" << "sidebar" \
<< "parsed-literal" << "epigraph" << "highlights" << "pull-quote" << "compound" << "table" << "csv-table" \
<< "list-table" << "raw" << "include"<< "class" << "meta" << "title" << "default-role" << "role";
rule.format.setForeground( QColor(settings->value("colors/altkeyword").toString()) );
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"::\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Reset the font color
rule.format = QTextCharFormat();
// Strong Emphasis
rule.format.setFontItalic(false);
rule.format.setFontWeight(QFont::Bold);
rule.pattern = QRegExp("\\b[*]{2}[^*\n]+[*]{2}\\b");
rules << rule;
// Emphasis
rule.format.setFontItalic(true);
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp("\\b[*][^*\n]+[*]\\b");
rules << rule;
// Code Sample
rule.format.setFontItalic(false);
rule.format.setFontWeight(QFont::Light);
rule.format.setFontFixedPitch(true);
rule.pattern = QRegExp("\\b`{2}.*`{2}\\b");
rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp("\".*\"");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("\\b[.]{2}[^\n]*");
rules << rule;
//Comment (multi-line)
//SyntaxRuleSplit srule;
//srule.format = rule.format; //re-use the single-line comment format
//srule.startPattern = QRegExp("/\\*");
//srule.endPattern = QRegExp("\\*/");
//splitrules << srule;
}
}<commit_msg>Fix up the syntax rule for highlighting quoted string. Now it will properly work for multiple strings on a single line, and ignore escaped quotes as necessary.<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "syntaxSupport.h"
QStringList Custom_Syntax::availableRules(){
QStringList avail;
avail << "C++";
avail << "Python";
avail << "reST";
return avail;
}
QStringList Custom_Syntax::knownColors(){
//Note: All these colors should be prefixed with "colors/" when accessing them from the settings file
QStringList avail;
//Standard colors
avail << "keyword" << "altkeyword" << "class" << "text" << "function" << "comment";
//Bracket/parenthesis/brace matching
avail << "bracket-found" << "bracket-missing";
return avail;
}
void Custom_Syntax::SetupDefaultColors(QSettings *settings){
if(!settings->contains("colors/keyword")){settings->setValue("colors/keyword", QColor(Qt::blue).name() ); }
if(!settings->contains("colors/altkeyword")){settings->setValue("colors/altkeyword", QColor(Qt::darkBlue).name() ); }
if(!settings->contains("colors/class")){settings->setValue("colors/class", QColor(Qt::darkRed).name() ); }
if(!settings->contains("colors/text")){settings->setValue("colors/text", QColor(Qt::darkMagenta).name() ); }
if(!settings->contains("colors/function")){settings->setValue("colors/function", QColor(Qt::darkCyan).name() ); }
if(!settings->contains("colors/comment")){settings->setValue("colors/comment", QColor(Qt::darkGreen).name() ); }
if(!settings->contains("colors/bracket-found")){settings->setValue("colors/bracket-found", QColor(Qt::green).name() ); }
if(!settings->contains("colors/bracket-missing")){settings->setValue("colors/bracket-missing", QColor(Qt::red).name() ); }
if(!settings->contains("colors/preprocessor")){settings->setValue("colors/preprocessor", QColor(Qt::darkYellow).name() ); }
}
QString Custom_Syntax::ruleForFile(QString filename){
QString suffix = filename.section(".",-1);
if(suffix=="cpp" || suffix=="hpp" || suffix=="c" || suffix=="h"){ return "C++"; }
else if(suffix=="py" || suffix=="pyc"){ return "Python"; }
else if(suffix=="rst"){ return "reST"; }
return "";
}
void Custom_Syntax::loadRules(QString type){
//NOTE: the "multiLineComment
lasttype = type;
rules.clear();
splitrules.clear();
if(type=="C++"){
//Keywords (standard C/C++/Qt definitions)
QStringList keywords;
keywords << "char" << "class" << "const" << "double" << "enum" << "explicit" << "friend" << "inline" \
<< "int" << "long" << "namespace" << "operator" << "private" << "protected" << "public" \
<< "short" << "signals" << "signed" << "slots" << "static" << "struct" << "template" \
<< "typedef" << "typename" << "union" << "unsigned" << "virtual" << "void" << "volatile";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Class Names
rule.format.setForeground( QColor(settings->value("colors/class").toString()) );
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp( "\"[^\"\\\\]*(\\\\(.|\\n)[^\"\\\\]*)*\"|'[^'\\\\]*(\\\\(.|\\n)[^'\\\\]*)*'");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Proprocessor commands
rule.format.setForeground( QColor(settings->value("colors/preprocessor").toString()) );
rule.pattern = QRegExp("^#[^\n]*");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("//[^\n]*");
rules << rule;
//Comment (multi-line)
SyntaxRuleSplit srule;
srule.format = rule.format; //re-use the single-line comment format
srule.startPattern = QRegExp("/\\*");
srule.endPattern = QRegExp("\\*/");
splitrules << srule;
}else if(type=="Python"){
//Keywords
QStringList keywords;
keywords << "and" << "as" << "assert" << "break" << "class" << "continue" << "def" << "del" \
<< "elif" << "else" << "except" << "exec" << "finally" << "for" << "from" \
<< "global" << "if" << "import" << "in" << "is" << "lambda" << "not" \
<< "or" << "pass" << "print" << "raise" << "return" << "try" << "while" << "with" << "yield";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Class Names
//rule.format.setForeground(Qt::darkMagenta);
//rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
//rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp( "\"[^\"\\\\]*(\\\\(.|\\n)[^\"\\\\]*)*\"|'[^'\\\\]*(\\\\(.|\\n)[^'\\\\]*)*'");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("#[^\n]*");
rules << rule;
//Comment (multi-line)
//SyntaxRuleSplit srule;
//srule.format = rule.format; //re-use the single-line comment format
//srule.startPattern = QRegExp("/\\*");
//srule.endPattern = QRegExp("\\*/");
//splitrules << srule;
}else if(type=="reST"){
//Keywords
QStringList keywords;
keywords << "emphasis" << "strong" << "literal" << "subscript" << "superscript" << "title-reference";
SyntaxRule rule;
rule.format.setForeground( QColor(settings->value("colors/keyword").toString()) );
rule.format.setFontWeight(QFont::Bold);
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Directives
keywords.clear();
keywords << "image" << "figure" << "contents" << "container" << "rubric" << "topic" << "sidebar" \
<< "parsed-literal" << "epigraph" << "highlights" << "pull-quote" << "compound" << "table" << "csv-table" \
<< "list-table" << "raw" << "include"<< "class" << "meta" << "title" << "default-role" << "role";
rule.format.setForeground( QColor(settings->value("colors/altkeyword").toString()) );
for(int i=0; i<keywords.length(); i++){
rule.pattern = QRegExp("\\b"+keywords[i]+"::\\b"); //turn each keyword into a QRegExp and insert the rule
rules << rule;
}
//Reset the font color
rule.format = QTextCharFormat();
// Strong Emphasis
rule.format.setFontItalic(false);
rule.format.setFontWeight(QFont::Bold);
rule.pattern = QRegExp("\\b[*]{2}[^*\n]+[*]{2}\\b");
rules << rule;
// Emphasis
rule.format.setFontItalic(true);
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp("\\b[*][^*\n]+[*]\\b");
rules << rule;
// Code Sample
rule.format.setFontItalic(false);
rule.format.setFontWeight(QFont::Light);
rule.format.setFontFixedPitch(true);
rule.pattern = QRegExp("\\b`{2}.*`{2}\\b");
rules << rule;
//Quotes
rule.format.setForeground( QColor(settings->value("colors/text").toString()) );
rule.format.setFontWeight(QFont::Normal);
rule.pattern = QRegExp( "\"[^\"\\\\]*(\\\\(.|\\n)[^\"\\\\]*)*\"|'[^'\\\\]*(\\\\(.|\\n)[^'\\\\]*)*'");
rules << rule;
//Functions
rule.format.setForeground( QColor(settings->value("colors/function").toString()) );
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rules << rule;
//Comment (single line)
rule.format.setForeground( QColor(settings->value("colors/comment").toString()) );
rule.pattern = QRegExp("\\b[.]{2}[^\n]*");
rules << rule;
//Comment (multi-line)
//SyntaxRuleSplit srule;
//srule.format = rule.format; //re-use the single-line comment format
//srule.startPattern = QRegExp("/\\*");
//srule.endPattern = QRegExp("\\*/");
//splitrules << srule;
}
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dp_sfwk.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-11-09 14:13:06 $
*
* 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 "dp_sfwk.hrc"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_parceldesc.hxx"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "svtools/inettype.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <memory>
using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::script;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
class PackageImpl : public ::dp_registry::backend::Package
{
BackendImpl * getMyBackend() const {
return static_cast<BackendImpl *>(m_myBackend.get());
}
Reference< container::XNameContainer > m_xNameCntrPkgHandler;
OUString m_descr;
void initPackageHandler();
// Package
virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
virtual void processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
public:
PackageImpl( ::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
Reference<XCommandEnvironment> const &xCmdEnv );
// XPackage
virtual OUString SAL_CALL getDescription() throw (RuntimeException);
};
friend class PackageImpl;
// PackageRegistryBackend
virtual Reference<deployment::XPackage> bindPackage_(
OUString const & url, OUString const & mediaType,
Reference<XCommandEnvironment> const & xCmdEnv );
const Reference<deployment::XPackageTypeInfo> m_xTypeInfo;
public:
BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName );
// XPackageRegistry
virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
getSupportedPackageTypes() throw (RuntimeException);
};
//______________________________________________________________________________
OUString BackendImpl::PackageImpl::getDescription() throw (RuntimeException)
{
if (m_descr.getLength() == 0)
return Package::getDescription();
else
return m_descr;
}
//______________________________________________________________________________
BackendImpl::PackageImpl::PackageImpl(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
Reference<XCommandEnvironment> const &xCmdEnv )
: Package( myBackend.get(), url, OUString(), OUString(),
myBackend->m_xTypeInfo ),
m_descr(libType)
{
initPackageHandler();
sal_Int32 segmEnd = url.getLength();
if (url.getLength() > 0 && url[ url.getLength() - 1 ] == '/')
--segmEnd;
sal_Int32 segmStart = (url.lastIndexOf( '/', segmEnd ) + 1);
if (segmStart < 0)
segmStart = 0;
// name and display name default the same:
m_displayName = ::rtl::Uri::decode(
url.copy( segmStart, segmEnd - segmStart ),
rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
m_name = m_displayName;
OSL_TRACE("PakageImpl displayName is %s",
::rtl::OUStringToOString( m_displayName , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
}
//______________________________________________________________________________
BackendImpl::BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName )
: PackageRegistryBackend( args, xComponentContext, implName ),
m_xTypeInfo( new Package::TypeInfo(
OUSTR("application/vnd.sun.star.framework-script"),
OUString() /* no file filter */,
OUSTR("Scripting Framework Script Library"),
RID_IMG_SCRIPTLIB, RID_IMG_SCRIPTLIB_HC ) )
{
if (! transientMode())
{
/*
if (office_is_running())
{
Reference<XComponentContext> xContext( getComponentContext() );
m_xScriptLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationScriptLibraryContainer"),
xContext ), UNO_QUERY_THROW );
m_xDialogLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationDialogLibraryContainer"),
xContext ), UNO_QUERY_THROW );
}
else
{
OUString basic_path(
m_eContext == CONTEXT_USER
? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":UserInstallation}/user/basic")
: OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":BaseInstallation}/share/basic") );
m_basic_script_libs.reset(
new LibraryContainer(
makeURL( basic_path, OUSTR("script.xlc") ),
getMutex(),
getComponentContext() ) );
m_dialog_libs.reset(
new LibraryContainer(
makeURL( basic_path, OUSTR("dialog.xlc") ),
getMutex(),
getComponentContext() ) );
}
*/
}
}
//==============================================================================
OUString SAL_CALL getImplementationName()
{
return OUSTR("com.sun.star.comp.deployment.sfwk.PackageRegistryBackend");
}
//==============================================================================
Reference<XInterface> SAL_CALL create(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext )
SAL_THROW( (Exception) )
{
return static_cast< ::cppu::OWeakObject * >(
new BackendImpl( args, xComponentContext, getImplementationName() ) );
}
// XPackageRegistry
//______________________________________________________________________________
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
return Sequence< Reference<deployment::XPackageTypeInfo> >(&m_xTypeInfo, 1);
}
// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
OUString const & url, OUString const & mediaType_,
Reference<XCommandEnvironment> const & xCmdEnv )
{
OUString mediaType( mediaType_ );
if (mediaType.getLength() == 0)
{
// detect media-type:
::ucb::Content ucbContent;
if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
ucbContent.isFolder())
{
// probe for script.xlb:
if (create_ucb_content(
0, makeURL( url, OUSTR("parcel-descriptor.xml") ),
xCmdEnv, false /* no throw */ ))
{
mediaType = OUSTR("application/vnd.sun.star.framework-script");
}
}
if (mediaType.getLength() == 0)
throw lang::IllegalArgumentException(
StrCannotDetectMediaType::get() + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
String type, subType;
INetContentTypeParameterList params;
if (INetContentTypes::parse( mediaType, type, subType, ¶ms ))
{
if (type.EqualsIgnoreCaseAscii("application"))
{
if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.framework-script"))
{
OUString sParcelDescURL = makeURL(
url, OUSTR("parcel-descriptor.xml") );
::ucb::Content ucb_content( sParcelDescURL, xCmdEnv );
ParcelDescDocHandler* pHandler =
new ParcelDescDocHandler();
Reference< xml::sax::XDocumentHandler > xDocHandler = pHandler;
Reference<XComponentContext> xContext( getComponentContext() );
Reference< xml::sax::XParser > xParser(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star.xml.sax.Parser"), xContext ),
UNO_QUERY_THROW );
xParser->setDocumentHandler( xDocHandler );
xml::sax::InputSource source;
source.aInputStream = ucb_content.openStream();
source.sSystemId = ucb_content.getURL();
xParser->parseStream( source );
OUString lang;
if ( !pHandler->isParsed() )
{
throw lang::IllegalArgumentException(
StrCannotDetectMediaType::get() + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
lang = pHandler->getParcelLanguage();
OUString sfwkLibType = getResourceString( RID_STR_SFWK_LIB );
// replace %MACRONAME placeholder with language name
OUString MACRONAME( OUSTR("%MACROLANG" ) );
sal_Int32 startOfReplace = sfwkLibType.indexOf( MACRONAME );
sal_Int32 charsToReplace = MACRONAME.getLength();
sfwkLibType = sfwkLibType.replaceAt( startOfReplace, charsToReplace, lang );
OSL_TRACE("******************************");
OSL_TRACE(" BackEnd detected lang = %s ",
rtl::OUStringToOString( lang, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE(" for url %s",
rtl::OUStringToOString( source.sSystemId, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE("******************************");
return new PackageImpl( this, url, sfwkLibType, xCmdEnv );
}
}
}
throw lang::IllegalArgumentException(
StrUnsupportedMediaType::get() + mediaType,
static_cast<OWeakObject *>(this),
static_cast<sal_Int16>(-1) );
}
//##############################################################################
void BackendImpl::PackageImpl:: initPackageHandler()
{
if (m_xNameCntrPkgHandler.is())
return;
BackendImpl * that = getMyBackend();
Any aContext;
if ( that->m_eContext == CONTEXT_USER )
{
aContext <<= OUSTR("user");
}
else if ( that->m_eContext == CONTEXT_SHARED )
{
aContext <<= OUSTR("share");
}
else
{
OSL_ASSERT( 0 );
// NOT supported at the momemtn // TODO
}
Reference< provider::XScriptProviderFactory > xFac(
that->getComponentContext()->getValueByName(
OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY );
if ( xFac.is() )
{
Reference< container::XNameContainer > xName( xFac->createScriptProvider( aContext ), UNO_QUERY );
if ( xName.is() )
{
m_xNameCntrPkgHandler.set( xName );
}
}
// TODO what happens if above fails??
}
// Package
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::PackageImpl::isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
return beans::Optional< beans::Ambiguous<sal_Bool> >(
true /* IsPresent */,
beans::Ambiguous<sal_Bool>(
m_xNameCntrPkgHandler.is() && m_xNameCntrPkgHandler->hasByName(
m_url ),
false /* IsAmbiguous */ ) );
}
//______________________________________________________________________________
void BackendImpl::PackageImpl::processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
BackendImpl * that = getMyBackend();
if ( !m_xNameCntrPkgHandler.is() )
{
OSL_TRACE("no package handler!!!!");
throw RuntimeException( OUSTR("No package Handler " ),
Reference< XInterface >() );
}
if (registerPackage)
{
// will throw if it fails
m_xNameCntrPkgHandler->insertByName( m_url, makeAny( Reference< XPackage >(this) ) );
}
else // revokePackage()
{
m_xNameCntrPkgHandler->removeByName( m_url );
}
}
} // namespace sfwk
} // namespace backend
} // namespace dp_registry
<commit_msg>INTEGRATION: CWS pyunofixes1 (1.6.32); FILE MERGED 2005/01/05 15:15:46 toconnor 1.6.32.2: #i37468# fix logic error in previous change Issue number: Submitted by: Reviewed by: 2004/12/21 12:46:34 toconnor 1.6.32.1: #i37468# allow deployment of scripts without parcel-descriptor.xml files Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
*
* $RCSfile: dp_sfwk.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2005-02-11 16:56:33 $
*
* 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 "dp_sfwk.hrc"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_parceldesc.hxx"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "svtools/inettype.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <memory>
using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::script;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
class PackageImpl : public ::dp_registry::backend::Package
{
BackendImpl * getMyBackend() const {
return static_cast<BackendImpl *>(m_myBackend.get());
}
Reference< container::XNameContainer > m_xNameCntrPkgHandler;
OUString m_descr;
void initPackageHandler();
// Package
virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
virtual void processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
public:
PackageImpl( ::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
Reference<XCommandEnvironment> const &xCmdEnv );
// XPackage
virtual OUString SAL_CALL getDescription() throw (RuntimeException);
};
friend class PackageImpl;
// PackageRegistryBackend
virtual Reference<deployment::XPackage> bindPackage_(
OUString const & url, OUString const & mediaType,
Reference<XCommandEnvironment> const & xCmdEnv );
const Reference<deployment::XPackageTypeInfo> m_xTypeInfo;
public:
BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName );
// XPackageRegistry
virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
getSupportedPackageTypes() throw (RuntimeException);
};
//______________________________________________________________________________
OUString BackendImpl::PackageImpl::getDescription() throw (RuntimeException)
{
if (m_descr.getLength() == 0)
return Package::getDescription();
else
return m_descr;
}
//______________________________________________________________________________
BackendImpl::PackageImpl::PackageImpl(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
Reference<XCommandEnvironment> const &xCmdEnv )
: Package( myBackend.get(), url, OUString(), OUString(),
myBackend->m_xTypeInfo ),
m_descr(libType)
{
initPackageHandler();
sal_Int32 segmEnd = url.getLength();
if (url.getLength() > 0 && url[ url.getLength() - 1 ] == '/')
--segmEnd;
sal_Int32 segmStart = (url.lastIndexOf( '/', segmEnd ) + 1);
if (segmStart < 0)
segmStart = 0;
// name and display name default the same:
m_displayName = ::rtl::Uri::decode(
url.copy( segmStart, segmEnd - segmStart ),
rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
m_name = m_displayName;
OSL_TRACE("PakageImpl displayName is %s",
::rtl::OUStringToOString( m_displayName , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
}
//______________________________________________________________________________
BackendImpl::BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName )
: PackageRegistryBackend( args, xComponentContext, implName ),
m_xTypeInfo( new Package::TypeInfo(
OUSTR("application/vnd.sun.star.framework-script"),
OUString() /* no file filter */,
OUSTR("Scripting Framework Script Library"),
RID_IMG_SCRIPTLIB, RID_IMG_SCRIPTLIB_HC ) )
{
if (! transientMode())
{
/*
if (office_is_running())
{
Reference<XComponentContext> xContext( getComponentContext() );
m_xScriptLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationScriptLibraryContainer"),
xContext ), UNO_QUERY_THROW );
m_xDialogLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationDialogLibraryContainer"),
xContext ), UNO_QUERY_THROW );
}
else
{
OUString basic_path(
m_eContext == CONTEXT_USER
? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":UserInstallation}/user/basic")
: OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":BaseInstallation}/share/basic") );
m_basic_script_libs.reset(
new LibraryContainer(
makeURL( basic_path, OUSTR("script.xlc") ),
getMutex(),
getComponentContext() ) );
m_dialog_libs.reset(
new LibraryContainer(
makeURL( basic_path, OUSTR("dialog.xlc") ),
getMutex(),
getComponentContext() ) );
}
*/
}
}
//==============================================================================
OUString SAL_CALL getImplementationName()
{
return OUSTR("com.sun.star.comp.deployment.sfwk.PackageRegistryBackend");
}
//==============================================================================
Reference<XInterface> SAL_CALL create(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext )
SAL_THROW( (Exception) )
{
return static_cast< ::cppu::OWeakObject * >(
new BackendImpl( args, xComponentContext, getImplementationName() ) );
}
// XPackageRegistry
//______________________________________________________________________________
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
return Sequence< Reference<deployment::XPackageTypeInfo> >(&m_xTypeInfo, 1);
}
// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
OUString const & url, OUString const & mediaType_,
Reference<XCommandEnvironment> const & xCmdEnv )
{
OUString mediaType( mediaType_ );
if (mediaType.getLength() == 0)
{
// detect media-type:
::ucb::Content ucbContent;
if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
ucbContent.isFolder())
{
// probe for parcel-descriptor.xml:
if (create_ucb_content(
0, makeURL( url, OUSTR("parcel-descriptor.xml") ),
xCmdEnv, false /* no throw */ ))
{
mediaType = OUSTR("application/vnd.sun.star.framework-script");
}
}
if (mediaType.getLength() == 0)
throw lang::IllegalArgumentException(
StrCannotDetectMediaType::get() + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
String type, subType;
INetContentTypeParameterList params;
if (INetContentTypes::parse( mediaType, type, subType, ¶ms ))
{
if (type.EqualsIgnoreCaseAscii("application"))
{
if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.framework-script"))
{
OUString lang = OUString::createFromAscii("Script");
OUString sParcelDescURL = makeURL(
url, OUSTR("parcel-descriptor.xml") );
::ucb::Content ucb_content;
if (create_ucb_content( &ucb_content, sParcelDescURL,
xCmdEnv, false /* no throw */ ))
{
ParcelDescDocHandler* pHandler =
new ParcelDescDocHandler();
Reference< xml::sax::XDocumentHandler >
xDocHandler = pHandler;
Reference<XComponentContext>
xContext( getComponentContext() );
Reference< xml::sax::XParser > xParser(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star.xml.sax.Parser"), xContext ),
UNO_QUERY_THROW );
xParser->setDocumentHandler( xDocHandler );
xml::sax::InputSource source;
source.aInputStream = ucb_content.openStream();
source.sSystemId = ucb_content.getURL();
xParser->parseStream( source );
if ( pHandler->isParsed() )
{
lang = pHandler->getParcelLanguage();
}
}
OUString sfwkLibType = getResourceString( RID_STR_SFWK_LIB );
// replace %MACRONAME placeholder with language name
OUString MACRONAME( OUSTR("%MACROLANG" ) );
sal_Int32 startOfReplace = sfwkLibType.indexOf( MACRONAME );
sal_Int32 charsToReplace = MACRONAME.getLength();
sfwkLibType = sfwkLibType.replaceAt( startOfReplace, charsToReplace, lang );
OSL_TRACE("******************************");
OSL_TRACE(" BackEnd detected lang = %s ",
rtl::OUStringToOString( lang, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE(" for url %s",
rtl::OUStringToOString( sParcelDescURL, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE("******************************");
return new PackageImpl( this, url, sfwkLibType, xCmdEnv );
}
}
}
throw lang::IllegalArgumentException(
StrUnsupportedMediaType::get() + mediaType,
static_cast<OWeakObject *>(this),
static_cast<sal_Int16>(-1) );
}
//##############################################################################
void BackendImpl::PackageImpl:: initPackageHandler()
{
if (m_xNameCntrPkgHandler.is())
return;
BackendImpl * that = getMyBackend();
Any aContext;
if ( that->m_eContext == CONTEXT_USER )
{
aContext <<= OUSTR("user");
}
else if ( that->m_eContext == CONTEXT_SHARED )
{
aContext <<= OUSTR("share");
}
else
{
OSL_ASSERT( 0 );
// NOT supported at the momemtn // TODO
}
Reference< provider::XScriptProviderFactory > xFac(
that->getComponentContext()->getValueByName(
OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY );
if ( xFac.is() )
{
Reference< container::XNameContainer > xName( xFac->createScriptProvider( aContext ), UNO_QUERY );
if ( xName.is() )
{
m_xNameCntrPkgHandler.set( xName );
}
}
// TODO what happens if above fails??
}
// Package
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::PackageImpl::isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
return beans::Optional< beans::Ambiguous<sal_Bool> >(
true /* IsPresent */,
beans::Ambiguous<sal_Bool>(
m_xNameCntrPkgHandler.is() && m_xNameCntrPkgHandler->hasByName(
m_url ),
false /* IsAmbiguous */ ) );
}
//______________________________________________________________________________
void BackendImpl::PackageImpl::processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
BackendImpl * that = getMyBackend();
if ( !m_xNameCntrPkgHandler.is() )
{
OSL_TRACE("no package handler!!!!");
throw RuntimeException( OUSTR("No package Handler " ),
Reference< XInterface >() );
}
if (registerPackage)
{
// will throw if it fails
m_xNameCntrPkgHandler->insertByName( m_url, makeAny( Reference< XPackage >(this) ) );
}
else // revokePackage()
{
m_xNameCntrPkgHandler->removeByName( m_url );
}
}
} // namespace sfwk
} // namespace backend
} // namespace dp_registry
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dp_sfwk.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-09-08 16:50:37 $
*
* 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 "dp_sfwk.hrc"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_parceldesc.hxx"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "svtools/inettype.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <drafts/com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <memory>
using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::drafts::com::sun::star::script;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
private:
OUString m_sCtx; //TODO needs an accessor or needs to be passed as part of create for Package
protected:
// PackageRegistryBackend
virtual Reference<deployment::XPackage> bindPackage_(
OUString const & url, OUString const & mediaType,
Reference<XCommandEnvironment> const & xCmdEnv );
public:
BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName,
Sequence<OUString> const & supportedMediaTypes );
OUString getCtx() { return m_sCtx; }
};
//==============================================================================
class PackageImpl : public ::dp_registry::backend::Package
{
protected:
Reference< container::XNameContainer > m_xNameCntrPkgHandler;
inline BackendImpl * getMyBackend() const
{ return static_cast<BackendImpl *>(m_myBackend.get()); }
void initPackageHandler();
// Package
virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
virtual void processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
inline PackageImpl(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
OUString const & mediaType )
: Package( myBackend.get(), url, mediaType,
OUString(), OUString(), // will be late-initialized
OUString( libType ) )
{ initPackageHandler(); }
public:
static PackageImpl * create(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url,
OUString const & mediaType,
Reference<XCommandEnvironment> const &xCmdEnv, OUString const & libType );
// XPackage
virtual Any SAL_CALL getIcon( sal_Bool highContrast, sal_Bool smallIcon )
throw (RuntimeException);
};
//______________________________________________________________________________
PackageImpl * PackageImpl::create(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url,
OUString const & mediaType,
Reference<XCommandEnvironment> const &xCmdEnv,
OUString const & libType )
{
::std::auto_ptr<PackageImpl> ret(
new PackageImpl( myBackend, url, libType, mediaType ) );
// name, displayName:
// name and display name default the same
ret->m_displayName = url.copy( url.lastIndexOf( '/' ) + 1 );
ret->m_name = ret->m_displayName;
OSL_TRACE("PakageImpl displayName is %s",
::rtl::OUStringToOString( ret->m_displayName , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
return ret.release();
}
//______________________________________________________________________________
BackendImpl::BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName,
Sequence<OUString> const & supportedMediaTypes )
: PackageRegistryBackend(
args, xComponentContext, implName, supportedMediaTypes )
{
if (! transientMode())
{
/*
if (office_is_running())
{
Reference<XComponentContext> xContext( getComponentContext() );
m_xScriptLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationScriptLibraryContainer"),
xContext ), UNO_QUERY_THROW );
m_xDialogLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationDialogLibraryContainer"),
xContext ), UNO_QUERY_THROW );
}
else
{
OUString basic_path(
m_eContext == CONTEXT_USER
? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":UserInstallation}/user/basic")
: OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":BaseInstallation}/share/basic") );
m_basic_script_libs.reset(
new LibraryContainer(
make_url( basic_path, OUSTR("/script.xlc") ),
getMutex(),
getComponentContext() ) );
m_dialog_libs.reset(
new LibraryContainer(
make_url( basic_path, OUSTR("/dialog.xlc") ),
getMutex(),
getComponentContext() ) );
}
*/
OUString ctx(
m_eContext == CONTEXT_USER
? OUSTR("user") : OUSTR("share") );
m_sCtx = ctx;
}
}
//==============================================================================
OUString SAL_CALL getImplementationName()
{
return OUSTR("com.sun.star.comp.deployment.sfwk.PackageRegistryBackend");
}
//==============================================================================
Reference<XInterface> SAL_CALL create(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext )
SAL_THROW( (Exception) )
{
OUString const mediaTypes [] = {
OUSTR("application/vnd.sun.star.framework-script")
};
return static_cast< ::cppu::OWeakObject * >(
new BackendImpl(
args, xComponentContext, getImplementationName(),
Sequence<OUString >( mediaTypes, ARLEN(mediaTypes) ) ) );
}
// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
OUString const & url, OUString const & mediaType_,
Reference<XCommandEnvironment> const & xCmdEnv )
{
OUString mediaType( mediaType_ );
if (mediaType.getLength() == 0)
{
// detect media-type:
::ucb::Content ucbContent;
if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
ucbContent.isFolder())
{
// probe for script.xlb:
if (create_ucb_content(
0, make_url( url, OUSTR("parcel-descriptor.xml") ),
xCmdEnv, false /* no throw */ ))
{
mediaType = OUSTR("application/vnd.sun.star.framework-script");
}
}
if (mediaType.getLength() == 0)
throw lang::IllegalArgumentException(
m_strCannotDetectMediaType + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
String type, subType;
INetContentTypeParameterList params;
if (INetContentTypes::parse( mediaType, type, subType, ¶ms ))
{
if (type.EqualsIgnoreCaseAscii("application"))
{
if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.framework-script"))
{
OUString sParcelDescURL = make_url( url, OUSTR("parcel-descriptor.xml") );
::ucb::Content ucb_content( sParcelDescURL, xCmdEnv );
ParcelDescDocHandler* pHandler =
new ParcelDescDocHandler();
Reference< xml::sax::XDocumentHandler > xDocHandler = pHandler;
Reference<XComponentContext> xContext( getComponentContext() );
Reference< xml::sax::XParser > xParser(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star.xml.sax.Parser"), xContext ),
UNO_QUERY_THROW );
xParser->setDocumentHandler( xDocHandler );
xml::sax::InputSource source;
source.aInputStream = ucb_content.openStream();
source.sSystemId = ucb_content.getURL();
xParser->parseStream( source );
OUString lang;
if ( !pHandler->isParsed() )
{
throw lang::IllegalArgumentException(
m_strCannotDetectMediaType + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
lang = pHandler->getParcelLanguage();
OUString sfwkLibType = getResourceString( RID_STR_SFWK_LIB );
// replace %MACRONAME placeholder with language name
OUString MACRONAME( OUSTR("%MACROLANG" ) );
sal_Int32 startOfReplace = sfwkLibType.indexOf( MACRONAME );
sal_Int32 charsToReplace = MACRONAME.getLength();
sfwkLibType = sfwkLibType.replaceAt( startOfReplace, charsToReplace, lang );
OSL_TRACE("******************************");
OSL_TRACE(" BackEnd detected lang = %s ",
rtl::OUStringToOString( lang, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE(" for url %s",
rtl::OUStringToOString( source.sSystemId, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE("******************************");
return PackageImpl::create(
this, url, mediaType, xCmdEnv, sfwkLibType );
}
}
}
throw lang::IllegalArgumentException(
m_strUnsupportedMediaType + mediaType,
static_cast<OWeakObject *>(this),
static_cast<sal_Int16>(-1) );
}
//##############################################################################
// XPackage
//______________________________________________________________________________
void PackageImpl:: initPackageHandler()
{
BackendImpl * that = getMyBackend();
Any aContext;
if ( that->getCtx().equals( OUSTR("user") ) )
{
aContext <<= OUSTR("user");
}
else if ( that->getCtx().equals( OUSTR( "share" ) ) )
{
aContext <<= OUSTR("share");
}
else
{
// NOT supported at the momemtn // TODO
}
Reference< provider::XScriptProviderFactory > xFac(
that->getComponentContext()->getValueByName(
OUSTR( "/singletons/drafts.com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY );
if ( xFac.is() )
{
Reference< container::XNameContainer > xName( xFac->createScriptProvider( aContext ), UNO_QUERY );
if ( xName.is() )
{
m_xNameCntrPkgHandler.set( xName );
}
}
// TODO what happens if above fails??
}
Any PackageImpl::getIcon( sal_Bool highContrast, sal_Bool smallIcon )
throw (RuntimeException)
{
OSL_ASSERT( smallIcon );
if (smallIcon)
{
sal_uInt16 ret = highContrast ? RID_IMG_SCRIPTLIB_HC : RID_IMG_SCRIPTLIB;
return makeAny(ret);
}
return Package::getIcon( highContrast, smallIcon );
}
// Package
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> > PackageImpl::isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
return beans::Optional< beans::Ambiguous<sal_Bool> >(
true /* IsPresent */,
beans::Ambiguous<sal_Bool>(
m_xNameCntrPkgHandler.is() && m_xNameCntrPkgHandler->hasByName(
m_url ),
false /* IsAmbiguous */ ) );
}
//______________________________________________________________________________
void PackageImpl::processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
BackendImpl * that = getMyBackend();
if ( !m_xNameCntrPkgHandler.is() )
{
OSL_TRACE("no package handler!!!!");
throw RuntimeException( OUSTR("No package Handler " ),
Reference< XInterface >() );
}
if (registerPackage)
{
// will throw if it fails
m_xNameCntrPkgHandler->insertByName( m_url, makeAny( Reference< XPackage >(this) ) );
}
else // revokePackage()
{
m_xNameCntrPkgHandler->removeByName( m_url );
}
}
} // namespace sfwk
} // namespace backend
} // namespace dp_registry
<commit_msg>INTEGRATION: CWS scriptingf6 (1.2.6); FILE MERGED 2004/10/11 15:27:07 toconnor 1.2.6.2: RESYNC: (1.2-1.4); FILE MERGED 2004/08/04 11:50:16 dfoster 1.2.6.1: #i32502#<commit_after>/*************************************************************************
*
* $RCSfile: dp_sfwk.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-10-22 14:43: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 "dp_sfwk.hrc"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "dp_parceldesc.hxx"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "svtools/inettype.hxx"
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <memory>
using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::script;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
private:
OUString m_sCtx; //TODO needs an accessor or needs to be passed as part of create for Package
protected:
// PackageRegistryBackend
virtual Reference<deployment::XPackage> bindPackage_(
OUString const & url, OUString const & mediaType,
Reference<XCommandEnvironment> const & xCmdEnv );
public:
BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName,
Sequence<OUString> const & supportedMediaTypes );
OUString getCtx() { return m_sCtx; }
};
//==============================================================================
class PackageImpl : public ::dp_registry::backend::Package
{
protected:
Reference< container::XNameContainer > m_xNameCntrPkgHandler;
inline BackendImpl * getMyBackend() const
{ return static_cast<BackendImpl *>(m_myBackend.get()); }
void initPackageHandler();
// Package
virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
virtual void processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv );
inline PackageImpl(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url, OUString const & libType,
OUString const & mediaType )
: Package( myBackend.get(), url, mediaType,
OUString(), OUString(), // will be late-initialized
OUString( libType ) )
{ initPackageHandler(); }
public:
static PackageImpl * create(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url,
OUString const & mediaType,
Reference<XCommandEnvironment> const &xCmdEnv, OUString const & libType );
// XPackage
virtual Any SAL_CALL getIcon( sal_Bool highContrast, sal_Bool smallIcon )
throw (RuntimeException);
};
//______________________________________________________________________________
PackageImpl * PackageImpl::create(
::rtl::Reference<BackendImpl> const & myBackend,
OUString const & url,
OUString const & mediaType,
Reference<XCommandEnvironment> const &xCmdEnv,
OUString const & libType )
{
::std::auto_ptr<PackageImpl> ret(
new PackageImpl( myBackend, url, libType, mediaType ) );
// name, displayName:
// name and display name default the same
ret->m_displayName = url.copy( url.lastIndexOf( '/' ) + 1 );
ret->m_name = ret->m_displayName;
OSL_TRACE("PakageImpl displayName is %s",
::rtl::OUStringToOString( ret->m_displayName , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
return ret.release();
}
//______________________________________________________________________________
BackendImpl::BackendImpl(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext,
OUString const & implName,
Sequence<OUString> const & supportedMediaTypes )
: PackageRegistryBackend(
args, xComponentContext, implName, supportedMediaTypes )
{
if (! transientMode())
{
/*
if (office_is_running())
{
Reference<XComponentContext> xContext( getComponentContext() );
m_xScriptLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationScriptLibraryContainer"),
xContext ), UNO_QUERY_THROW );
m_xDialogLibs.set(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star."
"script.ApplicationDialogLibraryContainer"),
xContext ), UNO_QUERY_THROW );
}
else
{
OUString basic_path(
m_eContext == CONTEXT_USER
? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":UserInstallation}/user/basic")
: OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
SAL_CONFIGFILE("bootstrap")
":BaseInstallation}/share/basic") );
m_basic_script_libs.reset(
new LibraryContainer(
make_url( basic_path, OUSTR("/script.xlc") ),
getMutex(),
getComponentContext() ) );
m_dialog_libs.reset(
new LibraryContainer(
make_url( basic_path, OUSTR("/dialog.xlc") ),
getMutex(),
getComponentContext() ) );
}
*/
OUString ctx(
m_eContext == CONTEXT_USER
? OUSTR("user") : OUSTR("share") );
m_sCtx = ctx;
}
}
//==============================================================================
OUString SAL_CALL getImplementationName()
{
return OUSTR("com.sun.star.comp.deployment.sfwk.PackageRegistryBackend");
}
//==============================================================================
Reference<XInterface> SAL_CALL create(
Sequence<Any> const & args,
Reference<XComponentContext> const & xComponentContext )
SAL_THROW( (Exception) )
{
OUString const mediaTypes [] = {
OUSTR("application/vnd.sun.star.framework-script")
};
return static_cast< ::cppu::OWeakObject * >(
new BackendImpl(
args, xComponentContext, getImplementationName(),
Sequence<OUString >( mediaTypes, ARLEN(mediaTypes) ) ) );
}
// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
OUString const & url, OUString const & mediaType_,
Reference<XCommandEnvironment> const & xCmdEnv )
{
OUString mediaType( mediaType_ );
if (mediaType.getLength() == 0)
{
// detect media-type:
::ucb::Content ucbContent;
if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
ucbContent.isFolder())
{
// probe for script.xlb:
if (create_ucb_content(
0, make_url( url, OUSTR("parcel-descriptor.xml") ),
xCmdEnv, false /* no throw */ ))
{
mediaType = OUSTR("application/vnd.sun.star.framework-script");
}
}
if (mediaType.getLength() == 0)
throw lang::IllegalArgumentException(
m_strCannotDetectMediaType + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
String type, subType;
INetContentTypeParameterList params;
if (INetContentTypes::parse( mediaType, type, subType, ¶ms ))
{
if (type.EqualsIgnoreCaseAscii("application"))
{
if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.framework-script"))
{
OUString sParcelDescURL = make_url( url, OUSTR("parcel-descriptor.xml") );
::ucb::Content ucb_content( sParcelDescURL, xCmdEnv );
ParcelDescDocHandler* pHandler =
new ParcelDescDocHandler();
Reference< xml::sax::XDocumentHandler > xDocHandler = pHandler;
Reference<XComponentContext> xContext( getComponentContext() );
Reference< xml::sax::XParser > xParser(
xContext->getServiceManager()->createInstanceWithContext(
OUSTR("com.sun.star.xml.sax.Parser"), xContext ),
UNO_QUERY_THROW );
xParser->setDocumentHandler( xDocHandler );
xml::sax::InputSource source;
source.aInputStream = ucb_content.openStream();
source.sSystemId = ucb_content.getURL();
xParser->parseStream( source );
OUString lang;
if ( !pHandler->isParsed() )
{
throw lang::IllegalArgumentException(
m_strCannotDetectMediaType + url,
static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
}
lang = pHandler->getParcelLanguage();
OUString sfwkLibType = getResourceString( RID_STR_SFWK_LIB );
// replace %MACRONAME placeholder with language name
OUString MACRONAME( OUSTR("%MACROLANG" ) );
sal_Int32 startOfReplace = sfwkLibType.indexOf( MACRONAME );
sal_Int32 charsToReplace = MACRONAME.getLength();
sfwkLibType = sfwkLibType.replaceAt( startOfReplace, charsToReplace, lang );
OSL_TRACE("******************************");
OSL_TRACE(" BackEnd detected lang = %s ",
rtl::OUStringToOString( lang, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE(" for url %s",
rtl::OUStringToOString( source.sSystemId, RTL_TEXTENCODING_ASCII_US ).getStr() );
OSL_TRACE("******************************");
return PackageImpl::create(
this, url, mediaType, xCmdEnv, sfwkLibType );
}
}
}
throw lang::IllegalArgumentException(
m_strUnsupportedMediaType + mediaType,
static_cast<OWeakObject *>(this),
static_cast<sal_Int16>(-1) );
}
//##############################################################################
// XPackage
//______________________________________________________________________________
void PackageImpl:: initPackageHandler()
{
BackendImpl * that = getMyBackend();
Any aContext;
if ( that->getCtx().equals( OUSTR("user") ) )
{
aContext <<= OUSTR("user");
}
else if ( that->getCtx().equals( OUSTR( "share" ) ) )
{
aContext <<= OUSTR("share");
}
else
{
// NOT supported at the momemtn // TODO
}
Reference< provider::XScriptProviderFactory > xFac(
that->getComponentContext()->getValueByName(
OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY );
if ( xFac.is() )
{
Reference< container::XNameContainer > xName( xFac->createScriptProvider( aContext ), UNO_QUERY );
if ( xName.is() )
{
m_xNameCntrPkgHandler.set( xName );
}
}
// TODO what happens if above fails??
}
Any PackageImpl::getIcon( sal_Bool highContrast, sal_Bool smallIcon )
throw (RuntimeException)
{
OSL_ASSERT( smallIcon );
if (smallIcon)
{
sal_uInt16 ret = highContrast ? RID_IMG_SCRIPTLIB_HC : RID_IMG_SCRIPTLIB;
return makeAny(ret);
}
return Package::getIcon( highContrast, smallIcon );
}
// Package
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> > PackageImpl::isRegistered_(
::osl::ResettableMutexGuard & guard,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
return beans::Optional< beans::Ambiguous<sal_Bool> >(
true /* IsPresent */,
beans::Ambiguous<sal_Bool>(
m_xNameCntrPkgHandler.is() && m_xNameCntrPkgHandler->hasByName(
m_url ),
false /* IsAmbiguous */ ) );
}
//______________________________________________________________________________
void PackageImpl::processPackage_(
::osl::ResettableMutexGuard & guard,
bool registerPackage,
::rtl::Reference<AbortChannel> const & abortChannel,
Reference<XCommandEnvironment> const & xCmdEnv )
{
BackendImpl * that = getMyBackend();
if ( !m_xNameCntrPkgHandler.is() )
{
OSL_TRACE("no package handler!!!!");
throw RuntimeException( OUSTR("No package Handler " ),
Reference< XInterface >() );
}
if (registerPackage)
{
// will throw if it fails
m_xNameCntrPkgHandler->insertByName( m_url, makeAny( Reference< XPackage >(this) ) );
}
else // revokePackage()
{
m_xNameCntrPkgHandler->removeByName( m_url );
}
}
} // namespace sfwk
} // namespace backend
} // namespace dp_registry
<|endoftext|>
|
<commit_before>//
// Created by monty on 30/07/16.
//
#include <map>
#include <memory>
#include <functional>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using sg14::fixed_point;
using eastl::vector;
using eastl::array;
#include "NativeBitmap.h"
#include "ETextures.h"
#include "IFileLoaderDelegate.h"
#include "NativeBitmap.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "VisibilityStrategy.h"
namespace odb {
const bool kNarrowByDistance = true;
const bool kConservativeOccluders = false;
bool VisibilityStrategy::isValid(const Knights::Vec2i& pos) {
return 0 <= pos.x && pos.x < Knights::kMapSize && 0 <= pos.y && pos.y < Knights::kMapSize;
}
bool VisibilityStrategy::isBlock(const IntMap& occluders, const Knights::Vec2i& transformed) {
auto tile = occluders[ transformed.y][transformed.x];
std::string occluderString = "";
if (kConservativeOccluders ) {
occluderString = "1IYXR";
} else {
occluderString = "1IYXR\\/SZ|%<>";
}
for (const auto& candidate : occluderString ) {
if (candidate == tile) {
return true;
}
}
return false;
}
void VisibilityStrategy::castVisibility(VisMap &visMap, const IntMap &occluders, const Knights::Vec2i& pos, Knights::EDirection direction, bool cleanPrevious, DistanceDistribution& distances) {
if ( cleanPrevious ) {
for (auto &line : visMap) {
std::fill(std::begin(line), std::end(line), EVisibility::kInvisible);
}
}
for ( auto& distanceLine : distances ) {
distanceLine.clear();
}
castVisibility(direction, visMap, occluders, transform( direction, pos ), distances);
}
bool VisibilityStrategy::isVisibleAt(const VisMap& visMap, const Knights::Vec2i& transformed ) {
return visMap[ transformed.y ][ transformed.x ] == EVisibility::kVisible;
}
void VisibilityStrategy::setIsVisible(VisMap& visMap, const Knights::Vec2i& transformed ) {
visMap[ transformed.y ][ transformed.x ] = EVisibility::kVisible;
}
Knights::Vec2i VisibilityStrategy::transform( Knights::EDirection from, const Knights::Vec2i& currentPos ) {
switch( from ) {
case Knights::EDirection::kNorth:
return currentPos;
case Knights::EDirection::kSouth:
return { Knights::kMapSize - currentPos.x - 1, Knights::kMapSize - currentPos.y - 1};
case Knights::EDirection::kEast:
return { Knights::kMapSize - currentPos.y - 1, Knights::kMapSize - currentPos.x - 1};
case Knights::EDirection::kWest:
return { currentPos.y, currentPos.x};
}
}
void VisibilityStrategy::castVisibility(Knights::EDirection from, VisMap &visMap, const IntMap &occluders,
const Knights::Vec2i& originalPos, DistanceDistribution& distances) {
array<Knights::Vec2i, Knights::kMapSize + Knights::kMapSize> positions;
Knights::Vec2i currentPos;
//The -1 is due to the fact I will add a new element.
auto stackEnd = std::end( positions ) - 1;
auto stackHead = std::begin(positions);
auto stackRoot = stackHead;
auto rightOffset = Knights::mapOffsetForDirection(Knights::EDirection::kEast);
auto leftOffset = Knights::mapOffsetForDirection(Knights::EDirection::kWest);
auto northOffset = Knights::mapOffsetForDirection(Knights::EDirection::kNorth);
*stackHead = originalPos;
++stackHead;
while (stackHead != stackRoot ) {
--stackHead;
currentPos = *stackHead;
auto transformed = transform( from, currentPos);
if (!isValid(transformed)) {
continue;
}
if ( isVisibleAt( visMap, transformed ) ) {
continue;
}
setIsVisible( visMap, transformed );
int verticalDistance = ( currentPos.y - originalPos.y );
int manhattanDistance = std::abs( verticalDistance ) + std::abs( currentPos.x - originalPos.x );
distances[ manhattanDistance ].push_back( transformed );
if (isBlock(occluders, transformed )) {
continue;
}
int narrowing = kNarrowByDistance ? std::abs(verticalDistance) : 1;
if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) >= -narrowing )&& ( currentPos.x - originalPos.x ) <= 0 && (stackHead != stackEnd ) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + leftOffset.x, currentPos.y + leftOffset.y};
}
if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) <= narrowing ) && ( currentPos.x - originalPos.x ) >= 0 && (stackHead != stackEnd ) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + rightOffset.x, currentPos.y + rightOffset.y};
}
if ( verticalDistance <= 0 && (stackHead != stackEnd) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + northOffset.x, currentPos.y + northOffset.y};
}
}
}
}
<commit_msg>Allow capping the draw distance<commit_after>//
// Created by monty on 30/07/16.
//
#include <map>
#include <memory>
#include <functional>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using sg14::fixed_point;
using eastl::vector;
using eastl::array;
#include "NativeBitmap.h"
#include "ETextures.h"
#include "IFileLoaderDelegate.h"
#include "NativeBitmap.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "VisibilityStrategy.h"
namespace odb {
const bool kNarrowByDistance = true;
const bool kConservativeOccluders = false;
const int kUseLimitedDrawingDistance = false;
const int kDrawingDistance = 20;
bool VisibilityStrategy::isValid(const Knights::Vec2i& pos) {
return 0 <= pos.x && pos.x < Knights::kMapSize && 0 <= pos.y && pos.y < Knights::kMapSize;
}
bool VisibilityStrategy::isBlock(const IntMap& occluders, const Knights::Vec2i& transformed) {
auto tile = occluders[ transformed.y][transformed.x];
std::string occluderString = "";
if (kConservativeOccluders ) {
occluderString = "1IYXR";
} else {
occluderString = "1IYXR\\/SZ|%<>";
}
for (const auto& candidate : occluderString ) {
if (candidate == tile) {
return true;
}
}
return false;
}
void VisibilityStrategy::castVisibility(VisMap &visMap, const IntMap &occluders, const Knights::Vec2i& pos, Knights::EDirection direction, bool cleanPrevious, DistanceDistribution& distances) {
if ( cleanPrevious ) {
for (auto &line : visMap) {
std::fill(std::begin(line), std::end(line), EVisibility::kInvisible);
}
}
for ( auto& distanceLine : distances ) {
distanceLine.clear();
}
castVisibility(direction, visMap, occluders, transform( direction, pos ), distances);
}
bool VisibilityStrategy::isVisibleAt(const VisMap& visMap, const Knights::Vec2i& transformed ) {
return visMap[ transformed.y ][ transformed.x ] == EVisibility::kVisible;
}
void VisibilityStrategy::setIsVisible(VisMap& visMap, const Knights::Vec2i& transformed ) {
visMap[ transformed.y ][ transformed.x ] = EVisibility::kVisible;
}
Knights::Vec2i VisibilityStrategy::transform( Knights::EDirection from, const Knights::Vec2i& currentPos ) {
switch( from ) {
case Knights::EDirection::kNorth:
return currentPos;
case Knights::EDirection::kSouth:
return { Knights::kMapSize - currentPos.x - 1, Knights::kMapSize - currentPos.y - 1};
case Knights::EDirection::kEast:
return { Knights::kMapSize - currentPos.y - 1, Knights::kMapSize - currentPos.x - 1};
case Knights::EDirection::kWest:
return { currentPos.y, currentPos.x};
}
}
void VisibilityStrategy::castVisibility(Knights::EDirection from, VisMap &visMap, const IntMap &occluders,
const Knights::Vec2i& originalPos, DistanceDistribution& distances) {
array<Knights::Vec2i, Knights::kMapSize + Knights::kMapSize> positions;
Knights::Vec2i currentPos;
//The -1 is due to the fact I will add a new element.
auto stackEnd = std::end( positions ) - 1;
auto stackHead = std::begin(positions);
auto stackRoot = stackHead;
auto rightOffset = Knights::mapOffsetForDirection(Knights::EDirection::kEast);
auto leftOffset = Knights::mapOffsetForDirection(Knights::EDirection::kWest);
auto northOffset = Knights::mapOffsetForDirection(Knights::EDirection::kNorth);
*stackHead = originalPos;
++stackHead;
while (stackHead != stackRoot ) {
--stackHead;
currentPos = *stackHead;
auto transformed = transform( from, currentPos);
if (!isValid(transformed)) {
continue;
}
if ( isVisibleAt( visMap, transformed ) ) {
continue;
}
setIsVisible( visMap, transformed );
int verticalDistance = ( currentPos.y - originalPos.y );
if (kUseLimitedDrawingDistance ) {
if (std::abs(verticalDistance) > kDrawingDistance) {
continue;
}
}
int manhattanDistance = std::abs( verticalDistance ) + std::abs( currentPos.x - originalPos.x );
distances[ manhattanDistance ].push_back( transformed );
if (isBlock(occluders, transformed )) {
continue;
}
int narrowing = kNarrowByDistance ? std::abs(verticalDistance) : 1;
if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) >= -narrowing )&& ( currentPos.x - originalPos.x ) <= 0 && (stackHead != stackEnd ) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + leftOffset.x, currentPos.y + leftOffset.y};
}
if ( ( !kNarrowByDistance || ( currentPos.x - originalPos.x ) <= narrowing ) && ( currentPos.x - originalPos.x ) >= 0 && (stackHead != stackEnd ) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + rightOffset.x, currentPos.y + rightOffset.y};
}
if ( verticalDistance <= 0 && (stackHead != stackEnd) ) {
*stackHead++ = Knights::Vec2i{currentPos.x + northOffset.x, currentPos.y + northOffset.y};
}
}
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistanceMetric.h"
#include <fstream>
int itkKdTreeTest1(int argc , char * argv [] )
{
if( argc < 4 )
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " numberOfDataPoints numberOfTestPoints bucketSize [graphvizDotOutputFile]" << std::endl;
return EXIT_FAILURE;
}
// Random number generator
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;
NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
randomNumberGenerator->Initialize();
typedef itk::Array< double > MeasurementVectorType;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType;
const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;
SampleType::Pointer sample = SampleType::New();
sample->SetMeasurementVectorSize( measurementVectorSize );
//
// Generate a sample of random points
//
const unsigned int numberOfDataPoints = atoi( argv[1] );
MeasurementVectorType mv( measurementVectorSize );
for (unsigned int i = 0; i < numberOfDataPoints; ++i )
{
mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
sample->PushBack( mv );
std::cout << "Add measurement vector: " << mv << std::endl;
}
typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType;
TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();
const unsigned int bucketSize = atoi( argv[3] );
treeGenerator->SetSample( sample );
treeGenerator->SetBucketSize( bucketSize );
treeGenerator->Update();
typedef TreeGeneratorType::KdTreeType TreeType;
typedef TreeType::NearestNeighbors NeighborsType;
typedef TreeType::KdTreeNodeType NodeType;
TreeType::Pointer tree = treeGenerator->GetOutput();
MeasurementVectorType queryPoint( measurementVectorSize );
unsigned int numberOfNeighbors = 1;
TreeType::InstanceIdentifierVectorType neighbors;
MeasurementVectorType result( measurementVectorSize );
MeasurementVectorType test_point( measurementVectorSize );
MeasurementVectorType min_point( measurementVectorSize );
unsigned int numberOfFailedPoints1 = 0;
const unsigned int numberOfTestPoints = atoi( argv[2] );
//
// Check that for every point in the sample, its closest point is itself.
//
typedef itk::Statistics::EuclideanDistanceMetric< MeasurementVectorType > DistanceMetricType;
typedef DistanceMetricType::OriginType OriginType;
DistanceMetricType::Pointer distanceMetric = DistanceMetricType::New();
OriginType origin( measurementVectorSize );
for( unsigned int k = 0; k < sample->Size(); k++ )
{
queryPoint = sample->GetMeasurementVector(k);
for ( unsigned int i = 0; i < sample->GetMeasurementVectorSize(); ++i )
{
origin[i] = queryPoint[i];
}
distanceMetric->SetOrigin( origin );
tree->Search( queryPoint, numberOfNeighbors, neighbors );
for ( unsigned int i = 0; i < numberOfNeighbors; ++i )
{
const double distance =
distanceMetric->Evaluate( tree->GetMeasurementVector( neighbors[i] ));
if( distance > vnl_math::eps )
{
std::cerr << "kd-tree knn search result:" << std::endl
<< "query point = [" << queryPoint << "]" << std::endl
<< "k = " << numberOfNeighbors << std::endl;
std::cerr << "measurement vector : distance" << std::endl;
std::cerr << "[" << tree->GetMeasurementVector( neighbors[i] )
<< "] : "
<< distance << std::endl;
numberOfFailedPoints1++;
}
}
}
unsigned int numberOfFailedPoints2 = 0;
//
// Generate a second sample of random points
// and use them to query the tree
//
for (unsigned int j = 0; j < numberOfTestPoints; ++j )
{
double min_dist = itk::NumericTraits< double >::max();
queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
tree->Search( queryPoint, numberOfNeighbors, neighbors );
//
// The first neighbor should be the closest point.
//
result = tree->GetMeasurementVector( neighbors[0] );
//
// Compute the distance to the "presumed" nearest neighbor
//
double result_dist = vcl_sqrt(
(result[0] - queryPoint[0]) *
(result[0] - queryPoint[0]) +
(result[1] - queryPoint[1]) *
(result[1] - queryPoint[1])
);
//
// Compute the distance to all other points, to verify
// whether the first neighbor was the closest one or not.
//
for( unsigned int i = 0; i < numberOfDataPoints; ++i )
{
test_point = tree->GetMeasurementVector( i );
const double dist = vcl_sqrt(
(test_point[0] - queryPoint[0]) *
(test_point[0] - queryPoint[0]) +
(test_point[1] - queryPoint[1]) *
(test_point[1] - queryPoint[1])
);
if( dist < min_dist )
{
min_dist = dist;
min_point = test_point;
}
}
if( min_dist < result_dist )
{
std::cerr << "Problem found " << std::endl;
std::cerr << "Query point " << queryPoint << std::endl;
std::cerr << "Reported closest point " << result
<< " distance " << result_dist << std::endl;
std::cerr << "Actual closest point " << min_point
<< " distance " << min_dist << std::endl;
std::cerr << std::endl;
std::cerr << "Test FAILED." << std::endl;
numberOfFailedPoints2++;
}
}
if( argc > 4 )
{
//
// Plot out the tree structure to the console in the format used by Graphviz dot
//
std::ofstream plotFile;
plotFile.open( argv[4] );
tree->PlotTree( plotFile );
plotFile.close();
}
if( numberOfFailedPoints1 )
{
std::cerr << numberOfFailedPoints1 << " out of " << sample->Size();
std::cerr << " points failed to find themselves as closest-point" << std::endl;
}
if( numberOfFailedPoints2 )
{
std::cerr << numberOfFailedPoints2 << " out of " << numberOfTestPoints;
std::cerr << " points failed to find the correct closest point." << std::endl;
}
if( numberOfFailedPoints1 || numberOfFailedPoints2 )
{
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: fix KDTree tests failing due to insignificant rounding error<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistanceMetric.h"
#include <fstream>
int itkKdTreeTest1(int argc , char * argv [] )
{
if( argc < 4 )
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " numberOfDataPoints numberOfTestPoints bucketSize [graphvizDotOutputFile]" << std::endl;
return EXIT_FAILURE;
}
// Random number generator
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;
NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
randomNumberGenerator->Initialize();
typedef itk::Array< double > MeasurementVectorType;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType;
const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;
SampleType::Pointer sample = SampleType::New();
sample->SetMeasurementVectorSize( measurementVectorSize );
//
// Generate a sample of random points
//
const unsigned int numberOfDataPoints = atoi( argv[1] );
MeasurementVectorType mv( measurementVectorSize );
for (unsigned int i = 0; i < numberOfDataPoints; ++i )
{
mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
sample->PushBack( mv );
std::cout << "Add measurement vector: " << mv << std::endl;
}
typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType;
TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();
const unsigned int bucketSize = atoi( argv[3] );
treeGenerator->SetSample( sample );
treeGenerator->SetBucketSize( bucketSize );
treeGenerator->Update();
typedef TreeGeneratorType::KdTreeType TreeType;
typedef TreeType::NearestNeighbors NeighborsType;
typedef TreeType::KdTreeNodeType NodeType;
TreeType::Pointer tree = treeGenerator->GetOutput();
MeasurementVectorType queryPoint( measurementVectorSize );
unsigned int numberOfNeighbors = 1;
TreeType::InstanceIdentifierVectorType neighbors;
MeasurementVectorType result( measurementVectorSize );
MeasurementVectorType test_point( measurementVectorSize );
MeasurementVectorType min_point( measurementVectorSize );
unsigned int numberOfFailedPoints1 = 0;
const unsigned int numberOfTestPoints = atoi( argv[2] );
//
// Check that for every point in the sample, its closest point is itself.
//
typedef itk::Statistics::EuclideanDistanceMetric< MeasurementVectorType > DistanceMetricType;
typedef DistanceMetricType::OriginType OriginType;
DistanceMetricType::Pointer distanceMetric = DistanceMetricType::New();
OriginType origin( measurementVectorSize );
for( unsigned int k = 0; k < sample->Size(); k++ )
{
queryPoint = sample->GetMeasurementVector(k);
for ( unsigned int i = 0; i < sample->GetMeasurementVectorSize(); ++i )
{
origin[i] = queryPoint[i];
}
distanceMetric->SetOrigin( origin );
tree->Search( queryPoint, numberOfNeighbors, neighbors );
for ( unsigned int i = 0; i < numberOfNeighbors; ++i )
{
const double distance =
distanceMetric->Evaluate( tree->GetMeasurementVector( neighbors[i] ));
if( distance > vnl_math::eps )
{
std::cerr << "kd-tree knn search result:" << std::endl
<< "query point = [" << queryPoint << "]" << std::endl
<< "k = " << numberOfNeighbors << std::endl;
std::cerr << "measurement vector : distance" << std::endl;
std::cerr << "[" << tree->GetMeasurementVector( neighbors[i] )
<< "] : "
<< distance << std::endl;
numberOfFailedPoints1++;
}
}
}
unsigned int numberOfFailedPoints2 = 0;
//
// Generate a second sample of random points
// and use them to query the tree
//
for (unsigned int j = 0; j < numberOfTestPoints; ++j )
{
double min_dist = itk::NumericTraits< double >::max();
queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
tree->Search( queryPoint, numberOfNeighbors, neighbors );
//
// The first neighbor should be the closest point.
//
result = tree->GetMeasurementVector( neighbors[0] );
//
// Compute the distance to the "presumed" nearest neighbor
//
double result_dist = vcl_sqrt(
(result[0] - queryPoint[0]) *
(result[0] - queryPoint[0]) +
(result[1] - queryPoint[1]) *
(result[1] - queryPoint[1])
);
//
// Compute the distance to all other points, to verify
// whether the first neighbor was the closest one or not.
//
for( unsigned int i = 0; i < numberOfDataPoints; ++i )
{
test_point = tree->GetMeasurementVector( i );
const double dist = vcl_sqrt(
(test_point[0] - queryPoint[0]) *
(test_point[0] - queryPoint[0]) +
(test_point[1] - queryPoint[1]) *
(test_point[1] - queryPoint[1])
);
if( dist < min_dist )
{
min_dist = dist;
min_point = test_point;
}
}
if( vcl_fabs(min_dist - result_dist) > 10.0*itk::NumericTraits<double>::epsilon()*min_dist )
{
std::cerr << "Problem found " << std::endl;
std::cerr << "Query point " << queryPoint << std::endl;
std::cerr << "Reported closest point " << result
<< " distance " << result_dist << std::endl;
std::cerr << "Actual closest point " << min_point
<< " distance " << min_dist << std::endl;
std::cerr << std::endl;
std::cerr << "Test FAILED." << std::endl;
numberOfFailedPoints2++;
}
}
if( argc > 4 )
{
//
// Plot out the tree structure to the console in the format used by Graphviz dot
//
std::ofstream plotFile;
plotFile.open( argv[4] );
tree->PlotTree( plotFile );
plotFile.close();
}
if( numberOfFailedPoints1 )
{
std::cerr << numberOfFailedPoints1 << " out of " << sample->Size();
std::cerr << " points failed to find themselves as closest-point" << std::endl;
}
if( numberOfFailedPoints2 )
{
std::cerr << numberOfFailedPoints2 << " out of " << numberOfTestPoints;
std::cerr << " points failed to find the correct closest point." << std::endl;
}
if( numberOfFailedPoints1 || numberOfFailedPoints2 )
{
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*!
* @file AESGCMGMAC_KeyExchange.cpp
*/
#include <sstream>
#include <fastrtps/rtps/common/Token.h>
#include <fastrtps/rtps/common/BinaryProperty.h>
#include "AESGCMGMAC_KeyExchange.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
using namespace eprosima::fastrtps::rtps::security;
AESGCMGMAC_KeyExchange::AESGCMGMAC_KeyExchange(){}
AESGCMGMAC_KeyExchange::~AESGCMGMAC_KeyExchange(){}
bool AESGCMGMAC_KeyExchange::create_local_participant_crypto_tokens(
ParticipantCryptoTokenSeq &local_participant_crypto_tokens,
ParticipantCryptoHandle &local_participant_crypto,
ParticipantCryptoHandle &remote_participant_crypto,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(local_participant_crypto);
AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto);
if( local_participant.nil() | remote_participant.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_participant_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
ParticipantCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_participant->Participant2ParticipantKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key);
temp.binary_properties().push_back(prop);
local_participant_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::set_remote_participant_crypto_tokens(
ParticipantCryptoHandle &local_participant_crypto,
ParticipantCryptoHandle &remote_participant_crypto,
const ParticipantCryptoTokenSeq &remote_participant_tokens,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(local_participant_crypto);
AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto);
if( local_participant.nil() | remote_participant.nil() ){
//TODO (Santi) provide insight
return false;
}
//As only relevant KeyMaterials are tokenized, only one Token is exchanged
if(remote_participant_tokens.size() != 1){
exception = SecurityException("Incorrect remote CryptoSequence length");
return false;
}
if(remote_participant_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){
exception = SecurityException("Incorrect token type received");
return false;
}
if(remote_participant_tokens.at(0).binary_properties().size() !=1 | remote_participant_tokens.at(0).properties().size() != 0 |
remote_participant_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat"){
exception = SecurityException("Malformed CryptoToken");
return false;
}
//Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial
std::vector<uint8_t> plaintext = aes_128_gcm_decrypt(remote_participant_tokens.at(0).binary_properties().at(0).value(),
remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key);
KeyMaterial_AES_GCM_GMAC keymat;
keymat = KeyMaterialCDRDeserialize(&plaintext);
local_participant->RemoteParticipant2ParticipantKeyMaterial.push_back(keymat);
remote_participant->RemoteParticipant2ParticipantKeyMaterial.push_back(keymat);
return true;
}
bool AESGCMGMAC_KeyExchange::create_local_datawriter_crypto_tokens(
DatawriterCryptoTokenSeq &local_datawriter_crypto_tokens,
DatawriterCryptoHandle &local_datawriter_crypto,
DatareaderCryptoHandle &remote_datareader_crypto,
SecurityException &exception){
AESGCMGMAC_WriterCryptoHandle& local_writer = AESGCMGMAC_WriterCryptoHandle::narrow(local_datawriter_crypto);
AESGCMGMAC_ReaderCryptoHandle& remote_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(remote_datareader_crypto);
if( local_writer.nil() | remote_reader.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_datawriter_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
DatawriterCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_reader->Writer2ReaderKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key);
temp.binary_properties().push_back(prop);
local_datawriter_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::create_local_datareader_crypto_tokens(
DatareaderCryptoTokenSeq &local_datareader_crypto_tokens,
DatareaderCryptoHandle &local_datareader_crypto,
DatawriterCryptoHandle &remote_datawriter_crypto,
SecurityException &exception){
AESGCMGMAC_ReaderCryptoHandle& local_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(local_datareader_crypto);
AESGCMGMAC_WriterCryptoHandle& remote_writer = AESGCMGMAC_WriterCryptoHandle::narrow(remote_datawriter_crypto);
if( local_reader.nil() | remote_writer.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_datareader_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
DatareaderCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_writer->Reader2WriterKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key);
temp.binary_properties().push_back(prop);
local_datareader_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::set_remote_datareader_crypto_tokens(
DatawriterCryptoHandle &local_datawriter_crypto,
DatareaderCryptoHandle &remote_datareader_crypto,
const DatareaderCryptoTokenSeq &remote_datareader_tokens,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_KeyExchange::set_remote_datawriter_crypto_tokens(
DatareaderCryptoHandle &local_datareader_crypto,
DatawriterCryptoHandle &remote_datawriter_crypto,
const DatawriterCryptoTokenSeq &remote_datawriter_tokens,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_KeyExchange::return_crypto_tokens(
const CryptoTokenSeq &crypto_tokens,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::KeyMaterialCDRSerialize(KeyMaterial_AES_GCM_GMAC &key){
std::vector<uint8_t> buffer;
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.transformation_kind[i]);
}
buffer.push_back(2);
for(int i=0;i<32;i++){
buffer.push_back(key.master_salt[i]);
}
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.sender_key_id[i]);
}
buffer.push_back(32);
for(int i=0;i<32;i++){
buffer.push_back(key.master_sender_key[i]);
}
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.receiver_specific_key_id[i]);
}
buffer.push_back(32);
for(int i=0;i<32;i++){
buffer.push_back(key.master_receiver_specific_key[i]);
}
return buffer;
}
KeyMaterial_AES_GCM_GMAC AESGCMGMAC_KeyExchange::KeyMaterialCDRDeserialize(std::vector<uint8_t> *CDR){
unsigned short index = 0;
KeyMaterial_AES_GCM_GMAC buffer;
for(int i=1; i<5; i++){
buffer.transformation_kind[i-1] = CDR->at(i);
}
for(int i=6; i<38; i++){
buffer.master_salt[i-6] = CDR->at(i);
}
for(int i=39; i<43; i++){
buffer.sender_key_id[i-39] = CDR->at(i);
}
for(int i=44; i<76; i++){
buffer.master_sender_key[i-44] = CDR->at(i);
}
for(int i=77; i<81; i++){
buffer.receiver_specific_key_id[i-77] = CDR->at(i);
}
for(int i=82; i< 114; i++){
buffer.master_receiver_specific_key[i-82] = CDR->at(i);
}
return buffer;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::aes_128_gcm_encrypt(std::vector<uint8_t> plaintext, std::array<uint8_t,32> key){
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
size_t enc_length = plaintext.size()*3;
std::vector<uint8_t> output;
output.resize(enc_length,'\0');
unsigned char tag[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];
RAND_bytes(iv, sizeof(iv));
std::copy(iv, iv+16, output.begin()+16);
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)key.data(), iv);
EVP_EncryptUpdate(e_ctx, &output[32], &actual_size, (const unsigned char*)plaintext.data(), plaintext.size());
EVP_EncryptFinal(e_ctx, &output[32+actual_size], &final_size);
EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
std::copy(iv,iv+16, output.begin());
std::copy(iv, iv+16, output.begin()+16);
output.resize(32+actual_size+final_size);
EVP_CIPHER_CTX_free(e_ctx);
return output;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::aes_128_gcm_decrypt(std::vector<uint8_t> crypto, std::array<uint8_t,32> key){
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
unsigned char tag[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];
std::copy(crypto.begin(), crypto.begin()+16, tag);
std::copy(crypto.begin()+16, crypto.begin()+32, iv);
std::vector<uint8_t> plaintext;
plaintext.resize(crypto.size(), '\0');
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* d_ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit(d_ctx, EVP_aes_128_gcm(), (const unsigned char*)key.data(), iv);
EVP_DecryptUpdate(d_ctx, &plaintext[0], &actual_size, (const unsigned char*)crypto.data()+32, crypto.size()-32);
EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
EVP_DecryptFinal(d_ctx, &plaintext[actual_size], &final_size);
plaintext.resize(actual_size + final_size, '\0');
EVP_CIPHER_CTX_free(d_ctx);
return plaintext;
}
<commit_msg>DataReader/Writer CryptoToken exchange test implementation<commit_after>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*!
* @file AESGCMGMAC_KeyExchange.cpp
*/
#include <sstream>
#include <fastrtps/rtps/common/Token.h>
#include <fastrtps/rtps/common/BinaryProperty.h>
#include "AESGCMGMAC_KeyExchange.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
using namespace eprosima::fastrtps::rtps::security;
AESGCMGMAC_KeyExchange::AESGCMGMAC_KeyExchange(){}
AESGCMGMAC_KeyExchange::~AESGCMGMAC_KeyExchange(){}
bool AESGCMGMAC_KeyExchange::create_local_participant_crypto_tokens(
ParticipantCryptoTokenSeq &local_participant_crypto_tokens,
ParticipantCryptoHandle &local_participant_crypto,
ParticipantCryptoHandle &remote_participant_crypto,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(local_participant_crypto);
AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto);
if( local_participant.nil() | remote_participant.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_participant_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
ParticipantCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_participant->Participant2ParticipantKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key);
temp.binary_properties().push_back(prop);
local_participant_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::set_remote_participant_crypto_tokens(
ParticipantCryptoHandle &local_participant_crypto,
ParticipantCryptoHandle &remote_participant_crypto,
const ParticipantCryptoTokenSeq &remote_participant_tokens,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(local_participant_crypto);
AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto);
if( local_participant.nil() | remote_participant.nil() ){
//TODO (Santi) provide insight
return false;
}
//As only relevant KeyMaterials are tokenized, only one Token is exchanged
if(remote_participant_tokens.size() != 1){
exception = SecurityException("Incorrect remote CryptoSequence length");
return false;
}
if(remote_participant_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){
exception = SecurityException("Incorrect token type received");
return false;
}
if(remote_participant_tokens.at(0).binary_properties().size() !=1 | remote_participant_tokens.at(0).properties().size() != 0 |
remote_participant_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat"){
exception = SecurityException("Malformed CryptoToken");
return false;
}
//Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial
std::vector<uint8_t> plaintext = aes_128_gcm_decrypt(remote_participant_tokens.at(0).binary_properties().at(0).value(),
remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key);
KeyMaterial_AES_GCM_GMAC keymat;
keymat = KeyMaterialCDRDeserialize(&plaintext);
local_participant->RemoteParticipant2ParticipantKeyMaterial.push_back(keymat);
remote_participant->RemoteParticipant2ParticipantKeyMaterial.push_back(keymat);
return true;
}
bool AESGCMGMAC_KeyExchange::create_local_datawriter_crypto_tokens(
DatawriterCryptoTokenSeq &local_datawriter_crypto_tokens,
DatawriterCryptoHandle &local_datawriter_crypto,
DatareaderCryptoHandle &remote_datareader_crypto,
SecurityException &exception){
AESGCMGMAC_WriterCryptoHandle& local_writer = AESGCMGMAC_WriterCryptoHandle::narrow(local_datawriter_crypto);
AESGCMGMAC_ReaderCryptoHandle& remote_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(remote_datareader_crypto);
if( local_writer.nil() | remote_reader.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_datawriter_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
DatawriterCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_reader->Writer2ReaderKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key);
temp.binary_properties().push_back(prop);
local_datawriter_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::create_local_datareader_crypto_tokens(
DatareaderCryptoTokenSeq &local_datareader_crypto_tokens,
DatareaderCryptoHandle &local_datareader_crypto,
DatawriterCryptoHandle &remote_datawriter_crypto,
SecurityException &exception){
AESGCMGMAC_ReaderCryptoHandle& local_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(local_datareader_crypto);
AESGCMGMAC_WriterCryptoHandle& remote_writer = AESGCMGMAC_WriterCryptoHandle::narrow(remote_datawriter_crypto);
if( local_reader.nil() | remote_writer.nil() ){
//TODO (Santi) provide insight
return false;
}
//Flush previously present CryptoTokens
local_datareader_crypto_tokens.clear();
//Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side
{
//Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant
DatareaderCryptoToken temp;
temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC");
BinaryProperty prop;
prop.name() = std::string("dds.cryp.keymat");
std::vector<uint8_t> plaintext= KeyMaterialCDRSerialize(remote_writer->Reader2WriterKeyMaterial.at(0));
prop.value() = aes_128_gcm_encrypt(plaintext, remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key);
temp.binary_properties().push_back(prop);
local_datareader_crypto_tokens.push_back(temp);
}
return true;
}
bool AESGCMGMAC_KeyExchange::set_remote_datareader_crypto_tokens(
DatawriterCryptoHandle &local_datawriter_crypto,
DatareaderCryptoHandle &remote_datareader_crypto,
const DatareaderCryptoTokenSeq &remote_datareader_tokens,
SecurityException &exception){
AESGCMGMAC_WriterCryptoHandle& local_writer = AESGCMGMAC_WriterCryptoHandle::narrow(local_datawriter_crypto);
AESGCMGMAC_ReaderCryptoHandle& remote_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(remote_datareader_crypto);
if( local_writer.nil() | remote_reader.nil() ){
//TODO (Santi) provide insight
return false;
}
//As only relevant KeyMaterials are tokenized, only one Token is exchanged
if(remote_datareader_tokens.size() != 1){
exception = SecurityException("Incorrect remote CryptoSequence length");
return false;
}
if(remote_datareader_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){
exception = SecurityException("Incorrect token type received");
return false;
}
if(remote_datareader_tokens.at(0).binary_properties().size() !=1 | remote_datareader_tokens.at(0).properties().size() != 0 |
remote_datareader_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat"){
exception = SecurityException("Malformed CryptoToken");
return false;
}
//Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial
std::vector<uint8_t> plaintext = aes_128_gcm_decrypt(remote_datareader_tokens.at(0).binary_properties().at(0).value(),
remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key);
KeyMaterial_AES_GCM_GMAC keymat;
keymat = KeyMaterialCDRDeserialize(&plaintext);
local_writer->Reader2WriterKeyMaterial.push_back(keymat);
remote_reader->Reader2WriterKeyMaterial.push_back(keymat);
}
bool AESGCMGMAC_KeyExchange::set_remote_datawriter_crypto_tokens(
DatareaderCryptoHandle &local_datareader_crypto,
DatawriterCryptoHandle &remote_datawriter_crypto,
const DatawriterCryptoTokenSeq &remote_datawriter_tokens,
SecurityException &exception){
AESGCMGMAC_ReaderCryptoHandle& local_reader = AESGCMGMAC_ReaderCryptoHandle::narrow(local_datareader_crypto);
AESGCMGMAC_WriterCryptoHandle& remote_writer = AESGCMGMAC_WriterCryptoHandle::narrow(remote_datawriter_crypto);
if( local_reader.nil() | remote_writer.nil() ){
//TODO (Santi) provide insight
return false;
}
//As only relevant KeyMaterials are tokenized, only one Token is exchanged
if(remote_datawriter_tokens.size() != 1){
exception = SecurityException("Incorrect remote CryptoSequence length");
return false;
}
if(remote_datawriter_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){
exception = SecurityException("Incorrect token type received");
return false;
}
if(remote_datawriter_tokens.at(0).binary_properties().size() !=1 | remote_datawriter_tokens.at(0).properties().size() != 0 |
remote_datawriter_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat"){
exception = SecurityException("Malformed CryptoToken");
return false;
}
//Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial
std::vector<uint8_t> plaintext = aes_128_gcm_decrypt(remote_datawriter_tokens.at(0).binary_properties().at(0).value(),
remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key);
KeyMaterial_AES_GCM_GMAC keymat;
keymat = KeyMaterialCDRDeserialize(&plaintext);
local_reader->Writer2ReaderKeyMaterial.push_back(keymat);
remote_writer->Writer2ReaderKeyMaterial.push_back(keymat);
}
bool AESGCMGMAC_KeyExchange::return_crypto_tokens(
const CryptoTokenSeq &crypto_tokens,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::KeyMaterialCDRSerialize(KeyMaterial_AES_GCM_GMAC &key){
std::vector<uint8_t> buffer;
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.transformation_kind[i]);
}
buffer.push_back(2);
for(int i=0;i<32;i++){
buffer.push_back(key.master_salt[i]);
}
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.sender_key_id[i]);
}
buffer.push_back(32);
for(int i=0;i<32;i++){
buffer.push_back(key.master_sender_key[i]);
}
buffer.push_back(4);
for(int i=0;i<4;i++){
buffer.push_back(key.receiver_specific_key_id[i]);
}
buffer.push_back(32);
for(int i=0;i<32;i++){
buffer.push_back(key.master_receiver_specific_key[i]);
}
return buffer;
}
KeyMaterial_AES_GCM_GMAC AESGCMGMAC_KeyExchange::KeyMaterialCDRDeserialize(std::vector<uint8_t> *CDR){
unsigned short index = 0;
KeyMaterial_AES_GCM_GMAC buffer;
for(int i=1; i<5; i++){
buffer.transformation_kind[i-1] = CDR->at(i);
}
for(int i=6; i<38; i++){
buffer.master_salt[i-6] = CDR->at(i);
}
for(int i=39; i<43; i++){
buffer.sender_key_id[i-39] = CDR->at(i);
}
for(int i=44; i<76; i++){
buffer.master_sender_key[i-44] = CDR->at(i);
}
for(int i=77; i<81; i++){
buffer.receiver_specific_key_id[i-77] = CDR->at(i);
}
for(int i=82; i< 114; i++){
buffer.master_receiver_specific_key[i-82] = CDR->at(i);
}
return buffer;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::aes_128_gcm_encrypt(std::vector<uint8_t> plaintext, std::array<uint8_t,32> key){
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
size_t enc_length = plaintext.size()*3;
std::vector<uint8_t> output;
output.resize(enc_length,'\0');
unsigned char tag[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];
RAND_bytes(iv, sizeof(iv));
std::copy(iv, iv+16, output.begin()+16);
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)key.data(), iv);
EVP_EncryptUpdate(e_ctx, &output[32], &actual_size, (const unsigned char*)plaintext.data(), plaintext.size());
EVP_EncryptFinal(e_ctx, &output[32+actual_size], &final_size);
EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
std::copy(iv,iv+16, output.begin());
std::copy(iv, iv+16, output.begin()+16);
output.resize(32+actual_size+final_size);
EVP_CIPHER_CTX_free(e_ctx);
return output;
}
std::vector<uint8_t> AESGCMGMAC_KeyExchange::aes_128_gcm_decrypt(std::vector<uint8_t> crypto, std::array<uint8_t,32> key){
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
unsigned char tag[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];
std::copy(crypto.begin(), crypto.begin()+16, tag);
std::copy(crypto.begin()+16, crypto.begin()+32, iv);
std::vector<uint8_t> plaintext;
plaintext.resize(crypto.size(), '\0');
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* d_ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit(d_ctx, EVP_aes_128_gcm(), (const unsigned char*)key.data(), iv);
EVP_DecryptUpdate(d_ctx, &plaintext[0], &actual_size, (const unsigned char*)crypto.data()+32, crypto.size()-32);
EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
EVP_DecryptFinal(d_ctx, &plaintext[actual_size], &final_size);
plaintext.resize(actual_size + final_size, '\0');
EVP_CIPHER_CTX_free(d_ctx);
return plaintext;
}
<|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 <config.h>
// When defined, different heap allocators can be used via an environment
// variable set before running the program. This may reduce the amount
// of inlining that we get with malloc/free/etc. Disabling makes it
// so that only tcmalloc can be used.
#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
// TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth
// from the "user code" so that debugging tools (HeapChecker) can work.
// __THROW is defined in glibc systems. It means, counter-intuitively,
// "This function will never throw an exception." It's an optional
// optimization tool, but we may need to use it to match glibc prototypes.
#ifndef __THROW // I guess we're not on a glibc system
# define __THROW // __THROW is just an optimization, so ok to make it ""
#endif
// new_mode behaves similarly to MSVC's _set_new_mode.
// If flag is 0 (default), calls to malloc will behave normally.
// If flag is 1, calls to malloc will behave like calls to new,
// and the std_new_handler will be invoked on failure.
// Can be set by calling _set_new_mode().
static int new_mode = 0;
typedef enum {
TCMALLOC, // TCMalloc is the default allocator.
JEMALLOC, // JEMalloc
WINDEFAULT, // Windows Heap
WINLFH, // Windows LFH Heap
} Allocator;
// This is the default allocator.
static Allocator allocator = TCMALLOC;
// We include tcmalloc and the win_allocator to get as much inlining as
// possible.
#include "tcmalloc.cc"
#include "win_allocator.cc"
// Forward declarations from jemalloc.
extern "C" {
void* je_malloc(size_t s);
void* je_realloc(void* p, size_t s);
void je_free(void* s);
size_t je_msize(void* p);
bool je_malloc_init_hard();
}
extern "C" {
// Call the new handler, if one has been set.
// Returns true on successfully calling the handler, false otherwise.
inline bool call_new_handler(bool nothrow) {
// Get the current new handler. NB: this function is not
// thread-safe. We make a feeble stab at making it so here, but
// this lock only protects against tcmalloc interfering with
// itself, not with other libraries calling set_new_handler.
std::new_handler nh;
{
SpinLockHolder h(&set_new_handler_lock);
nh = std::set_new_handler(0);
(void) std::set_new_handler(nh);
}
#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
if (!nh)
return false;
// Since exceptions are disabled, we don't really know if new_handler
// failed. Assume it will abort if it fails.
(*nh)();
return false; // break out of the retry loop.
#else
// If no new_handler is established, the allocation failed.
if (!nh) {
if (nothrow)
return 0;
throw std::bad_alloc();
}
// Otherwise, try the new_handler. If it returns, retry the
// allocation. If it throws std::bad_alloc, fail the allocation.
// if it throws something else, don't interfere.
try {
(*nh)();
} catch (const std::bad_alloc&) {
if (!nothrow)
throw;
return p;
}
#endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
}
void* malloc(size_t size) __THROW {
void* ptr;
for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
ptr = je_malloc(size);
break;
case WINDEFAULT:
case WINLFH:
ptr = win_heap_malloc(size);
break;
case TCMALLOC:
default:
ptr = do_malloc(size);
break;
}
#else
// TCMalloc case.
ptr = do_malloc(size);
#endif
if (ptr)
return ptr;
if (!new_mode || !call_new_handler(true))
break;
}
return ptr;
}
void free(void* p) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
je_free(p);
return;
case WINDEFAULT:
case WINLFH:
win_heap_free(p);
return;
}
#endif
// TCMalloc case.
do_free(p);
}
void* realloc(void* ptr, size_t size) __THROW {
void* new_ptr;
for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
new_ptr = je_realloc(ptr, size);
break;
case WINDEFAULT:
case WINLFH:
new_ptr = win_heap_realloc(ptr, size);
break;
case TCMALLOC:
default:
new_ptr = do_realloc(ptr, size);
break;
}
#else
// TCMalloc case.
new_ptr = do_realloc(ptr, size);
#endif
// Subtle warning: NULL return does not alwas indicate out-of-memory. If
// the requested new size is zero, realloc should free the ptr and return
// NULL.
if (new_ptr || !size)
return new_ptr;
if (!new_mode || !call_new_handler(true))
break;
}
return new_ptr;
}
// TODO(mbelshe): Implement this for other allocators.
void malloc_stats(void) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
// No stats.
return;
case WINDEFAULT:
case WINLFH:
// No stats.
return;
}
#endif
tc_malloc_stats();
}
#ifdef WIN32
extern "C" size_t _msize(void* p) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
return je_msize(p);
case WINDEFAULT:
case WINLFH:
return win_heap_msize(p);
}
#endif
return MallocExtension::instance()->GetAllocatedSize(p);
}
// This is included to resolve references from libcmt.
extern "C" intptr_t _get_heap_handle() {
return 0;
}
// The CRT heap initialization stub.
extern "C" int _heap_init() {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
const char* override = GetenvBeforeMain("CHROME_ALLOCATOR");
if (override) {
if (!stricmp(override, "jemalloc"))
allocator = JEMALLOC;
else if (!stricmp(override, "winheap"))
allocator = WINDEFAULT;
else if (!stricmp(override, "winlfh"))
allocator = WINLFH;
else if (!stricmp(override, "tcmalloc"))
allocator = TCMALLOC;
}
switch (allocator) {
case JEMALLOC:
return je_malloc_init_hard() ? 0 : 1;
case WINDEFAULT:
return win_heap_init(false) ? 1 : 0;
case WINLFH:
return win_heap_init(true) ? 1 : 0;
case TCMALLOC:
default:
// fall through
break;
}
#endif
// Initializing tcmalloc.
// We intentionally leak this object. It lasts for the process
// lifetime. Trying to teardown at _heap_term() is so late that
// you can't do anything useful anyway.
new TCMallocGuard();
return 1;
}
// The CRT heap cleanup stub.
extern "C" void _heap_term() {}
// We set this to 1 because part of the CRT uses a check of _crtheap != 0
// to test whether the CRT has been initialized. Once we've ripped out
// the allocators from libcmt, we need to provide this definition so that
// the rest of the CRT is still usable.
extern "C" void* _crtheap = reinterpret_cast<void*>(1);
#endif // WIN32
#include "generic_allocators.cc"
} // extern C
<commit_msg>Try to use JEMALLOC as the default allocator<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 <config.h>
// When defined, different heap allocators can be used via an environment
// variable set before running the program. This may reduce the amount
// of inlining that we get with malloc/free/etc. Disabling makes it
// so that only tcmalloc can be used.
#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
// TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth
// from the "user code" so that debugging tools (HeapChecker) can work.
// __THROW is defined in glibc systems. It means, counter-intuitively,
// "This function will never throw an exception." It's an optional
// optimization tool, but we may need to use it to match glibc prototypes.
#ifndef __THROW // I guess we're not on a glibc system
# define __THROW // __THROW is just an optimization, so ok to make it ""
#endif
// new_mode behaves similarly to MSVC's _set_new_mode.
// If flag is 0 (default), calls to malloc will behave normally.
// If flag is 1, calls to malloc will behave like calls to new,
// and the std_new_handler will be invoked on failure.
// Can be set by calling _set_new_mode().
static int new_mode = 0;
typedef enum {
TCMALLOC, // TCMalloc is the default allocator.
JEMALLOC, // JEMalloc
WINDEFAULT, // Windows Heap
WINLFH, // Windows LFH Heap
} Allocator;
// This is the default allocator.
static Allocator allocator = JEMALLOC;
// We include tcmalloc and the win_allocator to get as much inlining as
// possible.
#include "tcmalloc.cc"
#include "win_allocator.cc"
// Forward declarations from jemalloc.
extern "C" {
void* je_malloc(size_t s);
void* je_realloc(void* p, size_t s);
void je_free(void* s);
size_t je_msize(void* p);
bool je_malloc_init_hard();
}
extern "C" {
// Call the new handler, if one has been set.
// Returns true on successfully calling the handler, false otherwise.
inline bool call_new_handler(bool nothrow) {
// Get the current new handler. NB: this function is not
// thread-safe. We make a feeble stab at making it so here, but
// this lock only protects against tcmalloc interfering with
// itself, not with other libraries calling set_new_handler.
std::new_handler nh;
{
SpinLockHolder h(&set_new_handler_lock);
nh = std::set_new_handler(0);
(void) std::set_new_handler(nh);
}
#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
if (!nh)
return false;
// Since exceptions are disabled, we don't really know if new_handler
// failed. Assume it will abort if it fails.
(*nh)();
return false; // break out of the retry loop.
#else
// If no new_handler is established, the allocation failed.
if (!nh) {
if (nothrow)
return 0;
throw std::bad_alloc();
}
// Otherwise, try the new_handler. If it returns, retry the
// allocation. If it throws std::bad_alloc, fail the allocation.
// if it throws something else, don't interfere.
try {
(*nh)();
} catch (const std::bad_alloc&) {
if (!nothrow)
throw;
return p;
}
#endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
}
void* malloc(size_t size) __THROW {
void* ptr;
for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
ptr = je_malloc(size);
break;
case WINDEFAULT:
case WINLFH:
ptr = win_heap_malloc(size);
break;
case TCMALLOC:
default:
ptr = do_malloc(size);
break;
}
#else
// TCMalloc case.
ptr = do_malloc(size);
#endif
if (ptr)
return ptr;
if (!new_mode || !call_new_handler(true))
break;
}
return ptr;
}
void free(void* p) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
je_free(p);
return;
case WINDEFAULT:
case WINLFH:
win_heap_free(p);
return;
}
#endif
// TCMalloc case.
do_free(p);
}
void* realloc(void* ptr, size_t size) __THROW {
void* new_ptr;
for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
new_ptr = je_realloc(ptr, size);
break;
case WINDEFAULT:
case WINLFH:
new_ptr = win_heap_realloc(ptr, size);
break;
case TCMALLOC:
default:
new_ptr = do_realloc(ptr, size);
break;
}
#else
// TCMalloc case.
new_ptr = do_realloc(ptr, size);
#endif
// Subtle warning: NULL return does not alwas indicate out-of-memory. If
// the requested new size is zero, realloc should free the ptr and return
// NULL.
if (new_ptr || !size)
return new_ptr;
if (!new_mode || !call_new_handler(true))
break;
}
return new_ptr;
}
// TODO(mbelshe): Implement this for other allocators.
void malloc_stats(void) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
// No stats.
return;
case WINDEFAULT:
case WINLFH:
// No stats.
return;
}
#endif
tc_malloc_stats();
}
#ifdef WIN32
extern "C" size_t _msize(void* p) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
switch (allocator) {
case JEMALLOC:
return je_msize(p);
case WINDEFAULT:
case WINLFH:
return win_heap_msize(p);
}
#endif
return MallocExtension::instance()->GetAllocatedSize(p);
}
// This is included to resolve references from libcmt.
extern "C" intptr_t _get_heap_handle() {
return 0;
}
// The CRT heap initialization stub.
extern "C" int _heap_init() {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
const char* override = GetenvBeforeMain("CHROME_ALLOCATOR");
if (override) {
if (!stricmp(override, "jemalloc"))
allocator = JEMALLOC;
else if (!stricmp(override, "winheap"))
allocator = WINDEFAULT;
else if (!stricmp(override, "winlfh"))
allocator = WINLFH;
else if (!stricmp(override, "tcmalloc"))
allocator = TCMALLOC;
}
switch (allocator) {
case JEMALLOC:
return je_malloc_init_hard() ? 0 : 1;
case WINDEFAULT:
return win_heap_init(false) ? 1 : 0;
case WINLFH:
return win_heap_init(true) ? 1 : 0;
case TCMALLOC:
default:
// fall through
break;
}
#endif
// Initializing tcmalloc.
// We intentionally leak this object. It lasts for the process
// lifetime. Trying to teardown at _heap_term() is so late that
// you can't do anything useful anyway.
new TCMallocGuard();
return 1;
}
// The CRT heap cleanup stub.
extern "C" void _heap_term() {}
// We set this to 1 because part of the CRT uses a check of _crtheap != 0
// to test whether the CRT has been initialized. Once we've ripped out
// the allocators from libcmt, we need to provide this definition so that
// the rest of the CRT is still usable.
extern "C" void* _crtheap = reinterpret_cast<void*>(1);
#endif // WIN32
#include "generic_allocators.cc"
} // extern C
<|endoftext|>
|
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
//imshow("webcam", image);
// thresholds on dark regions
Mat gray, blurred_gray, threshold_gray;
cvtColor(image, gray, CV_BGR2GRAY);
blur(gray, blurred_gray, Size(width/10,height/20));
equalizeHist(blurred_gray, blurred_gray);
bitwise_not(blurred_gray, blurred_gray);
threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);
imshow("threshold", threshold_gray);
Mat canny;
Canny(gray, canny, 50, 200, 3);
vector<Vec4i> lines;
HoughLinesP(canny, lines, 10, CV_PI/180, 100);
for (size_t i = 0; i < lines.size(); i++) {
line(image, Point(lines[i][0], lines[i][1]),
Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8);
}
imshow("lola", image);
/*
bitwise_not(gray,gray);
Mat mask = threshold_gray.mul(gray);
imshow("mask", mask);
Moments lol = moments(mask, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
//imshow("webcam", image);
// thresholds on dark regions
Mat gray, blurred_gray, threshold_gray;
cvtColor(image, gray, CV_BGR2GRAY);
blur(gray, blurred_gray, Size(width/10,height/20));
equalizeHist(blurred_gray, blurred_gray);
bitwise_not(blurred_gray, blurred_gray);
threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);
imshow("threshold", threshold_gray);
Mat canny;
Canny(gray, canny, 50, 200, 3);
vector<Vec4i> lines;
HoughLinesP(canny, lines, 10, CV_PI/180, 150);
for (size_t i = 0; i < lines.size(); i++) {
line(image, Point(lines[i][0], lines[i][1]),
Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8);
}
imshow("lola", image);
/*
bitwise_not(gray,gray);
Mat mask = threshold_gray.mul(gray);
imshow("mask", mask);
Moments lol = moments(mask, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Resolves: tdf#91392 orig map for orig code paths, and new map for new path<commit_after><|endoftext|>
|
<commit_before>#include <EtFramework/stdafx.h>
#include "EcsTestUtilities.h"
#include <catch2/catch.hpp>
#include <rttr/registration>
#include <thread>
#include <chrono>
#include <mainTesting.h>
#include <EtFramework/ECS/EcsController.h>
TEST_CASE("command buffer reparent", "[ecs]")
{
fw::EcsController ecs;
// generate entities
fw::T_EntityId ent0 = ecs.AddEntity(TestBComponent(""));
fw::T_EntityId ent1 = ecs.AddEntity(TestCComponent(ent0));
class TestCReparentSystem final : public fw::System<TestCReparentSystem, TestCView>
{
public:
TestCReparentSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestCView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestCView& view : range)
{
cb.ReparentEntity(view.GetCurrentEntity(), view.c->val);
}
}
};
ecs.RegisterSystem<TestCReparentSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 2u);
REQUIRE(ecs.GetParent(ent1) == ent0);
REQUIRE(ecs.GetChildren(ent0).size() == 1u);
REQUIRE(ecs.GetChildren(ent0)[0] == ent1);
}
TEST_CASE("command buffer add", "[ecs]")
{
fw::EcsController ecs;
// generate entities
fw::T_EntityId ent0 = ecs.AddEntity(TestCComponent(fw::INVALID_ENTITY_ID));
fw::T_EntityId ent1 = ecs.AddEntity(TestCComponent(fw::INVALID_ENTITY_ID));
class TestAddSystem final : public fw::System<TestAddSystem, TestCWriteView>
{
public:
TestAddSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestCWriteView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestCWriteView& view : range)
{
view.c->val = cb.AddEntity();
cb.AddComponents(view.c->val, TestAComponent(), TestBComponent(), TestCComponent());
}
}
};
ecs.RegisterSystem<TestAddSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 4u);
fw::T_EntityId addEnt = ecs.GetComponent<TestCComponent>(ent0).val;
REQUIRE(addEnt != fw::INVALID_ENTITY_ID);
REQUIRE(ecs.HasComponent<TestAComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt));
fw::T_EntityId addEnt2 = ecs.GetComponent<TestCComponent>(ent1).val;
REQUIRE(addEnt2 != fw::INVALID_ENTITY_ID);
REQUIRE(ecs.HasComponent<TestAComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt2));
}
<commit_msg>ecs command buffer unit test covers all functionality<commit_after>#include <EtFramework/stdafx.h>
#include "EcsTestUtilities.h"
#include <catch2/catch.hpp>
#include <rttr/registration>
#include <thread>
#include <chrono>
#include <mainTesting.h>
#include <EtFramework/ECS/EcsController.h>
TEST_CASE("command buffer reparent", "[ecs]")
{
fw::EcsController ecs;
// generate entities
fw::T_EntityId ent0 = ecs.AddEntity(TestBComponent(""));
fw::T_EntityId ent1 = ecs.AddEntity(TestCComponent(ent0));
class TestCReparentSystem final : public fw::System<TestCReparentSystem, TestCView>
{
public:
TestCReparentSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestCView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestCView& view : range)
{
cb.ReparentEntity(view.GetCurrentEntity(), view.c->val);
}
}
};
ecs.RegisterSystem<TestCReparentSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 2u);
REQUIRE(ecs.GetParent(ent1) == ent0);
REQUIRE(ecs.GetChildren(ent0).size() == 1u);
REQUIRE(ecs.GetChildren(ent0)[0] == ent1);
}
TEST_CASE("command buffer add / duplicate / remove", "[ecs]")
{
fw::EcsController ecs;
// generate entities
fw::T_EntityId ent0 = ecs.AddEntity(TestCComponent(fw::INVALID_ENTITY_ID));
REQUIRE(ent0 == 0u);
class TestDuplicateSystem final : public fw::System<TestDuplicateSystem, TestCView>
{
public:
TestDuplicateSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestCView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestCView& view : range)
{
cb.DuplicateEntity(view.GetCurrentEntity());
}
}
};
ecs.RegisterSystem<TestDuplicateSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 2u);
REQUIRE(ecs.HasComponent<TestCComponent>(1u));
REQUIRE(ecs.GetComponent<TestCComponent>(1u).val == fw::INVALID_ENTITY_ID);
class TestAddSystem final : public fw::System<TestAddSystem, TestCWriteView>
{
public:
TestAddSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestCWriteView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestCWriteView& view : range)
{
view.c->val = cb.AddEntity();
cb.AddComponents(view.c->val, TestAComponent(), TestBComponent(), TestCComponent());
}
}
};
ecs.UnregisterSystem<TestDuplicateSystem>();
ecs.RegisterSystem<TestAddSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 4u);
fw::T_EntityId addEnt = ecs.GetComponent<TestCComponent>(ent0).val;
REQUIRE(addEnt != fw::INVALID_ENTITY_ID);
REQUIRE(ecs.HasComponent<TestAComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt));
fw::T_EntityId addEnt2 = ecs.GetComponent<TestCComponent>(1u).val;
REQUIRE(addEnt2 != fw::INVALID_ENTITY_ID);
REQUIRE(ecs.HasComponent<TestAComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt2));
class TestRemoveASystem final : public fw::System<TestRemoveASystem, TestBCView>
{
public:
TestRemoveASystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestBCView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestBCView& view : range)
{
cb.RemoveComponents<TestAComponent>(view.GetCurrentEntity());
}
}
};
ecs.UnregisterSystem<TestAddSystem>();
ecs.RegisterSystem<TestRemoveASystem>();
ecs.Process();
REQUIRE_FALSE(ecs.HasComponent<TestAComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt));
REQUIRE_FALSE(ecs.HasComponent<TestAComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestBComponent>(addEnt2));
REQUIRE(ecs.HasComponent<TestCComponent>(addEnt2));
class TestRemoveSystem final : public fw::System<TestRemoveSystem, TestBCView>
{
public:
TestRemoveSystem() = default;
// base class constructors don't do anything so are not needed unless we declare dependencies or init lookup variables
void Process(fw::ComponentRange<TestBCView>& range)
{
fw::EcsCommandBuffer& cb = GetCommandBuffer();
for (TestBCView& view : range)
{
cb.RemoveEntity(view.GetCurrentEntity());
}
}
};
ecs.UnregisterSystem<TestRemoveASystem>();
ecs.RegisterSystem<TestRemoveSystem>();
ecs.Process();
REQUIRE(ecs.GetEntityCount() == 2u);
}
<|endoftext|>
|
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
imshow("webcam", image);
// thresholds on dark regions
Mat black, blurred;
split(image, channel);
black = (channel[0] + channel[1] + channel[2])/3.0;
equalizeHist(black, black);
blur(black, blurred, Size(width/9,height/18));
threshold(blurred, blurred, 220, 255, THRESH_BINARY);
imshow("lol", blurred);
waitKey(1);
merge(channel, 3, black);
blur(black, blurred, Size(width/4.5,height/9));
split(blurred, channel);
black = (channel[0] + channel[1] + channel[2])/3.0;
equalizeHist(black, black);
bitwise_not(black,black);
threshold(black, black, 220, 255, THRESH_BINARY);
imshow("black", black);
/*
split(image, channel);
channel[0] = channel[0].mul(black);
channel[1] = channel[1].mul(black);
channel[2] = channel[2].mul(black);
merge(channel, 3, image);
*/
// imshow("yox", image);
//do some weird morphological closing thing
// Mat channel[3];
/*
Mat canny;
Canny(image, canny, 0, 50);
imshow("canny", canny);
*/
/*
Mat fill = image.clone();
Point seed(rand()%width, rand()%height);
floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
imshow("fill", fill);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
imshow("webcam", image);
// thresholds on dark regions
Mat black, blurred;
split(image, channel);
black = (channel[0] + channel[1] + channel[2])/3.0;
equalizeHist(black, black);
blur(black, blurred, Size(width/9,height/18));
bitwise_not(black,black);
threshold(blurred, blurred, 220, 255, THRESH_BINARY);
imshow("lol", blurred);
waitKey(1);
merge(channel, 3, black);
blur(black, blurred, Size(width/4.5,height/9));
split(blurred, channel);
black = (channel[0] + channel[1] + channel[2])/3.0;
equalizeHist(black, black);
bitwise_not(black,black);
threshold(black, black, 220, 255, THRESH_BINARY);
imshow("black", black);
/*
split(image, channel);
channel[0] = channel[0].mul(black);
channel[1] = channel[1].mul(black);
channel[2] = channel[2].mul(black);
merge(channel, 3, image);
*/
// imshow("yox", image);
//do some weird morphological closing thing
// Mat channel[3];
/*
Mat canny;
Canny(image, canny, 0, 50);
imshow("canny", canny);
*/
/*
Mat fill = image.clone();
Point seed(rand()%width, rand()%height);
floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
imshow("fill", fill);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>vcl: odd conditional whitespacing removed<commit_after><|endoftext|>
|
<commit_before>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat erodeKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, erodeKernel);
Mat dilateKernel = ellipticKernel(69,79);
dilate(smallMask1, smallMask1, dilateKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg
// Mat erodeKernel = ellipticKernel(21);
Mat erodedMask = mask.clone();
// erode(mask, erodedMask, erodeKernel);
Mat mask_;
subtract(1,erodedMask,mask_);
Mat mask3, mask3_;
channel[0] = erodedMask;
channel[1] = erodedMask;
channel[2] = erodedMask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
// background = background.mul(mask3) +
// (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
imshow("MOUTH", image);
*/
for (int i=0; i<6; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat erodeKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, erodeKernel);
Mat dilateKernel = ellipticKernel(69,79);
dilate(smallMask1, smallMask1, dilateKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg
Mat erodedMask;
erode(smallMask1, erodedMask, erodeKernel);
resize(erodedMask, erodedMask, Size(width, height));
Mat mask_;
subtract(1,erodedMask,mask_);
Mat mask3, mask3_;
channel[0] = erodedMask;
channel[1] = erodedMask;
channel[2] = erodedMask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
imshow("MOUTH", image);
*/
for (int i=0; i<6; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvd.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:46:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif
#ifndef _SV_WINCOMP_HXX
#include <wincomp.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif
// =======================================================================
static HBITMAP ImplCreateVirDevBitmap( HDC hDC, long nDX, long nDY,
USHORT nBitCount )
{
HBITMAP hBitmap;
if ( nBitCount == 1 )
hBitmap = CreateBitmap( (int)nDX, (int)nDY, 1, 1, NULL );
else
hBitmap = CreateCompatibleBitmap( hDC, (int)nDX, (int)nDY );
return hBitmap;
}
// =======================================================================
SalVirtualDevice* WinSalInstance::CreateVirtualDevice( SalGraphics* pSGraphics,
long nDX, long nDY,
USHORT nBitCount,
const SystemGraphicsData* pData )
{
WinSalGraphics* pGraphics = static_cast<WinSalGraphics*>(pSGraphics);
HDC hDC = NULL;
HBITMAP hBmp = NULL;
BOOL bOk = FALSE;
if( pData )
{
hDC = pData->hDC;
hBmp = NULL;
bOk = (hDC != NULL);
}
else
{
hDC = CreateCompatibleDC( pGraphics->mhDC );
if( !hDC )
ImplWriteLastError( GetLastError(), "CreateCompatibleDC in CreateVirtualDevice" );
hBmp = ImplCreateVirDevBitmap( pGraphics->mhDC,
nDX, nDY, nBitCount );
if( !hBmp )
ImplWriteLastError( GetLastError(), "ImplCreateVirDevBitmap in CreateVirtualDevice" );
// #124826# continue even if hBmp could not be created
// if we would return a failure in this case, the process
// would terminate which is not required
DBG_ASSERT( hBmp, "WinSalInstance::CreateVirtualDevice(), could not create Bitmap!" );
bOk = (hDC != NULL);
}
if ( bOk )
{
WinSalVirtualDevice* pVDev = new WinSalVirtualDevice;
SalData* pSalData = GetSalData();
WinSalGraphics* pVirGraphics = new WinSalGraphics;
pVirGraphics->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
pVirGraphics->mhDC = hDC;
pVirGraphics->mhWnd = 0;
pVirGraphics->mbPrinter = FALSE;
pVirGraphics->mbVirDev = TRUE;
pVirGraphics->mbWindow = FALSE;
pVirGraphics->mbScreen = pGraphics->mbScreen;
if ( pSalData->mhDitherPal && pVirGraphics->mbScreen )
{
pVirGraphics->mhDefPal = SelectPalette( hDC, pSalData->mhDitherPal, TRUE );
RealizePalette( hDC );
}
ImplSalInitGraphics( pVirGraphics );
pVDev->mhDC = hDC;
pVDev->mhBmp = hBmp;
if( hBmp )
pVDev->mhDefBmp = SelectBitmap( hDC, hBmp );
else
pVDev->mhDefBmp = NULL;
pVDev->mpGraphics = pVirGraphics;
pVDev->mnBitCount = nBitCount;
pVDev->mbGraphics = FALSE;
pVDev->mbForeignDC = (pData != NULL);
// insert VirDev in VirDevList
pVDev->mpNext = pSalData->mpFirstVD;
pSalData->mpFirstVD = pVDev;
return pVDev;
}
else
{
if ( hDC && !pData )
DeleteDC( hDC );
if ( hBmp )
DeleteBitmap( hBmp );
return NULL;
}
}
// -----------------------------------------------------------------------
void WinSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// =======================================================================
WinSalVirtualDevice::WinSalVirtualDevice()
{
mhDC = (HDC) NULL; // HDC or 0 for Cache Device
mhBmp = (HBITMAP) NULL; // Memory Bitmap
mhDefBmp = (HBITMAP) NULL; // Default Bitmap
mpGraphics = NULL; // current VirDev graphics
mpNext = NULL; // next VirDev
mnBitCount = 0; // BitCount (0 or 1)
mbGraphics = FALSE; // is Graphics used
mbForeignDC = FALSE; // uses a foreign DC instead of a bitmap
}
// -----------------------------------------------------------------------
WinSalVirtualDevice::~WinSalVirtualDevice()
{
// remove VirDev from list of virtual devices
SalData* pSalData = GetSalData();
WinSalVirtualDevice** ppVirDev = &pSalData->mpFirstVD;
for(; (*ppVirDev != this) && *ppVirDev; ppVirDev = &(*ppVirDev)->mpNext );
if( *ppVirDev )
*ppVirDev = mpNext;
// destroy saved DC
if( mpGraphics->mhDefPal )
SelectPalette( mpGraphics->mhDC, mpGraphics->mhDefPal, TRUE );
ImplSalDeInitGraphics( mpGraphics );
if( mhDefBmp )
SelectBitmap( mpGraphics->mhDC, mhDefBmp );
if( !mbForeignDC )
DeleteDC( mpGraphics->mhDC );
if( mhBmp )
DeleteBitmap( mhBmp );
delete mpGraphics;
mpGraphics = NULL;
}
// -----------------------------------------------------------------------
SalGraphics* WinSalVirtualDevice::GetGraphics()
{
if ( mbGraphics )
return NULL;
if ( mpGraphics )
mbGraphics = TRUE;
return mpGraphics;
}
// -----------------------------------------------------------------------
void WinSalVirtualDevice::ReleaseGraphics( SalGraphics* )
{
mbGraphics = FALSE;
}
// -----------------------------------------------------------------------
BOOL WinSalVirtualDevice::SetSize( long nDX, long nDY )
{
if( mbForeignDC || !mhBmp )
return TRUE; // ???
else
{
HBITMAP hNewBmp = ImplCreateVirDevBitmap( mhDC, nDX, nDY,
mnBitCount );
if ( hNewBmp )
{
SelectBitmap( mhDC, hNewBmp );
DeleteBitmap( mhBmp );
mhBmp = hNewBmp;
return TRUE;
}
else
{
ImplWriteLastError( GetLastError(), "ImplCreateVirDevBitmap in SetSize" );
return FALSE;
}
}
}
void WinSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
rWidth = GetDeviceCaps( mhDC, HORZRES );
rHeight= GetDeviceCaps( mhDC, VERTRES );
}
<commit_msg>INTEGRATION: CWS vcl78 (1.11.210); FILE MERGED 2007/04/26 14:21:57 thb 1.11.210.1: #146839# Replaced CreateCompatibleBitmap() with CreateDIBSection() - the latter does not run out of mem so fast<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvd.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2007-06-11 14:26:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif
#ifndef _SV_WINCOMP_HXX
#include <wincomp.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif
// =======================================================================
static HBITMAP ImplCreateVirDevBitmap( HDC hDC, long nDX, long nDY,
USHORT nBitCount )
{
HBITMAP hBitmap;
if ( nBitCount == 1 )
{
hBitmap = CreateBitmap( (int)nDX, (int)nDY, 1, 1, NULL );
}
else
{
// #146839# Don't use CreateCompatibleBitmap() - there seem to
// be build-in limits for those HBITMAPs, at least this fails
// rather often on large displays/multi-monitor setups.
BITMAPINFO aBitmapInfo;
aBitmapInfo.bmiHeader.biSize = sizeof( BITMAPINFOHEADER );
aBitmapInfo.bmiHeader.biWidth = nDX;
aBitmapInfo.bmiHeader.biHeight = nDY;
aBitmapInfo.bmiHeader.biPlanes = 1;
aBitmapInfo.bmiHeader.biBitCount = (WORD)GetDeviceCaps( hDC,
BITSPIXEL );
aBitmapInfo.bmiHeader.biCompression = BI_RGB;
aBitmapInfo.bmiHeader.biSizeImage = 0;
aBitmapInfo.bmiHeader.biXPelsPerMeter = 0;
aBitmapInfo.bmiHeader.biYPelsPerMeter = 0;
aBitmapInfo.bmiHeader.biClrUsed = 0;
aBitmapInfo.bmiHeader.biClrImportant = 0;
void* pDummy;
hBitmap = CreateDIBSection( hDC, &aBitmapInfo,
DIB_RGB_COLORS, &pDummy, NULL,
0 );
}
return hBitmap;
}
// =======================================================================
SalVirtualDevice* WinSalInstance::CreateVirtualDevice( SalGraphics* pSGraphics,
long nDX, long nDY,
USHORT nBitCount,
const SystemGraphicsData* pData )
{
WinSalGraphics* pGraphics = static_cast<WinSalGraphics*>(pSGraphics);
HDC hDC = NULL;
HBITMAP hBmp = NULL;
BOOL bOk = FALSE;
if( pData )
{
hDC = pData->hDC;
hBmp = NULL;
bOk = (hDC != NULL);
}
else
{
hDC = CreateCompatibleDC( pGraphics->mhDC );
if( !hDC )
ImplWriteLastError( GetLastError(), "CreateCompatibleDC in CreateVirtualDevice" );
hBmp = ImplCreateVirDevBitmap( pGraphics->mhDC,
nDX, nDY, nBitCount );
if( !hBmp )
ImplWriteLastError( GetLastError(), "ImplCreateVirDevBitmap in CreateVirtualDevice" );
// #124826# continue even if hBmp could not be created
// if we would return a failure in this case, the process
// would terminate which is not required
DBG_ASSERT( hBmp, "WinSalInstance::CreateVirtualDevice(), could not create Bitmap!" );
bOk = (hDC != NULL);
}
if ( bOk )
{
WinSalVirtualDevice* pVDev = new WinSalVirtualDevice;
SalData* pSalData = GetSalData();
WinSalGraphics* pVirGraphics = new WinSalGraphics;
pVirGraphics->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
pVirGraphics->mhDC = hDC;
pVirGraphics->mhWnd = 0;
pVirGraphics->mbPrinter = FALSE;
pVirGraphics->mbVirDev = TRUE;
pVirGraphics->mbWindow = FALSE;
pVirGraphics->mbScreen = pGraphics->mbScreen;
if ( pSalData->mhDitherPal && pVirGraphics->mbScreen )
{
pVirGraphics->mhDefPal = SelectPalette( hDC, pSalData->mhDitherPal, TRUE );
RealizePalette( hDC );
}
ImplSalInitGraphics( pVirGraphics );
pVDev->mhDC = hDC;
pVDev->mhBmp = hBmp;
if( hBmp )
pVDev->mhDefBmp = SelectBitmap( hDC, hBmp );
else
pVDev->mhDefBmp = NULL;
pVDev->mpGraphics = pVirGraphics;
pVDev->mnBitCount = nBitCount;
pVDev->mbGraphics = FALSE;
pVDev->mbForeignDC = (pData != NULL);
// insert VirDev in VirDevList
pVDev->mpNext = pSalData->mpFirstVD;
pSalData->mpFirstVD = pVDev;
return pVDev;
}
else
{
if ( hDC && !pData )
DeleteDC( hDC );
if ( hBmp )
DeleteBitmap( hBmp );
return NULL;
}
}
// -----------------------------------------------------------------------
void WinSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// =======================================================================
WinSalVirtualDevice::WinSalVirtualDevice()
{
mhDC = (HDC) NULL; // HDC or 0 for Cache Device
mhBmp = (HBITMAP) NULL; // Memory Bitmap
mhDefBmp = (HBITMAP) NULL; // Default Bitmap
mpGraphics = NULL; // current VirDev graphics
mpNext = NULL; // next VirDev
mnBitCount = 0; // BitCount (0 or 1)
mbGraphics = FALSE; // is Graphics used
mbForeignDC = FALSE; // uses a foreign DC instead of a bitmap
}
// -----------------------------------------------------------------------
WinSalVirtualDevice::~WinSalVirtualDevice()
{
// remove VirDev from list of virtual devices
SalData* pSalData = GetSalData();
WinSalVirtualDevice** ppVirDev = &pSalData->mpFirstVD;
for(; (*ppVirDev != this) && *ppVirDev; ppVirDev = &(*ppVirDev)->mpNext );
if( *ppVirDev )
*ppVirDev = mpNext;
// destroy saved DC
if( mpGraphics->mhDefPal )
SelectPalette( mpGraphics->mhDC, mpGraphics->mhDefPal, TRUE );
ImplSalDeInitGraphics( mpGraphics );
if( mhDefBmp )
SelectBitmap( mpGraphics->mhDC, mhDefBmp );
if( !mbForeignDC )
DeleteDC( mpGraphics->mhDC );
if( mhBmp )
DeleteBitmap( mhBmp );
delete mpGraphics;
mpGraphics = NULL;
}
// -----------------------------------------------------------------------
SalGraphics* WinSalVirtualDevice::GetGraphics()
{
if ( mbGraphics )
return NULL;
if ( mpGraphics )
mbGraphics = TRUE;
return mpGraphics;
}
// -----------------------------------------------------------------------
void WinSalVirtualDevice::ReleaseGraphics( SalGraphics* )
{
mbGraphics = FALSE;
}
// -----------------------------------------------------------------------
BOOL WinSalVirtualDevice::SetSize( long nDX, long nDY )
{
if( mbForeignDC || !mhBmp )
return TRUE; // ???
else
{
HBITMAP hNewBmp = ImplCreateVirDevBitmap( mhDC, nDX, nDY,
mnBitCount );
if ( hNewBmp )
{
SelectBitmap( mhDC, hNewBmp );
DeleteBitmap( mhBmp );
mhBmp = hNewBmp;
return TRUE;
}
else
{
ImplWriteLastError( GetLastError(), "ImplCreateVirDevBitmap in SetSize" );
return FALSE;
}
}
}
void WinSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
rWidth = GetDeviceCaps( mhDC, HORZRES );
rHeight= GetDeviceCaps( mhDC, VERTRES );
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "launcherlogging.h"
#include "launchersockethandler.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qtimer.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
BOOL WINAPI consoleCtrlHandler(DWORD)
{
// Ignore Ctrl-C / Ctrl-Break. Qbs will tell us to exit gracefully.
return TRUE;
}
#endif
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
SetConsoleCtrlHandler(consoleCtrlHandler, TRUE);
#endif
QCoreApplication app(argc, argv);
if (app.arguments().size() != 2) {
qbs::Internal::logError("Need exactly one argument (path to socket)");
return 1;
}
qbs::Internal::LauncherSocketHandler launcher(app.arguments().last());
QTimer::singleShot(0, &launcher, &qbs::Internal::LauncherSocketHandler::start);
return app.exec();
}
<commit_msg>Fix license header in qbs_processlauncher<commit_after>/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/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 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "launcherlogging.h"
#include "launchersockethandler.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qtimer.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
BOOL WINAPI consoleCtrlHandler(DWORD)
{
// Ignore Ctrl-C / Ctrl-Break. Qbs will tell us to exit gracefully.
return TRUE;
}
#endif
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
SetConsoleCtrlHandler(consoleCtrlHandler, TRUE);
#endif
QCoreApplication app(argc, argv);
if (app.arguments().size() != 2) {
qbs::Internal::logError("Need exactly one argument (path to socket)");
return 1;
}
qbs::Internal::LauncherSocketHandler launcher(app.arguments().last());
QTimer::singleShot(0, &launcher, &qbs::Internal::LauncherSocketHandler::start);
return app.exec();
}
<|endoftext|>
|
<commit_before>//individual.cpp
#include <vector>
#include <cstdlib>
#include <iostream>
#include "individual.hpp"
#include "utils.hpp"
Individual::Individual(){
expression = new Node();
}
Individual::~Individual(){
delete expression;
}
Node *Individual::crossover(double crossover_rate, Individual parent){
}
void Individual::mutation(double mutation_rate){
double rate = mutation_rate*100;
if (random()%100<rate){
int new_tipo = random() %utils::SIZETYPE;
std::cout << "new tipo: " << new_tipo << std::endl;
switch (new_tipo){
case utils::VAR:
expression->set_C(utils::VAR, random()%2);
break;
case utils::CTE:
expression->set_C(utils::CTE, random()%10);
break;
case utils::FUN1:
expression->set_C(utils::FUN1, random()%utils::SIZEFUNC1);
break;
case utils::FUN2:
expression->set_C(utils::FUN2, random()%utils::SIZEFUNC2);
break;
}
}
}
double Individual::fitness(std::vector<utils::DataPoint> points){
double mse = 0.0;
for(int i=0; i<points.size(); i++){
mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2);
}
this->mse_value = utils::uSqrt(mse/(double)points.size());
return this->mse_value;
}
void Individual::print_expression_d(){
expression->print_node_d();
}
<commit_msg>1.1.1 Apagado implementação ruim de mutation<commit_after>//individual.cpp
#include <vector>
#include <cstdlib>
#include <iostream>
#include "individual.hpp"
#include "utils.hpp"
Individual::Individual(){
expression = new Node();
}
Individual::~Individual(){
delete expression;
}
Node *Individual::crossover(double crossover_rate, Individual parent){
}
void Individual::mutation(double mutation_rate){
//falta implementar aqui
}
double Individual::fitness(std::vector<utils::DataPoint> points){
double mse = 0.0;
for(int i=0; i<points.size(); i++){
mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2);
}
this->mse_value = utils::uSqrt(mse/(double)points.size());
return this->mse_value;
}
void Individual::print_expression_d(){
expression->print_node_d();
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file GUIComponent.cpp
//! @author Flumes <flumes@lists.iei.liu.se>
//! @date 2010-01-01
//!
//! @brief Contains the GUI class representing Components
//!
//$Id$
#include <QDrag>
#include "GUIComponent.h"
#include "GUIContainerObject.h"
#include "Dialogs/ComponentPropertiesDialog.h"
#include "GUIPort.h"
#include "Widgets/ProjectTabWidget.h"
#include "GraphicsView.h"
GUIComponent::GUIComponent(QPointF position, qreal rotation, GUIModelObjectAppearance* pAppearanceData, GUIContainerObject *pParentContainer, selectionStatus startSelected, graphicsType gfxType)
: GUIModelObject(position, rotation, pAppearanceData, startSelected, gfxType, pParentContainer, pParentContainer)
{
//Set the hmf save tag name
mHmfTagName = HMF_COMPONENTTAG;
//Create the object in core, and get its default core name
mGUIModelObjectAppearance.setName(mpParentContainerObject->getCoreSystemAccessPtr()->createComponent(mGUIModelObjectAppearance.getTypeName(), mGUIModelObjectAppearance.getName()));
//Sets the ports
createPorts();
refreshDisplayName(); //Make sure name window is correct size for center positioning
//Component shall be hidden when toggle signals is deactivated, if it is of signal type and has no power ports (= is a sensor)
if(this->getTypeCQS() == "S" && !this->hasPowerPorts())
{
connect(gpMainWindow->mpToggleSignalsAction, SIGNAL(toggled(bool)), this, SLOT(setVisible(bool)));
}
QStringList defaultParameterNames = getParameterNames();
for(int i=0; i<defaultParameterNames.size(); ++i)
{
mDefaultParameters.insert(defaultParameterNames.at(i), getParameterValue(defaultParameterNames.at(i)));
}
}
GUIComponent::~GUIComponent()
{
//Remove in core
//! @todo maybe change to delte instead of remove with dodelete yes
mpParentContainerObject->getCoreSystemAccessPtr()->removeSubComponent(this->getName(), true);
}
//! @brief Returns whether or not the component has at least one power port
bool GUIComponent::hasPowerPorts()
{
bool retval = false;
for(int i=0; i<mPortListPtrs.size(); ++i)
{
if(mPortListPtrs.at(i)->getNodeType() != "NodeSignal")
{
retval = true;
}
}
return retval;
}
//! Event when double clicking on component icon.
void GUIComponent::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if(!mpParentContainerObject->mpParentProjectTab->isEditingEnabled())
return;
QGraphicsWidget::mouseDoubleClickEvent(event);
//std::cout << "GUIComponent.cpp: " << "mouseDoubleClickEvent " << std::endl;
//If this is a sink component that has plot data, plot it instead of showing the dialog
if(this->getTypeName() == "SignalSink" && this->getPort("in")->isConnected() && this->mpParentContainerObject->getAllPlotData().size() > 0) //Not very nice code, but a nice feature...
{
PlotWindow *pPlotWindow = getPort("in")->getConnectedPorts().first()->plot("Value");
for(int i=1; (i<getPort("in")->getConnectedPorts().size() && pPlotWindow != 0); ++i)
{
if(!pPlotWindow)
{
pPlotWindow = getPort("in")->getConnectedPorts().at(i)->plot("Value");
}
else
{
getPort("in")->getConnectedPorts().at(i)->plotToPlotWindow(pPlotWindow, "Value");
}
}
if(!pPlotWindow)
{
openPropertiesDialog();
}
}
else
openPropertiesDialog();
}
//! Returns a string with the component type.
QString GUIComponent::getTypeName()
{
return mGUIModelObjectAppearance.getTypeName();
}
QString GUIComponent::getTypeCQS()
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getSubComponentTypeCQS(this->getName());
}
void GUIComponent::getParameters(QVector<QString> &qParameterNames, QVector<QString> &qParameterValues, QVector<QString> &qDescriptions, QVector<QString> &qUnits, QVector<QString> &qTypes)
{
mpParentContainerObject->getCoreSystemAccessPtr()->getParameters(this->getName(), qParameterNames, qParameterValues, qDescriptions, qUnits, qTypes);
}
//! @brief Get a vector with the names of the available parameters
QStringList GUIComponent::getParameterNames()
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterNames(this->getName());
}
QString GUIComponent::getParameterUnit(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterUnit(this->getName(), name);
}
QString GUIComponent::getParameterDescription(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterDescription(this->getName(), name);
}
QString GUIComponent::getParameterValue(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValue(this->getName(), name);
}
//QString GUIComponent::getParameterValueTxt(QString name)
//{
// return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValueTxt(this->getName(), name);
//}
//! @brief Set a parameter value to be mapped to a System parameter
bool GUIComponent::setParameterValue(QString name, QString sysParName, bool force)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->setParameter(this->getName(), name, sysParName, force);
}
//! @brief Set a start value to be mapped to a System parameter
bool GUIComponent::setStartValue(QString portName, QString variable, QString sysParName)
{
// QVector<QString> vVariable;
// QVector<QString> vSysParName;
// vVariable.append(variable);
// vSysParName.append(sysParName);
// return this->getPort(portName)->setStartValueDataByNames(vVariable, vSysParName);
QString dataName;
dataName = portName + QString("::Value");
return mpParentContainerObject->getCoreSystemAccessPtr()->setParameter(this->getName(), dataName, sysParName);
}
//! @brief Set a start value to be mapped to a System parameter
QString GUIComponent::getStartValueTxt(QString portName, QString variable)
{
QVector<QString> vVariable, vSysParName, vUnit;
this->getPort(portName)->getStartValueDataNamesValuesAndUnits(vVariable, vSysParName, vUnit);
int idx = vVariable.indexOf(variable);
if(idx < 0)
return "";
else
return vSysParName[idx];
}
//! @brief Slot that opens the parameter dialog for the component
void GUIComponent::openPropertiesDialog()
{
ComponentPropertiesDialog *pDialog = new ComponentPropertiesDialog(this, gpMainWindow);
pDialog->exec();
delete pDialog;
}
//! @brief Help function to create ports in the component when it is created
void GUIComponent::createPorts()
{
//! @todo make sure that all old ports and connections are cleared, (not really necessary in guicomponents)
QString cqsType = mpParentContainerObject->getCoreSystemAccessPtr()->getSubComponentTypeCQS(getName());
PortAppearanceMapT::iterator i;
for (i = mGUIModelObjectAppearance.getPortAppearanceMap().begin(); i != mGUIModelObjectAppearance.getPortAppearanceMap().end(); ++i)
{
QString nodeType = mpParentContainerObject->getCoreSystemAccessPtr()->getNodeType(this->getName(), i.key());
QString portType = mpParentContainerObject->getCoreSystemAccessPtr()->getPortType(this->getName(), i.key());
i.value().selectPortIcon(cqsType, portType, nodeType);
qreal x = i.value().x * this->boundingRect().width();
qreal y = i.value().y * this->boundingRect().height();
GUIPort *pNewPort = new GUIPort(i.key(), x, y, &(i.value()), this);
mPortListPtrs.append(pNewPort);
}
}
int GUIComponent::type() const
{
return Type;
}
QString GUIComponent::getDefaultParameter(QString name)
{
if(mDefaultParameters.contains(name))
return mDefaultParameters.find(name).value();
else
return QString();
}
void GUIComponent::setVisible(bool visible)
{
this->mpIcon->setVisible(visible);
}
//! @brief Save component coredata to XML Dom Element
//! @param[in] rDomElement The dom element to save to
void GUIComponent::saveCoreDataToDomElement(QDomElement &rDomElement)
{
GUIModelObject::saveCoreDataToDomElement(rDomElement);
//Save parameters (also core related)
QDomElement xmlParameters = appendDomElement(rDomElement, HMF_PARAMETERS);
//! @todo need more efficient fetching of both par names and values in one call to avoid re-searching every time
QVector<QString> parameterNames, parameterValues, descriptions, units, types;
getParameters(parameterNames, parameterValues, descriptions, units, types);
QVector<QString>::iterator pit;
for(pit = parameterNames.begin(); pit != parameterNames.end(); ++pit)
{
QDomElement xmlParam = appendDomElement(xmlParameters, HMF_PARAMETERTAG);
xmlParam.setAttribute(HMF_NAMETAG, *pit);
xmlParam.setAttribute(HMF_VALUETAG, mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValue(this->getName(), (*pit)));
/*if(this->isParameterMappedToSystemParameter(*pit))
{
xmlParam.setAttribute(HMF_SYSTEMPARAMETERTAG, this->getSystemParameterKey(*pit));
}*/
}
//Save start values //Is not needed, start values are saved as ordinary parameters! This code snippet can probably be removed.
// QDomElement xmlStartValues = appendDomElement(rDomElement, HMF_STARTVALUES);
// QVector<QString> startValueNames;
// QVector<QString> startValueValuesTxt;
// QVector<QString> dummy;
// QList<GUIPort*>::iterator portIt;
// for(portIt = mPortListPtrs.begin(); portIt != mPortListPtrs.end(); ++portIt)
// {
// mpParentContainerObject->getCoreSystemAccessPtr()->getStartValueDataNamesValuesAndUnits(this->getName(), (*portIt)->getPortName(), startValueNames, startValueValuesTxt, dummy);
// if((!startValueNames.empty()))
// {
// for(int i = 0; i < startValueNames.size(); ++i)
// {
// QDomElement xmlStartValue = appendDomElement(xmlStartValues, "startvalue");
// xmlStartValue.setAttribute("portname", (*portIt)->getPortName());
// xmlStartValue.setAttribute("variable", startValueNames[i]);
// xmlStartValue.setAttribute("value", startValueValuesTxt[i]);
// }
// }
// }
}
<commit_msg>Fixed crash when double clicking sink while creating connector<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file GUIComponent.cpp
//! @author Flumes <flumes@lists.iei.liu.se>
//! @date 2010-01-01
//!
//! @brief Contains the GUI class representing Components
//!
//$Id$
#include <QDrag>
#include "GUIComponent.h"
#include "GUIContainerObject.h"
#include "Dialogs/ComponentPropertiesDialog.h"
#include "GUIPort.h"
#include "Widgets/ProjectTabWidget.h"
#include "GraphicsView.h"
GUIComponent::GUIComponent(QPointF position, qreal rotation, GUIModelObjectAppearance* pAppearanceData, GUIContainerObject *pParentContainer, selectionStatus startSelected, graphicsType gfxType)
: GUIModelObject(position, rotation, pAppearanceData, startSelected, gfxType, pParentContainer, pParentContainer)
{
//Set the hmf save tag name
mHmfTagName = HMF_COMPONENTTAG;
//Create the object in core, and get its default core name
mGUIModelObjectAppearance.setName(mpParentContainerObject->getCoreSystemAccessPtr()->createComponent(mGUIModelObjectAppearance.getTypeName(), mGUIModelObjectAppearance.getName()));
//Sets the ports
createPorts();
refreshDisplayName(); //Make sure name window is correct size for center positioning
//Component shall be hidden when toggle signals is deactivated, if it is of signal type and has no power ports (= is a sensor)
if(this->getTypeCQS() == "S" && !this->hasPowerPorts())
{
connect(gpMainWindow->mpToggleSignalsAction, SIGNAL(toggled(bool)), this, SLOT(setVisible(bool)));
}
QStringList defaultParameterNames = getParameterNames();
for(int i=0; i<defaultParameterNames.size(); ++i)
{
mDefaultParameters.insert(defaultParameterNames.at(i), getParameterValue(defaultParameterNames.at(i)));
}
}
GUIComponent::~GUIComponent()
{
//Remove in core
//! @todo maybe change to delte instead of remove with dodelete yes
mpParentContainerObject->getCoreSystemAccessPtr()->removeSubComponent(this->getName(), true);
}
//! @brief Returns whether or not the component has at least one power port
bool GUIComponent::hasPowerPorts()
{
bool retval = false;
for(int i=0; i<mPortListPtrs.size(); ++i)
{
if(mPortListPtrs.at(i)->getNodeType() != "NodeSignal")
{
retval = true;
}
}
return retval;
}
//! Event when double clicking on component icon.
void GUIComponent::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if(!mpParentContainerObject->mpParentProjectTab->isEditingEnabled())
return;
QGraphicsWidget::mouseDoubleClickEvent(event);
//std::cout << "GUIComponent.cpp: " << "mouseDoubleClickEvent " << std::endl;
//If this is a sink component that has plot data, plot it instead of showing the dialog
if(this->getTypeName() == "SignalSink" && this->getPort("in")->isConnected() && this->mpParentContainerObject->getAllPlotData().size() > 0 && !mpParentContainerObject->isCreatingConnector()) //Not very nice code, but a nice feature...
{
PlotWindow *pPlotWindow = getPort("in")->getConnectedPorts().first()->plot("Value");
for(int i=1; (i<getPort("in")->getConnectedPorts().size() && pPlotWindow != 0); ++i)
{
if(!pPlotWindow)
{
pPlotWindow = getPort("in")->getConnectedPorts().at(i)->plot("Value");
}
else
{
getPort("in")->getConnectedPorts().at(i)->plotToPlotWindow(pPlotWindow, "Value");
}
}
if(!pPlotWindow)
{
openPropertiesDialog();
}
}
else
openPropertiesDialog();
}
//! Returns a string with the component type.
QString GUIComponent::getTypeName()
{
return mGUIModelObjectAppearance.getTypeName();
}
QString GUIComponent::getTypeCQS()
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getSubComponentTypeCQS(this->getName());
}
void GUIComponent::getParameters(QVector<QString> &qParameterNames, QVector<QString> &qParameterValues, QVector<QString> &qDescriptions, QVector<QString> &qUnits, QVector<QString> &qTypes)
{
mpParentContainerObject->getCoreSystemAccessPtr()->getParameters(this->getName(), qParameterNames, qParameterValues, qDescriptions, qUnits, qTypes);
}
//! @brief Get a vector with the names of the available parameters
QStringList GUIComponent::getParameterNames()
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterNames(this->getName());
}
QString GUIComponent::getParameterUnit(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterUnit(this->getName(), name);
}
QString GUIComponent::getParameterDescription(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterDescription(this->getName(), name);
}
QString GUIComponent::getParameterValue(QString name)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValue(this->getName(), name);
}
//QString GUIComponent::getParameterValueTxt(QString name)
//{
// return mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValueTxt(this->getName(), name);
//}
//! @brief Set a parameter value to be mapped to a System parameter
bool GUIComponent::setParameterValue(QString name, QString sysParName, bool force)
{
return mpParentContainerObject->getCoreSystemAccessPtr()->setParameter(this->getName(), name, sysParName, force);
}
//! @brief Set a start value to be mapped to a System parameter
bool GUIComponent::setStartValue(QString portName, QString variable, QString sysParName)
{
// QVector<QString> vVariable;
// QVector<QString> vSysParName;
// vVariable.append(variable);
// vSysParName.append(sysParName);
// return this->getPort(portName)->setStartValueDataByNames(vVariable, vSysParName);
QString dataName;
dataName = portName + QString("::Value");
return mpParentContainerObject->getCoreSystemAccessPtr()->setParameter(this->getName(), dataName, sysParName);
}
//! @brief Set a start value to be mapped to a System parameter
QString GUIComponent::getStartValueTxt(QString portName, QString variable)
{
QVector<QString> vVariable, vSysParName, vUnit;
this->getPort(portName)->getStartValueDataNamesValuesAndUnits(vVariable, vSysParName, vUnit);
int idx = vVariable.indexOf(variable);
if(idx < 0)
return "";
else
return vSysParName[idx];
}
//! @brief Slot that opens the parameter dialog for the component
void GUIComponent::openPropertiesDialog()
{
ComponentPropertiesDialog *pDialog = new ComponentPropertiesDialog(this, gpMainWindow);
pDialog->exec();
delete pDialog;
}
//! @brief Help function to create ports in the component when it is created
void GUIComponent::createPorts()
{
//! @todo make sure that all old ports and connections are cleared, (not really necessary in guicomponents)
QString cqsType = mpParentContainerObject->getCoreSystemAccessPtr()->getSubComponentTypeCQS(getName());
PortAppearanceMapT::iterator i;
for (i = mGUIModelObjectAppearance.getPortAppearanceMap().begin(); i != mGUIModelObjectAppearance.getPortAppearanceMap().end(); ++i)
{
QString nodeType = mpParentContainerObject->getCoreSystemAccessPtr()->getNodeType(this->getName(), i.key());
QString portType = mpParentContainerObject->getCoreSystemAccessPtr()->getPortType(this->getName(), i.key());
i.value().selectPortIcon(cqsType, portType, nodeType);
qreal x = i.value().x * this->boundingRect().width();
qreal y = i.value().y * this->boundingRect().height();
GUIPort *pNewPort = new GUIPort(i.key(), x, y, &(i.value()), this);
mPortListPtrs.append(pNewPort);
}
}
int GUIComponent::type() const
{
return Type;
}
QString GUIComponent::getDefaultParameter(QString name)
{
if(mDefaultParameters.contains(name))
return mDefaultParameters.find(name).value();
else
return QString();
}
void GUIComponent::setVisible(bool visible)
{
this->mpIcon->setVisible(visible);
}
//! @brief Save component coredata to XML Dom Element
//! @param[in] rDomElement The dom element to save to
void GUIComponent::saveCoreDataToDomElement(QDomElement &rDomElement)
{
GUIModelObject::saveCoreDataToDomElement(rDomElement);
//Save parameters (also core related)
QDomElement xmlParameters = appendDomElement(rDomElement, HMF_PARAMETERS);
//! @todo need more efficient fetching of both par names and values in one call to avoid re-searching every time
QVector<QString> parameterNames, parameterValues, descriptions, units, types;
getParameters(parameterNames, parameterValues, descriptions, units, types);
QVector<QString>::iterator pit;
for(pit = parameterNames.begin(); pit != parameterNames.end(); ++pit)
{
QDomElement xmlParam = appendDomElement(xmlParameters, HMF_PARAMETERTAG);
xmlParam.setAttribute(HMF_NAMETAG, *pit);
xmlParam.setAttribute(HMF_VALUETAG, mpParentContainerObject->getCoreSystemAccessPtr()->getParameterValue(this->getName(), (*pit)));
/*if(this->isParameterMappedToSystemParameter(*pit))
{
xmlParam.setAttribute(HMF_SYSTEMPARAMETERTAG, this->getSystemParameterKey(*pit));
}*/
}
//Save start values //Is not needed, start values are saved as ordinary parameters! This code snippet can probably be removed.
// QDomElement xmlStartValues = appendDomElement(rDomElement, HMF_STARTVALUES);
// QVector<QString> startValueNames;
// QVector<QString> startValueValuesTxt;
// QVector<QString> dummy;
// QList<GUIPort*>::iterator portIt;
// for(portIt = mPortListPtrs.begin(); portIt != mPortListPtrs.end(); ++portIt)
// {
// mpParentContainerObject->getCoreSystemAccessPtr()->getStartValueDataNamesValuesAndUnits(this->getName(), (*portIt)->getPortName(), startValueNames, startValueValuesTxt, dummy);
// if((!startValueNames.empty()))
// {
// for(int i = 0; i < startValueNames.size(); ++i)
// {
// QDomElement xmlStartValue = appendDomElement(xmlStartValues, "startvalue");
// xmlStartValue.setAttribute("portname", (*portIt)->getPortName());
// xmlStartValue.setAttribute("variable", startValueNames[i]);
// xmlStartValue.setAttribute("value", startValueValuesTxt[i]);
// }
// }
// }
}
<|endoftext|>
|
<commit_before>//
// inpalprime.cpp
// InPal
//
// Created by Bryan Triana on 6/21/16.
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpalprime.hpp"
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
long long inpal::max_prime(long long n)
{
auto primes = prime_sieve(n);
auto it = std::find(primes.rbegin(), primes.rend(), true);
return primes.size()-std::distance(primes.rbegin(), it)-1;
}
long long inpal::count_primes(long long n)
{
auto primes = prime_sieve(n);
return std::count(primes.begin(), primes.end(), true);
}
long double inpal::prime_density(long double h)
{
return count_primes(h)/h;
}
bool inpal::prime_test(long long p)
{
return p == max_prime(p);
}
bool inpal::twin_test(long long p)
{
auto primes = prime_sieve(p+2);
return p!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]);
}
bool inpal::cousin_test(long long p)
{
auto primes = prime_sieve(p+4);
return p!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]);
}
bool inpal::sexy_test(long long p)
{
auto primes = prime_sieve(p+6);
return (p!=2 && p!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]);
}
long long inpal::max_palprime(long long n)
{
auto primes = prime_sieve(n);
for(std::vector<bool>::size_type it=primes.size()-1; it!=1; it--)
{
if(primes[it] && pal_test(it))
{
return it;
}
}
return 0;
}
long long inpal::max_factor(long long f)
{
return factorizer(f).back();
}
long long inpal::count_factors(long long f)
{
return factorizer(f).size();
}
std::vector<bool> inpal::prime_sieve(long long m)
{
std::vector<bool> p_test(m+1, false);
//defines square root of m
unsigned long long root = ceil(sqrt(m));
//sieve axioms
for(unsigned long long x=1; x<=root; x++)
{
for(long long y=1; y<=root; y++)
{
long long i=(4*x*x)+(y*y);
if (i<=m && (i%12==1 || i%12==5))
{
p_test[i].flip();
}
i=(3*x*x)+(y*y);
if(i<=m && i%12==7)
{
p_test[i].flip();
}
i=(3*x*x)-(y*y);
if(x>y && i<=m && i%12==11)
{
p_test[i].flip();
}
}
}
//marks 2,3,5 and 7 as prime numbers
p_test[2]=p_test[3]=p_test[5]=p_test[7]=true;
//marks all multiples of primes as non primes
for(long long r=5; r<=root; r++)
{
if((p_test[r]))
{
for(long long j=r*r; j<=m; j+=r*r)
{
p_test[j]=false;
}
}
}
return p_test;
}
std::vector<long long> inpal::factorizer(long long f)
{
std::vector<long long> p_fac;
long long p = 3;
//removes factors of 2
while(f%2==0)
{
p_fac.push_back(2);
f=f/2;
}
//finds prime factors of f
while(f!=1)
{
while(f%p==0)
{
p_fac.push_back(p);
f=f/p;
}
p+=2;
}
return p_fac;
}
bool inpal::pal_test(long long n)
{
//converts n to a string
std::string rev = std::to_string(n);
//checks if the reverse of rev is equal to rev
for(int i=0; i<rev.size()/2; i++)
{
if(rev[i]!=rev[rev.size()-1-i])
{
return false;
}
}
return true;
}
<commit_msg>code simplification<commit_after>//
// inpalprime.cpp
// InPal
//
// Created by Bryan Triana on 6/21/16.
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpalprime.hpp"
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
long long inpal::max_prime(long long n)
{
auto primes = prime_sieve(n);
auto it = std::find(primes.rbegin(), primes.rend(), true);
return primes.size()-std::distance(primes.rbegin(), it)-1;
}
long long inpal::count_primes(long long n)
{
auto primes = prime_sieve(n);
return std::count(primes.begin(), primes.end(), true);
}
long double inpal::prime_density(long double h)
{
return count_primes(h)/h;
}
bool inpal::prime_test(long long p)
{
return p == max_prime(p);
}
bool inpal::twin_test(long long p)
{
auto primes = prime_sieve(p+2);
return p!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]);
}
bool inpal::cousin_test(long long p)
{
auto primes = prime_sieve(p+4);
return p!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]);
}
bool inpal::sexy_test(long long p)
{
auto primes = prime_sieve(p+6);
return (p!=2 && p!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]);
}
long long inpal::max_palprime(long long n)
{
auto primes = prime_sieve(n);
for(std::vector<bool>::size_type it=primes.size()-1; it!=1; it--)
{
if(primes[it] && pal_test(it))
{
return it;
}
}
return 0;
}
long long inpal::max_factor(long long f)
{
return factorizer(f).back();
}
long long inpal::count_factors(long long f)
{
return factorizer(f).size();
}
std::vector<bool> inpal::prime_sieve(long long m)
{
std::vector<bool> p_test(m+1, false);
//defines square root of m
unsigned long long root = ceil(sqrt(m));
//sieve axioms
for(unsigned long long x=1; x<=root; x++)
{
for(long long y=1; y<=root; y++)
{
long long i=(4*x*x)+(y*y);
if (i<=m && (i%12==1 || i%12==5))
{
p_test[i].flip();
}
i=(3*x*x)+(y*y);
if(i<=m && i%12==7)
{
p_test[i].flip();
}
i=(3*x*x)-(y*y);
if(x>y && i<=m && i%12==11)
{
p_test[i].flip();
}
}
}
//marks 2,3,5 and 7 as prime numbers
p_test[2]=p_test[3]=p_test[5]=p_test[7]=true;
//marks all multiples of primes as non primes
for(long long r=5; r<=root; r++)
{
if((p_test[r]))
{
for(long long j=r*r; j<=m; j+=r*r)
{
p_test[j]=false;
}
}
}
return p_test;
}
std::vector<long long> inpal::factorizer(long long f)
{
std::vector<long long> p_fac;
long long p = 2;
//trial division
while(p<=f)
{
while(f%p==0)
{
p_fac.push_back(p);
f=f/p;
}
p+= p==2 ? 1 : 2;
}
return p_fac;
}
bool inpal::pal_test(long long n)
{
//converts n to a string
std::string rev = std::to_string(n);
//checks if the reverse of rev is equal to rev
for(int i=0; i<rev.size()/2; i++)
{
if(rev[i]!=rev[rev.size()-1-i])
{
return false;
}
}
return true;
}
<|endoftext|>
|
<commit_before>//Adjust the code to handle Strings of type Dna, Dna5 and AminoAcid. Print the text on screen and observe how it changes depending on the type of the string.
#include <iostream>
#include <seqan/sequence.h>
int computeLocalScore(seqan::String<char> subText, seqan::String<char> pattern)
{
int localScore = 0;
for (unsigned i = 0; i < seqan::length(pattern); ++i)
if (subText[i] == pattern[i])
++localScore;
return localScore;
}
seqan::String<int> computeScore(seqan::String<char> text, seqan::String<char> pattern)
{
seqan::String<int> score;
seqan::resize(score, seqan::length(text), 0);
for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i)
score[i] = computeLocalScore(infix(text, i, i + seqan::length(pattern)), pattern);
return score;
}
void print(seqan::String<int> score)
{
for (unsigned i = 0; i < seqan::length(score); ++i)
std::cout << score[i] << " ";
std::cout << std::endl;
}
int main()
{
seqan::String<char> text = "This is an awesome tutorial to get to now the basic principles of SeqAn!";
seqan::String<char> pattern = "tutorial";
seqan::String<int> score = computeScore(text, pattern);
print(score);
return 0;
}
<commit_msg>[Fix] This assignment was moved in an earlier svn version.<commit_after><|endoftext|>
|
<commit_before>#include "iotsa.h"
#include "iotsaInput.h"
#include "iotsaConfigFile.h"
#define DEBOUNCE_DELAY 50 // 50 ms debouncing
#ifdef ESP32
static void dummyTouchCallback() {}
#endif // ESP32
static bool anyWakeOnTouch;
static uint64_t bitmaskButtonWakeHigh;
static int buttonWakeLow;
void IotsaInputMod::setup() {
anyWakeOnTouch = false;
bitmaskButtonWakeHigh = 0;
buttonWakeLow = -1;
for(int i=0; i<nInput; i++) {
inputs[i]->setup();
}
#ifdef ESP32
esp_err_t err;
if (bitmaskButtonWakeHigh && buttonWakeLow && anyWakeOnTouch) {
IotsaSerial.println("IotsaInputMod: too many incompatible wakeup sources");
}
if (anyWakeOnTouch) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on touch");
err = esp_sleep_enable_touchpad_wakeup();
if (err != ESP_OK) IotsaSerial.println("Error in touchpad_wakeup");
}
if (bitmaskButtonWakeHigh) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on some high pins");
err = esp_sleep_enable_ext1_wakeup(bitmaskButtonWakeHigh, ESP_EXT1_WAKEUP_ANY_HIGH);
if (err != ESP_OK) IotsaSerial.println("Error in ext1_wakeup HIGH");
}
if (buttonWakeLow >= 0) {
if (!anyWakeOnTouch) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on one low pins");
err = esp_sleep_enable_ext0_wakeup((gpio_num_t)buttonWakeLow, 0);
if (err != ESP_OK) IotsaSerial.println("Error in ext0_wakeup");
} else {
err = esp_sleep_enable_ext1_wakeup(1<<buttonWakeLow, ESP_EXT1_WAKEUP_ALL_LOW);
if (err != ESP_OK) IotsaSerial.println("Error in ext1_wakeup LOW");
}
}
#else
if (anyWakeOnTouch || buttonWakeLow >= 0 || bitmaskButtonWakeHigh) {
IotsaSerial.println("Wake-from-sleep not implemented on esp8266");
}
#endif
}
void IotsaInputMod::serverSetup() {
}
void IotsaInputMod::loop() {
for (int i=0; i<nInput; i++) {
inputs[i]->loop();
}
}
Input::Input(bool _actOnPress, bool _actOnRelease, bool _wake)
: actOnPress(_actOnPress),
actOnRelease(_actOnRelease),
wake(_wake),
activationCallback(NULL)
{
}
void Input::setCallback(ActivationCallbackType callback)
{
activationCallback = callback;
}
Button::Button(int _pin, bool _actOnPress, bool _actOnRelease, bool _wake)
: Input(_actOnPress, _actOnRelease, _wake),
pressed(false),
duration(0),
repeatCount(0),
pin(_pin),
debounceState(false),
debounceTime(0),
lastChangeMillis(0),
firstRepeat(0),
minRepeat(0),
curRepeat(0),
nextRepeat(0),
boolVar(NULL),
toggle(false)
{
}
void Button::setRepeat(uint32_t _firstRepeat, uint32_t _minRepeat) {
firstRepeat = _firstRepeat;
minRepeat = _minRepeat;
}
void Button::bindVar(bool& _var, bool _toggle) {
boolVar = &_var;
if (!_toggle) *boolVar = pressed;
toggle = _toggle;
}
void Button::setup() {
pinMode(pin, INPUT_PULLUP);
if (wake) {
// Buttons should be wired to GND. So press gives a low level.
if (actOnPress) {
if (buttonWakeLow > 0) IotsaSerial.println("Multiple low wake inputs");
buttonWakeLow = pin;
} else {
bitmaskButtonWakeHigh |= 1LL << pin;
}
}
}
bool Button::_getState() {
return digitalRead(pin) == LOW;
}
void Button::loop() {
bool state = _getState();
if (state != debounceState) {
// The touchpad seems to have changed state. But we want
// it to remain in the new state for some time (to cater for 50Hz/60Hz interference)
debounceTime = millis();
iotsaConfig.postponeSleep(DEBOUNCE_DELAY*2);
}
debounceState = state;
if (millis() > debounceTime + DEBOUNCE_DELAY && state != pressed) {
// The touchpad or button has been in the new state for long enough for us to trust it.
pressed = state;
if (pressed) repeatCount = 0;
if (boolVar) {
if (toggle) {
if (pressed) {
*boolVar = !*boolVar;
}
} else {
*boolVar = pressed;
}
}
if (lastChangeMillis) {
duration = millis() - lastChangeMillis;
}
lastChangeMillis = millis();
if (pressed) {
// Setup for repeat, if wanted
if (firstRepeat) {
curRepeat = firstRepeat;
nextRepeat = millis() + curRepeat;
} else {
nextRepeat = 0;
}
} else {
// Cancel any repeating
nextRepeat = 0;
}
bool doSend = (pressed && actOnPress) || (!pressed && actOnRelease);
IFDEBUG IotsaSerial.printf("Button callback for button pin %d state %d\n", pin, state);
if (doSend && activationCallback) {
activationCallback();
}
}
// See if we need to do any repeating
if (nextRepeat && millis() > nextRepeat) {
if (curRepeat > minRepeat) {
curRepeat = curRepeat - minRepeat;
if (curRepeat < minRepeat) curRepeat = minRepeat;
}
nextRepeat = millis() + curRepeat;
repeatCount++;
if (activationCallback) activationCallback();
}
}
#ifdef ESP32
Touchpad::Touchpad(int _pin, bool _actOnPress, bool _actOnRelease, bool _wake)
: Button(_pin, _actOnPress, _actOnRelease, _wake),
threshold(20)
{
}
void Touchpad::setup() {
if (wake) {
anyWakeOnTouch = true;
touchAttachInterrupt(pin, dummyTouchCallback, threshold);
}
}
bool Touchpad::_getState() {
uint16_t value = touchRead(pin);
if (value == 0) return false;
return value < threshold;
}
#endif // ESP32
ValueInput::ValueInput()
: Input(true, true, false),
value(0),
intVar(NULL),
intMin(0),
intMax(0),
intStep(0),
floatVar(NULL),
floatMin(0),
floatMax(0),
floatStep(0)
{
}
void ValueInput::bindVar(int& _var, int _min, int _max, int _stepSize) {
intVar = &_var;
intMin = _min;
intMax = _max;
intStep = _stepSize;
}
void ValueInput::bindVar(float& _var, float _min, float _max, float _stepSize) {
floatVar = &_var;
floatMin = _min;
floatMax = _max;
floatStep = _stepSize;
}
void ValueInput::_changeValue(int steps) {
value += steps;
if (intVar) {
*intVar += steps*intStep;
if (*intVar < intMin) *intVar = intMin;
if (*intVar > intMax) *intVar = intMax;
}
if (floatVar) {
*floatVar += steps*floatStep;
if (*floatVar < floatMin) *floatVar = floatMin;
if (*floatVar > floatMax) *floatVar = floatMax;
}
IFDEBUG IotsaSerial.printf("ValueInput callback increment %d value %d\n", steps, value);
if (activationCallback) {
activationCallback();
}
}
RotaryEncoder::RotaryEncoder(int _pinA, int _pinB)
: ValueInput(),
duration(0),
pinA(_pinA),
pinB(_pinB),
pinAstate(false),
lastChangeMillis(0),
accelMillis(0)
{
}
void RotaryEncoder::setAcceleration(uint32_t _accelMillis) {
accelMillis = _accelMillis;
}
void RotaryEncoder::setup() {
pinMode(pinA, INPUT_PULLUP);
pinMode(pinB, INPUT_PULLUP);
pinAstate = digitalRead(pinA) == LOW;
if (wake) {
// xxxjack unsure about this: would "wake on any high" mean on positive flanks (as I hope) or
// would this mean the cpu remain awake when any pin is level high? To be determined.
bitmaskButtonWakeHigh |= 1LL << pinA;
bitmaskButtonWakeHigh |= 1LL << pinB;
}
}
void RotaryEncoder::loop() {
bool pinAnewState = digitalRead(pinA) == LOW;
if (pinAnewState != pinAstate) {
if (lastChangeMillis) {
duration = millis() - lastChangeMillis;
}
lastChangeMillis = millis();
// PinA is in a new state
pinAstate = pinAnewState;
// If pinA changed state high read pinB to determine whether this is an increment or a decrement.
bool pinBstate = digitalRead(pinB) == LOW;
bool increment = pinAstate != pinBstate;
int change = 1;
if (accelMillis > 0 && duration > 0) {
// Check if we want to do multiple steps, because the encoder was
// rotated fast
if (duration < accelMillis) {
change += accelMillis / duration;
}
}
if (increment) {
_changeValue(change);
} else {
_changeValue(-change);
}
}
}
UpDownButtons::UpDownButtons(Button& _up, Button& _down, bool _useState)
: ValueInput(),
state(false),
up(_up),
down(_down),
useState(_useState),
stateVar(NULL)
{
up.setCallback(std::bind(&UpDownButtons::_upPressed, this));
down.setCallback(std::bind(&UpDownButtons::_downPressed, this));
up.setRepeat(500, 100);
down.setRepeat(500, 100);
}
void UpDownButtons::bindStateVar(bool& _var) {
stateVar = &_var;
}
void UpDownButtons::setStateCallback(ActivationCallbackType callback) {
stateCallback = callback;
}
void UpDownButtons::setup() {
up.setup();
down.setup();
}
void UpDownButtons::loop() {
up.loop();
down.loop();
}
bool UpDownButtons::_upPressed() {
if (!up.pressed) return true;
if (useState) {
// The buttons double as on/off buttons. A short press means "on"
// only longer press (repeats) means "increase".
if (up.repeatCount == 0) {
state = true;
if (stateVar) *stateVar = true;
if (stateCallback) stateCallback();
return true;
}
}
_changeValue(1);
return true;
}
bool UpDownButtons::_downPressed() {
if (useState) {
// The buttons double as on/off buttons. A short press means "off"
// only longer press (repeats) means "decrease". We determine
// what to do at the release of the down button.
if (down.repeatCount == 0 && !down.pressed) {
// This was a release that had no repeats. Treat it as off.
state = false;
if (stateVar) *stateVar = false;
if (stateCallback) stateCallback();
return true;
}
}
if (!down.pressed) return true;
_changeValue(-1);
return true;
}
<commit_msg>Calibrate touchpad threshold during initialization<commit_after>#include "iotsa.h"
#include "iotsaInput.h"
#include "iotsaConfigFile.h"
#define DEBOUNCE_DELAY 50 // 50 ms debouncing
#ifdef ESP32
static void dummyTouchCallback() {}
#endif // ESP32
static bool anyWakeOnTouch;
static uint64_t bitmaskButtonWakeHigh;
static int buttonWakeLow;
void IotsaInputMod::setup() {
anyWakeOnTouch = false;
bitmaskButtonWakeHigh = 0;
buttonWakeLow = -1;
for(int i=0; i<nInput; i++) {
inputs[i]->setup();
}
#ifdef ESP32
esp_err_t err;
if (bitmaskButtonWakeHigh && buttonWakeLow && anyWakeOnTouch) {
IotsaSerial.println("IotsaInputMod: too many incompatible wakeup sources");
}
if (anyWakeOnTouch) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on touch");
err = esp_sleep_enable_touchpad_wakeup();
if (err != ESP_OK) IotsaSerial.println("Error in touchpad_wakeup");
}
if (bitmaskButtonWakeHigh) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on some high pins");
err = esp_sleep_enable_ext1_wakeup(bitmaskButtonWakeHigh, ESP_EXT1_WAKEUP_ANY_HIGH);
if (err != ESP_OK) IotsaSerial.println("Error in ext1_wakeup HIGH");
}
if (buttonWakeLow >= 0) {
if (!anyWakeOnTouch) {
IFDEBUG IotsaSerial.println("IotsaInputMod: enable wake on one low pins");
err = esp_sleep_enable_ext0_wakeup((gpio_num_t)buttonWakeLow, 0);
if (err != ESP_OK) IotsaSerial.println("Error in ext0_wakeup");
} else {
err = esp_sleep_enable_ext1_wakeup(1<<buttonWakeLow, ESP_EXT1_WAKEUP_ALL_LOW);
if (err != ESP_OK) IotsaSerial.println("Error in ext1_wakeup LOW");
}
}
#else
if (anyWakeOnTouch || buttonWakeLow >= 0 || bitmaskButtonWakeHigh) {
IotsaSerial.println("Wake-from-sleep not implemented on esp8266");
}
#endif
}
void IotsaInputMod::serverSetup() {
}
void IotsaInputMod::loop() {
for (int i=0; i<nInput; i++) {
inputs[i]->loop();
}
}
Input::Input(bool _actOnPress, bool _actOnRelease, bool _wake)
: actOnPress(_actOnPress),
actOnRelease(_actOnRelease),
wake(_wake),
activationCallback(NULL)
{
}
void Input::setCallback(ActivationCallbackType callback)
{
activationCallback = callback;
}
Button::Button(int _pin, bool _actOnPress, bool _actOnRelease, bool _wake)
: Input(_actOnPress, _actOnRelease, _wake),
pressed(false),
duration(0),
repeatCount(0),
pin(_pin),
debounceState(false),
debounceTime(0),
lastChangeMillis(0),
firstRepeat(0),
minRepeat(0),
curRepeat(0),
nextRepeat(0),
boolVar(NULL),
toggle(false)
{
}
void Button::setRepeat(uint32_t _firstRepeat, uint32_t _minRepeat) {
firstRepeat = _firstRepeat;
minRepeat = _minRepeat;
}
void Button::bindVar(bool& _var, bool _toggle) {
boolVar = &_var;
if (!_toggle) *boolVar = pressed;
toggle = _toggle;
}
void Button::setup() {
pinMode(pin, INPUT_PULLUP);
if (wake) {
// Buttons should be wired to GND. So press gives a low level.
if (actOnPress) {
if (buttonWakeLow > 0) IotsaSerial.println("Multiple low wake inputs");
buttonWakeLow = pin;
} else {
bitmaskButtonWakeHigh |= 1LL << pin;
}
}
}
bool Button::_getState() {
return digitalRead(pin) == LOW;
}
void Button::loop() {
bool state = _getState();
if (state != debounceState) {
// The touchpad seems to have changed state. But we want
// it to remain in the new state for some time (to cater for 50Hz/60Hz interference)
debounceTime = millis();
iotsaConfig.postponeSleep(DEBOUNCE_DELAY*2);
}
debounceState = state;
if (millis() > debounceTime + DEBOUNCE_DELAY && state != pressed) {
// The touchpad or button has been in the new state for long enough for us to trust it.
pressed = state;
if (pressed) repeatCount = 0;
if (boolVar) {
if (toggle) {
if (pressed) {
*boolVar = !*boolVar;
}
} else {
*boolVar = pressed;
}
}
if (lastChangeMillis) {
duration = millis() - lastChangeMillis;
}
lastChangeMillis = millis();
if (pressed) {
// Setup for repeat, if wanted
if (firstRepeat) {
curRepeat = firstRepeat;
nextRepeat = millis() + curRepeat;
} else {
nextRepeat = 0;
}
} else {
// Cancel any repeating
nextRepeat = 0;
}
bool doSend = (pressed && actOnPress) || (!pressed && actOnRelease);
IFDEBUG IotsaSerial.printf("Button callback for button pin %d state %d\n", pin, state);
if (doSend && activationCallback) {
activationCallback();
}
}
// See if we need to do any repeating
if (nextRepeat && millis() > nextRepeat) {
if (curRepeat > minRepeat) {
curRepeat = curRepeat - minRepeat;
if (curRepeat < minRepeat) curRepeat = minRepeat;
}
nextRepeat = millis() + curRepeat;
repeatCount++;
if (activationCallback) activationCallback();
}
}
#ifdef ESP32
Touchpad::Touchpad(int _pin, bool _actOnPress, bool _actOnRelease, bool _wake)
: Button(_pin, _actOnPress, _actOnRelease, _wake),
threshold(20)
{
// Initialize threshold by taking some readings, and assuming two thirds of the minimum reading is a good threshold.
uint16_t minRead = touchRead(pin);
for (int i=0; i< 10; i++) {
uint16_t newRead = touchRead(pin);
if (newRead < minRead) minRead = newRead;
}
if (minRead > 20) {
threshold = minRead*2/3;
}
}
void Touchpad::setup() {
IFDEBUG IotsaSerial.printf("touch(%d): threshold=%d\n", pin, threshold);
if (wake) {
anyWakeOnTouch = true;
touchAttachInterrupt(pin, dummyTouchCallback, threshold);
}
}
bool Touchpad::_getState() {
uint16_t value = touchRead(pin);
if (value == 0) return false;
return value < threshold;
}
#endif // ESP32
ValueInput::ValueInput()
: Input(true, true, false),
value(0),
intVar(NULL),
intMin(0),
intMax(0),
intStep(0),
floatVar(NULL),
floatMin(0),
floatMax(0),
floatStep(0)
{
}
void ValueInput::bindVar(int& _var, int _min, int _max, int _stepSize) {
intVar = &_var;
intMin = _min;
intMax = _max;
intStep = _stepSize;
}
void ValueInput::bindVar(float& _var, float _min, float _max, float _stepSize) {
floatVar = &_var;
floatMin = _min;
floatMax = _max;
floatStep = _stepSize;
}
void ValueInput::_changeValue(int steps) {
value += steps;
if (intVar) {
*intVar += steps*intStep;
if (*intVar < intMin) *intVar = intMin;
if (*intVar > intMax) *intVar = intMax;
}
if (floatVar) {
*floatVar += steps*floatStep;
if (*floatVar < floatMin) *floatVar = floatMin;
if (*floatVar > floatMax) *floatVar = floatMax;
}
IFDEBUG IotsaSerial.printf("ValueInput callback increment %d value %d\n", steps, value);
if (activationCallback) {
activationCallback();
}
}
RotaryEncoder::RotaryEncoder(int _pinA, int _pinB)
: ValueInput(),
duration(0),
pinA(_pinA),
pinB(_pinB),
pinAstate(false),
lastChangeMillis(0),
accelMillis(0)
{
}
void RotaryEncoder::setAcceleration(uint32_t _accelMillis) {
accelMillis = _accelMillis;
}
void RotaryEncoder::setup() {
pinMode(pinA, INPUT_PULLUP);
pinMode(pinB, INPUT_PULLUP);
pinAstate = digitalRead(pinA) == LOW;
if (wake) {
// xxxjack unsure about this: would "wake on any high" mean on positive flanks (as I hope) or
// would this mean the cpu remain awake when any pin is level high? To be determined.
bitmaskButtonWakeHigh |= 1LL << pinA;
bitmaskButtonWakeHigh |= 1LL << pinB;
}
}
void RotaryEncoder::loop() {
bool pinAnewState = digitalRead(pinA) == LOW;
if (pinAnewState != pinAstate) {
if (lastChangeMillis) {
duration = millis() - lastChangeMillis;
}
lastChangeMillis = millis();
// PinA is in a new state
pinAstate = pinAnewState;
// If pinA changed state high read pinB to determine whether this is an increment or a decrement.
bool pinBstate = digitalRead(pinB) == LOW;
bool increment = pinAstate != pinBstate;
int change = 1;
if (accelMillis > 0 && duration > 0) {
// Check if we want to do multiple steps, because the encoder was
// rotated fast
if (duration < accelMillis) {
change += accelMillis / duration;
}
}
if (increment) {
_changeValue(change);
} else {
_changeValue(-change);
}
}
}
UpDownButtons::UpDownButtons(Button& _up, Button& _down, bool _useState)
: ValueInput(),
state(false),
up(_up),
down(_down),
useState(_useState),
stateVar(NULL)
{
up.setCallback(std::bind(&UpDownButtons::_upPressed, this));
down.setCallback(std::bind(&UpDownButtons::_downPressed, this));
up.setRepeat(500, 100);
down.setRepeat(500, 100);
}
void UpDownButtons::bindStateVar(bool& _var) {
stateVar = &_var;
}
void UpDownButtons::setStateCallback(ActivationCallbackType callback) {
stateCallback = callback;
}
void UpDownButtons::setup() {
up.setup();
down.setup();
}
void UpDownButtons::loop() {
up.loop();
down.loop();
}
bool UpDownButtons::_upPressed() {
if (!up.pressed) return true;
if (useState) {
// The buttons double as on/off buttons. A short press means "on"
// only longer press (repeats) means "increase".
if (up.repeatCount == 0) {
state = true;
if (stateVar) *stateVar = true;
if (stateCallback) stateCallback();
return true;
}
}
_changeValue(1);
return true;
}
bool UpDownButtons::_downPressed() {
if (useState) {
// The buttons double as on/off buttons. A short press means "off"
// only longer press (repeats) means "decrease". We determine
// what to do at the release of the down button.
if (down.repeatCount == 0 && !down.pressed) {
// This was a release that had no repeats. Treat it as off.
state = false;
if (stateVar) *stateVar = false;
if (stateCallback) stateCallback();
return true;
}
}
if (!down.pressed) return true;
_changeValue(-1);
return true;
}
<|endoftext|>
|
<commit_before>#include "javaObject.h"
#include "java.h"
#include "javaScope.h"
#include "utils.h"
#include <sstream>
#include <algorithm>
/*static*/ std::map<std::string, v8::Persistent<v8::FunctionTemplate>*> JavaObject::sFunctionTemplates;
/*static*/ void JavaObject::Init(v8::Handle<v8::Object> target) {
}
/*static*/ v8::Local<v8::Object> JavaObject::New(Java *java, jobject obj) {
NanEscapableScope();
JNIEnv *env = java->getJavaEnv();
JavaScope javaScope(env);
jclass objClazz = env->GetObjectClass(obj);
jclass classClazz = env->FindClass("java/lang/Class");
jmethodID class_getName = env->GetMethodID(classClazz, "getName", "()Ljava/lang/String;");
jobject classNameJava = env->CallObjectMethod(objClazz, class_getName);
checkJavaException(env);
std::string className = javaObjectToString(env, classNameJava);
std::replace(className.begin(), className.end(), '.', '_');
std::replace(className.begin(), className.end(), '$', '_');
std::replace(className.begin(), className.end(), '[', 'a');
className = "nodeJava_" + className;
v8::Local<v8::FunctionTemplate> funcTemplate;
if(sFunctionTemplates.find(className) != sFunctionTemplates.end()) {
//printf("existing className: %s\n", className.c_str());
funcTemplate = NanNew(*sFunctionTemplates[className]);
} else {
//printf("create className: %s\n", className.c_str());
funcTemplate = NanNew<v8::FunctionTemplate>();
funcTemplate->InstanceTemplate()->SetInternalFieldCount(1);
funcTemplate->SetClassName(NanNew<v8::String>(className.c_str()));
std::list<jobject> methods;
javaReflectionGetMethods(env, objClazz, &methods, false);
jclass methodClazz = env->FindClass("java/lang/reflect/Method");
jmethodID method_getName = env->GetMethodID(methodClazz, "getName", "()Ljava/lang/String;");
for(std::list<jobject>::iterator it = methods.begin(); it != methods.end(); ++it) {
jstring methodNameJava = (jstring)env->CallObjectMethod(*it, method_getName);
assert(!env->ExceptionCheck());
std::string methodNameStr = javaToString(env, methodNameJava);
v8::Handle<v8::String> methodName = NanNew<v8::String>(methodNameStr.c_str());
v8::Local<v8::FunctionTemplate> methodCallTemplate = NanNew<v8::FunctionTemplate>(methodCall, methodName);
funcTemplate->PrototypeTemplate()->Set(methodName, methodCallTemplate->GetFunction());
v8::Handle<v8::String> methodNameSync = NanNew<v8::String>((methodNameStr + "Sync").c_str());
v8::Local<v8::FunctionTemplate> methodCallSyncTemplate = NanNew<v8::FunctionTemplate>(methodCallSync, methodName);
funcTemplate->PrototypeTemplate()->Set(methodNameSync, methodCallSyncTemplate->GetFunction());
}
std::list<jobject> fields;
javaReflectionGetFields(env, objClazz, &fields);
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_getName = env->GetMethodID(fieldClazz, "getName", "()Ljava/lang/String;");
for(std::list<jobject>::iterator it = fields.begin(); it != fields.end(); ++it) {
jstring fieldNameJava = (jstring)env->CallObjectMethod(*it, field_getName);
checkJavaException(env);
std::string fieldNameStr = javaToString(env, fieldNameJava);
v8::Handle<v8::String> fieldName = NanNew<v8::String>(fieldNameStr.c_str());
funcTemplate->InstanceTemplate()->SetAccessor(fieldName, fieldGetter, fieldSetter);
}
v8::Persistent<v8::FunctionTemplate>* persistentFuncTemplate = new v8::Persistent<v8::FunctionTemplate>();
NanAssignPersistent(*persistentFuncTemplate, funcTemplate);
sFunctionTemplates[className] = persistentFuncTemplate;
}
v8::Local<v8::Function> ctor = funcTemplate->GetFunction();
v8::Local<v8::Object> javaObjectObj = ctor->NewInstance();
javaObjectObj->SetHiddenValue(NanNew<v8::String>(V8_HIDDEN_MARKER_JAVA_OBJECT), NanNew<v8::Boolean>(true));
JavaObject *self = new JavaObject(java, obj);
self->Wrap(javaObjectObj);
return NanEscapeScope(javaObjectObj);
}
JavaObject::JavaObject(Java *java, jobject obj) {
m_java = java;
JNIEnv *env = m_java->getJavaEnv();
m_obj = env->NewGlobalRef(obj);
m_class = (jclass)env->NewGlobalRef(env->GetObjectClass(obj));
}
JavaObject::~JavaObject() {
JNIEnv *env = m_java->getJavaEnv();
env->DeleteGlobalRef(m_obj);
env->DeleteGlobalRef(m_class);
}
NAN_METHOD(JavaObject::methodCall) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value methodName(args.Data());
std::string methodNameStr = *methodName;
int argsStart = 0;
int argsEnd = args.Length();
// arguments
ARGS_BACK_CALLBACK();
if(!callbackProvided && methodNameStr == "toString") {
return methodCallSync(args);
}
jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);
jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
if(method == NULL) {
std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
EXCEPTION_CALL_CALLBACK(self->m_java, msg);
NanReturnUndefined();
}
// run
InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
baton->run();
END_CALLBACK_FUNCTION("\"Method '" << methodNameStr << "' called without a callback did you mean to use the Sync version?\"");
}
NAN_METHOD(JavaObject::methodCallSync) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value methodName(args.Data());
std::string methodNameStr = *methodName;
int argsStart = 0;
int argsEnd = args.Length();
jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);
jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
if(method == NULL) {
std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, msg);
return NanThrowError(ex);
}
// run
v8::Handle<v8::Value> callback = NanUndefined();
InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
v8::Handle<v8::Value> result = baton->runSync();
delete baton;
if(result->IsNativeError()) {
return NanThrowError(result);
}
NanReturnValue(result);
}
NAN_GETTER(JavaObject::fieldGetter) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value propertyCStr(property);
std::string propertyStr = *propertyCStr;
jobject field = javaFindField(env, self->m_class, propertyStr);
if(field == NULL) {
std::ostringstream errStr;
errStr << "Could not find field " << propertyStr;
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, errStr.str());
return NanThrowError(ex);
}
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_get = env->GetMethodID(fieldClazz, "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
// get field value
jobject val = env->CallObjectMethod(field, field_get, self->m_obj);
if(env->ExceptionOccurred()) {
std::ostringstream errStr;
errStr << "Could not get field " << propertyStr;
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, errStr.str());
return NanThrowError(ex);
}
v8::Handle<v8::Value> result = javaToV8(self->m_java, env, val);
NanReturnValue(result);
}
NAN_SETTER(JavaObject::fieldSetter) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
jobject newValue = v8ToJava(env, value);
v8::String::Utf8Value propertyCStr(property);
std::string propertyStr = *propertyCStr;
jobject field = javaFindField(env, self->m_class, propertyStr);
if(field == NULL) {
std::ostringstream errStr;
errStr << "Could not find field " << propertyStr;
v8::Handle<v8::Value> error = javaExceptionToV8(self->m_java, env, errStr.str());
NanThrowError(error);
return;
}
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_set = env->GetMethodID(fieldClazz, "set", "(Ljava/lang/Object;Ljava/lang/Object;)V");
//printf("newValue: %s\n", javaObjectToString(env, newValue).c_str());
// set field value
env->CallObjectMethod(field, field_set, self->m_obj, newValue);
if(env->ExceptionOccurred()) {
std::ostringstream errStr;
errStr << "Could not set field " << propertyStr;
v8::Handle<v8::Value> error = javaExceptionToV8(self->m_java, env, errStr.str());
NanThrowError(error);
return;
}
}
/*static*/ v8::Persistent<v8::FunctionTemplate> JavaProxyObject::s_proxyCt;
/*static*/ void JavaProxyObject::init() {
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>();
NanAssignPersistent(s_proxyCt, t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew<v8::String>("NodeDynamicProxy"));
v8::Handle<v8::String> methodName = NanNew<v8::String>("unref");
v8::Local<v8::FunctionTemplate> methodCallTemplate = NanNew<v8::FunctionTemplate>(doUnref);
t->PrototypeTemplate()->Set(methodName, methodCallTemplate->GetFunction());
v8::Handle<v8::String> fieldName = NanNew<v8::String>("invocationHandler");
t->InstanceTemplate()->SetAccessor(fieldName, invocationHandlerGetter);
}
v8::Local<v8::Object> JavaProxyObject::New(Java *java, jobject obj, DynamicProxyData* dynamicProxyData) {
NanEscapableScope();
v8::Local<v8::Function> ctor = s_proxyCt->GetFunction();
v8::Local<v8::Object> javaObjectObj = ctor->NewInstance();
javaObjectObj->SetHiddenValue(NanNew<v8::String>(V8_HIDDEN_MARKER_JAVA_OBJECT), NanNew<v8::Boolean>(true));
JavaProxyObject *self = new JavaProxyObject(java, obj, dynamicProxyData);
self->Wrap(javaObjectObj);
return NanEscapeScope(javaObjectObj);
}
JavaProxyObject::JavaProxyObject(Java *java, jobject obj, DynamicProxyData* dynamicProxyData) : JavaObject(java, obj) {
m_dynamicProxyData = dynamicProxyData;
}
JavaProxyObject::~JavaProxyObject() {
if(dynamicProxyDataVerify(m_dynamicProxyData)) {
unref(m_dynamicProxyData);
}
}
NAN_METHOD(JavaProxyObject::doUnref) {
JavaProxyObject* self = node::ObjectWrap::Unwrap<JavaProxyObject>(args.This());
if (dynamicProxyDataVerify(self->m_dynamicProxyData)) {
unref(self->m_dynamicProxyData);
}
NanReturnUndefined();
}
NAN_GETTER(JavaProxyObject::invocationHandlerGetter) {
NanScope();
JavaProxyObject* self = node::ObjectWrap::Unwrap<JavaProxyObject>(args.This());
if (!dynamicProxyDataVerify(self->m_dynamicProxyData)) {
return NanThrowError("dynamicProxyData has been destroyed or corrupted");
}
NanReturnValue(self->m_dynamicProxyData->functions);
}
<commit_msg>use Nan to get value from persistant<commit_after>#include "javaObject.h"
#include "java.h"
#include "javaScope.h"
#include "utils.h"
#include <sstream>
#include <algorithm>
/*static*/ std::map<std::string, v8::Persistent<v8::FunctionTemplate>*> JavaObject::sFunctionTemplates;
/*static*/ void JavaObject::Init(v8::Handle<v8::Object> target) {
}
/*static*/ v8::Local<v8::Object> JavaObject::New(Java *java, jobject obj) {
NanEscapableScope();
JNIEnv *env = java->getJavaEnv();
JavaScope javaScope(env);
jclass objClazz = env->GetObjectClass(obj);
jclass classClazz = env->FindClass("java/lang/Class");
jmethodID class_getName = env->GetMethodID(classClazz, "getName", "()Ljava/lang/String;");
jobject classNameJava = env->CallObjectMethod(objClazz, class_getName);
checkJavaException(env);
std::string className = javaObjectToString(env, classNameJava);
std::replace(className.begin(), className.end(), '.', '_');
std::replace(className.begin(), className.end(), '$', '_');
std::replace(className.begin(), className.end(), '[', 'a');
className = "nodeJava_" + className;
v8::Local<v8::FunctionTemplate> funcTemplate;
if(sFunctionTemplates.find(className) != sFunctionTemplates.end()) {
//printf("existing className: %s\n", className.c_str());
funcTemplate = NanNew(*sFunctionTemplates[className]);
} else {
//printf("create className: %s\n", className.c_str());
funcTemplate = NanNew<v8::FunctionTemplate>();
funcTemplate->InstanceTemplate()->SetInternalFieldCount(1);
funcTemplate->SetClassName(NanNew<v8::String>(className.c_str()));
std::list<jobject> methods;
javaReflectionGetMethods(env, objClazz, &methods, false);
jclass methodClazz = env->FindClass("java/lang/reflect/Method");
jmethodID method_getName = env->GetMethodID(methodClazz, "getName", "()Ljava/lang/String;");
for(std::list<jobject>::iterator it = methods.begin(); it != methods.end(); ++it) {
jstring methodNameJava = (jstring)env->CallObjectMethod(*it, method_getName);
assert(!env->ExceptionCheck());
std::string methodNameStr = javaToString(env, methodNameJava);
v8::Handle<v8::String> methodName = NanNew<v8::String>(methodNameStr.c_str());
v8::Local<v8::FunctionTemplate> methodCallTemplate = NanNew<v8::FunctionTemplate>(methodCall, methodName);
funcTemplate->PrototypeTemplate()->Set(methodName, methodCallTemplate->GetFunction());
v8::Handle<v8::String> methodNameSync = NanNew<v8::String>((methodNameStr + "Sync").c_str());
v8::Local<v8::FunctionTemplate> methodCallSyncTemplate = NanNew<v8::FunctionTemplate>(methodCallSync, methodName);
funcTemplate->PrototypeTemplate()->Set(methodNameSync, methodCallSyncTemplate->GetFunction());
}
std::list<jobject> fields;
javaReflectionGetFields(env, objClazz, &fields);
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_getName = env->GetMethodID(fieldClazz, "getName", "()Ljava/lang/String;");
for(std::list<jobject>::iterator it = fields.begin(); it != fields.end(); ++it) {
jstring fieldNameJava = (jstring)env->CallObjectMethod(*it, field_getName);
checkJavaException(env);
std::string fieldNameStr = javaToString(env, fieldNameJava);
v8::Handle<v8::String> fieldName = NanNew<v8::String>(fieldNameStr.c_str());
funcTemplate->InstanceTemplate()->SetAccessor(fieldName, fieldGetter, fieldSetter);
}
v8::Persistent<v8::FunctionTemplate>* persistentFuncTemplate = new v8::Persistent<v8::FunctionTemplate>();
NanAssignPersistent(*persistentFuncTemplate, funcTemplate);
sFunctionTemplates[className] = persistentFuncTemplate;
}
v8::Local<v8::Function> ctor = funcTemplate->GetFunction();
v8::Local<v8::Object> javaObjectObj = ctor->NewInstance();
javaObjectObj->SetHiddenValue(NanNew<v8::String>(V8_HIDDEN_MARKER_JAVA_OBJECT), NanNew<v8::Boolean>(true));
JavaObject *self = new JavaObject(java, obj);
self->Wrap(javaObjectObj);
return NanEscapeScope(javaObjectObj);
}
JavaObject::JavaObject(Java *java, jobject obj) {
m_java = java;
JNIEnv *env = m_java->getJavaEnv();
m_obj = env->NewGlobalRef(obj);
m_class = (jclass)env->NewGlobalRef(env->GetObjectClass(obj));
}
JavaObject::~JavaObject() {
JNIEnv *env = m_java->getJavaEnv();
env->DeleteGlobalRef(m_obj);
env->DeleteGlobalRef(m_class);
}
NAN_METHOD(JavaObject::methodCall) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value methodName(args.Data());
std::string methodNameStr = *methodName;
int argsStart = 0;
int argsEnd = args.Length();
// arguments
ARGS_BACK_CALLBACK();
if(!callbackProvided && methodNameStr == "toString") {
return methodCallSync(args);
}
jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);
jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
if(method == NULL) {
std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
EXCEPTION_CALL_CALLBACK(self->m_java, msg);
NanReturnUndefined();
}
// run
InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
baton->run();
END_CALLBACK_FUNCTION("\"Method '" << methodNameStr << "' called without a callback did you mean to use the Sync version?\"");
}
NAN_METHOD(JavaObject::methodCallSync) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value methodName(args.Data());
std::string methodNameStr = *methodName;
int argsStart = 0;
int argsEnd = args.Length();
jobjectArray methodArgs = v8ToJava(env, args, argsStart, argsEnd);
jobject method = javaFindMethod(env, self->m_class, methodNameStr, methodArgs);
if(method == NULL) {
std::string msg = methodNotFoundToString(env, self->m_class, methodNameStr, false, args, argsStart, argsEnd);
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, msg);
return NanThrowError(ex);
}
// run
v8::Handle<v8::Value> callback = NanUndefined();
InstanceMethodCallBaton* baton = new InstanceMethodCallBaton(self->m_java, self, method, methodArgs, callback);
v8::Handle<v8::Value> result = baton->runSync();
delete baton;
if(result->IsNativeError()) {
return NanThrowError(result);
}
NanReturnValue(result);
}
NAN_GETTER(JavaObject::fieldGetter) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
v8::String::Utf8Value propertyCStr(property);
std::string propertyStr = *propertyCStr;
jobject field = javaFindField(env, self->m_class, propertyStr);
if(field == NULL) {
std::ostringstream errStr;
errStr << "Could not find field " << propertyStr;
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, errStr.str());
return NanThrowError(ex);
}
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_get = env->GetMethodID(fieldClazz, "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
// get field value
jobject val = env->CallObjectMethod(field, field_get, self->m_obj);
if(env->ExceptionOccurred()) {
std::ostringstream errStr;
errStr << "Could not get field " << propertyStr;
v8::Handle<v8::Value> ex = javaExceptionToV8(self->m_java, env, errStr.str());
return NanThrowError(ex);
}
v8::Handle<v8::Value> result = javaToV8(self->m_java, env, val);
NanReturnValue(result);
}
NAN_SETTER(JavaObject::fieldSetter) {
NanScope();
JavaObject* self = node::ObjectWrap::Unwrap<JavaObject>(args.This());
JNIEnv *env = self->m_java->getJavaEnv();
JavaScope javaScope(env);
jobject newValue = v8ToJava(env, value);
v8::String::Utf8Value propertyCStr(property);
std::string propertyStr = *propertyCStr;
jobject field = javaFindField(env, self->m_class, propertyStr);
if(field == NULL) {
std::ostringstream errStr;
errStr << "Could not find field " << propertyStr;
v8::Handle<v8::Value> error = javaExceptionToV8(self->m_java, env, errStr.str());
NanThrowError(error);
return;
}
jclass fieldClazz = env->FindClass("java/lang/reflect/Field");
jmethodID field_set = env->GetMethodID(fieldClazz, "set", "(Ljava/lang/Object;Ljava/lang/Object;)V");
//printf("newValue: %s\n", javaObjectToString(env, newValue).c_str());
// set field value
env->CallObjectMethod(field, field_set, self->m_obj, newValue);
if(env->ExceptionOccurred()) {
std::ostringstream errStr;
errStr << "Could not set field " << propertyStr;
v8::Handle<v8::Value> error = javaExceptionToV8(self->m_java, env, errStr.str());
NanThrowError(error);
return;
}
}
/*static*/ v8::Persistent<v8::FunctionTemplate> JavaProxyObject::s_proxyCt;
/*static*/ void JavaProxyObject::init() {
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>();
NanAssignPersistent(s_proxyCt, t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew<v8::String>("NodeDynamicProxy"));
v8::Handle<v8::String> methodName = NanNew<v8::String>("unref");
v8::Local<v8::FunctionTemplate> methodCallTemplate = NanNew<v8::FunctionTemplate>(doUnref);
t->PrototypeTemplate()->Set(methodName, methodCallTemplate->GetFunction());
v8::Handle<v8::String> fieldName = NanNew<v8::String>("invocationHandler");
t->InstanceTemplate()->SetAccessor(fieldName, invocationHandlerGetter);
}
v8::Local<v8::Object> JavaProxyObject::New(Java *java, jobject obj, DynamicProxyData* dynamicProxyData) {
NanEscapableScope();
v8::Local<v8::Function> ctor = NanNew(s_proxyCt)->GetFunction();
v8::Local<v8::Object> javaObjectObj = ctor->NewInstance();
javaObjectObj->SetHiddenValue(NanNew<v8::String>(V8_HIDDEN_MARKER_JAVA_OBJECT), NanNew<v8::Boolean>(true));
JavaProxyObject *self = new JavaProxyObject(java, obj, dynamicProxyData);
self->Wrap(javaObjectObj);
return NanEscapeScope(javaObjectObj);
}
JavaProxyObject::JavaProxyObject(Java *java, jobject obj, DynamicProxyData* dynamicProxyData) : JavaObject(java, obj) {
m_dynamicProxyData = dynamicProxyData;
}
JavaProxyObject::~JavaProxyObject() {
if(dynamicProxyDataVerify(m_dynamicProxyData)) {
unref(m_dynamicProxyData);
}
}
NAN_METHOD(JavaProxyObject::doUnref) {
JavaProxyObject* self = node::ObjectWrap::Unwrap<JavaProxyObject>(args.This());
if (dynamicProxyDataVerify(self->m_dynamicProxyData)) {
unref(self->m_dynamicProxyData);
}
NanReturnUndefined();
}
NAN_GETTER(JavaProxyObject::invocationHandlerGetter) {
NanScope();
JavaProxyObject* self = node::ObjectWrap::Unwrap<JavaProxyObject>(args.This());
if (!dynamicProxyDataVerify(self->m_dynamicProxyData)) {
return NanThrowError("dynamicProxyData has been destroyed or corrupted");
}
NanReturnValue(self->m_dynamicProxyData->functions);
}
<|endoftext|>
|
<commit_before>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
return ret;
}
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx.def"
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}*/
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (p.vcols % 4 || p.wcols % 4) {
PERFWARNING_LOG("Use plain for non-multiple of four");
p.impl = GHOST_IMPLEMENTATION_SSE;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
if (v->context) {
tsmttsm_perfargs.vrows = v->context->gnrows;
} else {
tsmttsm_perfargs.vrows = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<commit_msg>actually use plain as promised<commit_after>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/math.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmttsm_gen.h"
#include "ghost/tsmttsm_avx_gen.h"
#include <map>
using namespace std;
static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b)
{
return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,0)) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,0));
}
static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels;
ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv,
ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror)
{
if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("w must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) {
if (printerror) {
ERROR_LOG("v must be stored row-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) {
if (printerror) {
ERROR_LOG("x must be stored col-major!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) {
if (printerror) {
ERROR_LOG("Different data types!");
}
return GHOST_ERR_INVALID_ARG;
}
if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) {
if (printerror) {
ERROR_LOG("Scattered densemats not supported!");
}
return GHOST_ERR_INVALID_ARG;
}
if (reduce != GHOST_GEMM_ALL_REDUCE) {
if (printerror) {
ERROR_LOG("Only Allreduce supported currently!");
}
return GHOST_ERR_INVALID_ARG;
}
if (!strncasecmp(transv,"N",1)) {
if (printerror) {
ERROR_LOG("v must be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
if (strncasecmp(transw,"N",1)) {
if (printerror) {
ERROR_LOG("w must not be transposed!");
}
return GHOST_ERR_INVALID_ARG;
}
UNUSED(alpha);
UNUSED(beta);
return GHOST_SUCCESS;
}
ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret;
if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) {
return ret;
}
if (ghost_tsmttsm_kernels.empty()) {
#include "tsmttsm.def"
#include "tsmttsm_avx.def"
}
ghost_tsmttsm_parameters_t p;
ghost_tsmttsm_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
/*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) {
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}*/
p.dt = x->traits.datatype;
p.vcols = v->traits.ncols;
p.wcols = w->traits.ncols;
if (p.vcols % 4 || p.wcols % 4) {
PERFWARNING_LOG("Use plain for non-multiple of four");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary wcols");
p.wcols = -1;
p.vcols = v->traits.ncols;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary vcols");
p.wcols = w->traits.ncols;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try kernel with arbitrary block sizes");
p.wcols = -1;
p.vcols = -1;
kernel = ghost_tsmttsm_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain implementation");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
}
kernel = ghost_tsmttsm_kernels[p];
if (!kernel) {
INFO_LOG("Could not find TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols);
return GHOST_ERR_INVALID_ARG;
//return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL);
}
ret = kernel(x,v,w,alpha,beta,conjv);
#ifdef GHOST_HAVE_INSTR_TIMING
ghost_gemm_perf_args_t tsmttsm_perfargs;
tsmttsm_perfargs.xcols = p.wcols;
tsmttsm_perfargs.vcols = p.vcols;
if (v->context) {
tsmttsm_perfargs.vrows = v->context->gnrows;
} else {
tsmttsm_perfargs.vrows = v->traits.nrows;
}
tsmttsm_perfargs.dt = x->traits.datatype;
ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s");
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/cerrno>
#include <libport/read-stdin.hh>
#include <libport/exception.hh>
#include <urbi/sdk.hh>
#include <kernel/userver.hh>
#include <runner/runner.hh>
namespace urbi
{
void
yield()
{
::kernel::urbiserver->getCurrentRunner().yield();
}
void
yield_until(libport::utime_t t)
{
::kernel::urbiserver->getCurrentRunner().yield_until(t);
}
void
yield_for(libport::utime_t t)
{
::kernel::urbiserver->getCurrentRunner().yield_until(libport::utime() + t);
}
void
yield_for_fd(int fd)
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
// Do not block
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
// FIXME: Kinda busy loop
int ret = 0;
for (ret = select(fd + 1, &rfds, NULL, NULL, &tv);
!ret;
ret = select(fd + 1, &rfds, NULL, NULL, &tv))
{
yield_for(128000);
FD_SET(fd, &rfds);
}
if (ret == -1)
errnoabort("select");
}
std::string
yield_for_read(int fd)
{
// FIXME: Kinda busy loop.
std::string res;
try
{
while (true)
{
std::string res = libport::read_fd(fd);
if (!res.empty())
return res;
yield_for(128000);
}
}
catch (const libport::Exception& e)
{
LIBPORT_ECHO(e.what());
}
return "";
}
}
<commit_msg>Style changes.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <libport/cerrno>
#include <libport/read-stdin.hh>
#include <libport/exception.hh>
#include <urbi/sdk.hh>
#include <kernel/userver.hh>
#include <runner/runner.hh>
namespace urbi
{
void
yield()
{
::kernel::urbiserver->getCurrentRunner().yield();
}
void
yield_until(libport::utime_t t)
{
::kernel::urbiserver->getCurrentRunner().yield_until(t);
}
void
yield_for(libport::utime_t t)
{
::kernel::urbiserver->getCurrentRunner().yield_until(libport::utime() + t);
}
void
yield_for_fd(int fd)
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
// Do not block
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
// FIXME: Kinda busy loop
int ret = 0;
for (ret = select(fd + 1, &rfds, NULL, NULL, &tv);
!ret;
ret = select(fd + 1, &rfds, NULL, NULL, &tv))
{
yield_for(128000);
FD_SET(fd, &rfds);
}
if (ret == -1)
errnoabort("select");
}
std::string
yield_for_read(int fd)
{
std::string res;
try
{
// FIXME: Kinda busy loop.
while (true)
{
res = libport::read_fd(fd);
if (!res.empty())
break;
yield_for(128000);
}
}
catch (const libport::Exception& e)
{
LIBPORT_ECHO(e.what());
}
return res;
}
}
<|endoftext|>
|
<commit_before>#include "scraps/utility.h"
#include "scraps/format.h"
#include <cctype>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#if !SCRAPS_WINDOWS
#include <termios.h>
#include <unistd.h>
#endif
#if __clang__ || __GNUC__
#include <cxxabi.h>
#endif
#include <fcntl.h>
#include <sys/sysctl.h>
namespace scraps {
std::string JSONEscape(const char* str) {
std::string ret;
while (*str) {
if (*str < 0x20) {
ret += "\\u";
ret += Formatf("%04X", (unsigned int)*(uint8_t*)str);
} else if (*str == '"' || *str == '\\') {
ret += '\\';
ret += *str;
} else {
ret += *str;
}
++str;
}
return ret;
}
std::string Base64Decode(const char* data, size_t length) {
// maps the ascii value of a base64 encoded char minus '+' (the lowest ascii value of the base64 encoded char set) to
// the index in the base64 character set.
static constexpr uint_fast32_t decodeMap[] = {
62, // +
0, 0, 0,
63, // /
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // 0-9
0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // A-Z
0, 0, 0,
0, // =
0, 0,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 // a-z
};
assert(length >= 4 && length % 4 == 0);
std::string decoded;
decoded.reserve(length / 4 * 3);
for (size_t i = 0; i < length; i += 4) {
auto temp = (decodeMap[data[i ] - '+'] << 18) +
(decodeMap[data[i + 1] - '+'] << 12) +
(decodeMap[data[i + 2] - '+'] << 6 ) +
(decodeMap[data[i + 3] - '+'] );
decoded.append({static_cast<char>(temp >> 16),
static_cast<char>(temp >> 8),
static_cast<char>(temp)});
}
if (data[length - 1] == '=') { decoded.pop_back(); }
if (data[length - 2] == '=') { decoded.pop_back(); }
return decoded;
}
std::string Base64Encode(const char* data, size_t length) {
static constexpr auto base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encoded;
encoded.reserve(((length / 3) + ((length % 3) > 0)) * 4);
uint_fast32_t temp = 0;
for (size_t i = 0; i < (length / 3); ++i) {
temp = *data++ << 16;
temp += *data++ << 8;
temp += *data++;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
base64chars[(temp & 0b000000000000111111000000) >> 6 ],
base64chars[(temp & 0b000000000000000000111111) ]});
}
switch (length % 3) {
case 1:
temp = *data++ << 16;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
'=',
'='});
break;
case 2:
temp = *data++ << 16;
temp += *data++ << 8;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
base64chars[(temp & 0b000000000000111111000000) >> 6 ],
'='});
break;
default:
break;
}
return encoded;
}
std::string URLEncode(const char* str) {
std::ostringstream ret;
while (char c = *str) {
if (isalnum(c) || c == '-' || c == '_' || c == '.') {
ret << c;
} else if (c == ' ') {
ret << '+';
} else {
ret << '%' << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << (int)static_cast<unsigned char>(c);
}
++str;
}
return ret.str();
}
std::string URLDecode(const char* str) {
std::ostringstream ret;
while (char c = *str) {
if (c == '+') {
ret << ' ';
} else if (c == '%' && str[1] && str[2]) {
char tmp[3];
tmp[0] = *++str;
tmp[1] = *++str;
tmp[2] = '\0';
ret << (unsigned char)strtoul(tmp, nullptr, 16);
} else {
ret << c;
}
++str;
}
return ret.str();
}
std::string Basename(const std::string& path) {
auto folder = path.rfind('/');
#if SCRAPS_WINDOWS
if (folder == path.npos) {
folder = path.rfind('\\');
}
#endif
if (folder != path.npos) {
return path.substr(folder+1);
}
return path;
}
std::string Dirname(const std::string& path) {
auto folder = path.rfind('/');
#if SCRAPS_WINDOWS
if (folder == path.npos) {
folder = path.rfind('\\');
}
#endif
if (folder != path.npos) {
return path.substr(0, folder);
}
return path;
}
std::tuple<std::string, uint16_t> ParseAddressAndPort(const std::string& host,
uint16_t defaultPort) {
auto sep = host.find(':');
if (sep == host.npos) {
return std::make_tuple(host, defaultPort);
}
const auto address = host.substr(0, sep);
const auto port = static_cast<uint16_t>(std::atoi(host.substr(sep + 1).c_str()));
return std::make_tuple(address, port);
}
std::string GetPasswordFromStdin() {
#ifdef WIN32
HANDLE stdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(stdin, &mode);
SetConsoleMode(stdin, mode & (~ENABLE_ECHO_INPUT));
#else
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
#endif
std::string password;
std::cout << "Password: " << std::flush;
std::getline(std::cin, password);
return password;
}
size_t PhysicalMemory() {
#if SCRAPS_MACOS
uint64_t mem = 0;
size_t len = sizeof(mem);
return sysctlbyname("hw.memsize", &mem, &len, NULL, 0) == 0 ? mem : 0;
#else
auto pages = sysconf(_SC_PHYS_PAGES);
auto pageSize = sysconf(_SC_PAGE_SIZE);
return (pages > 0 && pageSize > 0) ? pages * pageSize : 0;
#endif
}
stdts::optional<std::vector<Byte>> BytesFromFile(const std::string& path) {
std::ifstream dataFile{path, std::ifstream::ate | std::ios::binary};
const auto fileSize = dataFile.tellg();
if (dataFile.bad() || fileSize <= 0) {
return {};
}
std::vector<Byte> buf;
buf.resize(fileSize);
dataFile.seekg(0, std::ios::beg);
dataFile.read(reinterpret_cast<char*>(buf.data()), fileSize);
if (dataFile.bad()) {
return {};
}
return buf;
}
bool SetBlocking(int fd, bool blocking) {
#ifdef _WIN32
unsigned long arg = blocking ? 1 : 0;
return !ioctlsocket(fd, FIONBIO, &arg);
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) {
return false;
}
return !fcntl(fd, F_SETFL, blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK);
#endif
}
std::string Demangle(const char* mangled) {
#if __clang__ || __GNUC__
struct FreeDeleter { void operator()(char* p) const { std::free(p); } };
int status = 0;
auto demangled = std::unique_ptr<char, FreeDeleter>{abi::__cxa_demangle(mangled, nullptr, nullptr, &status)};
if (status == 0) {
return demangled.get();
}
#endif
return mangled;
}
} // namespace scraps
<commit_msg>Fix Android build<commit_after>#include "scraps/utility.h"
#include "scraps/format.h"
#include <cctype>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#if !SCRAPS_WINDOWS
#include <termios.h>
#include <unistd.h>
#endif
#if __clang__ || __GNUC__
#include <cxxabi.h>
#endif
#include <fcntl.h>
#if SCRAPS_MACOS
// for sysctlbyname
#include <sys/sysctl.h>
#endif
namespace scraps {
std::string JSONEscape(const char* str) {
std::string ret;
while (*str) {
if (*str < 0x20) {
ret += "\\u";
ret += Formatf("%04X", (unsigned int)*(uint8_t*)str);
} else if (*str == '"' || *str == '\\') {
ret += '\\';
ret += *str;
} else {
ret += *str;
}
++str;
}
return ret;
}
std::string Base64Decode(const char* data, size_t length) {
// maps the ascii value of a base64 encoded char minus '+' (the lowest ascii value of the base64 encoded char set) to
// the index in the base64 character set.
static constexpr uint_fast32_t decodeMap[] = {
62, // +
0, 0, 0,
63, // /
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // 0-9
0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // A-Z
0, 0, 0,
0, // =
0, 0,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 // a-z
};
assert(length >= 4 && length % 4 == 0);
std::string decoded;
decoded.reserve(length / 4 * 3);
for (size_t i = 0; i < length; i += 4) {
auto temp = (decodeMap[data[i ] - '+'] << 18) +
(decodeMap[data[i + 1] - '+'] << 12) +
(decodeMap[data[i + 2] - '+'] << 6 ) +
(decodeMap[data[i + 3] - '+'] );
decoded.append({static_cast<char>(temp >> 16),
static_cast<char>(temp >> 8),
static_cast<char>(temp)});
}
if (data[length - 1] == '=') { decoded.pop_back(); }
if (data[length - 2] == '=') { decoded.pop_back(); }
return decoded;
}
std::string Base64Encode(const char* data, size_t length) {
static constexpr auto base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encoded;
encoded.reserve(((length / 3) + ((length % 3) > 0)) * 4);
uint_fast32_t temp = 0;
for (size_t i = 0; i < (length / 3); ++i) {
temp = *data++ << 16;
temp += *data++ << 8;
temp += *data++;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
base64chars[(temp & 0b000000000000111111000000) >> 6 ],
base64chars[(temp & 0b000000000000000000111111) ]});
}
switch (length % 3) {
case 1:
temp = *data++ << 16;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
'=',
'='});
break;
case 2:
temp = *data++ << 16;
temp += *data++ << 8;
encoded.append({base64chars[(temp & 0b111111000000000000000000) >> 18],
base64chars[(temp & 0b000000111111000000000000) >> 12],
base64chars[(temp & 0b000000000000111111000000) >> 6 ],
'='});
break;
default:
break;
}
return encoded;
}
std::string URLEncode(const char* str) {
std::ostringstream ret;
while (char c = *str) {
if (isalnum(c) || c == '-' || c == '_' || c == '.') {
ret << c;
} else if (c == ' ') {
ret << '+';
} else {
ret << '%' << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << (int)static_cast<unsigned char>(c);
}
++str;
}
return ret.str();
}
std::string URLDecode(const char* str) {
std::ostringstream ret;
while (char c = *str) {
if (c == '+') {
ret << ' ';
} else if (c == '%' && str[1] && str[2]) {
char tmp[3];
tmp[0] = *++str;
tmp[1] = *++str;
tmp[2] = '\0';
ret << (unsigned char)strtoul(tmp, nullptr, 16);
} else {
ret << c;
}
++str;
}
return ret.str();
}
std::string Basename(const std::string& path) {
auto folder = path.rfind('/');
#if SCRAPS_WINDOWS
if (folder == path.npos) {
folder = path.rfind('\\');
}
#endif
if (folder != path.npos) {
return path.substr(folder+1);
}
return path;
}
std::string Dirname(const std::string& path) {
auto folder = path.rfind('/');
#if SCRAPS_WINDOWS
if (folder == path.npos) {
folder = path.rfind('\\');
}
#endif
if (folder != path.npos) {
return path.substr(0, folder);
}
return path;
}
std::tuple<std::string, uint16_t> ParseAddressAndPort(const std::string& host,
uint16_t defaultPort) {
auto sep = host.find(':');
if (sep == host.npos) {
return std::make_tuple(host, defaultPort);
}
const auto address = host.substr(0, sep);
const auto port = static_cast<uint16_t>(std::atoi(host.substr(sep + 1).c_str()));
return std::make_tuple(address, port);
}
std::string GetPasswordFromStdin() {
#ifdef WIN32
HANDLE stdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(stdin, &mode);
SetConsoleMode(stdin, mode & (~ENABLE_ECHO_INPUT));
#else
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
#endif
std::string password;
std::cout << "Password: " << std::flush;
std::getline(std::cin, password);
return password;
}
size_t PhysicalMemory() {
#if SCRAPS_MACOS
uint64_t mem = 0;
size_t len = sizeof(mem);
return sysctlbyname("hw.memsize", &mem, &len, NULL, 0) == 0 ? mem : 0;
#else
auto pages = sysconf(_SC_PHYS_PAGES);
auto pageSize = sysconf(_SC_PAGE_SIZE);
return (pages > 0 && pageSize > 0) ? pages * pageSize : 0;
#endif
}
stdts::optional<std::vector<Byte>> BytesFromFile(const std::string& path) {
std::ifstream dataFile{path, std::ifstream::ate | std::ios::binary};
const auto fileSize = dataFile.tellg();
if (dataFile.bad() || fileSize <= 0) {
return {};
}
std::vector<Byte> buf;
buf.resize(fileSize);
dataFile.seekg(0, std::ios::beg);
dataFile.read(reinterpret_cast<char*>(buf.data()), fileSize);
if (dataFile.bad()) {
return {};
}
return buf;
}
bool SetBlocking(int fd, bool blocking) {
#ifdef _WIN32
unsigned long arg = blocking ? 1 : 0;
return !ioctlsocket(fd, FIONBIO, &arg);
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) {
return false;
}
return !fcntl(fd, F_SETFL, blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK);
#endif
}
std::string Demangle(const char* mangled) {
#if __clang__ || __GNUC__
struct FreeDeleter { void operator()(char* p) const { std::free(p); } };
int status = 0;
auto demangled = std::unique_ptr<char, FreeDeleter>{abi::__cxa_demangle(mangled, nullptr, nullptr, &status)};
if (status == 0) {
return demangled.get();
}
#endif
return mangled;
}
} // namespace scraps
<|endoftext|>
|
<commit_before>#include "./label_node.h"
#include <QPainter>
#include <QImage>
#include <QPoint>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "./graphics/texture_address.h"
#include "./graphics/shader_program.h"
#include "./importer.h"
#include "./math/eigen.h"
#include "./labelling/labeller_frame_data.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("assets/anchor.dae", 0);
quad = std::make_shared<Graphics::Quad>(":/shader/label.vert",
":/shader/label.frag");
connector = std::make_shared<Graphics::Connector>(
":/shader/pass.vert", ":/shader/connector.frag", Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(1, 0, 0));
connector->color = Eigen::Vector4f(0.75f, 0.75f, 0.75f, 1);
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!label.isAnchorInsideFieldOfView(LabellerFrameData(
0, renderData.projectionMatrix, renderData.viewMatrix)))
return;
if (textureId == -1 || textureText != label.text)
{
initialize(gl, managers);
}
if (isVisible)
renderAnchor(gl, managers, renderData);
}
void
LabelNode::renderLabelAndConnector(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!label.isAnchorInsideFieldOfView(LabellerFrameData(
0, renderData.projectionMatrix, renderData.viewMatrix)))
return;
if (textureId == -1 || textureText != label.text)
{
initialize(gl, managers);
}
if (isVisible)
{
renderConnector(gl, managers, renderData);
renderLabel(gl, managers, renderData);
}
}
void LabelNode::setIsVisible(bool isVisible)
{
this->isVisible = isVisible;
}
void LabelNode::initialize(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers)
{
quad->initialize(gl, managers);
connector->initialize(gl, managers);
auto image = renderLabelTextToQImage();
auto textureManager = managers->getTextureManager();
textureId = textureManager->addTexture(image);
delete image;
if (!labelQuad.isInitialized())
{
labelQuad = quad->getObjectData();
labelQuad.setCustomBuffer(sizeof(Graphics::TextureAddress),
[textureManager, this](void *insertionPoint)
{
auto textureAddress = textureManager->getAddressFor(textureId);
textureAddress.reserved = this->layerIndex;
std::memcpy(insertionPoint, &textureAddress,
sizeof(Graphics::TextureAddress));
});
}
if (!labelConnector.isInitialized())
{
labelConnector = connector->getObjectData();
labelConnector.setCustomBuffer(sizeof(int), [this](void *insertionPoint)
{
std::memcpy(insertionPoint, &this->layerIndex, sizeof(int));
});
}
}
void LabelNode::renderConnector(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
Eigen::Vector3f anchorToPosition = labelPosition - label.anchorPosition;
auto length = anchorToPosition.norm();
auto rotation = Eigen::Quaternionf::FromTwoVectors(Eigen::Vector3f::UnitX(),
anchorToPosition);
Eigen::Affine3f connectorTransform(
Eigen::Translation3f(label.anchorPosition) * rotation *
Eigen::Scaling(length));
labelConnector.modelMatrix = connectorTransform.matrix();
auto shaderId = labelConnector.getShaderProgramId();
auto shader = managers->getShaderManager()->getShader(shaderId);
managers->getShaderManager()->bind(shaderId, renderData);
managers->getObjectManager()->renderImmediately(labelConnector);
}
void LabelNode::renderAnchor(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
anchorNDC =
renderData.viewProjectionMatrix * toVector4f(label.anchorPosition);
anchorNDC /= anchorNDC.w();
float sizeNDC = anchorSize / renderData.windowPixelSize.x();
Eigen::Vector3f sizeWorld =
calculateWorldScale(Eigen::Vector4f(sizeNDC, sizeNDC, anchorNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f anchorTransform(Eigen::Translation3f(label.anchorPosition) *
Eigen::Scaling(sizeWorld.x()));
renderData.modelMatrix = anchorTransform.matrix();
anchorMesh->render(gl, managers, renderData);
}
void LabelNode::renderLabel(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
Eigen::Vector2f sizeNDC =
label.size.cwiseQuotient(renderData.windowPixelSize);
Eigen::Vector3f sizeWorld = calculateWorldScale(
Eigen::Vector4f(sizeNDC.x(), sizeNDC.y(), anchorNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f labelTransform(
Eigen::Translation3f(labelPosition) *
Eigen::Scaling(sizeWorld.x(), sizeWorld.y(), 1.0f));
labelQuad.modelMatrix = labelTransform.matrix();
auto shaderId = labelQuad.getShaderProgramId();
auto shader = managers->getShaderManager()->getShader(shaderId);
managers->getShaderManager()->bind(shaderId, renderData);
managers->getObjectManager()->renderImmediately(labelQuad);
}
QImage *LabelNode::renderLabelTextToQImage()
{
int width = label.size.x() * 4;
int height = label.size.y() * 4;
QImage *image = new QImage(width, height, QImage::Format_ARGB32);
image->fill(Qt::GlobalColor::transparent);
QPainter painter;
painter.begin(image);
painter.setBrush(QBrush(Qt::GlobalColor::lightGray));
painter.setPen(Qt::GlobalColor::lightGray);
painter.drawRoundRect(QRectF(0, 0, width, height), 15, 60);
painter.setPen(Qt::black);
painter.setFont(QFont("Arial", 72));
painter.drawText(QRectF(0, 0, width, height), Qt::AlignCenter,
label.text.c_str());
painter.end();
textureText = label.text;
return image;
}
Eigen::Vector3f LabelNode::calculateWorldScale(Eigen::Vector4f sizeNDC,
Eigen::Matrix4f projectionMatrix)
{
Eigen::Vector4f sizeWorld =
projectionMatrix.inverse() *
Eigen::Vector4f(sizeNDC.x(), sizeNDC.y(), anchorNDC.z(), 1);
sizeWorld /= sizeWorld.w();
return Eigen::Vector3f(sizeWorld.x(), sizeWorld.y(), 1.0f);
}
<commit_msg>Adjust rounded corner of label depending on label aspect ratio.<commit_after>#include "./label_node.h"
#include <QPainter>
#include <QImage>
#include <QPoint>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "./graphics/texture_address.h"
#include "./graphics/shader_program.h"
#include "./importer.h"
#include "./math/eigen.h"
#include "./labelling/labeller_frame_data.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("assets/anchor.dae", 0);
quad = std::make_shared<Graphics::Quad>(":/shader/label.vert",
":/shader/label.frag");
connector = std::make_shared<Graphics::Connector>(
":/shader/pass.vert", ":/shader/connector.frag", Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(1, 0, 0));
connector->color = Eigen::Vector4f(0.75f, 0.75f, 0.75f, 1);
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!label.isAnchorInsideFieldOfView(LabellerFrameData(
0, renderData.projectionMatrix, renderData.viewMatrix)))
return;
if (textureId == -1 || textureText != label.text)
{
initialize(gl, managers);
}
if (isVisible)
renderAnchor(gl, managers, renderData);
}
void
LabelNode::renderLabelAndConnector(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!label.isAnchorInsideFieldOfView(LabellerFrameData(
0, renderData.projectionMatrix, renderData.viewMatrix)))
return;
if (textureId == -1 || textureText != label.text)
{
initialize(gl, managers);
}
if (isVisible)
{
renderConnector(gl, managers, renderData);
renderLabel(gl, managers, renderData);
}
}
void LabelNode::setIsVisible(bool isVisible)
{
this->isVisible = isVisible;
}
void LabelNode::initialize(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers)
{
quad->initialize(gl, managers);
connector->initialize(gl, managers);
auto image = renderLabelTextToQImage();
auto textureManager = managers->getTextureManager();
textureId = textureManager->addTexture(image);
delete image;
if (!labelQuad.isInitialized())
{
labelQuad = quad->getObjectData();
labelQuad.setCustomBuffer(sizeof(Graphics::TextureAddress),
[textureManager, this](void *insertionPoint)
{
auto textureAddress = textureManager->getAddressFor(textureId);
textureAddress.reserved = this->layerIndex;
std::memcpy(insertionPoint, &textureAddress,
sizeof(Graphics::TextureAddress));
});
}
if (!labelConnector.isInitialized())
{
labelConnector = connector->getObjectData();
labelConnector.setCustomBuffer(sizeof(int), [this](void *insertionPoint)
{
std::memcpy(insertionPoint, &this->layerIndex, sizeof(int));
});
}
}
void LabelNode::renderConnector(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
Eigen::Vector3f anchorToPosition = labelPosition - label.anchorPosition;
auto length = anchorToPosition.norm();
auto rotation = Eigen::Quaternionf::FromTwoVectors(Eigen::Vector3f::UnitX(),
anchorToPosition);
Eigen::Affine3f connectorTransform(
Eigen::Translation3f(label.anchorPosition) * rotation *
Eigen::Scaling(length));
labelConnector.modelMatrix = connectorTransform.matrix();
auto shaderId = labelConnector.getShaderProgramId();
auto shader = managers->getShaderManager()->getShader(shaderId);
managers->getShaderManager()->bind(shaderId, renderData);
managers->getObjectManager()->renderImmediately(labelConnector);
}
void LabelNode::renderAnchor(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
anchorNDC =
renderData.viewProjectionMatrix * toVector4f(label.anchorPosition);
anchorNDC /= anchorNDC.w();
float sizeNDC = anchorSize / renderData.windowPixelSize.x();
Eigen::Vector3f sizeWorld =
calculateWorldScale(Eigen::Vector4f(sizeNDC, sizeNDC, anchorNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f anchorTransform(Eigen::Translation3f(label.anchorPosition) *
Eigen::Scaling(sizeWorld.x()));
renderData.modelMatrix = anchorTransform.matrix();
anchorMesh->render(gl, managers, renderData);
}
void LabelNode::renderLabel(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
Eigen::Vector2f sizeNDC =
label.size.cwiseQuotient(renderData.windowPixelSize);
Eigen::Vector3f sizeWorld = calculateWorldScale(
Eigen::Vector4f(sizeNDC.x(), sizeNDC.y(), anchorNDC.z(), 1),
renderData.projectionMatrix);
Eigen::Affine3f labelTransform(
Eigen::Translation3f(labelPosition) *
Eigen::Scaling(sizeWorld.x(), sizeWorld.y(), 1.0f));
labelQuad.modelMatrix = labelTransform.matrix();
auto shaderId = labelQuad.getShaderProgramId();
auto shader = managers->getShaderManager()->getShader(shaderId);
managers->getShaderManager()->bind(shaderId, renderData);
managers->getObjectManager()->renderImmediately(labelQuad);
}
QImage *LabelNode::renderLabelTextToQImage()
{
int width = label.size.x() * 4;
int height = label.size.y() * 4;
QImage *image = new QImage(width, height, QImage::Format_ARGB32);
image->fill(Qt::GlobalColor::transparent);
QPainter painter;
painter.begin(image);
painter.setBrush(QBrush(Qt::GlobalColor::lightGray));
painter.setPen(Qt::GlobalColor::lightGray);
painter.drawRoundRect(QRectF(0, 0, width, height), 15, 15 * width / height);
painter.setPen(Qt::black);
painter.setFont(QFont("Arial", 72));
painter.drawText(QRectF(0, 0, width, height), Qt::AlignCenter,
label.text.c_str());
painter.end();
textureText = label.text;
return image;
}
Eigen::Vector3f LabelNode::calculateWorldScale(Eigen::Vector4f sizeNDC,
Eigen::Matrix4f projectionMatrix)
{
Eigen::Vector4f sizeWorld =
projectionMatrix.inverse() *
Eigen::Vector4f(sizeNDC.x(), sizeNDC.y(), anchorNDC.z(), 1);
sizeWorld /= sizeWorld.w();
return Eigen::Vector3f(sizeWorld.x(), sizeWorld.y(), 1.0f);
}
<|endoftext|>
|
<commit_before>#ifndef UTILITY_H
#define UTILITY_H
#include <string>
#include <vector>
#include <sstream>
#include <omp.h>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include "vg.pb.h"
#include "sha1.hpp"
#include "Variant.h"
namespace vg {
using namespace std;
char reverse_complement(const char& c);
string reverse_complement(const string& seq);
int get_thread_count(void);
string wrap_text(const string& str, size_t width);
bool is_number(const string& s);
// split a string on any character found in the string of delimiters (delims)
std::vector<std::string>& split_delims(const std::string &s, const std::string& delims, std::vector<std::string> &elems);
std::vector<std::string> split_delims(const std::string &s, const std::string& delims);
const std::string sha1sum(const std::string& data);
const std::string sha1head(const std::string& data, size_t head);
bool allATGC(const string& s);
string nonATGCNtoN(const string& s);
double median(std::vector<int> &v);
double stdev(const std::vector<double>& v);
template<typename T>
double stdev(const T& v) {
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
return std::sqrt(sq_sum / v.size());
}
// Convert a probability to a natural log probability.
inline double prob_to_logprob(double prob) {
return log(prob);
}
// Convert natural log probability to a probability
inline double logprob_to_prob(double logprob) {
return exp(logprob);
}
// Add two probabilities (expressed as logprobs) together and return the result
// as a logprob.
inline double logprob_add(double logprob1, double logprob2) {
// Pull out the larger one to avoid underflows
double pulled_out = max(logprob1, logprob2);
return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));
}
// Invert a logprob, and get the probability of its opposite.
inline double logprob_invert(double logprob) {
return prob_to_logprob(1.0 - logprob_to_prob(logprob));
}
// Convert integer Phred quality score to probability of wrongness.
inline double phred_to_prob(int phred) {
return pow(10, -((double)phred) / 10);
}
// Convert probability of wrongness to integer Phred quality score.
inline int prob_to_phred(double prob) {
return round(-10.0 * log10(prob));
}
// Convert a Phred quality score directly to a natural log probability of wrongness.
inline double phred_to_logprob(int phred) {
return (-((double)phred) / 10) / log10(exp(1.0));
}
// Convert a natural log probability of wrongness directly to a Phred quality score.
inline int logprob_to_phred(double logprob ) {
return round(-10.0 * logprob * log10(exp(1.0)));
}
template<typename T, typename V>
set<T> map_keys_to_set(const map<T, V>& m) {
set<T> r;
for (auto p : m) r.insert(p.first);
return r;
}
// pairwise maximum
template<typename T>
vector<T> pmax(const std::vector<T>& a, const std::vector<T>& b) {
std::vector<T> c;
assert(a.size() == b.size());
c.reserve(a.size());
std::transform(a.begin(), a.end(), b.begin(),
std::back_inserter(c),
[](T a, T b) { return std::max<T>(a, b); });
return c;
}
// maximum of all vectors
template<typename T>
vector<T> vpmax(const std::vector<std::vector<T>>& vv) {
std::vector<T> c;
if (vv.empty()) return c;
c = vv.front();
typename std::vector<std::vector<T> >::const_iterator v = vv.begin();
++v; // skip the first element
for ( ; v != vv.end(); ++v) {
c = pmax(c, *v);
}
return c;
}
/**
* Compute the sum of the values in a collection. Values must be default-
* constructable (like numbers are).
*/
template<typename Collection>
typename Collection::value_type sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Make a new zero-valued item to hold the sum
auto total = Item();
for(auto& to_sum : collection) {
total += to_sum;
}
return total;
}
/**
* Compute the sum of the values in a collection, where the values are log
* probabilities and the result is the log of the total probability. Items must
* be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type logprob_sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Pull out the minimum value
auto min_iterator = min_element(begin(collection), end(collection));
if(min_iterator == end(collection)) {
// Nothing there, p = 0
return Item(prob_to_logprob(0));
}
auto check_iterator = begin(collection);
++check_iterator;
if(check_iterator == end(collection)) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
Item pulled_out = *min_iterator;
if(logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
Item total(0);
for(auto& to_add : collection) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(to_add - pulled_out);
}
// Re-log and re-scale
return pulled_out + prob_to_logprob(total);
}
string tmpfilename(const string& base);
// Code to detect if a variant lacks an ID and give it a unique but repeatable
// one.
string get_or_make_variant_id(vcflib::Variant variant);
// Simple little tree
template<typename T>
struct TreeNode {
T v;
vector<TreeNode<T>*> children;
~TreeNode() { for (auto c : children) { delete c; } }
void for_each_preorder(function<void(TreeNode<T>*)> lambda) {
lambda(this);
for (auto c : children) {
c->for_each_preorder(lambda);
}
}
void for_each_postorder(function<void(TreeNode<T>*)> lambda) {
for (auto c : children) {
c->for_each_postorder(lambda);
}
lambda(this);
}
};
template<typename T>
struct Tree {
typedef TreeNode<T> Node;
Node* root;
Tree(Node* r = 0) : root(r) {}
~Tree() { delete root; }
void for_each_preorder(function<void(Node*)> lambda) {
if (root) root->for_each_preorder(lambda);
}
void for_each_postorder(function<void(Node*)> lambda) {
if (root) root->for_each_postorder(lambda);
}
};
}
#endif
<commit_msg>src/utility.hpp - adds include to build with gcc (GCC) 6.1.1 20160802<commit_after>#ifndef UTILITY_H
#define UTILITY_H
#include <string>
#include <vector>
#include <sstream>
#include <omp.h>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <unistd.h>
#include "vg.pb.h"
#include "sha1.hpp"
#include "Variant.h"
namespace vg {
using namespace std;
char reverse_complement(const char& c);
string reverse_complement(const string& seq);
int get_thread_count(void);
string wrap_text(const string& str, size_t width);
bool is_number(const string& s);
// split a string on any character found in the string of delimiters (delims)
std::vector<std::string>& split_delims(const std::string &s, const std::string& delims, std::vector<std::string> &elems);
std::vector<std::string> split_delims(const std::string &s, const std::string& delims);
const std::string sha1sum(const std::string& data);
const std::string sha1head(const std::string& data, size_t head);
bool allATGC(const string& s);
string nonATGCNtoN(const string& s);
double median(std::vector<int> &v);
double stdev(const std::vector<double>& v);
template<typename T>
double stdev(const T& v) {
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
return std::sqrt(sq_sum / v.size());
}
// Convert a probability to a natural log probability.
inline double prob_to_logprob(double prob) {
return log(prob);
}
// Convert natural log probability to a probability
inline double logprob_to_prob(double logprob) {
return exp(logprob);
}
// Add two probabilities (expressed as logprobs) together and return the result
// as a logprob.
inline double logprob_add(double logprob1, double logprob2) {
// Pull out the larger one to avoid underflows
double pulled_out = max(logprob1, logprob2);
return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));
}
// Invert a logprob, and get the probability of its opposite.
inline double logprob_invert(double logprob) {
return prob_to_logprob(1.0 - logprob_to_prob(logprob));
}
// Convert integer Phred quality score to probability of wrongness.
inline double phred_to_prob(int phred) {
return pow(10, -((double)phred) / 10);
}
// Convert probability of wrongness to integer Phred quality score.
inline int prob_to_phred(double prob) {
return round(-10.0 * log10(prob));
}
// Convert a Phred quality score directly to a natural log probability of wrongness.
inline double phred_to_logprob(int phred) {
return (-((double)phred) / 10) / log10(exp(1.0));
}
// Convert a natural log probability of wrongness directly to a Phred quality score.
inline int logprob_to_phred(double logprob ) {
return round(-10.0 * logprob * log10(exp(1.0)));
}
template<typename T, typename V>
set<T> map_keys_to_set(const map<T, V>& m) {
set<T> r;
for (auto p : m) r.insert(p.first);
return r;
}
// pairwise maximum
template<typename T>
vector<T> pmax(const std::vector<T>& a, const std::vector<T>& b) {
std::vector<T> c;
assert(a.size() == b.size());
c.reserve(a.size());
std::transform(a.begin(), a.end(), b.begin(),
std::back_inserter(c),
[](T a, T b) { return std::max<T>(a, b); });
return c;
}
// maximum of all vectors
template<typename T>
vector<T> vpmax(const std::vector<std::vector<T>>& vv) {
std::vector<T> c;
if (vv.empty()) return c;
c = vv.front();
typename std::vector<std::vector<T> >::const_iterator v = vv.begin();
++v; // skip the first element
for ( ; v != vv.end(); ++v) {
c = pmax(c, *v);
}
return c;
}
/**
* Compute the sum of the values in a collection. Values must be default-
* constructable (like numbers are).
*/
template<typename Collection>
typename Collection::value_type sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Make a new zero-valued item to hold the sum
auto total = Item();
for(auto& to_sum : collection) {
total += to_sum;
}
return total;
}
/**
* Compute the sum of the values in a collection, where the values are log
* probabilities and the result is the log of the total probability. Items must
* be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type logprob_sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Pull out the minimum value
auto min_iterator = min_element(begin(collection), end(collection));
if(min_iterator == end(collection)) {
// Nothing there, p = 0
return Item(prob_to_logprob(0));
}
auto check_iterator = begin(collection);
++check_iterator;
if(check_iterator == end(collection)) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
Item pulled_out = *min_iterator;
if(logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
Item total(0);
for(auto& to_add : collection) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(to_add - pulled_out);
}
// Re-log and re-scale
return pulled_out + prob_to_logprob(total);
}
string tmpfilename(const string& base);
// Code to detect if a variant lacks an ID and give it a unique but repeatable
// one.
string get_or_make_variant_id(vcflib::Variant variant);
// Simple little tree
template<typename T>
struct TreeNode {
T v;
vector<TreeNode<T>*> children;
~TreeNode() { for (auto c : children) { delete c; } }
void for_each_preorder(function<void(TreeNode<T>*)> lambda) {
lambda(this);
for (auto c : children) {
c->for_each_preorder(lambda);
}
}
void for_each_postorder(function<void(TreeNode<T>*)> lambda) {
for (auto c : children) {
c->for_each_postorder(lambda);
}
lambda(this);
}
};
template<typename T>
struct Tree {
typedef TreeNode<T> Node;
Node* root;
Tree(Node* r = 0) : root(r) {}
~Tree() { delete root; }
void for_each_preorder(function<void(Node*)> lambda) {
if (root) root->for_each_preorder(lambda);
}
void for_each_postorder(function<void(Node*)> lambda) {
if (root) root->for_each_postorder(lambda);
}
};
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: updatesvc.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2003-04-17 13:20:24 $
*
* 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: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "updatesvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_EMPTYLAYER_HXX
#include "emptylayer.hxx"
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATABLELAYER_HPP_
#include <com/sun/star/configuration/backend/XUpdatableLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_
#include <com/sun/star/configuration/backend/XLayerHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace beans = ::com::sun::star::beans;
namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
AsciiServiceName const aUpdateMergerServices[] =
{
"com.sun.star.configuration.backend.LayerUpdateMerger",
0
};
const ServiceImplementationInfo aUpdateMergerSI =
{
"com.sun.star.comp.configuration.backend.LayerUpdateMerger",
aUpdateMergerServices,
0
};
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getUpdateMergerServiceInfo()
{ return getRegistrationInfo(& aUpdateMergerSI); }
// -----------------------------------------------------------------------------
inline
ServiceInfoHelper UpdateService::getServiceInfo()
{
return & aUpdateMergerSI;
}
// -----------------------------------------------------------------------------
UpdateService::UpdateService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(),uno::UNO_QUERY)
, m_aSourceMode(merge)
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Update Merger: Context has no service manager (or missing interface)"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
void SAL_CALL
UpdateService::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
sal_Int16 const nCount = static_cast<sal_Int16>(aArguments.getLength());
if (sal_Int32(nCount) != aArguments.getLength())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Update Merger"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
for (sal_Int16 i = 0; i < nCount; ++i)
{
uno::Reference< backenduno::XUpdatableLayer > xUpdLayer;
if (aArguments[i] >>= xUpdLayer)
{
m_xSourceLayer = xUpdLayer.get();
m_xLayerWriter.clear();
OSL_ASSERT( uno::Reference< backenduno::XUpdatableLayer >::query(m_xSourceLayer).is() || !xUpdLayer.is() );
continue;
}
if (aArguments[i] >>= m_xSourceLayer)
continue;
if (aArguments[i] >>= m_xLayerWriter)
continue;
beans::NamedValue aExtraArg;
if (aArguments[i] >>= aExtraArg)
{
OSL_VERIFY( setImplementationProperty(aExtraArg.Name, aExtraArg.Value) );
continue;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Update Merger"
"- XLayer, XLayerHandler or XUpdatableLayer expected"));
throw lang::IllegalArgumentException(sMessage,*this,i);
}
}
// -----------------------------------------------------------------------------
sal_Bool UpdateService::setImplementationProperty(OUString const & aName, uno::Any const & aValue)
{
if (aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Overwrite")))
{
sal_Bool bOverwrite;
if (aValue >>= bOverwrite)
{
if (!bOverwrite)
m_aSourceMode = protect;
else if (protect == m_aSourceMode)
m_aSourceMode = merge;
return true;
}
}
else if (aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Truncate")))
{
sal_Bool bTruncate;
if (aValue >>= bTruncate)
{
if (!bTruncate)
m_aSourceMode = merge;
else if (merge == m_aSourceMode)
m_aSourceMode = truncate;
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------
bool UpdateService::validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) )
{
switch (m_aSourceMode)
{
case merge: // TODO: check for readonly layer
return true;
case protect: if (!checkEmptyLayer(m_xSourceLayer))
raiseIllegalAccessException("UpdateService: Layer already exists");
// else fall through
case truncate: return false;
default: OSL_ASSERT(!"not reached");
return true;
}
}
// -----------------------------------------------------------------------------
UpdateService::Layer UpdateService::getSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
{
if ( validateSourceLayerAndCheckNotEmpty() )
return m_xSourceLayer;
else
return createEmptyLayer();
}
// -----------------------------------------------------------------------------
void UpdateService::raiseIllegalAccessException(sal_Char const * pMsg)
SAL_THROW( (lang::IllegalAccessException) )
{
OUString sMsg = OUString::createFromAscii(pMsg);
throw lang::IllegalAccessException(sMsg,*this);
}
// -----------------------------------------------------------------------------
void UpdateService::writeUpdatedLayer(Layer const & _xLayer)
{
OSL_ENSURE( _xLayer.is(), "UpdateService: Trying to write NULL XLayer");
if (!_xLayer.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Update Merger - Internal error: trying to write a NULL Layer"));
throw uno::RuntimeException(sMessage,*this);
}
// use our layer writer, if we have one
if ( m_xLayerWriter.is() )
{
_xLayer->readData( m_xLayerWriter );
return;
}
// look for an updatable layer otherwise
uno::Reference< backenduno::XUpdatableLayer > xUpdLayer(m_xSourceLayer, uno::UNO_QUERY);
if (xUpdLayer.is())
{
xUpdLayer->replaceWith( _xLayer );
return;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Update Merger: Cannot write merge results - no recipient available."));
throw uno::RuntimeException(sMessage,*this);
}
// -----------------------------------------------------------------------------
// XServiceInfo
::rtl::OUString SAL_CALL
UpdateService::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName( );
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL
UpdateService::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL
UpdateService::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.180); FILE MERGED 2005/09/05 17:04:08 rt 1.8.180.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: updatesvc.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:35:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "updatesvc.hxx"
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_BACKEND_EMPTYLAYER_HXX
#include "emptylayer.hxx"
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATABLELAYER_HPP_
#include <com/sun/star/configuration/backend/XUpdatableLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_
#include <com/sun/star/configuration/backend/XLayerHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace beans = ::com::sun::star::beans;
namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
AsciiServiceName const aUpdateMergerServices[] =
{
"com.sun.star.configuration.backend.LayerUpdateMerger",
0
};
const ServiceImplementationInfo aUpdateMergerSI =
{
"com.sun.star.comp.configuration.backend.LayerUpdateMerger",
aUpdateMergerServices,
0
};
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getUpdateMergerServiceInfo()
{ return getRegistrationInfo(& aUpdateMergerSI); }
// -----------------------------------------------------------------------------
inline
ServiceInfoHelper UpdateService::getServiceInfo()
{
return & aUpdateMergerSI;
}
// -----------------------------------------------------------------------------
UpdateService::UpdateService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(),uno::UNO_QUERY)
, m_aSourceMode(merge)
{
if (!m_xServiceFactory.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Update Merger: Context has no service manager (or missing interface)"));
throw uno::RuntimeException(sMessage,NULL);
}
}
// -----------------------------------------------------------------------------
// XInitialization
void SAL_CALL
UpdateService::initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException)
{
sal_Int16 const nCount = static_cast<sal_Int16>(aArguments.getLength());
if (sal_Int32(nCount) != aArguments.getLength())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Update Merger"));
throw lang::IllegalArgumentException(sMessage,*this,0);
}
for (sal_Int16 i = 0; i < nCount; ++i)
{
uno::Reference< backenduno::XUpdatableLayer > xUpdLayer;
if (aArguments[i] >>= xUpdLayer)
{
m_xSourceLayer = xUpdLayer.get();
m_xLayerWriter.clear();
OSL_ASSERT( uno::Reference< backenduno::XUpdatableLayer >::query(m_xSourceLayer).is() || !xUpdLayer.is() );
continue;
}
if (aArguments[i] >>= m_xSourceLayer)
continue;
if (aArguments[i] >>= m_xLayerWriter)
continue;
beans::NamedValue aExtraArg;
if (aArguments[i] >>= aExtraArg)
{
OSL_VERIFY( setImplementationProperty(aExtraArg.Name, aExtraArg.Value) );
continue;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Update Merger"
"- XLayer, XLayerHandler or XUpdatableLayer expected"));
throw lang::IllegalArgumentException(sMessage,*this,i);
}
}
// -----------------------------------------------------------------------------
sal_Bool UpdateService::setImplementationProperty(OUString const & aName, uno::Any const & aValue)
{
if (aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Overwrite")))
{
sal_Bool bOverwrite;
if (aValue >>= bOverwrite)
{
if (!bOverwrite)
m_aSourceMode = protect;
else if (protect == m_aSourceMode)
m_aSourceMode = merge;
return true;
}
}
else if (aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Truncate")))
{
sal_Bool bTruncate;
if (aValue >>= bTruncate)
{
if (!bTruncate)
m_aSourceMode = merge;
else if (merge == m_aSourceMode)
m_aSourceMode = truncate;
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------
bool UpdateService::validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) )
{
switch (m_aSourceMode)
{
case merge: // TODO: check for readonly layer
return true;
case protect: if (!checkEmptyLayer(m_xSourceLayer))
raiseIllegalAccessException("UpdateService: Layer already exists");
// else fall through
case truncate: return false;
default: OSL_ASSERT(!"not reached");
return true;
}
}
// -----------------------------------------------------------------------------
UpdateService::Layer UpdateService::getSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
{
if ( validateSourceLayerAndCheckNotEmpty() )
return m_xSourceLayer;
else
return createEmptyLayer();
}
// -----------------------------------------------------------------------------
void UpdateService::raiseIllegalAccessException(sal_Char const * pMsg)
SAL_THROW( (lang::IllegalAccessException) )
{
OUString sMsg = OUString::createFromAscii(pMsg);
throw lang::IllegalAccessException(sMsg,*this);
}
// -----------------------------------------------------------------------------
void UpdateService::writeUpdatedLayer(Layer const & _xLayer)
{
OSL_ENSURE( _xLayer.is(), "UpdateService: Trying to write NULL XLayer");
if (!_xLayer.is())
{
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Update Merger - Internal error: trying to write a NULL Layer"));
throw uno::RuntimeException(sMessage,*this);
}
// use our layer writer, if we have one
if ( m_xLayerWriter.is() )
{
_xLayer->readData( m_xLayerWriter );
return;
}
// look for an updatable layer otherwise
uno::Reference< backenduno::XUpdatableLayer > xUpdLayer(m_xSourceLayer, uno::UNO_QUERY);
if (xUpdLayer.is())
{
xUpdLayer->replaceWith( _xLayer );
return;
}
OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Update Merger: Cannot write merge results - no recipient available."));
throw uno::RuntimeException(sMessage,*this);
}
// -----------------------------------------------------------------------------
// XServiceInfo
::rtl::OUString SAL_CALL
UpdateService::getImplementationName( )
throw (uno::RuntimeException)
{
return getServiceInfo().getImplementationName( );
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL
UpdateService::supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException)
{
return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL
UpdateService::getSupportedServiceNames( )
throw (uno::RuntimeException)
{
return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
} // namespace
<|endoftext|>
|
<commit_before>#include "version.hpp"
// Get the git version macro from the build system
#include "vg_git_version.hpp"
// Do the same for the build environment info
#include "vg_environment_version.hpp"
#include <iostream>
#include <sstream>
namespace vg {
using namespace std;
// Define all the strings as the macros' values
const string Version::VERSION = VG_GIT_VERSION;
const string Version::COMPILER = VG_COMPILER_VERSION;
const string Version::OS = VG_OS;
const string Version::BUILD_USER = VG_BUILD_USER;
const string Version::BUILD_HOST = VG_BUILD_HOST;
// Keep the list of codenames.
// Add new codenames here
const unordered_map<string, string> Version::codenames = {
{"v1.8.0", "Vallata"},
{"v1.9.0", "Miglionico"},
{"v1.10.0", "Rionero"},
{"v1.11.0", "Cairano"},
{"v1.12.0", "Parolise"},
{"v1.13.0", "Moschiano"},
{"v1.14.0", "Quadrelle"},
{"v1.15.0", "Tufo"},
{"v1.16.0", "Rotondi"},
{"v1.17.0", "Candida"},
{"v1.18.0", "Zungoli"},
{"v1.19.0", "Tramutola"},
{"v1.20.0", "Ginestra"}
// Add more codenames here
};
string Version::get_version() {
return VERSION;
}
string Version::get_release() {
auto dash = VERSION.find('-');
if (dash == -1) {
// Pure tag versions have no dash
return VERSION;
} else {
// Otherwise it is tag-count-ghash and the tag describes the release
return VERSION.substr(0, dash);
}
}
string Version::get_codename() {
auto release = get_release();
auto found = codenames.find(release);
if (found == codenames.end()) {
// No known codename for this release.
// Return an empty string so we can just not show it.
return "";
} else {
// We have a known codename!
return found->second;
}
}
string Version::get_short() {
stringstream s;
s << VERSION;
auto codename = get_codename();
if (!codename.empty()) {
// Add the codename if we have one
s << " \"" << codename << "\"";
}
return s.str();
}
string Version::get_long() {
stringstream s;
s << "vg version " << get_short() << endl;
s << "Compiled with " << COMPILER << " on " << OS << endl;
s << "Built by " << BUILD_USER << "@" << BUILD_HOST;
return s.str();
}
}
<commit_msg>Add codename for patch<commit_after>#include "version.hpp"
// Get the git version macro from the build system
#include "vg_git_version.hpp"
// Do the same for the build environment info
#include "vg_environment_version.hpp"
#include <iostream>
#include <sstream>
namespace vg {
using namespace std;
// Define all the strings as the macros' values
const string Version::VERSION = VG_GIT_VERSION;
const string Version::COMPILER = VG_COMPILER_VERSION;
const string Version::OS = VG_OS;
const string Version::BUILD_USER = VG_BUILD_USER;
const string Version::BUILD_HOST = VG_BUILD_HOST;
// Keep the list of codenames.
// Add new codenames here
const unordered_map<string, string> Version::codenames = {
{"v1.8.0", "Vallata"},
{"v1.9.0", "Miglionico"},
{"v1.10.0", "Rionero"},
{"v1.11.0", "Cairano"},
{"v1.12.0", "Parolise"},
{"v1.12.1", "Parolise"},
{"v1.13.0", "Moschiano"},
{"v1.14.0", "Quadrelle"},
{"v1.15.0", "Tufo"},
{"v1.16.0", "Rotondi"},
{"v1.17.0", "Candida"},
{"v1.18.0", "Zungoli"},
{"v1.19.0", "Tramutola"},
{"v1.20.0", "Ginestra"}
// Add more codenames here
};
string Version::get_version() {
return VERSION;
}
string Version::get_release() {
auto dash = VERSION.find('-');
if (dash == -1) {
// Pure tag versions have no dash
return VERSION;
} else {
// Otherwise it is tag-count-ghash and the tag describes the release
return VERSION.substr(0, dash);
}
}
string Version::get_codename() {
auto release = get_release();
auto found = codenames.find(release);
if (found == codenames.end()) {
// No known codename for this release.
// Return an empty string so we can just not show it.
return "";
} else {
// We have a known codename!
return found->second;
}
}
string Version::get_short() {
stringstream s;
s << VERSION;
auto codename = get_codename();
if (!codename.empty()) {
// Add the codename if we have one
s << " \"" << codename << "\"";
}
return s.str();
}
string Version::get_long() {
stringstream s;
s << "vg version " << get_short() << endl;
s << "Compiled with " << COMPILER << " on " << OS << endl;
s << "Built by " << BUILD_USER << "@" << BUILD_HOST;
return s.str();
}
}
<|endoftext|>
|
<commit_before>#include "config.h"
#ifdef CONFIG_XFREETYPE
#include "ystring.h"
#include "ypaint.h"
#include "yxapp.h"
#include "intl.h"
#include <stdio.h>
#ifdef CONFIG_FRIBIDI
// remove deprecated warnings for now...
#include <fribidi/fribidi-config.h>
#if FRIBIDI_USE_GLIB+0
#include <glib.h>
#undef G_GNUC_DEPRECATED
#define G_GNUC_DEPRECATED
#endif
#include <fribidi/fribidi.h>
#endif
/******************************************************************************/
class YXftFont : public YFont {
public:
#ifdef CONFIG_I18N
typedef class YUnicodeString string_t;
typedef XftChar32 char_t;
#else
typedef class YLocaleString string_t;
typedef XftChar8 char_t;
#endif
YXftFont(ustring name, bool xlfd, bool antialias);
virtual ~YXftFont();
virtual bool valid() const { return (fFontCount > 0); }
virtual int descent() const { return fDescent; }
virtual int ascent() const { return fAscent; }
virtual int textWidth(const ustring &s) const;
virtual int textWidth(char const * str, int len) const;
virtual int textWidth(string_t const & str) const;
virtual void drawGlyphs(class Graphics & graphics, int x, int y,
char const * str, int len);
private:
struct TextPart {
XftFont * font;
size_t length;
unsigned width;
};
TextPart * partitions(char_t * str, size_t len, size_t nparts = 0) const;
unsigned fFontCount, fAscent, fDescent;
XftFont ** fFonts;
};
class XftGraphics {
public:
#ifdef CONFIG_I18N
typedef XftChar32 char_t;
#define XftDrawString XftDrawString32
#define XftTextExtents XftTextExtents32
#else
typedef XftChar8 char_t;
#define XftTextExtents XftTextExtents8
#define XftDrawString XftDrawString8
#endif
#if 0
void drawRect(Graphics &g, XftColor * color, int x, int y, unsigned w, unsigned h) {
XftDrawRect(fDraw, color, x - xOrigin, y - yOrigin, w, h);
}
#endif
static void drawString(Graphics &g, XftFont * font, int x, int y,
char_t * str, size_t len)
{
XftColor *c = *g.color();
#ifdef CONFIG_FRIBIDI
#define STATIS_STRING_SIZE 256
// Based around upstream (1.3.2) patch with some optimization
// on my end. (reduce unnecessary memory allocation)
// - Gilboa
char_t static_str[STATIS_STRING_SIZE];
char_t *vis_str = static_str;
if (len >= STATIS_STRING_SIZE)
{
vis_str = new char_t[len+1];
if (!vis_str)
return;
}
FriBidiCharType pbase_dir = FRIBIDI_TYPE_N;
if (fribidi_log2vis(str, len, &pbase_dir, //input
vis_str, // output
NULL, NULL, NULL // "statistics" that we don't need
)) ;
str = vis_str;
#endif
XftDrawString(g.handleXft(), c, font,
x - g.xorigin(),
y - g.yorigin(),
str, len);
#ifdef CONFIG_FRIBIDI
if (vis_str != static_str)
delete[] str;
#endif
}
static void textExtents(XftFont * font, char_t * str, size_t len,
XGlyphInfo & extends) {
XftTextExtents(xapp->display (), font, str, len, &extends);
}
// XftDraw * handle() const { return fDraw; }
};
/******************************************************************************/
YXftFont::YXftFont(ustring name, bool use_xlfd, bool /*antialias*/):
fFontCount(0), fAscent(0), fDescent(0)
{
fFontCount = 0;
ustring s(null), r(null);
for (s = name; s.splitall(',', &s, &r); s = r) {
fFontCount++;
}
XftFont ** fptr(fFonts = new XftFont* [fFontCount]);
for (s = name; s.splitall(',', &s, &r); s = r) {
// for (char const *s(name); '\0' != *s; s = strnxt(s, ",")) {
XftFont *& font(*fptr);
ustring fname = s.trim();
//char * fname(newstr(s + strspn(s, " \t\r\n"), ","));
//char * endptr(fname + strlen(fname) - 1);
//while (endptr > fname && strchr(" \t\r\n", *endptr)) --endptr;
//endptr[1] = '\0';
cstring cs(fname);
if (use_xlfd) {
font = XftFontOpenXlfd(xapp->display(), xapp->screen(), cs.c_str());
} else {
font = XftFontOpenName(xapp->display(), xapp->screen(), cs.c_str());
}
if (NULL != font) {
fAscent = max(fAscent, (unsigned) max(0, font->ascent));
fDescent = max(fDescent, (unsigned) max(0, font->descent));
++fptr;
} else {
warn(_("Could not load font \"%s\"."), cs.c_str());
--fFontCount;
}
}
if (0 == fFontCount) {
msg("xft: fallback from '%s'", cstring(name).c_str());
XftFont *sans =
XftFontOpen(xapp->display(), xapp->screen(),
XFT_FAMILY, XftTypeString, "sans-serif",
XFT_PIXEL_SIZE, XftTypeInteger, 12,
NULL);
if (NULL != sans) {
delete[] fFonts;
fFontCount = 1;
fFonts = new XftFont* [fFontCount];
fFonts[0] = sans;
fAscent = sans->ascent;
fDescent = sans->descent;
} else
warn(_("Loading of fallback font \"%s\" failed."), "sans-serif");
}
}
YXftFont::~YXftFont() {
for (unsigned n = 0; n < fFontCount; ++n) {
// this leaks memory when xapp is destroyed before fonts
if (xapp != 0)
XftFontClose(xapp->display(), fFonts[n]);
}
delete[] fFonts;
}
int YXftFont::textWidth(const ustring &s) const {
cstring cs(s);
return textWidth(cs.c_str(), cs.c_str_len());
}
int YXftFont::textWidth(string_t const & text) const {
char_t * str((char_t *) text.data());
size_t len(text.length());
TextPart *parts = partitions(str, len);
unsigned width(0);
for (TextPart * p = parts; p && p->length; ++p) width+= p->width;
delete[] parts;
return width;
}
int YXftFont::textWidth(char const * str, int len) const {
return textWidth(string_t(str, len));
}
void YXftFont::drawGlyphs(Graphics & graphics, int x, int y,
char const * str, int len) {
string_t xtext(str, len);
if (0 == xtext.length()) return;
int const y0(y - ascent());
int const gcFn(graphics.function());
char_t * xstr((char_t *) xtext.data());
size_t xlen(xtext.length());
TextPart *parts = partitions(xstr, xlen);
/// unsigned w(0);
/// unsigned const h(height());
/// for (TextPart *p = parts; p && p->length; ++p) w+= p->width;
/// YPixmap *pixmap = new YPixmap(w, h);
/// Graphics canvas(*pixmap, 0, 0);
// XftGraphics textarea(graphics, xapp->visual(), xapp->colormap());
switch (gcFn) {
case GXxor:
/// textarea.drawRect(*YColor::black, 0, 0, w, h);
break;
case GXcopy:
/// canvas.copyDrawable(graphics.drawable(),
/// x - graphics.xorigin(), y0 - graphics.yorigin(), w, h, 0, 0);
break;
}
int xpos(0);
for (TextPart *p = parts; p && p->length; ++p) {
if (p->font) {
XftGraphics::drawString(graphics, p->font,
xpos + x, ascent() + y0,
xstr, p->length);
}
xstr += p->length;
xpos += p->width;
}
delete[] parts;
/// graphics.copyDrawable(canvas.drawable(), 0, 0, w, h, x, y0);
/// delete pixmap;
}
YXftFont::TextPart * YXftFont::partitions(char_t * str, size_t len,
size_t nparts) const
{
XGlyphInfo extends;
XftFont ** lFont(fFonts + fFontCount);
XftFont ** font(NULL);
char_t * c(str);
for (char_t * endptr(str + len); c < endptr; ++c) {
XftFont ** probe(fFonts);
while (probe < lFont && !XftGlyphExists(xapp->display(), *probe, *c))
++probe;
if (probe != font) {
if (NULL != font) {
TextPart *parts = partitions(c, len - (c - str), nparts + 1);
parts[nparts].length = (c - str);
if (font < lFont) {
XftGraphics::textExtents(*font, str, (c - str), extends);
parts[nparts].font = *font;
parts[nparts].width = extends.xOff;
} else {
parts[nparts].font = NULL;
parts[nparts].width = 0;
warn("glyph not found: %d", *(c - 1));
}
return parts;
} else
font = probe;
}
}
TextPart *parts = new TextPart[nparts + 2];
parts[nparts + 1].font = NULL;
parts[nparts + 1].width = 0;
parts[nparts + 1].length = 0;
parts[nparts].length = (c - str);
if (NULL != font && font < lFont) {
XftGraphics::textExtents(*font, str, (c - str), extends);
parts[nparts].font = *font;
parts[nparts].width = extends.xOff;
} else {
parts[nparts].font = NULL;
parts[nparts].width = 0;
}
return parts;
}
ref<YFont> getXftFontXlfd(ustring name, bool antialias) {
ref<YFont> font(new YXftFont(name, true, antialias));
if (font == null || !font->valid()) {
msg("failed to load font '%s', trying fallback", cstring(name).c_str());
font.init(new YXftFont("sans-serif:size=12", false, antialias));
if (font == null || !font->valid())
msg("Could not load fallback Xft font.");
}
return font;
}
ref<YFont> getXftFont(ustring name, bool antialias) {
ref<YFont>font(new YXftFont(name, false, antialias));
if (font == null || !font->valid()) {
msg("failed to load font '%s', trying fallback", cstring(name).c_str());
font.init(new YXftFont("sans-serif:size=12", false, antialias));
if (font == null || !font->valid())
msg("Could not load fallback Xft font.");
}
return font;
}
#endif // CONFIG_XFREETYPE
<commit_msg>Fix the check of fribidi_log2vis' result (the code looks like it was intended that way, and clang barfs otherwise)<commit_after>#include "config.h"
#ifdef CONFIG_XFREETYPE
#include "ystring.h"
#include "ypaint.h"
#include "yxapp.h"
#include "intl.h"
#include <stdio.h>
#ifdef CONFIG_FRIBIDI
// remove deprecated warnings for now...
#include <fribidi/fribidi-config.h>
#if FRIBIDI_USE_GLIB+0
#include <glib.h>
#undef G_GNUC_DEPRECATED
#define G_GNUC_DEPRECATED
#endif
#include <fribidi/fribidi.h>
#endif
/******************************************************************************/
class YXftFont : public YFont {
public:
#ifdef CONFIG_I18N
typedef class YUnicodeString string_t;
typedef XftChar32 char_t;
#else
typedef class YLocaleString string_t;
typedef XftChar8 char_t;
#endif
YXftFont(ustring name, bool xlfd, bool antialias);
virtual ~YXftFont();
virtual bool valid() const { return (fFontCount > 0); }
virtual int descent() const { return fDescent; }
virtual int ascent() const { return fAscent; }
virtual int textWidth(const ustring &s) const;
virtual int textWidth(char const * str, int len) const;
virtual int textWidth(string_t const & str) const;
virtual void drawGlyphs(class Graphics & graphics, int x, int y,
char const * str, int len);
private:
struct TextPart {
XftFont * font;
size_t length;
unsigned width;
};
TextPart * partitions(char_t * str, size_t len, size_t nparts = 0) const;
unsigned fFontCount, fAscent, fDescent;
XftFont ** fFonts;
};
class XftGraphics {
public:
#ifdef CONFIG_I18N
typedef XftChar32 char_t;
#define XftDrawString XftDrawString32
#define XftTextExtents XftTextExtents32
#else
typedef XftChar8 char_t;
#define XftTextExtents XftTextExtents8
#define XftDrawString XftDrawString8
#endif
#if 0
void drawRect(Graphics &g, XftColor * color, int x, int y, unsigned w, unsigned h) {
XftDrawRect(fDraw, color, x - xOrigin, y - yOrigin, w, h);
}
#endif
static void drawString(Graphics &g, XftFont * font, int x, int y,
char_t * str, size_t len)
{
XftColor *c = *g.color();
#ifdef CONFIG_FRIBIDI
#define STATIS_STRING_SIZE 256
// Based around upstream (1.3.2) patch with some optimization
// on my end. (reduce unnecessary memory allocation)
// - Gilboa
char_t static_str[STATIS_STRING_SIZE];
char_t *vis_str = static_str;
if (len >= STATIS_STRING_SIZE)
{
vis_str = new char_t[len+1];
if (!vis_str)
return;
}
FriBidiCharType pbase_dir = FRIBIDI_TYPE_N;
if (fribidi_log2vis(str, len, &pbase_dir, //input
vis_str, // output
NULL, NULL, NULL // "statistics" that we don't need
))
{
str = vis_str;
}
#endif
XftDrawString(g.handleXft(), c, font,
x - g.xorigin(),
y - g.yorigin(),
str, len);
#ifdef CONFIG_FRIBIDI
if (vis_str != static_str)
delete[] str;
#endif
}
static void textExtents(XftFont * font, char_t * str, size_t len,
XGlyphInfo & extends) {
XftTextExtents(xapp->display (), font, str, len, &extends);
}
// XftDraw * handle() const { return fDraw; }
};
/******************************************************************************/
YXftFont::YXftFont(ustring name, bool use_xlfd, bool /*antialias*/):
fFontCount(0), fAscent(0), fDescent(0)
{
fFontCount = 0;
ustring s(null), r(null);
for (s = name; s.splitall(',', &s, &r); s = r) {
fFontCount++;
}
XftFont ** fptr(fFonts = new XftFont* [fFontCount]);
for (s = name; s.splitall(',', &s, &r); s = r) {
// for (char const *s(name); '\0' != *s; s = strnxt(s, ",")) {
XftFont *& font(*fptr);
ustring fname = s.trim();
//char * fname(newstr(s + strspn(s, " \t\r\n"), ","));
//char * endptr(fname + strlen(fname) - 1);
//while (endptr > fname && strchr(" \t\r\n", *endptr)) --endptr;
//endptr[1] = '\0';
cstring cs(fname);
if (use_xlfd) {
font = XftFontOpenXlfd(xapp->display(), xapp->screen(), cs.c_str());
} else {
font = XftFontOpenName(xapp->display(), xapp->screen(), cs.c_str());
}
if (NULL != font) {
fAscent = max(fAscent, (unsigned) max(0, font->ascent));
fDescent = max(fDescent, (unsigned) max(0, font->descent));
++fptr;
} else {
warn(_("Could not load font \"%s\"."), cs.c_str());
--fFontCount;
}
}
if (0 == fFontCount) {
msg("xft: fallback from '%s'", cstring(name).c_str());
XftFont *sans =
XftFontOpen(xapp->display(), xapp->screen(),
XFT_FAMILY, XftTypeString, "sans-serif",
XFT_PIXEL_SIZE, XftTypeInteger, 12,
NULL);
if (NULL != sans) {
delete[] fFonts;
fFontCount = 1;
fFonts = new XftFont* [fFontCount];
fFonts[0] = sans;
fAscent = sans->ascent;
fDescent = sans->descent;
} else
warn(_("Loading of fallback font \"%s\" failed."), "sans-serif");
}
}
YXftFont::~YXftFont() {
for (unsigned n = 0; n < fFontCount; ++n) {
// this leaks memory when xapp is destroyed before fonts
if (xapp != 0)
XftFontClose(xapp->display(), fFonts[n]);
}
delete[] fFonts;
}
int YXftFont::textWidth(const ustring &s) const {
cstring cs(s);
return textWidth(cs.c_str(), cs.c_str_len());
}
int YXftFont::textWidth(string_t const & text) const {
char_t * str((char_t *) text.data());
size_t len(text.length());
TextPart *parts = partitions(str, len);
unsigned width(0);
for (TextPart * p = parts; p && p->length; ++p) width+= p->width;
delete[] parts;
return width;
}
int YXftFont::textWidth(char const * str, int len) const {
return textWidth(string_t(str, len));
}
void YXftFont::drawGlyphs(Graphics & graphics, int x, int y,
char const * str, int len) {
string_t xtext(str, len);
if (0 == xtext.length()) return;
int const y0(y - ascent());
int const gcFn(graphics.function());
char_t * xstr((char_t *) xtext.data());
size_t xlen(xtext.length());
TextPart *parts = partitions(xstr, xlen);
/// unsigned w(0);
/// unsigned const h(height());
/// for (TextPart *p = parts; p && p->length; ++p) w+= p->width;
/// YPixmap *pixmap = new YPixmap(w, h);
/// Graphics canvas(*pixmap, 0, 0);
// XftGraphics textarea(graphics, xapp->visual(), xapp->colormap());
switch (gcFn) {
case GXxor:
/// textarea.drawRect(*YColor::black, 0, 0, w, h);
break;
case GXcopy:
/// canvas.copyDrawable(graphics.drawable(),
/// x - graphics.xorigin(), y0 - graphics.yorigin(), w, h, 0, 0);
break;
}
int xpos(0);
for (TextPart *p = parts; p && p->length; ++p) {
if (p->font) {
XftGraphics::drawString(graphics, p->font,
xpos + x, ascent() + y0,
xstr, p->length);
}
xstr += p->length;
xpos += p->width;
}
delete[] parts;
/// graphics.copyDrawable(canvas.drawable(), 0, 0, w, h, x, y0);
/// delete pixmap;
}
YXftFont::TextPart * YXftFont::partitions(char_t * str, size_t len,
size_t nparts) const
{
XGlyphInfo extends;
XftFont ** lFont(fFonts + fFontCount);
XftFont ** font(NULL);
char_t * c(str);
for (char_t * endptr(str + len); c < endptr; ++c) {
XftFont ** probe(fFonts);
while (probe < lFont && !XftGlyphExists(xapp->display(), *probe, *c))
++probe;
if (probe != font) {
if (NULL != font) {
TextPart *parts = partitions(c, len - (c - str), nparts + 1);
parts[nparts].length = (c - str);
if (font < lFont) {
XftGraphics::textExtents(*font, str, (c - str), extends);
parts[nparts].font = *font;
parts[nparts].width = extends.xOff;
} else {
parts[nparts].font = NULL;
parts[nparts].width = 0;
warn("glyph not found: %d", *(c - 1));
}
return parts;
} else
font = probe;
}
}
TextPart *parts = new TextPart[nparts + 2];
parts[nparts + 1].font = NULL;
parts[nparts + 1].width = 0;
parts[nparts + 1].length = 0;
parts[nparts].length = (c - str);
if (NULL != font && font < lFont) {
XftGraphics::textExtents(*font, str, (c - str), extends);
parts[nparts].font = *font;
parts[nparts].width = extends.xOff;
} else {
parts[nparts].font = NULL;
parts[nparts].width = 0;
}
return parts;
}
ref<YFont> getXftFontXlfd(ustring name, bool antialias) {
ref<YFont> font(new YXftFont(name, true, antialias));
if (font == null || !font->valid()) {
msg("failed to load font '%s', trying fallback", cstring(name).c_str());
font.init(new YXftFont("sans-serif:size=12", false, antialias));
if (font == null || !font->valid())
msg("Could not load fallback Xft font.");
}
return font;
}
ref<YFont> getXftFont(ustring name, bool antialias) {
ref<YFont>font(new YXftFont(name, false, antialias));
if (font == null || !font->valid()) {
msg("failed to load font '%s', trying fallback", cstring(name).c_str());
font.init(new YXftFont("sans-serif:size=12", false, antialias));
if (font == null || !font->valid())
msg("Could not load fallback Xft font.");
}
return font;
}
#endif // CONFIG_XFREETYPE
<|endoftext|>
|
<commit_before>#include "libtommath/mp_2expt.c"
#include "libtommath/mp_abs.c"
#include "libtommath/mp_add.c"
#include "libtommath/mp_add_d.c"
#include "libtommath/mp_addmod.c"
#include "libtommath/mp_and.c"
#include "libtommath/mp_clamp.c"
#include "libtommath/mp_clear.c"
#include "libtommath/mp_clear_multi.c"
#include "libtommath/mp_cmp.c"
#include "libtommath/mp_cmp_d.c"
#include "libtommath/mp_cmp_mag.c"
#include "libtommath/mp_cnt_lsb.c"
#include "libtommath/mp_complement.c"
#include "libtommath/mp_copy.c"
#include "libtommath/mp_count_bits.c"
#include "libtommath/mp_cutoffs.c"
#include "libtommath/mp_div.c"
#include "libtommath/mp_div_2.c"
#include "libtommath/mp_div_2d.c"
#include "libtommath/mp_div_d.c"
#include "libtommath/mp_dr_is_modulus.c"
#include "libtommath/mp_dr_reduce.c"
#include "libtommath/mp_dr_setup.c"
#include "libtommath/mp_error_to_string.c"
#include "libtommath/mp_exch.c"
#include "libtommath/mp_expt_n.c"
#include "libtommath/mp_exptmod.c"
#include "libtommath/mp_exteuclid.c"
#include "libtommath/mp_fread.c"
#include "libtommath/mp_from_sbin.c"
#include "libtommath/mp_from_ubin.c"
#include "libtommath/mp_fwrite.c"
#include "libtommath/mp_gcd.c"
#include "libtommath/mp_get_double.c"
#include "libtommath/mp_get_i32.c"
#include "libtommath/mp_get_i64.c"
#include "libtommath/mp_get_l.c"
#include "libtommath/mp_get_mag_u32.c"
#include "libtommath/mp_get_mag_u64.c"
#include "libtommath/mp_get_mag_ul.c"
#include "libtommath/mp_grow.c"
#include "libtommath/mp_init.c"
#include "libtommath/mp_init_copy.c"
#include "libtommath/mp_init_i32.c"
#include "libtommath/mp_init_i64.c"
#include "libtommath/mp_init_l.c"
#include "libtommath/mp_init_multi.c"
#include "libtommath/mp_init_set.c"
#include "libtommath/mp_init_size.c"
#include "libtommath/mp_init_u32.c"
#include "libtommath/mp_init_u64.c"
#include "libtommath/mp_init_ul.c"
#include "libtommath/mp_invmod.c"
#include "libtommath/mp_is_square.c"
#include "libtommath/mp_kronecker.c"
#include "libtommath/mp_lcm.c"
#include "libtommath/mp_log_n.c"
#include "libtommath/mp_lshd.c"
#include "libtommath/mp_mod.c"
#include "libtommath/mp_mod_2d.c"
#include "libtommath/mp_montgomery_calc_normalization.c"
#include "libtommath/mp_montgomery_reduce.c"
#include "libtommath/mp_montgomery_setup.c"
#include "libtommath/mp_mul.c"
#include "libtommath/mp_mul_2.c"
#include "libtommath/mp_mul_2d.c"
#include "libtommath/mp_mul_d.c"
#include "libtommath/mp_mulmod.c"
#include "libtommath/mp_neg.c"
#include "libtommath/mp_or.c"
#include "libtommath/mp_pack.c"
#include "libtommath/mp_pack_count.c"
// #include "libtommath/mp_prime_fermat.c"
// #include "libtommath/mp_prime_frobenius_underwood.c"
// #include "libtommath/mp_prime_is_prime.c"
// #include "libtommath/mp_prime_miller_rabin.c"
// #include "libtommath/mp_prime_next_prime.c"
// #include "libtommath/mp_prime_rabin_miller_trials.c"
// #include "libtommath/mp_prime_rand.c"
// #include "libtommath/mp_prime_strong_lucas_selfridge.c"
#include "libtommath/mp_radix_size.c"
#include "libtommath/mp_radix_size_overestimate.c"
// #include "libtommath/mp_rand.c"
// #include "libtommath/mp_rand_source.c"
#include "libtommath/mp_read_radix.c"
#include "libtommath/mp_reduce.c"
#include "libtommath/mp_reduce_2k.c"
#include "libtommath/mp_reduce_2k_l.c"
#include "libtommath/mp_reduce_2k_setup.c"
#include "libtommath/mp_reduce_2k_setup_l.c"
#include "libtommath/mp_reduce_is_2k.c"
#include "libtommath/mp_reduce_is_2k_l.c"
#include "libtommath/mp_reduce_setup.c"
#include "libtommath/mp_root_n.c"
#include "libtommath/mp_rshd.c"
#include "libtommath/mp_sbin_size.c"
#include "libtommath/mp_set.c"
#include "libtommath/mp_set_double.c"
#include "libtommath/mp_set_i32.c"
#include "libtommath/mp_set_i64.c"
#include "libtommath/mp_set_l.c"
#include "libtommath/mp_set_u32.c"
#include "libtommath/mp_set_u64.c"
#include "libtommath/mp_set_ul.c"
#include "libtommath/mp_shrink.c"
#include "libtommath/mp_signed_rsh.c"
#include "libtommath/mp_sqrmod.c"
#include "libtommath/mp_sqrt.c"
#include "libtommath/mp_sqrtmod_prime.c"
#include "libtommath/mp_sub.c"
#include "libtommath/mp_sub_d.c"
#include "libtommath/mp_submod.c"
#include "libtommath/mp_to_radix.c"
#include "libtommath/mp_to_sbin.c"
#include "libtommath/mp_to_ubin.c"
#include "libtommath/mp_ubin_size.c"
#include "libtommath/mp_unpack.c"
#include "libtommath/mp_xor.c"
#include "libtommath/mp_zero.c"
#include "libtommath/s_mp_add.c"
#include "libtommath/s_mp_copy_digs.c"
#include "libtommath/s_mp_div_3.c"
#include "libtommath/s_mp_div_recursive.c"
#include "libtommath/s_mp_div_school.c"
#include "libtommath/s_mp_div_small.c"
#include "libtommath/s_mp_exptmod.c"
#include "libtommath/s_mp_exptmod_fast.c"
#include "libtommath/s_mp_get_bit.c"
#include "libtommath/s_mp_invmod.c"
#include "libtommath/s_mp_invmod_odd.c"
#include "libtommath/s_mp_log.c"
#include "libtommath/s_mp_log_2expt.c"
#include "libtommath/s_mp_log_d.c"
#include "libtommath/s_mp_montgomery_reduce_comba.c"
#include "libtommath/s_mp_mul.c"
#include "libtommath/s_mp_mul_balance.c"
#include "libtommath/s_mp_mul_comba.c"
#include "libtommath/s_mp_mul_high.c"
#include "libtommath/s_mp_mul_high_comba.c"
#include "libtommath/s_mp_mul_karatsuba.c"
#include "libtommath/s_mp_mul_toom.c"
#include "libtommath/s_mp_prime_is_divisible.c"
#include "libtommath/s_mp_prime_tab.c"
#include "libtommath/s_mp_radix_map.c"
#include "libtommath/s_mp_radix_size_overestimate.c"
// #include "libtommath/s_mp_rand_platform.c"
#include "libtommath/s_mp_sqr.c"
#include "libtommath/s_mp_sqr_comba.c"
#include "libtommath/s_mp_sqr_karatsuba.c"
#include "libtommath/s_mp_sqr_toom.c"
#include "libtommath/s_mp_sub.c"
#include "libtommath/s_mp_zero_buf.c"
#include "libtommath/s_mp_zero_digs.c"
<commit_msg>Slim down LibTomMath compile.<commit_after>#include "libtommath/mp_2expt.c"
#include "libtommath/mp_abs.c"
#include "libtommath/mp_add.c"
#include "libtommath/mp_add_d.c"
#include "libtommath/mp_addmod.c"
#include "libtommath/mp_and.c"
#include "libtommath/mp_clamp.c"
#include "libtommath/mp_clear.c"
#include "libtommath/mp_clear_multi.c"
#include "libtommath/mp_cmp.c"
#include "libtommath/mp_cmp_d.c"
#include "libtommath/mp_cmp_mag.c"
#include "libtommath/mp_cnt_lsb.c"
#include "libtommath/mp_complement.c"
#include "libtommath/mp_copy.c"
#include "libtommath/mp_count_bits.c"
#include "libtommath/mp_cutoffs.c"
#include "libtommath/mp_div.c"
#include "libtommath/mp_div_2.c"
#include "libtommath/mp_div_2d.c"
#include "libtommath/mp_div_d.c"
#include "libtommath/mp_dr_is_modulus.c"
#include "libtommath/mp_dr_reduce.c"
#include "libtommath/mp_dr_setup.c"
#include "libtommath/mp_error_to_string.c"
#include "libtommath/mp_exch.c"
#include "libtommath/mp_expt_n.c"
// #include "libtommath/mp_exptmod.c"
// #include "libtommath/mp_exteuclid.c"
#include "libtommath/mp_fread.c"
#include "libtommath/mp_from_sbin.c"
#include "libtommath/mp_from_ubin.c"
#include "libtommath/mp_fwrite.c"
#include "libtommath/mp_gcd.c"
#include "libtommath/mp_get_double.c"
#include "libtommath/mp_get_i32.c"
#include "libtommath/mp_get_i64.c"
#include "libtommath/mp_get_l.c"
#include "libtommath/mp_get_mag_u32.c"
#include "libtommath/mp_get_mag_u64.c"
#include "libtommath/mp_get_mag_ul.c"
#include "libtommath/mp_grow.c"
#include "libtommath/mp_init.c"
#include "libtommath/mp_init_copy.c"
#include "libtommath/mp_init_i32.c"
#include "libtommath/mp_init_i64.c"
#include "libtommath/mp_init_l.c"
#include "libtommath/mp_init_multi.c"
#include "libtommath/mp_init_set.c"
#include "libtommath/mp_init_size.c"
#include "libtommath/mp_init_u32.c"
#include "libtommath/mp_init_u64.c"
#include "libtommath/mp_init_ul.c"
#include "libtommath/mp_invmod.c"
#include "libtommath/mp_is_square.c"
// #include "libtommath/mp_kronecker.c"
#include "libtommath/mp_lcm.c"
#include "libtommath/mp_log_n.c"
#include "libtommath/mp_lshd.c"
#include "libtommath/mp_mod.c"
#include "libtommath/mp_mod_2d.c"
// #include "libtommath/mp_montgomery_calc_normalization.c"
// #include "libtommath/mp_montgomery_reduce.c"
// #include "libtommath/mp_montgomery_setup.c"
#include "libtommath/mp_mul.c"
#include "libtommath/mp_mul_2.c"
#include "libtommath/mp_mul_2d.c"
#include "libtommath/mp_mul_d.c"
#include "libtommath/mp_mulmod.c"
#include "libtommath/mp_neg.c"
#include "libtommath/mp_or.c"
#include "libtommath/mp_pack.c"
#include "libtommath/mp_pack_count.c"
// #include "libtommath/mp_prime_fermat.c"
// #include "libtommath/mp_prime_frobenius_underwood.c"
// #include "libtommath/mp_prime_is_prime.c"
// #include "libtommath/mp_prime_miller_rabin.c"
// #include "libtommath/mp_prime_next_prime.c"
// #include "libtommath/mp_prime_rabin_miller_trials.c"
// #include "libtommath/mp_prime_rand.c"
// #include "libtommath/mp_prime_strong_lucas_selfridge.c"
#include "libtommath/mp_radix_size.c"
#include "libtommath/mp_radix_size_overestimate.c"
// #include "libtommath/mp_rand.c"
// #include "libtommath/mp_rand_source.c"
#include "libtommath/mp_read_radix.c"
// #include "libtommath/mp_reduce.c"
// #include "libtommath/mp_reduce_2k.c"
// #include "libtommath/mp_reduce_2k_l.c"
// #include "libtommath/mp_reduce_2k_setup.c"
// #include "libtommath/mp_reduce_2k_setup_l.c"
// #include "libtommath/mp_reduce_is_2k.c"
// #include "libtommath/mp_reduce_is_2k_l.c"
// #include "libtommath/mp_reduce_setup.c"
#include "libtommath/mp_root_n.c"
#include "libtommath/mp_rshd.c"
#include "libtommath/mp_sbin_size.c"
#include "libtommath/mp_set.c"
#include "libtommath/mp_set_double.c"
#include "libtommath/mp_set_i32.c"
#include "libtommath/mp_set_i64.c"
#include "libtommath/mp_set_l.c"
#include "libtommath/mp_set_u32.c"
#include "libtommath/mp_set_u64.c"
#include "libtommath/mp_set_ul.c"
#include "libtommath/mp_shrink.c"
#include "libtommath/mp_signed_rsh.c"
// #include "libtommath/mp_sqrmod.c"
#include "libtommath/mp_sqrt.c"
// #include "libtommath/mp_sqrtmod_prime.c"
#include "libtommath/mp_sub.c"
#include "libtommath/mp_sub_d.c"
#include "libtommath/mp_submod.c"
#include "libtommath/mp_to_radix.c"
#include "libtommath/mp_to_sbin.c"
#include "libtommath/mp_to_ubin.c"
#include "libtommath/mp_ubin_size.c"
#include "libtommath/mp_unpack.c"
#include "libtommath/mp_xor.c"
#include "libtommath/mp_zero.c"
#include "libtommath/s_mp_add.c"
#include "libtommath/s_mp_copy_digs.c"
#include "libtommath/s_mp_div_3.c"
#include "libtommath/s_mp_div_recursive.c"
#include "libtommath/s_mp_div_school.c"
#include "libtommath/s_mp_div_small.c"
// #include "libtommath/s_mp_exptmod.c"
// #include "libtommath/s_mp_exptmod_fast.c"
#include "libtommath/s_mp_get_bit.c"
#include "libtommath/s_mp_invmod.c"
#include "libtommath/s_mp_invmod_odd.c"
#include "libtommath/s_mp_log.c"
#include "libtommath/s_mp_log_2expt.c"
#include "libtommath/s_mp_log_d.c"
// #include "libtommath/s_mp_montgomery_reduce_comba.c"
#include "libtommath/s_mp_mul.c"
#include "libtommath/s_mp_mul_balance.c"
#include "libtommath/s_mp_mul_comba.c"
#include "libtommath/s_mp_mul_high.c"
#include "libtommath/s_mp_mul_high_comba.c"
#include "libtommath/s_mp_mul_karatsuba.c"
#include "libtommath/s_mp_mul_toom.c"
#include "libtommath/s_mp_prime_is_divisible.c"
#include "libtommath/s_mp_prime_tab.c"
#include "libtommath/s_mp_radix_map.c"
#include "libtommath/s_mp_radix_size_overestimate.c"
// #include "libtommath/s_mp_rand_platform.c"
#include "libtommath/s_mp_sqr.c"
#include "libtommath/s_mp_sqr_comba.c"
#include "libtommath/s_mp_sqr_karatsuba.c"
#include "libtommath/s_mp_sqr_toom.c"
#include "libtommath/s_mp_sub.c"
#include "libtommath/s_mp_zero_buf.c"
#include "libtommath/s_mp_zero_digs.c"
<|endoftext|>
|
<commit_before>/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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. *
* *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>
#include "arghelpers.h"
#include "io.h"
#include "optionparser.h"
//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;
XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";
DepthMapLogger g_Log;
//---------------------------------------------------------------------------
// Forward declarations
//---------------------------------------------------------------------------
bool InitialiseContextFromRecording(const char* recordingFilename);
bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename);
bool EnsureDepthGenerator();
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);
//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"
#define CHECK_RC(nRetVal, what) \
if (nRetVal != XN_STATUS_OK) \
{ \
printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
return nRetVal; \
}
#define CHECK_RC_RETURNING(rv, nRetVal, what) \
if (nRetVal != XN_STATUS_OK) \
{ \
printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
return rv; \
}
// Command-line option description
enum optionIndex { UNKNOWN, HELP, CAPTURE, PLAYBACK, };
const option::Descriptor g_Usage[] =
{
{ UNKNOWN, 0, "", "", option::Arg::None, "Usage:\n"
" skeletonexport_nongui [options]\n\n"
"Options:" },
{ HELP, 0, "h?", "help", option::Arg::None, " --help, -h, -? \tPrint a brief usage summary." },
{ CAPTURE, 0, "c", "capture", Arg::Required, " --capture, -c CONFIG \tCapture from sensor using specified XML config." },
{ PLAYBACK, 0, "p", "playback", Arg::Required, " --playback, -p RECORDING \tPlayback a .oni recording." },
{ 0,0,0,0,0,0 } // Zero record marking end of array.
};
int main(int argc, char **argv)
{
// Parse command-line options
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(g_Usage, argc, argv);
option::Option options[stats.options_max], buffer[stats.buffer_max];
option::Parser parse(g_Usage, argc, argv, options, buffer);
if (parse.error()) {
return EXIT_FAILURE;
}
if (options[HELP]) {
option::printUsage(std::cout, g_Usage);
return EXIT_SUCCESS;
}
// Check command-line options for validity.
if (options[CAPTURE] && options[PLAYBACK]) {
std::cerr << "Error: only one of --playback and --capture may be specified.\n";
option::printUsage(std::cerr, g_Usage);
return EXIT_FAILURE;
}
// Set up capture device
if (options[PLAYBACK])
{
if(!InitialiseContextFromRecording(options[PLAYBACK].arg))
{
return EXIT_FAILURE;
}
}
else if(options[CAPTURE])
{
if(!InitialiseContextFromXmlConfig(options[CAPTURE].arg))
{
return EXIT_FAILURE;
}
} else {
std::cerr << "Error: exactly one of --playback and --capture must be specified.\n";
option::printUsage(std::cerr, g_Usage);
return EXIT_FAILURE;
}
EnsureDepthGenerator();
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
if (nRetVal != XN_STATUS_OK)
{
nRetVal = g_UserGenerator.Create(g_Context);
CHECK_RC(nRetVal, "Find user generator");
}
XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
{
printf("Supplied user generator doesn't support skeleton\n");
return 1;
}
nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
CHECK_RC(nRetVal, "Register to user callbacks");
nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
CHECK_RC(nRetVal, "Register to calibration start");
nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
CHECK_RC(nRetVal, "Register to calibration complete");
if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
{
g_bNeedPose = TRUE;
if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
{
printf("Pose required, but not supported\n");
return 1;
}
nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
CHECK_RC(nRetVal, "Register to Pose Detected");
g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
}
g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);
nRetVal = g_Context.StartGeneratingAll();
CHECK_RC(nRetVal, "StartGenerating");
g_Log.Open("log.h5", "log.txt");
// Main event loop
xn::SceneMetaData sceneMD;
xn::DepthMetaData depthMD;
while (!xnOSWasKeyboardHit())
{
// Wait for an update
g_Context.WaitOneUpdateAll(g_UserGenerator);
// Process the data
g_DepthGenerator.GetMetaData(depthMD);
g_UserGenerator.GetUserPixels(0, sceneMD);
// Log the data
g_Log.DumpDepthMap(depthMD, sceneMD);
}
// Clean up all resources
g_scriptNode.Release();
g_DepthGenerator.Release();
g_UserGenerator.Release();
g_Player.Release();
g_Context.Release();
return EXIT_SUCCESS;
}
bool InitialiseContextFromRecording(const char* recordingFilename)
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.Init();
CHECK_RC_RETURNING(false, nRetVal, "Init");
nRetVal = g_Context.OpenFileRecording(recordingFilename, g_Player);
if (nRetVal != XN_STATUS_OK)
{
printf("Can't open recording %s: %s\n", recordingFilename, xnGetStatusString(nRetVal));
return false;
}
return true;
}
bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename)
{
XnStatus nRetVal = XN_STATUS_OK;
xn::EnumerationErrors errors;
nRetVal = g_Context.InitFromXmlFile(xmlConfigFilename, g_scriptNode, &errors);
if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
{
XnChar strError[1024];
errors.ToString(strError, 1024);
printf("%s\n", strError);
return false;
}
else if (nRetVal != XN_STATUS_OK)
{
printf("Open failed: %s\n", xnGetStatusString(nRetVal));
return false;
}
return true;
}
bool EnsureDepthGenerator()
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
if (nRetVal != XN_STATUS_OK)
{
printf("No depth generator found. Using a default one...");
xn::MockDepthGenerator mockDepth;
nRetVal = mockDepth.Create(g_Context);
CHECK_RC_RETURNING(false, nRetVal, "Create mock depth");
// set some defaults
XnMapOutputMode defaultMode;
defaultMode.nXRes = 320;
defaultMode.nYRes = 240;
defaultMode.nFPS = 30;
nRetVal = mockDepth.SetMapOutputMode(defaultMode);
CHECK_RC_RETURNING(false, nRetVal, "set default mode");
// set FOV
XnFieldOfView fov;
fov.fHFOV = 1.0225999419141749;
fov.fVFOV = 0.79661567681716894;
nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
CHECK_RC_RETURNING(false, nRetVal, "set FOV");
XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);
nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
CHECK_RC_RETURNING(false, nRetVal, "set empty depth map");
g_DepthGenerator = mockDepth;
}
return true;
}
// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d New User %d\n", epochTime, nId);
// New user found
if (g_bNeedPose)
{
g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
}
else
{
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
}
// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Lost user %d\n", epochTime, nId);
}
// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Calibration started for user %d\n", epochTime, nId);
}
// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
if (eStatus == XN_CALIBRATION_STATUS_OK)
{
// Calibration succeeded
printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
g_UserGenerator.GetSkeletonCap().StartTracking(nId);
}
else
{
// Calibration failed
printf("%d Calibration failed for user %d\n", epochTime, nId);
if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
{
printf("Manual abort occured, stop attempting to calibrate!");
return;
}
if (g_bNeedPose)
{
g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
}
else
{
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
}
}
<commit_msg>main_nogui: specify log-file output file prefix<commit_after>/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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. *
* *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>
#include "arghelpers.h"
#include "io.h"
#include "optionparser.h"
//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;
XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";
DepthMapLogger g_Log;
//---------------------------------------------------------------------------
// Forward declarations
//---------------------------------------------------------------------------
bool InitialiseContextFromRecording(const char* recordingFilename);
bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename);
bool EnsureDepthGenerator();
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);
//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"
#define CHECK_RC(nRetVal, what) \
if (nRetVal != XN_STATUS_OK) \
{ \
printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
return nRetVal; \
}
#define CHECK_RC_RETURNING(rv, nRetVal, what) \
if (nRetVal != XN_STATUS_OK) \
{ \
printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
return rv; \
}
// Command-line option description
enum optionIndex { UNKNOWN, HELP, CAPTURE, PLAYBACK, LOG, };
const option::Descriptor g_Usage[] =
{
{ UNKNOWN, 0, "", "", option::Arg::None, "Usage:\n"
" skeletonexport_nongui [options]\n\n"
"Options:" },
{ HELP, 0, "h?", "help", option::Arg::None, " --help, -h, -? \tPrint a brief usage summary." },
{ CAPTURE, 0, "c", "capture", Arg::Required, " --capture, -c CONFIG \tCapture from sensor using specified XML config." },
{ PLAYBACK, 0, "p", "playback", Arg::Required, " --playback, -p RECORDING \tPlayback a .oni recording." },
{ LOG, 0, "l", "log", Arg::Required, " --log, -l PREFIX \tLog results to PREFIX.{h5,txt}." },
{ 0,0,0,0,0,0 } // Zero record marking end of array.
};
int main(int argc, char **argv)
{
// Parse command-line options
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(g_Usage, argc, argv);
option::Option options[stats.options_max], buffer[stats.buffer_max];
option::Parser parse(g_Usage, argc, argv, options, buffer);
if (parse.error()) {
return EXIT_FAILURE;
}
if (options[HELP]) {
option::printUsage(std::cout, g_Usage);
return EXIT_SUCCESS;
}
// Check command-line options for validity.
if (options[CAPTURE] && options[PLAYBACK]) {
std::cerr << "Error: only one of --playback and --capture may be specified.\n";
option::printUsage(std::cerr, g_Usage);
return EXIT_FAILURE;
}
// Set up capture device
if (options[PLAYBACK])
{
if(!InitialiseContextFromRecording(options[PLAYBACK].arg))
{
return EXIT_FAILURE;
}
}
else if(options[CAPTURE])
{
if(!InitialiseContextFromXmlConfig(options[CAPTURE].arg))
{
return EXIT_FAILURE;
}
} else {
std::cerr << "Error: exactly one of --playback and --capture must be specified.\n";
option::printUsage(std::cerr, g_Usage);
return EXIT_FAILURE;
}
EnsureDepthGenerator();
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
if (nRetVal != XN_STATUS_OK)
{
nRetVal = g_UserGenerator.Create(g_Context);
CHECK_RC(nRetVal, "Find user generator");
}
XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
{
printf("Supplied user generator doesn't support skeleton\n");
return 1;
}
nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
CHECK_RC(nRetVal, "Register to user callbacks");
nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
CHECK_RC(nRetVal, "Register to calibration start");
nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
CHECK_RC(nRetVal, "Register to calibration complete");
if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
{
g_bNeedPose = TRUE;
if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
{
printf("Pose required, but not supported\n");
return 1;
}
nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
CHECK_RC(nRetVal, "Register to Pose Detected");
g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
}
g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);
nRetVal = g_Context.StartGeneratingAll();
CHECK_RC(nRetVal, "StartGenerating");
if (options[LOG]) {
std::string logfile_prefix(options[LOG].arg);
std::string h5_logfile(logfile_prefix + ".h5"), txt_logfile(logfile_prefix + ".txt");
std::cout << "Logging to " << h5_logfile << " and " << txt_logfile << '\n';
g_Log.Open(h5_logfile.c_str(), txt_logfile.c_str());
}
// Main event loop
xn::SceneMetaData sceneMD;
xn::DepthMetaData depthMD;
std::cout << "---------------------------------------------------------------------------\n";
std::cout << "Starting tracker. Press any key to exit.\n";
std::cout << "---------------------------------------------------------------------------\n";
while (!xnOSWasKeyboardHit())
{
// Wait for an update
g_Context.WaitOneUpdateAll(g_UserGenerator);
// Process the data
g_DepthGenerator.GetMetaData(depthMD);
g_UserGenerator.GetUserPixels(0, sceneMD);
// Log the data
g_Log.DumpDepthMap(depthMD, sceneMD);
}
std::cout << '\n';
std::cout << "---------------------------------------------------------------------------\n";
std::cout << "Exiting tracker.\n";
std::cout << "---------------------------------------------------------------------------\n";
// Clean up all resources
g_scriptNode.Release();
g_DepthGenerator.Release();
g_UserGenerator.Release();
g_Player.Release();
g_Context.Release();
return EXIT_SUCCESS;
}
bool InitialiseContextFromRecording(const char* recordingFilename)
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.Init();
CHECK_RC_RETURNING(false, nRetVal, "Init");
nRetVal = g_Context.OpenFileRecording(recordingFilename, g_Player);
if (nRetVal != XN_STATUS_OK)
{
printf("Can't open recording %s: %s\n", recordingFilename, xnGetStatusString(nRetVal));
return false;
}
return true;
}
bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename)
{
XnStatus nRetVal = XN_STATUS_OK;
xn::EnumerationErrors errors;
nRetVal = g_Context.InitFromXmlFile(xmlConfigFilename, g_scriptNode, &errors);
if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
{
XnChar strError[1024];
errors.ToString(strError, 1024);
printf("%s\n", strError);
return false;
}
else if (nRetVal != XN_STATUS_OK)
{
printf("Open failed: %s\n", xnGetStatusString(nRetVal));
return false;
}
return true;
}
bool EnsureDepthGenerator()
{
XnStatus nRetVal = XN_STATUS_OK;
nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
if (nRetVal != XN_STATUS_OK)
{
printf("No depth generator found. Using a default one...");
xn::MockDepthGenerator mockDepth;
nRetVal = mockDepth.Create(g_Context);
CHECK_RC_RETURNING(false, nRetVal, "Create mock depth");
// set some defaults
XnMapOutputMode defaultMode;
defaultMode.nXRes = 320;
defaultMode.nYRes = 240;
defaultMode.nFPS = 30;
nRetVal = mockDepth.SetMapOutputMode(defaultMode);
CHECK_RC_RETURNING(false, nRetVal, "set default mode");
// set FOV
XnFieldOfView fov;
fov.fHFOV = 1.0225999419141749;
fov.fVFOV = 0.79661567681716894;
nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
CHECK_RC_RETURNING(false, nRetVal, "set FOV");
XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);
nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
CHECK_RC_RETURNING(false, nRetVal, "set empty depth map");
g_DepthGenerator = mockDepth;
}
return true;
}
// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d New User %d\n", epochTime, nId);
// New user found
if (g_bNeedPose)
{
g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
}
else
{
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
}
// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Lost user %d\n", epochTime, nId);
}
// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
printf("%d Calibration started for user %d\n", epochTime, nId);
}
// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
XnUInt32 epochTime = 0;
xnOSGetEpochTime(&epochTime);
if (eStatus == XN_CALIBRATION_STATUS_OK)
{
// Calibration succeeded
printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
g_UserGenerator.GetSkeletonCap().StartTracking(nId);
}
else
{
// Calibration failed
printf("%d Calibration failed for user %d\n", epochTime, nId);
if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
{
printf("Manual abort occured, stop attempting to calibrate!");
return;
}
if (g_bNeedPose)
{
g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
}
else
{
g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef STORED_VALUE_H
#define STORED_VALUE_H 1
#include <climits>
#include <cstring>
#include <algorithm>
#include "common.hh"
#include "item.hh"
#include "locks.hh"
extern "C" {
extern rel_time_t (*ep_current_time)();
}
// Forward declaration for StoredValue
class HashTable;
class StoredValueFactory;
class StoredValue {
public:
void operator delete(void* p) {
::operator delete(p);
}
virtual ~StoredValue() {
}
void markDirty() {
// We eat the last second of time for our dirty flag.
dirtiness = ep_current_time() | 1;
}
void reDirty(rel_time_t dataAge) {
dirtiness = dataAge | 1;
}
// returns time this object was dirtied.
void markClean(rel_time_t *dataAge) {
if (dataAge) {
*dataAge = dirtiness;
}
dirtiness = 0;
}
bool isDirty() const {
return dirtiness & 1;
}
bool isClean() const {
return !isDirty();
}
virtual const char* getKeyBytes() const = 0;
virtual uint8_t getKeyLen() const = 0;
virtual bool hasKey(const std::string &k) const = 0;
virtual const std::string getKey() const = 0;
value_t getValue() const {
return value;
}
virtual rel_time_t getExptime() const {
return 0;
}
virtual uint32_t getFlags() const {
return 0;
}
virtual void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
(void)newFlags;
(void)newExp;
(void)theCas;
value = v;
markDirty();
}
virtual uint64_t getCas() const {
return 0;
}
rel_time_t getDataAge() const {
return dirtiness;
}
virtual void setCas(uint64_t c) {
(void)c;
}
void lock(rel_time_t expiry) {
(void)expiry;
}
virtual void unlock() {
}
bool hasId() {
return id > 0;
}
int64_t getId() {
return id;
}
void setId(int64_t to) {
assert(!hasId());
id = to;
}
virtual bool isLocked(rel_time_t curtime) {
(void)curtime;
return false;
}
protected:
StoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
value(itm.getValue()), next(n), id(itm.getId())
{
if (setDirty) {
markDirty();
} else {
markClean(NULL);
}
}
friend class HashTable;
friend class StoredValueFactory;
value_t value;
StoredValue *next;
int64_t id;
uint32_t dirtiness;
DISALLOW_COPY_AND_ASSIGN(StoredValue);
};
class SmallStoredValue : protected StoredValue {
public:
const std::string getKey() const{
return std::string(keybytes, keylen);
}
const char* getKeyBytes() const {
return keybytes;
}
uint8_t getKeyLen() const {
return keylen;
}
bool hasKey(const std::string &k) const {
return k.length() == keylen
&& (std::memcmp(k.data(), keybytes, keylen) == 0);
}
private:
friend class StoredValueFactory;
SmallStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
StoredValue(itm, n, setDirty),
keylen(static_cast<uint8_t>(itm.getKey().length()))
{
if (setDirty) {
markDirty();
} else {
markClean(NULL);
}
}
uint8_t keylen;
char keybytes[1];
};
class FeaturedStoredValue : protected StoredValue {
public:
bool isLocked(rel_time_t curtime) {
if (locked && (curtime > lock_expiry)) {
locked = false;
return locked;
}
return locked;
}
void unlock() {
locked = false;
lock_expiry = 0;
}
void lock(rel_time_t expiry) {
locked = true;
lock_expiry = expiry;
}
void setCas(uint64_t c) {
cas = c;
}
uint64_t getCas() const {
return cas;
}
rel_time_t getExptime() const {
return exptime;
}
uint32_t getFlags() const {
return flags;
}
virtual void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
cas = theCas;
flags = newFlags;
exptime = newExp;
StoredValue::setValue(v, newFlags, newExp, theCas);
}
const std::string getKey() const{
return std::string(keybytes, keylen);
}
const char* getKeyBytes() const {
return keybytes;
}
uint8_t getKeyLen() const {
return keylen;
}
bool hasKey(const std::string &k) const {
return k.length() == keylen
&& (std::memcmp(k.data(), keybytes, keylen) == 0);
}
private:
friend class StoredValueFactory;
FeaturedStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
StoredValue(itm, n, setDirty),
cas(itm.getCas()),
flags(itm.getFlags()),
exptime(itm.getExptime()),
locked(false), lock_expiry(0),
keylen(static_cast<uint8_t>(itm.getKey().length())) {}
uint64_t cas;
uint32_t flags;
rel_time_t exptime;
bool locked;
rel_time_t lock_expiry;
uint8_t keylen;
char keybytes[1];
};
typedef enum {
NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY, IS_LOCKED, SUCCESS
} mutation_type_t;
class HashTableVisitor {
public:
virtual ~HashTableVisitor() {}
virtual void visit(StoredValue *v) = 0;
};
class HashTableDepthVisitor {
public:
virtual ~HashTableDepthVisitor() {}
virtual void visit(int bucket, int depth) = 0;
};
class HashTableDepthStatVisitor : public HashTableDepthVisitor {
public:
HashTableDepthStatVisitor() : min(INT_MAX), max(0) {}
void visit(int bucket, int depth) {
(void)bucket;
min = std::min(min, depth);
max = std::max(max, depth);
}
int min;
int max;
};
enum stored_value_type {
small, featured
};
class StoredValueFactory {
public:
StoredValueFactory(enum stored_value_type t = featured) : type(t) {}
StoredValue *operator ()(const Item &itm, StoredValue *n,
bool setDirty = true) {
switch(type) {
case small:
return newStoredValue<SmallStoredValue>(itm, n, setDirty);
break;
case featured:
return newStoredValue<FeaturedStoredValue>(itm, n, setDirty);
break;
default:
abort();
};
}
private:
template <typename SV>
StoredValue* newStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) {
std::string key = itm.getKey();
assert(key.length() < 256);
size_t len = key.length() + sizeof(SV);
SV *t = new (::operator new(len)) SV(itm, n, setDirty);
std::memcpy(t->keybytes, key.data(), key.length());
return t;
}
enum stored_value_type type;
};
class HashTable {
public:
// Construct with number of buckets and locks.
HashTable(size_t s = 0, size_t l = 0, enum stored_value_type t = featured)
: valFact(t) {
size = HashTable::getNumBuckets(s);
n_locks = HashTable::getNumLocks(l);
valFact = StoredValueFactory(getDefaultStorageValueType());
assert(size > 0);
assert(n_locks > 0);
values = new StoredValue*[size];
std::fill_n(values, size, static_cast<StoredValue*>(NULL));
mutexes = new Mutex[n_locks];
}
~HashTable() {
clear();
delete []mutexes;
delete []values;
values = NULL;
}
size_t getSize(void) { return size; }
size_t getNumLocks(void) { return n_locks; }
void clear();
StoredValue *find(std::string &key) {
assert(active());
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
return unlocked_find(key, bucket_num);
}
mutation_type_t set(const Item &val) {
assert(active());
mutation_type_t rv = NOT_FOUND;
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
Item &itm = const_cast<Item&>(val);
if (v) {
if (v->isLocked(ep_current_time())) {
/*
* item is locked, deny if there is cas value mismatch
* or no cas value is provided by the user
*/
if (val.getCas() != v->getCas()) {
return IS_LOCKED;
}
/* allow operation*/
v->unlock();
} else if (val.getCas() != 0 && val.getCas() != v->getCas()) {
return INVALID_CAS;
}
itm.setCas();
rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY;
v->setValue(itm.getValue(),
itm.getFlags(), itm.getExptime(),
itm.getCas());
} else {
if (itm.getCas() != 0) {
return INVALID_CAS;
}
itm.setCas();
v = valFact(itm, values[bucket_num]);
values[bucket_num] = v;
}
return rv;
}
bool add(const Item &val, bool isDirty = true) {
assert(active());
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
if (v) {
return false;
} else {
Item &itm = const_cast<Item&>(val);
itm.setCas();
v = valFact(itm, values[bucket_num], isDirty);
values[bucket_num] = v;
}
return true;
}
StoredValue *unlocked_find(const std::string &key, int bucket_num) {
StoredValue *v = values[bucket_num];
while (v) {
if (v->hasKey(key)) {
return v;
}
v = v->next;
}
return NULL;
}
inline int bucket(const char *str, const size_t len) {
assert(active());
int h=5381;
for(size_t i=0; i < len; i++) {
h = ((h << 5) + h) ^ str[i];
}
return abs(h) % (int)size;
}
inline int bucket(const std::string &s) {
return bucket(s.data(), s.length());
}
// Get the mutex for a bucket (for doing your own lock management)
inline Mutex &getMutex(int bucket_num) {
assert(active());
assert(bucket_num < (int)size);
assert(bucket_num >= 0);
int lock_num = bucket_num % (int)n_locks;
assert(lock_num < (int)n_locks);
assert(lock_num >= 0);
return mutexes[lock_num];
}
// True if it existed
bool del(const std::string &key) {
assert(active());
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
StoredValue *v = values[bucket_num];
// Special case empty bucket.
if (!v) {
return false;
}
// Special case the first one
if (v->hasKey(key)) {
if (v->isLocked(ep_current_time())) {
return false;
}
values[bucket_num] = v->next;
delete v;
return true;
}
while (v->next) {
if (v->next->hasKey(key)) {
StoredValue *tmp = v->next;
if (tmp->isLocked(ep_current_time())) {
return false;
}
v->next = v->next->next;
delete tmp;
return true;
} else {
v = v->next;
}
}
return false;
}
void visit(HashTableVisitor &visitor);
void visitDepth(HashTableDepthVisitor &visitor);
static size_t getNumBuckets(size_t);
static size_t getNumLocks(size_t);
static void setDefaultNumBuckets(size_t);
static void setDefaultNumLocks(size_t);
/**
* Set the stored value type by name.
*
* @param t either "small" or "featured"
*
* @rteurn true if this type is not handled.
*/
static bool setDefaultStorageValueType(const char *t);
static void setDefaultStorageValueType(enum stored_value_type);
static enum stored_value_type getDefaultStorageValueType();
static const char* getDefaultStorageValueTypeStr();
private:
inline bool active() { return values != NULL; }
size_t size;
size_t n_locks;
StoredValue **values;
Mutex *mutexes;
StoredValueFactory valFact;
static size_t defaultNumBuckets;
static size_t defaultNumLocks;
static enum stored_value_type defaultStoredValueType;
DISALLOW_COPY_AND_ASSIGN(HashTable);
};
#endif /* STORED_VALUE_H */
<commit_msg>Initialize hashtable buckets with calloc.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef STORED_VALUE_H
#define STORED_VALUE_H 1
#include <climits>
#include <cstring>
#include <algorithm>
#include "common.hh"
#include "item.hh"
#include "locks.hh"
extern "C" {
extern rel_time_t (*ep_current_time)();
}
// Forward declaration for StoredValue
class HashTable;
class StoredValueFactory;
class StoredValue {
public:
void operator delete(void* p) {
::operator delete(p);
}
virtual ~StoredValue() {
}
void markDirty() {
// We eat the last second of time for our dirty flag.
dirtiness = ep_current_time() | 1;
}
void reDirty(rel_time_t dataAge) {
dirtiness = dataAge | 1;
}
// returns time this object was dirtied.
void markClean(rel_time_t *dataAge) {
if (dataAge) {
*dataAge = dirtiness;
}
dirtiness = 0;
}
bool isDirty() const {
return dirtiness & 1;
}
bool isClean() const {
return !isDirty();
}
virtual const char* getKeyBytes() const = 0;
virtual uint8_t getKeyLen() const = 0;
virtual bool hasKey(const std::string &k) const = 0;
virtual const std::string getKey() const = 0;
value_t getValue() const {
return value;
}
virtual rel_time_t getExptime() const {
return 0;
}
virtual uint32_t getFlags() const {
return 0;
}
virtual void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
(void)newFlags;
(void)newExp;
(void)theCas;
value = v;
markDirty();
}
virtual uint64_t getCas() const {
return 0;
}
rel_time_t getDataAge() const {
return dirtiness;
}
virtual void setCas(uint64_t c) {
(void)c;
}
void lock(rel_time_t expiry) {
(void)expiry;
}
virtual void unlock() {
}
bool hasId() {
return id > 0;
}
int64_t getId() {
return id;
}
void setId(int64_t to) {
assert(!hasId());
id = to;
}
virtual bool isLocked(rel_time_t curtime) {
(void)curtime;
return false;
}
protected:
StoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
value(itm.getValue()), next(n), id(itm.getId())
{
if (setDirty) {
markDirty();
} else {
markClean(NULL);
}
}
friend class HashTable;
friend class StoredValueFactory;
value_t value;
StoredValue *next;
int64_t id;
uint32_t dirtiness;
DISALLOW_COPY_AND_ASSIGN(StoredValue);
};
class SmallStoredValue : protected StoredValue {
public:
const std::string getKey() const{
return std::string(keybytes, keylen);
}
const char* getKeyBytes() const {
return keybytes;
}
uint8_t getKeyLen() const {
return keylen;
}
bool hasKey(const std::string &k) const {
return k.length() == keylen
&& (std::memcmp(k.data(), keybytes, keylen) == 0);
}
private:
friend class StoredValueFactory;
SmallStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
StoredValue(itm, n, setDirty),
keylen(static_cast<uint8_t>(itm.getKey().length()))
{
if (setDirty) {
markDirty();
} else {
markClean(NULL);
}
}
uint8_t keylen;
char keybytes[1];
};
class FeaturedStoredValue : protected StoredValue {
public:
bool isLocked(rel_time_t curtime) {
if (locked && (curtime > lock_expiry)) {
locked = false;
return locked;
}
return locked;
}
void unlock() {
locked = false;
lock_expiry = 0;
}
void lock(rel_time_t expiry) {
locked = true;
lock_expiry = expiry;
}
void setCas(uint64_t c) {
cas = c;
}
uint64_t getCas() const {
return cas;
}
rel_time_t getExptime() const {
return exptime;
}
uint32_t getFlags() const {
return flags;
}
virtual void setValue(value_t v,
uint32_t newFlags, rel_time_t newExp, uint64_t theCas) {
cas = theCas;
flags = newFlags;
exptime = newExp;
StoredValue::setValue(v, newFlags, newExp, theCas);
}
const std::string getKey() const{
return std::string(keybytes, keylen);
}
const char* getKeyBytes() const {
return keybytes;
}
uint8_t getKeyLen() const {
return keylen;
}
bool hasKey(const std::string &k) const {
return k.length() == keylen
&& (std::memcmp(k.data(), keybytes, keylen) == 0);
}
private:
friend class StoredValueFactory;
FeaturedStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) :
StoredValue(itm, n, setDirty),
cas(itm.getCas()),
flags(itm.getFlags()),
exptime(itm.getExptime()),
locked(false), lock_expiry(0),
keylen(static_cast<uint8_t>(itm.getKey().length())) {}
uint64_t cas;
uint32_t flags;
rel_time_t exptime;
bool locked;
rel_time_t lock_expiry;
uint8_t keylen;
char keybytes[1];
};
typedef enum {
NOT_FOUND, INVALID_CAS, WAS_CLEAN, WAS_DIRTY, IS_LOCKED, SUCCESS
} mutation_type_t;
class HashTableVisitor {
public:
virtual ~HashTableVisitor() {}
virtual void visit(StoredValue *v) = 0;
};
class HashTableDepthVisitor {
public:
virtual ~HashTableDepthVisitor() {}
virtual void visit(int bucket, int depth) = 0;
};
class HashTableDepthStatVisitor : public HashTableDepthVisitor {
public:
HashTableDepthStatVisitor() : min(INT_MAX), max(0) {}
void visit(int bucket, int depth) {
(void)bucket;
min = std::min(min, depth);
max = std::max(max, depth);
}
int min;
int max;
};
enum stored_value_type {
small, featured
};
class StoredValueFactory {
public:
StoredValueFactory(enum stored_value_type t = featured) : type(t) {}
StoredValue *operator ()(const Item &itm, StoredValue *n,
bool setDirty = true) {
switch(type) {
case small:
return newStoredValue<SmallStoredValue>(itm, n, setDirty);
break;
case featured:
return newStoredValue<FeaturedStoredValue>(itm, n, setDirty);
break;
default:
abort();
};
}
private:
template <typename SV>
StoredValue* newStoredValue(const Item &itm, StoredValue *n, bool setDirty = true) {
std::string key = itm.getKey();
assert(key.length() < 256);
size_t len = key.length() + sizeof(SV);
SV *t = new (::operator new(len)) SV(itm, n, setDirty);
std::memcpy(t->keybytes, key.data(), key.length());
return t;
}
enum stored_value_type type;
};
class HashTable {
public:
// Construct with number of buckets and locks.
HashTable(size_t s = 0, size_t l = 0, enum stored_value_type t = featured)
: valFact(t) {
size = HashTable::getNumBuckets(s);
n_locks = HashTable::getNumLocks(l);
valFact = StoredValueFactory(getDefaultStorageValueType());
assert(size > 0);
assert(n_locks > 0);
values = static_cast<StoredValue**>(calloc(size, sizeof(StoredValue*)));
mutexes = new Mutex[n_locks];
}
~HashTable() {
clear();
delete []mutexes;
free(values);
values = NULL;
}
size_t getSize(void) { return size; }
size_t getNumLocks(void) { return n_locks; }
void clear();
StoredValue *find(std::string &key) {
assert(active());
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
return unlocked_find(key, bucket_num);
}
mutation_type_t set(const Item &val) {
assert(active());
mutation_type_t rv = NOT_FOUND;
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
Item &itm = const_cast<Item&>(val);
if (v) {
if (v->isLocked(ep_current_time())) {
/*
* item is locked, deny if there is cas value mismatch
* or no cas value is provided by the user
*/
if (val.getCas() != v->getCas()) {
return IS_LOCKED;
}
/* allow operation*/
v->unlock();
} else if (val.getCas() != 0 && val.getCas() != v->getCas()) {
return INVALID_CAS;
}
itm.setCas();
rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY;
v->setValue(itm.getValue(),
itm.getFlags(), itm.getExptime(),
itm.getCas());
} else {
if (itm.getCas() != 0) {
return INVALID_CAS;
}
itm.setCas();
v = valFact(itm, values[bucket_num]);
values[bucket_num] = v;
}
return rv;
}
bool add(const Item &val, bool isDirty = true) {
assert(active());
int bucket_num = bucket(val.getKey());
LockHolder lh(getMutex(bucket_num));
StoredValue *v = unlocked_find(val.getKey(), bucket_num);
if (v) {
return false;
} else {
Item &itm = const_cast<Item&>(val);
itm.setCas();
v = valFact(itm, values[bucket_num], isDirty);
values[bucket_num] = v;
}
return true;
}
StoredValue *unlocked_find(const std::string &key, int bucket_num) {
StoredValue *v = values[bucket_num];
while (v) {
if (v->hasKey(key)) {
return v;
}
v = v->next;
}
return NULL;
}
inline int bucket(const char *str, const size_t len) {
assert(active());
int h=5381;
for(size_t i=0; i < len; i++) {
h = ((h << 5) + h) ^ str[i];
}
return abs(h) % (int)size;
}
inline int bucket(const std::string &s) {
return bucket(s.data(), s.length());
}
// Get the mutex for a bucket (for doing your own lock management)
inline Mutex &getMutex(int bucket_num) {
assert(active());
assert(bucket_num < (int)size);
assert(bucket_num >= 0);
int lock_num = bucket_num % (int)n_locks;
assert(lock_num < (int)n_locks);
assert(lock_num >= 0);
return mutexes[lock_num];
}
// True if it existed
bool del(const std::string &key) {
assert(active());
int bucket_num = bucket(key);
LockHolder lh(getMutex(bucket_num));
StoredValue *v = values[bucket_num];
// Special case empty bucket.
if (!v) {
return false;
}
// Special case the first one
if (v->hasKey(key)) {
if (v->isLocked(ep_current_time())) {
return false;
}
values[bucket_num] = v->next;
delete v;
return true;
}
while (v->next) {
if (v->next->hasKey(key)) {
StoredValue *tmp = v->next;
if (tmp->isLocked(ep_current_time())) {
return false;
}
v->next = v->next->next;
delete tmp;
return true;
} else {
v = v->next;
}
}
return false;
}
void visit(HashTableVisitor &visitor);
void visitDepth(HashTableDepthVisitor &visitor);
static size_t getNumBuckets(size_t);
static size_t getNumLocks(size_t);
static void setDefaultNumBuckets(size_t);
static void setDefaultNumLocks(size_t);
/**
* Set the stored value type by name.
*
* @param t either "small" or "featured"
*
* @rteurn true if this type is not handled.
*/
static bool setDefaultStorageValueType(const char *t);
static void setDefaultStorageValueType(enum stored_value_type);
static enum stored_value_type getDefaultStorageValueType();
static const char* getDefaultStorageValueTypeStr();
private:
inline bool active() { return values != NULL; }
size_t size;
size_t n_locks;
StoredValue **values;
Mutex *mutexes;
StoredValueFactory valFact;
static size_t defaultNumBuckets;
static size_t defaultNumLocks;
static enum stored_value_type defaultStoredValueType;
DISALLOW_COPY_AND_ASSIGN(HashTable);
};
#endif /* STORED_VALUE_H */
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/native_mate_converters/net_converter.h"
#include <string>
#include <vector>
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace {
bool CertFromData(const std::string& data,
scoped_refptr<net::X509Certificate>* out) {
auto cert_list = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(),
net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
if (cert_list.empty())
return false;
auto leaf_cert = cert_list.front();
if (!leaf_cert)
return false;
*out = leaf_cert;
return true;
}
} // namespace
// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("isProxy", val->is_proxy);
dict.Set("scheme", val->scheme);
dict.Set("host", val->challenger.host());
dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
dict.Set("realm", val->realm);
return mate::ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
std::string encoded_data;
net::X509Certificate::GetPEMEncoded(
val->os_cert_handle(), &encoded_data);
dict.Set("data", encoded_data);
dict.Set("issuer", val->issuer());
dict.Set("issuerName", val->issuer().GetDisplayName());
dict.Set("subject", val->subject());
dict.Set("subjectName", val->subject().GetDisplayName());
dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
val->serial_number().size()));
dict.Set("validStart", val->valid_start().ToDoubleT());
dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
dict.Set("fingerprint",
net::HashValue(
val->CalculateFingerprint256(val->os_cert_handle())).ToString());
if (!val->GetIntermediateCertificates().empty()) {
net::X509Certificate::OSCertHandles issuer_intermediates(
val->GetIntermediateCertificates().begin() + 1,
val->GetIntermediateCertificates().end());
const scoped_refptr<net::X509Certificate>& issuer_cert =
net::X509Certificate::CreateFromHandle(
val->GetIntermediateCertificates().front(),
issuer_intermediates);
dict.Set("issuerCert", issuer_cert);
}
return dict.GetHandle();
}
bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
v8::Isolate* isolate, v8::Local<v8::Value> val,
scoped_refptr<net::X509Certificate>* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
std::string data;
dict.Get("data", &data);
scoped_refptr<net::X509Certificate> leaf_cert;
if (!CertFromData(data, &leaf_cert))
return false;
scoped_refptr<net::X509Certificate> parent;
if (dict.Get("issuerCert", &parent)) {
auto parents = std::vector<net::X509Certificate::OSCertHandle>(
parent->GetIntermediateCertificates());
parents.insert(parents.begin(), parent->os_cert_handle());
auto cert = net::X509Certificate::CreateFromHandle(
leaf_cert->os_cert_handle(), parents);
if (!cert)
return false;
*out = cert;
} else {
*out = leaf_cert;
}
return true;
}
// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
v8::Isolate* isolate, const net::CertPrincipal& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("commonName", val.common_name);
dict.Set("organizations", val.organization_names);
dict.Set("organizationUnits", val.organization_unit_names);
dict.Set("locality", val.locality_name);
dict.Set("state", val.state_or_province_name);
dict.Set("country", val.country_name);
return dict.GetHandle();
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
} // namespace mate
namespace atom {
void FillRequestDetails(base::DictionaryValue* details,
const net::URLRequest* request) {
details->SetString("method", request->method());
std::string url;
if (!request->url_chain().empty()) url = request->url().spec();
details->SetStringWithoutPathExpansion("url", url);
details->SetString("referrer", request->referrer());
std::unique_ptr<base::ListValue> list(new base::ListValue);
GetUploadData(list.get(), request);
if (!list->empty())
details->Set("uploadData", std::move(list));
}
void GetUploadData(base::ListValue* upload_data_list,
const net::URLRequest* request) {
const net::UploadDataStream* upload_data = request->get_upload();
if (!upload_data)
return;
const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
upload_data->GetElementReaders();
for (const auto& reader : *readers) {
std::unique_ptr<base::DictionaryValue> upload_data_dict(
new base::DictionaryValue);
if (reader->AsBytesReader()) {
const net::UploadBytesElementReader* bytes_reader =
reader->AsBytesReader();
std::unique_ptr<base::Value> bytes(
base::Value::CreateWithCopiedBuffer(bytes_reader->bytes(),
bytes_reader->length()));
upload_data_dict->Set("bytes", std::move(bytes));
} else if (reader->AsFileReader()) {
const net::UploadFileElementReader* file_reader =
reader->AsFileReader();
auto file_path = file_reader->path().AsUTF8Unsafe();
upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
} else {
const storage::UploadBlobElementReader* blob_reader =
static_cast<storage::UploadBlobElementReader*>(reader.get());
upload_data_dict->SetString("blobUUID", blob_reader->uuid());
}
upload_data_list->Append(std::move(upload_data_dict));
}
}
} // namespace atom
<commit_msg>Modify FillRequestDetails to pass headers dictionary.<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/native_mate_converters/net_converter.h"
#include <string>
#include <vector>
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/x509_certificate.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "storage/browser/blob/upload_blob_element_reader.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace {
bool CertFromData(const std::string& data,
scoped_refptr<net::X509Certificate>* out) {
auto cert_list = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(),
net::X509Certificate::FORMAT_SINGLE_CERTIFICATE);
if (cert_list.empty())
return false;
auto leaf_cert = cert_list.front();
if (!leaf_cert)
return false;
*out = leaf_cert;
return true;
}
} // namespace
// static
v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8(
v8::Isolate* isolate, const net::AuthChallengeInfo* val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("isProxy", val->is_proxy);
dict.Set("scheme", val->scheme);
dict.Set("host", val->challenger.host());
dict.Set("port", static_cast<uint32_t>(val->challenger.port()));
dict.Set("realm", val->realm);
return mate::ConvertToV8(isolate, dict);
}
// static
v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
std::string encoded_data;
net::X509Certificate::GetPEMEncoded(
val->os_cert_handle(), &encoded_data);
dict.Set("data", encoded_data);
dict.Set("issuer", val->issuer());
dict.Set("issuerName", val->issuer().GetDisplayName());
dict.Set("subject", val->subject());
dict.Set("subjectName", val->subject().GetDisplayName());
dict.Set("serialNumber", base::HexEncode(val->serial_number().data(),
val->serial_number().size()));
dict.Set("validStart", val->valid_start().ToDoubleT());
dict.Set("validExpiry", val->valid_expiry().ToDoubleT());
dict.Set("fingerprint",
net::HashValue(
val->CalculateFingerprint256(val->os_cert_handle())).ToString());
if (!val->GetIntermediateCertificates().empty()) {
net::X509Certificate::OSCertHandles issuer_intermediates(
val->GetIntermediateCertificates().begin() + 1,
val->GetIntermediateCertificates().end());
const scoped_refptr<net::X509Certificate>& issuer_cert =
net::X509Certificate::CreateFromHandle(
val->GetIntermediateCertificates().front(),
issuer_intermediates);
dict.Set("issuerCert", issuer_cert);
}
return dict.GetHandle();
}
bool Converter<scoped_refptr<net::X509Certificate>>::FromV8(
v8::Isolate* isolate, v8::Local<v8::Value> val,
scoped_refptr<net::X509Certificate>* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
std::string data;
dict.Get("data", &data);
scoped_refptr<net::X509Certificate> leaf_cert;
if (!CertFromData(data, &leaf_cert))
return false;
scoped_refptr<net::X509Certificate> parent;
if (dict.Get("issuerCert", &parent)) {
auto parents = std::vector<net::X509Certificate::OSCertHandle>(
parent->GetIntermediateCertificates());
parents.insert(parents.begin(), parent->os_cert_handle());
auto cert = net::X509Certificate::CreateFromHandle(
leaf_cert->os_cert_handle(), parents);
if (!cert)
return false;
*out = cert;
} else {
*out = leaf_cert;
}
return true;
}
// static
v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8(
v8::Isolate* isolate, const net::CertPrincipal& val) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("commonName", val.common_name);
dict.Set("organizations", val.organization_names);
dict.Set("organizationUnits", val.organization_unit_names);
dict.Set("locality", val.locality_name);
dict.Set("state", val.state_or_province_name);
dict.Set("country", val.country_name);
return dict.GetHandle();
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
} // namespace mate
namespace atom {
void FillRequestDetails(base::DictionaryValue* details,
const net::URLRequest* request) {
details->SetString("method", request->method());
std::string url;
if (!request->url_chain().empty()) url = request->url().spec();
details->SetStringWithoutPathExpansion("url", url);
details->SetString("referrer", request->referrer());
std::unique_ptr<base::ListValue> list(new base::ListValue);
GetUploadData(list.get(), request);
if (!list->empty())
details->Set("uploadData", std::move(list));
std::unique_ptr<base::DictionaryValue> headers_value(
new base::DictionaryValue);
for (net::HttpRequestHeaders::Iterator it(request->extra_request_headers());
it.GetNext();) {
headers_value->SetString(it.name(), it.value());
}
details->Set("headers", std::move(headers_value));
}
void GetUploadData(base::ListValue* upload_data_list,
const net::URLRequest* request) {
const net::UploadDataStream* upload_data = request->get_upload();
if (!upload_data)
return;
const std::vector<std::unique_ptr<net::UploadElementReader>>* readers =
upload_data->GetElementReaders();
for (const auto& reader : *readers) {
std::unique_ptr<base::DictionaryValue> upload_data_dict(
new base::DictionaryValue);
if (reader->AsBytesReader()) {
const net::UploadBytesElementReader* bytes_reader =
reader->AsBytesReader();
std::unique_ptr<base::Value> bytes(
base::Value::CreateWithCopiedBuffer(bytes_reader->bytes(),
bytes_reader->length()));
upload_data_dict->Set("bytes", std::move(bytes));
} else if (reader->AsFileReader()) {
const net::UploadFileElementReader* file_reader =
reader->AsFileReader();
auto file_path = file_reader->path().AsUTF8Unsafe();
upload_data_dict->SetStringWithoutPathExpansion("file", file_path);
} else {
const storage::UploadBlobElementReader* blob_reader =
static_cast<storage::UploadBlobElementReader*>(reader.get());
upload_data_dict->SetString("blobUUID", blob_reader->uuid());
}
upload_data_list->Append(std::move(upload_data_dict));
}
}
} // namespace atom
<|endoftext|>
|
<commit_before>// Begin CVS Header
// $Source: /fs/turing/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $
// $Revision: 1.83 $
// $Name: $
// $Author: jpahle $
// $Date: 2011/05/24 17:30:48 $
// End CVS Header
// Copyright (C) 2011 - 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CScanTask class.
*
* This class implements a scan task which is comprised of a
* of a problem and a method.
*
*/
#include "copasi.h"
#include "CScanTask.h"
#include "CScanProblem.h"
#include "CScanMethod.h"
#include "utilities/CReadConfig.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "optimization/COptProblem.h"
#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryProblem.h"
#include "steadystate/CSteadyStateTask.h"
#include "steadystate/CSteadyStateProblem.h"
#include "lna/CLNAProblem.h"
#include "lna/CLNATask.h"
#include "utilities/COutputHandler.h"
#include "utilities/CProcessReport.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
CScanTask::CScanTask(const CCopasiContainer * pParent):
CCopasiTask(CCopasiTask::scan, pParent)
{
mpProblem = new CScanProblem(this);
mpMethod = createMethod(CCopasiMethod::scanMethod);
this->add(mpMethod, true);
static_cast< CScanMethod * >(mpMethod)->setProblem(static_cast< CScanProblem * >(mpProblem));
}
CScanTask::CScanTask(const CScanTask & src,
const CCopasiContainer * pParent):
CCopasiTask(src, pParent)
{
mpProblem = new CScanProblem(*(CScanProblem *) src.mpProblem, this);
mpMethod = createMethod(CCopasiMethod::scanMethod);
this->add(mpMethod, true);
static_cast< CScanMethod * >(mpMethod)->setProblem(static_cast< CScanProblem * >(mpProblem));
}
CScanTask::~CScanTask()
{cleanup();}
// virtual
CCopasiMethod * CScanTask::createMethod(const int & type) const
{
CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;
return CScanMethod::createMethod(Type);
}
void CScanTask::cleanup()
{}
bool CScanTask::initialize(const OutputFlag & of,
COutputHandler * pOutputHandler,
std::ostream * pOstream)
{
assert(mpProblem && mpMethod);
mpMethod->isValidProblem(mpProblem);
bool success = true;
if ((of & REPORT) &&
pOutputHandler != NULL)
{
if (mReport.open(getObjectDataModel(), pOstream))
pOutputHandler->addInterface(&mReport);
else
CCopasiMessage(CCopasiMessage::COMMANDLINE, MCCopasiTask + 5, getObjectName().c_str());
}
success &= initSubtask(of, pOutputHandler, mReport.getStream());
success &= CCopasiTask::initialize(of, pOutputHandler, mReport.getStream());
return success;
}
void CScanTask::load(CReadConfig & C_UNUSED(configBuffer))
{}
bool CScanTask::process(const bool & useInitialValues)
{
if (!mpProblem) fatalError();
if (!mpMethod) fatalError();
//mpMethod->isValidProblem(mpProblem);
CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem);
if (!pProblem) fatalError();
CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod);
if (!pMethod) fatalError();
bool success = true;
//initSubtask();
if (useInitialValues)
{
mpProblem->getModel()->applyInitialValues();
}
//TODO: reports
//initialize the method (parsing the ScanItems)
pMethod->setProblem(pProblem);
if (!pMethod->init()) return false;
// init progress bar
mProgress = 0;
if (mpCallBack)
{
mpCallBack->setName("performing parameter scan...");
unsigned C_INT32 totalSteps = (unsigned C_INT32) pMethod->getTotalNumberOfSteps();
mhProgress = mpCallBack->addItem("Number of Steps",
mProgress,
&totalSteps);
if (mpSubtask)
mpSubtask->setCallBack(mpCallBack);
}
// init output handler (plotting)
output(COutputInterface::BEFORE);
//calling the scanner, output is done in the callback
if (!pMethod->scan()) success = false;
//finishing progress bar and output
//if (mpCallBack) mpCallBack->finish();
//if (mpOutputHandler) mpOutputHandler->finish();
output(COutputInterface::AFTER);
if (mpSubtask)
mpSubtask->setCallBack(NULL);
return success;
}
bool CScanTask::processCallback()
{
bool success = mpSubtask->process(!mAdjustInitialConditions);
//do output
if (success && !mOutputInSubtask)
output(COutputInterface::DURING);
if (mpSubtask->isUpdateModel())
{
COptProblem* problem = dynamic_cast<COptProblem*> (mpSubtask->getProblem());
if (problem != NULL)
{
problem->restoreModel(true);
}
}
//do progress bar
++mProgress;
if (mpCallBack) return mpCallBack->progressItem(mhProgress);
return true;
}
bool CScanTask::outputSeparatorCallback(bool isLast)
{
if ((!isLast) || mOutputInSubtask)
separate(COutputInterface::DURING);
return true;
}
bool CScanTask::initSubtask(const OutputFlag & /* of */,
COutputHandler * pOutputHandler,
std::ostream * pOstream)
{
if (!mpProblem) fatalError();
CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem);
if (!pProblem) fatalError();
//get the parameters from the problem
CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT;
CCopasiDataModel* pDataModel = getObjectDataModel();
assert(pDataModel != NULL);
switch (type)
{
case CCopasiTask::steadyState:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Steady-State"]);
break;
case CCopasiTask::timeCourse:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Time-Course"]);
break;
case CCopasiTask::mca:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Metabolic Control Analysis"]);
break;
case CCopasiTask::lyap:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Lyapunov Exponents"]);
break;
case CCopasiTask::optimization:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Optimization"]);
break;
case CCopasiTask::parameterFitting:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Parameter Estimation"]);
break;
case CCopasiTask::sens:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Sensitivities"]);
break;
case CCopasiTask::lna:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Linear Noise Approximation"]);
break;
default:
mpSubtask = NULL;
}
mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL;
//if (type != CCopasiTask::timeCourse)
// mOutputInSubtask = false;
mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL;
if (!mpSubtask) return false;
mpSubtask->getProblem()->setModel(pDataModel->getModel()); //TODO
mpSubtask->setCallBack(NULL);
if (mOutputInSubtask)
return mpSubtask->initialize(OUTPUT, pOutputHandler, pOstream);
else
return mpSubtask->initialize(NO_OUTPUT, pOutputHandler, pOstream);
return true;
}
<commit_msg>Fixed copyright and formating.<commit_after>// Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
/**
* CScanTask class.
*
* This class implements a scan task which is comprised of a
* of a problem and a method.
*
*/
#include "copasi.h"
#include "CScanTask.h"
#include "CScanProblem.h"
#include "CScanMethod.h"
#include "utilities/CReadConfig.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "optimization/COptProblem.h"
#include "trajectory/CTrajectoryTask.h"
#include "trajectory/CTrajectoryProblem.h"
#include "steadystate/CSteadyStateTask.h"
#include "steadystate/CSteadyStateProblem.h"
#include "lna/CLNAProblem.h"
#include "lna/CLNATask.h"
#include "utilities/COutputHandler.h"
#include "utilities/CProcessReport.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
CScanTask::CScanTask(const CCopasiContainer * pParent):
CCopasiTask(CCopasiTask::scan, pParent)
{
mpProblem = new CScanProblem(this);
mpMethod = createMethod(CCopasiMethod::scanMethod);
this->add(mpMethod, true);
static_cast< CScanMethod * >(mpMethod)->setProblem(static_cast< CScanProblem * >(mpProblem));
}
CScanTask::CScanTask(const CScanTask & src,
const CCopasiContainer * pParent):
CCopasiTask(src, pParent)
{
mpProblem = new CScanProblem(*(CScanProblem *) src.mpProblem, this);
mpMethod = createMethod(CCopasiMethod::scanMethod);
this->add(mpMethod, true);
static_cast< CScanMethod * >(mpMethod)->setProblem(static_cast< CScanProblem * >(mpProblem));
}
CScanTask::~CScanTask()
{cleanup();}
// virtual
CCopasiMethod * CScanTask::createMethod(const int & type) const
{
CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;
return CScanMethod::createMethod(Type);
}
void CScanTask::cleanup()
{}
bool CScanTask::initialize(const OutputFlag & of,
COutputHandler * pOutputHandler,
std::ostream * pOstream)
{
assert(mpProblem && mpMethod);
mpMethod->isValidProblem(mpProblem);
bool success = true;
if ((of & REPORT) &&
pOutputHandler != NULL)
{
if (mReport.open(getObjectDataModel(), pOstream))
pOutputHandler->addInterface(&mReport);
else
CCopasiMessage(CCopasiMessage::COMMANDLINE, MCCopasiTask + 5, getObjectName().c_str());
}
success &= initSubtask(of, pOutputHandler, mReport.getStream());
success &= CCopasiTask::initialize(of, pOutputHandler, mReport.getStream());
return success;
}
void CScanTask::load(CReadConfig & C_UNUSED(configBuffer))
{}
bool CScanTask::process(const bool & useInitialValues)
{
if (!mpProblem) fatalError();
if (!mpMethod) fatalError();
//mpMethod->isValidProblem(mpProblem);
CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem);
if (!pProblem) fatalError();
CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod);
if (!pMethod) fatalError();
bool success = true;
//initSubtask();
if (useInitialValues)
{
mpProblem->getModel()->applyInitialValues();
}
//TODO: reports
//initialize the method (parsing the ScanItems)
pMethod->setProblem(pProblem);
if (!pMethod->init()) return false;
// init progress bar
mProgress = 0;
if (mpCallBack)
{
mpCallBack->setName("performing parameter scan...");
unsigned C_INT32 totalSteps = (unsigned C_INT32) pMethod->getTotalNumberOfSteps();
mhProgress = mpCallBack->addItem("Number of Steps",
mProgress,
&totalSteps);
if (mpSubtask)
mpSubtask->setCallBack(mpCallBack);
}
// init output handler (plotting)
output(COutputInterface::BEFORE);
//calling the scanner, output is done in the callback
if (!pMethod->scan()) success = false;
//finishing progress bar and output
//if (mpCallBack) mpCallBack->finish();
//if (mpOutputHandler) mpOutputHandler->finish();
output(COutputInterface::AFTER);
if (mpSubtask)
mpSubtask->setCallBack(NULL);
return success;
}
bool CScanTask::processCallback()
{
bool success = mpSubtask->process(!mAdjustInitialConditions);
//do output
if (success && !mOutputInSubtask)
output(COutputInterface::DURING);
if (mpSubtask->isUpdateModel())
{
COptProblem* problem = dynamic_cast<COptProblem*>(mpSubtask->getProblem());
if (problem != NULL)
{
problem->restoreModel(true);
}
}
//do progress bar
++mProgress;
if (mpCallBack) return mpCallBack->progressItem(mhProgress);
return true;
}
bool CScanTask::outputSeparatorCallback(bool isLast)
{
if ((!isLast) || mOutputInSubtask)
separate(COutputInterface::DURING);
return true;
}
bool CScanTask::initSubtask(const OutputFlag & /* of */,
COutputHandler * pOutputHandler,
std::ostream * pOstream)
{
if (!mpProblem) fatalError();
CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem);
if (!pProblem) fatalError();
//get the parameters from the problem
CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT;
CCopasiDataModel* pDataModel = getObjectDataModel();
assert(pDataModel != NULL);
switch (type)
{
case CCopasiTask::steadyState:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Steady-State"]);
break;
case CCopasiTask::timeCourse:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Time-Course"]);
break;
case CCopasiTask::mca:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Metabolic Control Analysis"]);
break;
case CCopasiTask::lyap:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Lyapunov Exponents"]);
break;
case CCopasiTask::optimization:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Optimization"]);
break;
case CCopasiTask::parameterFitting:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Parameter Estimation"]);
break;
case CCopasiTask::sens:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Sensitivities"]);
break;
case CCopasiTask::lna:
mpSubtask = dynamic_cast<CCopasiTask*>
((*pDataModel->getTaskList())["Linear Noise Approximation"]);
break;
default:
mpSubtask = NULL;
}
mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL;
//if (type != CCopasiTask::timeCourse)
// mOutputInSubtask = false;
mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL;
if (!mpSubtask) return false;
mpSubtask->getProblem()->setModel(pDataModel->getModel()); //TODO
mpSubtask->setCallBack(NULL);
if (mOutputInSubtask)
return mpSubtask->initialize(OUTPUT, pOutputHandler, pOstream);
else
return mpSubtask->initialize(NO_OUTPUT, pOutputHandler, pOstream);
return true;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "MeshPrimitiveBinding.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECorePython/RunTimeTypedBinding.h"
using namespace boost::python;
using namespace IECore;
using namespace IECorePython;
using namespace IECoreScene;
namespace IECoreSceneModule
{
static IntVectorDataPtr verticesPerFace( const MeshPrimitive &p )
{
return p.verticesPerFace()->copy();
}
static IntVectorDataPtr vertexIds( const MeshPrimitive &p )
{
return p.vertexIds()->copy();
}
void bindMeshPrimitive()
{
RunTimeTypedClass<MeshPrimitive>()
.def( init<>() )
.def( init<IntVectorDataPtr, IntVectorDataPtr, optional<const std::string &, V3fVectorDataPtr> >() )
.def( "numFaces", &MeshPrimitive::numFaces )
.def("minVerticesPerFace", &MeshPrimitive::minVerticesPerFace )
.def("maxVerticesPerFace", &MeshPrimitive::maxVerticesPerFace )
/// \todo I'd rather see these bound as functions rather than properties so they match the C++ interface.
/// I think this is particularly important for verticesPerFace and vertexIds as it's pretty unintuitive that a property
/// should return a copy. This is something we need to be more consistent about throughout cortex.
.add_property( "verticesPerFace", &verticesPerFace, "A copy of the mesh's list of vertices per face." )
.add_property( "vertexIds", &vertexIds, "A copy of the mesh's list of vertex ids." )
.add_property( "interpolation", make_function( &MeshPrimitive::interpolation, return_value_policy<copy_const_reference>() ), &MeshPrimitive::setInterpolation )
.def( "setTopology", &MeshPrimitive::setTopology )
.def( "createBox", &MeshPrimitive::createBox, ( arg_( "bounds" ) ) ).staticmethod( "createBox" )
.def( "createPlane", &MeshPrimitive::createPlane, ( arg_( "bounds" ), arg_( "divisions" ) = Imath::V2i( 1 ) ) ).staticmethod( "createPlane" )
.def( "createSphere", &MeshPrimitive::createSphere, ( arg_( "radius" ), arg_( "zMin" ) = -1.0f, arg_( "zMax" ) = 1.0f, arg_( "thetaMax" ) = 360.0f, arg_( "divisions" ) = Imath::V2i( 20, 40 ) ) ).staticmethod( "createSphere" )
;
}
}
<commit_msg>MeshPrimitiveBinding : Reformat<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "MeshPrimitiveBinding.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECorePython/RunTimeTypedBinding.h"
using namespace boost::python;
using namespace IECore;
using namespace IECorePython;
using namespace IECoreScene;
namespace
{
IntVectorDataPtr verticesPerFace( const MeshPrimitive &p )
{
return p.verticesPerFace()->copy();
}
IntVectorDataPtr vertexIds( const MeshPrimitive &p )
{
return p.vertexIds()->copy();
}
} // namespace
void IECoreSceneModule::bindMeshPrimitive()
{
RunTimeTypedClass<MeshPrimitive>()
.def( init<>() )
.def( init<IntVectorDataPtr, IntVectorDataPtr, optional<const std::string &, V3fVectorDataPtr> >() )
.def( "numFaces", &MeshPrimitive::numFaces )
.def("minVerticesPerFace", &MeshPrimitive::minVerticesPerFace )
.def("maxVerticesPerFace", &MeshPrimitive::maxVerticesPerFace )
/// \todo I'd rather see these bound as functions rather than properties so they match the C++ interface.
/// I think this is particularly important for verticesPerFace and vertexIds as it's pretty unintuitive that a property
/// should return a copy. This is something we need to be more consistent about throughout cortex.
.add_property( "verticesPerFace", &verticesPerFace, "A copy of the mesh's list of vertices per face." )
.add_property( "vertexIds", &vertexIds, "A copy of the mesh's list of vertex ids." )
.add_property( "interpolation", make_function( &MeshPrimitive::interpolation, return_value_policy<copy_const_reference>() ), &MeshPrimitive::setInterpolation )
.def( "setTopology", &MeshPrimitive::setTopology )
.def( "createBox", &MeshPrimitive::createBox, ( arg_( "bounds" ) ) ).staticmethod( "createBox" )
.def( "createPlane", &MeshPrimitive::createPlane, ( arg_( "bounds" ), arg_( "divisions" ) = Imath::V2i( 1 ) ) ).staticmethod( "createPlane" )
.def( "createSphere", &MeshPrimitive::createSphere, ( arg_( "radius" ), arg_( "zMin" ) = -1.0f, arg_( "zMax" ) = 1.0f, arg_( "thetaMax" ) = 360.0f, arg_( "divisions" ) = Imath::V2i( 20, 40 ) ) ).staticmethod( "createSphere" )
;
}
<|endoftext|>
|
<commit_before>// SinkFacility.cpp
// Implements the SinkFacility class
#include <sstream>
#include <limits>
#include <boost/lexical_cast.hpp>
#include "SinkFacility.h"
#include "Logger.h"
#include "GenericResource.h"
#include "CycException.h"
#include "MarketModel.h"
using namespace std;
using boost::lexical_cast;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SinkFacility::SinkFacility() :
commod_price_(0),
capacity_(numeric_limits<double>::max())
{}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SinkFacility::~SinkFacility()
{}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::initModuleMembers(QueryEngine* qe) {
QueryEngine* input = qe->queryElement("input");
QueryEngine* commodities = input->queryElement("commodities");
string query = "incommodity";
int nCommodities = commodities->nElementsMatchingQuery(query);
for (int i = 0; i < nCommodities; i++) {
addCommodity(commodities->getElementContent(query,i));
}
string data;
try {
data = input->getElementContent("input_capacity");
setCapacity(lexical_cast<double>(data));
} catch (CycNullQueryException e) {
setCapacity(numeric_limits<double>::max());
}
try {
data = input->getElementContent("inventorysize");
setMaxInventorySize(lexical_cast<double>(data));
} catch (CycNullQueryException e) {
setMaxInventorySize(numeric_limits<double>::max());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SinkFacility::str() {
std::stringstream ss;
ss << FacilityModel::str();
string msg = "";
msg += "accepts commodities ";
for (vector<string>::iterator commod=in_commods_.begin();
commod != in_commods_.end();
commod++) {
msg += (commod == in_commods_.begin() ? "{" : ", " );
msg += (*commod);
}
msg += "} until its inventory is full at ";
ss << msg << inventory_.capacity() << " kg.";
return "" + ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::cloneModuleMembersFrom(FacilityModel* sourceModel) {
SinkFacility* source = dynamic_cast<SinkFacility*>(sourceModel);
setCapacity(source->capacity());
setMaxInventorySize(source->maxInventorySize());
in_commods_ = source->inputCommodities();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::handleTick(int time){
LOG(LEV_INFO3, "SnkFac") << facName() << " is ticking {";
double requestAmt = getRequestAmt();
CLOG(LEV_DEBUG3) << "SinkFacility " << name() << " on the tick has "
<< "a request amount of: " << requestAmt;
double minAmt = 0;
if (requestAmt>EPS_KG){
// for each potential commodity, make a request
for (vector<string>::iterator commod = in_commods_.begin();
commod != in_commods_.end();
commod++) {
LOG(LEV_INFO4, "SnkFac") << " requests "<< requestAmt << " kg of " << *commod << ".";
MarketModel* market = MarketModel::marketForCommod(*commod);
Communicator* recipient = dynamic_cast<Communicator*>(market);
// create a generic resource
gen_rsrc_ptr request_res = gen_rsrc_ptr(new GenericResource((*commod), "kg", requestAmt));
// build the transaction and message
Transaction trans(this, REQUEST);
trans.setCommod(*commod);
trans.setMinFrac(minAmt/requestAmt);
trans.setPrice(commod_price_);
trans.setResource(request_res);
msg_ptr request(new Message(this, recipient, trans));
request->sendOn();
}
}
LOG(LEV_INFO3, "SnkFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::handleTock(int time){
LOG(LEV_INFO3, "SnkFac") << facName() << " is tocking {";
// On the tock, the sink facility doesn't really do much.
// Maybe someday it will record things.
// For now, lets just print out what we have at each timestep.
LOG(LEV_INFO4, "SnkFac") << "SinkFacility " << this->ID()
<< " is holding " << inventory_.quantity()
<< " units of material at the close of month " << time
<< ".";
LOG(LEV_INFO3, "SnkFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::addCommodity(std::string name) {
in_commods_.push_back(name);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::setCapacity(double capacity) {
capacity_ = capacity;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::capacity() {
return capacity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::setMaxInventorySize(double size) {
inventory_.setCapacity(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::maxInventorySize() {
return inventory_.capacity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::inventorySize() {
return inventory_.quantity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<std::string> SinkFacility::inputCommodities() {
return in_commods_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::addResource(Transaction trans, std::vector<rsrc_ptr> manifest) {
inventory_.pushAll(MatBuff::toMat(manifest));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const double SinkFacility::getRequestAmt(){
// The sink facility should ask for as much stuff as it can reasonably receive.
double requestAmt;
// get current capacity
double space = inventory_.space();
if (space <= 0 ){
requestAmt=0;
} else if (space < capacity_){
requestAmt = space/in_commods_.size();
} else if (space >= capacity_){
requestAmt = capacity_/in_commods_.size();
}
return requestAmt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" Model* constructSinkFacility() {
return new SinkFacility();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" void destructSinkFacility(Model* model) {
delete model;
}
<commit_msg>the sink facility generic resource constructor now correctly orders the commodity and resource arguments<commit_after>// SinkFacility.cpp
// Implements the SinkFacility class
#include <sstream>
#include <limits>
#include <boost/lexical_cast.hpp>
#include "SinkFacility.h"
#include "Logger.h"
#include "GenericResource.h"
#include "CycException.h"
#include "MarketModel.h"
using namespace std;
using boost::lexical_cast;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SinkFacility::SinkFacility() :
commod_price_(0),
capacity_(numeric_limits<double>::max())
{}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SinkFacility::~SinkFacility()
{}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::initModuleMembers(QueryEngine* qe) {
QueryEngine* input = qe->queryElement("input");
QueryEngine* commodities = input->queryElement("commodities");
string query = "incommodity";
int nCommodities = commodities->nElementsMatchingQuery(query);
for (int i = 0; i < nCommodities; i++) {
addCommodity(commodities->getElementContent(query,i));
}
string data;
try {
data = input->getElementContent("input_capacity");
setCapacity(lexical_cast<double>(data));
} catch (CycNullQueryException e) {
setCapacity(numeric_limits<double>::max());
}
try {
data = input->getElementContent("inventorysize");
setMaxInventorySize(lexical_cast<double>(data));
} catch (CycNullQueryException e) {
setMaxInventorySize(numeric_limits<double>::max());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string SinkFacility::str() {
std::stringstream ss;
ss << FacilityModel::str();
string msg = "";
msg += "accepts commodities ";
for (vector<string>::iterator commod=in_commods_.begin();
commod != in_commods_.end();
commod++) {
msg += (commod == in_commods_.begin() ? "{" : ", " );
msg += (*commod);
}
msg += "} until its inventory is full at ";
ss << msg << inventory_.capacity() << " kg.";
return "" + ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::cloneModuleMembersFrom(FacilityModel* sourceModel) {
SinkFacility* source = dynamic_cast<SinkFacility*>(sourceModel);
setCapacity(source->capacity());
setMaxInventorySize(source->maxInventorySize());
in_commods_ = source->inputCommodities();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::handleTick(int time){
LOG(LEV_INFO3, "SnkFac") << facName() << " is ticking {";
double requestAmt = getRequestAmt();
CLOG(LEV_DEBUG3) << "SinkFacility " << name() << " on the tick has "
<< "a request amount of: " << requestAmt;
double minAmt = 0;
if (requestAmt>EPS_KG){
// for each potential commodity, make a request
for (vector<string>::iterator commod = in_commods_.begin();
commod != in_commods_.end();
commod++) {
LOG(LEV_INFO4, "SnkFac") << " requests "<< requestAmt << " kg of " << *commod << ".";
MarketModel* market = MarketModel::marketForCommod(*commod);
Communicator* recipient = dynamic_cast<Communicator*>(market);
// create a generic resource
gen_rsrc_ptr request_res = gen_rsrc_ptr(new GenericResource("kg",*commod,requestAmt));
// build the transaction and message
Transaction trans(this, REQUEST);
trans.setCommod(*commod);
trans.setMinFrac(minAmt/requestAmt);
trans.setPrice(commod_price_);
trans.setResource(request_res);
msg_ptr request(new Message(this, recipient, trans));
request->sendOn();
}
}
LOG(LEV_INFO3, "SnkFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::handleTock(int time){
LOG(LEV_INFO3, "SnkFac") << facName() << " is tocking {";
// On the tock, the sink facility doesn't really do much.
// Maybe someday it will record things.
// For now, lets just print out what we have at each timestep.
LOG(LEV_INFO4, "SnkFac") << "SinkFacility " << this->ID()
<< " is holding " << inventory_.quantity()
<< " units of material at the close of month " << time
<< ".";
LOG(LEV_INFO3, "SnkFac") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::addCommodity(std::string name) {
in_commods_.push_back(name);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::setCapacity(double capacity) {
capacity_ = capacity;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::capacity() {
return capacity_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::setMaxInventorySize(double size) {
inventory_.setCapacity(size);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::maxInventorySize() {
return inventory_.capacity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double SinkFacility::inventorySize() {
return inventory_.quantity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<std::string> SinkFacility::inputCommodities() {
return in_commods_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void SinkFacility::addResource(Transaction trans, std::vector<rsrc_ptr> manifest) {
inventory_.pushAll(MatBuff::toMat(manifest));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const double SinkFacility::getRequestAmt(){
// The sink facility should ask for as much stuff as it can reasonably receive.
double requestAmt;
// get current capacity
double space = inventory_.space();
if (space <= 0 ){
requestAmt=0;
} else if (space < capacity_){
requestAmt = space/in_commods_.size();
} else if (space >= capacity_){
requestAmt = capacity_/in_commods_.size();
}
return requestAmt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" Model* constructSinkFacility() {
return new SinkFacility();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" void destructSinkFacility(Model* model) {
delete model;
}
<|endoftext|>
|
<commit_before>#include "qztest.h"
#include "testquazip.h"
#include "testquazipfile.h"
#include "testquachecksum32.h"
#include "testjlcompress.h"
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QTextStream>
#include <QtTest/QtTest>
bool createTestFiles(const QStringList &fileNames, const QString &dir)
{
QDir curDir;
foreach (QString fileName, fileNames) {
QString filePath = QDir(dir).filePath(fileName);
QDir testDir = QFileInfo(filePath).dir();
if (!testDir.exists()) {
if (!curDir.mkpath(testDir.path())) {
qWarning("Couldn't mkpath %s",
testDir.path().toUtf8().constData());
return false;
}
}
if (fileName.endsWith('/')) {
if (!curDir.mkpath(filePath)) {
qWarning("Couldn't mkpath %s", fileName);
return false;
}
} else {
QFile testFile(filePath);
if (!testFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning("Couldn't create %s",
fileName.toUtf8().constData());
return false;
}
QTextStream testStream(&testFile);
testStream << "This is a test file named " << fileName << endl;
}
}
return true;
}
bool createTestArchive(const QString &zipName,
const QStringList &fileNames,
const QString &dir) {
QuaZip zip(zipName);
if (!zip.open(QuaZip::mdCreate)) {
qWarning("Couldn't open %s", zipName.toUtf8().constData());
return false;
}
foreach (QString fileName, fileNames) {
QuaZipFile zipFile(&zip);
QString filePath = QDir(dir).filePath(fileName);
QFileInfo fileInfo(filePath);
if (!zipFile.open(QIODevice::WriteOnly,
QuaZipNewInfo(fileName, filePath), NULL, 0,
fileInfo.isDir() ? 0 : 8)) {
qWarning("Couldn't open %s in %s", fileName.toUtf8()
.constData(), zipName.toUtf8().constData());
return false;
}
if (!fileInfo.isDir()) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning("Couldn't open %s", filePath.toUtf8()
.constData());
return false;
}
while (!file.atEnd()) {
char buf[4096];
qint64 l = file.read(buf, 4096);
if (l <= 0) {
qWarning("Couldn't read %s", filePath.toUtf8()
.constData());
return false;
}
if (zipFile.write(buf, l) != l) {
qWarning("Couldn't write to %s in %s",
filePath.toUtf8().constData(),
zipName.toUtf8().constData());
return false;
}
}
file.close();
}
zipFile.close();
}
zip.close();
return true;
}
void removeTestFiles(const QStringList &fileNames, const QString &dir)
{
QDir curDir;
foreach (QString fileName, fileNames) {
curDir.remove(QDir(dir).filePath(fileName));
}
foreach (QString fileName, fileNames) {
QDir fileDir = QFileInfo(QDir(dir).filePath(fileName)).dir();
if (fileDir.exists()) {
// Non-empty dirs won't get removed, and that's good.
curDir.rmpath(fileDir.path());
}
}
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int err = 0;
TestQuaZip testQuaZip;
err = qMax(err, QTest::qExec(&testQuaZip, app.arguments()));
TestQuaZipFile testQuaZipFile;
err = qMax(err, QTest::qExec(&testQuaZipFile, app.arguments()));
TestQuaChecksum32 testQuaChecksum32;
err = qMax(err, QTest::qExec(&testQuaChecksum32, app.arguments()));
TestJlCompress testJlCompress;
err = qMax(err, QTest::qExec(&testJlCompress, app.arguments()));
return err;
}
<commit_msg>Fix passing QString to a printf-style function<commit_after>#include "qztest.h"
#include "testquazip.h"
#include "testquazipfile.h"
#include "testquachecksum32.h"
#include "testjlcompress.h"
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QTextStream>
#include <QtTest/QtTest>
bool createTestFiles(const QStringList &fileNames, const QString &dir)
{
QDir curDir;
foreach (QString fileName, fileNames) {
QString filePath = QDir(dir).filePath(fileName);
QDir testDir = QFileInfo(filePath).dir();
if (!testDir.exists()) {
if (!curDir.mkpath(testDir.path())) {
qWarning("Couldn't mkpath %s",
testDir.path().toUtf8().constData());
return false;
}
}
if (fileName.endsWith('/')) {
if (!curDir.mkpath(filePath)) {
qWarning("Couldn't mkpath %s",
fileName.toUtf8().constData());
return false;
}
} else {
QFile testFile(filePath);
if (!testFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning("Couldn't create %s",
fileName.toUtf8().constData());
return false;
}
QTextStream testStream(&testFile);
testStream << "This is a test file named " << fileName << endl;
}
}
return true;
}
bool createTestArchive(const QString &zipName,
const QStringList &fileNames,
const QString &dir) {
QuaZip zip(zipName);
if (!zip.open(QuaZip::mdCreate)) {
qWarning("Couldn't open %s", zipName.toUtf8().constData());
return false;
}
foreach (QString fileName, fileNames) {
QuaZipFile zipFile(&zip);
QString filePath = QDir(dir).filePath(fileName);
QFileInfo fileInfo(filePath);
if (!zipFile.open(QIODevice::WriteOnly,
QuaZipNewInfo(fileName, filePath), NULL, 0,
fileInfo.isDir() ? 0 : 8)) {
qWarning("Couldn't open %s in %s", fileName.toUtf8()
.constData(), zipName.toUtf8().constData());
return false;
}
if (!fileInfo.isDir()) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning("Couldn't open %s", filePath.toUtf8()
.constData());
return false;
}
while (!file.atEnd()) {
char buf[4096];
qint64 l = file.read(buf, 4096);
if (l <= 0) {
qWarning("Couldn't read %s", filePath.toUtf8()
.constData());
return false;
}
if (zipFile.write(buf, l) != l) {
qWarning("Couldn't write to %s in %s",
filePath.toUtf8().constData(),
zipName.toUtf8().constData());
return false;
}
}
file.close();
}
zipFile.close();
}
zip.close();
return true;
}
void removeTestFiles(const QStringList &fileNames, const QString &dir)
{
QDir curDir;
foreach (QString fileName, fileNames) {
curDir.remove(QDir(dir).filePath(fileName));
}
foreach (QString fileName, fileNames) {
QDir fileDir = QFileInfo(QDir(dir).filePath(fileName)).dir();
if (fileDir.exists()) {
// Non-empty dirs won't get removed, and that's good.
curDir.rmpath(fileDir.path());
}
}
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int err = 0;
TestQuaZip testQuaZip;
err = qMax(err, QTest::qExec(&testQuaZip, app.arguments()));
TestQuaZipFile testQuaZipFile;
err = qMax(err, QTest::qExec(&testQuaZipFile, app.arguments()));
TestQuaChecksum32 testQuaChecksum32;
err = qMax(err, QTest::qExec(&testQuaChecksum32, app.arguments()));
TestJlCompress testJlCompress;
err = qMax(err, QTest::qExec(&testJlCompress, app.arguments()));
return err;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_SEARCH_TEST_HELPERS_HPP
#define DTK_SEARCH_TEST_HELPERS_HPP
#include <DTK_DistributedSearchTree.hpp>
#include <DTK_LinearBVH.hpp>
#include <Kokkos_View.hpp>
#include <Teuchos_FancyOStream.hpp>
#include <Teuchos_LocalTestingHelpers.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/range/combine.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <vector>
// The `out` and `success` parameters come from the Teuchos unit testing macros
// expansion.
template <typename Query, typename DeviceType>
void checkResults( DataTransferKit::BVH<DeviceType> const &bvh,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref,
std::vector<int> const &offset_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
bvh.query( queries, indices, offset );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
}
// Same as above except that we get the distances out of the queries and
// compare them to the reference solution passed as argument. Templated type
// `Query` is pretty much a nearest predicate in this case.
template <typename Query, typename DeviceType>
void checkResults( DataTransferKit::BVH<DeviceType> const &bvh,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref,
std::vector<int> const &offset_ref,
std::vector<double> const &distances_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<double *, DeviceType> distances( "distances" );
bvh.query( queries, indices, offset, distances );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto distances_host = Kokkos::create_mirror_view( distances );
deep_copy( distances_host, distances );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
TEST_COMPARE_FLOATING_ARRAYS( distances_host, distances_ref, 1e-14 );
}
// The `out` and `success` parameters come from the Teuchos unit testing macros
// expansion.
template <typename Query, typename DeviceType>
void checkResults(
DataTransferKit::DistributedSearchTree<DeviceType> const &tree,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref, std::vector<int> const &offset_ref,
std::vector<int> const &ranks_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
tree.query( queries, indices, offset, ranks );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto ranks_host = Kokkos::create_mirror_view( ranks );
deep_copy( ranks_host, ranks );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
auto const m = offset_host.extent_int( 0 ) - 1;
for ( int i = 0; i < m; ++i )
{
std::vector<std::tuple<int, int>> l;
std::vector<std::tuple<int, int>> r;
for ( int j = offset_ref[i]; j < offset_ref[i + 1]; ++j )
{
l.push_back( std::make_tuple( ranks_host[j], indices_host[j] ) );
r.push_back( std::make_tuple( ranks_ref[j], indices_ref[j] ) );
}
sort( l.begin(), l.end() );
sort( r.begin(), r.end() );
TEST_EQUALITY( l.size(), r.size() );
int const n = l.size();
TEST_EQUALITY( n, offset_ref[i + 1] - offset_ref[i] );
for ( int j = 0; j < n; ++j )
TEST_ASSERT( l[j] == r[j] );
}
}
template <typename Query, typename DeviceType>
void checkResults(
DataTransferKit::DistributedSearchTree<DeviceType> const &tree,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref, std::vector<int> const &offset_ref,
std::vector<int> const &ranks_ref, std::vector<double> const &distances_ref,
bool &success, Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
Kokkos::View<double *, DeviceType> distances( "distances" );
tree.query( queries, indices, offset, ranks, distances );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto ranks_host = Kokkos::create_mirror_view( ranks );
deep_copy( ranks_host, ranks );
auto distances_host = Kokkos::create_mirror_view( distances );
deep_copy( distances_host, distances );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
TEST_COMPARE_ARRAYS( ranks_host, ranks_ref );
TEST_COMPARE_FLOATING_ARRAYS( distances_host, distances_ref, 1e-14 );
}
template <typename DeviceType>
DataTransferKit::BVH<DeviceType>
makeBvh( std::vector<DataTransferKit::Box> const &b )
{
int const n = b.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> boxes( "boxes", n );
auto boxes_host = Kokkos::create_mirror_view( boxes );
for ( int i = 0; i < n; ++i )
boxes_host( i ) = b[i];
Kokkos::deep_copy( boxes, boxes_host );
return DataTransferKit::BVH<DeviceType>( boxes );
}
template <typename DeviceType>
DataTransferKit::DistributedSearchTree<DeviceType>
makeDistributedSearchTree( MPI_Comm comm,
std::vector<DataTransferKit::Box> const &b )
{
int const n = b.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> boxes( "boxes", n );
auto boxes_host = Kokkos::create_mirror_view( boxes );
for ( int i = 0; i < n; ++i )
boxes_host( i ) = b[i];
Kokkos::deep_copy( boxes, boxes_host );
return DataTransferKit::DistributedSearchTree<DeviceType>( comm, boxes );
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Overlap *, DeviceType>
makeOverlapQueries( std::vector<DataTransferKit::Box> const &boxes )
{
int const n = boxes.size();
Kokkos::View<DataTransferKit::Overlap *, DeviceType> queries(
"overlap_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) = DataTransferKit::overlap( boxes[i] );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
makeNearestQueries(
std::vector<std::pair<DataTransferKit::Point, int>> const &points )
{
// NOTE: `points` is not a very descriptive name here. It stores both the
// actual point and the number k of neighbors to query for.
int const n = points.size();
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
queries( "nearest_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) =
DataTransferKit::nearest( points[i].first, points[i].second );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Within *, DeviceType> makeWithinQueries(
std::vector<std::pair<DataTransferKit::Point, double>> const &points )
{
// NOTE: `points` is not a very descriptive name here. It stores both the
// actual point and the radius for the search around that point.
int const n = points.size();
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
"within_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) =
DataTransferKit::within( points[i].first, points[i].second );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename View, typename Value = typename View::value_type>
std::vector<Value> extractAndSort( View const &v, int begin, int end )
{
std::vector<Value> r( v.data() + begin, v.data() + end );
std::sort( r.begin(), r.end() );
return r;
}
template <typename InputView1, typename InputView2>
void validateResults( std::tuple<InputView1, InputView1> const &reference,
std::tuple<InputView2, InputView2> const &other,
bool &success, Teuchos::FancyOStream &out )
{
TEST_COMPARE_ARRAYS( std::get<0>( reference ), std::get<0>( other ) );
auto const offset = std::get<0>( reference );
auto const n_queries = offset.extent_int( 0 ) - 1;
for ( int i = 0; i < n_queries; ++i )
{
std::vector<int> l;
std::vector<int> r;
boost::copy(
Kokkos::subview( std::get<1>( reference ),
std::make_pair( offset( i ), offset( i + 1 ) ) ),
std::back_inserter( l ) );
boost::copy(
Kokkos::subview( std::get<1>( other ),
std::make_pair( offset( i ), offset( i + 1 ) ) ),
std::back_inserter( r ) );
boost::range::sort( l );
boost::range::sort( r );
TEST_COMPARE_ARRAYS( l, r );
TEST_COMPARE_ARRAYS( extractAndSort( std::get<1>( reference ),
offset( i ), offset( i + 1 ) ),
extractAndSort( std::get<1>( other ), offset( i ),
offset( i + 1 ) ) );
}
}
template <typename InputView1, typename InputView2>
void validateResults(
std::tuple<InputView1, InputView1, InputView1> const &reference,
std::tuple<InputView2, InputView2, InputView2> const &other, bool &success,
Teuchos::FancyOStream &out )
{
TEST_COMPARE_ARRAYS( std::get<0>( reference ), std::get<0>( other ) );
auto const offset = std::get<0>( reference );
auto const m = offset.extent_int( 0 ) - 1;
for ( int i = 0; i < m; ++i )
{
std::vector<std::tuple<int, int>> l;
std::vector<std::tuple<int, int>> r;
for ( int j = offset[i]; j < offset[i + 1]; ++j )
{
l.emplace_back( std::get<1>( other )[j], std::get<2>( other )[j] );
r.emplace_back( std::get<1>( reference )[j],
std::get<2>( reference )[j] );
}
std::sort( l.begin(), l.end() );
std::sort( r.begin(), r.end() );
// somehow can't use TEST_COMPARE_ARRAY() so doing it myself
TEST_EQUALITY( l.size(), r.size() );
int const n = l.size();
TEST_EQUALITY( n, offset( i + 1 ) - offset( i ) );
for ( int j = 0; j < n; ++j )
TEST_ASSERT( l[j] == r[j] );
}
}
#endif
<commit_msg>Get rid of boost dependency of Search package unit tests helper function validateResults()<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_SEARCH_TEST_HELPERS_HPP
#define DTK_SEARCH_TEST_HELPERS_HPP
#include <DTK_DistributedSearchTree.hpp>
#include <DTK_LinearBVH.hpp>
#include <Kokkos_View.hpp>
#include <Teuchos_FancyOStream.hpp>
#include <Teuchos_LocalTestingHelpers.hpp>
#include <tuple>
#include <vector>
// The `out` and `success` parameters come from the Teuchos unit testing macros
// expansion.
template <typename Query, typename DeviceType>
void checkResults( DataTransferKit::BVH<DeviceType> const &bvh,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref,
std::vector<int> const &offset_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
bvh.query( queries, indices, offset );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
}
// Same as above except that we get the distances out of the queries and
// compare them to the reference solution passed as argument. Templated type
// `Query` is pretty much a nearest predicate in this case.
template <typename Query, typename DeviceType>
void checkResults( DataTransferKit::BVH<DeviceType> const &bvh,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref,
std::vector<int> const &offset_ref,
std::vector<double> const &distances_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<double *, DeviceType> distances( "distances" );
bvh.query( queries, indices, offset, distances );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto distances_host = Kokkos::create_mirror_view( distances );
deep_copy( distances_host, distances );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
TEST_COMPARE_FLOATING_ARRAYS( distances_host, distances_ref, 1e-14 );
}
// The `out` and `success` parameters come from the Teuchos unit testing macros
// expansion.
template <typename Query, typename DeviceType>
void checkResults(
DataTransferKit::DistributedSearchTree<DeviceType> const &tree,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref, std::vector<int> const &offset_ref,
std::vector<int> const &ranks_ref, bool &success,
Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
tree.query( queries, indices, offset, ranks );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto ranks_host = Kokkos::create_mirror_view( ranks );
deep_copy( ranks_host, ranks );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
auto const m = offset_host.extent_int( 0 ) - 1;
for ( int i = 0; i < m; ++i )
{
std::vector<std::tuple<int, int>> l;
std::vector<std::tuple<int, int>> r;
for ( int j = offset_ref[i]; j < offset_ref[i + 1]; ++j )
{
l.push_back( std::make_tuple( ranks_host[j], indices_host[j] ) );
r.push_back( std::make_tuple( ranks_ref[j], indices_ref[j] ) );
}
sort( l.begin(), l.end() );
sort( r.begin(), r.end() );
TEST_EQUALITY( l.size(), r.size() );
int const n = l.size();
TEST_EQUALITY( n, offset_ref[i + 1] - offset_ref[i] );
for ( int j = 0; j < n; ++j )
TEST_ASSERT( l[j] == r[j] );
}
}
template <typename Query, typename DeviceType>
void checkResults(
DataTransferKit::DistributedSearchTree<DeviceType> const &tree,
Kokkos::View<Query *, DeviceType> const &queries,
std::vector<int> const &indices_ref, std::vector<int> const &offset_ref,
std::vector<int> const &ranks_ref, std::vector<double> const &distances_ref,
bool &success, Teuchos::FancyOStream &out )
{
Kokkos::View<int *, DeviceType> indices( "indices" );
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> ranks( "ranks" );
Kokkos::View<double *, DeviceType> distances( "distances" );
tree.query( queries, indices, offset, ranks, distances );
auto indices_host = Kokkos::create_mirror_view( indices );
deep_copy( indices_host, indices );
auto offset_host = Kokkos::create_mirror_view( offset );
deep_copy( offset_host, offset );
auto ranks_host = Kokkos::create_mirror_view( ranks );
deep_copy( ranks_host, ranks );
auto distances_host = Kokkos::create_mirror_view( distances );
deep_copy( distances_host, distances );
TEST_COMPARE_ARRAYS( indices_host, indices_ref );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
TEST_COMPARE_ARRAYS( ranks_host, ranks_ref );
TEST_COMPARE_FLOATING_ARRAYS( distances_host, distances_ref, 1e-14 );
}
template <typename DeviceType>
DataTransferKit::BVH<DeviceType>
makeBvh( std::vector<DataTransferKit::Box> const &b )
{
int const n = b.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> boxes( "boxes", n );
auto boxes_host = Kokkos::create_mirror_view( boxes );
for ( int i = 0; i < n; ++i )
boxes_host( i ) = b[i];
Kokkos::deep_copy( boxes, boxes_host );
return DataTransferKit::BVH<DeviceType>( boxes );
}
template <typename DeviceType>
DataTransferKit::DistributedSearchTree<DeviceType>
makeDistributedSearchTree( MPI_Comm comm,
std::vector<DataTransferKit::Box> const &b )
{
int const n = b.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> boxes( "boxes", n );
auto boxes_host = Kokkos::create_mirror_view( boxes );
for ( int i = 0; i < n; ++i )
boxes_host( i ) = b[i];
Kokkos::deep_copy( boxes, boxes_host );
return DataTransferKit::DistributedSearchTree<DeviceType>( comm, boxes );
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Overlap *, DeviceType>
makeOverlapQueries( std::vector<DataTransferKit::Box> const &boxes )
{
int const n = boxes.size();
Kokkos::View<DataTransferKit::Overlap *, DeviceType> queries(
"overlap_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) = DataTransferKit::overlap( boxes[i] );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
makeNearestQueries(
std::vector<std::pair<DataTransferKit::Point, int>> const &points )
{
// NOTE: `points` is not a very descriptive name here. It stores both the
// actual point and the number k of neighbors to query for.
int const n = points.size();
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *, DeviceType>
queries( "nearest_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) =
DataTransferKit::nearest( points[i].first, points[i].second );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename DeviceType>
Kokkos::View<DataTransferKit::Within *, DeviceType> makeWithinQueries(
std::vector<std::pair<DataTransferKit::Point, double>> const &points )
{
// NOTE: `points` is not a very descriptive name here. It stores both the
// actual point and the radius for the search around that point.
int const n = points.size();
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
"within_queries", n );
auto queries_host = Kokkos::create_mirror_view( queries );
for ( int i = 0; i < n; ++i )
queries_host( i ) =
DataTransferKit::within( points[i].first, points[i].second );
Kokkos::deep_copy( queries, queries_host );
return queries;
}
template <typename InputView1, typename InputView2>
void validateResults( std::tuple<InputView1, InputView1> const &reference,
std::tuple<InputView2, InputView2> const &other,
bool &success, Teuchos::FancyOStream &out )
{
TEST_COMPARE_ARRAYS( std::get<0>( reference ), std::get<0>( other ) );
auto const offset = std::get<0>( reference );
auto const m = offset.extent_int( 0 ) - 1;
for ( int i = 0; i < m; ++i )
{
std::vector<int> l;
std::vector<int> r;
for ( int j = offset[i]; j < offset[i + 1]; ++j )
{
l.push_back( std::get<1>( other )[j] );
r.push_back( std::get<1>( reference )[j] );
}
std::sort( l.begin(), l.end() );
std::sort( r.begin(), r.end() );
TEST_EQUALITY( l.size(), r.size() );
int const n = l.size();
TEST_EQUALITY( n, offset[i + 1] - offset[i] );
for ( int j = 0; j < n; ++j )
TEST_ASSERT( l[j] == r[j] );
}
}
template <typename InputView1, typename InputView2>
void validateResults(
std::tuple<InputView1, InputView1, InputView1> const &reference,
std::tuple<InputView2, InputView2, InputView2> const &other, bool &success,
Teuchos::FancyOStream &out )
{
TEST_COMPARE_ARRAYS( std::get<0>( reference ), std::get<0>( other ) );
auto const offset = std::get<0>( reference );
auto const m = offset.extent_int( 0 ) - 1;
for ( int i = 0; i < m; ++i )
{
std::vector<std::tuple<int, int>> l;
std::vector<std::tuple<int, int>> r;
for ( int j = offset[i]; j < offset[i + 1]; ++j )
{
l.emplace_back( std::get<1>( other )[j], std::get<2>( other )[j] );
r.emplace_back( std::get<1>( reference )[j],
std::get<2>( reference )[j] );
}
std::sort( l.begin(), l.end() );
std::sort( r.begin(), r.end() );
// somehow can't use TEST_COMPARE_ARRAY() so doing it myself
TEST_EQUALITY( l.size(), r.size() );
int const n = l.size();
TEST_EQUALITY( n, offset( i + 1 ) - offset( i ) );
for ( int j = 0; j < n; ++j )
TEST_ASSERT( l[j] == r[j] );
}
}
#endif
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#define __STDC_FORMAT_MACROS
#include "authz_curl.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <pthread.h>
#include <cassert>
#include "authz/authz_session.h"
#include "duplex_curl.h"
#include "duplex_ssl.h"
#include "logging.h"
#include "util/pointer.h"
#include "util_concurrency.h"
using namespace std; // NOLINT
namespace {
struct sslctx_info {
sslctx_info() : chain(NULL), pkey(NULL) {}
STACK_OF(X509) *chain;
EVP_PKEY *pkey;
};
struct bearer_info {
/**
* List of extra headers to put on the HTTP request. This is required
* in order to add the "Authorization: Bearer XXXXX" header.
*/
struct curl_slist *list;
/**
* Actual text of the bearer token
*/
char* token;
};
} // anonymous namespace
bool AuthzAttachment::ssl_strings_loaded_ = false;
AuthzAttachment::AuthzAttachment(AuthzSessionManager *sm)
: authz_session_manager_(sm)
{
// Required for logging OpenSSL errors
SSL_load_error_strings();
ssl_strings_loaded_ = true;
}
CURLcode AuthzAttachment::CallbackSslCtx(
CURL *curl,
void *sslctx,
void *parm)
{
sslctx_info *p = reinterpret_cast<sslctx_info *>(parm);
SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(sslctx);
if (parm == NULL)
return CURLE_OK;
STACK_OF(X509) *chain = p->chain;
EVP_PKEY *pkey = p->pkey;
LogCvmfs(kLogAuthz, kLogDebug, "Customizing OpenSSL context.");
int cert_count = sk_X509_num(chain);
if (cert_count == 0) {
LogOpenSSLErrors("No certificate found in chain.");
}
X509 *cert = sk_X509_value(chain, 0);
// NOTE: SSL_CTX_use_certificate and _user_PrivateKey increase the ref count.
if (!SSL_CTX_use_certificate(ctx, cert)) {
LogOpenSSLErrors("Failed to set the user certificate in the SSL "
"connection");
return CURLE_SSL_CERTPROBLEM;
}
if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
LogOpenSSLErrors("Failed to set the private key in the SSL connection");
return CURLE_SSL_CERTPROBLEM;
}
if (!SSL_CTX_check_private_key(ctx)) {
LogOpenSSLErrors("Provided certificate and key do not match");
return CURLE_SSL_CERTPROBLEM;
} else {
LogCvmfs(kLogAuthz, kLogDebug, "Client certificate and key match.");
}
// NOTE: SSL_CTX_add_extra_chain_cert DOES NOT increase the ref count
// Instead, it now owns the pointer. THIS IS DIFFERENT FROM ABOVE.
for (int idx = 1; idx < cert_count; idx++) {
cert = sk_X509_value(chain, idx);
if (!SSL_CTX_add_extra_chain_cert(ctx, X509_dup(cert))) {
LogOpenSSLErrors("Failed to add client cert to chain");
}
}
return CURLE_OK;
}
bool AuthzAttachment::ConfigureSciTokenCurl(
CURL *curl_handle,
const AuthzToken &token,
void **info_data)
{
if (*info_data == NULL) {
AuthzToken* saved_token = new AuthzToken();
saved_token->type = kTokenBearer;
saved_token->data = new bearer_info;
bearer_info* bearer = static_cast<bearer_info*>(saved_token->data);
bearer->list = NULL;
bearer->token = static_cast<char*>(smalloc((sizeof(char) * token.size)+ 1));
memcpy(bearer->token, token.data, token.size);
static_cast<char*>(bearer->token)[token.size] = 0;
*info_data = saved_token;
}
AuthzToken* tmp_token = static_cast<AuthzToken*>(*info_data);
bearer_info* bearer = static_cast<bearer_info*>(tmp_token->data);
LogCvmfs(kLogAuthz, kLogDebug, "Setting OAUTH bearer token to: %s",
static_cast<char*>(bearer->token));
// Create the Bearer token
// The CURLOPT_XOAUTH2_BEARER option only works "IMAP, POP3 and SMTP"
// protocols. Not HTTPS
std::string auth_preamble = "Authorization: Bearer ";
std::string auth_header = auth_preamble + static_cast<char*>(bearer->token);
bearer->list = curl_slist_append(bearer->list, auth_header.c_str());
int retval = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, bearer->list);
if (retval != CURLE_OK) {
LogCvmfs(kLogAuthz, kLogSyslogErr, "Failed to set Oauth2 Bearer Token");
return false;
}
return true;
}
bool AuthzAttachment::ConfigureCurlHandle(
CURL *curl_handle,
pid_t pid,
void **info_data)
{
assert(info_data);
// We cannot rely on libcurl to pipeline (yet), as cvmfs may
// bounce between different auth handles.
curl_easy_setopt(curl_handle, CURLOPT_FRESH_CONNECT, 1);
curl_easy_setopt(curl_handle, CURLOPT_FORBID_REUSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_SSL_SESSIONID_CACHE, 0);
UniquePtr<AuthzToken> token(
authz_session_manager_->GetTokenCopy(pid, membership_));
if (!token.IsValid()) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get authz token for pid %d", pid);
return false;
}
switch (token->type) {
case kTokenBearer:
// If it's a scitoken, then just go to the private
// ConfigureSciTokenCurl function
return ConfigureSciTokenCurl(curl_handle, *token, info_data);
case kTokenX509:
// The x509 code is below, so just break and go.
break;
default:
// Oh no, don't know the the token type, throw error and return
LogCvmfs(kLogAuthz, kLogDebug, "unknown token type: %d", token->type);
return false;
}
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, NULL);
// The calling layer is reusing data;
if (*info_data) {
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA,
static_cast<AuthzToken*>(*info_data)->data);
return true;
}
int retval = curl_easy_setopt(curl_handle,
CURLOPT_SSL_CTX_FUNCTION,
CallbackSslCtx);
if (retval != CURLE_OK) {
LogCvmfs(kLogAuthz, kLogDebug, "cannot configure curl ssl callback");
return false;
}
UniquePtr<sslctx_info> parm(new sslctx_info);
STACK_OF(X509_INFO) *sk = NULL;
STACK_OF(X509) *certstack = sk_X509_new_null();
parm->chain = certstack;
if (certstack == NULL) {
LogCvmfs(kLogAuthz, kLogSyslogErr, "Failed to allocate new X509 chain.");
return false;
}
BIO *bio_token = BIO_new_mem_buf(token->data, token->size);
assert(bio_token != NULL);
sk = PEM_X509_INFO_read_bio(bio_token, NULL, NULL, NULL);
BIO_free(bio_token);
if (!sk) {
LogOpenSSLErrors("Failed to load credential file.");
sk_X509_INFO_free(sk);
sk_X509_free(certstack);
return false;
}
while (sk_X509_INFO_num(sk)) {
X509_INFO *xi = sk_X509_INFO_shift(sk);
if (xi == NULL) {continue;}
if (xi->x509 != NULL) {
#ifdef OPENSSL_API_INTERFACE_V11
retval = X509_up_ref(xi->x509);
assert(retval == 1);
#else
CRYPTO_add(&xi->x509->references, 1, CRYPTO_LOCK_X509);
#endif
sk_X509_push(certstack, xi->x509);
}
if ((xi->x_pkey != NULL) && (xi->x_pkey->dec_pkey != NULL)) {
parm->pkey = xi->x_pkey->dec_pkey;
#ifdef OPENSSL_API_INTERFACE_V11
retval = EVP_PKEY_up_ref(parm->pkey);
assert(retval == 1);
#else
CRYPTO_add(&parm->pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
#endif
}
X509_INFO_free(xi);
}
sk_X509_INFO_free(sk);
if (parm->pkey == NULL) {
// Sigh - PEM_X509_INFO_read doesn't understand old key encodings.
// Try a more general-purpose funciton.
BIO *bio_token = BIO_new_mem_buf(token->data, token->size);
assert(bio_token != NULL);
EVP_PKEY *old_pkey = PEM_read_bio_PrivateKey(bio_token, NULL, NULL, NULL);
BIO_free(bio_token);
if (old_pkey) {
parm->pkey = old_pkey;
} else {
sk_X509_free(certstack);
LogCvmfs(kLogAuthz, kLogSyslogErr,
"credential did not contain a decrypted private key.");
return false;
}
}
if (!sk_X509_num(certstack)) {
EVP_PKEY_free(parm->pkey);
sk_X509_free(certstack);
LogCvmfs(kLogAuthz, kLogSyslogErr,
"Credential file did not contain any actual credentials.");
return false;
} else {
LogCvmfs(kLogAuthz, kLogDebug, "Certificate stack contains %d entries.",
sk_X509_num(certstack));
}
AuthzToken* to_return = new AuthzToken();
to_return->type = kTokenX509;
to_return->data = static_cast<void*>(parm.Release());
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA,
static_cast<sslctx_info*>(to_return->data));
*info_data = to_return;
return true;
}
void AuthzAttachment::LogOpenSSLErrors(const char *top_message) {
assert(ssl_strings_loaded_);
char error_buf[1024];
LogCvmfs(kLogAuthz, kLogSyslogWarn, "%s", top_message);
unsigned long next_err; // NOLINT; this is the type expected by OpenSSL
while ((next_err = ERR_get_error())) {
ERR_error_string_n(next_err, error_buf, 1024);
LogCvmfs(kLogAuthz, kLogSyslogErr, "%s", error_buf);
}
}
void AuthzAttachment::ReleaseCurlHandle(CURL *curl_handle, void *info_data) {
assert(info_data);
AuthzToken* token = static_cast<AuthzToken*>(info_data);
if (token->type == kTokenBearer) {
// Compiler complains if we delete a void*
bearer_info* bearer = static_cast<bearer_info*>(token->data);
delete static_cast<char*>(bearer->token);
curl_slist_free_all(bearer->list);
delete static_cast<bearer_info*>(token->data);
token->data = NULL;
delete token;
} else if (token->type == kTokenX509) {
sslctx_info *p = static_cast<sslctx_info *>(info_data);
STACK_OF(X509) *chain = p->chain;
EVP_PKEY *pkey = p->pkey;
p->chain = NULL;
p->pkey = NULL;
delete p;
// Calls X509_free on each element, then frees the stack itself
sk_X509_pop_free(chain, X509_free);
EVP_PKEY_free(pkey);
// Make sure that if CVMFS reuses this curl handle, curl doesn't try
// to reuse cert chain we just freed.
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, 0);
}
}
<commit_msg>Fix incorrect casting.<commit_after>/**
* This file is part of the CernVM File System.
*/
#define __STDC_FORMAT_MACROS
#include "authz_curl.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <pthread.h>
#include <cassert>
#include "authz/authz_session.h"
#include "duplex_curl.h"
#include "duplex_ssl.h"
#include "logging.h"
#include "util/pointer.h"
#include "util_concurrency.h"
using namespace std; // NOLINT
namespace {
struct sslctx_info {
sslctx_info() : chain(NULL), pkey(NULL) {}
STACK_OF(X509) *chain;
EVP_PKEY *pkey;
};
struct bearer_info {
/**
* List of extra headers to put on the HTTP request. This is required
* in order to add the "Authorization: Bearer XXXXX" header.
*/
struct curl_slist *list;
/**
* Actual text of the bearer token
*/
char* token;
};
} // anonymous namespace
bool AuthzAttachment::ssl_strings_loaded_ = false;
AuthzAttachment::AuthzAttachment(AuthzSessionManager *sm)
: authz_session_manager_(sm)
{
// Required for logging OpenSSL errors
SSL_load_error_strings();
ssl_strings_loaded_ = true;
}
CURLcode AuthzAttachment::CallbackSslCtx(
CURL *curl,
void *sslctx,
void *parm)
{
sslctx_info *p = reinterpret_cast<sslctx_info *>(parm);
SSL_CTX *ctx = reinterpret_cast<SSL_CTX *>(sslctx);
if (parm == NULL)
return CURLE_OK;
STACK_OF(X509) *chain = p->chain;
EVP_PKEY *pkey = p->pkey;
LogCvmfs(kLogAuthz, kLogDebug, "Customizing OpenSSL context.");
int cert_count = sk_X509_num(chain);
if (cert_count == 0) {
LogOpenSSLErrors("No certificate found in chain.");
}
X509 *cert = sk_X509_value(chain, 0);
// NOTE: SSL_CTX_use_certificate and _user_PrivateKey increase the ref count.
if (!SSL_CTX_use_certificate(ctx, cert)) {
LogOpenSSLErrors("Failed to set the user certificate in the SSL "
"connection");
return CURLE_SSL_CERTPROBLEM;
}
if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
LogOpenSSLErrors("Failed to set the private key in the SSL connection");
return CURLE_SSL_CERTPROBLEM;
}
if (!SSL_CTX_check_private_key(ctx)) {
LogOpenSSLErrors("Provided certificate and key do not match");
return CURLE_SSL_CERTPROBLEM;
} else {
LogCvmfs(kLogAuthz, kLogDebug, "Client certificate and key match.");
}
// NOTE: SSL_CTX_add_extra_chain_cert DOES NOT increase the ref count
// Instead, it now owns the pointer. THIS IS DIFFERENT FROM ABOVE.
for (int idx = 1; idx < cert_count; idx++) {
cert = sk_X509_value(chain, idx);
if (!SSL_CTX_add_extra_chain_cert(ctx, X509_dup(cert))) {
LogOpenSSLErrors("Failed to add client cert to chain");
}
}
return CURLE_OK;
}
bool AuthzAttachment::ConfigureSciTokenCurl(
CURL *curl_handle,
const AuthzToken &token,
void **info_data)
{
if (*info_data == NULL) {
AuthzToken* saved_token = new AuthzToken();
saved_token->type = kTokenBearer;
saved_token->data = new bearer_info;
bearer_info* bearer = static_cast<bearer_info*>(saved_token->data);
bearer->list = NULL;
bearer->token = static_cast<char*>(smalloc((sizeof(char) * token.size)+ 1));
memcpy(bearer->token, token.data, token.size);
static_cast<char*>(bearer->token)[token.size] = 0;
*info_data = saved_token;
}
AuthzToken* tmp_token = static_cast<AuthzToken*>(*info_data);
bearer_info* bearer = static_cast<bearer_info*>(tmp_token->data);
LogCvmfs(kLogAuthz, kLogDebug, "Setting OAUTH bearer token to: %s",
static_cast<char*>(bearer->token));
// Create the Bearer token
// The CURLOPT_XOAUTH2_BEARER option only works "IMAP, POP3 and SMTP"
// protocols. Not HTTPS
std::string auth_preamble = "Authorization: Bearer ";
std::string auth_header = auth_preamble + static_cast<char*>(bearer->token);
bearer->list = curl_slist_append(bearer->list, auth_header.c_str());
int retval = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, bearer->list);
if (retval != CURLE_OK) {
LogCvmfs(kLogAuthz, kLogSyslogErr, "Failed to set Oauth2 Bearer Token");
return false;
}
return true;
}
bool AuthzAttachment::ConfigureCurlHandle(
CURL *curl_handle,
pid_t pid,
void **info_data)
{
assert(info_data);
// We cannot rely on libcurl to pipeline (yet), as cvmfs may
// bounce between different auth handles.
curl_easy_setopt(curl_handle, CURLOPT_FRESH_CONNECT, 1);
curl_easy_setopt(curl_handle, CURLOPT_FORBID_REUSE, 1);
curl_easy_setopt(curl_handle, CURLOPT_SSL_SESSIONID_CACHE, 0);
UniquePtr<AuthzToken> token(
authz_session_manager_->GetTokenCopy(pid, membership_));
if (!token.IsValid()) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get authz token for pid %d", pid);
return false;
}
switch (token->type) {
case kTokenBearer:
// If it's a scitoken, then just go to the private
// ConfigureSciTokenCurl function
return ConfigureSciTokenCurl(curl_handle, *token, info_data);
case kTokenX509:
// The x509 code is below, so just break and go.
break;
default:
// Oh no, don't know the the token type, throw error and return
LogCvmfs(kLogAuthz, kLogDebug, "unknown token type: %d", token->type);
return false;
}
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, NULL);
// The calling layer is reusing data;
if (*info_data) {
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA,
static_cast<AuthzToken*>(*info_data)->data);
return true;
}
int retval = curl_easy_setopt(curl_handle,
CURLOPT_SSL_CTX_FUNCTION,
CallbackSslCtx);
if (retval != CURLE_OK) {
LogCvmfs(kLogAuthz, kLogDebug, "cannot configure curl ssl callback");
return false;
}
UniquePtr<sslctx_info> parm(new sslctx_info);
STACK_OF(X509_INFO) *sk = NULL;
STACK_OF(X509) *certstack = sk_X509_new_null();
parm->chain = certstack;
if (certstack == NULL) {
LogCvmfs(kLogAuthz, kLogSyslogErr, "Failed to allocate new X509 chain.");
return false;
}
BIO *bio_token = BIO_new_mem_buf(token->data, token->size);
assert(bio_token != NULL);
sk = PEM_X509_INFO_read_bio(bio_token, NULL, NULL, NULL);
BIO_free(bio_token);
if (!sk) {
LogOpenSSLErrors("Failed to load credential file.");
sk_X509_INFO_free(sk);
sk_X509_free(certstack);
return false;
}
while (sk_X509_INFO_num(sk)) {
X509_INFO *xi = sk_X509_INFO_shift(sk);
if (xi == NULL) {continue;}
if (xi->x509 != NULL) {
#ifdef OPENSSL_API_INTERFACE_V11
retval = X509_up_ref(xi->x509);
assert(retval == 1);
#else
CRYPTO_add(&xi->x509->references, 1, CRYPTO_LOCK_X509);
#endif
sk_X509_push(certstack, xi->x509);
}
if ((xi->x_pkey != NULL) && (xi->x_pkey->dec_pkey != NULL)) {
parm->pkey = xi->x_pkey->dec_pkey;
#ifdef OPENSSL_API_INTERFACE_V11
retval = EVP_PKEY_up_ref(parm->pkey);
assert(retval == 1);
#else
CRYPTO_add(&parm->pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
#endif
}
X509_INFO_free(xi);
}
sk_X509_INFO_free(sk);
if (parm->pkey == NULL) {
// Sigh - PEM_X509_INFO_read doesn't understand old key encodings.
// Try a more general-purpose funciton.
BIO *bio_token = BIO_new_mem_buf(token->data, token->size);
assert(bio_token != NULL);
EVP_PKEY *old_pkey = PEM_read_bio_PrivateKey(bio_token, NULL, NULL, NULL);
BIO_free(bio_token);
if (old_pkey) {
parm->pkey = old_pkey;
} else {
sk_X509_free(certstack);
LogCvmfs(kLogAuthz, kLogSyslogErr,
"credential did not contain a decrypted private key.");
return false;
}
}
if (!sk_X509_num(certstack)) {
EVP_PKEY_free(parm->pkey);
sk_X509_free(certstack);
LogCvmfs(kLogAuthz, kLogSyslogErr,
"Credential file did not contain any actual credentials.");
return false;
} else {
LogCvmfs(kLogAuthz, kLogDebug, "Certificate stack contains %d entries.",
sk_X509_num(certstack));
}
AuthzToken* to_return = new AuthzToken();
to_return->type = kTokenX509;
to_return->data = static_cast<void*>(parm.Release());
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA,
static_cast<sslctx_info*>(to_return->data));
*info_data = to_return;
return true;
}
void AuthzAttachment::LogOpenSSLErrors(const char *top_message) {
assert(ssl_strings_loaded_);
char error_buf[1024];
LogCvmfs(kLogAuthz, kLogSyslogWarn, "%s", top_message);
unsigned long next_err; // NOLINT; this is the type expected by OpenSSL
while ((next_err = ERR_get_error())) {
ERR_error_string_n(next_err, error_buf, 1024);
LogCvmfs(kLogAuthz, kLogSyslogErr, "%s", error_buf);
}
}
void AuthzAttachment::ReleaseCurlHandle(CURL *curl_handle, void *info_data) {
assert(info_data);
AuthzToken* token = static_cast<AuthzToken*>(info_data);
if (token->type == kTokenBearer) {
// Compiler complains if we delete a void*
bearer_info* bearer = static_cast<bearer_info*>(token->data);
delete static_cast<char*>(bearer->token);
curl_slist_free_all(bearer->list);
delete static_cast<bearer_info*>(token->data);
token->data = NULL;
delete token;
} else if (token->type == kTokenX509) {
sslctx_info *p = static_cast<sslctx_info *>(token->data);
STACK_OF(X509) *chain = p->chain;
EVP_PKEY *pkey = p->pkey;
p->chain = NULL;
p->pkey = NULL;
delete p;
// Calls X509_free on each element, then frees the stack itself
sk_X509_pop_free(chain, X509_free);
EVP_PKEY_free(pkey);
// Make sure that if CVMFS reuses this curl handle, curl doesn't try
// to reuse cert chain we just freed.
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, 0);
}
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "Importer.h"
#include "common/sg/SceneGraph.h"
#include <memory>
/*! \file sg/module/Importer.cpp Defines the interface for writing
file importers for the ospray::sg */
namespace ospray {
namespace sg {
bool readOne(FILE *file, float *f, int N, bool ascii)
{
if (!ascii)
return fread(f,sizeof(float),N,file) == N;
// ascii:
for (int i=0;i<N;i++) {
int rc = fscanf(file,"%f",f+i);
if (rc == 0) return (i == 0);
fscanf(file,"\n");
}
}
// for now, let's hardcode the importers - should be moved to a
// registry at some point ...
void importFileType_points(std::shared_ptr<World> &world,
const FileName &url)
{
std::cout << "--------------------------------------------" << std::endl;
std::cout << "#osp.sg: importer for 'points': " << url.str() << std::endl;
FormatURL fu(url.str());
PRINT(fu.fileName);
// const std::string portHeader = strstr(url.str().c_str(),"://")+3;
// const char *fileName = strstr(url.str().c_str(),"://")+3;
PRINT(fu.fileName);
FILE *file = fopen(fu.fileName.c_str(),"rb");
if (!file)
throw std::runtime_error("could not open file "+fu.fileName);
// read the data vector
PING;
std::shared_ptr<DataVectorT<Spheres::Sphere,OSP_RAW>> data
= std::make_shared<DataVectorT<Spheres::Sphere,OSP_RAW>>();
float radius = .1f;
if (fu.hasArg("radius"))
radius = std::stof(fu["radius"]);
if (radius == 0.f)
throw std::runtime_error("#sg.importPoints: could not parse radius ...");
std::string format = "xyz";
if (fu.hasArg("format"))
format = fu["format"];
bool ascii = fu.hasArg("ascii");
/* for now, hard-coded sphere componetns to be in float format,
so the number of chars in the format string is the num components */
int numFloatsPerSphere = format.size();
size_t xPos = format.find("x");
size_t yPos = format.find("y");
size_t zPos = format.find("z");
size_t rPos = format.find("r");
size_t sPos = format.find("s");
if (xPos == std::string::npos)
throw std::runtime_error("invalid points format: no x component");
if (yPos == std::string::npos)
throw std::runtime_error("invalid points format: no y component");
if (zPos == std::string::npos)
throw std::runtime_error("invalid points format: no z component");
float f[numFloatsPerSphere];
while (readOne(file,f,numFloatsPerSphere,ascii)) {
// read one more sphere ....
Spheres::Sphere s;
s.position.x = f[xPos];
s.position.y = f[yPos];
s.position.z = f[zPos];
s.radius
= (rPos == std::string::npos)
? radius
: f[rPos];
data->v.push_back(s);
}
fclose(file);
// create the node
NodeHandle spheres = createNode("spheres","Spheres");
// iw - note that 'add' sounds wrong here, but that's the way
// the current scene graph works - 'adding' that node (which
// happens to have the right name) will essentially replace the
// old value of that node, and thereby assign the 'data' field
data->setName("data");
spheres->add(data); //["data"]->setValue(data);
NodeHandle(world) += spheres;
}
}// ::ospray::sg
}// ::ospray
<commit_msg>bugfix - missing return value<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "Importer.h"
#include "common/sg/SceneGraph.h"
#include <memory>
/*! \file sg/module/Importer.cpp Defines the interface for writing
file importers for the ospray::sg */
namespace ospray {
namespace sg {
bool readOne(FILE *file, float *f, int N, bool ascii)
{
if (!ascii)
return fread(f,sizeof(float),N,file) == N;
// ascii:
for (int i=0;i<N;i++) {
int rc = fscanf(file,"%f",f+i);
if (rc == 0) return (i == 0);
fscanf(file,"\n");
}
return true;
}
// for now, let's hardcode the importers - should be moved to a
// registry at some point ...
void importFileType_points(std::shared_ptr<World> &world,
const FileName &url)
{
std::cout << "--------------------------------------------" << std::endl;
std::cout << "#osp.sg: importer for 'points': " << url.str() << std::endl;
FormatURL fu(url.str());
PRINT(fu.fileName);
// const std::string portHeader = strstr(url.str().c_str(),"://")+3;
// const char *fileName = strstr(url.str().c_str(),"://")+3;
PRINT(fu.fileName);
FILE *file = fopen(fu.fileName.c_str(),"rb");
if (!file)
throw std::runtime_error("could not open file "+fu.fileName);
// read the data vector
PING;
std::shared_ptr<DataVectorT<Spheres::Sphere,OSP_RAW>> data
= std::make_shared<DataVectorT<Spheres::Sphere,OSP_RAW>>();
float radius = .1f;
if (fu.hasArg("radius"))
radius = std::stof(fu["radius"]);
if (radius == 0.f)
throw std::runtime_error("#sg.importPoints: could not parse radius ...");
std::string format = "xyz";
if (fu.hasArg("format"))
format = fu["format"];
bool ascii = fu.hasArg("ascii");
/* for now, hard-coded sphere componetns to be in float format,
so the number of chars in the format string is the num components */
int numFloatsPerSphere = format.size();
size_t xPos = format.find("x");
size_t yPos = format.find("y");
size_t zPos = format.find("z");
size_t rPos = format.find("r");
size_t sPos = format.find("s");
if (xPos == std::string::npos)
throw std::runtime_error("invalid points format: no x component");
if (yPos == std::string::npos)
throw std::runtime_error("invalid points format: no y component");
if (zPos == std::string::npos)
throw std::runtime_error("invalid points format: no z component");
float f[numFloatsPerSphere];
while (readOne(file,f,numFloatsPerSphere,ascii)) {
// read one more sphere ....
Spheres::Sphere s;
s.position.x = f[xPos];
s.position.y = f[yPos];
s.position.z = f[zPos];
s.radius
= (rPos == std::string::npos)
? radius
: f[rPos];
data->v.push_back(s);
}
fclose(file);
// create the node
NodeHandle spheres = createNode("spheres","Spheres");
// iw - note that 'add' sounds wrong here, but that's the way
// the current scene graph works - 'adding' that node (which
// happens to have the right name) will essentially replace the
// old value of that node, and thereby assign the 'data' field
data->setName("data");
spheres->add(data); //["data"]->setValue(data);
NodeHandle(world) += spheres;
}
}// ::ospray::sg
}// ::ospray
<|endoftext|>
|
<commit_before>/******************************************************************************
* Turbo C++11 metaprogramming Library *
* *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez *
* *
* This file is part of The Turbo Library. *
* *
* The Turbo 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, version 2 of the License. *
* *
* The Turbo 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 The Turbo Library. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#ifndef TYPE_TRAITS_HPP
#define TYPE_TRAITS_HPP
#include "function.hpp"
#include "basic_types.hpp"
#include "fixed_point.hpp"
#include "lazy.hpp"
#include "utils/assert.hpp"
#include <type_traits>
#include <utility>
namespace tml
{
namespace impl
{
template<typename T>
struct is_parametrized_expression : public tml::function<tml::false_type>
{};
template<template<typename...> class E , typename... ARGS>
struct is_parametrized_expression<E<ARGS...>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_integral_constant : public tml::function<tml::false_type>
{};
template<typename T , T V>
struct is_integral_constant<tml::integral_constant<T,V>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_fixed_point : public tml::function<tml::false_type>
{};
template<typename INTEGER_T , INTEGER_T V>
struct is_fixed_point<tml::fixed_point<INTEGER_T,V>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_functor
{
template<typename U> static tml::true_type f( decltype(&U::operator())* );
template<typename U> static tml::false_type f( ... );
using result = decltype( f<T>( nullptr ) );
};
template<typename T>
struct is_runtime_function : public tml::impl::is_functor<T>
{};
template<typename R , typename... ARGS>
struct is_runtime_function<R(*)(ARGS...)> : public tml::function<tml::true_type>
{};
template<typename C , typename R , typename... ARGS>
struct is_runtime_function<R(C::*)(ARGS...)> : public tml::function<tml::true_type>
{};
template<typename R , typename... ARGS>
struct function_signature_holder
{
using return_type = R;
using args = tml::list<ARGS...>;
};
/*
* This is the default template. Its used to evaluate functors.
* The other function entities (Function pointers) are treated bellow.
*/
template<typename F>
struct function_signature
{
TURBO_ASSERT( (tml::eval<tml::impl::is_functor<F>>) , "ERROR: The type specified is not a function" );
template<typename T>
struct signature_extractor;
template<typename C , typename R , typename... ARGS>
struct signature_extractor<R(C::*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename C , typename R , typename... ARGS>
struct signature_extractor<R(C::*)(ARGS...) const> : public tml::impl::function_signature_holder<R,ARGS...>
{};
using return_type = typename signature_extractor<decltype(&F::operator())>::return_type;
using args = typename signature_extractor<decltype(&F::operator())>::args;
};
template<typename R , typename... ARGS>
struct function_signature<R(*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename C , typename R , typename... ARGS>
struct function_signature<R(C::*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename F, typename... ARGS>
struct is_valid_call
{
private:
template<typename FF, typename... AA>
static auto f(int) ->
decltype( std::declval<FF>()(std::declval<AA>()...), tml::true_type{} );
template<typename FF, typename... AA>
static tml::false_type f(...);
public:
using result = decltype( f<F,ARGS...>(0) );
};
}
namespace func
{
/*
* Checks if a type T is considered a parametrized expression by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a parametrized expression. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_parametrized_expression = tml::impl::is_parametrized_expression<T>;
/*
* Checks if a type T is considered a function by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a metafunction. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_metafunction = tml::impl::is_function<T>;
/*
* Checks if a type T is an integral constant, that is, a basic metavalue
* (A tml::Int , a tml::Char , etc).
*
* Returns tml::true_type if the type T is an integral constant. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_integral_constant = tml::impl::is_integral_constant<T>;
/*
* Checks if a type T is a fixed-point value.
*
* Returns tml::true_type if the type T is a fixed-point value. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_fixed_point = tml::impl::is_fixed_point<T>;
/*
* Checks if a type T is a function entity (A function pointer, a functor,
* a lambda, etc).
* Returns tml::true_type if T is a function entity type. Returns
* tml::false_type.
*/
template<typename T>
using is_runtime_function = tml::impl::is_runtime_function<T>;
/*
* Given a function entity with type F, returns the type of the argumments of the function entity.
*/
template<typename F>
using function_argumments = tml::function<typename tml::impl::function_signature<F>::args>;
/*
* Given a function entity with type F, returns the return type of the function entity.
*/
template<typename F>
using function_return_type = tml::function<typename tml::impl::function_signature<F>::return_type>;
/*
* Given a function entity type, and a set of argumment types, checks if the call to that
* function with the parameters is well-formed.
*/
template<typename F , typename... ARGS>
using is_valid_call = tml::impl::is_valid_call<F,ARGS...>;
}
/*
* Checks if a type T is considered a parametrized expression by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a parametrized expression. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_parametrized_expression = tml::eval<tml::func::is_parametrized_expression<T>>;
/*
* Checks if a type T is considered a function by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a metafunction. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_metafunction = tml::eval<tml::func::is_metafunction<T>>;
/*
* Checks if a type T is an integral constant, that is, a basic metavalue
* (A tml::Int , a tml::Char , etc).
*
* Returns tml::true_type if the type T is an integral constant. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_integral_constant = tml::eval<tml::func::is_integral_constant<T>>;
/*
* Checks if a type T is a fixed-point value.
*
* Returns tml::true_type if the type T is a fixed-point value. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_fixed_point = tml::eval<tml::func::is_fixed_point<T>>;
/*
* Checks if a type T is a function entity (A function pointer, a functor,
* a lambda, etc).
* Returns tml::true_type if T is a function entity type. Returns
* tml::false_type.
*/
template<typename T>
using is_runtime_function = tml::eval<tml::func::is_runtime_function<T>>;
/*
* Given a function entity with type F, returns the type of the argumments of the function entity.
*/
template<typename F>
using function_argumments = tml::eval<tml::func::function_argumments<F>>;
/*
* Given a function entity with type F, returns the return type of the function entity.
*/
template<typename F>
using function_return_type = tml::eval<tml::func::function_return_type<F>>;
/*
* Given a function entity type, and a set of argumment types, checks if the call to that
* function with the parameters is well-formed.
*/
template<typename F , typename... ARGS>
using is_valid_call = tml::eval<tml::func::is_valid_call<F,ARGS...>>;
}
#endif /* TYPE_TRAITS_HPP */
<commit_msg>tml::make_function_signature metafunction. Added case for non-decayed function signature type on tml::impl::function_signature metafunction<commit_after>/******************************************************************************
* Turbo C++11 metaprogramming Library *
* *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez *
* *
* This file is part of The Turbo Library. *
* *
* The Turbo 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, version 2 of the License. *
* *
* The Turbo 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 The Turbo Library. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#ifndef TYPE_TRAITS_HPP
#define TYPE_TRAITS_HPP
#include "function.hpp"
#include "basic_types.hpp"
#include "fixed_point.hpp"
#include "lazy.hpp"
#include "utils/assert.hpp"
#include <type_traits>
#include <utility>
namespace tml
{
namespace impl
{
template<typename T>
struct is_parametrized_expression : public tml::function<tml::false_type>
{};
template<template<typename...> class E , typename... ARGS>
struct is_parametrized_expression<E<ARGS...>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_integral_constant : public tml::function<tml::false_type>
{};
template<typename T , T V>
struct is_integral_constant<tml::integral_constant<T,V>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_fixed_point : public tml::function<tml::false_type>
{};
template<typename INTEGER_T , INTEGER_T V>
struct is_fixed_point<tml::fixed_point<INTEGER_T,V>> : public tml::function<tml::true_type>
{};
template<typename T>
struct is_functor
{
template<typename U> static tml::true_type f( decltype(&U::operator())* );
template<typename U> static tml::false_type f( ... );
using result = decltype( f<T>( nullptr ) );
};
template<typename T>
struct is_runtime_function : public tml::impl::is_functor<T>
{};
template<typename R , typename... ARGS>
struct is_runtime_function<R(*)(ARGS...)> : public tml::function<tml::true_type>
{};
template<typename C , typename R , typename... ARGS>
struct is_runtime_function<R(C::*)(ARGS...)> : public tml::function<tml::true_type>
{};
template<typename R , typename... ARGS>
struct function_signature_holder
{
using return_type = R;
using args = tml::list<ARGS...>;
};
/*
* This is the default template. Its used to evaluate functors.
* The other function entities (Function pointers) are treated bellow.
*/
template<typename F>
struct function_signature
{
TURBO_ASSERT( (tml::eval<tml::impl::is_functor<F>>) , "ERROR: The type specified is not a function" );
template<typename T>
struct signature_extractor;
template<typename C , typename R , typename... ARGS>
struct signature_extractor<R(C::*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename C , typename R , typename... ARGS>
struct signature_extractor<R(C::*)(ARGS...) const> : public tml::impl::function_signature_holder<R,ARGS...>
{};
using return_type = typename signature_extractor<decltype(&F::operator())>::return_type;
using args = typename signature_extractor<decltype(&F::operator())>::args;
};
template<typename R , typename... ARGS>
struct function_signature<R(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename R , typename... ARGS>
struct function_signature<R(*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename C , typename R , typename... ARGS>
struct function_signature<R(C::*)(ARGS...)> : public tml::impl::function_signature_holder<R,ARGS...>
{};
template<typename R , typename... ARGS>
struct make_function_signature : public tml::function<R(ARGS...)>
{};
template<typename F, typename... ARGS>
struct is_valid_call
{
private:
template<typename FF, typename... AA>
static auto f(int) ->
decltype( std::declval<FF>()(std::declval<AA>()...), tml::true_type{} );
template<typename FF, typename... AA>
static tml::false_type f(...);
public:
using result = decltype( f<F,ARGS...>(0) );
};
}
namespace func
{
/*
* Checks if a type T is considered a parametrized expression by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a parametrized expression. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_parametrized_expression = tml::impl::is_parametrized_expression<T>;
/*
* Checks if a type T is considered a function by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a metafunction. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_metafunction = tml::impl::is_function<T>;
/*
* Checks if a type T is an integral constant, that is, a basic metavalue
* (A tml::Int , a tml::Char , etc).
*
* Returns tml::true_type if the type T is an integral constant. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_integral_constant = tml::impl::is_integral_constant<T>;
/*
* Checks if a type T is a fixed-point value.
*
* Returns tml::true_type if the type T is a fixed-point value. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_fixed_point = tml::impl::is_fixed_point<T>;
/*
* Checks if a type T is a function entity (A function pointer, a functor,
* a lambda, etc).
* Returns tml::true_type if T is a function entity type. Returns
* tml::false_type.
*/
template<typename T>
using is_runtime_function = tml::impl::is_runtime_function<T>;
/*
* Given a function entity with type F, returns the type of the argumments of the function entity.
*/
template<typename F>
using function_argumments = tml::function<typename tml::impl::function_signature<F>::args>;
/*
* Given a function entity with type F, returns the return type of the function entity.
*/
template<typename F>
using function_return_type = tml::function<typename tml::impl::function_signature<F>::return_type>;
/*
* Given a return type R and a set of argumments types, returns the corresponding function signature type.
*/
template<typename R , typename... ARGS>
using make_function_signature = tml::impl::make_function_signature<R,ARGS...>;
/*
* Given a function entity type, and a set of argumment types, checks if the call to that
* function with the parameters is well-formed.
*/
template<typename F , typename... ARGS>
using is_valid_call = tml::impl::is_valid_call<F,ARGS...>;
}
/*
* Checks if a type T is considered a parametrized expression by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a parametrized expression. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_parametrized_expression = tml::eval<tml::func::is_parametrized_expression<T>>;
/*
* Checks if a type T is considered a function by the Turbo expression
* evaluation system.
*
* Returns tml::true_type if the type T is a metafunction. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_metafunction = tml::eval<tml::func::is_metafunction<T>>;
/*
* Checks if a type T is an integral constant, that is, a basic metavalue
* (A tml::Int , a tml::Char , etc).
*
* Returns tml::true_type if the type T is an integral constant. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_integral_constant = tml::eval<tml::func::is_integral_constant<T>>;
/*
* Checks if a type T is a fixed-point value.
*
* Returns tml::true_type if the type T is a fixed-point value. Returns
* tml::false_type otherwise.
*/
template<typename T>
using is_fixed_point = tml::eval<tml::func::is_fixed_point<T>>;
/*
* Checks if a type T is a function entity (A function pointer, a functor,
* a lambda, etc).
* Returns tml::true_type if T is a function entity type. Returns
* tml::false_type.
*/
template<typename T>
using is_runtime_function = tml::eval<tml::func::is_runtime_function<T>>;
/*
* Given a function entity with type F, returns the type of the argumments of the function entity.
*/
template<typename F>
using function_argumments = tml::eval<tml::func::function_argumments<F>>;
/*
* Given a function entity with type F, returns the return type of the function entity.
*/
template<typename F>
using function_return_type = tml::eval<tml::func::function_return_type<F>>;
/*
* Given a return type R and a set of argumments types, returns the corresponding function signature type.
*/
template<typename R , typename... ARGS>
using make_function_signature = tml::eval<tml::func::make_function_signature<R,ARGS...>>;
/*
* Given a function entity type, and a set of argumment types, checks if the call to that
* function with the parameters is well-formed.
*/
template<typename F , typename... ARGS>
using is_valid_call = tml::eval<tml::func::is_valid_call<F,ARGS...>>;
}
#endif /* TYPE_TRAITS_HPP */
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: main.cpp
* Purpose: main for wxExtension cpp unit testing
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
* Created: za 17 jan 2009 11:51:20 CET
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <ui/text/TestRunner.h>
#include <cppunit/TestRunner.h>
#include "test.h"
IMPLEMENT_APP(wxExTestApp)
bool wxExTestApp::OnInit()
{
SetAppName("wxex-test-app");
if (!wxExApp::OnInit())
{
return false;
}
wxExFrame *frame = new wxExFrame(NULL, wxID_ANY, "wxex-test-app");
frame->Show(true);
SetTopWindow(frame);
CppUnit::TextUi::TestRunner runner;
wxExAppTestSuite* suite = new wxExAppTestSuite;
runner.addTest(suite);
runner.run();
// Return false, so test ends here.
return false;
}
<commit_msg>frame should now be a managed frame<commit_after>/******************************************************************************\
* File: main.cpp
* Purpose: main for wxExtension cpp unit testing
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
* Created: za 17 jan 2009 11:51:20 CET
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <ui/text/TestRunner.h>
#include <cppunit/TestRunner.h>
#include "test.h"
IMPLEMENT_APP(wxExTestApp)
bool wxExTestApp::OnInit()
{
SetAppName("wxex-test-app");
if (!wxExApp::OnInit())
{
return false;
}
wxExManagedFrame *frame = new wxExManagedFrame(NULL, wxID_ANY, "wxex-test-app");
frame->Show(true);
SetTopWindow(frame);
CppUnit::TextUi::TestRunner runner;
wxExAppTestSuite* suite = new wxExAppTestSuite;
runner.addTest(suite);
runner.run();
// Return false, so test ends here.
return false;
}
<|endoftext|>
|
<commit_before>// Halide tutorial lesson 15: Generators part 1
// This lesson demonstrates how to encapsulate Halide pipelines into
// resuable components called generators.
// On linux, you can compile and run it like so:
// g++ lesson_15*.cpp ../tools/GenGen.cpp -g -std=c++11 -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_15_generate
// bash lesson_15_generators_usage.sh
// On os x:
// g++ lesson_15*.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -o lesson_15_generate
// bash lesson_15_generators_usage.sh
// If you have the entire Halide source tree, you can also build it by
// running:
// make tutorial_lesson_15_generators
// in a shell with the current directory at the top of the halide
// source tree.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
// Generators are a more structured way to do ahead-of-time
// compilation of Halide pipelines. Instead of writing an int main()
// with an ad-hoc command-line interface like we did in lesson 10, we
// define a class that inherits from Halide::Generator.
class MyFirstGenerator : public Halide::Generator<MyFirstGenerator> {
public:
// We declare the parameters to the Halide pipeline as public
// member variables. We'll give the parameters explicit names this
// time. They'll appear in the signature of our generated function
// in the same order as we declare them.
Param<uint8_t> offset{"offset"};
ImageParam input{UInt(8), 2, "input"};
// Typically you declare your Vars at this scope as well, so that
// they can be used in any helper methods you add later.
Var x, y;
// We then define a method that constructs and return the Halide
// pipeline:
Func build() {
// Define the Func.
Func brighter;
brighter(x, y) = input(x, y) + offset;
// Schedule it.
brighter.vectorize(x, 16).parallel(y);
// In lesson 10, here is where we called
// Func::compile_to_file. In a Generator, we just need to
// return the Func representing the output of the pipeline.
return brighter;
}
};
// We compile this file along with tools/GenGen.cpp. That file defines
// an "int main(...)" that provides the command-line interface to use
// your generator class. We need to tell that code about our
// generator. We do this like so:
RegisterGenerator<MyFirstGenerator> my_first_generator{"my_first_generator"};
// If you like, you can put multiple Generators in the one file. This
// could be a good idea if they share some common code. Let's define
// another more complex generator:
class MySecondGenerator : public Halide::Generator<MySecondGenerator> {
public:
// This generator will take some compile-time parameters
// too. These let you compile multiple variants of a Halide
// pipeline. We'll define one that tells us whether or not to
// parallelize in our schedule:
GeneratorParam<bool> parallel{"parallel", /* default value */ true};
// ... and another representing a constant scale factor to use:
GeneratorParam<float> scale{"scale",
1.0f /* default value */,
0.0f /* minimum value */,
100.0f /* maximum value */};
// You can define GeneratorParams of all the basic scalar
// types. For numeric types you can optionally provide a minimum
// and maximum value, as we did for scale above.
// You can also define GeneratorParams for enums. To make this
// work you must provide a mapping from strings to your enum
// values.
enum class Rotation { None, Clockwise, CounterClockwise };
GeneratorParam<Rotation> rotation{"rotation",
/* default value */
Rotation::None,
/* map from names to values */
{{ "none", Rotation::None },
{ "cw", Rotation::Clockwise },
{ "ccw", Rotation::CounterClockwise }}};
// Halide::Type is supported as though it was an enum. It's most
// useful for customizing the type of input or output image
// params.
GeneratorParam<Halide::Type> output_type{"output_type", Int(32)};
// We'll use the same Param and ImageParam as before:
Param<uint8_t> offset{"offset"};
ImageParam input{UInt(8), 2, "input"};
// And we'll declare our Vars here as before.
Var x, y;
Func build() {
// Define the Func. We'll use the compile-time scale factor as
// well as the runtime offset param.
Func brighter;
brighter(x, y) = scale * (input(x, y) + offset);
// We'll possibly do some sort of rotation, depending on the
// enum. To get the value of a GeneratorParam, cast it to the
// corresponding type. This cast happens implicitly most of
// the time (e.g. with scale above).
Func rotated;
switch ((Rotation)rotation) {
case Rotation::None:
rotated(x, y) = brighter(x, y);
break;
case Rotation::Clockwise:
rotated(x, y) = brighter(y, 100-x);
break;
case Rotation::CounterClockwise:
rotated(x, y) = brighter(100-y, x);
break;
}
// We'll then cast to the desired output type.
Func output;
output(x, y) = cast(output_type, rotated(x, y));
// The structure of the pipeline depended on the generator
// params. So will the schedule.
// Let's start by vectorizing the output. We don't know the
// type though, so it's hard to pick a good factor. Generators
// provide a helper called "natural_vector_size" which will
// pick a reasonable factor for you given the type and the
// target you're compiling to.
output.vectorize(x, natural_vector_size(output_type));
// Now we'll possibly parallelize it:
if (parallel) {
output.parallel(y);
}
// If there was a rotation, we'll schedule that to occur per
// scanline of the output and vectorize it according to its
// type.
if (rotation != Rotation::None) {
rotated
.compute_at(output, y)
.vectorize(x, natural_vector_size(rotated.output_types()[0]));
}
return output;
}
};
// Register our second generator:
RegisterGenerator<MySecondGenerator> my_second_generator{"my_second_generator"};
// After compiling this file, see how to use it in
// lesson_15_generators_build.sh
<commit_msg>Add -fno-rtti to build instructions for lesson 15<commit_after>// Halide tutorial lesson 15: Generators part 1
// This lesson demonstrates how to encapsulate Halide pipelines into
// resuable components called generators.
// On linux, you can compile and run it like so:
// g++ lesson_15*.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_15_generate
// bash lesson_15_generators_usage.sh
// On os x:
// g++ lesson_15*.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -o lesson_15_generate
// bash lesson_15_generators_usage.sh
// If you have the entire Halide source tree, you can also build it by
// running:
// make tutorial_lesson_15_generators
// in a shell with the current directory at the top of the halide
// source tree.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
// Generators are a more structured way to do ahead-of-time
// compilation of Halide pipelines. Instead of writing an int main()
// with an ad-hoc command-line interface like we did in lesson 10, we
// define a class that inherits from Halide::Generator.
class MyFirstGenerator : public Halide::Generator<MyFirstGenerator> {
public:
// We declare the parameters to the Halide pipeline as public
// member variables. We'll give the parameters explicit names this
// time. They'll appear in the signature of our generated function
// in the same order as we declare them.
Param<uint8_t> offset{"offset"};
ImageParam input{UInt(8), 2, "input"};
// Typically you declare your Vars at this scope as well, so that
// they can be used in any helper methods you add later.
Var x, y;
// We then define a method that constructs and return the Halide
// pipeline:
Func build() {
// Define the Func.
Func brighter;
brighter(x, y) = input(x, y) + offset;
// Schedule it.
brighter.vectorize(x, 16).parallel(y);
// In lesson 10, here is where we called
// Func::compile_to_file. In a Generator, we just need to
// return the Func representing the output of the pipeline.
return brighter;
}
};
// We compile this file along with tools/GenGen.cpp. That file defines
// an "int main(...)" that provides the command-line interface to use
// your generator class. We need to tell that code about our
// generator. We do this like so:
RegisterGenerator<MyFirstGenerator> my_first_generator{"my_first_generator"};
// If you like, you can put multiple Generators in the one file. This
// could be a good idea if they share some common code. Let's define
// another more complex generator:
class MySecondGenerator : public Halide::Generator<MySecondGenerator> {
public:
// This generator will take some compile-time parameters
// too. These let you compile multiple variants of a Halide
// pipeline. We'll define one that tells us whether or not to
// parallelize in our schedule:
GeneratorParam<bool> parallel{"parallel", /* default value */ true};
// ... and another representing a constant scale factor to use:
GeneratorParam<float> scale{"scale",
1.0f /* default value */,
0.0f /* minimum value */,
100.0f /* maximum value */};
// You can define GeneratorParams of all the basic scalar
// types. For numeric types you can optionally provide a minimum
// and maximum value, as we did for scale above.
// You can also define GeneratorParams for enums. To make this
// work you must provide a mapping from strings to your enum
// values.
enum class Rotation { None, Clockwise, CounterClockwise };
GeneratorParam<Rotation> rotation{"rotation",
/* default value */
Rotation::None,
/* map from names to values */
{{ "none", Rotation::None },
{ "cw", Rotation::Clockwise },
{ "ccw", Rotation::CounterClockwise }}};
// Halide::Type is supported as though it was an enum. It's most
// useful for customizing the type of input or output image
// params.
GeneratorParam<Halide::Type> output_type{"output_type", Int(32)};
// We'll use the same Param and ImageParam as before:
Param<uint8_t> offset{"offset"};
ImageParam input{UInt(8), 2, "input"};
// And we'll declare our Vars here as before.
Var x, y;
Func build() {
// Define the Func. We'll use the compile-time scale factor as
// well as the runtime offset param.
Func brighter;
brighter(x, y) = scale * (input(x, y) + offset);
// We'll possibly do some sort of rotation, depending on the
// enum. To get the value of a GeneratorParam, cast it to the
// corresponding type. This cast happens implicitly most of
// the time (e.g. with scale above).
Func rotated;
switch ((Rotation)rotation) {
case Rotation::None:
rotated(x, y) = brighter(x, y);
break;
case Rotation::Clockwise:
rotated(x, y) = brighter(y, 100-x);
break;
case Rotation::CounterClockwise:
rotated(x, y) = brighter(100-y, x);
break;
}
// We'll then cast to the desired output type.
Func output;
output(x, y) = cast(output_type, rotated(x, y));
// The structure of the pipeline depended on the generator
// params. So will the schedule.
// Let's start by vectorizing the output. We don't know the
// type though, so it's hard to pick a good factor. Generators
// provide a helper called "natural_vector_size" which will
// pick a reasonable factor for you given the type and the
// target you're compiling to.
output.vectorize(x, natural_vector_size(output_type));
// Now we'll possibly parallelize it:
if (parallel) {
output.parallel(y);
}
// If there was a rotation, we'll schedule that to occur per
// scanline of the output and vectorize it according to its
// type.
if (rotation != Rotation::None) {
rotated
.compute_at(output, y)
.vectorize(x, natural_vector_size(rotated.output_types()[0]));
}
return output;
}
};
// Register our second generator:
RegisterGenerator<MySecondGenerator> my_second_generator{"my_second_generator"};
// After compiling this file, see how to use it in
// lesson_15_generators_build.sh
<|endoftext|>
|
<commit_before>/*
obtainkeysjob.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2005 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef GPG_ERR_SOURCE_DEFAULT
#define GPG_ERR_SOURCE_DEFAULT ((gpg_err_source_t)176) // chiasmus
#endif
#include "obtainkeysjob.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kshell.h>
#include <qdir.h>
#include <qstringlist.h>
#include <qvariant.h>
#include <qtimer.h>
#include <qfileinfo.h>
#include <gpg-error.h>
Kleo::ObtainKeysJob::ObtainKeysJob( const QStringList & keypaths )
: SpecialJob( 0, 0 ),
mKeyPaths( keypaths ),
mIndex( 0 ),
mCanceled( false )
{
}
Kleo::ObtainKeysJob::~ObtainKeysJob() {}
GpgME::Error Kleo::ObtainKeysJob::start() {
QTimer::singleShot( 0, this, SLOT(slotPerform()) );
return 0;
}
GpgME::Error Kleo::ObtainKeysJob::exec( QVariant * result ) {
slotPerform( false );
if ( result )
*result = mResult;
return mError;
}
void Kleo::ObtainKeysJob::slotCancel() {
mCanceled = true;
}
void Kleo::ObtainKeysJob::slotPerform() {
slotPerform( true );
}
void Kleo::ObtainKeysJob::slotPerform( bool async ) {
if ( mCanceled && !mError )
mError = gpg_error( GPG_ERR_CANCELED );
if ( mIndex >= mKeyPaths.size() || mError ) {
emit done();
emit result( mError, QVariant( mResult ) );
return;
}
emit progress( i18n( "Scanning directory %1..." ).arg( mKeyPaths[mIndex] ),
mIndex, mKeyPaths.size() );
const QDir dir( KShell::tildeExpand( mKeyPaths[mIndex] ) );
if ( const QFileInfoList * xiaFiles = dir.entryInfoList( "*.xia;*.XIA", QDir::Files ) )
for ( QFileInfoList::const_iterator it = xiaFiles->begin(), end = xiaFiles->end() ; it != end ; ++it )
if ( (*it)->isReadable() )
mResult.push_back( (*it)->absFilePath() );
++mIndex;
if ( async )
QTimer::singleShot( 0, this, SLOT(slotPerform()) );
else
slotPerform( false );
}
void Kleo::ObtainKeysJob::showErrorDialog( QWidget * parent, const QString & caption ) const {
if ( !mError )
return;
if ( mError.isCanceled() )
return;
const QString msg = QString::fromUtf8( mError.asString() );
KMessageBox::error( parent, msg, caption );
}
#include "obtainkeysjob.moc"
<commit_msg>chiasmus key files are called .xis, not .xia. .xia are the encrypted files.<commit_after>/*
obtainkeysjob.cpp
This file is part of libkleopatra, the KDE keymanagement library
Copyright (c) 2005 Klarlvdalens Datakonsult AB
Libkleopatra 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.
Libkleopatra 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef GPG_ERR_SOURCE_DEFAULT
#define GPG_ERR_SOURCE_DEFAULT ((gpg_err_source_t)176) // chiasmus
#endif
#include "obtainkeysjob.h"
#include <klocale.h>
#include <kmessagebox.h>
#include <kshell.h>
#include <qdir.h>
#include <qstringlist.h>
#include <qvariant.h>
#include <qtimer.h>
#include <qfileinfo.h>
#include <gpg-error.h>
Kleo::ObtainKeysJob::ObtainKeysJob( const QStringList & keypaths )
: SpecialJob( 0, 0 ),
mKeyPaths( keypaths ),
mIndex( 0 ),
mCanceled( false )
{
}
Kleo::ObtainKeysJob::~ObtainKeysJob() {}
GpgME::Error Kleo::ObtainKeysJob::start() {
QTimer::singleShot( 0, this, SLOT(slotPerform()) );
return 0;
}
GpgME::Error Kleo::ObtainKeysJob::exec( QVariant * result ) {
slotPerform( false );
if ( result )
*result = mResult;
return mError;
}
void Kleo::ObtainKeysJob::slotCancel() {
mCanceled = true;
}
void Kleo::ObtainKeysJob::slotPerform() {
slotPerform( true );
}
void Kleo::ObtainKeysJob::slotPerform( bool async ) {
if ( mCanceled && !mError )
mError = gpg_error( GPG_ERR_CANCELED );
if ( mIndex >= mKeyPaths.size() || mError ) {
emit done();
emit result( mError, QVariant( mResult ) );
return;
}
emit progress( i18n( "Scanning directory %1..." ).arg( mKeyPaths[mIndex] ),
mIndex, mKeyPaths.size() );
const QDir dir( KShell::tildeExpand( mKeyPaths[mIndex] ) );
if ( const QFileInfoList * xisFiles = dir.entryInfoList( "*.xis;*.XIS", QDir::Files ) )
for ( QFileInfoList::const_iterator it = xisFiles->begin(), end = xisFiles->end() ; it != end ; ++it )
if ( (*it)->isReadable() )
mResult.push_back( (*it)->absFilePath() );
++mIndex;
if ( async )
QTimer::singleShot( 0, this, SLOT(slotPerform()) );
else
slotPerform( false );
}
void Kleo::ObtainKeysJob::showErrorDialog( QWidget * parent, const QString & caption ) const {
if ( !mError )
return;
if ( mError.isCanceled() )
return;
const QString msg = QString::fromUtf8( mError.asString() );
KMessageBox::error( parent, msg, caption );
}
#include "obtainkeysjob.moc"
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/options/wifi_config_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/options/network_config_view.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/button/native_button.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"
namespace chromeos {
// The width of the password field.
const int kPasswordWidth = 150;
WifiConfigView::WifiConfigView(NetworkConfigView* parent, WifiNetwork wifi)
: parent_(parent),
other_network_(false),
can_login_(false),
wifi_(wifi),
ssid_textfield_(NULL),
identity_textfield_(NULL),
certificate_browse_button_(NULL),
certificate_path_(),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
autoconnect_checkbox_(NULL) {
Init();
}
WifiConfigView::WifiConfigView(NetworkConfigView* parent)
: parent_(parent),
other_network_(true),
can_login_(false),
ssid_textfield_(NULL),
identity_textfield_(NULL),
certificate_browse_button_(NULL),
certificate_path_(),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
autoconnect_checkbox_(NULL) {
Init();
}
void WifiConfigView::UpdateCanLogin(void) {
bool can_login = true;
if (other_network_) {
// Since the user can try to connect to a non-encrypted hidden network,
// only enforce ssid is non-empty.
can_login = !ssid_textfield_->text().empty();
} else {
// Connecting to an encrypted network
if (passphrase_textfield_ != NULL) {
// if the network requires a passphrase, make sure it is non empty.
can_login &= !passphrase_textfield_->text().empty();
}
if (identity_textfield_ != NULL) {
// If we have an identity field, we can login if we have a non empty
// identity and a certificate path
can_login &= !identity_textfield_->text().empty() &&
!certificate_path_.empty();
}
}
// Update the login button enable/disable state if can_login_ changes.
if (can_login != can_login_) {
can_login_ = can_login;
parent_->GetDialogClientView()->UpdateDialogButtons();
}
}
void WifiConfigView::ContentsChanged(views::Textfield* sender,
const string16& new_contents) {
UpdateCanLogin();
}
bool WifiConfigView::HandleKeystroke(
views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
if (sender == passphrase_textfield_) {
if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
parent_->Accept();
return true;
} else if (keystroke.GetKeyboardCode() == app::VKEY_ESCAPE) {
parent_->Cancel();
return true;
}
}
return false;
}
void WifiConfigView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == passphrase_visible_button_) {
if (passphrase_textfield_)
passphrase_textfield_->SetPassword(!passphrase_textfield_->IsPassword());
} else if (sender == certificate_browse_button_) {
select_file_dialog_ = SelectFileDialog::Create(this);
select_file_dialog_->set_browser_mode(parent_->is_browser_mode());
select_file_dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16(), FilePath(), NULL, 0,
std::string(),
parent_->is_browser_mode() ?
NULL :
parent_->GetNativeWindow(),
NULL);
} else {
NOTREACHED();
}
}
void WifiConfigView::FileSelected(const FilePath& path,
int index, void* params) {
certificate_path_ = path.value();
if (certificate_browse_button_)
certificate_browse_button_->SetLabel(path.BaseName().ToWStringHack());
UpdateCanLogin(); // TODO(njw) Check if the passphrase decrypts the key.
}
bool WifiConfigView::Login() {
std::string identity_string;
if (identity_textfield_ != NULL) {
identity_string = UTF16ToUTF8(identity_textfield_->text());
}
if (other_network_) {
CrosLibrary::Get()->GetNetworkLibrary()->ConnectToWifiNetwork(
GetSSID(), GetPassphrase(),
identity_string, certificate_path_,
autoconnect_checkbox_ ? autoconnect_checkbox_->checked() : true);
} else {
Save();
CrosLibrary::Get()->GetNetworkLibrary()->ConnectToWifiNetwork(
wifi_, GetPassphrase(),
identity_string, certificate_path_);
}
return true;
}
bool WifiConfigView::Save() {
// Save password and auto-connect here.
if (!other_network_) {
bool changed = false;
if (autoconnect_checkbox_) {
bool auto_connect = autoconnect_checkbox_->checked();
if (auto_connect != wifi_.auto_connect()) {
wifi_.set_auto_connect(auto_connect);
changed = true;
}
}
if (passphrase_textfield_) {
const std::string& passphrase =
UTF16ToUTF8(passphrase_textfield_->text());
if (passphrase != wifi_.passphrase()) {
wifi_.set_passphrase(passphrase);
changed = true;
}
}
if (changed)
CrosLibrary::Get()->GetNetworkLibrary()->SaveWifiNetwork(wifi_);
}
return true;
}
const std::string WifiConfigView::GetSSID() const {
std::string result;
if (ssid_textfield_ != NULL)
result = UTF16ToUTF8(ssid_textfield_->text());
return result;
}
const std::string WifiConfigView::GetPassphrase() const {
std::string result;
if (passphrase_textfield_ != NULL)
result = UTF16ToUTF8(passphrase_textfield_->text());
return result;
}
void WifiConfigView::FocusFirstField() {
if (ssid_textfield_)
ssid_textfield_->RequestFocus();
else if (identity_textfield_)
identity_textfield_->RequestFocus();
else if (passphrase_textfield_)
passphrase_textfield_->RequestFocus();
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
static bool is_certificate_in_pkcs11(const std::string& path) {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (path.find(settings_string) == 0) {
std::string::size_type idx = path.find(pkcs11_key);
if (idx != std::string::npos)
idx = path.find_first_not_of(kWhitespaceASCII, idx + pkcs11_key.length());
if (idx != std::string::npos && path[idx] == '=')
return true;
}
return false;
}
void WifiConfigView::Init() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
// Label
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
// Textfield
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, kPasswordWidth);
// Password visible button
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID)));
if (other_network_) {
ssid_textfield_ = new views::Textfield(views::Textfield::STYLE_DEFAULT);
ssid_textfield_->SetController(this);
layout->AddView(ssid_textfield_);
} else {
views::Label* label = new views::Label(ASCIIToWide(wifi_.name()));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(label);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
// Certificates stored in a pkcs11 device can not be browsed
// and do not require a passphrase.
bool certificate_in_pkcs11 = false;
// Add ID and cert password if we're using 802.1x
// XXX we're cheating and assuming 802.1x means EAP-TLS - not true
// in general, but very common. WPA Supplicant doesn't report the
// EAP type because it's unknown until the process begins, and we'd
// need some kind of callback.
if (wifi_.encrypted() && wifi_.encryption() == SECURITY_8021X) {
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY)));
identity_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
identity_textfield_->SetController(this);
if (!wifi_.identity().empty())
identity_textfield_->SetText(UTF8ToUTF16(wifi_.identity()));
layout->AddView(identity_textfield_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT)));
if (!wifi_.cert_path().empty()) {
certificate_path_ = wifi_.cert_path();
certificate_in_pkcs11 = is_certificate_in_pkcs11(certificate_path_);
}
if (certificate_in_pkcs11) {
std::wstring label = l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_INSTALLED);
views::Label* cert_text = new views::Label(label);
cert_text->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(cert_text);
} else {
std::wstring label;
if (!certificate_path_.empty())
label = UTF8ToWide(certificate_path_);
else
label = l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_BUTTON);
certificate_browse_button_ = new views::NativeButton(this, label);
layout->AddView(certificate_browse_button_);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// Add passphrase if other_network or wifi is encrypted.
if (other_network_ || (wifi_.encrypted() && !certificate_in_pkcs11)) {
layout->StartRow(0, column_view_set_id);
int label_text_id;
if (wifi_.encryption() == SECURITY_8021X)
label_text_id =
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PRIVATE_KEY_PASSWORD;
else
label_text_id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE;
layout->AddView(new views::Label(l10n_util::GetString(label_text_id)));
passphrase_textfield_ = new views::Textfield(
views::Textfield::STYLE_PASSWORD);
passphrase_textfield_->SetController(this);
if (!wifi_.passphrase().empty())
passphrase_textfield_->SetText(UTF8ToUTF16(wifi_.passphrase()));
layout->AddView(passphrase_textfield_);
// Password visible button.
passphrase_visible_button_ = new views::ImageButton(this);
passphrase_visible_button_->SetImage(views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetBitmapNamed(IDR_STATUSBAR_NETWORK_SECURE));
passphrase_visible_button_->SetImageAlignment(
views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE);
layout->AddView(passphrase_visible_button_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// If there's an error, add an error message label.
// Right now, only displaying bad_passphrase and bad_wepkey errors.
if (wifi_.error() == ERROR_BAD_PASSPHRASE ||
wifi_.error() == ERROR_BAD_WEPKEY) {
layout->StartRow(0, column_view_set_id);
layout->SkipColumns(1);
int id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_PASSPHRASE;
if (wifi_.error() == ERROR_BAD_WEPKEY)
id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_WEPKEY;
views::Label* label_error = new views::Label(l10n_util::GetString(id));
label_error->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
label_error->SetColor(SK_ColorRED);
layout->AddView(label_error);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// Autoconnect checkbox
// Only show if this network is already remembered (a favorite).
if (wifi_.favorite()) {
autoconnect_checkbox_ = new views::Checkbox(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_AUTO_CONNECT));
// For other network, default to autoconnect.
bool autoconnect = other_network_ || wifi_.auto_connect();
autoconnect_checkbox_->SetChecked(autoconnect);
layout->StartRow(0, column_view_set_id);
layout->AddView(autoconnect_checkbox_, 3, 1);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
}
} // namespace chromeos
<commit_msg>Make Enter key work on wi-fi password window. Another attempt (previous one was incorrect).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/options/wifi_config_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/options/network_config_view.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "views/controls/button/image_button.h"
#include "views/controls/button/native_button.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"
namespace chromeos {
// The width of the password field.
const int kPasswordWidth = 150;
WifiConfigView::WifiConfigView(NetworkConfigView* parent, WifiNetwork wifi)
: parent_(parent),
other_network_(false),
can_login_(false),
wifi_(wifi),
ssid_textfield_(NULL),
identity_textfield_(NULL),
certificate_browse_button_(NULL),
certificate_path_(),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
autoconnect_checkbox_(NULL) {
Init();
}
WifiConfigView::WifiConfigView(NetworkConfigView* parent)
: parent_(parent),
other_network_(true),
can_login_(false),
ssid_textfield_(NULL),
identity_textfield_(NULL),
certificate_browse_button_(NULL),
certificate_path_(),
passphrase_textfield_(NULL),
passphrase_visible_button_(NULL),
autoconnect_checkbox_(NULL) {
Init();
}
void WifiConfigView::UpdateCanLogin(void) {
bool can_login = true;
if (other_network_) {
// Since the user can try to connect to a non-encrypted hidden network,
// only enforce ssid is non-empty.
can_login = !ssid_textfield_->text().empty();
} else {
// Connecting to an encrypted network
if (passphrase_textfield_ != NULL) {
// if the network requires a passphrase, make sure it is non empty.
can_login &= !passphrase_textfield_->text().empty();
}
if (identity_textfield_ != NULL) {
// If we have an identity field, we can login if we have a non empty
// identity and a certificate path
can_login &= !identity_textfield_->text().empty() &&
!certificate_path_.empty();
}
}
// Update the login button enable/disable state if can_login_ changes.
if (can_login != can_login_) {
can_login_ = can_login;
parent_->GetDialogClientView()->UpdateDialogButtons();
}
}
void WifiConfigView::ContentsChanged(views::Textfield* sender,
const string16& new_contents) {
UpdateCanLogin();
}
bool WifiConfigView::HandleKeystroke(
views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
if (sender == passphrase_textfield_ &&
keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
parent_->GetDialogClientView()->AcceptWindow();
}
return false;
}
void WifiConfigView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == passphrase_visible_button_) {
if (passphrase_textfield_)
passphrase_textfield_->SetPassword(!passphrase_textfield_->IsPassword());
} else if (sender == certificate_browse_button_) {
select_file_dialog_ = SelectFileDialog::Create(this);
select_file_dialog_->set_browser_mode(parent_->is_browser_mode());
select_file_dialog_->SelectFile(SelectFileDialog::SELECT_OPEN_FILE,
string16(), FilePath(), NULL, 0,
std::string(),
parent_->is_browser_mode() ?
NULL :
parent_->GetNativeWindow(),
NULL);
} else {
NOTREACHED();
}
}
void WifiConfigView::FileSelected(const FilePath& path,
int index, void* params) {
certificate_path_ = path.value();
if (certificate_browse_button_)
certificate_browse_button_->SetLabel(path.BaseName().ToWStringHack());
UpdateCanLogin(); // TODO(njw) Check if the passphrase decrypts the key.
}
bool WifiConfigView::Login() {
std::string identity_string;
if (identity_textfield_ != NULL) {
identity_string = UTF16ToUTF8(identity_textfield_->text());
}
if (other_network_) {
CrosLibrary::Get()->GetNetworkLibrary()->ConnectToWifiNetwork(
GetSSID(), GetPassphrase(),
identity_string, certificate_path_,
autoconnect_checkbox_ ? autoconnect_checkbox_->checked() : true);
} else {
Save();
CrosLibrary::Get()->GetNetworkLibrary()->ConnectToWifiNetwork(
wifi_, GetPassphrase(),
identity_string, certificate_path_);
}
return true;
}
bool WifiConfigView::Save() {
// Save password and auto-connect here.
if (!other_network_) {
bool changed = false;
if (autoconnect_checkbox_) {
bool auto_connect = autoconnect_checkbox_->checked();
if (auto_connect != wifi_.auto_connect()) {
wifi_.set_auto_connect(auto_connect);
changed = true;
}
}
if (passphrase_textfield_) {
const std::string& passphrase =
UTF16ToUTF8(passphrase_textfield_->text());
if (passphrase != wifi_.passphrase()) {
wifi_.set_passphrase(passphrase);
changed = true;
}
}
if (changed)
CrosLibrary::Get()->GetNetworkLibrary()->SaveWifiNetwork(wifi_);
}
return true;
}
const std::string WifiConfigView::GetSSID() const {
std::string result;
if (ssid_textfield_ != NULL)
result = UTF16ToUTF8(ssid_textfield_->text());
return result;
}
const std::string WifiConfigView::GetPassphrase() const {
std::string result;
if (passphrase_textfield_ != NULL)
result = UTF16ToUTF8(passphrase_textfield_->text());
return result;
}
void WifiConfigView::FocusFirstField() {
if (ssid_textfield_)
ssid_textfield_->RequestFocus();
else if (identity_textfield_)
identity_textfield_->RequestFocus();
else if (passphrase_textfield_)
passphrase_textfield_->RequestFocus();
}
// Parse 'path' to determine if the certificate is stored in a pkcs#11 device.
// flimflam recognizes the string "SETTINGS:" to specify authentication
// parameters. 'key_id=' indicates that the certificate is stored in a pkcs#11
// device. See src/third_party/flimflam/files/doc/service-api.txt.
static bool is_certificate_in_pkcs11(const std::string& path) {
static const std::string settings_string("SETTINGS:");
static const std::string pkcs11_key("key_id");
if (path.find(settings_string) == 0) {
std::string::size_type idx = path.find(pkcs11_key);
if (idx != std::string::npos)
idx = path.find_first_not_of(kWhitespaceASCII, idx + pkcs11_key.length());
if (idx != std::string::npos && path[idx] == '=')
return true;
}
return false;
}
void WifiConfigView::Init() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
int column_view_set_id = 0;
views::ColumnSet* column_set = layout->AddColumnSet(column_view_set_id);
// Label
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
// Textfield
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, kPasswordWidth);
// Password visible button
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_NETWORK_ID)));
if (other_network_) {
ssid_textfield_ = new views::Textfield(views::Textfield::STYLE_DEFAULT);
ssid_textfield_->SetController(this);
layout->AddView(ssid_textfield_);
} else {
views::Label* label = new views::Label(ASCIIToWide(wifi_.name()));
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(label);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
// Certificates stored in a pkcs11 device can not be browsed
// and do not require a passphrase.
bool certificate_in_pkcs11 = false;
// Add ID and cert password if we're using 802.1x
// XXX we're cheating and assuming 802.1x means EAP-TLS - not true
// in general, but very common. WPA Supplicant doesn't report the
// EAP type because it's unknown until the process begins, and we'd
// need some kind of callback.
if (wifi_.encrypted() && wifi_.encryption() == SECURITY_8021X) {
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_IDENTITY)));
identity_textfield_ = new views::Textfield(
views::Textfield::STYLE_DEFAULT);
identity_textfield_->SetController(this);
if (!wifi_.identity().empty())
identity_textfield_->SetText(UTF8ToUTF16(wifi_.identity()));
layout->AddView(identity_textfield_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, column_view_set_id);
layout->AddView(new views::Label(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT)));
if (!wifi_.cert_path().empty()) {
certificate_path_ = wifi_.cert_path();
certificate_in_pkcs11 = is_certificate_in_pkcs11(certificate_path_);
}
if (certificate_in_pkcs11) {
std::wstring label = l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_INSTALLED);
views::Label* cert_text = new views::Label(label);
cert_text->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
layout->AddView(cert_text);
} else {
std::wstring label;
if (!certificate_path_.empty())
label = UTF8ToWide(certificate_path_);
else
label = l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_CERT_BUTTON);
certificate_browse_button_ = new views::NativeButton(this, label);
layout->AddView(certificate_browse_button_);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// Add passphrase if other_network or wifi is encrypted.
if (other_network_ || (wifi_.encrypted() && !certificate_in_pkcs11)) {
layout->StartRow(0, column_view_set_id);
int label_text_id;
if (wifi_.encryption() == SECURITY_8021X)
label_text_id =
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PRIVATE_KEY_PASSWORD;
else
label_text_id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_PASSPHRASE;
layout->AddView(new views::Label(l10n_util::GetString(label_text_id)));
passphrase_textfield_ = new views::Textfield(
views::Textfield::STYLE_PASSWORD);
passphrase_textfield_->SetController(this);
if (!wifi_.passphrase().empty())
passphrase_textfield_->SetText(UTF8ToUTF16(wifi_.passphrase()));
layout->AddView(passphrase_textfield_);
// Password visible button.
passphrase_visible_button_ = new views::ImageButton(this);
passphrase_visible_button_->SetImage(views::ImageButton::BS_NORMAL,
ResourceBundle::GetSharedInstance().
GetBitmapNamed(IDR_STATUSBAR_NETWORK_SECURE));
passphrase_visible_button_->SetImageAlignment(
views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE);
layout->AddView(passphrase_visible_button_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// If there's an error, add an error message label.
// Right now, only displaying bad_passphrase and bad_wepkey errors.
if (wifi_.error() == ERROR_BAD_PASSPHRASE ||
wifi_.error() == ERROR_BAD_WEPKEY) {
layout->StartRow(0, column_view_set_id);
layout->SkipColumns(1);
int id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_PASSPHRASE;
if (wifi_.error() == ERROR_BAD_WEPKEY)
id = IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_BAD_WEPKEY;
views::Label* label_error = new views::Label(l10n_util::GetString(id));
label_error->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
label_error->SetColor(SK_ColorRED);
layout->AddView(label_error);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
// Autoconnect checkbox
// Only show if this network is already remembered (a favorite).
if (wifi_.favorite()) {
autoconnect_checkbox_ = new views::Checkbox(l10n_util::GetString(
IDS_OPTIONS_SETTINGS_INTERNET_OPTIONS_AUTO_CONNECT));
// For other network, default to autoconnect.
bool autoconnect = other_network_ || wifi_.auto_connect();
autoconnect_checkbox_->SetChecked(autoconnect);
layout->StartRow(0, column_view_set_id);
layout->AddView(autoconnect_checkbox_, 3, 1);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kPauseWhenScriptIsRunning[] =
L"files/devtools/pause_when_script_is_running.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
DISABLED_TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<commit_msg>Disable DevTools sanity tests pending investigation.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kPauseWhenScriptIsRunning[] =
L"files/devtools/pause_when_script_is_running.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
DISABLED_TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
void OpenWebInspector(const std::wstring& page_url) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(page_url);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetSelectedTabContents();
RenderViewHost* inspected_rvh = tab->render_view_host();
DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
devtools_manager->OpenDevToolsWindow(inspected_rvh);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh);
DevToolsWindow* window = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void AssertTrue(const std::string& expr) {
AssertEquals("true", expr);
}
void AssertEquals(const std::string& expected, const std::string& expr) {
std::string call = StringPrintf(
"try {"
" var domAgent = devtools.tools.getDomAgent();"
" var netAgent = devtools.tools.getNetAgent();"
" var doc = domAgent.getDocument();"
" window.domAutomationController.send((%s) + '');"
"} catch(e) {"
" window.domAutomationController.send(e.toString());"
"}", expr.c_str());
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_,
L"",
UTF8ToWide(call),
&result));
ASSERT_EQ(expected, result);
}
protected:
TabContents* client_contents_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_OpenWebInspector) {
OpenWebInspector(kSimplePage);
AssertTrue("typeof DevToolsHost == 'object' && !DevToolsHost.isStub");
AssertTrue("!!doc.documentElement");
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_ElementsPanel) {
OpenWebInspector(kSimplePage);
AssertEquals("HTML", "doc.documentElement.nodeName");
AssertTrue("doc.documentElement.hasChildNodes()");
}
// Tests resources panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_ResourcesPanel) {
OpenWebInspector(kSimplePage);
std::string func =
"function() {"
" var tokens = [];"
" var resources = netAgent.resources_;"
" for (var id in resources) {"
" tokens.push(resources[id].lastPathComponent);"
" }"
" return tokens.join(',');"
"}()";
AssertEquals("simple_page.html", func);
}
} // namespace
<commit_msg>DevTools: Enable dev tools ui sanity tests, take 2. Review URL: http://codereview.chromium.org/115560<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
void OpenWebInspector(const std::wstring& page_url) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(page_url);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetSelectedTabContents();
RenderViewHost* inspected_rvh = tab->render_view_host();
DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
devtools_manager->OpenDevToolsWindow(inspected_rvh);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh);
DevToolsWindow* window = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void AssertTrue(const std::string& expr) {
AssertEquals("true", expr);
}
void AssertEquals(const std::string& expected, const std::string& expr) {
std::string call = StringPrintf(
"try {"
" var domAgent = devtools.tools.getDomAgent();"
" var netAgent = devtools.tools.getNetAgent();"
" var doc = domAgent.getDocument();"
" window.domAutomationController.send((%s) + '');"
"} catch(e) {"
" window.domAutomationController.send(e.toString());"
"}", expr.c_str());
std::string result;
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_,
L"",
UTF8ToWide(call),
&result));
ASSERT_EQ(expected, result);
}
protected:
TabContents* client_contents_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, OpenWebInspector) {
OpenWebInspector(kSimplePage);
AssertTrue("typeof DevToolsHost == 'object' && !DevToolsHost.isStub");
AssertTrue("!!doc.documentElement");
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, ElementsPanel) {
OpenWebInspector(kSimplePage);
AssertEquals("HTML", "doc.documentElement.nodeName");
AssertTrue("doc.documentElement.hasChildNodes()");
}
// Tests resources panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, ResourcesPanel) {
OpenWebInspector(kSimplePage);
std::string func =
"function() {"
" var tokens = [];"
" var resources = WebInspector.resources;"
" for (var id in resources) {"
" tokens.push(resources[id].lastPathComponent);"
" }"
" return tokens.join(',');"
"}()";
AssertEquals("simple_page.html", func);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Fails after WebKit roll 69808:70011, http://crbug.com/59727.
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestEnableResourcesTab DISABLED_TestEnableResourcesTab
#else
#define MAYBE_TestEnableResourcesTab TestEnableResourcesTab
#endif // defined(OS_LINUX) || defined(OS_WIN)
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
} // namespace
<commit_msg>Disable DevToolsSanityTest.TestProfilerTab, flakily times out.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Fails after WebKit roll 69808:70011, http://crbug.com/59727.
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestEnableResourcesTab DISABLED_TestEnableResourcesTab
#else
#define MAYBE_TestEnableResourcesTab TestEnableResourcesTab
#endif // defined(OS_LINUX) || defined(OS_WIN)
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests profiler panel.
// Disabled, http://crbug.com/68447.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
} // namespace
<|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/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
} // namespace
<commit_msg>Mark DevToolsSanityTest.TestPauseWhenScriptIsRunning as flaky.<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/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
"chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(base::StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionService* service = browser()->profile()->GetExtensionService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
RunTest("testNetworkTiming", kSlowTestPage);
}
// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
RunTest("testNetworkSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
RunTest("testNetworkSyncSize", kChunkedTestPage);
}
// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/backing_store.h"
BackingStore::BackingStore(const gfx::Size& size)
: size_(size) {
if (!canvas_.initialize(size.width(), size.height(), true))
SK_CRASH();
}
BackingStore::~BackingStore() {
}
bool BackingStore::PaintRect(base::ProcessHandle process,
BitmapWireData bitmap,
const gfx::Rect& bitmap_rect) {
if (bitmap.width() != bitmap_rect.width() ||
bitmap.height() != bitmap_rect.height() ||
bitmap.config() != SkBitmap::kARGB_8888_Config) {
return false;
}
canvas_.drawBitmap(bitmap, bitmap_rect.x(), bitmap_rect.y());
return true;
}
void BackingStore::ScrollRect(base::ProcessHandle process,
BitmapWireData bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
// TODO(port): implement scrolling
NOTIMPLEMENTED();
}
<commit_msg>POSIX: Backing store scrolling.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/backing_store.h"
#include "base/logging.h"
#include "skia/ext/platform_canvas.h"
#include "skia/include/SkBitmap.h"
#include "skia/include/SkCanvas.h"
BackingStore::BackingStore(const gfx::Size& size)
: size_(size) {
if (!canvas_.initialize(size.width(), size.height(), true))
SK_CRASH();
}
BackingStore::~BackingStore() {
}
bool BackingStore::PaintRect(base::ProcessHandle process,
BitmapWireData bitmap,
const gfx::Rect& bitmap_rect) {
if (bitmap.width() != bitmap_rect.width() ||
bitmap.height() != bitmap_rect.height() ||
bitmap.config() != SkBitmap::kARGB_8888_Config) {
return false;
}
canvas_.drawBitmap(bitmap, bitmap_rect.x(), bitmap_rect.y());
return true;
}
// Return the given value, clipped to 0..max (inclusive)
static int RangeClip(int value, int max) {
return std::min(max, std::max(value, 0));
}
void BackingStore::ScrollRect(base::ProcessHandle process,
BitmapWireData bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
// WARNING: this is temporary code until a real solution is found for Mac and
// Linux.
//
// On Windows, there's a ScrollDC call which performs horiz and vertical
// scrolling
//
// clip_rect: MSDN says "The only bits that will be painted are the
// bits that remain inside this rectangle after the scroll operation has been
// completed."
//
// The Windows code always sets the whole backing store as the source of the
// scroll. Thus, we only have to worry about pixels which will end up inside
// the clipping rectangle. (Note that the clipping rectangle is not
// translated by the scrol.)
// We only support scrolling in one direction at a time.
DCHECK(dx == 0 || dy == 0);
if (bitmap.width() != bitmap_rect.width() ||
bitmap.height() != bitmap_rect.height() ||
bitmap.config() != SkBitmap::kARGB_8888_Config) {
return;
}
// We assume that |clip_rect| is within the backing store.
const SkBitmap &backing_bitmap = canvas_.getDevice()->accessBitmap(true);
const int stride = backing_bitmap.rowBytes();
uint8_t* x = static_cast<uint8_t*>(backing_bitmap.getPixels());
if (dx) {
// Horizontal scroll. Positive values of |dx| scroll right.
// We know that |clip_rect| is the destination rectangle. The source
// rectangle, in an infinite world, would be the destination rectangle
// translated by -dx. However, we can't pull pixels from beyound the
// edge of the backing store. By truncating the source rectangle to the
// backing store, we might have made it thinner, thus we find the final
// dest rectangle by translating the resulting source rectangle back.
const int bs_width = canvas_.getDevice()->width();
const int src_rect_left = RangeClip(clip_rect.x() - dx, bs_width);
const int src_rect_right = RangeClip(clip_rect.right() - dx, bs_width);
const int dest_rect_left = RangeClip(src_rect_left + dx, bs_width);
const int dest_rect_right = RangeClip(src_rect_right + dx, bs_width);
DCHECK(dest_rect_right >= dest_rect_left);
DCHECK(src_rect_right >= src_rect_left);
DCHECK(dest_rect_right - dest_rect_left ==
src_rect_right - src_rect_left);
// This is the number of bytes to move per line at 4 bytes per pixel.
const int len = (dest_rect_right - dest_rect_left) * 4;
// Position the pixel data pointer at the top-left corner of the dest rect
x += clip_rect.y() * stride;
x += clip_rect.x() * 4;
// This is the number of bytes to reach left in order to find the source
// rectangle. (Will be negative for a left scroll.)
const int left_reach = dest_rect_left - src_rect_left;
for (int y = clip_rect.y(); y < clip_rect.bottom(); ++y) {
// Note that overlapping regions requires memmove, not memcpy.
memmove(x, x + left_reach, len);
x += stride;
}
} else {
// Vertical scroll. Positive values of |dy| scroll down.
// The logic is very similar to the horizontal case, above.
const int bs_height = canvas_.getDevice()->height();
const int src_rect_top = RangeClip(clip_rect.y() - dy, bs_height);
const int src_rect_bottom = RangeClip(clip_rect.bottom() - dy, bs_height);
const int dest_rect_top = RangeClip(src_rect_top + dy, bs_height);
const int dest_rect_bottom = RangeClip(src_rect_bottom + dy, bs_height);
const int len = clip_rect.width() * 4;
DCHECK(dest_rect_bottom >= dest_rect_top);
DCHECK(src_rect_bottom >= src_rect_top);
// We need to consider the two directions separately here because the order
// of copying rows must vary to avoid writing data which we later need to
// read.
if (dy > 0) {
// Scrolling down; dest rect is above src rect.
// Position the pixel data pointer at the top-left corner of the dest
// rect.
x += dest_rect_top * stride;
x += clip_rect.x() * 4;
DCHECK(dest_rect_top <= src_rect_top);
const int down_reach_bytes = stride * (src_rect_top - dest_rect_top);
for (int y = dest_rect_top; y < dest_rect_bottom; ++y) {
memcpy(x, x + down_reach_bytes, len);
x += stride;
}
} else {
// Scrolling up; dest rect is below src rect.
// Position the pixel data pointer at the bottom-left corner of the dest
// rect.
x += (dest_rect_bottom - 1) * stride;
x += clip_rect.x() * 4;
DCHECK(src_rect_top <= dest_rect_top);
const int up_reach_bytes = stride * (dest_rect_bottom - src_rect_bottom);
for (int y = dest_rect_bottom - 1; y >= dest_rect_top; --y) {
memcpy(x, x - up_reach_bytes, len);
x -= stride;
}
}
}
// Now paint the new bitmap data.
canvas_.drawBitmap(bitmap, bitmap_rect.x(), bitmap_rect.y());
return;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 House of Life Property Ltd. All rights reserved.
// Copyright (c) 2012 Crystalnix <vgachkaylo@crystalnix.com>
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/facebook_chat/chat_popup.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "ui/views/layout/fill_layout.h"
using content::WebContents;
// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ChatPopup::kMinWidth = 25;
const int ChatPopup::kMinHeight = 25;
const int ChatPopup::kMaxWidth = 800;
const int ChatPopup::kMaxHeight = 600;
ChatPopup::ChatPopup(
Browser* browser,
ExtensionHost* host,
views::View* anchor_view,
BitpopBubbleBorder::ArrowLocation arrow_location)
: BitpopBubbleDelegateView(anchor_view, arrow_location),
extension_host_(host) {
// Adjust the margin so that contents fit better.
set_margin(BitpopBubbleBorder::GetCornerRadius() / 2);
SetLayoutManager(new views::FillLayout());
AddChildView(host->view());
host->view()->SetContainer(this);
#if defined(OS_WIN) && !defined(USE_AURA)
// Use OnNativeFocusChange to check for child window activation on deactivate.
set_close_on_deactivate(false);
#else
set_close_on_deactivate(false); // it's actually the same, leaved to
// preserve original source structure
#endif
// Wait to show the popup until the contained host finishes loading.
registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::Source<WebContents>(host->host_contents()));
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
content::Source<Profile>(host->profile()));
}
ChatPopup::~ChatPopup() {
views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);
}
void ChatPopup::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:
DCHECK(content::Source<WebContents>(host()->host_contents()) == source);
// Show when the content finishes loading and its width is computed.
ShowBubble();
break;
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (content::Details<ExtensionHost>(host()) == details)
GetWidget()->Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
}
}
void ChatPopup::OnExtensionPreferredSizeChanged(ExtensionView* view) {
SizeToContents();
}
gfx::Size ChatPopup::GetPreferredSize() {
// Constrain the size to popup min/max.
gfx::Size sz = views::View::GetPreferredSize();
sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));
sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
return sz;
}
void ChatPopup::OnNativeFocusChange(gfx::NativeView focused_before,
gfx::NativeView focused_now) {
// TODO(msw): Implement something equivalent for Aura. See crbug.com/106958
#if defined(OS_WIN) && !defined(USE_AURA)
// Don't close if a child of this window is activated (only needed on Win).
// ChatPopups can create Javascipt dialogs; see crbug.com/106723.
gfx::NativeView this_window = GetWidget()->GetNativeView();
gfx::NativeView parent_window = anchor_view()->GetWidget()->GetNativeView();
if (focused_now == this_window ||
::GetWindow(focused_now, GW_OWNER) == this_window) {
return;
}
gfx::NativeView focused_parent = focused_now;
while (focused_parent = ::GetParent(focused_parent)) {
if (this_window == focused_parent)
return;
if (parent_window == focused_parent)
GetWidget()->Close();
}
//GetWidget()->Close();
#endif
}
// static
ChatPopup* ChatPopup::ShowPopup(
const GURL& url,
Browser* browser,
views::View* anchor_view,
BitpopBubbleBorder::ArrowLocation arrow_location) {
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
ExtensionHost* host = manager->CreatePopupHost(url, browser);
ChatPopup* popup = new ChatPopup(browser, host, anchor_view,
arrow_location);
BitpopBubbleDelegateView::CreateBubble(popup);
// If the host had somehow finished loading, then we'd miss the notification
// and not show. This seems to happen in single-process mode.
if (host->did_stop_loading())
popup->ShowBubble();
return popup;
}
void ChatPopup::ShowBubble() {
Show();
// Focus on the host contents when the bubble is first shown.
host()->host_contents()->Focus();
// Listen for widget focus changes after showing (used for non-aura win).
views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);
}
<commit_msg>Instant showing of chat popups.<commit_after>// Copyright (c) 2012 House of Life Property Ltd. All rights reserved.
// Copyright (c) 2012 Crystalnix <vgachkaylo@crystalnix.com>
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/facebook_chat/chat_popup.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "ui/views/layout/fill_layout.h"
using content::WebContents;
// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ChatPopup::kMinWidth = 25;
const int ChatPopup::kMinHeight = 25;
const int ChatPopup::kMaxWidth = 203 + 4;
const int ChatPopup::kMaxHeight = 350 + 4 + 7;
ChatPopup::ChatPopup(
Browser* browser,
ExtensionHost* host,
views::View* anchor_view,
BitpopBubbleBorder::ArrowLocation arrow_location)
: BitpopBubbleDelegateView(anchor_view, arrow_location),
extension_host_(host) {
// Adjust the margin so that contents fit better.
set_margin(BitpopBubbleBorder::GetCornerRadius() / 2);
SetLayoutManager(new views::FillLayout());
AddChildView(host->view());
host->view()->SetContainer(this);
#if defined(OS_WIN) && !defined(USE_AURA)
// Use OnNativeFocusChange to check for child window activation on deactivate.
set_close_on_deactivate(false);
#else
set_close_on_deactivate(false); // it's actually the same, leaved to
// preserve original source structure
#endif
// Wait to show the popup until the contained host finishes loading.
registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::Source<WebContents>(host->host_contents()));
// Listen for the containing view calling window.close();
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
content::Source<Profile>(host->profile()));
}
ChatPopup::~ChatPopup() {
views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);
}
void ChatPopup::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:
DCHECK(content::Source<WebContents>(host()->host_contents()) == source);
// Show when the content finishes loading and its width is computed.
host()->host_contents()->Focus();
break;
case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (content::Details<ExtensionHost>(host()) == details)
GetWidget()->Close();
break;
default:
NOTREACHED() << L"Received unexpected notification";
}
}
void ChatPopup::OnExtensionPreferredSizeChanged(ExtensionView* view) {
SizeToContents();
}
gfx::Size ChatPopup::GetPreferredSize() {
// Constrain the size to popup min/max.
gfx::Size sz = views::View::GetPreferredSize();
sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));
sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
return sz;
}
void ChatPopup::OnNativeFocusChange(gfx::NativeView focused_before,
gfx::NativeView focused_now) {
// TODO(msw): Implement something equivalent for Aura. See crbug.com/106958
#if defined(OS_WIN) && !defined(USE_AURA)
// Don't close if a child of this window is activated (only needed on Win).
// ChatPopups can create Javascipt dialogs; see crbug.com/106723.
gfx::NativeView this_window = GetWidget()->GetNativeView();
gfx::NativeView parent_window = anchor_view()->GetWidget()->GetNativeView();
if (focused_now == this_window ||
::GetWindow(focused_now, GW_OWNER) == this_window) {
return;
}
gfx::NativeView focused_parent = focused_now;
while (focused_parent = ::GetParent(focused_parent)) {
if (this_window == focused_parent)
return;
if (parent_window == focused_parent)
GetWidget()->Close();
}
//GetWidget()->Close();
#endif
}
// static
ChatPopup* ChatPopup::ShowPopup(
const GURL& url,
Browser* browser,
views::View* anchor_view,
BitpopBubbleBorder::ArrowLocation arrow_location) {
ExtensionProcessManager* manager =
browser->profile()->GetExtensionProcessManager();
ExtensionHost* host = manager->CreatePopupHost(url, browser);
ChatPopup* popup = new ChatPopup(browser, host, anchor_view,
arrow_location);
BitpopBubbleDelegateView::CreateBubble(popup);
// If the host had somehow finished loading, then we'd miss the notification
// and not show. This seems to happen in single-process mode.
//if (host->did_stop_loading())
popup->ShowBubble();
return popup;
}
void ChatPopup::ShowBubble() {
Show();
// Focus on the host contents when the bubble is first shown.
// Listen for widget focus changes after showing (used for non-aura win).
views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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.
//
// This file defines specific implementation of BrowserDistribution class for
// Google Chrome.
#include "chrome/installer/util/google_chrome_distribution.h"
#include <atlbase.h>
#include <windows.h>
#include <msi.h>
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/wmi_util.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/util_constants.h"
#include "installer_util_strings.h"
namespace {
// Substitute the locale parameter in uninstall URL with whatever
// Google Update tells us is the locale. In case we fail to find
// the locale, we use US English.
std::wstring GetUninstallSurveyUrl() {
std::wstring kSurveyUrl = L"http://www.google.com/support/chrome/bin/"
L"request.py?hl=$1&contact_type=uninstall";
std::wstring language;
if (!GoogleUpdateSettings::GetLanguage(&language))
language = L"en-US"; // Default to US English.
return ReplaceStringPlaceholders(kSurveyUrl.c_str(), language.c_str(), NULL);
}
}
bool GoogleChromeDistribution::BuildUninstallMetricsString(
DictionaryValue* uninstall_metrics_dict, std::wstring* metrics) {
DCHECK(NULL != metrics);
bool has_values = false;
DictionaryValue::key_iterator iter(uninstall_metrics_dict->begin_keys());
for (; iter != uninstall_metrics_dict->end_keys(); ++iter) {
has_values = true;
metrics->append(L"&");
metrics->append(*iter);
metrics->append(L"=");
std::wstring value;
uninstall_metrics_dict->GetString(*iter, &value);
metrics->append(value);
}
return has_values;
}
bool GoogleChromeDistribution::ExtractUninstallMetricsFromFile(
const std::wstring& file_path, std::wstring* uninstall_metrics_string) {
JSONFileValueSerializer json_serializer(FilePath::FromWStringHack(file_path));
std::string json_error_string;
scoped_ptr<Value> root(json_serializer.Deserialize(NULL));
if (!root.get())
return false;
// Preferences should always have a dictionary root.
if (!root->IsType(Value::TYPE_DICTIONARY))
return false;
return ExtractUninstallMetrics(*static_cast<DictionaryValue*>(root.get()),
uninstall_metrics_string);
}
bool GoogleChromeDistribution::ExtractUninstallMetrics(
const DictionaryValue& root, std::wstring* uninstall_metrics_string) {
// Make sure that the user wants us reporting metrics. If not, don't
// add our uninstall metrics.
bool metrics_reporting_enabled = false;
if (!root.GetBoolean(prefs::kMetricsReportingEnabled,
&metrics_reporting_enabled) ||
!metrics_reporting_enabled) {
return false;
}
DictionaryValue* uninstall_metrics_dict;
if (!root.HasKey(installer_util::kUninstallMetricsName) ||
!root.GetDictionary(installer_util::kUninstallMetricsName,
&uninstall_metrics_dict)) {
return false;
}
if (!BuildUninstallMetricsString(uninstall_metrics_dict,
uninstall_metrics_string)) {
return false;
}
return true;
}
void GoogleChromeDistribution::DoPostUninstallOperations(
const installer::Version& version, const std::wstring& local_data_path,
const std::wstring& distribution_data) {
// Send the Chrome version and OS version as params to the form.
// It would be nice to send the locale, too, but I don't see an
// easy way to get that in the existing code. It's something we
// can add later, if needed.
// We depend on installed_version.GetString() not having spaces or other
// characters that need escaping: 0.2.13.4. Should that change, we will
// need to escape the string before using it in a URL.
const std::wstring kVersionParam = L"crversion";
const std::wstring kVersion = version.GetString();
const std::wstring kOSParam = L"os";
std::wstring os_version = L"na";
OSVERSIONINFO version_info;
version_info.dwOSVersionInfoSize = sizeof(version_info);
if (GetVersionEx(&version_info)) {
os_version = StringPrintf(L"%d.%d.%d", version_info.dwMajorVersion,
version_info.dwMinorVersion,
version_info.dwBuildNumber);
}
FilePath iexplore;
if (!PathService::Get(base::DIR_PROGRAM_FILES, &iexplore))
return;
iexplore = iexplore.AppendASCII("Internet Explorer");
iexplore = iexplore.AppendASCII("iexplore.exe");
std::wstring command = iexplore.value() + L" " + GetUninstallSurveyUrl() +
L"&" + kVersionParam + L"=" + kVersion + L"&" + kOSParam + L"=" +
os_version;
std::wstring uninstall_metrics;
if (ExtractUninstallMetricsFromFile(local_data_path, &uninstall_metrics)) {
// The user has opted into anonymous usage data collection, so append
// metrics and distribution data.
command += uninstall_metrics;
if (!distribution_data.empty()) {
command += L"&";
command += distribution_data;
}
}
int pid = 0;
WMIProcessUtil::Launch(command, &pid);
}
std::wstring GoogleChromeDistribution::GetApplicationName() {
const std::wstring& product_name =
installer_util::GetLocalizedString(IDS_PRODUCT_NAME_BASE);
return product_name;
}
std::wstring GoogleChromeDistribution::GetAlternateApplicationName() {
const std::wstring& alt_product_name =
installer_util::GetLocalizedString(IDS_OEM_MAIN_SHORTCUT_NAME_BASE);
return alt_product_name;
}
std::wstring GoogleChromeDistribution::GetInstallSubDir() {
return L"Google\\Chrome";
}
std::wstring GoogleChromeDistribution::GetNewGoogleUpdateApKey(
bool diff_install, installer_util::InstallStatus status,
const std::wstring& value) {
// Magic suffix that we need to add or remove to "ap" key value.
const std::wstring kMagicSuffix = L"-full";
bool has_magic_string = false;
if ((value.length() >= kMagicSuffix.length()) &&
(value.rfind(kMagicSuffix) == (value.length() - kMagicSuffix.length()))) {
LOG(INFO) << "Incremental installer failure key already set.";
has_magic_string = true;
}
std::wstring new_value(value);
if ((!diff_install || !GetInstallReturnCode(status)) && has_magic_string) {
LOG(INFO) << "Removing failure key from value " << value;
new_value = value.substr(0, value.length() - kMagicSuffix.length());
} else if ((diff_install && GetInstallReturnCode(status)) &&
!has_magic_string) {
LOG(INFO) << "Incremental installer failed, setting failure key.";
new_value.append(kMagicSuffix);
}
return new_value;
}
std::wstring GoogleChromeDistribution::GetPublisherName() {
const std::wstring& publisher_name =
installer_util::GetLocalizedString(IDS_ABOUT_VERSION_COMPANY_NAME_BASE);
return publisher_name;
}
std::wstring GoogleChromeDistribution::GetAppDescription() {
const std::wstring& app_description =
installer_util::GetLocalizedString(IDS_SHORTCUT_TOOLTIP_BASE);
return app_description;
}
int GoogleChromeDistribution::GetInstallReturnCode(
installer_util::InstallStatus status) {
switch (status) {
case installer_util::FIRST_INSTALL_SUCCESS:
case installer_util::INSTALL_REPAIRED:
case installer_util::NEW_VERSION_UPDATED:
case installer_util::HIGHER_VERSION_EXISTS:
return 0; // For Google Update's benefit we need to return 0 for success
default:
return status;
}
}
std::wstring GoogleChromeDistribution::GetStateKey() {
std::wstring key(google_update::kRegPathClientState);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
std::wstring GoogleChromeDistribution::GetStateMediumKey() {
std::wstring key(google_update::kRegPathClientStateMedium);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
std::wstring GoogleChromeDistribution::GetStatsServerURL() {
return L"https://clients4.google.com/firefox/metrics/collect";
}
std::wstring GoogleChromeDistribution::GetDistributionData(RegKey* key) {
DCHECK(NULL != key);
std::wstring sub_key(google_update::kRegPathClientState);
sub_key.append(L"\\");
sub_key.append(google_update::kChromeGuid);
RegKey client_state_key(key->Handle(), sub_key.c_str());
std::wstring result;
std::wstring brand_value;
if (client_state_key.ReadValue(google_update::kRegRLZBrandField,
&brand_value)) {
result = google_update::kRegRLZBrandField;
result.append(L"=");
result.append(brand_value);
}
return result;
}
std::wstring GoogleChromeDistribution::GetUninstallLinkName() {
const std::wstring& link_name =
installer_util::GetLocalizedString(IDS_UNINSTALL_CHROME_BASE);
return link_name;
}
std::wstring GoogleChromeDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"
L"Google Chrome";
}
std::wstring GoogleChromeDistribution::GetVersionKey() {
std::wstring key(google_update::kRegPathClients);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
// This method checks if we need to change "ap" key in Google Update to try
// full installer as fall back method in case incremental installer fails.
// - If incremental installer fails we append a magic string ("-full"), if
// it is not present already, so that Google Update server next time will send
// full installer to update Chrome on the local machine
// - If we are currently running full installer, we remove this magic
// string (if it is present) regardless of whether installer failed or not.
// There is no fall-back for full installer :)
void GoogleChromeDistribution::UpdateDiffInstallStatus(bool system_install,
bool incremental_install, installer_util::InstallStatus install_status) {
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
RegKey key;
std::wstring ap_key_value;
std::wstring reg_key(google_update::kRegPathClientState);
reg_key.append(L"\\");
reg_key.append(google_update::kChromeGuid);
if (!key.Open(reg_root, reg_key.c_str(), KEY_ALL_ACCESS) ||
!key.ReadValue(google_update::kRegApField, &ap_key_value)) {
LOG(INFO) << "Application key not found.";
if (!incremental_install || !GetInstallReturnCode(install_status)) {
LOG(INFO) << "Returning without changing application key.";
key.Close();
return;
} else if (!key.Valid()) {
reg_key.assign(google_update::kRegPathClientState);
if (!key.Open(reg_root, reg_key.c_str(), KEY_ALL_ACCESS) ||
!key.CreateKey(google_update::kChromeGuid, KEY_ALL_ACCESS)) {
LOG(ERROR) << "Failed to create application key.";
key.Close();
return;
}
}
}
std::wstring new_value = GoogleChromeDistribution::GetNewGoogleUpdateApKey(
incremental_install, install_status, ap_key_value);
if ((new_value.compare(ap_key_value) != 0) &&
!key.WriteValue(google_update::kRegApField, new_value.c_str())) {
LOG(ERROR) << "Failed to write value " << new_value
<< " to the registry field " << google_update::kRegApField;
}
key.Close();
}
<commit_msg>Adding ap key inclusion to uninstall metrics.<commit_after>// Copyright (c) 2006-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.
//
// This file defines specific implementation of BrowserDistribution class for
// Google Chrome.
#include "chrome/installer/util/google_chrome_distribution.h"
#include <atlbase.h>
#include <windows.h>
#include <msi.h>
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/wmi_util.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/util_constants.h"
#include "installer_util_strings.h"
namespace {
// Substitute the locale parameter in uninstall URL with whatever
// Google Update tells us is the locale. In case we fail to find
// the locale, we use US English.
std::wstring GetUninstallSurveyUrl() {
std::wstring kSurveyUrl = L"http://www.google.com/support/chrome/bin/"
L"request.py?hl=$1&contact_type=uninstall";
std::wstring language;
if (!GoogleUpdateSettings::GetLanguage(&language))
language = L"en-US"; // Default to US English.
return ReplaceStringPlaceholders(kSurveyUrl.c_str(), language.c_str(), NULL);
}
}
bool GoogleChromeDistribution::BuildUninstallMetricsString(
DictionaryValue* uninstall_metrics_dict, std::wstring* metrics) {
DCHECK(NULL != metrics);
bool has_values = false;
DictionaryValue::key_iterator iter(uninstall_metrics_dict->begin_keys());
for (; iter != uninstall_metrics_dict->end_keys(); ++iter) {
has_values = true;
metrics->append(L"&");
metrics->append(*iter);
metrics->append(L"=");
std::wstring value;
uninstall_metrics_dict->GetString(*iter, &value);
metrics->append(value);
}
return has_values;
}
bool GoogleChromeDistribution::ExtractUninstallMetricsFromFile(
const std::wstring& file_path, std::wstring* uninstall_metrics_string) {
JSONFileValueSerializer json_serializer(FilePath::FromWStringHack(file_path));
std::string json_error_string;
scoped_ptr<Value> root(json_serializer.Deserialize(NULL));
if (!root.get())
return false;
// Preferences should always have a dictionary root.
if (!root->IsType(Value::TYPE_DICTIONARY))
return false;
return ExtractUninstallMetrics(*static_cast<DictionaryValue*>(root.get()),
uninstall_metrics_string);
}
bool GoogleChromeDistribution::ExtractUninstallMetrics(
const DictionaryValue& root, std::wstring* uninstall_metrics_string) {
// Make sure that the user wants us reporting metrics. If not, don't
// add our uninstall metrics.
bool metrics_reporting_enabled = false;
if (!root.GetBoolean(prefs::kMetricsReportingEnabled,
&metrics_reporting_enabled) ||
!metrics_reporting_enabled) {
return false;
}
DictionaryValue* uninstall_metrics_dict;
if (!root.HasKey(installer_util::kUninstallMetricsName) ||
!root.GetDictionary(installer_util::kUninstallMetricsName,
&uninstall_metrics_dict)) {
return false;
}
if (!BuildUninstallMetricsString(uninstall_metrics_dict,
uninstall_metrics_string)) {
return false;
}
return true;
}
void GoogleChromeDistribution::DoPostUninstallOperations(
const installer::Version& version, const std::wstring& local_data_path,
const std::wstring& distribution_data) {
// Send the Chrome version and OS version as params to the form.
// It would be nice to send the locale, too, but I don't see an
// easy way to get that in the existing code. It's something we
// can add later, if needed.
// We depend on installed_version.GetString() not having spaces or other
// characters that need escaping: 0.2.13.4. Should that change, we will
// need to escape the string before using it in a URL.
const std::wstring kVersionParam = L"crversion";
const std::wstring kVersion = version.GetString();
const std::wstring kOSParam = L"os";
std::wstring os_version = L"na";
OSVERSIONINFO version_info;
version_info.dwOSVersionInfoSize = sizeof(version_info);
if (GetVersionEx(&version_info)) {
os_version = StringPrintf(L"%d.%d.%d", version_info.dwMajorVersion,
version_info.dwMinorVersion,
version_info.dwBuildNumber);
}
FilePath iexplore;
if (!PathService::Get(base::DIR_PROGRAM_FILES, &iexplore))
return;
iexplore = iexplore.AppendASCII("Internet Explorer");
iexplore = iexplore.AppendASCII("iexplore.exe");
std::wstring command = iexplore.value() + L" " + GetUninstallSurveyUrl() +
L"&" + kVersionParam + L"=" + kVersion + L"&" + kOSParam + L"=" +
os_version;
std::wstring uninstall_metrics;
if (ExtractUninstallMetricsFromFile(local_data_path, &uninstall_metrics)) {
// The user has opted into anonymous usage data collection, so append
// metrics and distribution data.
command += uninstall_metrics;
if (!distribution_data.empty()) {
command += L"&";
command += distribution_data;
}
}
int pid = 0;
WMIProcessUtil::Launch(command, &pid);
}
std::wstring GoogleChromeDistribution::GetApplicationName() {
const std::wstring& product_name =
installer_util::GetLocalizedString(IDS_PRODUCT_NAME_BASE);
return product_name;
}
std::wstring GoogleChromeDistribution::GetAlternateApplicationName() {
const std::wstring& alt_product_name =
installer_util::GetLocalizedString(IDS_OEM_MAIN_SHORTCUT_NAME_BASE);
return alt_product_name;
}
std::wstring GoogleChromeDistribution::GetInstallSubDir() {
return L"Google\\Chrome";
}
std::wstring GoogleChromeDistribution::GetNewGoogleUpdateApKey(
bool diff_install, installer_util::InstallStatus status,
const std::wstring& value) {
// Magic suffix that we need to add or remove to "ap" key value.
const std::wstring kMagicSuffix = L"-full";
bool has_magic_string = false;
if ((value.length() >= kMagicSuffix.length()) &&
(value.rfind(kMagicSuffix) == (value.length() - kMagicSuffix.length()))) {
LOG(INFO) << "Incremental installer failure key already set.";
has_magic_string = true;
}
std::wstring new_value(value);
if ((!diff_install || !GetInstallReturnCode(status)) && has_magic_string) {
LOG(INFO) << "Removing failure key from value " << value;
new_value = value.substr(0, value.length() - kMagicSuffix.length());
} else if ((diff_install && GetInstallReturnCode(status)) &&
!has_magic_string) {
LOG(INFO) << "Incremental installer failed, setting failure key.";
new_value.append(kMagicSuffix);
}
return new_value;
}
std::wstring GoogleChromeDistribution::GetPublisherName() {
const std::wstring& publisher_name =
installer_util::GetLocalizedString(IDS_ABOUT_VERSION_COMPANY_NAME_BASE);
return publisher_name;
}
std::wstring GoogleChromeDistribution::GetAppDescription() {
const std::wstring& app_description =
installer_util::GetLocalizedString(IDS_SHORTCUT_TOOLTIP_BASE);
return app_description;
}
int GoogleChromeDistribution::GetInstallReturnCode(
installer_util::InstallStatus status) {
switch (status) {
case installer_util::FIRST_INSTALL_SUCCESS:
case installer_util::INSTALL_REPAIRED:
case installer_util::NEW_VERSION_UPDATED:
case installer_util::HIGHER_VERSION_EXISTS:
return 0; // For Google Update's benefit we need to return 0 for success
default:
return status;
}
}
std::wstring GoogleChromeDistribution::GetStateKey() {
std::wstring key(google_update::kRegPathClientState);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
std::wstring GoogleChromeDistribution::GetStateMediumKey() {
std::wstring key(google_update::kRegPathClientStateMedium);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
std::wstring GoogleChromeDistribution::GetStatsServerURL() {
return L"https://clients4.google.com/firefox/metrics/collect";
}
std::wstring GoogleChromeDistribution::GetDistributionData(RegKey* key) {
DCHECK(NULL != key);
std::wstring sub_key(google_update::kRegPathClientState);
sub_key.append(L"\\");
sub_key.append(google_update::kChromeGuid);
RegKey client_state_key(key->Handle(), sub_key.c_str());
std::wstring result;
std::wstring brand_value;
if (client_state_key.ReadValue(google_update::kRegRLZBrandField,
&brand_value)) {
result = google_update::kRegRLZBrandField;
result.append(L"=");
result.append(brand_value);
result.append(L"&");
}
std::wstring ap_value;
// If we fail to read the ap key, send up "&ap=" anyway to indicate
// that this was probably a stable channel release.
client_state_key.ReadValue(google_update::kRegApField, &ap_value);
result.append(google_update::kRegApField);
result.append(L"=");
result.append(ap_value);
return result;
}
std::wstring GoogleChromeDistribution::GetUninstallLinkName() {
const std::wstring& link_name =
installer_util::GetLocalizedString(IDS_UNINSTALL_CHROME_BASE);
return link_name;
}
std::wstring GoogleChromeDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"
L"Google Chrome";
}
std::wstring GoogleChromeDistribution::GetVersionKey() {
std::wstring key(google_update::kRegPathClients);
key.append(L"\\");
key.append(google_update::kChromeGuid);
return key;
}
// This method checks if we need to change "ap" key in Google Update to try
// full installer as fall back method in case incremental installer fails.
// - If incremental installer fails we append a magic string ("-full"), if
// it is not present already, so that Google Update server next time will send
// full installer to update Chrome on the local machine
// - If we are currently running full installer, we remove this magic
// string (if it is present) regardless of whether installer failed or not.
// There is no fall-back for full installer :)
void GoogleChromeDistribution::UpdateDiffInstallStatus(bool system_install,
bool incremental_install, installer_util::InstallStatus install_status) {
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
RegKey key;
std::wstring ap_key_value;
std::wstring reg_key(google_update::kRegPathClientState);
reg_key.append(L"\\");
reg_key.append(google_update::kChromeGuid);
if (!key.Open(reg_root, reg_key.c_str(), KEY_ALL_ACCESS) ||
!key.ReadValue(google_update::kRegApField, &ap_key_value)) {
LOG(INFO) << "Application key not found.";
if (!incremental_install || !GetInstallReturnCode(install_status)) {
LOG(INFO) << "Returning without changing application key.";
key.Close();
return;
} else if (!key.Valid()) {
reg_key.assign(google_update::kRegPathClientState);
if (!key.Open(reg_root, reg_key.c_str(), KEY_ALL_ACCESS) ||
!key.CreateKey(google_update::kChromeGuid, KEY_ALL_ACCESS)) {
LOG(ERROR) << "Failed to create application key.";
key.Close();
return;
}
}
}
std::wstring new_value = GoogleChromeDistribution::GetNewGoogleUpdateApKey(
incremental_install, install_status, ap_key_value);
if ((new_value.compare(ap_key_value) != 0) &&
!key.WriteValue(google_update::kRegApField, new_value.c_str())) {
LOG(ERROR) << "Failed to write value " << new_value
<< " to the registry field " << google_update::kRegApField;
}
key.Close();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "chrome/installer/util/language_selector.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const wchar_t* const kExactMatchCandidates[] = {
L"am", L"ar", L"bg", L"bn", L"ca", L"cs", L"da", L"de", L"el", L"en-gb",
L"en-us", L"es", L"es-419", L"et", L"fa", L"fi", L"fil", L"fr", L"gu", L"hi",
L"hr", L"hu", L"id", L"it", L"iw", L"ja", L"kn", L"ko", L"lt", L"lv", L"ml",
L"mr", L"nl", L"no", L"pl", L"pt-br", L"pt-pt", L"ro", L"ru", L"sk", L"sl",
L"sr", L"sv", L"sw", L"ta", L"te", L"th", L"tr", L"uk", L"vi", L"zh-cn",
L"zh-tw"
};
const wchar_t* const kAliasMatchCandidates[] = {
L"he", L"nb", L"tl", L"zh-chs", L"zh-cht", L"zh-hans", L"zh-hant", L"zh-hk",
L"zh-mo"
};
const wchar_t* const kWildcardMatchCandidates[] = {
L"en-AU",
L"es-CO", L"pt-AB", L"zh-SG"
};
} // namespace
// Test that a language is selected from the system.
TEST(LanguageSelectorTest, DefaultSelection) {
installer::LanguageSelector instance;
EXPECT_FALSE(instance.matched_candidate().empty());
}
// Test some hypothetical candidate sets.
TEST(LanguageSelectorTest, AssortedSelections) {
{
std::wstring candidates[] = {
L"fr-BE", L"fr", L"en"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the exact match to win.
EXPECT_EQ(L"fr", instance.matched_candidate());
}
{
std::wstring candidates[] = {
L"xx-YY", L"cc-Ssss-RR"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the fallback to win.
EXPECT_EQ(L"en-us", instance.matched_candidate());
}
{
std::wstring candidates[] = {
L"zh-SG", L"en-GB"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the alias match to win.
EXPECT_EQ(L"zh-SG", instance.matched_candidate());
}
}
// A fixture for testing sets of single-candidate selections.
class LanguageSelectorMatchCandidateTest
: public ::testing::TestWithParam<const wchar_t*> {
};
TEST_P(LanguageSelectorMatchCandidateTest, TestMatchCandidate) {
installer::LanguageSelector instance(
std::vector<std::wstring>(1, std::wstring(GetParam())));
EXPECT_EQ(GetParam(), instance.matched_candidate());
}
// Test that all existing translations can be found by exact match.
INSTANTIATE_TEST_CASE_P(
TestExactMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kExactMatchCandidates[0],
&kExactMatchCandidates[arraysize(kExactMatchCandidates)]));
// Test the alias matches.
INSTANTIATE_TEST_CASE_P(
TestAliasMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kAliasMatchCandidates[0],
&kAliasMatchCandidates[arraysize(kAliasMatchCandidates)]));
// Test a few wildcard matches.
INSTANTIATE_TEST_CASE_P(
TestWildcardMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kWildcardMatchCandidates[0],
&kWildcardMatchCandidates[arraysize(kWildcardMatchCandidates)]));
// A fixture for testing aliases that match to an expected translation. The
// first member of the tuple is the expected translation, the second is a
// candidate that should be aliased to the expectation.
class LanguageSelectorAliasTest
: public ::testing::TestWithParam< std::tr1::tuple<const wchar_t*,
const wchar_t*> > {
};
// Test that the candidate language maps to the aliased translation.
TEST_P(LanguageSelectorAliasTest, AliasesMatch) {
installer::LanguageSelector instance(
std::vector<std::wstring>(1, std::tr1::get<1>(GetParam())));
EXPECT_EQ(std::tr1::get<0>(GetParam()), instance.selected_translation());
}
INSTANTIATE_TEST_CASE_P(
EnGbAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"en-gb"),
::testing::Values(L"en-au", L"en-ca", L"en-nz", L"en-za")));
INSTANTIATE_TEST_CASE_P(
IwAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"iw"),
::testing::Values(L"he")));
INSTANTIATE_TEST_CASE_P(
NoAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"no"),
::testing::Values(L"nb")));
INSTANTIATE_TEST_CASE_P(
FilAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"fil"),
::testing::Values(L"tl")));
INSTANTIATE_TEST_CASE_P(
ZhCnAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"zh-cn"),
::testing::Values(L"zh-chs", L"zh-hans", L"zh-sg")));
INSTANTIATE_TEST_CASE_P(
ZhTwAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"zh-tw"),
::testing::Values(L"zh-cht", L"zh-hant", L"zh-hk", L"zh-mo")));
// Test that we can get the name of the default language.
TEST(LanguageSelectorTest, DefaultLanguageName) {
installer::LanguageSelector instance;
EXPECT_FALSE(instance.GetLanguageName(instance.offset()).empty());
}
<commit_msg>Added newline to the end of language_selector_unittest.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "chrome/installer/util/language_selector.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const wchar_t* const kExactMatchCandidates[] = {
L"am", L"ar", L"bg", L"bn", L"ca", L"cs", L"da", L"de", L"el", L"en-gb",
L"en-us", L"es", L"es-419", L"et", L"fa", L"fi", L"fil", L"fr", L"gu", L"hi",
L"hr", L"hu", L"id", L"it", L"iw", L"ja", L"kn", L"ko", L"lt", L"lv", L"ml",
L"mr", L"nl", L"no", L"pl", L"pt-br", L"pt-pt", L"ro", L"ru", L"sk", L"sl",
L"sr", L"sv", L"sw", L"ta", L"te", L"th", L"tr", L"uk", L"vi", L"zh-cn",
L"zh-tw"
};
const wchar_t* const kAliasMatchCandidates[] = {
L"he", L"nb", L"tl", L"zh-chs", L"zh-cht", L"zh-hans", L"zh-hant", L"zh-hk",
L"zh-mo"
};
const wchar_t* const kWildcardMatchCandidates[] = {
L"en-AU",
L"es-CO", L"pt-AB", L"zh-SG"
};
} // namespace
// Test that a language is selected from the system.
TEST(LanguageSelectorTest, DefaultSelection) {
installer::LanguageSelector instance;
EXPECT_FALSE(instance.matched_candidate().empty());
}
// Test some hypothetical candidate sets.
TEST(LanguageSelectorTest, AssortedSelections) {
{
std::wstring candidates[] = {
L"fr-BE", L"fr", L"en"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the exact match to win.
EXPECT_EQ(L"fr", instance.matched_candidate());
}
{
std::wstring candidates[] = {
L"xx-YY", L"cc-Ssss-RR"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the fallback to win.
EXPECT_EQ(L"en-us", instance.matched_candidate());
}
{
std::wstring candidates[] = {
L"zh-SG", L"en-GB"
};
installer::LanguageSelector instance(
std::vector<std::wstring>(&candidates[0],
&candidates[arraysize(candidates)]));
// Expect the alias match to win.
EXPECT_EQ(L"zh-SG", instance.matched_candidate());
}
}
// A fixture for testing sets of single-candidate selections.
class LanguageSelectorMatchCandidateTest
: public ::testing::TestWithParam<const wchar_t*> {
};
TEST_P(LanguageSelectorMatchCandidateTest, TestMatchCandidate) {
installer::LanguageSelector instance(
std::vector<std::wstring>(1, std::wstring(GetParam())));
EXPECT_EQ(GetParam(), instance.matched_candidate());
}
// Test that all existing translations can be found by exact match.
INSTANTIATE_TEST_CASE_P(
TestExactMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kExactMatchCandidates[0],
&kExactMatchCandidates[arraysize(kExactMatchCandidates)]));
// Test the alias matches.
INSTANTIATE_TEST_CASE_P(
TestAliasMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kAliasMatchCandidates[0],
&kAliasMatchCandidates[arraysize(kAliasMatchCandidates)]));
// Test a few wildcard matches.
INSTANTIATE_TEST_CASE_P(
TestWildcardMatches,
LanguageSelectorMatchCandidateTest,
::testing::ValuesIn(
&kWildcardMatchCandidates[0],
&kWildcardMatchCandidates[arraysize(kWildcardMatchCandidates)]));
// A fixture for testing aliases that match to an expected translation. The
// first member of the tuple is the expected translation, the second is a
// candidate that should be aliased to the expectation.
class LanguageSelectorAliasTest
: public ::testing::TestWithParam< std::tr1::tuple<const wchar_t*,
const wchar_t*> > {
};
// Test that the candidate language maps to the aliased translation.
TEST_P(LanguageSelectorAliasTest, AliasesMatch) {
installer::LanguageSelector instance(
std::vector<std::wstring>(1, std::tr1::get<1>(GetParam())));
EXPECT_EQ(std::tr1::get<0>(GetParam()), instance.selected_translation());
}
INSTANTIATE_TEST_CASE_P(
EnGbAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"en-gb"),
::testing::Values(L"en-au", L"en-ca", L"en-nz", L"en-za")));
INSTANTIATE_TEST_CASE_P(
IwAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"iw"),
::testing::Values(L"he")));
INSTANTIATE_TEST_CASE_P(
NoAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"no"),
::testing::Values(L"nb")));
INSTANTIATE_TEST_CASE_P(
FilAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"fil"),
::testing::Values(L"tl")));
INSTANTIATE_TEST_CASE_P(
ZhCnAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"zh-cn"),
::testing::Values(L"zh-chs", L"zh-hans", L"zh-sg")));
INSTANTIATE_TEST_CASE_P(
ZhTwAliases,
LanguageSelectorAliasTest,
::testing::Combine(
::testing::Values(L"zh-tw"),
::testing::Values(L"zh-cht", L"zh-hant", L"zh-hk", L"zh-mo")));
// Test that we can get the name of the default language.
TEST(LanguageSelectorTest, DefaultLanguageName) {
installer::LanguageSelector instance;
EXPECT_FALSE(instance.GetLanguageName(instance.offset()).empty());
}
<|endoftext|>
|
<commit_before>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for writing to a Windows console
// i.e. cmd.exe.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "textinput/TerminalDisplayWin.h"
#include "textinput/Color.h"
#include <assert.h>
namespace textinput {
TerminalDisplayWin::TerminalDisplayWin():
TerminalDisplay(false), fStartLine(0), fIsAttached(false),
fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) {
DWORD mode;
SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0);
fOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0;
if (!isConsole) {
// Prevent redirection from stealing our console handle,
// simply open our own.
fOut = ::CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
::GetConsoleMode(fOut, &fOldMode);
} else {
// disable unicode (UTF-8) for the time being, since it causes
// problems on Windows 10
//::SetConsoleOutputCP(65001); // Force UTF-8 output
}
CONSOLE_SCREEN_BUFFER_INFO csbi;
::GetConsoleScreenBufferInfo(fOut, &csbi);
fDefaultAttributes = csbi.wAttributes;
assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken");
fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
HandleResizeEvent();
}
TerminalDisplayWin::~TerminalDisplayWin() {
if (fDefaultAttributes) {
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
// We allocated CONOUT$:
CloseHandle(fOut);
}
::SetConsoleOutputCP(fOldCodePage);
}
void
TerminalDisplayWin::HandleResizeEvent() {
if (IsTTY()) {
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("resize / getting console info");
return;
}
SetWidth(Info.dwSize.X);
}
}
void
TerminalDisplayWin::SetColor(char CIdx, const Color& C) {
WORD Attribs = 0;
// There is no underline since DOS has died.
if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY;
if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY;
if (C.fR > 64) Attribs |= FOREGROUND_RED;
if (C.fG > 64) Attribs |= FOREGROUND_GREEN;
if (C.fB > 64) Attribs |= FOREGROUND_BLUE;
// if CIdx is 0 (default) then use the original console text color
// (instead of the greyish one)
if (CIdx == 0)
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
else
::SetConsoleTextAttribute(fOut, Attribs);
}
void
TerminalDisplayWin::CheckCursorPos() {
if (!IsTTY()) return;
// Did something print something on the screen?
// I.e. did the cursor move?
CONSOLE_SCREEN_BUFFER_INFO CSI;
if (::GetConsoleScreenBufferInfo(fOut, &CSI)) {
if (CSI.dwCursorPosition.X != fWritePos.fCol
|| CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) {
fStartLine = CSI.dwCursorPosition.Y;
if (CSI.dwCursorPosition.X) {
// fStartLine may be a couple of lines higher (or more precisely
// the number of written lines higher)
fStartLine -= fWritePos.fLine;
}
fWritePos.fCol = 0;
fWritePos.fLine = 0;
}
}
}
void
TerminalDisplayWin::Move(Pos P) {
CheckCursorPos();
MoveInternal(P);
fWritePos = P;
}
void
TerminalDisplayWin::MoveInternal(Pos P) {
if (IsTTY()) {
COORD C = {P.fCol, P.fLine + fStartLine};
::SetConsoleCursorPosition(fOut, C);
}
}
void
TerminalDisplayWin::MoveFront() {
Pos P(fWritePos);
P.fCol = 0;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) {
Pos P(fWritePos);
--P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) {
Pos P(fWritePos);
++P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) {
Pos P(fWritePos);
++P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) {
Pos P(fWritePos);
--P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::EraseToRight() {
DWORD NumWritten;
COORD C = {fWritePos.fCol, fWritePos.fLine + fStartLine};
::FillConsoleOutputCharacter(fOut, ' ', GetWidth() - C.X, C,
&NumWritten);
// It wraps, so move up and reset WritePos:
//MoveUp();
//++WritePos.Line;
}
void
TerminalDisplayWin::WriteRawString(const char *text, size_t len) {
DWORD NumWritten = 0;
if (IsTTY()) {
WriteConsole(fOut, text, (DWORD) len, &NumWritten, NULL);
} else {
WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL);
}
if (NumWritten != len) {
ShowError("writing to output");
}
}
void
TerminalDisplayWin::Attach() {
// set to noecho
if (fIsAttached || !IsTTY()) return;
if (!::SetConsoleMode(fOut, fMyMode)) {
ShowError("attaching to console output");
}
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("attaching / getting console info");
} else {
fStartLine = Info.dwCursorPosition.Y;
if (Info.dwCursorPosition.X) {
// Whooa - where are we?! Newline and cross fingers:
WriteRawString("\n", 1);
++fStartLine;
}
}
fIsAttached = true;
}
void
TerminalDisplayWin::Detach() {
if (!fIsAttached || !IsTTY()) return;
if (!SetConsoleMode(fOut, fOldMode)) {
ShowError("detaching to console output");
}
TerminalDisplay::Detach();
fIsAttached = false;
}
void
TerminalDisplayWin::ShowError(const char* Where) const {
DWORD Err = GetLastError();
LPVOID MsgBuf = 0;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &MsgBuf, 0, NULL);
printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, MsgBuf);
LocalFree(MsgBuf);
}
}
#endif // ifdef _WIN32
<commit_msg>Fix potential issue with Unicode<commit_after>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for writing to a Windows console
// i.e. cmd.exe.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "textinput/TerminalDisplayWin.h"
#include "textinput/Color.h"
#include <assert.h>
#ifdef UNICODE
#define filename L"CONOUT$"
#else
#define filename "CONOUT$"
#endif
namespace textinput {
TerminalDisplayWin::TerminalDisplayWin():
TerminalDisplay(false), fStartLine(0), fIsAttached(false),
fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) {
DWORD mode;
SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0);
fOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0;
if (!isConsole) {
// Prevent redirection from stealing our console handle,
// simply open our own.
fOut = ::CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
::GetConsoleMode(fOut, &fOldMode);
} else {
// disable unicode (UTF-8) for the time being, since it causes
// problems on Windows 10
//::SetConsoleOutputCP(65001); // Force UTF-8 output
}
CONSOLE_SCREEN_BUFFER_INFO csbi;
::GetConsoleScreenBufferInfo(fOut, &csbi);
fDefaultAttributes = csbi.wAttributes;
assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken");
fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
HandleResizeEvent();
}
#undef filename
TerminalDisplayWin::~TerminalDisplayWin() {
if (fDefaultAttributes) {
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
// We allocated CONOUT$:
CloseHandle(fOut);
}
::SetConsoleOutputCP(fOldCodePage);
}
void
TerminalDisplayWin::HandleResizeEvent() {
if (IsTTY()) {
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("resize / getting console info");
return;
}
SetWidth(Info.dwSize.X);
}
}
void
TerminalDisplayWin::SetColor(char CIdx, const Color& C) {
WORD Attribs = 0;
// There is no underline since DOS has died.
if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY;
if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY;
if (C.fR > 64) Attribs |= FOREGROUND_RED;
if (C.fG > 64) Attribs |= FOREGROUND_GREEN;
if (C.fB > 64) Attribs |= FOREGROUND_BLUE;
// if CIdx is 0 (default) then use the original console text color
// (instead of the greyish one)
if (CIdx == 0)
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
else
::SetConsoleTextAttribute(fOut, Attribs);
}
void
TerminalDisplayWin::CheckCursorPos() {
if (!IsTTY()) return;
// Did something print something on the screen?
// I.e. did the cursor move?
CONSOLE_SCREEN_BUFFER_INFO CSI;
if (::GetConsoleScreenBufferInfo(fOut, &CSI)) {
if (CSI.dwCursorPosition.X != fWritePos.fCol
|| CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) {
fStartLine = CSI.dwCursorPosition.Y;
if (CSI.dwCursorPosition.X) {
// fStartLine may be a couple of lines higher (or more precisely
// the number of written lines higher)
fStartLine -= fWritePos.fLine;
}
fWritePos.fCol = 0;
fWritePos.fLine = 0;
}
}
}
void
TerminalDisplayWin::Move(Pos P) {
CheckCursorPos();
MoveInternal(P);
fWritePos = P;
}
void
TerminalDisplayWin::MoveInternal(Pos P) {
if (IsTTY()) {
COORD C = {P.fCol, P.fLine + fStartLine};
::SetConsoleCursorPosition(fOut, C);
}
}
void
TerminalDisplayWin::MoveFront() {
Pos P(fWritePos);
P.fCol = 0;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) {
Pos P(fWritePos);
--P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) {
Pos P(fWritePos);
++P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) {
Pos P(fWritePos);
++P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) {
Pos P(fWritePos);
--P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::EraseToRight() {
DWORD NumWritten;
COORD C = {fWritePos.fCol, fWritePos.fLine + fStartLine};
::FillConsoleOutputCharacter(fOut, ' ', GetWidth() - C.X, C,
&NumWritten);
// It wraps, so move up and reset WritePos:
//MoveUp();
//++WritePos.Line;
}
void
TerminalDisplayWin::WriteRawString(const char *text, size_t len) {
DWORD NumWritten = 0;
if (IsTTY()) {
WriteConsole(fOut, text, (DWORD) len, &NumWritten, NULL);
} else {
WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL);
}
if (NumWritten != len) {
ShowError("writing to output");
}
}
void
TerminalDisplayWin::Attach() {
// set to noecho
if (fIsAttached || !IsTTY()) return;
if (!::SetConsoleMode(fOut, fMyMode)) {
ShowError("attaching to console output");
}
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("attaching / getting console info");
} else {
fStartLine = Info.dwCursorPosition.Y;
if (Info.dwCursorPosition.X) {
// Whooa - where are we?! Newline and cross fingers:
WriteRawString("\n", 1);
++fStartLine;
}
}
fIsAttached = true;
}
void
TerminalDisplayWin::Detach() {
if (!fIsAttached || !IsTTY()) return;
if (!SetConsoleMode(fOut, fOldMode)) {
ShowError("detaching to console output");
}
TerminalDisplay::Detach();
fIsAttached = false;
}
void
TerminalDisplayWin::ShowError(const char* Where) const {
DWORD Err = GetLastError();
LPVOID MsgBuf = 0;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &MsgBuf, 0, NULL);
printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, MsgBuf);
LocalFree(MsgBuf);
}
}
#endif // ifdef _WIN32
<|endoftext|>
|
<commit_before>// Problem 9 from Project Euler
// http://projecteuler.net/problem=9
#include <cmath>
#include <array>
#include <numeric>
#include <iostream>
int main()
{
std::array<unsigned int, 1000> range;
std::iota(range.begin(), range.end(), 1);
for (unsigned int a = 0; a < 997; a++)
{
unsigned int int_a = range[a];
for (unsigned int b = a + 1; b < 998; b++)
{
unsigned int int_b = range[b];
unsigned int c = 1000 - (int_a + int_b);
if (pow(int_a, 2) + pow(int_b, 2) == pow(c, 2))
{
std::cout << int_a << " * " << int_b << " * " << c << " = " << int_a * int_b * c << std::endl;
return 0;
}
}
}
}
<commit_msg>Minor code cleanup, added comments etc.<commit_after>// Problem 9 from Project Euler
// http://projecteuler.net/problem=9
#include <cmath>
#include <array>
#include <numeric>
#include <iostream>
int main()
{
std::array<unsigned int, 1000> range;
std::iota(range.begin(), range.end(), 1); // Populate the range array
// We set 'a's upper bound to 997 so that the max value of 'int_a' will be 998,
// thus making sure that it will always be possible to get an 'int_b' and 'c' larger than 'a'
for (unsigned int a = 0; a <= 997; a++)
{
unsigned int int_a = range[a];
for (unsigned int b = a + 1; b < 998; b++) // Note that 'b' will always be greater than 'a'
{
unsigned int int_b = range[b];
unsigned int int_c = 1000 - (int_a + int_b);
if (pow(int_a, 2) + pow(int_b, 2) == pow(int_c, 2))
{
std::cout << int_a << " * " << int_b << " * " << int_c << " = " << int_a * int_b * int_c << std::endl;
return 0;
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>tdf#84294: vcl: fix PDF export of transparent Writer frames in LO 4.3<commit_after><|endoftext|>
|
<commit_before>#define SKEW_GC_MARK_AND_SWEEP
#import <skew.h>
namespace Log {
void info(const Skew::string &text) {}
void warning(const Skew::string &text) {}
void error(const Skew::string &text) {}
}
#import "compiled.cpp"
#import <skew.cpp>
#import <ncurses.h>
////////////////////////////////////////////////////////////////////////////////
enum {
SKY_COLOR_COMMENT = 1,
SKY_COLOR_CONSTANT = 2,
SKY_COLOR_KEYWORD = 3,
SKY_COLOR_MARGIN = 4,
SKY_COLOR_STRING = 5,
};
namespace Terminal {
struct Host : Editor::Platform, private Editor::Window, private Editor::SemanticRenderer {
void showCarets() {
_areCaretsVisible = true;
}
void toggleCarets() {
_areCaretsVisible = !_areCaretsVisible;
}
void handleResize() {
_width = getmaxx(stdscr);
_height = getmaxy(stdscr);
_view->resize(_width - 1, _height); // Subtract 1 so the cursor can be seen at the end of the line
}
void render() {
clear();
_view->render();
refresh();
}
void triggerAction(Editor::Action action) {
if (action == Editor::Action::CUT || action == Editor::Action::COPY) {
auto selection = _view->selection()->isEmpty() ? _view->selectionExpandedToLines() : _view->selection();
_clipboard = _view->textInSelection(selection).std_str();
if (action == Editor::Action::CUT) {
_view->changeSelection(selection, Editor::ScrollBehavior::DO_NOT_SCROLL);
_view->insertText("");
}
}
else if (action == Editor::Action::PASTE) {
_view->insertText(_clipboard);
}
else {
_view->triggerAction(action);
}
}
void insertASCII(char c) {
_view->insertText(std::string(1, c));
}
virtual Editor::OperatingSystem operatingSystem() override {
return Editor::OperatingSystem::UNKNOWN;
}
virtual Editor::UserAgent userAgent() override {
return Editor::UserAgent::UNKNOWN;
}
virtual double nowInSeconds() override {
timeval data;
gettimeofday(&data, nullptr);
return data.tv_sec + data.tv_usec / 1.0e6;
}
virtual Graphics::GlyphProvider *createGlyphProvider(Skew::List<Skew::string> *fontNames) override {
return nullptr;
}
virtual Editor::Window *createWindow() override {
return this;
}
virtual Editor::SemanticRenderer *renderer() override {
return this;
}
virtual void setView(Editor::View *view) override {
_view = view;
_view->resizeFont(1, 1, 1);
_view->setScrollbarThickness(1);
_view->changePadding(0, 0, 0, 0);
_view->changeMarginPadding(1, 1);
_view->triggerAction(Editor::Action::SELECT_ALL);
_view->insertText(
"Shortcuts:\n"
"\n"
"Ctrl+Q: Quit\n"
"Ctrl+X: Cut\n"
"Ctrl+C: Copy\n"
"Ctrl+V: Paste\n"
"Ctrl+A: Select All\n"
"Ctrl+Z: Undo\n"
"Ctrl+Y: Redo\n");
_view->triggerAction(Editor::Action::MOVE_UP_DOCUMENT);
handleResize();
}
virtual void setTitle(Skew::string title) override {
}
virtual void invalidate() override {
}
virtual void setCursor(Editor::Cursor cursor) override {
}
virtual void renderRect(double x, double y, double width, double height, Editor::Color color) override {
}
virtual void renderCaret(double x, double y, Editor::Color color) override {
assert(x == (int)x);
assert(y == (int)y);
if (!_areCaretsVisible || x < 0 || y < 0 || x >= _width || y >= _height) {
return;
}
mvaddch(y, x, mvinch(y, x) | A_UNDERLINE);
}
virtual void renderSquiggle(double x, double y, double width, double height, Editor::Color color) override {
}
virtual void renderRightwardShadow(double x, double y, double width, double height) override {
}
virtual void renderText(double x, double y, Skew::string text, Editor::Font font, Editor::Color color, int alpha) override {
assert(x == (int)x);
assert(y == (int)y);
if (y < 0 || y >= _height) {
return;
}
bool isMargin = color == Editor::Color::FOREGROUND_MARGIN || color == Editor::Color::FOREGROUND_MARGIN_HIGHLIGHTED;
int attributes =
isMargin ? COLOR_PAIR(SKY_COLOR_MARGIN) :
color == Editor::Color::FOREGROUND_KEYWORD || color == Editor::Color::FOREGROUND_KEYWORD_CONSTANT ? COLOR_PAIR(SKY_COLOR_KEYWORD) :
color == Editor::Color::FOREGROUND_CONSTANT || color == Editor::Color::FOREGROUND_NUMBER ? COLOR_PAIR(SKY_COLOR_CONSTANT) :
color == Editor::Color::FOREGROUND_COMMENT ? COLOR_PAIR(SKY_COLOR_COMMENT) :
color == Editor::Color::FOREGROUND_STRING ? COLOR_PAIR(SKY_COLOR_STRING) :
color == Editor::Color::FOREGROUND_DEFINITION ? A_BOLD :
0;
int minX = isMargin ? 0 : _view->marginWidth();
int maxX = _width - 1; // Subtract 1 so the cursor can be seen at the end of the line
int start = std::max(0, std::min(text.count(), minX - (int)x));
int end = std::max(0, std::min(text.count(), maxX - (int)x));
attron(attributes);
mvaddstr(y, x + start, text.slice(start, end).c_str());
attroff(attributes);
}
virtual void renderHorizontalLine(double x1, double x2, double y, Editor::Color color) override {
}
virtual void renderVerticalLine(double x, double y1, double y2, Editor::Color color) override {
}
virtual void renderScrollbarThumb(double x, double y, double width, double height, Editor::Color color) override {
}
#ifdef SKEW_GC_MARK_AND_SWEEP
virtual void __gc_mark() override {
Skew::GC::mark(_view);
}
#endif
private:
int _width = 0;
int _height = 0;
bool _areCaretsVisible = true;
std::string _clipboard;
std::vector<short> _buffer;
Editor::View *_view = nullptr;
};
}
////////////////////////////////////////////////////////////////////////////////
static void handleEscapeSequence(Terminal::Host *host) {
static std::unordered_map<std::string, Editor::Action> map = {
{ "[", Editor::Action::SELECT_FIRST_REGION },
{ "[3~", Editor::Action::DELETE_RIGHT_CHARACTER },
{ "[A", Editor::Action::MOVE_UP_LINE },
{ "[B", Editor::Action::MOVE_DOWN_LINE },
{ "[C", Editor::Action::MOVE_RIGHT_CHARACTER },
{ "[D", Editor::Action::MOVE_LEFT_CHARACTER },
};
std::string sequence;
// Escape sequences can have arbitrary length
do {
int c = getch();
// If getch times out, this was just a plain escape
if (c == -1) {
break;
}
sequence += c;
} while (sequence == "[" || sequence[sequence.size() - 1] < '@');
// Dispatch an action if there's a match
auto it = map.find(sequence);
if (it != map.end()) {
host->triggerAction(it->second);
}
}
static void handleControlCharacter(Terminal::Host *host, char c) {
static std::unordered_map<char, Editor::Action> map = {
{ 'A', Editor::Action::SELECT_ALL },
{ 'C', Editor::Action::COPY },
{ 'V', Editor::Action::PASTE },
{ 'X', Editor::Action::CUT },
{ 'Y', Editor::Action::REDO },
{ 'Z', Editor::Action::UNDO },
};
auto it = map.find(c);
if (it != map.end()) {
host->triggerAction(it->second);
}
}
int main() {
// Let the ncurses library take over the screen and make sure it's cleaned up
initscr();
atexit([] { endwin(); });
// Prepare colors
start_color();
use_default_colors();
init_pair(SKY_COLOR_MARGIN, COLOR_BLUE, -1);
init_pair(SKY_COLOR_KEYWORD, COLOR_RED, -1);
init_pair(SKY_COLOR_COMMENT, COLOR_CYAN, -1);
init_pair(SKY_COLOR_STRING, COLOR_GREEN, -1);
init_pair(SKY_COLOR_CONSTANT, COLOR_MAGENTA, -1);
// More setup
raw(); // Don't automatically generate any signals
noecho(); // Don't auto-print typed characters
curs_set(0); // Hide the cursor since we have our own carets
timeout(50); // Don't let getch() block too long, need to blink the carets
int blinkToggle = 0;
auto host = new Terminal::Host;
Skew::Root<Editor::App> app(new Editor::App(host));
host->render();
while (true) {
int c = getch();
// Handle getch() timeout for blinking carets
if (c == -1) {
if (++blinkToggle == 10) {
host->toggleCarets();
blinkToggle = 0;
} else {
continue;
}
}
// Reset blinking any time anything happens
else {
host->showCarets();
blinkToggle = 0;
}
// Handle escape sequences
if (c == 27) {
handleEscapeSequence(host);
}
// Special-case the Control+Q shortcut to quit
else if (c == 'Q' - 'A' + 1) {
break;
}
// Handle shortcuts using control characters
else if (c < 32 && c != '\n' && c != '\t') {
handleControlCharacter(host, c + 'A' - 1);
}
// Special-case backspace
else if (c == 127) {
host->triggerAction(Editor::Action::DELETE_LEFT_CHARACTER);
}
// Handle regular typed text
else if ((c >= 32 && c < 127) || c == '\n') {
host->insertASCII(c);
}
host->render();
Skew::GC::collect();
}
return 0;
}
<commit_msg>selection rendering, fix high-ASCII<commit_after>#define SKEW_GC_MARK_AND_SWEEP
#import <skew.h>
namespace Log {
void info(const Skew::string &text) {}
void warning(const Skew::string &text) {}
void error(const Skew::string &text) {}
}
#import "compiled.cpp"
#import <skew.cpp>
#import <ncurses.h>
#import <codecvt>
#import <locale>
////////////////////////////////////////////////////////////////////////////////
enum {
SKY_COLOR_COMMENT = 1,
SKY_COLOR_CONSTANT = 2,
SKY_COLOR_KEYWORD = 3,
SKY_COLOR_MARGIN = 4,
SKY_COLOR_SELECTED = 5,
SKY_COLOR_STRING = 6,
};
namespace Terminal {
struct Host : Editor::Platform, private Editor::Window, private Editor::SemanticRenderer {
void showCarets() {
_areCaretsVisible = true;
}
void toggleCarets() {
_areCaretsVisible = !_areCaretsVisible;
}
void handleResize() {
_width = getmaxx(stdscr);
_height = getmaxy(stdscr);
_view->resize(_width - 1, _height); // Subtract 1 so the cursor can be seen at the end of the line
}
void render() {
clear();
_view->render();
refresh();
}
void triggerAction(Editor::Action action) {
if (action == Editor::Action::CUT || action == Editor::Action::COPY) {
auto selection = _view->selection()->isEmpty() ? _view->selectionExpandedToLines() : _view->selection();
_clipboard = _view->textInSelection(selection).std_str();
if (action == Editor::Action::CUT) {
_view->changeSelection(selection, Editor::ScrollBehavior::DO_NOT_SCROLL);
_view->insertText("");
}
}
else if (action == Editor::Action::PASTE) {
_view->insertText(_clipboard);
}
else {
_view->triggerAction(action);
}
}
void insertASCII(char c) {
_view->insertText(std::string(1, c));
}
virtual Editor::OperatingSystem operatingSystem() override {
return Editor::OperatingSystem::UNKNOWN;
}
virtual Editor::UserAgent userAgent() override {
return Editor::UserAgent::UNKNOWN;
}
virtual double nowInSeconds() override {
timeval data;
gettimeofday(&data, nullptr);
return data.tv_sec + data.tv_usec / 1.0e6;
}
virtual Graphics::GlyphProvider *createGlyphProvider(Skew::List<Skew::string> *fontNames) override {
return nullptr;
}
virtual Editor::Window *createWindow() override {
return this;
}
virtual Editor::SemanticRenderer *renderer() override {
return this;
}
virtual void setView(Editor::View *view) override {
_view = view;
_view->resizeFont(1, 1, 1);
_view->setScrollbarThickness(1);
_view->changePadding(0, 0, 0, 0);
_view->changeMarginPadding(1, 1);
_view->triggerAction(Editor::Action::SELECT_ALL);
_view->insertText(
"Shortcuts:\n"
"\n"
"Ctrl+Q: Quit\n"
"Ctrl+X: Cut\n"
"Ctrl+C: Copy\n"
"Ctrl+V: Paste\n"
"Ctrl+A: Select All\n"
"Ctrl+Z: Undo\n"
"Ctrl+Y: Redo\n");
_view->triggerAction(Editor::Action::MOVE_UP_DOCUMENT);
handleResize();
}
virtual void setTitle(Skew::string title) override {
}
virtual void invalidate() override {
}
virtual void setCursor(Editor::Cursor cursor) override {
}
virtual void renderRect(double x, double y, double width, double height, Editor::Color color) override {
if (color == Editor::Color::BACKGROUND_SELECTED) {
int minX = std::max((int)x, (int)_view->marginWidth());
int minY = std::max((int)y, 0);
int maxX = std::min((int)(x + width), _width);
int maxY = std::min((int)(y + height), _height);
int n = std::max(0, maxX - minX);
chtype buffer[n];
for (int y = minY; y < maxY; y++) {
mvinchnstr(y, minX, buffer, n);
for (int x = 0; x < n; x++) {
buffer[x] = (buffer[x] & ~A_COLOR) | COLOR_PAIR(SKY_COLOR_SELECTED);
}
mvaddchnstr(y, minX, buffer, n);
}
}
}
virtual void renderCaret(double x, double y, Editor::Color color) override {
assert(x == (int)x);
assert(y == (int)y);
if (!_areCaretsVisible || x < 0 || y < 0 || x >= _width || y >= _height) {
return;
}
mvaddch(y, x, mvinch(y, x) | A_UNDERLINE);
}
virtual void renderSquiggle(double x, double y, double width, double height, Editor::Color color) override {
}
virtual void renderRightwardShadow(double x, double y, double width, double height) override {
}
virtual void renderText(double x, double y, Skew::string text, Editor::Font font, Editor::Color color, int alpha) override {
assert(x == (int)x);
assert(y == (int)y);
if (y < 0 || y >= _height) {
return;
}
bool isMargin = color == Editor::Color::FOREGROUND_MARGIN || color == Editor::Color::FOREGROUND_MARGIN_HIGHLIGHTED;
int attributes =
isMargin ? COLOR_PAIR(SKY_COLOR_MARGIN) :
color == Editor::Color::FOREGROUND_KEYWORD || color == Editor::Color::FOREGROUND_KEYWORD_CONSTANT ? COLOR_PAIR(SKY_COLOR_KEYWORD) :
color == Editor::Color::FOREGROUND_CONSTANT || color == Editor::Color::FOREGROUND_NUMBER ? COLOR_PAIR(SKY_COLOR_CONSTANT) :
color == Editor::Color::FOREGROUND_COMMENT ? COLOR_PAIR(SKY_COLOR_COMMENT) :
color == Editor::Color::FOREGROUND_STRING ? COLOR_PAIR(SKY_COLOR_STRING) :
color == Editor::Color::FOREGROUND_DEFINITION ? A_BOLD :
0;
auto utf32 = std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t>().from_bytes(text.std_str());
int minX = isMargin ? 0 : _view->marginWidth();
int maxX = _width - 1; // Subtract 1 so the cursor can be seen at the end of the line
int start = std::max(0, std::min((int)utf32.size(), minX - (int)x));
int end = std::max(0, std::min((int)utf32.size(), maxX - (int)x));
int n = std::max(0, end - start);
chtype buffer[n];
mvinchnstr(y, x + start, buffer, n);
for (int i = 0; i < n; i++) {
int color = buffer[i] & A_COLOR;
int c = utf32[start + i];
if (c == ' ') c = buffer[i] & (~A_ATTRIBUTES | A_ALTCHARSET);
else if (c == 0xB7) c = 126 | A_ALTCHARSET;
else if (c > 0xFF) c = '?';
buffer[i] = (PAIR_NUMBER(color) == 0 ? attributes : color | (attributes & A_BOLD)) | c;
}
mvaddchnstr(y, x + start, buffer, n);
}
virtual void renderHorizontalLine(double x1, double x2, double y, Editor::Color color) override {
}
virtual void renderVerticalLine(double x, double y1, double y2, Editor::Color color) override {
}
virtual void renderScrollbarThumb(double x, double y, double width, double height, Editor::Color color) override {
}
#ifdef SKEW_GC_MARK_AND_SWEEP
virtual void __gc_mark() override {
Skew::GC::mark(_view);
}
#endif
private:
int _width = 0;
int _height = 0;
bool _areCaretsVisible = true;
std::string _clipboard;
std::vector<short> _buffer;
Editor::View *_view = nullptr;
};
}
////////////////////////////////////////////////////////////////////////////////
static void handleEscapeSequence(Terminal::Host *host) {
static std::unordered_map<std::string, Editor::Action> map = {
{ "[", Editor::Action::SELECT_FIRST_REGION },
{ "[3~", Editor::Action::DELETE_RIGHT_CHARACTER },
{ "[A", Editor::Action::MOVE_UP_LINE },
{ "[B", Editor::Action::MOVE_DOWN_LINE },
{ "[C", Editor::Action::MOVE_RIGHT_CHARACTER },
{ "[D", Editor::Action::MOVE_LEFT_CHARACTER },
};
std::string sequence;
// Escape sequences can have arbitrary length
do {
int c = getch();
// If getch times out, this was just a plain escape
if (c == -1) {
break;
}
sequence += c;
} while (sequence == "[" || sequence[sequence.size() - 1] < '@');
// Dispatch an action if there's a match
auto it = map.find(sequence);
if (it != map.end()) {
host->triggerAction(it->second);
}
}
static void handleControlCharacter(Terminal::Host *host, char c) {
static std::unordered_map<char, Editor::Action> map = {
{ 'A', Editor::Action::SELECT_ALL },
{ 'C', Editor::Action::COPY },
{ 'V', Editor::Action::PASTE },
{ 'X', Editor::Action::CUT },
{ 'Y', Editor::Action::REDO },
{ 'Z', Editor::Action::UNDO },
};
auto it = map.find(c);
if (it != map.end()) {
host->triggerAction(it->second);
}
}
int main() {
// Let the ncurses library take over the screen and make sure it's cleaned up
initscr();
atexit([] { endwin(); });
// Prepare colors
start_color();
use_default_colors();
init_pair(SKY_COLOR_MARGIN, COLOR_BLUE, -1);
init_pair(SKY_COLOR_KEYWORD, COLOR_RED, -1);
init_pair(SKY_COLOR_COMMENT, COLOR_CYAN, -1);
init_pair(SKY_COLOR_STRING, COLOR_GREEN, -1);
init_pair(SKY_COLOR_CONSTANT, COLOR_MAGENTA, -1);
init_pair(SKY_COLOR_SELECTED, COLOR_BLACK, COLOR_YELLOW);
// More setup
raw(); // Don't automatically generate any signals
noecho(); // Don't auto-print typed characters
curs_set(0); // Hide the cursor since we have our own carets
timeout(50); // Don't let getch() block too long, need to blink the carets
int blinkToggle = 0;
auto host = new Terminal::Host;
Skew::Root<Editor::App> app(new Editor::App(host));
host->render();
while (true) {
int c = getch();
// Handle getch() timeout for blinking carets
if (c == -1) {
if (++blinkToggle == 10) {
host->toggleCarets();
blinkToggle = 0;
} else {
continue;
}
}
// Reset blinking any time anything happens
else {
host->showCarets();
blinkToggle = 0;
}
// Handle escape sequences
if (c == 27) {
handleEscapeSequence(host);
}
// Special-case the Control+Q shortcut to quit
else if (c == 'Q' - 'A' + 1) {
break;
}
// Handle shortcuts using control characters
else if (c < 32 && c != '\n' && c != '\t') {
handleControlCharacter(host, c + 'A' - 1);
}
// Special-case backspace
else if (c == 127) {
host->triggerAction(Editor::Action::DELETE_LEFT_CHARACTER);
}
// Handle regular typed text
else if ((c >= 32 && c < 127) || c == '\n') {
host->insertASCII(c);
}
host->render();
Skew::GC::collect();
}
return 0;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
//////////////////////////////////////////////////
//
// ターゲットプラットフォーム
// Target Platform
//
//////////////////////////////////////////////////
# if defined(_WIN32)
/// <summary>
/// ターゲットプラットフォーム: Windows
/// Target platform: Windows
/// </summary>
# define SIV3D_TARGET_WINDOWS
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"Windows Desktop"
# elif defined(__APPLE__) && defined(__MACH__)
/// <summary>
/// ターゲットプラットフォーム: macOS
/// Target platform: macOS
/// </summary>
# define SIV3D_TARGET_MACOS
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"macOS"
# elif defined(__linux__)
/// <summary>
/// ターゲットプラットフォーム: Linux
/// Target platform: Linux
/// </summary>
# define SIV3D_TARGET_LINUX
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"Linux"
# else
# error Unsupported platform
# endif
//////////////////////////////////////////////////
//
// ターゲット Windows プラットフォーム
// Target Windows Platform
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS)
# if defined(_WIN64)
/// <summary>
/// ターゲット Windows プラットフォーム: 64-bit デスクトップ
/// Target Windows platform: 64-bit desktop application
/// </summary>
# define SIV3D_TARGET_WINDOWS_DESKTOP_X64
# else
# error Windows 32-bit 版のサポートは終了しました。
# error Windows 32-bit is no longer supported.
# endif
# endif
//////////////////////////////////////////////////
//
// SSE2 サポート
// SSE2 Support
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS) || defined(SIV3D_TARGET_MACOS) || defined(SIV3D_TARGET_LINUX)
# define SIV3D_HAVE_SSE2
# else
# error Unimplemented
# endif
//////////////////////////////////////////////////
//
// __m128 のメンバ
// __m128 members
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS)
# define SIV3D_HAVE_M128_MEMBERS
# elif defined(SIV3D_TARGET_MACOS) || defined(SIV3D_TARGET_LINUX)
# else
# error Unimplemented
# endif
//////////////////////////////////////////////////
//
// ビルド設定
// Build Configuration
//
//////////////////////////////////////////////////
# if defined(_DEBUG) || defined(DEBUG)
# define SIV3D_DEBUG 1
# else
# define SIV3D_DEBUG 0
# endif
namespace s3d
{
namespace Platform
{
inline constexpr bool DebugBuild = (SIV3D_DEBUG == 1);
}
}
//////////////////////////////////////////////////
//
// コンパイラ拡張
// Compiler Extensions
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS)
# define SIV3D_DISABLE_MSVC_WARNINGS_PUSH(warnings) \
__pragma(warning(push)) \
__pragma(warning(disable: warnings))
# define SIV3D_DISABLE_MSVC_WARNINGS_POP() \
__pragma(warning(pop))
# else
# define SIV3D_DISABLE_MSVC_WARNINGS_PUSH(warnings)
# define SIV3D_DISABLE_MSVC_WARNINGS_POP()
# endif
//////////////////////////////////////////////////
//
// Visual Studio のバージョンチェック
// MSVC Version Check
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS) && (_MSC_FULL_VER < 192127702)
# error このプロジェクトをビルドするには Visual Studio 2019 16.1 以降が必要です。
# error Visual Studio 2019 16.1 or later is required to build this project.
# endif
//////////////////////////////////////////////////
//
// 警告抑制
// Disable warning messages
//
//////////////////////////////////////////////////
# if defined(SIV3D_TARGET_WINDOWS)
# pragma warning(disable : 26444 26451 26495)
# endif
<commit_msg>新方式のプラットフォームマクロを導入、旧方式は順次置き換え<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
//////////////////////////////////////////////////
//
// ターゲットプラットフォーム
// Target Platform
//
//////////////////////////////////////////////////
# define SIV3D_PLATFORM(X) SIV3D_PRIVATE_DEFINITION_##X()
# define SIV3D_PRIVATE_DEFINITION_WINDOWS() 0
# define SIV3D_PRIVATE_DEFINITION_MACOS() 0
# define SIV3D_PRIVATE_DEFINITION_LINUX() 0
# if defined(_WIN32)
/// <summary>
/// ターゲットプラットフォーム: Windows
/// Target platform: Windows
/// </summary>
# define SIV3D_TARGET_WINDOWS
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"Windows Desktop"
# undef SIV3D_PRIVATE_DEFINITION_WINDOWS
# define SIV3D_PRIVATE_DEFINITION_WINDOWS() 1
# elif defined(__APPLE__) && defined(__MACH__)
/// <summary>
/// ターゲットプラットフォーム: macOS
/// Target platform: macOS
/// </summary>
# define SIV3D_TARGET_MACOS
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"macOS"
# undef SIV3D_PRIVATE_DEFINITION_MACOS
# define SIV3D_PRIVATE_DEFINITION_MACOS() 1
# elif defined(__linux__)
/// <summary>
/// ターゲットプラットフォーム: Linux
/// Target platform: Linux
/// </summary>
# define SIV3D_TARGET_LINUX
/// <summary>
/// ターゲットプラットフォームの名前
/// Name of the Target Platform
/// </summary>
# define SIV3D_PLATFORM_NAME U"Linux"
# undef SIV3D_PRIVATE_DEFINITION_LINUX
# define SIV3D_PRIVATE_DEFINITION_LINUX() 1
# else
# error Unsupported platform
# endif
//////////////////////////////////////////////////
//
// ターゲット Windows プラットフォーム
// Target Windows Platform
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS)
# if defined(_WIN64)
/// <summary>
/// ターゲット Windows プラットフォーム: 64-bit デスクトップ
/// Target Windows platform: 64-bit desktop application
/// </summary>
# define SIV3D_TARGET_WINDOWS_DESKTOP_X64
# else
# error Windows 32-bit 版のサポートは終了しました。
# error Windows 32-bit is no longer supported.
# endif
# endif
//////////////////////////////////////////////////
//
// SSE2 サポート
// SSE2 Support
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS) || SIV3D_PLATFORM(MACOS) || SIV3D_PLATFORM(LINUX)
# define SIV3D_HAVE_SSE2
# else
# error Unimplemented
# endif
//////////////////////////////////////////////////
//
// __m128 のメンバ
// __m128 members
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS)
# define SIV3D_HAVE_M128_MEMBERS
# elif SIV3D_PLATFORM(MACOS) || SIV3D_PLATFORM(LINUX)
# else
# error Unimplemented
# endif
//////////////////////////////////////////////////
//
// ビルド設定
// Build Configuration
//
//////////////////////////////////////////////////
# if defined(_DEBUG) || defined(DEBUG)
# define SIV3D_DEBUG 1
# else
# define SIV3D_DEBUG 0
# endif
namespace s3d
{
namespace Platform
{
inline constexpr bool DebugBuild = (SIV3D_DEBUG == 1);
}
}
//////////////////////////////////////////////////
//
// コンパイラ拡張
// Compiler Extensions
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS)
# define SIV3D_DISABLE_MSVC_WARNINGS_PUSH(warnings) \
__pragma(warning(push)) \
__pragma(warning(disable: warnings))
# define SIV3D_DISABLE_MSVC_WARNINGS_POP() \
__pragma(warning(pop))
# else
# define SIV3D_DISABLE_MSVC_WARNINGS_PUSH(warnings)
# define SIV3D_DISABLE_MSVC_WARNINGS_POP()
# endif
//////////////////////////////////////////////////
//
// Visual Studio のバージョンチェック
// MSVC Version Check
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS) && (_MSC_FULL_VER < 192127702)
# error このプロジェクトをビルドするには Visual Studio 2019 16.1 以降が必要です。
# error Visual Studio 2019 16.1 or later is required to build this project.
# endif
//////////////////////////////////////////////////
//
// 警告抑制
// Disable warning messages
//
//////////////////////////////////////////////////
# if SIV3D_PLATFORM(WINDOWS)
# pragma warning(disable : 26444 26451 26495)
# endif
<|endoftext|>
|
<commit_before><commit_msg>remove spurious xDocStorage temp<commit_after><|endoftext|>
|
<commit_before>//
// Current author and maintainer: Grzegorz Jaskiewicz
// gj at pointblue.com.pl
//
// Kopete initial author:
// Copyright (C) 2002-2003 Zack Rusin <zack@kde.org>
//
// gaducommands.h - all basic, and not-session dependent commands
// (meaning you don't have to be logged in for any
// of these). These delete themselves, meaning you don't
// have to/can't delete them explicitely and have to create
// them dynamically (via the 'new' call).
//
// 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
#include "gadueditaccount.h"
#include "gaduaccount.h"
#include "gaduprotocol.h"
#include <qradiobutton.h>
#include <qlabel.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qbutton.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <klocale.h>
GaduEditAccount::GaduEditAccount( GaduProtocol *proto, KopeteAccount *ident,
QWidget *parent, const char *name )
: GaduAccountEditUI( parent, name ), EditAccountWidget( ident )
,
protocol_( proto ), rcmd(0)
{
if (!m_account){
reg_in_progress=false;
kdDebug(14100)<<"GJ"<<"NEW ACCOUNT WIZ"<<endl;
radio1->setDisabled(false);
radio2->setDisabled(false);
textLabel2_2->setDisabled(false);
textLabel1_2->setDisabled(false);
emailedit_->setDisabled(false);
passwordEdit2__->setDisabled(false);
}
else{
kdDebug(14100)<<"GJ"<<"ACCOUNT EDIT"<<endl;
radio1->setDisabled(true);
radio2->setDisabled(true);
radio2->setDisabled(true);
textLabel2_2->setDisabled(true);
loginEdit_->setDisabled(true);
emailedit_->setDisabled(true);
passwordEdit2__->setDisabled(true);
loginEdit_->setText(m_account->accountId());
if (m_account->rememberPassword()){
passwordEdit_->setText(m_account->getPassword());
}
else{
passwordEdit_->setText("");
}
NickName->setText(m_account->myself()->displayName());
rememberCheck_->setChecked(m_account->rememberPassword());
autoLoginCheck_->setChecked(m_account->autoLogin());
}
}
void GaduEditAccount::registrationComplete( const QString& title, const QString& )
{
reg_in_progress=false;
kdDebug(14100)<<"GJ"<<" ID " << title << endl;
// i am sure rcmd is valid, since it sends this signal ;)
loginEdit_->setText(QString::number(rcmd->newUin()));
passwordEdit_->setText(passwordEdit2__->text());
radio1->setChecked(true);
radio2->setChecked(false);
radio1->setDisabled(true);
radio2->setDisabled(true);
textLabel2_2->setDisabled(true);
textLabel1_2->setDisabled(true);
emailedit_->setDisabled(true);
passwordEdit2__->setDisabled(true);
rememberCheck_->setChecked(true);
KMessageBox::information(this, i18n("<b>You've registered a new acount.</b>"), i18n("Gadu-Gadu"));
}
void GaduEditAccount::registrationError( const QString& title, const QString& what )
{
reg_in_progress=false;
KMessageBox::information(this, what, title);
}
bool GaduEditAccount::validateData()
{
// FIXME: I need to disable somehow next, finish and back button here
if (reg_in_progress){
return false;
}
if (radio1->isChecked()){
if (loginEdit_->text().toInt()<0 || loginEdit_->text().toInt()==0){
KMessageBox::sorry(this, i18n("<b>UIN should be a positive number.</b>"), i18n("Gadu-Gadu"));
return false;
}
if (passwordEdit_->text().isEmpty() && rememberCheck_->isChecked()){
KMessageBox::sorry(this, i18n("<b>Enter password please.</b>"), i18n("Gadu-Gadu"));
return false;
}
}
else{
if (emailedit_->text().isEmpty()){
KMessageBox::sorry(this, i18n("<b>Please enter a valid email addres</b>"), i18n("Gadu-Gadu"));
return false;
}
if (passwordEdit2__->text().isEmpty()){
KMessageBox::sorry(this, i18n("<b>Enter password please.</b>"), i18n("Gadu-Gadu"));
return false;
}
kdDebug(14100)<<"GJ"<<"email:" << emailedit_->text() <<endl;
reg_in_progress=true;
rcmd=new RegisterCommand(emailedit_->text(),
passwordEdit2__->text(), this);
connect( rcmd, SIGNAL(done(const QString&, const QString&)),
SLOT(registrationComplete(const QString&, const QString&)) );
connect( rcmd, SIGNAL(error(const QString&, const QString&)),
SLOT(registrationError(const QString&, const QString&)) );
rcmd->execute();
return false;
}
return true;
}
KopeteAccount* GaduEditAccount::apply()
{
if (m_account){
kdDebug(14100)<<"GJ"<<"ACCOUNT CHANGE"<<endl;
}
else{
if (radio1->isChecked()){
kdDebug(14100)<<"GJ"<<"NEW ACCOUNT"<<endl;
m_account = new GaduAccount( protocol_, loginEdit_->text() );
if (!m_account){
kdDebug(14100)<<"Couldn't create GaduAccount object, fatal!"<<endl;
return NULL;
}
m_account->setAccountId(loginEdit_->text());
}
else{
// should never happend
return NULL;
}
}
m_account->setAutoLogin(autoLoginCheck_->isChecked());
if(rememberCheck_->isChecked()){
m_account->setPassword(passwordEdit_->text());
}
else{
m_account->setPassword(QString::null);
}
m_account->myself()->rename(NickName->text());
// this is changed only here, so i won't add any proper handling now
m_account->setPluginData(m_account->protocol(),
QString::fromLatin1("nickName"), NickName->text());
m_account->setAutoLogin(autoLoginCheck_->isChecked());
return m_account;
}
#include "gadueditaccount.moc"
<commit_msg>no comment :-)<commit_after>//
// Current author and maintainer: Grzegorz Jaskiewicz
// gj at pointblue.com.pl
//
// Kopete initial author:
// Copyright (C) 2002-2003 Zack Rusin <zack@kde.org>
//
// 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
#include "gadueditaccount.h"
#include "gaduaccount.h"
#include "gaduprotocol.h"
#include <qradiobutton.h>
#include <qlabel.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qbutton.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <klocale.h>
GaduEditAccount::GaduEditAccount( GaduProtocol *proto, KopeteAccount *ident,
QWidget *parent, const char *name )
: GaduAccountEditUI( parent, name ), EditAccountWidget( ident )
,
protocol_( proto ), rcmd(0)
{
if (!m_account){
reg_in_progress=false;
kdDebug(14100)<<"GJ"<<"NEW ACCOUNT WIZ"<<endl;
radio1->setDisabled(false);
radio2->setDisabled(false);
textLabel2_2->setDisabled(false);
textLabel1_2->setDisabled(false);
emailedit_->setDisabled(false);
passwordEdit2__->setDisabled(false);
}
else{
kdDebug(14100)<<"GJ"<<"ACCOUNT EDIT"<<endl;
radio1->setDisabled(true);
radio2->setDisabled(true);
radio2->setDisabled(true);
textLabel2_2->setDisabled(true);
loginEdit_->setDisabled(true);
emailedit_->setDisabled(true);
passwordEdit2__->setDisabled(true);
loginEdit_->setText(m_account->accountId());
if (m_account->rememberPassword()){
passwordEdit_->setText(m_account->getPassword());
}
else{
passwordEdit_->setText("");
}
NickName->setText(m_account->myself()->displayName());
rememberCheck_->setChecked(m_account->rememberPassword());
autoLoginCheck_->setChecked(m_account->autoLogin());
}
}
void GaduEditAccount::registrationComplete( const QString& title, const QString& )
{
reg_in_progress=false;
kdDebug(14100)<<"GJ"<<" ID " << title << endl;
// i am sure rcmd is valid, since it sends this signal ;)
loginEdit_->setText(QString::number(rcmd->newUin()));
passwordEdit_->setText(passwordEdit2__->text());
radio1->setChecked(true);
radio2->setChecked(false);
radio1->setDisabled(true);
radio2->setDisabled(true);
textLabel2_2->setDisabled(true);
textLabel1_2->setDisabled(true);
emailedit_->setDisabled(true);
passwordEdit2__->setDisabled(true);
rememberCheck_->setChecked(true);
KMessageBox::information(this, i18n("<b>You've registered a new acount.</b>"), i18n("Gadu-Gadu"));
}
void GaduEditAccount::registrationError( const QString& title, const QString& what )
{
reg_in_progress=false;
KMessageBox::information(this, what, title);
}
bool GaduEditAccount::validateData()
{
// FIXME: I need to disable somehow next, finish and back button here
if (reg_in_progress){
return false;
}
if (radio1->isChecked()){
if (loginEdit_->text().toInt()<0 || loginEdit_->text().toInt()==0){
KMessageBox::sorry(this, i18n("<b>UIN should be a positive number.</b>"), i18n("Gadu-Gadu"));
return false;
}
if (passwordEdit_->text().isEmpty() && rememberCheck_->isChecked()){
KMessageBox::sorry(this, i18n("<b>Enter password please.</b>"), i18n("Gadu-Gadu"));
return false;
}
}
else{
if (emailedit_->text().isEmpty()){
KMessageBox::sorry(this, i18n("<b>Please enter a valid email addres</b>"), i18n("Gadu-Gadu"));
return false;
}
if (passwordEdit2__->text().isEmpty()){
KMessageBox::sorry(this, i18n("<b>Enter password please.</b>"), i18n("Gadu-Gadu"));
return false;
}
kdDebug(14100)<<"GJ"<<"email:" << emailedit_->text() <<endl;
reg_in_progress=true;
rcmd=new RegisterCommand(emailedit_->text(),
passwordEdit2__->text(), this);
connect( rcmd, SIGNAL(done(const QString&, const QString&)),
SLOT(registrationComplete(const QString&, const QString&)) );
connect( rcmd, SIGNAL(error(const QString&, const QString&)),
SLOT(registrationError(const QString&, const QString&)) );
rcmd->execute();
return false;
}
return true;
}
KopeteAccount* GaduEditAccount::apply()
{
if (m_account){
kdDebug(14100)<<"GJ"<<"ACCOUNT CHANGE"<<endl;
}
else{
if (radio1->isChecked()){
kdDebug(14100)<<"GJ"<<"NEW ACCOUNT"<<endl;
m_account = new GaduAccount( protocol_, loginEdit_->text() );
if (!m_account){
kdDebug(14100)<<"Couldn't create GaduAccount object, fatal!"<<endl;
return NULL;
}
m_account->setAccountId(loginEdit_->text());
}
else{
// should never happend
return NULL;
}
}
m_account->setAutoLogin(autoLoginCheck_->isChecked());
if(rememberCheck_->isChecked()){
m_account->setPassword(passwordEdit_->text());
}
else{
m_account->setPassword(QString::null);
}
m_account->myself()->rename(NickName->text());
// this is changed only here, so i won't add any proper handling now
m_account->setPluginData(m_account->protocol(),
QString::fromLatin1("nickName"), NickName->text());
m_account->setAutoLogin(autoLoginCheck_->isChecked());
return m_account;
}
#include "gadueditaccount.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** Copyright (c) 2013 Hugues Delorme
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "optionspage.h"
#include "bazaarsettings.h"
#include "bazaarplugin.h"
#include <coreplugin/icore.h>
#include <vcsbase/vcsbaseconstants.h>
#include <QTextStream>
using namespace Bazaar::Internal;
using namespace Bazaar;
OptionsPageWidget::OptionsPageWidget(QWidget *parent)
: QWidget(parent)
{
m_ui.setupUi(this);
m_ui.commandChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_ui.commandChooser->setPromptDialogTitle(tr("Bazaar Command"));
}
BazaarSettings OptionsPageWidget::settings() const
{
BazaarSettings s = BazaarPlugin::instance()->settings();
s.setValue(BazaarSettings::binaryPathKey, m_ui.commandChooser->rawPath());
s.setValue(BazaarSettings::userNameKey, m_ui.defaultUsernameLineEdit->text().trimmed());
s.setValue(BazaarSettings::userEmailKey, m_ui.defaultEmailLineEdit->text().trimmed());
s.setValue(BazaarSettings::logCountKey, m_ui.logEntriesCount->value());
s.setValue(BazaarSettings::timeoutKey, m_ui.timeout->value());
return s;
}
void OptionsPageWidget::setSettings(const BazaarSettings &s)
{
m_ui.commandChooser->setPath(s.stringValue(BazaarSettings::binaryPathKey));
m_ui.defaultUsernameLineEdit->setText(s.stringValue(BazaarSettings::userNameKey));
m_ui.defaultEmailLineEdit->setText(s.stringValue(BazaarSettings::userEmailKey));
m_ui.logEntriesCount->setValue(s.intValue(BazaarSettings::logCountKey));
m_ui.timeout->setValue(s.intValue(BazaarSettings::timeoutKey));
}
QString OptionsPageWidget::searchKeywords() const
{
QString rc;
QLatin1Char sep(' ');
QTextStream(&rc)
<< sep << m_ui.configGroupBox->title()
<< sep << m_ui.commandLabel->text()
<< sep << m_ui.userGroupBox->title()
<< sep << m_ui.defaultUsernameLabel->text()
<< sep << m_ui.defaultEmailLabel->text()
<< sep << m_ui.miscGroupBox->title()
<< sep << m_ui.showLogEntriesLabel->text()
<< sep << m_ui.timeoutSecondsLabel->text()
;
rc.remove(QLatin1Char('&'));
return rc;
}
OptionsPage::OptionsPage()
{
setId(VcsBase::Constants::VCS_ID_BAZAAR);
setDisplayName(tr("Bazaar"));
}
QWidget *OptionsPage::createPage(QWidget *parent)
{
if (!m_optionsPageWidget)
m_optionsPageWidget = new OptionsPageWidget(parent);
m_optionsPageWidget->setSettings(BazaarPlugin::instance()->settings());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_optionsPageWidget->searchKeywords();
return m_optionsPageWidget;
}
void OptionsPage::apply()
{
if (!m_optionsPageWidget)
return;
BazaarPlugin *plugin = BazaarPlugin::instance();
const BazaarSettings newSettings = m_optionsPageWidget->settings();
if (newSettings != plugin->settings()) {
//assume success and emit signal that settings are changed;
plugin->setSettings(newSettings);
newSettings.writeSettings(Core::ICore::settings());
emit settingsChanged();
}
}
bool OptionsPage::matches(const QString &s) const
{
return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}
<commit_msg>Bazaar: Add history completer to path choosers<commit_after>/**************************************************************************
**
** Copyright (c) 2013 Hugues Delorme
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "optionspage.h"
#include "bazaarsettings.h"
#include "bazaarplugin.h"
#include <coreplugin/icore.h>
#include <vcsbase/vcsbaseconstants.h>
#include <QTextStream>
using namespace Bazaar::Internal;
using namespace Bazaar;
OptionsPageWidget::OptionsPageWidget(QWidget *parent)
: QWidget(parent)
{
m_ui.setupUi(this);
m_ui.commandChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_ui.commandChooser->setPromptDialogTitle(tr("Bazaar Command"));
m_ui.commandChooser->setHistoryCompleter(QLatin1String("Bazaar.Command.History"));
}
BazaarSettings OptionsPageWidget::settings() const
{
BazaarSettings s = BazaarPlugin::instance()->settings();
s.setValue(BazaarSettings::binaryPathKey, m_ui.commandChooser->rawPath());
s.setValue(BazaarSettings::userNameKey, m_ui.defaultUsernameLineEdit->text().trimmed());
s.setValue(BazaarSettings::userEmailKey, m_ui.defaultEmailLineEdit->text().trimmed());
s.setValue(BazaarSettings::logCountKey, m_ui.logEntriesCount->value());
s.setValue(BazaarSettings::timeoutKey, m_ui.timeout->value());
return s;
}
void OptionsPageWidget::setSettings(const BazaarSettings &s)
{
m_ui.commandChooser->setPath(s.stringValue(BazaarSettings::binaryPathKey));
m_ui.defaultUsernameLineEdit->setText(s.stringValue(BazaarSettings::userNameKey));
m_ui.defaultEmailLineEdit->setText(s.stringValue(BazaarSettings::userEmailKey));
m_ui.logEntriesCount->setValue(s.intValue(BazaarSettings::logCountKey));
m_ui.timeout->setValue(s.intValue(BazaarSettings::timeoutKey));
}
QString OptionsPageWidget::searchKeywords() const
{
QString rc;
QLatin1Char sep(' ');
QTextStream(&rc)
<< sep << m_ui.configGroupBox->title()
<< sep << m_ui.commandLabel->text()
<< sep << m_ui.userGroupBox->title()
<< sep << m_ui.defaultUsernameLabel->text()
<< sep << m_ui.defaultEmailLabel->text()
<< sep << m_ui.miscGroupBox->title()
<< sep << m_ui.showLogEntriesLabel->text()
<< sep << m_ui.timeoutSecondsLabel->text()
;
rc.remove(QLatin1Char('&'));
return rc;
}
OptionsPage::OptionsPage()
{
setId(VcsBase::Constants::VCS_ID_BAZAAR);
setDisplayName(tr("Bazaar"));
}
QWidget *OptionsPage::createPage(QWidget *parent)
{
if (!m_optionsPageWidget)
m_optionsPageWidget = new OptionsPageWidget(parent);
m_optionsPageWidget->setSettings(BazaarPlugin::instance()->settings());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_optionsPageWidget->searchKeywords();
return m_optionsPageWidget;
}
void OptionsPage::apply()
{
if (!m_optionsPageWidget)
return;
BazaarPlugin *plugin = BazaarPlugin::instance();
const BazaarSettings newSettings = m_optionsPageWidget->settings();
if (newSettings != plugin->settings()) {
//assume success and emit signal that settings are changed;
plugin->setSettings(newSettings);
newSettings.writeSettings(Core::ICore::settings());
emit settingsChanged();
}
}
bool OptionsPage::matches(const QString &s) const
{
return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XercesNodeListWrapper.hpp"
#include <cassert>
#include <xercesc/DOM/DOMNodeList.hpp>
#include "XercesWrapperNavigator.hpp"
XercesNodeListWrapper::XercesNodeListWrapper(
const DOMNodeList* theXercesNodeList,
const XercesWrapperNavigator& theNavigator) :
XalanNodeList(),
m_xercesNodeList(theXercesNodeList),
m_navigator(theNavigator)
{
assert(theXercesNodeList != 0);
}
XercesNodeListWrapper::~XercesNodeListWrapper()
{
}
XercesNodeListWrapper::XercesNodeListWrapper(const XercesNodeListWrapper& theSource) :
XalanNodeList(theSource),
m_xercesNodeList(theSource.m_xercesNodeList),
m_navigator(theSource.m_navigator)
{
}
XalanNode*
XercesNodeListWrapper::item(unsigned int index) const
{
assert(m_xercesNodeList != 0);
return m_navigator.mapNode(m_xercesNodeList->item(index));
}
unsigned int
XercesNodeListWrapper::getLength() const
{
assert(m_xercesNodeList != 0);
return m_xercesNodeList->getLength();
}
<commit_msg>Corrected case of file name.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XercesNodeListWrapper.hpp"
#include <cassert>
#include <xercesc/dom/DOMNodeList.hpp>
#include "XercesWrapperNavigator.hpp"
XercesNodeListWrapper::XercesNodeListWrapper(
const DOMNodeList* theXercesNodeList,
const XercesWrapperNavigator& theNavigator) :
XalanNodeList(),
m_xercesNodeList(theXercesNodeList),
m_navigator(theNavigator)
{
assert(theXercesNodeList != 0);
}
XercesNodeListWrapper::~XercesNodeListWrapper()
{
}
XercesNodeListWrapper::XercesNodeListWrapper(const XercesNodeListWrapper& theSource) :
XalanNodeList(theSource),
m_xercesNodeList(theSource.m_xercesNodeList),
m_navigator(theSource.m_navigator)
{
}
XalanNode*
XercesNodeListWrapper::item(unsigned int index) const
{
assert(m_xercesNodeList != 0);
return m_navigator.mapNode(m_xercesNodeList->item(index));
}
unsigned int
XercesNodeListWrapper::getLength() const
{
assert(m_xercesNodeList != 0);
return m_xercesNodeList->getLength();
}
<|endoftext|>
|
<commit_before>/** -*- c++ -*-
* networkaccount.cpp
*
* Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
* Copyright (c) 2002 Marc Mutz <mutz@kde.org>
*
* This file is based on work on pop3 and imap account implementations
* by Don Sanders <sanders@kde.org> and Michael Haeckel <haeckel@kde.org>
*
* 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; version 2 of the License
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "networkaccount.h"
#include "accountmanager.h"
#include "kmkernel.h"
#include "globalsettings.h"
#include <kconfig.h>
#include <kio/global.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kwallet.h>
using KIO::MetaData;
using KWallet::Wallet;
#include <climits>
namespace KMail {
// for restricting number of concurrent connections to the same server
static QMap<QString, int> s_serverConnections;
NetworkAccount::NetworkAccount( AccountManager * parent, const QString & name, uint id )
: KMAccount( parent, name, id ),
mSlave( 0 ),
mAuth( "*" ),
mPort( 0 ),
mStorePasswd( false ),
mUseSSL( false ),
mUseTLS( false ),
mAskAgain( false ),
mPasswdDirty( false ),
mStorePasswdInConfig( false )
{
}
NetworkAccount::~NetworkAccount() {
}
void NetworkAccount::init() {
KMAccount::init();
mSieveConfig = SieveConfig();
mLogin = QString::null;
mPasswd = QString::null;
mAuth = "*";
mHost = QString::null;
mPort = defaultPort();
mStorePasswd = false;
mUseSSL = false;
mUseTLS = false;
mAskAgain = false;
}
//
//
// Getters and Setters
//
//
void NetworkAccount::setLogin( const QString & login ) {
mLogin = login;
}
QString NetworkAccount::passwd() const {
if ( storePasswd() && mPasswd.isEmpty() )
mOwner->readPasswords();
return decryptStr( mPasswd );
}
void NetworkAccount::setPasswd( const QString & passwd, bool storeInConfig ) {
if ( mPasswd != encryptStr( passwd ) ) {
mPasswd = encryptStr( passwd );
mPasswdDirty = true;
}
setStorePasswd( storeInConfig );
}
void NetworkAccount::clearPasswd() {
setPasswd( "", false );
}
void NetworkAccount::setAuth( const QString & auth ) {
mAuth = auth;
}
void NetworkAccount::setStorePasswd( bool store ) {
if( mStorePasswd != store && store )
mPasswdDirty = true;
mStorePasswd = store;
}
void NetworkAccount::setHost( const QString & host ) {
mHost = host;
}
void NetworkAccount::setPort( unsigned short int port ) {
mPort = port;
}
void NetworkAccount::setUseSSL( bool use ) {
mUseSSL = use;
}
void NetworkAccount::setUseTLS( bool use ) {
mUseTLS = use;
}
void NetworkAccount::setSieveConfig( const SieveConfig & config ) {
mSieveConfig = config;
}
//
//
// read/write config
//
//
void NetworkAccount::readConfig( /*const*/ KConfig/*Base*/ & config ) {
KMAccount::readConfig( config );
setLogin( config.readEntry( "login" ) );
if ( config.readNumEntry( "store-passwd", false ) ) { // ### s/Num/Bool/
mStorePasswd = true;
QString encpasswd = config.readEntry( "pass" );
if ( encpasswd.isEmpty() ) {
encpasswd = config.readEntry( "passwd" );
if ( !encpasswd.isEmpty() ) encpasswd = importPassword( encpasswd );
}
if ( !encpasswd.isEmpty() ) {
setPasswd( decryptStr( encpasswd ), true );
// migrate to KWallet if available
if ( Wallet::isEnabled() ) {
config.deleteEntry( "pass" );
config.deleteEntry( "passwd" );
mPasswdDirty = true;
mStorePasswdInConfig = false;
} else {
mPasswdDirty = false; // set by setPasswd() on first read
mStorePasswdInConfig = true;
}
} else {
// read password if wallet is already open, otherwise defer to on-demand loading
if ( Wallet::isOpen( Wallet::NetworkWallet() ) )
readPassword();
}
} else {
setPasswd( "", false );
}
setHost( config.readEntry( "host" ) );
unsigned int port = config.readUnsignedNumEntry( "port", defaultPort() );
if ( port > USHRT_MAX ) port = defaultPort();
setPort( port );
setAuth( config.readEntry( "auth", "*" ) );
setUseSSL( config.readBoolEntry( "use-ssl", false ) );
setUseTLS( config.readBoolEntry( "use-tls", false ) );
mSieveConfig.readConfig( config );
}
void NetworkAccount::writeConfig( KConfig/*Base*/ & config ) /*const*/ {
KMAccount::writeConfig( config );
config.writeEntry( "login", login() );
config.writeEntry( "store-passwd", storePasswd() );
if ( storePasswd() ) {
// write password to the wallet if possbile and necessary
bool passwdStored = false;
if ( mPasswdDirty ) {
Wallet *wallet = kmkernel->wallet();
if ( wallet && wallet->writePassword( "account-" + QString::number(mId), passwd() ) == 0 ) {
passwdStored = true;
mPasswdDirty = false;
mStorePasswdInConfig = false;
}
} else {
passwdStored = !mStorePasswdInConfig; // already in the wallet
}
// if wallet is not available, write to config file, since the account
// manager deletes this group, we need to write it always
if ( !passwdStored && ( mStorePasswdInConfig || KMessageBox::warningYesNo( 0,
i18n("KWallet is not available. It is strongly recommended to use "
"KWallet for managing your passwords.\n"
"However, KMail can store the password in its configuration "
"file instead. The password is stored in an obfuscated format, "
"but should not be considered secure from decryption efforts "
"if access to the configuration file is obtained.\n"
"Do you want to store the password for account '%1' in the "
"configuration file?").arg( name() ),
i18n("KWallet Not Available"),
KGuiItem( i18n("Store Password") ),
KGuiItem( i18n("Do Not Store Password") ) )
== KMessageBox::Yes ) ) {
config.writeEntry( "pass", encryptStr( passwd() ) );
mStorePasswdInConfig = true;
}
}
// delete password from the wallet if password storage is disabled
if (!storePasswd() && !Wallet::keyDoesNotExist(
Wallet::NetworkWallet(), "kmail", "account-" + QString::number(mId))) {
Wallet *wallet = kmkernel->wallet();
if (wallet)
wallet->removeEntry( "account-" + QString::number(mId) );
}
config.writeEntry( "host", host() );
config.writeEntry( "port", static_cast<unsigned int>( port() ) );
config.writeEntry( "auth", auth() );
config.writeEntry( "use-ssl", useSSL() );
config.writeEntry( "use-tls", useTLS() );
mSieveConfig.writeConfig( config );
}
//
//
// Network processing
//
//
KURL NetworkAccount::getUrl() const {
KURL url;
url.setProtocol( protocol() );
url.setUser( login() );
url.setPass( passwd() );
url.setHost( host() );
url.setPort( port() );
return url;
}
MetaData NetworkAccount::slaveConfig() const {
MetaData m;
m.insert( "tls", useTLS() ? "on" : "off" );
return m;
}
void NetworkAccount::pseudoAssign( const KMAccount * a ) {
KMAccount::pseudoAssign( a );
const NetworkAccount * n = dynamic_cast<const NetworkAccount*>( a );
if ( !n ) return;
setLogin( n->login() );
setPasswd( n->passwd(), n->storePasswd() );
setHost( n->host() );
setPort( n->port() );
setAuth( n->auth() );
setUseSSL( n->useSSL() );
setUseTLS( n->useTLS() );
setSieveConfig( n->sieveConfig() );
}
void NetworkAccount::readPassword() {
if ( !storePasswd() )
return;
// ### workaround for broken Wallet::keyDoesNotExist() which returns wrong
// results for new entries without closing and reopening the wallet
if ( Wallet::isOpen( Wallet::NetworkWallet() ) )
{
Wallet *wallet = kmkernel->wallet();
if (!wallet || !wallet->hasEntry( "account-" + QString::number(mId) ) )
return;
}
else
{
if (Wallet::keyDoesNotExist( Wallet::NetworkWallet(), "kmail", "account-" + QString::number(mId) ) )
return;
}
if ( kmkernel->wallet() ) {
QString passwd;
kmkernel->wallet()->readPassword( "account-" + QString::number(mId), passwd );
setPasswd( passwd, true );
mPasswdDirty = false;
}
}
void NetworkAccount::setCheckingMail( bool checking )
{
mCheckingMail = checking;
if ( host().isEmpty() )
return;
if ( checking ) {
if ( s_serverConnections.find( host() ) != s_serverConnections.end() )
s_serverConnections[host()] += 1;
else
s_serverConnections[host()] = 1;
kdDebug(5006) << "check mail started - connections for host "
<< host() << " now is "
<< s_serverConnections[host()] << endl;
} else {
if ( s_serverConnections.find( host() ) != s_serverConnections.end() &&
s_serverConnections[host()] > 0 ) {
s_serverConnections[host()] -= 1;
kdDebug(5006) << "connections to server " << host()
<< " now " << s_serverConnections[host()] << endl;
}
}
}
bool NetworkAccount::mailCheckCanProceed() const
{
bool offlineMode = KMKernel::isOffline();
kdDebug(5006) << "for host " << host()
<< " current connections="
<< (s_serverConnections.find(host())==s_serverConnections.end() ? 0 : s_serverConnections[host()])
<< " and limit is " << GlobalSettings::self()->maxConnectionsPerHost()
<< endl;
bool connectionLimitForHostReached = !host().isEmpty()
&& GlobalSettings::self()->maxConnectionsPerHost() > 0
&& s_serverConnections.find( host() ) != s_serverConnections.end()
&& s_serverConnections[host()] >= GlobalSettings::self()->maxConnectionsPerHost();
kdDebug(5006) << "connection limit reached: "
<< connectionLimitForHostReached << endl;
return ( !connectionLimitForHostReached && !offlineMode );
}
void NetworkAccount::resetConnectionList( NetworkAccount* acct )
{
s_serverConnections[ acct->host() ] = 0;
}
} // namespace KMail
#include "networkaccount.moc"
<commit_msg>Write the password (to wallet or config file) immediately after setting it in the auth dialog, not when kmail exits cleanly (which it doesn't do when session management terminates it) BUG: 97324, 98545<commit_after>/** -*- c++ -*-
* networkaccount.cpp
*
* Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
* Copyright (c) 2002 Marc Mutz <mutz@kde.org>
*
* This file is based on work on pop3 and imap account implementations
* by Don Sanders <sanders@kde.org> and Michael Haeckel <haeckel@kde.org>
*
* 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; version 2 of the License
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "networkaccount.h"
#include "accountmanager.h"
#include "kmkernel.h"
#include "globalsettings.h"
#include <kconfig.h>
#include <kio/global.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kwallet.h>
using KIO::MetaData;
using KWallet::Wallet;
#include <climits>
namespace KMail {
// for restricting number of concurrent connections to the same server
static QMap<QString, int> s_serverConnections;
NetworkAccount::NetworkAccount( AccountManager * parent, const QString & name, uint id )
: KMAccount( parent, name, id ),
mSlave( 0 ),
mAuth( "*" ),
mPort( 0 ),
mStorePasswd( false ),
mUseSSL( false ),
mUseTLS( false ),
mAskAgain( false ),
mPasswdDirty( false ),
mStorePasswdInConfig( false )
{
}
NetworkAccount::~NetworkAccount() {
}
void NetworkAccount::init() {
KMAccount::init();
mSieveConfig = SieveConfig();
mLogin = QString::null;
mPasswd = QString::null;
mAuth = "*";
mHost = QString::null;
mPort = defaultPort();
mStorePasswd = false;
mUseSSL = false;
mUseTLS = false;
mAskAgain = false;
}
//
//
// Getters and Setters
//
//
void NetworkAccount::setLogin( const QString & login ) {
mLogin = login;
}
QString NetworkAccount::passwd() const {
if ( storePasswd() && mPasswd.isEmpty() )
mOwner->readPasswords();
return decryptStr( mPasswd );
}
void NetworkAccount::setPasswd( const QString & passwd, bool storeInConfig ) {
if ( mPasswd != encryptStr( passwd ) ) {
mPasswd = encryptStr( passwd );
mPasswdDirty = true;
}
setStorePasswd( storeInConfig );
if ( storeInConfig ) {
kmkernel->acctMgr()->writeConfig( true );
}
}
void NetworkAccount::clearPasswd() {
setPasswd( "", false );
}
void NetworkAccount::setAuth( const QString & auth ) {
mAuth = auth;
}
void NetworkAccount::setStorePasswd( bool store ) {
if( mStorePasswd != store && store )
mPasswdDirty = true;
mStorePasswd = store;
}
void NetworkAccount::setHost( const QString & host ) {
mHost = host;
}
void NetworkAccount::setPort( unsigned short int port ) {
mPort = port;
}
void NetworkAccount::setUseSSL( bool use ) {
mUseSSL = use;
}
void NetworkAccount::setUseTLS( bool use ) {
mUseTLS = use;
}
void NetworkAccount::setSieveConfig( const SieveConfig & config ) {
mSieveConfig = config;
}
//
//
// read/write config
//
//
void NetworkAccount::readConfig( /*const*/ KConfig/*Base*/ & config ) {
KMAccount::readConfig( config );
setLogin( config.readEntry( "login" ) );
if ( config.readNumEntry( "store-passwd", false ) ) { // ### s/Num/Bool/
mStorePasswd = true;
QString encpasswd = config.readEntry( "pass" );
if ( encpasswd.isEmpty() ) {
encpasswd = config.readEntry( "passwd" );
if ( !encpasswd.isEmpty() ) encpasswd = importPassword( encpasswd );
}
if ( !encpasswd.isEmpty() ) {
setPasswd( decryptStr( encpasswd ), true );
// migrate to KWallet if available
if ( Wallet::isEnabled() ) {
config.deleteEntry( "pass" );
config.deleteEntry( "passwd" );
mPasswdDirty = true;
mStorePasswdInConfig = false;
} else {
mPasswdDirty = false; // set by setPasswd() on first read
mStorePasswdInConfig = true;
}
} else {
// read password if wallet is already open, otherwise defer to on-demand loading
if ( Wallet::isOpen( Wallet::NetworkWallet() ) )
readPassword();
}
} else {
setPasswd( "", false );
}
setHost( config.readEntry( "host" ) );
unsigned int port = config.readUnsignedNumEntry( "port", defaultPort() );
if ( port > USHRT_MAX ) port = defaultPort();
setPort( port );
setAuth( config.readEntry( "auth", "*" ) );
setUseSSL( config.readBoolEntry( "use-ssl", false ) );
setUseTLS( config.readBoolEntry( "use-tls", false ) );
mSieveConfig.readConfig( config );
}
void NetworkAccount::writeConfig( KConfig/*Base*/ & config ) /*const*/ {
KMAccount::writeConfig( config );
config.writeEntry( "login", login() );
config.writeEntry( "store-passwd", storePasswd() );
if ( storePasswd() ) {
// write password to the wallet if possbile and necessary
bool passwdStored = false;
if ( mPasswdDirty ) {
Wallet *wallet = kmkernel->wallet();
if ( wallet && wallet->writePassword( "account-" + QString::number(mId), passwd() ) == 0 ) {
passwdStored = true;
mPasswdDirty = false;
mStorePasswdInConfig = false;
}
} else {
passwdStored = !mStorePasswdInConfig; // already in the wallet
}
// if wallet is not available, write to config file, since the account
// manager deletes this group, we need to write it always
if ( !passwdStored && ( mStorePasswdInConfig || KMessageBox::warningYesNo( 0,
i18n("KWallet is not available. It is strongly recommended to use "
"KWallet for managing your passwords.\n"
"However, KMail can store the password in its configuration "
"file instead. The password is stored in an obfuscated format, "
"but should not be considered secure from decryption efforts "
"if access to the configuration file is obtained.\n"
"Do you want to store the password for account '%1' in the "
"configuration file?").arg( name() ),
i18n("KWallet Not Available"),
KGuiItem( i18n("Store Password") ),
KGuiItem( i18n("Do Not Store Password") ) )
== KMessageBox::Yes ) ) {
config.writeEntry( "pass", encryptStr( passwd() ) );
mStorePasswdInConfig = true;
}
}
// delete password from the wallet if password storage is disabled
if (!storePasswd() && !Wallet::keyDoesNotExist(
Wallet::NetworkWallet(), "kmail", "account-" + QString::number(mId))) {
Wallet *wallet = kmkernel->wallet();
if (wallet)
wallet->removeEntry( "account-" + QString::number(mId) );
}
config.writeEntry( "host", host() );
config.writeEntry( "port", static_cast<unsigned int>( port() ) );
config.writeEntry( "auth", auth() );
config.writeEntry( "use-ssl", useSSL() );
config.writeEntry( "use-tls", useTLS() );
mSieveConfig.writeConfig( config );
}
//
//
// Network processing
//
//
KURL NetworkAccount::getUrl() const {
KURL url;
url.setProtocol( protocol() );
url.setUser( login() );
url.setPass( passwd() );
url.setHost( host() );
url.setPort( port() );
return url;
}
MetaData NetworkAccount::slaveConfig() const {
MetaData m;
m.insert( "tls", useTLS() ? "on" : "off" );
return m;
}
void NetworkAccount::pseudoAssign( const KMAccount * a ) {
KMAccount::pseudoAssign( a );
const NetworkAccount * n = dynamic_cast<const NetworkAccount*>( a );
if ( !n ) return;
setLogin( n->login() );
setPasswd( n->passwd(), n->storePasswd() );
setHost( n->host() );
setPort( n->port() );
setAuth( n->auth() );
setUseSSL( n->useSSL() );
setUseTLS( n->useTLS() );
setSieveConfig( n->sieveConfig() );
}
void NetworkAccount::readPassword() {
if ( !storePasswd() )
return;
// ### workaround for broken Wallet::keyDoesNotExist() which returns wrong
// results for new entries without closing and reopening the wallet
if ( Wallet::isOpen( Wallet::NetworkWallet() ) )
{
Wallet *wallet = kmkernel->wallet();
if (!wallet || !wallet->hasEntry( "account-" + QString::number(mId) ) )
return;
}
else
{
if (Wallet::keyDoesNotExist( Wallet::NetworkWallet(), "kmail", "account-" + QString::number(mId) ) )
return;
}
if ( kmkernel->wallet() ) {
QString passwd;
kmkernel->wallet()->readPassword( "account-" + QString::number(mId), passwd );
setPasswd( passwd, true );
mPasswdDirty = false;
}
}
void NetworkAccount::setCheckingMail( bool checking )
{
mCheckingMail = checking;
if ( host().isEmpty() )
return;
if ( checking ) {
if ( s_serverConnections.find( host() ) != s_serverConnections.end() )
s_serverConnections[host()] += 1;
else
s_serverConnections[host()] = 1;
kdDebug(5006) << "check mail started - connections for host "
<< host() << " now is "
<< s_serverConnections[host()] << endl;
} else {
if ( s_serverConnections.find( host() ) != s_serverConnections.end() &&
s_serverConnections[host()] > 0 ) {
s_serverConnections[host()] -= 1;
kdDebug(5006) << "connections to server " << host()
<< " now " << s_serverConnections[host()] << endl;
}
}
}
bool NetworkAccount::mailCheckCanProceed() const
{
bool offlineMode = KMKernel::isOffline();
kdDebug(5006) << "for host " << host()
<< " current connections="
<< (s_serverConnections.find(host())==s_serverConnections.end() ? 0 : s_serverConnections[host()])
<< " and limit is " << GlobalSettings::self()->maxConnectionsPerHost()
<< endl;
bool connectionLimitForHostReached = !host().isEmpty()
&& GlobalSettings::self()->maxConnectionsPerHost() > 0
&& s_serverConnections.find( host() ) != s_serverConnections.end()
&& s_serverConnections[host()] >= GlobalSettings::self()->maxConnectionsPerHost();
kdDebug(5006) << "connection limit reached: "
<< connectionLimitForHostReached << endl;
return ( !connectionLimitForHostReached && !offlineMode );
}
void NetworkAccount::resetConnectionList( NetworkAccount* acct )
{
s_serverConnections[ acct->host() ] = 0;
}
} // namespace KMail
#include "networkaccount.moc"
<|endoftext|>
|
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*-
regexplineedit.cpp
This file is part of KMail, the KDE mail client.
Copyright (c) 2004 Ingo Kloecker <kloecker@kde.org>
KMail 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.
KMail 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "regexplineedit.h"
#include <klocale.h>
#include <klineedit.h>
#include <kparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <kdialog.h>
#include <qlayout.h>
#include <qstring.h>
#include <qpushbutton.h>
#include <qdialog.h>
namespace KMail {
RegExpLineEdit::RegExpLineEdit( QWidget *parent, const char *name )
: QWidget( parent, name ),
mLineEdit( 0 ),
mRegExpEditButton( 0 ),
mRegExpEditDialog( 0 )
{
initWidget();
}
RegExpLineEdit::RegExpLineEdit( const QString &str, QWidget *parent,
const char *name )
: QWidget( parent, name ),
mLineEdit( 0 ),
mRegExpEditButton( 0 ),
mRegExpEditDialog( 0 )
{
initWidget( str );
}
void RegExpLineEdit::initWidget( const QString &str )
{
QHBoxLayout * hlay = new QHBoxLayout( this, 0, KDialog::spacingHint() );
mLineEdit = new KLineEdit( str, this );
hlay->addWidget( mLineEdit );
connect( mLineEdit, SIGNAL( textChanged( const QString & ) ),
this, SIGNAL( textChanged( const QString & ) ) );
if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) {
mRegExpEditButton = new QPushButton( i18n("Edit..."), this,
"mRegExpEditButton" );
mRegExpEditButton->setSizePolicy( QSizePolicy::Minimum,
QSizePolicy::Fixed );
hlay->addWidget( mRegExpEditButton );
connect( mRegExpEditButton, SIGNAL( clicked() ),
this, SLOT( slotEditRegExp() ) );
}
}
void RegExpLineEdit::clear()
{
mLineEdit->clear();
}
QString RegExpLineEdit::text() const
{
return mLineEdit->text();
}
void RegExpLineEdit::setText( const QString & str )
{
mLineEdit->setText( str );
}
void RegExpLineEdit::showEditButton( bool show )
{
if ( !mRegExpEditButton )
return;
if ( show )
mRegExpEditButton->show();
else
mRegExpEditButton->hide();
}
void RegExpLineEdit::slotEditRegExp()
{
if ( !mRegExpEditDialog )
mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this );
KRegExpEditorInterface *iface =
static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) );
if( iface ) {
iface->setRegExp( mLineEdit->text() );
if( mRegExpEditDialog->exec() == QDialog::Accepted )
mLineEdit->setText( iface->regExp() );
}
}
} // namespace KMail
#include "regexplineedit.moc"
<commit_msg>Give focus to the line edit if the RegExpLineEdit gets the focus.<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*-
regexplineedit.cpp
This file is part of KMail, the KDE mail client.
Copyright (c) 2004 Ingo Kloecker <kloecker@kde.org>
KMail 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.
KMail 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "regexplineedit.h"
#include <klocale.h>
#include <klineedit.h>
#include <kparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <kdialog.h>
#include <qlayout.h>
#include <qstring.h>
#include <qpushbutton.h>
#include <qdialog.h>
namespace KMail {
RegExpLineEdit::RegExpLineEdit( QWidget *parent, const char *name )
: QWidget( parent, name ),
mLineEdit( 0 ),
mRegExpEditButton( 0 ),
mRegExpEditDialog( 0 )
{
initWidget();
}
RegExpLineEdit::RegExpLineEdit( const QString &str, QWidget *parent,
const char *name )
: QWidget( parent, name ),
mLineEdit( 0 ),
mRegExpEditButton( 0 ),
mRegExpEditDialog( 0 )
{
initWidget( str );
}
void RegExpLineEdit::initWidget( const QString &str )
{
QHBoxLayout * hlay = new QHBoxLayout( this, 0, KDialog::spacingHint() );
mLineEdit = new KLineEdit( str, this );
setFocusProxy( mLineEdit );
hlay->addWidget( mLineEdit );
connect( mLineEdit, SIGNAL( textChanged( const QString & ) ),
this, SIGNAL( textChanged( const QString & ) ) );
if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) {
mRegExpEditButton = new QPushButton( i18n("Edit..."), this,
"mRegExpEditButton" );
mRegExpEditButton->setSizePolicy( QSizePolicy::Minimum,
QSizePolicy::Fixed );
hlay->addWidget( mRegExpEditButton );
connect( mRegExpEditButton, SIGNAL( clicked() ),
this, SLOT( slotEditRegExp() ) );
}
}
void RegExpLineEdit::clear()
{
mLineEdit->clear();
}
QString RegExpLineEdit::text() const
{
return mLineEdit->text();
}
void RegExpLineEdit::setText( const QString & str )
{
mLineEdit->setText( str );
}
void RegExpLineEdit::showEditButton( bool show )
{
if ( !mRegExpEditButton )
return;
if ( show )
mRegExpEditButton->show();
else
mRegExpEditButton->hide();
}
void RegExpLineEdit::slotEditRegExp()
{
if ( !mRegExpEditDialog )
mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this );
KRegExpEditorInterface *iface =
static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) );
if( iface ) {
iface->setRegExp( mLineEdit->text() );
if( mRegExpEditDialog->exec() == QDialog::Accepted )
mLineEdit->setText( iface->regExp() );
}
}
} // namespace KMail
#include "regexplineedit.moc"
<|endoftext|>
|
<commit_before>#include "kontsevich_graph_sum.hpp"
#include "util/cartesian_product.hpp"
#include "util/sort_pairs.hpp"
#include <algorithm>
#include <map>
template <class T>
void KontsevichGraphSum<T>::reduce()
{
auto current_term = this->begin();
while (current_term < this->end())
{
current_term->first *= current_term->second.sign();
current_term->second.sign(1);
auto subsequent_term = current_term + 1;
while (subsequent_term < this->end())
{
if (subsequent_term->second.abs() == current_term->second.abs())
{
current_term->first += subsequent_term->first * subsequent_term->second.sign();
subsequent_term = this->erase(subsequent_term);
}
else
subsequent_term++;
}
if (current_term->first == 0)
current_term = this->erase(current_term);
else
current_term++;
}
}
template <class T>
std::ostream& operator<<(std::ostream& os, const std::pair<T, KontsevichGraph>& term)
{
os << term.first * term.second.sign() << "*(" << term.second << ")";
return os;
}
template <class T>
std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs)
{
if (gs.size() == 0)
return os << "0";
for (auto& term : gs)
{
os << term;
if (&term != &gs.back())
os << " + ";
}
return os;
}
template <class T>
std::istream& operator>>(std::istream& is, KontsevichGraphSum<T>& sum)
{
typename KontsevichGraphSum<T>::Term term;
while (is >> term.first >> term.second) {
sum.push_back(term);
}
return is;
}
template <class T>
bool KontsevichGraphSum<T>::operator==(const KontsevichGraphSum<T> &other)
{
KontsevichGraphSum<T> difference = *this - other;
difference.reduce();
return difference.size() == 0;
}
template <class T>
bool KontsevichGraphSum<T>::operator!=(const KontsevichGraphSum<T> &other)
{
return !(*this == other);
}
template <class T>
KontsevichGraphSum<T>& KontsevichGraphSum<T>::operator+=(const KontsevichGraphSum<T>& rhs)
{
this->reserve(this->size() + rhs.size());
this->insert(this->end(), rhs.begin(), rhs.end());
return *this;
}
template <class T>
KontsevichGraphSum<T> operator+(KontsevichGraphSum<T> lhs, const KontsevichGraphSum<T> &rhs)
{
lhs += rhs;
return lhs;
}
template <class T>
KontsevichGraphSum<T>& KontsevichGraphSum<T>::operator-=(const KontsevichGraphSum<T>& rhs)
{
size_t my_size = this->size();
// Add the lists of terms
*this += rhs;
// Flip the appropriate signs
for (auto it = this->begin() + my_size; it != this->end(); ++it)
it->first = -it->first;
return *this;
}
template <class T>
KontsevichGraphSum<T> operator-(KontsevichGraphSum<T> lhs, const KontsevichGraphSum<T>& rhs)
{
lhs -= rhs;
return lhs;
}
template <class T>
std::vector< std::vector<size_t> > KontsevichGraphSum<T>::in_degrees(bool ascending) const
{
std::map< std::vector<size_t>, size_t > indegree_counts;
for (auto& term : *this)
{
indegree_counts[term.second.in_degrees()]++;
}
std::vector< std::vector<size_t> > indegrees;
for (auto map_pair : indegree_counts)
{
indegrees.push_back(map_pair.first);
}
if (ascending)
sort(indegrees.begin(), indegrees.end(),
[&indegree_counts](std::vector<size_t>& indegree1, std::vector<size_t>& indegree2) {
return indegree_counts[indegree1] < indegree_counts[indegree2];
});
return indegrees;
}
template <class T>
KontsevichGraphSum<T> KontsevichGraphSum<T>::operator[](std::vector<size_t> indegrees) const
{
// TODO: write a custom iterator instead?
KontsevichGraphSum<T> filtered(this->size());
auto it = std::copy_if(this->begin(), this->end(), filtered.begin(),
[indegrees](KontsevichGraphSum<T>::Term term)
{
return term.second.in_degrees() == indegrees;
});
filtered.resize(std::distance(filtered.begin(), it));
return filtered;
}
template <class T>
T KontsevichGraphSum<T>::operator[](KontsevichGraph graph)
{
T coefficient = 0;
for (auto& term : *this)
{
if (term.second.abs() == graph.abs())
{
coefficient += graph.sign() * term.second.sign() * term.first;
}
}
return coefficient;
}
template <class T>
KontsevichGraphSum<T> KontsevichGraphSum<T>::operator()(std::vector< KontsevichGraphSum<T> > arguments)
{
KontsevichGraphSum<T> total; // TODO: pre-compute size?
for (auto& main_term : *this) // Linearity
{
// TODO: check arguments.size() equals main_term.d_external?
std::vector<size_t> argument_sizes(arguments.size());
for (size_t i = 0; i != arguments.size(); ++i)
argument_sizes[i] = arguments[i].size();
CartesianProduct multilinearity_indices(argument_sizes);
for (auto arg_indices = multilinearity_indices.begin(); arg_indices != multilinearity_indices.end(); ++arg_indices) // Multi-linearity
{
// Now main_term acts on arguments indicated by arg_indices
T coeff = main_term.first;
size_t internal = main_term.second.internal(), external = 0;
int sign = main_term.second.sign();
for (size_t i = 0; i != arguments.size(); ++i)
{
coeff *= arguments[i][(*arg_indices)[i]].first;
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
internal += graph->internal();
external += graph->external();
sign *= graph->sign();
}
// Prepare to concatenate targets
std::vector<KontsevichGraph::VertexPair> new_targets(internal);
auto new_targets_it = new_targets.begin();
// Relabel argument targets and copy them
size_t start_internal = external;
size_t start_external = 0;
std::vector<size_t> start_internal_vec(arguments.size());
std::vector<size_t> start_external_vec(arguments.size());
for (size_t i = 0; i != arguments.size(); ++i)
{
KontsevichGraphSum<T>::Term arg_term = arguments[i][(*arg_indices)[i]];
std::vector<KontsevichGraph::VertexPair> arg_targets = arg_term.second.targets();
std::vector<size_t> offsets(arg_term.second.vertices());
std::fill(offsets.begin(), offsets.begin() + arg_term.second.external(), start_external);
std::fill(offsets.begin() + arg_term.second.external(), offsets.begin() + arg_term.second.vertices(), start_internal - arg_term.second.external());
for (auto& target_pair : arg_targets)
{
target_pair.first += offsets[target_pair.first];
target_pair.second += offsets[target_pair.second];
}
std::copy(arg_targets.begin(), arg_targets.end(), new_targets_it);
start_external_vec[i] = start_external;
start_external += arg_term.second.external();
start_internal_vec[i] = start_internal;
start_internal += arg_term.second.internal();
new_targets_it += arg_targets.size();
}
// Relabel main_term internal targets, but not the external ones
std::vector<KontsevichGraph::VertexPair> main_targets = main_term.second.targets();
for (auto& target_pair : main_targets)
{
for (KontsevichGraph::Vertex* target : {&target_pair.first, &target_pair.second})
if ((size_t)*target >= main_term.second.external()) // internal
*target += (start_internal - main_term.second.external());
}
std::copy(main_targets.begin(), main_targets.end(), new_targets_it);
// Prepare to apply the Leibniz rule
std::vector<size_t> indegrees = main_term.second.in_degrees();
size_t incoming_edges = 0;
for (size_t i = 0; i != indegrees.size(); ++i)
incoming_edges += indegrees[i];
std::vector<size_t> leibniz_factors(incoming_edges);
// Build list of pointers to targets that should be replaced to apply the Leibniz rule
std::vector< KontsevichGraph::Vertex* > targets(incoming_edges);
size_t target_idx = 0;
size_t main_idx = new_targets.size() - main_targets.size();
for (KontsevichGraph::Vertex i = 0; (size_t)i != arguments.size(); ++i)
{
for (size_t n : main_term.second.neighbors_in(i))
{
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
leibniz_factors[target_idx] = graph->vertices();
auto& source = new_targets[main_idx + n - main_term.second.external()];
// Use the fact that main_term's ground vertices were not relabeled:
targets[target_idx] = (source.first == i) ? &source.first : &source.second;
target_idx++;
}
}
auto leibniz_indices = CartesianProduct(leibniz_factors);
for (auto target_indices = leibniz_indices.begin(); target_indices != leibniz_indices.end(); ++target_indices) // Leibniz rule
{
// Now assign targets according to the Leibniz rule
size_t target_idx = 0;
for (size_t i = 0; i != arguments.size(); ++i)
{
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
for (size_t j = 0; j != indegrees[i]; ++j)
{
if ((size_t)(*target_indices)[target_idx] >= graph->external()) // internal
*targets[target_idx] = start_internal_vec[i] - graph->external() + (*target_indices)[target_idx];
else // external
*targets[target_idx] = start_external_vec[i] + (*target_indices)[target_idx];
target_idx++;
}
}
// TODO: can we do something here to normalize the result more efficiently?
KontsevichGraph graph(internal, external, new_targets, sign);
total.push_back({ coeff, graph });
}
}
}
return total;
}
<commit_msg>Reduce KontsevichGraphSums more efficiently: first sort terms by graph.<commit_after>#include "kontsevich_graph_sum.hpp"
#include "util/cartesian_product.hpp"
#include "util/sort_pairs.hpp"
#include <algorithm>
#include <map>
template <class T>
void KontsevichGraphSum<T>::reduce()
{
// fix signs
for (auto& term : *this)
{
term.first *= term.second.sign();
term.second.sign(1);
}
// sort
sort(this->begin(), this->end(), [](const std::pair<T, KontsevichGraph>& lhs, const std::pair<T, KontsevichGraph>& rhs) {
return lhs.second < rhs.second;
});
// collect
auto current_term = this->begin();
while (current_term < this->end())
{
auto subsequent_term = current_term + 1;
while (subsequent_term < this->end())
{
if (subsequent_term->second == current_term->second)
{
current_term->first += subsequent_term->first;
subsequent_term = this->erase(subsequent_term);
}
else
break;
}
if (current_term->first == 0)
current_term = this->erase(current_term);
else
current_term++;
}
}
template <class T>
std::ostream& operator<<(std::ostream& os, const std::pair<T, KontsevichGraph>& term)
{
os << term.first * term.second.sign() << "*(" << term.second << ")";
return os;
}
template <class T>
std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs)
{
if (gs.size() == 0)
return os << "0";
for (auto& term : gs)
{
os << term;
if (&term != &gs.back())
os << " + ";
}
return os;
}
template <class T>
std::istream& operator>>(std::istream& is, KontsevichGraphSum<T>& sum)
{
typename KontsevichGraphSum<T>::Term term;
while (is >> term.first >> term.second) {
sum.push_back(term);
}
return is;
}
template <class T>
bool KontsevichGraphSum<T>::operator==(const KontsevichGraphSum<T> &other)
{
KontsevichGraphSum<T> difference = *this - other;
difference.reduce();
return difference.size() == 0;
}
template <class T>
bool KontsevichGraphSum<T>::operator!=(const KontsevichGraphSum<T> &other)
{
return !(*this == other);
}
template <class T>
KontsevichGraphSum<T>& KontsevichGraphSum<T>::operator+=(const KontsevichGraphSum<T>& rhs)
{
this->reserve(this->size() + rhs.size());
this->insert(this->end(), rhs.begin(), rhs.end());
return *this;
}
template <class T>
KontsevichGraphSum<T> operator+(KontsevichGraphSum<T> lhs, const KontsevichGraphSum<T> &rhs)
{
lhs += rhs;
return lhs;
}
template <class T>
KontsevichGraphSum<T>& KontsevichGraphSum<T>::operator-=(const KontsevichGraphSum<T>& rhs)
{
size_t my_size = this->size();
// Add the lists of terms
*this += rhs;
// Flip the appropriate signs
for (auto it = this->begin() + my_size; it != this->end(); ++it)
it->first = -it->first;
return *this;
}
template <class T>
KontsevichGraphSum<T> operator-(KontsevichGraphSum<T> lhs, const KontsevichGraphSum<T>& rhs)
{
lhs -= rhs;
return lhs;
}
template <class T>
std::vector< std::vector<size_t> > KontsevichGraphSum<T>::in_degrees(bool ascending) const
{
std::map< std::vector<size_t>, size_t > indegree_counts;
for (auto& term : *this)
{
indegree_counts[term.second.in_degrees()]++;
}
std::vector< std::vector<size_t> > indegrees;
for (auto map_pair : indegree_counts)
{
indegrees.push_back(map_pair.first);
}
if (ascending)
sort(indegrees.begin(), indegrees.end(),
[&indegree_counts](std::vector<size_t>& indegree1, std::vector<size_t>& indegree2) {
return indegree_counts[indegree1] < indegree_counts[indegree2];
});
return indegrees;
}
template <class T>
KontsevichGraphSum<T> KontsevichGraphSum<T>::operator[](std::vector<size_t> indegrees) const
{
// TODO: write a custom iterator instead?
KontsevichGraphSum<T> filtered(this->size());
auto it = std::copy_if(this->begin(), this->end(), filtered.begin(),
[indegrees](KontsevichGraphSum<T>::Term term)
{
return term.second.in_degrees() == indegrees;
});
filtered.resize(std::distance(filtered.begin(), it));
return filtered;
}
template <class T>
T KontsevichGraphSum<T>::operator[](KontsevichGraph graph)
{
T coefficient = 0;
for (auto& term : *this)
{
if (term.second.abs() == graph.abs())
{
coefficient += graph.sign() * term.second.sign() * term.first;
}
}
return coefficient;
}
template <class T>
KontsevichGraphSum<T> KontsevichGraphSum<T>::operator()(std::vector< KontsevichGraphSum<T> > arguments)
{
KontsevichGraphSum<T> total; // TODO: pre-compute size?
for (auto& main_term : *this) // Linearity
{
// TODO: check arguments.size() equals main_term.d_external?
std::vector<size_t> argument_sizes(arguments.size());
for (size_t i = 0; i != arguments.size(); ++i)
argument_sizes[i] = arguments[i].size();
CartesianProduct multilinearity_indices(argument_sizes);
for (auto arg_indices = multilinearity_indices.begin(); arg_indices != multilinearity_indices.end(); ++arg_indices) // Multi-linearity
{
// Now main_term acts on arguments indicated by arg_indices
T coeff = main_term.first;
size_t internal = main_term.second.internal(), external = 0;
int sign = main_term.second.sign();
for (size_t i = 0; i != arguments.size(); ++i)
{
coeff *= arguments[i][(*arg_indices)[i]].first;
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
internal += graph->internal();
external += graph->external();
sign *= graph->sign();
}
// Prepare to concatenate targets
std::vector<KontsevichGraph::VertexPair> new_targets(internal);
auto new_targets_it = new_targets.begin();
// Relabel argument targets and copy them
size_t start_internal = external;
size_t start_external = 0;
std::vector<size_t> start_internal_vec(arguments.size());
std::vector<size_t> start_external_vec(arguments.size());
for (size_t i = 0; i != arguments.size(); ++i)
{
KontsevichGraphSum<T>::Term arg_term = arguments[i][(*arg_indices)[i]];
std::vector<KontsevichGraph::VertexPair> arg_targets = arg_term.second.targets();
std::vector<size_t> offsets(arg_term.second.vertices());
std::fill(offsets.begin(), offsets.begin() + arg_term.second.external(), start_external);
std::fill(offsets.begin() + arg_term.second.external(), offsets.begin() + arg_term.second.vertices(), start_internal - arg_term.second.external());
for (auto& target_pair : arg_targets)
{
target_pair.first += offsets[target_pair.first];
target_pair.second += offsets[target_pair.second];
}
std::copy(arg_targets.begin(), arg_targets.end(), new_targets_it);
start_external_vec[i] = start_external;
start_external += arg_term.second.external();
start_internal_vec[i] = start_internal;
start_internal += arg_term.second.internal();
new_targets_it += arg_targets.size();
}
// Relabel main_term internal targets, but not the external ones
std::vector<KontsevichGraph::VertexPair> main_targets = main_term.second.targets();
for (auto& target_pair : main_targets)
{
for (KontsevichGraph::Vertex* target : {&target_pair.first, &target_pair.second})
if ((size_t)*target >= main_term.second.external()) // internal
*target += (start_internal - main_term.second.external());
}
std::copy(main_targets.begin(), main_targets.end(), new_targets_it);
// Prepare to apply the Leibniz rule
std::vector<size_t> indegrees = main_term.second.in_degrees();
size_t incoming_edges = 0;
for (size_t i = 0; i != indegrees.size(); ++i)
incoming_edges += indegrees[i];
std::vector<size_t> leibniz_factors(incoming_edges);
// Build list of pointers to targets that should be replaced to apply the Leibniz rule
std::vector< KontsevichGraph::Vertex* > targets(incoming_edges);
size_t target_idx = 0;
size_t main_idx = new_targets.size() - main_targets.size();
for (KontsevichGraph::Vertex i = 0; (size_t)i != arguments.size(); ++i)
{
for (size_t n : main_term.second.neighbors_in(i))
{
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
leibniz_factors[target_idx] = graph->vertices();
auto& source = new_targets[main_idx + n - main_term.second.external()];
// Use the fact that main_term's ground vertices were not relabeled:
targets[target_idx] = (source.first == i) ? &source.first : &source.second;
target_idx++;
}
}
auto leibniz_indices = CartesianProduct(leibniz_factors);
for (auto target_indices = leibniz_indices.begin(); target_indices != leibniz_indices.end(); ++target_indices) // Leibniz rule
{
// Now assign targets according to the Leibniz rule
size_t target_idx = 0;
for (size_t i = 0; i != arguments.size(); ++i)
{
KontsevichGraph* graph = &arguments[i][(*arg_indices)[i]].second;
for (size_t j = 0; j != indegrees[i]; ++j)
{
if ((size_t)(*target_indices)[target_idx] >= graph->external()) // internal
*targets[target_idx] = start_internal_vec[i] - graph->external() + (*target_indices)[target_idx];
else // external
*targets[target_idx] = start_external_vec[i] + (*target_indices)[target_idx];
target_idx++;
}
}
// TODO: can we do something here to normalize the result more efficiently?
KontsevichGraph graph(internal, external, new_targets, sign);
total.push_back({ coeff, graph });
}
}
}
return total;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <type_traits>
#include "ksp_plugin/plugin.hpp"
// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(CDECL)
# error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
# if defined(__i386) || defined(_M_IX86)
# if defined(_MSC_VER) || defined(__clang__)
# define CDECL __cdecl
# elif defined(__GNUC__) || defined(__INTEL_COMPILER)
# define CDECL __attribute__((cdecl))
# else
# error "Get a real compiler"
# endif
# elif defined(_M_X64) || defined(__x86_64__)
# define CDECL
# else
# error "Have you tried a Cray-1?"
# endif
#endif
#if defined(DLLEXPORT)
# error "DLLEXPORT already defined"
#else
# if defined(_WIN32) || defined(_WIN64)
# define DLLEXPORT __declspec(dllexport)
# else
# define DLLEXPORT __attribute__((visibility("default")))
# endif
#endif
namespace principia {
namespace ksp_plugin {
extern "C"
struct XYZ {
double x, y, z;
};
static_assert(std::is_standard_layout<XYZ>::value,
"XYZ is used for interfacing");
extern "C"
struct XYZSegment {
XYZ begin, end;
};
static_assert(std::is_standard_layout<XYZSegment>::value,
"SplineSegment is used for interfacing");
struct LineAndIterator {
LineAndIterator(RenderedTrajectory<World> const& rendered_trajectory)
: rendered_trajectory(rendered_trajectory) {};
RenderedTrajectory<World> const rendered_trajectory;
RenderedTrajectory<World>::const_iterator it;
};
// Sets stderr to log INFO, and redirects stderr, which Unity does not log, to
// "<KSP directory>/stderr.log". This provides an easily accessible file
// containing a sufficiently verbose log of the latest session, instead of
// requiring users to dig in the archive of all past logs at all severities.
// This archive is written to
// "<KSP directory>/glog/Principia/<SEVERITY>.<date>-<time>.<pid>",
// where date and time are in ISO 8601 basic format.
// TODO(egg): libglog should really be statically linked, what happens if two
// plugins use glog?
extern "C" DLLEXPORT
void CDECL InitGoogleLogging();
// Exports |LOG(SEVERITY) << message| for fast logging from the C# adapter.
// This will always evaluate its argument even if the corresponding log severity
// is disabled, so it is less efficient than LOG(INFO). It will not report the
// line and file of the caller.
extern "C" DLLEXPORT
void CDECL LogInfo(char const* message);
extern "C" DLLEXPORT
void CDECL LogWarning(char const* message);
extern "C" DLLEXPORT
void CDECL LogError(char const* message);
extern "C" DLLEXPORT
void CDECL LogFatal(char const* message);
// Returns a pointer to a plugin constructed with the arguments given.
// The caller takes ownership of the result.
extern "C" DLLEXPORT
Plugin* CDECL NewPlugin(double const initial_time,
int const sun_index,
double const sun_gravitational_parameter,
double const planetarium_rotation_in_degrees);
// Deletes and nulls |*plugin|.
// |plugin| must not be null. No transfer of ownership of |*plugin|,
// takes ownership of |**plugin|.
extern "C" DLLEXPORT
void CDECL DeletePlugin(Plugin const** const plugin);
// Calls |plugin->InsertCelestial| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL InsertCelestial(Plugin* const plugin,
int const celestial_index,
double const gravitational_parameter,
int const parent_index,
XYZ const from_parent_position,
XYZ const from_parent_velocity);
// Calls |plugin->UpdateCelestialHierarchy| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL UpdateCelestialHierarchy(Plugin const* const plugin,
int const celestial_index,
int const parent_index);
// Calls |plugin->EndInitialization|.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL EndInitialization(Plugin* const plugin);
// Calls |plugin->InsertOrKeepVessel| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
bool CDECL InsertOrKeepVessel(Plugin* const plugin,
char const* vessel_guid,
int const parent_index);
// Calls |plugin->SetVesselStateOffset| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL SetVesselStateOffset(Plugin* const plugin,
char const* vessel_guid,
XYZ const from_parent_position,
XYZ const from_parent_velocity);
extern "C" DLLEXPORT
void CDECL AdvanceTime(Plugin* const plugin,
double const t,
double const planetarium_rotation);
// Calls |plugin->VesselDisplacementFromParent| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL VesselDisplacementFromParent(Plugin const* const plugin,
char const* vessel_guid);
// Calls |plugin->VesselParentRelativeVelocity| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL VesselParentRelativeVelocity(Plugin const* const plugin,
char const* vessel_guid);
// Calls |plugin->CelestialDisplacementFromParent| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL CelestialDisplacementFromParent(Plugin const* const plugin,
int const celestial_index);
// Calls |plugin->CelestialParentRelativeVelocity| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL CelestialParentRelativeVelocity(Plugin const* const plugin,
int const celestial_index);
extern "C" DLLEXPORT
BodyCentredNonRotatingFrame const* CDECL NewBodyCentredNonRotatingFrame(
Plugin const* const plugin,
int const reference_body_index);
extern "C" DLLEXPORT
void CDECL DeleteBodyCentredNonRotatingFrame(
BodyCentredNonRotatingFrame const** const frame);
extern "C" DLLEXPORT
LineAndIterator* CDECL RenderedVesselTrajectory(Plugin const* const plugin,
char const* vessel_guid,
RenderingFrame const* frame,
XYZ const sun_world_position);
extern "C" DLLEXPORT
int CDECL NumberOfSegments(LineAndIterator const* line);
extern "C" DLLEXPORT
XYZSegment CDECL FetchAndIncrement(LineAndIterator* const line);
extern "C" DLLEXPORT
bool CDECL AtEnd(LineAndIterator* const line);
extern "C" DLLEXPORT
void CDECL DeleteLineAndIterator(LineAndIterator const** const line);
// Says hello, convenient for checking that calls to the DLL work.
extern "C" DLLEXPORT
char const* CDECL SayHello();
} // namespace ksp_plugin
} // namespace principia
#undef CDECL
#undef DLLEXPORT
<commit_msg>Comments.<commit_after>#pragma once
#include <type_traits>
#include "ksp_plugin/plugin.hpp"
// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(CDECL)
# error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
# if defined(__i386) || defined(_M_IX86)
# if defined(_MSC_VER) || defined(__clang__)
# define CDECL __cdecl
# elif defined(__GNUC__) || defined(__INTEL_COMPILER)
# define CDECL __attribute__((cdecl))
# else
# error "Get a real compiler"
# endif
# elif defined(_M_X64) || defined(__x86_64__)
# define CDECL
# else
# error "Have you tried a Cray-1?"
# endif
#endif
#if defined(DLLEXPORT)
# error "DLLEXPORT already defined"
#else
# if defined(_WIN32) || defined(_WIN64)
# define DLLEXPORT __declspec(dllexport)
# else
# define DLLEXPORT __attribute__((visibility("default")))
# endif
#endif
namespace principia {
namespace ksp_plugin {
extern "C"
struct XYZ {
double x, y, z;
};
static_assert(std::is_standard_layout<XYZ>::value,
"XYZ is used for interfacing");
extern "C"
struct XYZSegment {
XYZ begin, end;
};
static_assert(std::is_standard_layout<XYZSegment>::value,
"XYZSegment is used for interfacing");
struct LineAndIterator {
LineAndIterator(RenderedTrajectory<World> const& rendered_trajectory)
: rendered_trajectory(rendered_trajectory) {};
RenderedTrajectory<World> const rendered_trajectory;
RenderedTrajectory<World>::const_iterator it;
};
// Sets stderr to log INFO, and redirects stderr, which Unity does not log, to
// "<KSP directory>/stderr.log". This provides an easily accessible file
// containing a sufficiently verbose log of the latest session, instead of
// requiring users to dig in the archive of all past logs at all severities.
// This archive is written to
// "<KSP directory>/glog/Principia/<SEVERITY>.<date>-<time>.<pid>",
// where date and time are in ISO 8601 basic format.
// TODO(egg): libglog should really be statically linked, what happens if two
// plugins use glog?
extern "C" DLLEXPORT
void CDECL InitGoogleLogging();
// Exports |LOG(SEVERITY) << message| for fast logging from the C# adapter.
// This will always evaluate its argument even if the corresponding log severity
// is disabled, so it is less efficient than LOG(INFO). It will not report the
// line and file of the caller.
extern "C" DLLEXPORT
void CDECL LogInfo(char const* message);
extern "C" DLLEXPORT
void CDECL LogWarning(char const* message);
extern "C" DLLEXPORT
void CDECL LogError(char const* message);
extern "C" DLLEXPORT
void CDECL LogFatal(char const* message);
// Returns a pointer to a plugin constructed with the arguments given.
// The caller takes ownership of the result.
extern "C" DLLEXPORT
Plugin* CDECL NewPlugin(double const initial_time,
int const sun_index,
double const sun_gravitational_parameter,
double const planetarium_rotation_in_degrees);
// Deletes and nulls |*plugin|.
// |plugin| must not be null. No transfer of ownership of |*plugin|, takes
// ownership of |**plugin|.
extern "C" DLLEXPORT
void CDECL DeletePlugin(Plugin const** const plugin);
// Calls |plugin->InsertCelestial| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL InsertCelestial(Plugin* const plugin,
int const celestial_index,
double const gravitational_parameter,
int const parent_index,
XYZ const from_parent_position,
XYZ const from_parent_velocity);
// Calls |plugin->UpdateCelestialHierarchy| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL UpdateCelestialHierarchy(Plugin const* const plugin,
int const celestial_index,
int const parent_index);
// Calls |plugin->EndInitialization|.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL EndInitialization(Plugin* const plugin);
// Calls |plugin->InsertOrKeepVessel| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
bool CDECL InsertOrKeepVessel(Plugin* const plugin,
char const* vessel_guid,
int const parent_index);
// Calls |plugin->SetVesselStateOffset| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
void CDECL SetVesselStateOffset(Plugin* const plugin,
char const* vessel_guid,
XYZ const from_parent_position,
XYZ const from_parent_velocity);
extern "C" DLLEXPORT
void CDECL AdvanceTime(Plugin* const plugin,
double const t,
double const planetarium_rotation);
// Calls |plugin->VesselDisplacementFromParent| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL VesselDisplacementFromParent(Plugin const* const plugin,
char const* vessel_guid);
// Calls |plugin->VesselParentRelativeVelocity| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL VesselParentRelativeVelocity(Plugin const* const plugin,
char const* vessel_guid);
// Calls |plugin->CelestialDisplacementFromParent| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL CelestialDisplacementFromParent(Plugin const* const plugin,
int const celestial_index);
// Calls |plugin->CelestialParentRelativeVelocity| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
XYZ CDECL CelestialParentRelativeVelocity(Plugin const* const plugin,
int const celestial_index);
// Calls |plugin->NewBodyCentredNonRotatingFrame| with the arguments given.
// |plugin| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
BodyCentredNonRotatingFrame const* CDECL NewBodyCentredNonRotatingFrame(
Plugin const* const plugin,
int const reference_body_index);
// Deletes and nulls |*frame|.
// |frame| must not be null. No transfer of ownership of |*frame|, takes
// ownership of |**frame|.
extern "C" DLLEXPORT
void CDECL DeleteBodyCentredNonRotatingFrame(
BodyCentredNonRotatingFrame const** const frame);
// Returns the result of |plugin->RenderedVesselTrajectory| called with the
// arguments given, together with an iterator to its beginning.
// |plugin| must not be null. No transfer of ownership of |plugin|. The caller
// gets ownership of the result.
extern "C" DLLEXPORT
LineAndIterator* CDECL RenderedVesselTrajectory(Plugin const* const plugin,
char const* vessel_guid,
RenderingFrame const* frame,
XYZ const sun_world_position);
// Returns |line->rendered_trajectory.size()|.
// |line| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
int CDECL NumberOfSegments(LineAndIterator const* line);
// Returns the |XYZSegment| corresponding to the |LineSegment| |*line->it|, then
// increments |line->it|.
// |line| must not be null. |line->it| must not be the end of
// |line->rendered_trajectory|. No transfer of ownership.
extern "C" DLLEXPORT
XYZSegment CDECL FetchAndIncrement(LineAndIterator* const line);
// Returns |true| if and only if |line->it| is the end of
// |line->rendered_trajectory|.
// |line| must not be null. No transfer of ownership.
extern "C" DLLEXPORT
bool CDECL AtEnd(LineAndIterator* const line);
// Deletes and nulls |*line|.
// |line| must not be null. No transfer of ownership of |*line|, takes
// ownership of |**line|.
extern "C" DLLEXPORT
void CDECL DeleteLineAndIterator(LineAndIterator const** const line);
// Says hello, convenient for checking that calls to the DLL work.
extern "C" DLLEXPORT
char const* CDECL SayHello();
} // namespace ksp_plugin
} // namespace principia
#undef CDECL
#undef DLLEXPORT
<|endoftext|>
|
<commit_before>#include "bitcoinaddressvalidator.h"
/* Base58 characters are:
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
This is:
- All numbers except for '0'
- All uppercase letters except for 'I' and 'O'
- All lowercase letters except for 'l'
User friendly Base58 input can map
- 'l' and 'I' to '1'
- '0' and 'O' to 'o'
*/
BitcoinAddressValidator::BitcoinAddressValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State BitcoinAddressValidator::validate(QString &input, int &pos) const
{
// Correction
for(int idx=0; idx<input.size();)
{
bool removeChar = false;
QChar ch = input.at(idx);
// Transform characters that are visually close
switch(ch.unicode())
{
case 'l':
case 'I':
input[idx] = QChar('1');
break;
case '0':
case 'O':
input[idx] = QChar('o');
break;
// Qt categorizes these as "Other_Format" not "Separator_Space"
case 0x200B: // ZERO WIDTH SPACE
case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
removeChar = true;
break;
default:
break;
}
// Remove whitespace
if(ch.isSpace())
removeChar = true;
// To next character
if(removeChar)
input.remove(idx, 1);
else
++idx;
}
// Validation
QValidator::State state = QValidator::Acceptable;
for(int idx=0; idx<input.size(); ++idx)
{
int ch = input.at(idx).unicode();
if(((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z')) &&
ch != 'l' && ch != 'I' && ch != '0' && ch != 'O')
{
// Alphanumeric and not a 'forbidden' character
}
else
{
state = QValidator::Invalid;
}
}
// Empty address is "intermediate" input
if(input.isEmpty())
{
state = QValidator::Intermediate;
}
return state;
}
<commit_msg>Remove autocorrection of 0/i in addresses in UI<commit_after>#include "bitcoinaddressvalidator.h"
/* Base58 characters are:
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
This is:
- All numbers except for '0'
- All uppercase letters except for 'I' and 'O'
- All lowercase letters except for 'l'
User friendly Base58 input can map
- 'l' and 'I' to '1'
- '0' and 'O' to 'o'
*/
BitcoinAddressValidator::BitcoinAddressValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State BitcoinAddressValidator::validate(QString &input, int &pos) const
{
// Correction
for(int idx=0; idx<input.size();)
{
bool removeChar = false;
QChar ch = input.at(idx);
// Corrections made are very conservative on purpose, to avoid
// users unexpectedly getting away with typos that would normally
// be detected, and thus sending to the wrong address.
switch(ch.unicode())
{
// Qt categorizes these as "Other_Format" not "Separator_Space"
case 0x200B: // ZERO WIDTH SPACE
case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
removeChar = true;
break;
default:
break;
}
// Remove whitespace
if(ch.isSpace())
removeChar = true;
// To next character
if(removeChar)
input.remove(idx, 1);
else
++idx;
}
// Validation
QValidator::State state = QValidator::Acceptable;
for(int idx=0; idx<input.size(); ++idx)
{
int ch = input.at(idx).unicode();
if(((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z')) &&
ch != 'l' && ch != 'I' && ch != '0' && ch != 'O')
{
// Alphanumeric and not a 'forbidden' character
}
else
{
state = QValidator::Invalid;
}
}
// Empty address is "intermediate" input
if(input.isEmpty())
{
state = QValidator::Intermediate;
}
return state;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickdroparea_p.h"
#include "qquickdrag_p.h"
#include "qquickitem_p.h"
#include "qquickcanvas.h"
#include <private/qqmlengine_p.h>
QT_BEGIN_NAMESPACE
QQuickDropAreaDrag::QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent)
: QObject(parent)
, d(d)
{
}
QQuickDropAreaDrag::~QQuickDropAreaDrag()
{
}
class QQuickDropAreaPrivate : public QQuickItemPrivate
{
Q_DECLARE_PUBLIC(QQuickDropArea)
public:
QQuickDropAreaPrivate();
~QQuickDropAreaPrivate();
bool hasMatchingKey(const QStringList &keys) const;
QStringList getKeys(const QMimeData *mimeData) const;
QStringList keys;
QRegExp keyRegExp;
QPointF dragPosition;
QQuickDropAreaDrag *drag;
QQmlGuard<QObject> source;
QQmlGuard<QMimeData> mimeData;
};
QQuickDropAreaPrivate::QQuickDropAreaPrivate()
: drag(0)
{
}
QQuickDropAreaPrivate::~QQuickDropAreaPrivate()
{
delete drag;
}
/*!
\qmlclass DropArea QQuickDropArea
\inqmlmodule QtQuick 2
\brief The DropArea item provides drag and drop handling.
A DropArea is an invisible item which receives events when other items are
dragged over it.
The Drag attached property can be used to notify the DropArea when an Item is
dragged over it.
The \l keys property can be used to filter drag events which don't include
a matching key.
The \l dropItem property is communicated to the source of a drag event as
the recipient of a drop on the drag target.
The \l delegate property provides a means to specify a component to be
instantiated for each active drag over a drag target.
*/
QQuickDropArea::QQuickDropArea(QQuickItem *parent)
: QQuickItem(*new QQuickDropAreaPrivate, parent)
{
setFlags(ItemAcceptsDrops);
}
QQuickDropArea::~QQuickDropArea()
{
}
/*!
\qmlproperty bool QtQuick2::DropArea::containsDrag
This property identifies whether the DropArea currently contains any
dragged items.
*/
bool QQuickDropArea::containsDrag() const
{
Q_D(const QQuickDropArea);
return d->mimeData;
}
/*!
\qmlproperty stringlist QtQuick2::DropArea::keys
This property holds a list of drag keys a DropArea will accept.
If no keys are listed the DropArea will accept events from any drag source,
otherwise the drag source must have at least one compatible key.
\sa QtQuick2::Drag::keys
*/
QStringList QQuickDropArea::keys() const
{
Q_D(const QQuickDropArea);
return d->keys;
}
void QQuickDropArea::setKeys(const QStringList &keys)
{
Q_D(QQuickDropArea);
if (d->keys != keys) {
d->keys = keys;
if (keys.isEmpty()) {
d->keyRegExp = QRegExp();
} else {
QString pattern = QLatin1Char('(') + QRegExp::escape(keys.first());
for (int i = 1; i < keys.count(); ++i)
pattern += QLatin1Char('|') + QRegExp::escape(keys.at(i));
pattern += QLatin1Char(')');
d->keyRegExp = QRegExp(pattern.replace(QLatin1String("\\*"), QLatin1String(".+")));
}
emit keysChanged();
}
}
QQuickDropAreaDrag *QQuickDropArea::drag()
{
Q_D(QQuickDropArea);
if (!d->drag)
d->drag = new QQuickDropAreaDrag(d);
return d->drag;
}
/*!
\qmlproperty Object QtQuick2::DropArea::drag.source
This property holds the source of a drag.
*/
QObject *QQuickDropAreaDrag::source() const
{
return d->source;
}
/*!
\qmlproperty qreal QtQuick2::DropArea::drag.x
\qmlproperty qreal QtQuick2::DropArea::drag.y
These properties hold the coordinates of the last drag event.
*/
qreal QQuickDropAreaDrag::x() const
{
return d->dragPosition.x();
}
qreal QQuickDropAreaDrag::y() const
{
return d->dragPosition.y();
}
/*!
\qmlsignal QtQuick2::DropArea::onPositionChanged(DragEvent drag)
This handler is called when the position of a drag has changed.
*/
void QQuickDropArea::dragMoveEvent(QDragMoveEvent *event)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
d->dragPosition = event->pos();
if (d->drag)
emit d->drag->positionChanged();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit positionChanged(&dragTargetEvent);
}
bool QQuickDropAreaPrivate::hasMatchingKey(const QStringList &keys) const
{
if (keyRegExp.isEmpty())
return true;
foreach (const QString &key, keys) {
if (keyRegExp.exactMatch(key))
return true;
}
return false;
}
QStringList QQuickDropAreaPrivate::getKeys(const QMimeData *mimeData) const
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(mimeData))
return dragMime->keys();
return mimeData->formats();
}
/*!
\qmlsignal QtQuick2::DropArea::onEntered(DragEvent drag)
This handler is called when a \a drag enters the bounds of a DropArea.
*/
void QQuickDropArea::dragEnterEvent(QDragEnterEvent *event)
{
Q_D(QQuickDropArea);
const QMimeData *mimeData = event->mimeData();
if (!d->effectiveEnable || d->mimeData || !mimeData || !d->hasMatchingKey(d->getKeys(mimeData)))
return;
d->dragPosition = event->pos();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit entered(&dragTargetEvent);
if (event->isAccepted()) {
d->mimeData = const_cast<QMimeData *>(mimeData);
if (QQuickDragMimeData *dragMime = qobject_cast<QQuickDragMimeData *>(d->mimeData))
d->source = dragMime->source();
else
d->source = event->source();
d->dragPosition = event->pos();
if (d->drag) {
emit d->drag->positionChanged();
emit d->drag->sourceChanged();
}
emit containsDragChanged();
}
}
/*!
\qmlsignal QtQuick2::DropArea::onExited()
This handler is called when a drag exits the bounds of a DropArea.
*/
void QQuickDropArea::dragLeaveEvent(QDragLeaveEvent *)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
emit exited();
d->mimeData = 0;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlsignal QtQuick2::DropArea::onDropped(DragEvent drop)
This handler is called when a drop event occurs within the bounds of a
a DropArea.
*/
void QQuickDropArea::dropEvent(QDropEvent *event)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
QQuickDropEvent dragTargetEvent(d, event);
emit dropped(&dragTargetEvent);
d->mimeData = 0;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlclass DragEvent QQuickDragEvent
\inqmlmodule QtQuick 2
\brief The DragEvent object provides information about a drag event.
The position of the drag event can be obtained from the \l x and \l y
properties, and the \l keys property identifies the drag keys of the event
\l source.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::x
This property holds the x coordinate of a drag event.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::y
This property holds the y coordinate of a drag event.
*/
/*!
\qmlproperty Object QtQuick2::DragEvent::drag.source
This property holds the source of a drag event.
*/
QObject *QQuickDropEvent::source()
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(event->mimeData()))
return dragMime->source();
else
return event->source();
}
/*!
\qmlproperty stringlist QtQuick2::DragEvent::keys
This property holds a list of keys identifying the data type or source of a
drag event.
*/
QStringList QQuickDropEvent::keys() const
{
return d->getKeys(event->mimeData());
}
/*!
\qmlproperty enum QtQuick2::DragEvent::action
This property holds the action that the \l source is to perform on an accepted drop.
The drop action may be one of:
\list
\li Qt.CopyAction Copy the data to the target
\li Qt.MoveAction Move the data from the source to the target
\li Qt.LinkAction Create a link from the source to the target.
\li Qt.IgnoreAction Ignore the action (do nothing with the data).
\endlist
*/
/*!
\qmlproperty flags QtQuick2::DragEvent::supportedActions
This property holds the set of \l {action}{actions} supported by the
drag source.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::accepted
This property holds whether the drag event was accepted by a handler.
The default value is true.
*/
/*!
\qmlmethod void QtQuick2::DragEvent::accept()
\qmlmethod void QtQuick2::DragEvent::accept(enum action)
Accepts the drag event.
If an \a action is specified it will overwrite the value of the \l action property.
*/
void QQuickDropEvent::accept(QQmlV8Function *args)
{
Qt::DropAction action = event->dropAction();
if (args->Length() >= 1) {
v8::Local<v8::Value> v = (*args)[0];
if (v->IsInt32())
action = Qt::DropAction(v->Int32Value());
}
// get action from arguments.
event->setDropAction(action);
event->accept();
}
QT_END_NAMESPACE
<commit_msg>Don't use the QRegExp methods that modify the object<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickdroparea_p.h"
#include "qquickdrag_p.h"
#include "qquickitem_p.h"
#include "qquickcanvas.h"
#include <private/qqmlengine_p.h>
QT_BEGIN_NAMESPACE
QQuickDropAreaDrag::QQuickDropAreaDrag(QQuickDropAreaPrivate *d, QObject *parent)
: QObject(parent)
, d(d)
{
}
QQuickDropAreaDrag::~QQuickDropAreaDrag()
{
}
class QQuickDropAreaPrivate : public QQuickItemPrivate
{
Q_DECLARE_PUBLIC(QQuickDropArea)
public:
QQuickDropAreaPrivate();
~QQuickDropAreaPrivate();
bool hasMatchingKey(const QStringList &keys) const;
QStringList getKeys(const QMimeData *mimeData) const;
QStringList keys;
QRegExp keyRegExp;
QPointF dragPosition;
QQuickDropAreaDrag *drag;
QQmlGuard<QObject> source;
QQmlGuard<QMimeData> mimeData;
};
QQuickDropAreaPrivate::QQuickDropAreaPrivate()
: drag(0)
{
}
QQuickDropAreaPrivate::~QQuickDropAreaPrivate()
{
delete drag;
}
/*!
\qmlclass DropArea QQuickDropArea
\inqmlmodule QtQuick 2
\brief The DropArea item provides drag and drop handling.
A DropArea is an invisible item which receives events when other items are
dragged over it.
The Drag attached property can be used to notify the DropArea when an Item is
dragged over it.
The \l keys property can be used to filter drag events which don't include
a matching key.
The \l dropItem property is communicated to the source of a drag event as
the recipient of a drop on the drag target.
The \l delegate property provides a means to specify a component to be
instantiated for each active drag over a drag target.
*/
QQuickDropArea::QQuickDropArea(QQuickItem *parent)
: QQuickItem(*new QQuickDropAreaPrivate, parent)
{
setFlags(ItemAcceptsDrops);
}
QQuickDropArea::~QQuickDropArea()
{
}
/*!
\qmlproperty bool QtQuick2::DropArea::containsDrag
This property identifies whether the DropArea currently contains any
dragged items.
*/
bool QQuickDropArea::containsDrag() const
{
Q_D(const QQuickDropArea);
return d->mimeData;
}
/*!
\qmlproperty stringlist QtQuick2::DropArea::keys
This property holds a list of drag keys a DropArea will accept.
If no keys are listed the DropArea will accept events from any drag source,
otherwise the drag source must have at least one compatible key.
\sa QtQuick2::Drag::keys
*/
QStringList QQuickDropArea::keys() const
{
Q_D(const QQuickDropArea);
return d->keys;
}
void QQuickDropArea::setKeys(const QStringList &keys)
{
Q_D(QQuickDropArea);
if (d->keys != keys) {
d->keys = keys;
if (keys.isEmpty()) {
d->keyRegExp = QRegExp();
} else {
QString pattern = QLatin1Char('(') + QRegExp::escape(keys.first());
for (int i = 1; i < keys.count(); ++i)
pattern += QLatin1Char('|') + QRegExp::escape(keys.at(i));
pattern += QLatin1Char(')');
d->keyRegExp = QRegExp(pattern.replace(QLatin1String("\\*"), QLatin1String(".+")));
}
emit keysChanged();
}
}
QQuickDropAreaDrag *QQuickDropArea::drag()
{
Q_D(QQuickDropArea);
if (!d->drag)
d->drag = new QQuickDropAreaDrag(d);
return d->drag;
}
/*!
\qmlproperty Object QtQuick2::DropArea::drag.source
This property holds the source of a drag.
*/
QObject *QQuickDropAreaDrag::source() const
{
return d->source;
}
/*!
\qmlproperty qreal QtQuick2::DropArea::drag.x
\qmlproperty qreal QtQuick2::DropArea::drag.y
These properties hold the coordinates of the last drag event.
*/
qreal QQuickDropAreaDrag::x() const
{
return d->dragPosition.x();
}
qreal QQuickDropAreaDrag::y() const
{
return d->dragPosition.y();
}
/*!
\qmlsignal QtQuick2::DropArea::onPositionChanged(DragEvent drag)
This handler is called when the position of a drag has changed.
*/
void QQuickDropArea::dragMoveEvent(QDragMoveEvent *event)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
d->dragPosition = event->pos();
if (d->drag)
emit d->drag->positionChanged();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit positionChanged(&dragTargetEvent);
}
bool QQuickDropAreaPrivate::hasMatchingKey(const QStringList &keys) const
{
if (keyRegExp.isEmpty())
return true;
QRegExp copy = keyRegExp;
foreach (const QString &key, keys) {
if (copy.exactMatch(key))
return true;
}
return false;
}
QStringList QQuickDropAreaPrivate::getKeys(const QMimeData *mimeData) const
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(mimeData))
return dragMime->keys();
return mimeData->formats();
}
/*!
\qmlsignal QtQuick2::DropArea::onEntered(DragEvent drag)
This handler is called when a \a drag enters the bounds of a DropArea.
*/
void QQuickDropArea::dragEnterEvent(QDragEnterEvent *event)
{
Q_D(QQuickDropArea);
const QMimeData *mimeData = event->mimeData();
if (!d->effectiveEnable || d->mimeData || !mimeData || !d->hasMatchingKey(d->getKeys(mimeData)))
return;
d->dragPosition = event->pos();
event->accept();
QQuickDropEvent dragTargetEvent(d, event);
emit entered(&dragTargetEvent);
if (event->isAccepted()) {
d->mimeData = const_cast<QMimeData *>(mimeData);
if (QQuickDragMimeData *dragMime = qobject_cast<QQuickDragMimeData *>(d->mimeData))
d->source = dragMime->source();
else
d->source = event->source();
d->dragPosition = event->pos();
if (d->drag) {
emit d->drag->positionChanged();
emit d->drag->sourceChanged();
}
emit containsDragChanged();
}
}
/*!
\qmlsignal QtQuick2::DropArea::onExited()
This handler is called when a drag exits the bounds of a DropArea.
*/
void QQuickDropArea::dragLeaveEvent(QDragLeaveEvent *)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
emit exited();
d->mimeData = 0;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlsignal QtQuick2::DropArea::onDropped(DragEvent drop)
This handler is called when a drop event occurs within the bounds of a
a DropArea.
*/
void QQuickDropArea::dropEvent(QDropEvent *event)
{
Q_D(QQuickDropArea);
if (!d->mimeData)
return;
QQuickDropEvent dragTargetEvent(d, event);
emit dropped(&dragTargetEvent);
d->mimeData = 0;
d->source = 0;
emit containsDragChanged();
if (d->drag)
emit d->drag->sourceChanged();
}
/*!
\qmlclass DragEvent QQuickDragEvent
\inqmlmodule QtQuick 2
\brief The DragEvent object provides information about a drag event.
The position of the drag event can be obtained from the \l x and \l y
properties, and the \l keys property identifies the drag keys of the event
\l source.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::x
This property holds the x coordinate of a drag event.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::y
This property holds the y coordinate of a drag event.
*/
/*!
\qmlproperty Object QtQuick2::DragEvent::drag.source
This property holds the source of a drag event.
*/
QObject *QQuickDropEvent::source()
{
if (const QQuickDragMimeData *dragMime = qobject_cast<const QQuickDragMimeData *>(event->mimeData()))
return dragMime->source();
else
return event->source();
}
/*!
\qmlproperty stringlist QtQuick2::DragEvent::keys
This property holds a list of keys identifying the data type or source of a
drag event.
*/
QStringList QQuickDropEvent::keys() const
{
return d->getKeys(event->mimeData());
}
/*!
\qmlproperty enum QtQuick2::DragEvent::action
This property holds the action that the \l source is to perform on an accepted drop.
The drop action may be one of:
\list
\li Qt.CopyAction Copy the data to the target
\li Qt.MoveAction Move the data from the source to the target
\li Qt.LinkAction Create a link from the source to the target.
\li Qt.IgnoreAction Ignore the action (do nothing with the data).
\endlist
*/
/*!
\qmlproperty flags QtQuick2::DragEvent::supportedActions
This property holds the set of \l {action}{actions} supported by the
drag source.
*/
/*!
\qmlproperty real QtQuick2::DragEvent::accepted
This property holds whether the drag event was accepted by a handler.
The default value is true.
*/
/*!
\qmlmethod void QtQuick2::DragEvent::accept()
\qmlmethod void QtQuick2::DragEvent::accept(enum action)
Accepts the drag event.
If an \a action is specified it will overwrite the value of the \l action property.
*/
void QQuickDropEvent::accept(QQmlV8Function *args)
{
Qt::DropAction action = event->dropAction();
if (args->Length() >= 1) {
v8::Local<v8::Value> v = (*args)[0];
if (v->IsInt32())
action = Qt::DropAction(v->Int32Value());
}
// get action from arguments.
event->setDropAction(action);
event->accept();
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Decodes the blocks generated by block_builder.cc.
#include "table/block.h"
#include <vector>
#include <algorithm>
#include "leveldb/comparator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
inline uint32_t Block::NumRestarts() const {
assert(size_ >= 2*sizeof(uint32_t));
return DecodeFixed32(data_ + size_ - sizeof(uint32_t));
}
Block::Block(const char* data, size_t size)
: data_(data),
size_(size) {
if (size_ < sizeof(uint32_t)) {
size_ = 0; // Error marker
} else {
restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t);
if (restart_offset_ > size_ - sizeof(uint32_t)) {
// The size is too small for NumRestarts() and therefore
// restart_offset_ wrapped around.
size_ = 0;
}
}
}
Block::~Block() {
delete[] data_;
}
// Helper routine: decode the next block entry starting at "p",
// storing the number of shared key bytes, non_shared key bytes,
// and the length of the value in "*shared", "*non_shared", and
// "*value_length", respectively. Will not derefence past "limit".
//
// If any errors are detected, returns NULL. Otherwise, returns a
// pointer to the key delta (just past the three decoded values).
static inline const char* DecodeEntry(const char* p, const char* limit,
uint32_t* shared,
uint32_t* non_shared,
uint32_t* value_length) {
if (limit - p < 3) return NULL;
*shared = reinterpret_cast<const unsigned char*>(p)[0];
*non_shared = reinterpret_cast<const unsigned char*>(p)[1];
*value_length = reinterpret_cast<const unsigned char*>(p)[2];
if ((*shared | *non_shared | *value_length) < 128) {
// Fast path: all three values are encoded in one byte each
p += 3;
} else {
if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL;
}
if (static_cast<uint32>(limit - p) < (*non_shared + *value_length)) {
return NULL;
}
return p;
}
class Block::Iter : public Iterator {
private:
const Comparator* const comparator_;
const char* const data_; // underlying block contents
uint32_t const restarts_; // Offset of restart array (list of fixed32)
uint32_t const num_restarts_; // Number of uint32_t entries in restart array
// current_ is offset in data_ of current entry. >= restarts_ if !Valid
uint32_t current_;
uint32_t restart_index_; // Index of restart block in which current_ falls
std::string key_;
Slice value_;
Status status_;
inline int Compare(const Slice& a, const Slice& b) const {
return comparator_->Compare(a, b);
}
// Return the offset in data_ just past the end of the current entry.
inline uint32_t NextEntryOffset() const {
return (value_.data() + value_.size()) - data_;
}
uint32_t GetRestartPoint(uint32_t index) {
assert(index < num_restarts_);
return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t));
}
void SeekToRestartPoint(uint32_t index) {
key_.clear();
restart_index_ = index;
// current_ will be fixed by ParseNextKey();
// ParseNextKey() starts at the end of value_, so set value_ accordingly
uint32_t offset = GetRestartPoint(index);
value_ = Slice(data_ + offset, 0);
}
public:
Iter(const Comparator* comparator,
const char* data,
uint32_t restarts,
uint32_t num_restarts)
: comparator_(comparator),
data_(data),
restarts_(restarts),
num_restarts_(num_restarts),
current_(restarts_),
restart_index_(num_restarts_) {
assert(num_restarts_ > 0);
}
virtual bool Valid() const { return current_ < restarts_; }
virtual Status status() const { return status_; }
virtual Slice key() const {
assert(Valid());
return key_;
}
virtual Slice value() const {
assert(Valid());
return value_;
}
virtual void Next() {
assert(Valid());
ParseNextKey();
}
virtual void Prev() {
assert(Valid());
// Scan backwards to a restart point before current_
const uint32_t original = current_;
while (GetRestartPoint(restart_index_) >= original) {
if (restart_index_ == 0) {
// No more entries
current_ = restarts_;
restart_index_ = num_restarts_;
return;
}
restart_index_--;
}
SeekToRestartPoint(restart_index_);
do {
// Loop until end of current entry hits the start of original entry
} while (ParseNextKey() && NextEntryOffset() < original);
}
virtual void Seek(const Slice& target) {
// Binary search in restart array to find the first restart point
// with a key >= target
uint32_t left = 0;
uint32_t right = num_restarts_ - 1;
while (left < right) {
uint32_t mid = (left + right + 1) / 2;
uint32_t region_offset = GetRestartPoint(mid);
uint32_t shared, non_shared, value_length;
const char* key_ptr = DecodeEntry(data_ + region_offset,
data_ + restarts_,
&shared, &non_shared, &value_length);
if (key_ptr == NULL || (shared != 0)) {
CorruptionError();
return;
}
Slice mid_key(key_ptr, non_shared);
if (Compare(mid_key, target) < 0) {
// Key at "mid" is smaller than "target". Therefore all
// blocks before "mid" are uninteresting.
left = mid;
} else {
// Key at "mid" is >= "target". Therefore all blocks at or
// after "mid" are uninteresting.
right = mid - 1;
}
}
// Linear search (within restart block) for first key >= target
SeekToRestartPoint(left);
while (true) {
if (!ParseNextKey()) {
return;
}
if (Compare(key_, target) >= 0) {
return;
}
}
}
virtual void SeekToFirst() {
SeekToRestartPoint(0);
ParseNextKey();
}
virtual void SeekToLast() {
SeekToRestartPoint(num_restarts_ - 1);
while (ParseNextKey() && NextEntryOffset() < restarts_) {
// Keep skipping
}
}
private:
void CorruptionError() {
current_ = restarts_;
restart_index_ = num_restarts_;
status_ = Status::Corruption("bad entry in block");
key_.clear();
value_.clear();
}
bool ParseNextKey() {
current_ = NextEntryOffset();
const char* p = data_ + current_;
const char* limit = data_ + restarts_; // Restarts come right after data
if (p >= limit) {
// No more entries to return. Mark as invalid.
current_ = restarts_;
restart_index_ = num_restarts_;
return false;
}
// Decode next entry
uint32_t shared, non_shared, value_length;
p = DecodeEntry(p, limit, &shared, &non_shared, &value_length);
if (p == NULL || key_.size() < shared) {
CorruptionError();
return false;
} else {
key_.resize(shared);
key_.append(p, non_shared);
value_ = Slice(p + non_shared, value_length);
while (restart_index_ + 1 < num_restarts_ &&
GetRestartPoint(restart_index_ + 1) < current_) {
++restart_index_;
}
return true;
}
}
};
Iterator* Block::NewIterator(const Comparator* cmp) {
if (size_ < 2*sizeof(uint32_t)) {
return NewErrorIterator(Status::Corruption("bad block contents"));
}
const uint32_t num_restarts = NumRestarts();
if (num_restarts == 0) {
return NewEmptyIterator();
} else {
return new Iter(cmp, data_, restart_offset_, num_restarts);
}
}
}
<commit_msg>fix build on at least linux<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Decodes the blocks generated by block_builder.cc.
#include "table/block.h"
#include <vector>
#include <algorithm>
#include "leveldb/comparator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
inline uint32_t Block::NumRestarts() const {
assert(size_ >= 2*sizeof(uint32_t));
return DecodeFixed32(data_ + size_ - sizeof(uint32_t));
}
Block::Block(const char* data, size_t size)
: data_(data),
size_(size) {
if (size_ < sizeof(uint32_t)) {
size_ = 0; // Error marker
} else {
restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t);
if (restart_offset_ > size_ - sizeof(uint32_t)) {
// The size is too small for NumRestarts() and therefore
// restart_offset_ wrapped around.
size_ = 0;
}
}
}
Block::~Block() {
delete[] data_;
}
// Helper routine: decode the next block entry starting at "p",
// storing the number of shared key bytes, non_shared key bytes,
// and the length of the value in "*shared", "*non_shared", and
// "*value_length", respectively. Will not derefence past "limit".
//
// If any errors are detected, returns NULL. Otherwise, returns a
// pointer to the key delta (just past the three decoded values).
static inline const char* DecodeEntry(const char* p, const char* limit,
uint32_t* shared,
uint32_t* non_shared,
uint32_t* value_length) {
if (limit - p < 3) return NULL;
*shared = reinterpret_cast<const unsigned char*>(p)[0];
*non_shared = reinterpret_cast<const unsigned char*>(p)[1];
*value_length = reinterpret_cast<const unsigned char*>(p)[2];
if ((*shared | *non_shared | *value_length) < 128) {
// Fast path: all three values are encoded in one byte each
p += 3;
} else {
if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL;
}
if (static_cast<uint32_t>(limit - p) < (*non_shared + *value_length)) {
return NULL;
}
return p;
}
class Block::Iter : public Iterator {
private:
const Comparator* const comparator_;
const char* const data_; // underlying block contents
uint32_t const restarts_; // Offset of restart array (list of fixed32)
uint32_t const num_restarts_; // Number of uint32_t entries in restart array
// current_ is offset in data_ of current entry. >= restarts_ if !Valid
uint32_t current_;
uint32_t restart_index_; // Index of restart block in which current_ falls
std::string key_;
Slice value_;
Status status_;
inline int Compare(const Slice& a, const Slice& b) const {
return comparator_->Compare(a, b);
}
// Return the offset in data_ just past the end of the current entry.
inline uint32_t NextEntryOffset() const {
return (value_.data() + value_.size()) - data_;
}
uint32_t GetRestartPoint(uint32_t index) {
assert(index < num_restarts_);
return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t));
}
void SeekToRestartPoint(uint32_t index) {
key_.clear();
restart_index_ = index;
// current_ will be fixed by ParseNextKey();
// ParseNextKey() starts at the end of value_, so set value_ accordingly
uint32_t offset = GetRestartPoint(index);
value_ = Slice(data_ + offset, 0);
}
public:
Iter(const Comparator* comparator,
const char* data,
uint32_t restarts,
uint32_t num_restarts)
: comparator_(comparator),
data_(data),
restarts_(restarts),
num_restarts_(num_restarts),
current_(restarts_),
restart_index_(num_restarts_) {
assert(num_restarts_ > 0);
}
virtual bool Valid() const { return current_ < restarts_; }
virtual Status status() const { return status_; }
virtual Slice key() const {
assert(Valid());
return key_;
}
virtual Slice value() const {
assert(Valid());
return value_;
}
virtual void Next() {
assert(Valid());
ParseNextKey();
}
virtual void Prev() {
assert(Valid());
// Scan backwards to a restart point before current_
const uint32_t original = current_;
while (GetRestartPoint(restart_index_) >= original) {
if (restart_index_ == 0) {
// No more entries
current_ = restarts_;
restart_index_ = num_restarts_;
return;
}
restart_index_--;
}
SeekToRestartPoint(restart_index_);
do {
// Loop until end of current entry hits the start of original entry
} while (ParseNextKey() && NextEntryOffset() < original);
}
virtual void Seek(const Slice& target) {
// Binary search in restart array to find the first restart point
// with a key >= target
uint32_t left = 0;
uint32_t right = num_restarts_ - 1;
while (left < right) {
uint32_t mid = (left + right + 1) / 2;
uint32_t region_offset = GetRestartPoint(mid);
uint32_t shared, non_shared, value_length;
const char* key_ptr = DecodeEntry(data_ + region_offset,
data_ + restarts_,
&shared, &non_shared, &value_length);
if (key_ptr == NULL || (shared != 0)) {
CorruptionError();
return;
}
Slice mid_key(key_ptr, non_shared);
if (Compare(mid_key, target) < 0) {
// Key at "mid" is smaller than "target". Therefore all
// blocks before "mid" are uninteresting.
left = mid;
} else {
// Key at "mid" is >= "target". Therefore all blocks at or
// after "mid" are uninteresting.
right = mid - 1;
}
}
// Linear search (within restart block) for first key >= target
SeekToRestartPoint(left);
while (true) {
if (!ParseNextKey()) {
return;
}
if (Compare(key_, target) >= 0) {
return;
}
}
}
virtual void SeekToFirst() {
SeekToRestartPoint(0);
ParseNextKey();
}
virtual void SeekToLast() {
SeekToRestartPoint(num_restarts_ - 1);
while (ParseNextKey() && NextEntryOffset() < restarts_) {
// Keep skipping
}
}
private:
void CorruptionError() {
current_ = restarts_;
restart_index_ = num_restarts_;
status_ = Status::Corruption("bad entry in block");
key_.clear();
value_.clear();
}
bool ParseNextKey() {
current_ = NextEntryOffset();
const char* p = data_ + current_;
const char* limit = data_ + restarts_; // Restarts come right after data
if (p >= limit) {
// No more entries to return. Mark as invalid.
current_ = restarts_;
restart_index_ = num_restarts_;
return false;
}
// Decode next entry
uint32_t shared, non_shared, value_length;
p = DecodeEntry(p, limit, &shared, &non_shared, &value_length);
if (p == NULL || key_.size() < shared) {
CorruptionError();
return false;
} else {
key_.resize(shared);
key_.append(p, non_shared);
value_ = Slice(p + non_shared, value_length);
while (restart_index_ + 1 < num_restarts_ &&
GetRestartPoint(restart_index_ + 1) < current_) {
++restart_index_;
}
return true;
}
}
};
Iterator* Block::NewIterator(const Comparator* cmp) {
if (size_ < 2*sizeof(uint32_t)) {
return NewErrorIterator(Status::Corruption("bad block contents"));
}
const uint32_t num_restarts = NumRestarts();
if (num_restarts == 0) {
return NewEmptyIterator();
} else {
return new Iter(cmp, data_, restart_offset_, num_restarts);
}
}
}
<|endoftext|>
|
<commit_before>// Input:
// 32 digit key, then
// 8 digit nonce, then
// plaintext (cyphertext) digits
//
// Output:
// 8 digit nonce, then
// cyphertext (plaintext) digits
#include <stdio.h>
#include <inttypes.h>
#include <cstdint>
std::uint32_t rotl(std::uint32_t v, std::uint32_t shift)
{
shift = shift % 32;
return (v << shift) | (v >> (32 - shift));
}
const uint8_t r = 20; // rounds
const uint8_t t = 2 * (r + 1); // the number of words in the expanded key table
uint32_t expaned_key_table[t];
void rc5_setup(unsigned char *key_bytes)
{
const uint8_t w = 32; // word length in bits. Block is two words.
const uint8_t b = 16; // key length in bytes
const uint8_t c = 4; // RFC: (b + w/8 - 1) / (w/8) = (16 + 4 - 1) / 4 = 4
uint32_t i, j, k, u = w/8, A, B, key_words[c];
key_words[c - 1] = 0;
for (i = b - 1; i != -1; i--) {
key_words[i/u] = (key_words[i/u] << 8) + key_bytes[i];
}
expaned_key_table[0] = 0xB7E15163;
for (i = 1; i < t; i++) {
expaned_key_table[i] = expaned_key_table[i - 1] + 0x9E3779B9;
}
A = B = i = j = 0;
for (k = 0; k < 3 * t; k++)
{
A = expaned_key_table[i] = rotl(expaned_key_table[i] + (A + B), 3);
B = key_words[j] = rotl(key_words[j] + (A + B), (A + B));
i = (i + 1) % t;
j = (j + 1) % c;
}
}
void rc5_encrypt(uint32_t *pin, uint32_t *pout)
{
uint32_t A = pin[0] + expaned_key_table[0];
fprintf(stderr, "A0=0x%08x+0x%08x=0x%08x\n",pin[0],expaned_key_table[0],A);
uint32_t B = pin[1] + expaned_key_table[1];
fprintf(stderr, "B0=0x%08x+0x%08x=0x%08x\n",pin[1],expaned_key_table[1],B);
for (uint32_t i = 1; i <= r; i++) {
fprintf(stderr, "A%d = rotl(0x%08x ^ 0x%08x = 0x%08x, 0x%08x) + 0x%08x = 0x%08x + 0x%08x = 0x%08x\n",
i, A, B, A ^ B, B, expaned_key_table[2 * i], rotl(A ^ B, B), expaned_key_table[2 * i], rotl(A ^ B, B) + expaned_key_table[2 * i]);
A = rotl(A ^ B, B) + expaned_key_table[2 * i];
fprintf(stderr, "B%d = rotl(0x%08x ^ 0x%08x= 0x%08x, 0x%08x) + 0x%08x = 0x%08x\n",
i, B, A, B ^ A, A, expaned_key_table[2 * i + 1], rotl(B ^ A, A) + expaned_key_table[2 * i + 1]);
B = rotl(B ^ A, A) + expaned_key_table[2 * i + 1];
}
pout[0] = A;
pout[1] = B;
}
void emit(char c)
{
static int count = 0;
if (c < '0' || c > '9') {
fprintf(stderr, "Generated invalid character code %d\n", c);
return;
}
putchar(c);
switch (++count) {
case 4: putchar(' '); break;
case 8: putchar(' '); break;
case 12: putchar(' '); break;
case 16: putchar(' '); putchar(' '); break;
case 20: putchar(' '); break;
case 24: putchar(' '); break;
case 28: putchar(' '); break;
case 32: putchar('\n'); count = 0; break;
}
}
int main(void)
{
unsigned char key[16] = {0};
int c;
for (int i = 0; i < 32; ) {
c = getchar();
switch (c) {
case EOF:
fprintf(stderr, "Key too short (expected 32 digits, got %d)\n", i);
return -1;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
if (i & 1) {
key[i >> 1] |= (c - '0') << 4;
} else {
key[i >> 1] |= (c - '0');
}
i++;
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected key digit, got %c\n", c);
return -2;
}
}
// fprintf(stderr, "Key: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
// key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], key[8], key[9], key[10], key[11], key[12], key[13], key[14], key[15]
// );
rc5_setup(&key[0]);
// Nibbler assembly code generation
#if 1
printf("#define EXPANDED_KEY_TABLE $c0 ; 42 32 bit words = 172 nibbles\n");
for (int i = 0; i < t; i++) {
printf("\n;Expaned key table word %d of %d\n", i, t);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] ) & 0xf, i * 8 + 0);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 4) & 0xf, i * 8 + 1);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 8) & 0xf, i * 8 + 2);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 12) & 0xf, i * 8 + 3);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 16) & 0xf, i * 8 + 4);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 20) & 0xf, i * 8 + 5);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 24) & 0xf, i * 8 + 6);
printf(" lit #$%x\n st EXPANDED_KEY_TABLE+%d\n", (expaned_key_table[i] >> 28) & 0xf, i * 8 + 7);
}
#endif
uint32_t text[2] = { 0 }; // text[0] is nonce, text[1] is counter for CTR mode
for (int i = 0; i < 8; ) {
c = getchar();
switch (c) {
case EOF:
fprintf(stderr, "Nonce too short (expected 8 digits, got %d)\n", i);
return -3;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
text[0] |= (c - '0') << i * 4;
i++;
emit(c);
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected nonce digit, got %c\n", c);
return -4;
}
}
// fprintf(stderr, "Nonce: %08x\n", text[0]);
uint32_t stream[2] = { 0 };
int nibbles_left = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case EOF:
putchar('\n');
return 0;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
int digit;
for (;;) {
if (!nibbles_left) {
rc5_encrypt(text, stream);
text[1]++;
nibbles_left = 16; // 2 32 bit words = 16 4 bit nibbles
}
nibbles_left--;
if (nibbles_left > 8) {
digit = (stream[0] >> ((nibbles_left - 8) * 4)) & 0xf;
} else {
digit = (stream[1] >> (nibbles_left * 4)) & 0xf;
}
if (digit < 10) {
break;
}
}
//fprintf(stderr, "%d %d %d\n", digit, c - '0', (20 - digit - (c - '0')) % 10);
digit = (20 - digit - (c - '0')) % 10;
emit(digit + '0');
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected plaintext digit, got %c\n", c);
return -5;
}
}
}
<commit_msg>Reordering expanded key table setup to save program space<commit_after>// Input:
// 32 digit key, then
// 8 digit nonce, then
// plaintext (cyphertext) digits
//
// Output:
// 8 digit nonce, then
// cyphertext (plaintext) digits
#include <stdio.h>
#include <inttypes.h>
#include <cstdint>
#include <set>
std::uint32_t rotl(std::uint32_t v, std::uint32_t shift)
{
shift = shift % 32;
return (v << shift) | (v >> (32 - shift));
}
const uint8_t r = 16; // rounds
const uint8_t t = 2 * (r + 1); // the number of words in the expanded key table
uint32_t expaned_key_table[t];
void rc5_setup(unsigned char *key_bytes)
{
const uint8_t w = 32; // word length in bits. Block is two words.
const uint8_t b = 16; // key length in bytes
const uint8_t c = 4; // RFC: (b + w/8 - 1) / (w/8) = (16 + 4 - 1) / 4 = 4
uint32_t i, j, k, u = w/8, A, B, key_words[c];
key_words[c - 1] = 0;
for (i = b - 1; i != -1; i--) {
key_words[i/u] = (key_words[i/u] << 8) + key_bytes[i];
}
expaned_key_table[0] = 0xB7E15163;
for (i = 1; i < t; i++) {
expaned_key_table[i] = expaned_key_table[i - 1] + 0x9E3779B9;
}
A = B = i = j = 0;
for (k = 0; k < 3 * t; k++)
{
A = expaned_key_table[i] = rotl(expaned_key_table[i] + (A + B), 3);
B = key_words[j] = rotl(key_words[j] + (A + B), (A + B));
i = (i + 1) % t;
j = (j + 1) % c;
}
}
void rc5_encrypt(uint32_t *pin, uint32_t *pout)
{
uint32_t A = pin[0] + expaned_key_table[0];
fprintf(stderr, "A0=0x%08x+0x%08x=0x%08x\n",pin[0],expaned_key_table[0],A);
uint32_t B = pin[1] + expaned_key_table[1];
fprintf(stderr, "B0=0x%08x+0x%08x=0x%08x\n",pin[1],expaned_key_table[1],B);
for (uint32_t i = 1; i <= r; i++) {
fprintf(stderr, "A%d = rotl(0x%08x ^ 0x%08x = 0x%08x, 0x%08x) + 0x%08x = 0x%08x + 0x%08x = 0x%08x\n",
i, A, B, A ^ B, B, expaned_key_table[2 * i], rotl(A ^ B, B), expaned_key_table[2 * i], rotl(A ^ B, B) + expaned_key_table[2 * i]);
A = rotl(A ^ B, B) + expaned_key_table[2 * i];
fprintf(stderr, "B%d = rotl(0x%08x ^ 0x%08x= 0x%08x, 0x%08x) + 0x%08x = 0x%08x\n",
i, B, A, B ^ A, A, expaned_key_table[2 * i + 1], rotl(B ^ A, A) + expaned_key_table[2 * i + 1]);
B = rotl(B ^ A, A) + expaned_key_table[2 * i + 1];
}
pout[0] = A;
pout[1] = B;
fprintf(stderr, "%08x %08x -> %08x %08x\n",pin[0],pin[1],pout[0],pout[1]);
}
void emit(char c)
{
static int count = 0;
if (c < '0' || c > '9') {
fprintf(stderr, "Generated invalid character code %d\n", c);
return;
}
putchar(c);
switch (++count) {
case 4: putchar(' '); break;
case 8: putchar(' '); break;
case 12: putchar(' '); break;
case 16: putchar(' '); putchar(' '); break;
case 20: putchar(' '); break;
case 24: putchar(' '); break;
case 28: putchar(' '); break;
case 32: putchar('\n'); count = 0; break;
}
}
int main(void)
{
unsigned char key[16] = {0};
int c;
for (int i = 0; i < 32; ) {
c = getchar();
switch (c) {
case EOF:
fprintf(stderr, "Key too short (expected 32 digits, got %d)\n", i);
return -1;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
if (i & 1) {
key[i >> 1] |= (c - '0') << 4;
} else {
key[i >> 1] |= (c - '0');
}
i++;
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected key digit, got %c\n", c);
return -2;
}
}
// fprintf(stderr, "Key: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
// key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], key[8], key[9], key[10], key[11], key[12], key[13], key[14], key[15]
// );
rc5_setup(&key[0]);
// Nibbler assembly code generation
#if 1
printf("#define EXPANDED_KEY_TABLE $c0 ; %d 32 bit words = %d nibbles\n", t, t * 8);
// Order by nibble value to reduce number of lit commands
std::set<int> nibble_addr[16];
for (int i = 0; i < t; i++) {
nibble_addr[(expaned_key_table[i] ) & 0xf].insert(i * 8 + 0);
nibble_addr[(expaned_key_table[i] >> 4) & 0xf].insert(i * 8 + 1);
nibble_addr[(expaned_key_table[i] >> 8) & 0xf].insert(i * 8 + 2);
nibble_addr[(expaned_key_table[i] >> 12) & 0xf].insert(i * 8 + 3);
nibble_addr[(expaned_key_table[i] >> 16) & 0xf].insert(i * 8 + 4);
nibble_addr[(expaned_key_table[i] >> 20) & 0xf].insert(i * 8 + 5);
nibble_addr[(expaned_key_table[i] >> 24) & 0xf].insert(i * 8 + 6);
nibble_addr[(expaned_key_table[i] >> 28) & 0xf].insert(i * 8 + 7);
}
for (int i = 0; i < 16; i++) {
printf(" lit #$%x\n", i);
for ( std::set<int>::const_iterator it = nibble_addr[i].begin()
; it != nibble_addr[i].end()
; ++it
) {
printf(" st EXPANDED_KEY_TABLE+%d\n", *it);
}
}
#endif
uint32_t text[2] = { 0 }; // text[0] is nonce, text[1] is counter for CTR mode
for (int i = 0; i < 8; ) {
c = getchar();
switch (c) {
case EOF:
fprintf(stderr, "Nonce too short (expected 8 digits, got %d)\n", i);
return -3;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
text[0] |= (c - '0') << i * 4;
i++;
emit(c);
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected nonce digit, got %c\n", c);
return -4;
}
}
// fprintf(stderr, "Nonce: %08x\n", text[0]);
uint32_t stream[2] = { 0 };
int nibbles_left = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case EOF:
putchar('\n');
return 0;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '0':
int digit;
for (;;) {
if (!nibbles_left) {
rc5_encrypt(text, stream);
text[1]++;
nibbles_left = 16; // 2 32 bit words = 16 4 bit nibbles
}
nibbles_left--;
if (nibbles_left > 8) {
digit = (stream[0] >> ((nibbles_left - 8) * 4)) & 0xf;
} else {
digit = (stream[1] >> (nibbles_left * 4)) & 0xf;
}
if (digit < 10) {
break;
}
}
//fprintf(stderr, "%d %d %d\n", digit, c - '0', (20 - digit - (c - '0')) % 10);
digit = (20 - digit - (c - '0')) % 10;
emit(digit + '0');
break;
case ' ': case '\n': case '\r': case '\t':
break;
default:
fprintf(stderr, "Expected plaintext digit, got %c\n", c);
return -5;
}
}
}
<|endoftext|>
|
<commit_before>/*
* about_dialog.cpp
* PHD Guiding
*
* Created by Sylvain Girard.
* Copyright (c) 2013 Sylvain Girard.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>
BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()
AboutDialog::AboutDialog(void) :
wxDialog(pFrame, wxID_ANY, _T("About ") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
#include "icons/phd.xpm" // defines prog_icon[]
SetBackgroundColour(*wxWHITE);
wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
wxBitmap bmp(prog_icon);
wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);
wxFileSystem::AddHandler(new wxMemoryFSHandler);
wxMemoryFSHandler::AddFile("about.html", wxString::Format(
"<html><body>"
"<h3>%s %s</h3>"
"<a href=\"http://openphdguiding.org\">PHD2 home page - openphdguiding.org</a><br>"
"<a href=\"https://code.google.com/p/open-phd-guiding/\">PHD2 open source project page</a><br><br>"
"<font size=\"2\">"
"Credits:<br>"
" Craig Stark<br>"
" Bret McKee<br>"
" Andy Galasso<br>"
" Bernhard Reutner-Fischer<br>"
" Stefan Elste<br>"
" Geoffrey Hausheer<br>"
" Jared Wellman<br>"
" John Wainwright<br>"
" Sylvain Girard<br>"
" Bruce Waddington<br>"
" Max Chen<br>"
" Carsten Przygoda<br>"
" Hans Lambermont<br>"
" David Ault<br>"
" Markus Wieczorek<br>"
" Linkage<br>"
" Robin Glover<br>"
"<br>"
"Copyright 2006-2013 Craig Stark<br>"
"Copyright 2009 Geoffrey Hausheer<br>"
"Copyright 2012-2013 Bret McKee<br>"
"Copyright 2013 Sylvain Girard<br>"
"Copyright 2013-2014 Andy Galasso<br>"
"Copyright 2013-2014 Bruce Waddington<br>"
"Copyright 2014 Hans Lambermont<br>"
"Copyright 2014 Robin Glover<br>"
"</font>"
"</body></html>", APPNAME, FULLVER));
wxHtmlWindow *pHtml;
pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 540), wxHW_SCROLLBAR_AUTO);
pHtml->SetBorders(0);
pHtml->LoadPage("memory:about.html");
pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());
pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));
wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));
SetSizerAndFit(pTopLevelSizer);
}
AboutDialog::~AboutDialog(void)
{
wxMemoryFSHandler::RemoveFile("about.html");
}
void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<commit_msg>add Patrick and Scott to About dialog<commit_after>/*
* about_dialog.cpp
* PHD Guiding
*
* Created by Sylvain Girard.
* Copyright (c) 2013 Sylvain Girard.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>
BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()
AboutDialog::AboutDialog(void) :
wxDialog(pFrame, wxID_ANY, _T("About ") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
#include "icons/phd.xpm" // defines prog_icon[]
SetBackgroundColour(*wxWHITE);
wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
wxBitmap bmp(prog_icon);
wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);
wxFileSystem::AddHandler(new wxMemoryFSHandler);
wxMemoryFSHandler::AddFile("about.html", wxString::Format(
"<html><body>"
"<h3>%s %s</h3>"
"<a href=\"http://openphdguiding.org\">PHD2 home page - openphdguiding.org</a><br>"
"<a href=\"https://code.google.com/p/open-phd-guiding/\">PHD2 open source project page</a><br><br>"
"<font size=\"2\">"
"Credits:<br>"
"<table>"
"<tr>"
"<td>Craig Stark</td>"
"<td>Bret McKee</td>"
"</tr>"
"<tr>"
"<td>Andy Galasso</td>"
"<td>Bernhard Reutner-Fischer</td>"
"</tr>"
"<tr>"
"<td>Stefan Elste</td>"
"<td>Geoffrey Hausheer</td>"
"</tr>"
"<tr>"
"<td>Jared Wellman</td>"
"<td>John Wainwright</td>"
"</tr>"
"<tr>"
"<td>Sylvain Girard</td>"
"<td>Bruce Waddington</td>"
"</tr>"
"<tr>"
"<td>Max Chen</td>"
"<td>Carsten Przygoda</td>"
"</tr>"
"<tr>"
"<td>Hans Lambermont</td>"
"<td>David Ault</td>"
"</tr>"
"<tr>"
"<td>Markus Wieczorek</td>"
"<td>Linkage</td>"
"</tr>"
"<tr>"
"<td>Robin Glover</td>"
"<td>Patrick Chevalley</td>"
"</tr>"
"<tr>"
"<td>Scott Edwards</td>"
"</tr>"
"</table><br>"
"<br>"
"<br>"
"Copyright 2006-2013 Craig Stark<br>"
"Copyright 2009 Geoffrey Hausheer<br>"
"Copyright 2012-2013 Bret McKee<br>"
"Copyright 2013 Sylvain Girard<br>"
"Copyright 2013-2014 Andy Galasso<br>"
"Copyright 2013-2014 Bruce Waddington<br>"
"Copyright 2014 Hans Lambermont<br>"
"Copyright 2014 Robin Glover<br>"
"</font>"
"</body></html>", APPNAME, FULLVER));
wxHtmlWindow *pHtml;
pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 540), wxHW_SCROLLBAR_AUTO);
pHtml->SetBorders(0);
pHtml->LoadPage("memory:about.html");
pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());
pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));
wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));
SetSizerAndFit(pTopLevelSizer);
}
AboutDialog::~AboutDialog(void)
{
wxMemoryFSHandler::RemoveFile("about.html");
}
void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_receiver.h"
#include <vector>
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/utility/interface/rtp_dump.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
ViEReceiver::ViEReceiver(const int32_t channel_id,
VideoCodingModule* module_vcm,
RemoteBitrateEstimator* remote_bitrate_estimator)
: receive_cs_(CriticalSectionWrapper::CreateCriticalSection()),
channel_id_(channel_id),
rtp_header_parser_(RtpHeaderParser::Create()),
rtp_rtcp_(NULL),
vcm_(module_vcm),
remote_bitrate_estimator_(remote_bitrate_estimator),
external_decryption_(NULL),
decryption_buffer_(NULL),
rtp_dump_(NULL),
receiving_(false) {
assert(remote_bitrate_estimator);
}
ViEReceiver::~ViEReceiver() {
if (decryption_buffer_) {
delete[] decryption_buffer_;
decryption_buffer_ = NULL;
}
if (rtp_dump_) {
rtp_dump_->Stop();
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
}
}
int ViEReceiver::RegisterExternalDecryption(Encryption* decryption) {
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_) {
return -1;
}
decryption_buffer_ = new uint8_t[kViEMaxMtu];
if (decryption_buffer_ == NULL) {
return -1;
}
external_decryption_ = decryption;
return 0;
}
int ViEReceiver::DeregisterExternalDecryption() {
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_ == NULL) {
return -1;
}
external_decryption_ = NULL;
return 0;
}
void ViEReceiver::SetRtpRtcpModule(RtpRtcp* module) {
rtp_rtcp_ = module;
}
void ViEReceiver::RegisterSimulcastRtpRtcpModules(
const std::list<RtpRtcp*>& rtp_modules) {
CriticalSectionScoped cs(receive_cs_.get());
rtp_rtcp_simulcast_.clear();
if (!rtp_modules.empty()) {
rtp_rtcp_simulcast_.insert(rtp_rtcp_simulcast_.begin(),
rtp_modules.begin(),
rtp_modules.end());
}
}
bool ViEReceiver::SetReceiveTimestampOffsetStatus(bool enable, int id) {
if (enable) {
return rtp_header_parser_->RegisterRtpHeaderExtension(
kRtpExtensionTransmissionTimeOffset, id);
} else {
return rtp_header_parser_->DeregisterRtpHeaderExtension(
kRtpExtensionTransmissionTimeOffset);
}
}
bool ViEReceiver::SetReceiveAbsoluteSendTimeStatus(bool enable, int id) {
if (enable) {
return rtp_header_parser_->RegisterRtpHeaderExtension(
kRtpExtensionAbsoluteSendTime, id);
} else {
return rtp_header_parser_->DeregisterRtpHeaderExtension(
kRtpExtensionAbsoluteSendTime);
}
}
int ViEReceiver::ReceivedRTPPacket(const void* rtp_packet,
int rtp_packet_length) {
if (!receiving_) {
return -1;
}
return InsertRTPPacket(static_cast<const int8_t*>(rtp_packet),
rtp_packet_length);
}
int ViEReceiver::ReceivedRTCPPacket(const void* rtcp_packet,
int rtcp_packet_length) {
if (!receiving_) {
return -1;
}
return InsertRTCPPacket(static_cast<const int8_t*>(rtcp_packet),
rtcp_packet_length);
}
int32_t ViEReceiver::OnReceivedPayloadData(
const uint8_t* payload_data, const uint16_t payload_size,
const WebRtcRTPHeader* rtp_header) {
if (rtp_header == NULL) {
return 0;
}
if (vcm_->IncomingPacket(payload_data, payload_size, *rtp_header) != 0) {
// Check this...
return -1;
}
return 0;
}
int ViEReceiver::InsertRTPPacket(const int8_t* rtp_packet,
int rtp_packet_length) {
// TODO(mflodman) Change decrypt to get rid of this cast.
int8_t* tmp_ptr = const_cast<int8_t*>(rtp_packet);
unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
int received_packet_length = rtp_packet_length;
{
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_) {
int decrypted_length = kViEMaxMtu;
external_decryption_->decrypt(channel_id_, received_packet,
decryption_buffer_, received_packet_length,
&decrypted_length);
if (decrypted_length <= 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"RTP decryption failed");
return -1;
} else if (decrypted_length > kViEMaxMtu) {
WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
"InsertRTPPacket: %d bytes is allocated as RTP decrytption"
" output, external decryption used %d bytes. => memory is "
" now corrupted", kViEMaxMtu, decrypted_length);
return -1;
}
received_packet = decryption_buffer_;
received_packet_length = decrypted_length;
}
if (rtp_dump_) {
rtp_dump_->DumpPacket(received_packet,
static_cast<uint16_t>(received_packet_length));
}
}
RTPHeader header;
if (!rtp_header_parser_->Parse(received_packet, received_packet_length,
&header)) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
"IncomingPacket invalid RTP header");
return -1;
}
const int payload_size = received_packet_length - header.headerLength;
remote_bitrate_estimator_->IncomingPacket(TickTime::MillisecondTimestamp(),
payload_size, header);
assert(rtp_rtcp_); // Should be set by owner at construction time.
return rtp_rtcp_->IncomingRtpPacket(received_packet, received_packet_length,
header);
}
int ViEReceiver::InsertRTCPPacket(const int8_t* rtcp_packet,
int rtcp_packet_length) {
// TODO(mflodman) Change decrypt to get rid of this cast.
int8_t* tmp_ptr = const_cast<int8_t*>(rtcp_packet);
unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
int received_packet_length = rtcp_packet_length;
{
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_) {
int decrypted_length = kViEMaxMtu;
external_decryption_->decrypt_rtcp(channel_id_, received_packet,
decryption_buffer_,
received_packet_length,
&decrypted_length);
if (decrypted_length <= 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"RTP decryption failed");
return -1;
} else if (decrypted_length > kViEMaxMtu) {
WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
"InsertRTCPPacket: %d bytes is allocated as RTP "
" decrytption output, external decryption used %d bytes. "
" => memory is now corrupted",
kViEMaxMtu, decrypted_length);
return -1;
}
received_packet = decryption_buffer_;
received_packet_length = decrypted_length;
}
if (rtp_dump_) {
rtp_dump_->DumpPacket(
received_packet, static_cast<uint16_t>(received_packet_length));
}
}
{
CriticalSectionScoped cs(receive_cs_.get());
std::list<RtpRtcp*>::iterator it = rtp_rtcp_simulcast_.begin();
while (it != rtp_rtcp_simulcast_.end()) {
RtpRtcp* rtp_rtcp = *it++;
rtp_rtcp->IncomingRtcpPacket(received_packet, received_packet_length);
}
}
assert(rtp_rtcp_); // Should be set by owner at construction time.
return rtp_rtcp_->IncomingRtcpPacket(received_packet, received_packet_length);
}
void ViEReceiver::StartReceive() {
receiving_ = true;
}
void ViEReceiver::StopReceive() {
receiving_ = false;
}
int ViEReceiver::StartRTPDump(const char file_nameUTF8[1024]) {
CriticalSectionScoped cs(receive_cs_.get());
if (rtp_dump_) {
// Restart it if it already exists and is started
rtp_dump_->Stop();
} else {
rtp_dump_ = RtpDump::CreateRtpDump();
if (rtp_dump_ == NULL) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StartRTPDump: Failed to create RTP dump");
return -1;
}
}
if (rtp_dump_->Start(file_nameUTF8) != 0) {
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StartRTPDump: Failed to start RTP dump");
return -1;
}
return 0;
}
int ViEReceiver::StopRTPDump() {
CriticalSectionScoped cs(receive_cs_.get());
if (rtp_dump_) {
if (rtp_dump_->IsActive()) {
rtp_dump_->Stop();
} else {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StopRTPDump: Dump not active");
}
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
} else {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StopRTPDump: RTP dump not started");
return -1;
}
return 0;
}
// TODO(holmer): To be moved to ViEChannelGroup.
void ViEReceiver::EstimatedReceiveBandwidth(
unsigned int* available_bandwidth) const {
std::vector<unsigned int> ssrcs;
// LatestEstimate returns an error if there is no valid bitrate estimate, but
// ViEReceiver instead returns a zero estimate.
remote_bitrate_estimator_->LatestEstimate(&ssrcs, available_bandwidth);
if (std::find(ssrcs.begin(), ssrcs.end(), rtp_rtcp_->RemoteSSRC()) !=
ssrcs.end()) {
*available_bandwidth /= ssrcs.size();
} else {
*available_bandwidth = 0;
}
}
} // namespace webrtc
<commit_msg>Access receiving_ under receive_cs critical section Note: InsertRTPPacket/InsertRTCPPacket could be merged into ReceivedRTPPacket, as there are no other callers.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_receiver.h"
#include <vector>
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/utility/interface/rtp_dump.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
ViEReceiver::ViEReceiver(const int32_t channel_id,
VideoCodingModule* module_vcm,
RemoteBitrateEstimator* remote_bitrate_estimator)
: receive_cs_(CriticalSectionWrapper::CreateCriticalSection()),
channel_id_(channel_id),
rtp_header_parser_(RtpHeaderParser::Create()),
rtp_rtcp_(NULL),
vcm_(module_vcm),
remote_bitrate_estimator_(remote_bitrate_estimator),
external_decryption_(NULL),
decryption_buffer_(NULL),
rtp_dump_(NULL),
receiving_(false) {
assert(remote_bitrate_estimator);
}
ViEReceiver::~ViEReceiver() {
if (decryption_buffer_) {
delete[] decryption_buffer_;
decryption_buffer_ = NULL;
}
if (rtp_dump_) {
rtp_dump_->Stop();
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
}
}
int ViEReceiver::RegisterExternalDecryption(Encryption* decryption) {
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_) {
return -1;
}
decryption_buffer_ = new uint8_t[kViEMaxMtu];
if (decryption_buffer_ == NULL) {
return -1;
}
external_decryption_ = decryption;
return 0;
}
int ViEReceiver::DeregisterExternalDecryption() {
CriticalSectionScoped cs(receive_cs_.get());
if (external_decryption_ == NULL) {
return -1;
}
external_decryption_ = NULL;
return 0;
}
void ViEReceiver::SetRtpRtcpModule(RtpRtcp* module) {
rtp_rtcp_ = module;
}
void ViEReceiver::RegisterSimulcastRtpRtcpModules(
const std::list<RtpRtcp*>& rtp_modules) {
CriticalSectionScoped cs(receive_cs_.get());
rtp_rtcp_simulcast_.clear();
if (!rtp_modules.empty()) {
rtp_rtcp_simulcast_.insert(rtp_rtcp_simulcast_.begin(),
rtp_modules.begin(),
rtp_modules.end());
}
}
bool ViEReceiver::SetReceiveTimestampOffsetStatus(bool enable, int id) {
if (enable) {
return rtp_header_parser_->RegisterRtpHeaderExtension(
kRtpExtensionTransmissionTimeOffset, id);
} else {
return rtp_header_parser_->DeregisterRtpHeaderExtension(
kRtpExtensionTransmissionTimeOffset);
}
}
bool ViEReceiver::SetReceiveAbsoluteSendTimeStatus(bool enable, int id) {
if (enable) {
return rtp_header_parser_->RegisterRtpHeaderExtension(
kRtpExtensionAbsoluteSendTime, id);
} else {
return rtp_header_parser_->DeregisterRtpHeaderExtension(
kRtpExtensionAbsoluteSendTime);
}
}
int ViEReceiver::ReceivedRTPPacket(const void* rtp_packet,
int rtp_packet_length) {
return InsertRTPPacket(static_cast<const int8_t*>(rtp_packet),
rtp_packet_length);
}
int ViEReceiver::ReceivedRTCPPacket(const void* rtcp_packet,
int rtcp_packet_length) {
return InsertRTCPPacket(static_cast<const int8_t*>(rtcp_packet),
rtcp_packet_length);
}
int32_t ViEReceiver::OnReceivedPayloadData(
const uint8_t* payload_data, const uint16_t payload_size,
const WebRtcRTPHeader* rtp_header) {
if (rtp_header == NULL) {
return 0;
}
if (vcm_->IncomingPacket(payload_data, payload_size, *rtp_header) != 0) {
// Check this...
return -1;
}
return 0;
}
int ViEReceiver::InsertRTPPacket(const int8_t* rtp_packet,
int rtp_packet_length) {
// TODO(mflodman) Change decrypt to get rid of this cast.
int8_t* tmp_ptr = const_cast<int8_t*>(rtp_packet);
unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
int received_packet_length = rtp_packet_length;
{
CriticalSectionScoped cs(receive_cs_.get());
if (!receiving_) {
return -1;
}
if (external_decryption_) {
int decrypted_length = kViEMaxMtu;
external_decryption_->decrypt(channel_id_, received_packet,
decryption_buffer_, received_packet_length,
&decrypted_length);
if (decrypted_length <= 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"RTP decryption failed");
return -1;
} else if (decrypted_length > kViEMaxMtu) {
WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
"InsertRTPPacket: %d bytes is allocated as RTP decrytption"
" output, external decryption used %d bytes. => memory is "
" now corrupted", kViEMaxMtu, decrypted_length);
return -1;
}
received_packet = decryption_buffer_;
received_packet_length = decrypted_length;
}
if (rtp_dump_) {
rtp_dump_->DumpPacket(received_packet,
static_cast<uint16_t>(received_packet_length));
}
}
RTPHeader header;
if (!rtp_header_parser_->Parse(received_packet, received_packet_length,
&header)) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideo, channel_id_,
"IncomingPacket invalid RTP header");
return -1;
}
const int payload_size = received_packet_length - header.headerLength;
remote_bitrate_estimator_->IncomingPacket(TickTime::MillisecondTimestamp(),
payload_size, header);
assert(rtp_rtcp_); // Should be set by owner at construction time.
return rtp_rtcp_->IncomingRtpPacket(received_packet, received_packet_length,
header);
}
int ViEReceiver::InsertRTCPPacket(const int8_t* rtcp_packet,
int rtcp_packet_length) {
// TODO(mflodman) Change decrypt to get rid of this cast.
int8_t* tmp_ptr = const_cast<int8_t*>(rtcp_packet);
unsigned char* received_packet = reinterpret_cast<unsigned char*>(tmp_ptr);
int received_packet_length = rtcp_packet_length;
{
CriticalSectionScoped cs(receive_cs_.get());
if (!receiving_) {
return -1;
}
if (external_decryption_) {
int decrypted_length = kViEMaxMtu;
external_decryption_->decrypt_rtcp(channel_id_, received_packet,
decryption_buffer_,
received_packet_length,
&decrypted_length);
if (decrypted_length <= 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"RTP decryption failed");
return -1;
} else if (decrypted_length > kViEMaxMtu) {
WEBRTC_TRACE(webrtc::kTraceCritical, webrtc::kTraceVideo, channel_id_,
"InsertRTCPPacket: %d bytes is allocated as RTP "
" decrytption output, external decryption used %d bytes. "
" => memory is now corrupted",
kViEMaxMtu, decrypted_length);
return -1;
}
received_packet = decryption_buffer_;
received_packet_length = decrypted_length;
}
if (rtp_dump_) {
rtp_dump_->DumpPacket(
received_packet, static_cast<uint16_t>(received_packet_length));
}
}
{
CriticalSectionScoped cs(receive_cs_.get());
std::list<RtpRtcp*>::iterator it = rtp_rtcp_simulcast_.begin();
while (it != rtp_rtcp_simulcast_.end()) {
RtpRtcp* rtp_rtcp = *it++;
rtp_rtcp->IncomingRtcpPacket(received_packet, received_packet_length);
}
}
assert(rtp_rtcp_); // Should be set by owner at construction time.
return rtp_rtcp_->IncomingRtcpPacket(received_packet, received_packet_length);
}
void ViEReceiver::StartReceive() {
CriticalSectionScoped cs(receive_cs_.get());
receiving_ = true;
}
void ViEReceiver::StopReceive() {
CriticalSectionScoped cs(receive_cs_.get());
receiving_ = false;
}
int ViEReceiver::StartRTPDump(const char file_nameUTF8[1024]) {
CriticalSectionScoped cs(receive_cs_.get());
if (rtp_dump_) {
// Restart it if it already exists and is started
rtp_dump_->Stop();
} else {
rtp_dump_ = RtpDump::CreateRtpDump();
if (rtp_dump_ == NULL) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StartRTPDump: Failed to create RTP dump");
return -1;
}
}
if (rtp_dump_->Start(file_nameUTF8) != 0) {
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StartRTPDump: Failed to start RTP dump");
return -1;
}
return 0;
}
int ViEReceiver::StopRTPDump() {
CriticalSectionScoped cs(receive_cs_.get());
if (rtp_dump_) {
if (rtp_dump_->IsActive()) {
rtp_dump_->Stop();
} else {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StopRTPDump: Dump not active");
}
RtpDump::DestroyRtpDump(rtp_dump_);
rtp_dump_ = NULL;
} else {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, channel_id_,
"StopRTPDump: RTP dump not started");
return -1;
}
return 0;
}
// TODO(holmer): To be moved to ViEChannelGroup.
void ViEReceiver::EstimatedReceiveBandwidth(
unsigned int* available_bandwidth) const {
std::vector<unsigned int> ssrcs;
// LatestEstimate returns an error if there is no valid bitrate estimate, but
// ViEReceiver instead returns a zero estimate.
remote_bitrate_estimator_->LatestEstimate(&ssrcs, available_bandwidth);
if (std::find(ssrcs.begin(), ssrcs.end(), rtp_rtcp_->RemoteSSRC()) !=
ssrcs.end()) {
*available_bandwidth /= ssrcs.size();
} else {
*available_bandwidth = 0;
}
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>// Comprehensive benchmark demonstrating sharing of cores for different
// workloads.
//
// When built, accepts an arbitrary number of argument pairs: (workload, cpu)
// and launches the given workloads in separate threads on the given CPUs.
//
// For example:
//
// ./thread-workload-benchmark accum 0 sin 1
//
// Launches the "accum" workload in on (logical) CPU 0, and the "sin" workload
// in parallel on CPU 1. Each workload is given its own (separately allocated)
// vector of 100 million floats.
//
// Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <mutex>
#include <pthread.h>
#include <random>
#include <thread>
#include <vector>
// "Workload function" type. Takes a vector of float data and a reference to
// a single float result.
using WorkloadFunc = std::function<void(const std::vector<float>&, float&)>;
// Some aliases to make std::chrono calls shorter.
using hires_clock = std::chrono::high_resolution_clock;
using duration_ms = std::chrono::duration<double, std::milli>;
std::mutex iomutex;
void workload_fpchurn(const std::vector<float>& data, float& result) {
constexpr size_t NUM_ITERS = 10 * 1000 * 1000;
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < NUM_ITERS; ++i) {
float item = data[i];
float l = std::log(item);
if (l > rt) {
l = std::sin(l);
} else {
l = std::cos(l);
}
if (l > rt - 2.0) {
l = std::exp(l);
} else {
l = std::exp(l + 1.0);
}
rt += l;
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [CPU " << sched_getcpu() << "]:\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
}
}
void workload_sin(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < data.size(); ++i) {
rt += std::sin(data[i]);
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_accum(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < data.size(); ++i) {
// On x86-64, this should generate a loop of data.size ADDSS instructions,
// all adding up into the same xmm register. If built with -Ofast
// (-ffast-math), the compiler will be willing to perform unsafe FP
// optimizations and will vectorize the loop into data.size/4 ADDPS
// instructions. Note that this changes the order in which the floats are
// added, which is unsafe because FP addition is not associative.
rt += data[i];
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_unrollaccum4(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
if (data.size() % 4 != 0) {
std::cerr
<< "ERROR in " << __func__ << ": data.size " << data.size() << "\n";
}
float rt0 = 0;
float rt1 = 0;
float rt2 = 0;
float rt3 = 0;
for (size_t i = 0; i < data.size(); i += 4) {
// This unrolling performs manual break-down of dependencies on a single xmm
// register that happens in workload_accum. It should be faster because
// distinct ADDSS instructions will accumulate into separate registers. It
// is also unsafe for the same reasons as described above.
rt0 += data[i];
rt1 += data[i + 1];
rt2 += data[i + 2];
rt3 += data[i + 3];
}
result = rt0 + rt1 + rt2 + rt3;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_unrollaccum8(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
if (data.size() % 8 != 0) {
std::cerr
<< "ERROR in " << __func__ << ": data.size " << data.size() << "\n";
}
float rt0 = 0;
float rt1 = 0;
float rt2 = 0;
float rt3 = 0;
float rt4 = 0;
float rt5 = 0;
float rt6 = 0;
float rt7 = 0;
for (size_t i = 0; i < data.size(); i += 8) {
rt0 += data[i];
rt1 += data[i + 1];
rt2 += data[i + 2];
rt3 += data[i + 3];
rt4 += data[i + 4];
rt5 += data[i + 5];
rt6 += data[i + 6];
rt7 += data[i + 7];
}
result = rt0 + rt1 + rt2 + rt3 + rt4 + rt5 + rt6 + rt7;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_stdaccum(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
result = std::accumulate(data.begin(), data.end(), 0.0f);
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
// Create a vector filled with N floats uniformly distributed in the range
// (-1.0,1.0)
std::vector<float> make_input_array(int N) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
std::vector<float> vf(N);
for (size_t i = 0; i < vf.size(); ++i) {
vf[i] = dis(gen);
}
return vf;
}
// This function can be used to mark memory that shouldn't be optimized away,
// without actually generating any code.
void do_not_optimize(void* p) {
asm volatile("" : : "g"(p) : "memory");
}
// Set the given thread's affinity to be exclusively on the given logical CPU
// number.
void pin_thread_to_cpu(std::thread& t, int cpu_num) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu_num, &cpuset);
int rc =
pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
}
}
int main(int argc, const char** argv) {
// Set locale for comma-separation in large numbers.
std::cout.imbue(std::locale(""));
// Command-line invocation:
//
// argv[0] is the program name
// argv[1] is workload name, with cpu number at argv[2]
// argv[3] is workload name, with cpu number at argv[4]
// ... etc.
int num_workloads = argc / 2;
std::vector<float> results(num_workloads);
do_not_optimize(results.data());
std::vector<std::thread> threads(num_workloads);
constexpr size_t INPUT_SIZE = 100 * 1000 * 1000;
auto t1 = hires_clock::now();
// Allocate and initialize one extra input array - not used by any workload.
// This makes sure none of the actual working inputs stays in L3 cache (which
// is fairly sizable), giving one of the workloads an unfair advantage. The
// lower cache layers are so small compared to the input size that their
// pre-seeding advantage is negligible.
std::vector<std::vector<float>> inputs(num_workloads + 1);
for (int i = 0; i < num_workloads; ++i) {
inputs[i] = make_input_array(INPUT_SIZE);
}
std::cout << "Created " << num_workloads + 1 << " input arrays"
<< "; elapsed: " << duration_ms(hires_clock::now() - t1).count()
<< " ms\n";
for (int i = 1; i < argc; i += 2) {
WorkloadFunc func;
std::string workload_name = argv[i];
if (workload_name == "fpchurn") {
func = workload_fpchurn;
} else if (workload_name == "sin") {
func = workload_sin;
} else if (workload_name == "accum") {
func = workload_accum;
} else if (workload_name == "unrollaccum4") {
func = workload_unrollaccum4;
} else if (workload_name == "unrollaccum8") {
func = workload_unrollaccum8;
} else if (workload_name == "stdaccum") {
func = workload_stdaccum;
} else {
std::cerr << "unknown workload: " << argv[i] << "\n";
return 1;
}
int cpu_num;
if (i + 1 >= argc) {
cpu_num = 0;
} else {
cpu_num = std::atoi(argv[i + 1]);
}
{
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << "Spawning workload '" << workload_name << "' on CPU "
<< cpu_num << "\n";
}
int nworkload = i / 2;
threads[nworkload] = std::thread(func, std::cref(inputs[nworkload]),
std::ref(results[nworkload]));
pin_thread_to_cpu(threads[nworkload], cpu_num);
}
// All the threads were launched in parallel in the loop above. Now wait for
// all of them to finish.
for (auto& t : threads) {
t.join();
}
return 0;
}
<commit_msg>Fix compile error in thread-workload-benchmark.cpp<commit_after>// Comprehensive benchmark demonstrating sharing of cores for different
// workloads.
//
// When built, accepts an arbitrary number of argument pairs: (workload, cpu)
// and launches the given workloads in separate threads on the given CPUs.
//
// For example:
//
// ./thread-workload-benchmark accum 0 sin 1
//
// Launches the "accum" workload in on (logical) CPU 0, and the "sin" workload
// in parallel on CPU 1. Each workload is given its own (separately allocated)
// vector of 100 million floats.
//
// Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <functional>
#include <iostream>
#include <mutex>
#include <pthread.h>
#include <random>
#include <thread>
#include <vector>
// "Workload function" type. Takes a vector of float data and a reference to
// a single float result.
using WorkloadFunc = std::function<void(const std::vector<float>&, float&)>;
// Some aliases to make std::chrono calls shorter.
using hires_clock = std::chrono::high_resolution_clock;
using duration_ms = std::chrono::duration<double, std::milli>;
std::mutex iomutex;
void workload_fpchurn(const std::vector<float>& data, float& result) {
constexpr size_t NUM_ITERS = 10 * 1000 * 1000;
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < NUM_ITERS; ++i) {
float item = data[i];
float l = std::log(item);
if (l > rt) {
l = std::sin(l);
} else {
l = std::cos(l);
}
if (l > rt - 2.0) {
l = std::exp(l);
} else {
l = std::exp(l + 1.0);
}
rt += l;
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [CPU " << sched_getcpu() << "]:\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
}
}
void workload_sin(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < data.size(); ++i) {
rt += std::sin(data[i]);
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_accum(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
float rt = 0;
for (size_t i = 0; i < data.size(); ++i) {
// On x86-64, this should generate a loop of data.size ADDSS instructions,
// all adding up into the same xmm register. If built with -Ofast
// (-ffast-math), the compiler will be willing to perform unsafe FP
// optimizations and will vectorize the loop into data.size/4 ADDPS
// instructions. Note that this changes the order in which the floats are
// added, which is unsafe because FP addition is not associative.
rt += data[i];
}
result = rt;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_unrollaccum4(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
if (data.size() % 4 != 0) {
std::cerr
<< "ERROR in " << __func__ << ": data.size " << data.size() << "\n";
}
float rt0 = 0;
float rt1 = 0;
float rt2 = 0;
float rt3 = 0;
for (size_t i = 0; i < data.size(); i += 4) {
// This unrolling performs manual break-down of dependencies on a single xmm
// register that happens in workload_accum. It should be faster because
// distinct ADDSS instructions will accumulate into separate registers. It
// is also unsafe for the same reasons as described above.
rt0 += data[i];
rt1 += data[i + 1];
rt2 += data[i + 2];
rt3 += data[i + 3];
}
result = rt0 + rt1 + rt2 + rt3;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_unrollaccum8(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
if (data.size() % 8 != 0) {
std::cerr
<< "ERROR in " << __func__ << ": data.size " << data.size() << "\n";
}
float rt0 = 0;
float rt1 = 0;
float rt2 = 0;
float rt3 = 0;
float rt4 = 0;
float rt5 = 0;
float rt6 = 0;
float rt7 = 0;
for (size_t i = 0; i < data.size(); i += 8) {
rt0 += data[i];
rt1 += data[i + 1];
rt2 += data[i + 2];
rt3 += data[i + 3];
rt4 += data[i + 4];
rt5 += data[i + 5];
rt6 += data[i + 6];
rt7 += data[i + 7];
}
result = rt0 + rt1 + rt2 + rt3 + rt4 + rt5 + rt6 + rt7;
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
void workload_stdaccum(const std::vector<float>& data, float& result) {
auto t1 = hires_clock::now();
result = std::accumulate(data.begin(), data.end(), 0.0f);
{
auto t2 = hires_clock::now();
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << __func__ << " [cpu " << sched_getcpu() << "]:\n";
std::cout << " processed items: " << data.size() << "\n";
std::cout << " elapsed: " << duration_ms(t2 - t1).count() << " ms\n";
std::cout << " result: " << result << "\n";
}
}
// Create a vector filled with N floats uniformly distributed in the range
// (-1.0,1.0)
std::vector<float> make_input_array(int N) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
std::vector<float> vf(N);
for (size_t i = 0; i < vf.size(); ++i) {
vf[i] = dis(gen);
}
return vf;
}
// This function can be used to mark memory that shouldn't be optimized away,
// without actually generating any code.
void do_not_optimize(void* p) {
asm volatile("" : : "g"(p) : "memory");
}
// Set the given thread's affinity to be exclusively on the given logical CPU
// number.
void pin_thread_to_cpu(std::thread& t, int cpu_num) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu_num, &cpuset);
int rc =
pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
}
}
int main(int argc, const char** argv) {
// Set locale for comma-separation in large numbers.
std::cout.imbue(std::locale(""));
// Command-line invocation:
//
// argv[0] is the program name
// argv[1] is workload name, with cpu number at argv[2]
// argv[3] is workload name, with cpu number at argv[4]
// ... etc.
int num_workloads = argc / 2;
std::vector<float> results(num_workloads);
do_not_optimize(results.data());
std::vector<std::thread> threads(num_workloads);
constexpr size_t INPUT_SIZE = 100 * 1000 * 1000;
auto t1 = hires_clock::now();
// Allocate and initialize one extra input array - not used by any workload.
// This makes sure none of the actual working inputs stays in L3 cache (which
// is fairly sizable), giving one of the workloads an unfair advantage. The
// lower cache layers are so small compared to the input size that their
// pre-seeding advantage is negligible.
std::vector<std::vector<float>> inputs(num_workloads + 1);
for (int i = 0; i < num_workloads; ++i) {
inputs[i] = make_input_array(INPUT_SIZE);
}
std::cout << "Created " << num_workloads + 1 << " input arrays"
<< "; elapsed: " << duration_ms(hires_clock::now() - t1).count()
<< " ms\n";
for (int i = 1; i < argc; i += 2) {
WorkloadFunc func;
std::string workload_name = argv[i];
if (workload_name == "fpchurn") {
func = workload_fpchurn;
} else if (workload_name == "sin") {
func = workload_sin;
} else if (workload_name == "accum") {
func = workload_accum;
} else if (workload_name == "unrollaccum4") {
func = workload_unrollaccum4;
} else if (workload_name == "unrollaccum8") {
func = workload_unrollaccum8;
} else if (workload_name == "stdaccum") {
func = workload_stdaccum;
} else {
std::cerr << "unknown workload: " << argv[i] << "\n";
return 1;
}
int cpu_num;
if (i + 1 >= argc) {
cpu_num = 0;
} else {
cpu_num = std::atoi(argv[i + 1]);
}
{
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << "Spawning workload '" << workload_name << "' on CPU "
<< cpu_num << "\n";
}
int nworkload = i / 2;
threads[nworkload] = std::thread(func, std::cref(inputs[nworkload]),
std::ref(results[nworkload]));
pin_thread_to_cpu(threads[nworkload], cpu_num);
}
// All the threads were launched in parallel in the loop above. Now wait for
// all of them to finish.
for (auto& t : threads) {
t.join();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The Fuchsia 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 "engine.h"
#include <sstream>
#include "flutter/common/task_runners.h"
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/run_configuration.h"
#include "lib/fsl/tasks/message_loop.h"
#include "lib/fxl/functional/make_copyable.h"
#include "lib/fxl/synchronization/waitable_event.h"
#include "platform_view.h"
namespace flutter {
Engine::Engine(Delegate& delegate,
std::string thread_label,
component::ApplicationContext& application_context,
blink::Settings settings,
fidl::InterfaceRequest<views_v1_token::ViewOwner> view_owner,
const UniqueFDIONS& fdio_ns,
fidl::InterfaceRequest<component::ServiceProvider>
outgoing_services_request)
: delegate_(delegate),
thread_label_(std::move(thread_label)),
settings_(std::move(settings)),
weak_factory_(this) {
// Launch the threads that will be used to run the shell. These threads will
// be joined in the destructor.
for (auto& thread : host_threads_) {
thread.Run();
}
views_v1::ViewManagerPtr view_manager;
application_context.ConnectToEnvironmentService(view_manager.NewRequest());
zx::eventpair import_token, export_token;
if (zx::eventpair::create(0u, &import_token, &export_token) != ZX_OK) {
FXL_DLOG(ERROR) << "Could not create event pair.";
return;
}
// Setup the session connection.
ui::ScenicPtr scenic;
view_manager->GetScenic(scenic.NewRequest());
// Grab the parent environent services. The platform view may want to access
// some of these services.
component::ServiceProviderPtr parent_environment_service_provider;
application_context.environment()->GetServices(
parent_environment_service_provider.NewRequest());
// We need to manually schedule a frame when the session metrics change.
OnMetricsUpdate on_session_metrics_change_callback = std::bind(
&Engine::OnSessionMetricsDidChange, this, std::placeholders::_1);
fxl::Closure on_session_error_callback = std::bind(&Engine::Terminate, this);
// Grab the accessibilty context writer that can understand the semtics tree
// on the platform view.
modular::ContextWriterPtr accessibility_context_writer;
application_context.ConnectToEnvironmentService(
accessibility_context_writer.NewRequest());
// Create the compositor context from the scenic pointer to create the
// rasterizer.
std::unique_ptr<flow::CompositorContext> compositor_context =
std::make_unique<flutter::CompositorContext>(
scenic, // scenic
thread_label_, // debug label
std::move(import_token), // import token
on_session_metrics_change_callback, // session metrics did change
on_session_error_callback // session did encounter error
);
// Setup the callback that will instantiate the platform view.
shell::Shell::CreateCallback<shell::PlatformView> on_create_platform_view =
fxl::MakeCopyable([debug_label = thread_label_, //
parent_environment_service_provider =
std::move(parent_environment_service_provider), //
view_manager = std::ref(view_manager), //
view_owner = std::move(view_owner), //
scenic = std::move(scenic), //
accessibility_context_writer =
std::move(accessibility_context_writer), //
export_token = std::move(export_token) //
](shell::Shell& shell) mutable {
return std::make_unique<flutter::PlatformView>(
shell, // delegate
debug_label, // debug label
shell.GetTaskRunners(), // task runners
std::move(parent_environment_service_provider), // services
view_manager, // view manager
std::move(view_owner), // view owner
std::move(scenic), // scenic
std::move(export_token), // export token
std::move(
accessibility_context_writer) // accessibility context writer
);
});
// Setup the callback that will instantiate the rasterizer.
shell::Shell::CreateCallback<shell::Rasterizer> on_create_rasterizer =
fxl::MakeCopyable([compositor_context = std::move(compositor_context)](
shell::Shell& shell) mutable {
return std::make_unique<shell::Rasterizer>(
shell.GetTaskRunners(), // task runners
std::move(compositor_context) // compositor context
);
});
// Get the task runners from the managed threads. The current thread will be
// used as the "platform" thread.
blink::TaskRunners task_runners(
thread_label_, // Dart thread labels
fsl::MessageLoop::GetCurrent()->task_runner(), // platform
host_threads_[0].TaskRunner(), // gpu
host_threads_[1].TaskRunner(), // ui
host_threads_[2].TaskRunner() // io
);
settings_.root_isolate_create_callback =
std::bind(&Engine::OnMainIsolateStart, this);
settings_.root_isolate_shutdown_callback =
std::bind([weak = weak_factory_.GetWeakPtr(),
runner = task_runners.GetPlatformTaskRunner()]() {
runner->PostTask([weak = std::move(weak)] {
if (weak) {
weak->OnMainIsolateShutdown();
}
});
});
shell_ = shell::Shell::Create(
task_runners, // host task runners
settings_, // shell launch settings
on_create_platform_view, // platform view create callback
on_create_rasterizer // rasterizer create callback
);
if (!shell_) {
FXL_LOG(ERROR) << "Could not launch the shell with settings: "
<< settings_.ToString();
return;
}
// Shell has been created. Before we run the engine, setup the isolate
// configurator.
{
PlatformView* platform_view =
static_cast<PlatformView*>(shell_->GetPlatformView().get());
auto& view = platform_view->GetMozartView();
component::ApplicationEnvironmentPtr application_environment;
application_context.ConnectToEnvironmentService(
application_environment.NewRequest());
isolate_configurator_ = std::make_unique<IsolateConfigurator>(
fdio_ns, //
view, //
std::move(application_environment), //
std::move(outgoing_services_request) //
);
}
// This platform does not get a separate surface platform view creation
// notification. Fire one eagerly.
shell_->GetPlatformView()->NotifyCreated();
// Launch the engine in the appropriate configuration.
auto run_configuration =
shell::RunConfiguration::InferFromSettings(settings_);
shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
fxl::MakeCopyable([engine = shell_->GetEngine(), //
run_configuration = std::move(run_configuration) //
]() mutable {
if (!engine || !engine->Run(std::move(run_configuration))) {
FXL_LOG(ERROR) << "Could not (re)launch the engine in configuration";
}
}));
UpdateNativeThreadLabelNames();
}
Engine::~Engine() {
for (const auto& thread : host_threads_) {
thread.TaskRunner()->PostTask(
[]() { fsl::MessageLoop::GetCurrent()->PostQuitTask(); });
}
}
void Engine::UpdateNativeThreadLabelNames() const {
auto set_thread_name = [](fxl::RefPtr<fxl::TaskRunner> runner,
std::string prefix, std::string suffix) {
runner->PostTask([name = prefix + suffix]() {
zx::thread::self().set_property(ZX_PROP_NAME, name.c_str(), name.size());
});
};
auto runners = shell_->GetTaskRunners();
set_thread_name(runners.GetPlatformTaskRunner(), thread_label_, ".platform");
set_thread_name(runners.GetUITaskRunner(), thread_label_, ".ui");
set_thread_name(runners.GetGPUTaskRunner(), thread_label_, ".gpu");
set_thread_name(runners.GetIOTaskRunner(), thread_label_, ".io");
}
std::pair<bool, uint32_t> Engine::GetEngineReturnCode() const {
std::pair<bool, uint32_t> code(false, 0);
if (!shell_) {
return code;
}
fxl::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell_->GetTaskRunners().GetUITaskRunner(),
[&latch, &code, engine = shell_->GetEngine()]() {
if (engine) {
code = engine->GetUIIsolateReturnCode();
}
latch.Signal();
});
latch.Wait();
return code;
}
void Engine::OnMainIsolateStart() {
if (!isolate_configurator_ ||
!isolate_configurator_->ConfigureCurrentIsolate()) {
FXL_LOG(ERROR) << "Could not configure some native embedder bindings for a "
"new root isolate.";
}
}
void Engine::OnMainIsolateShutdown() {
Terminate();
}
void Engine::Terminate() {
delegate_.OnEngineTerminate(this);
// Warning. Do not do anything after this point as the delegate may have
// collected this object.
}
void Engine::OnSessionMetricsDidChange(double device_pixel_ratio) {
if (!shell_) {
return;
}
shell_->GetTaskRunners().GetPlatformTaskRunner()->PostTask(
[platform_view = shell_->GetPlatformView(), device_pixel_ratio]() {
if (platform_view) {
reinterpret_cast<flutter::PlatformView*>(platform_view.get())
->UpdateViewportMetrics(device_pixel_ratio);
}
});
}
} // namespace flutter
<commit_msg>Always enable verbose logging on fuchsia. (#5104)<commit_after>// Copyright 2018 The Fuchsia 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 "engine.h"
#include <sstream>
#include "flutter/common/task_runners.h"
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/run_configuration.h"
#include "lib/fsl/tasks/message_loop.h"
#include "lib/fxl/functional/make_copyable.h"
#include "lib/fxl/synchronization/waitable_event.h"
#include "platform_view.h"
namespace flutter {
Engine::Engine(Delegate& delegate,
std::string thread_label,
component::ApplicationContext& application_context,
blink::Settings settings,
fidl::InterfaceRequest<views_v1_token::ViewOwner> view_owner,
const UniqueFDIONS& fdio_ns,
fidl::InterfaceRequest<component::ServiceProvider>
outgoing_services_request)
: delegate_(delegate),
thread_label_(std::move(thread_label)),
settings_(std::move(settings)),
weak_factory_(this) {
// Launch the threads that will be used to run the shell. These threads will
// be joined in the destructor.
for (auto& thread : host_threads_) {
thread.Run();
}
views_v1::ViewManagerPtr view_manager;
application_context.ConnectToEnvironmentService(view_manager.NewRequest());
zx::eventpair import_token, export_token;
if (zx::eventpair::create(0u, &import_token, &export_token) != ZX_OK) {
FXL_DLOG(ERROR) << "Could not create event pair.";
return;
}
// Setup the session connection.
ui::ScenicPtr scenic;
view_manager->GetScenic(scenic.NewRequest());
// Grab the parent environent services. The platform view may want to access
// some of these services.
component::ServiceProviderPtr parent_environment_service_provider;
application_context.environment()->GetServices(
parent_environment_service_provider.NewRequest());
// We need to manually schedule a frame when the session metrics change.
OnMetricsUpdate on_session_metrics_change_callback = std::bind(
&Engine::OnSessionMetricsDidChange, this, std::placeholders::_1);
fxl::Closure on_session_error_callback = std::bind(&Engine::Terminate, this);
// Grab the accessibilty context writer that can understand the semtics tree
// on the platform view.
modular::ContextWriterPtr accessibility_context_writer;
application_context.ConnectToEnvironmentService(
accessibility_context_writer.NewRequest());
// Create the compositor context from the scenic pointer to create the
// rasterizer.
std::unique_ptr<flow::CompositorContext> compositor_context =
std::make_unique<flutter::CompositorContext>(
scenic, // scenic
thread_label_, // debug label
std::move(import_token), // import token
on_session_metrics_change_callback, // session metrics did change
on_session_error_callback // session did encounter error
);
// Setup the callback that will instantiate the platform view.
shell::Shell::CreateCallback<shell::PlatformView> on_create_platform_view =
fxl::MakeCopyable([debug_label = thread_label_, //
parent_environment_service_provider =
std::move(parent_environment_service_provider), //
view_manager = std::ref(view_manager), //
view_owner = std::move(view_owner), //
scenic = std::move(scenic), //
accessibility_context_writer =
std::move(accessibility_context_writer), //
export_token = std::move(export_token) //
](shell::Shell& shell) mutable {
return std::make_unique<flutter::PlatformView>(
shell, // delegate
debug_label, // debug label
shell.GetTaskRunners(), // task runners
std::move(parent_environment_service_provider), // services
view_manager, // view manager
std::move(view_owner), // view owner
std::move(scenic), // scenic
std::move(export_token), // export token
std::move(
accessibility_context_writer) // accessibility context writer
);
});
// Setup the callback that will instantiate the rasterizer.
shell::Shell::CreateCallback<shell::Rasterizer> on_create_rasterizer =
fxl::MakeCopyable([compositor_context = std::move(compositor_context)](
shell::Shell& shell) mutable {
return std::make_unique<shell::Rasterizer>(
shell.GetTaskRunners(), // task runners
std::move(compositor_context) // compositor context
);
});
// Get the task runners from the managed threads. The current thread will be
// used as the "platform" thread.
blink::TaskRunners task_runners(
thread_label_, // Dart thread labels
fsl::MessageLoop::GetCurrent()->task_runner(), // platform
host_threads_[0].TaskRunner(), // gpu
host_threads_[1].TaskRunner(), // ui
host_threads_[2].TaskRunner() // io
);
settings_.verbose_logging = true;
settings_.root_isolate_create_callback =
std::bind(&Engine::OnMainIsolateStart, this);
settings_.root_isolate_shutdown_callback =
std::bind([weak = weak_factory_.GetWeakPtr(),
runner = task_runners.GetPlatformTaskRunner()]() {
runner->PostTask([weak = std::move(weak)] {
if (weak) {
weak->OnMainIsolateShutdown();
}
});
});
shell_ = shell::Shell::Create(
task_runners, // host task runners
settings_, // shell launch settings
on_create_platform_view, // platform view create callback
on_create_rasterizer // rasterizer create callback
);
if (!shell_) {
FXL_LOG(ERROR) << "Could not launch the shell with settings: "
<< settings_.ToString();
return;
}
// Shell has been created. Before we run the engine, setup the isolate
// configurator.
{
PlatformView* platform_view =
static_cast<PlatformView*>(shell_->GetPlatformView().get());
auto& view = platform_view->GetMozartView();
component::ApplicationEnvironmentPtr application_environment;
application_context.ConnectToEnvironmentService(
application_environment.NewRequest());
isolate_configurator_ = std::make_unique<IsolateConfigurator>(
fdio_ns, //
view, //
std::move(application_environment), //
std::move(outgoing_services_request) //
);
}
// This platform does not get a separate surface platform view creation
// notification. Fire one eagerly.
shell_->GetPlatformView()->NotifyCreated();
// Launch the engine in the appropriate configuration.
auto run_configuration =
shell::RunConfiguration::InferFromSettings(settings_);
shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
fxl::MakeCopyable([engine = shell_->GetEngine(), //
run_configuration = std::move(run_configuration) //
]() mutable {
if (!engine || !engine->Run(std::move(run_configuration))) {
FXL_LOG(ERROR) << "Could not (re)launch the engine in configuration";
}
}));
UpdateNativeThreadLabelNames();
}
Engine::~Engine() {
for (const auto& thread : host_threads_) {
thread.TaskRunner()->PostTask(
[]() { fsl::MessageLoop::GetCurrent()->PostQuitTask(); });
}
}
void Engine::UpdateNativeThreadLabelNames() const {
auto set_thread_name = [](fxl::RefPtr<fxl::TaskRunner> runner,
std::string prefix, std::string suffix) {
runner->PostTask([name = prefix + suffix]() {
zx::thread::self().set_property(ZX_PROP_NAME, name.c_str(), name.size());
});
};
auto runners = shell_->GetTaskRunners();
set_thread_name(runners.GetPlatformTaskRunner(), thread_label_, ".platform");
set_thread_name(runners.GetUITaskRunner(), thread_label_, ".ui");
set_thread_name(runners.GetGPUTaskRunner(), thread_label_, ".gpu");
set_thread_name(runners.GetIOTaskRunner(), thread_label_, ".io");
}
std::pair<bool, uint32_t> Engine::GetEngineReturnCode() const {
std::pair<bool, uint32_t> code(false, 0);
if (!shell_) {
return code;
}
fxl::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell_->GetTaskRunners().GetUITaskRunner(),
[&latch, &code, engine = shell_->GetEngine()]() {
if (engine) {
code = engine->GetUIIsolateReturnCode();
}
latch.Signal();
});
latch.Wait();
return code;
}
void Engine::OnMainIsolateStart() {
if (!isolate_configurator_ ||
!isolate_configurator_->ConfigureCurrentIsolate()) {
FXL_LOG(ERROR) << "Could not configure some native embedder bindings for a "
"new root isolate.";
}
}
void Engine::OnMainIsolateShutdown() {
Terminate();
}
void Engine::Terminate() {
delegate_.OnEngineTerminate(this);
// Warning. Do not do anything after this point as the delegate may have
// collected this object.
}
void Engine::OnSessionMetricsDidChange(double device_pixel_ratio) {
if (!shell_) {
return;
}
shell_->GetTaskRunners().GetPlatformTaskRunner()->PostTask(
[platform_view = shell_->GetPlatformView(), device_pixel_ratio]() {
if (platform_view) {
reinterpret_cast<flutter::PlatformView*>(platform_view.get())
->UpdateViewportMetrics(device_pixel_ratio);
}
});
}
} // namespace flutter
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Christian Menard
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#include <iomanip>
#include <sstream>
#include "debug/Dtu.hh"
#include "debug/DtuBuf.hh"
#include "debug/DtuCmd.hh"
#include "debug/DtuPackets.hh"
#include "debug/DtuSysCalls.hh"
#include "debug/DtuPower.hh"
#include "cpu/simple/base.hh"
#include "mem/dtu/dtu.hh"
#include "mem/dtu/msg_unit.hh"
#include "mem/dtu/mem_unit.hh"
#include "mem/dtu/xfer_unit.hh"
#include "mem/page_table.hh"
#include "sim/system.hh"
#include "sim/process.hh"
static const char *cmdNames[] =
{
"IDLE",
"SEND",
"REPLY",
"READ",
"WRITE",
"INC_READ_PTR",
"WAKEUP_CORE",
};
Dtu::Dtu(DtuParams* p)
: BaseDtu(p),
masterId(p->system->getMasterId(name())),
system(p->system),
regFile(name() + ".regFile", p->num_endpoints),
msgUnit(new MessageUnit(*this)),
memUnit(new MemoryUnit(*this)),
xferUnit(new XferUnit(*this, p->block_size, p->buf_count, p->buf_size)),
executeCommandEvent(*this),
finishCommandEvent(*this),
cmdInProgress(false),
memEp(p->memory_ep),
atomicMode(p->system->isAtomicMode()),
numEndpoints(p->num_endpoints),
maxNocPacketSize(p->max_noc_packet_size),
numCmdEpidBits(p->num_cmd_epid_bits),
blockSize(p->block_size),
bufCount(p->buf_count),
bufSize(p->buf_size),
registerAccessLatency(p->register_access_latency),
commandToNocRequestLatency(p->command_to_noc_request_latency),
startMsgTransferDelay(p->start_msg_transfer_delay),
transferToMemRequestLatency(p->transfer_to_mem_request_latency),
transferToNocLatency(p->transfer_to_noc_latency),
nocToTransferLatency(p->noc_to_transfer_latency)
{
assert(p->buf_size >= maxNocPacketSize);
regFile.set(memEp, EpReg::TGT_COREID, p->memory_pe);
regFile.set(memEp, EpReg::REQ_REM_ADDR, p->memory_offset);
regFile.set(memEp, EpReg::REQ_REM_SIZE, p->memory_size);
regFile.set(memEp, EpReg::REQ_FLAGS, READ | WRITE);
}
Dtu::~Dtu()
{
delete xferUnit;
delete memUnit;
delete msgUnit;
}
PacketPtr
Dtu::generateRequest(Addr paddr, Addr size, MemCmd cmd)
{
Request::Flags flags;
auto req = new Request(paddr, size, flags, masterId);
auto pkt = new Packet(req, cmd);
auto pktData = new uint8_t[size];
pkt->dataDynamic(pktData);
return pkt;
}
void
Dtu::freeRequest(PacketPtr pkt)
{
delete pkt->req;
delete pkt;
}
Dtu::Command
Dtu::getCommand()
{
assert(numCmdEpidBits + numCmdOpcodeBits <= sizeof(RegFile::reg_t) * 8);
using reg_t = RegFile::reg_t;
/*
* COMMAND 0
* |--------------------|
* | epid | opcode |
* |--------------------|
*/
reg_t opcodeMask = ((reg_t)1 << numCmdOpcodeBits) - 1;
reg_t epidMask = (((reg_t)1 << numCmdEpidBits) - 1) << numCmdOpcodeBits;
auto reg = regFile.get(CmdReg::COMMAND);
Command cmd;
cmd.opcode = static_cast<CommandOpcode>(reg & opcodeMask);
cmd.epId = (reg & epidMask) >> numCmdOpcodeBits;
return cmd;
}
void
Dtu::executeCommand()
{
Command cmd = getCommand();
if(cmd.opcode == CommandOpcode::IDLE)
return;
assert(!cmdInProgress);
assert(cmd.epId < numEndpoints);
cmdInProgress = true;
DPRINTF(DtuCmd, "Starting command %s with EP%d\n",
cmdNames[static_cast<size_t>(cmd.opcode)], cmd.epId);
switch (cmd.opcode)
{
case CommandOpcode::SEND:
case CommandOpcode::REPLY:
msgUnit->startTransmission(cmd);
break;
case CommandOpcode::READ:
memUnit->startRead(cmd);
break;
case CommandOpcode::WRITE:
memUnit->startWrite(cmd);
break;
case CommandOpcode::INC_READ_PTR:
msgUnit->incrementReadPtr(cmd.epId);
finishCommand();
break;
case CommandOpcode::WAKEUP_CORE:
wakeupCore();
finishCommand();
break;
default:
// TODO error handling
panic("Invalid opcode %#x\n", static_cast<RegFile::reg_t>(cmd.opcode));
}
}
void
Dtu::finishCommand()
{
Command cmd = getCommand();
assert(cmdInProgress);
DPRINTF(DtuCmd, "Finished command %s with EP%d\n",
cmdNames[static_cast<size_t>(cmd.opcode)], cmd.epId);
// let the SW know that the command is finished
regFile.set(CmdReg::COMMAND, 0);
cmdInProgress = false;
}
void
Dtu::wakeupCore()
{
if(system->threadContexts.size() == 0)
return;
if(system->threadContexts[0]->status() == ThreadContext::Suspended)
{
DPRINTF(DtuPower, "Waking up core\n");
system->threadContexts[0]->activate();
}
}
void
Dtu::updateSuspendablePin()
{
if(system->threadContexts.size() == 0)
return;
bool pendingMsgs = regFile.get(DtuReg::MSG_CNT) > 0;
bool hadPending = system->threadContexts[0]->getCpuPtr()->_denySuspend;
system->threadContexts[0]->getCpuPtr()->_denySuspend = pendingMsgs;
if(hadPending && !pendingMsgs)
DPRINTF(DtuPower, "Core can be suspended\n");
}
void
Dtu::sendMemRequest(PacketPtr pkt,
unsigned epId,
MemReqType type,
Cycles delay)
{
pkt->setAddr(pkt->getAddr());
auto senderState = new MemSenderState();
senderState->epId = epId;
senderState->mid = pkt->req->masterId();
senderState->type = type;
// ensure that this packet has our master id (not the id of a master in a different PE)
pkt->req->setMasterId(masterId);
pkt->pushSenderState(senderState);
if (atomicMode)
{
sendAtomicMemRequest(pkt);
completeMemRequest(pkt);
}
else
{
schedMemRequest(pkt, clockEdge(delay));
}
}
void
Dtu::sendNocRequest(NocPacketType type, PacketPtr pkt, Cycles delay, bool functional)
{
auto senderState = new NocSenderState();
senderState->packetType = type;
pkt->pushSenderState(senderState);
if (functional)
{
sendFunctionalNocRequest(pkt);
completeNocRequest(pkt);
}
else if (atomicMode)
{
sendAtomicNocRequest(pkt);
completeNocRequest(pkt);
}
else
{
schedNocRequest(pkt, clockEdge(delay));
}
}
void
Dtu::startTransfer(TransferType type,
NocAddr targetAddr,
Addr sourceAddr,
Addr size,
PacketPtr pkt,
MessageHeader* header,
Cycles delay,
bool last)
{
xferUnit->startTransfer(type,
targetAddr,
sourceAddr,
size,
pkt,
header,
delay,
last);
}
void
Dtu::completeNocRequest(PacketPtr pkt)
{
auto senderState = dynamic_cast<NocSenderState*>(pkt->popSenderState());
if(senderState->packetType == NocPacketType::CACHE_MEM_REQ)
{
Addr targetAddr = regs().get(numEndpoints - 1, EpReg::REQ_REM_ADDR);
Addr reqAddr = NocAddr(pkt->getAddr()).offset - targetAddr;
pkt->setAddr(reqAddr);
pkt->req->setPaddr(reqAddr);
sendCacheMemResponse(pkt);
}
else if(senderState->packetType != NocPacketType::CACHE_MEM_REQ_FUNC)
{
if (pkt->isWrite())
memUnit->writeComplete(pkt);
else if (pkt->isRead())
memUnit->readComplete(pkt);
else
panic("unexpected packet type\n");
}
delete senderState;
}
void
Dtu::completeMemRequest(PacketPtr pkt)
{
assert(!pkt->isError());
assert(pkt->isResponse());
auto senderState = dynamic_cast<MemSenderState*>(pkt->popSenderState());
// set the old master id again
pkt->req->setMasterId(senderState->mid);
switch(senderState->type)
{
case MemReqType::TRANSFER:
xferUnit->recvMemResponse(senderState->epId,
pkt->getConstPtr<uint8_t>(),
pkt->getSize(),
pkt->headerDelay,
pkt->payloadDelay);
break;
case MemReqType::HEADER:
msgUnit->recvFromMem(getCommand(), pkt);
break;
}
delete senderState;
freeRequest(pkt);
}
void
Dtu::handleNocRequest(PacketPtr pkt)
{
assert(!pkt->isError());
auto senderState = dynamic_cast<NocSenderState*>(pkt->senderState);
switch (senderState->packetType)
{
case NocPacketType::MESSAGE:
msgUnit->recvFromNoc(pkt);
break;
case NocPacketType::READ_REQ:
case NocPacketType::WRITE_REQ:
case NocPacketType::CACHE_MEM_REQ:
memUnit->recvFromNoc(pkt);
break;
case NocPacketType::CACHE_MEM_REQ_FUNC:
memUnit->recvFunctionalFromNoc(pkt);
break;
default:
panic("Unexpected NocPacketType\n");
}
}
void
Dtu::handleCpuRequest(PacketPtr pkt)
{
forwardRequestToRegFile(pkt, true);
}
bool
Dtu::handleCacheMemRequest(PacketPtr pkt, bool functional)
{
if(pkt->cmd == MemCmd::CleanEvict)
{
assert(!pkt->needsResponse());
DPRINTF(DtuPackets, "Dropping CleanEvict packet\n");
return true;
}
unsigned targetCoreId = regs().get(memEp, EpReg::TGT_COREID);
Addr targetAddr = regs().get(memEp, EpReg::REQ_REM_ADDR);
Addr remoteSize = regs().get(memEp, EpReg::REQ_REM_SIZE);
unsigned flags = regs().get(memEp, EpReg::REQ_FLAGS);
if((pkt->isWrite() && !(flags & WRITE)) ||
((pkt->isRead() && !(flags & READ))))
{
DPRINTF(Dtu, "Denying %s request @ %p:%lu because of insufficient permissions\n",
pkt->isRead() ? "read" : "write",
pkt->getAddr(), pkt->getSize());
return false;
}
if((pkt->getAddr() + pkt->getSize() <= pkt->getAddr()) ||
(pkt->getAddr() + pkt->getSize() > remoteSize))
{
DPRINTF(Dtu, "Denying %s request @ %p:%lu because it's out of bounds (%p..%p)\n",
pkt->isRead() ? "read" : "write",
pkt->getAddr(), pkt->getSize(),
0, remoteSize);
return false;
}
pkt->setAddr(NocAddr(targetCoreId, 0, targetAddr + pkt->getAddr()).getAddr());
auto type = functional ? Dtu::NocPacketType::CACHE_MEM_REQ_FUNC : Dtu::NocPacketType::CACHE_MEM_REQ;
sendNocRequest(type, pkt, Cycles(1), functional);
return true;
}
void
Dtu::forwardRequestToRegFile(PacketPtr pkt, bool isCpuRequest)
{
Addr oldAddr = pkt->getAddr();
// Strip the base address to handle requests based on the register address only.
pkt->setAddr(oldAddr - regFileBaseAddr);
bool commandWritten = regFile.handleRequest(pkt, isCpuRequest);
// restore old address
pkt->setAddr(oldAddr);
updateSuspendablePin();
if (!atomicMode)
{
/*
* We handle the request immediatly and do not care about timing. The
* delay is payed by scheduling the response at some point in the
* future. Additionaly a write operation on the command register needs
* to schedule an event that executes this command at a future tick.
*/
Cycles transportDelay =
ticksToCycles(pkt->headerDelay + pkt->payloadDelay);
Tick when = clockEdge(transportDelay + registerAccessLatency);
pkt->headerDelay = 0;
pkt->payloadDelay = 0;
if (isCpuRequest)
schedCpuResponse(pkt, when);
else
{
schedNocRequestFinished(clockEdge(Cycles(1)));
schedNocResponse(pkt, when);
}
if (commandWritten)
schedule(executeCommandEvent, when);
}
else if (commandWritten)
{
executeCommand();
}
}
Dtu*
DtuParams::create()
{
return new Dtu(this);
}
void
Dtu::printPacket(PacketPtr pkt) const
{
DDUMP(DtuPackets, pkt->getPtr<uint8_t>(), pkt->getSize());
}
<commit_msg>DTU: ignore invalidate requests from cache.<commit_after>/*
* Copyright (c) 2015, Christian Menard
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#include <iomanip>
#include <sstream>
#include "debug/Dtu.hh"
#include "debug/DtuBuf.hh"
#include "debug/DtuCmd.hh"
#include "debug/DtuPackets.hh"
#include "debug/DtuSysCalls.hh"
#include "debug/DtuPower.hh"
#include "cpu/simple/base.hh"
#include "mem/dtu/dtu.hh"
#include "mem/dtu/msg_unit.hh"
#include "mem/dtu/mem_unit.hh"
#include "mem/dtu/xfer_unit.hh"
#include "mem/page_table.hh"
#include "sim/system.hh"
#include "sim/process.hh"
static const char *cmdNames[] =
{
"IDLE",
"SEND",
"REPLY",
"READ",
"WRITE",
"INC_READ_PTR",
"WAKEUP_CORE",
};
Dtu::Dtu(DtuParams* p)
: BaseDtu(p),
masterId(p->system->getMasterId(name())),
system(p->system),
regFile(name() + ".regFile", p->num_endpoints),
msgUnit(new MessageUnit(*this)),
memUnit(new MemoryUnit(*this)),
xferUnit(new XferUnit(*this, p->block_size, p->buf_count, p->buf_size)),
executeCommandEvent(*this),
finishCommandEvent(*this),
cmdInProgress(false),
memEp(p->memory_ep),
atomicMode(p->system->isAtomicMode()),
numEndpoints(p->num_endpoints),
maxNocPacketSize(p->max_noc_packet_size),
numCmdEpidBits(p->num_cmd_epid_bits),
blockSize(p->block_size),
bufCount(p->buf_count),
bufSize(p->buf_size),
registerAccessLatency(p->register_access_latency),
commandToNocRequestLatency(p->command_to_noc_request_latency),
startMsgTransferDelay(p->start_msg_transfer_delay),
transferToMemRequestLatency(p->transfer_to_mem_request_latency),
transferToNocLatency(p->transfer_to_noc_latency),
nocToTransferLatency(p->noc_to_transfer_latency)
{
assert(p->buf_size >= maxNocPacketSize);
regFile.set(memEp, EpReg::TGT_COREID, p->memory_pe);
regFile.set(memEp, EpReg::REQ_REM_ADDR, p->memory_offset);
regFile.set(memEp, EpReg::REQ_REM_SIZE, p->memory_size);
regFile.set(memEp, EpReg::REQ_FLAGS, READ | WRITE);
}
Dtu::~Dtu()
{
delete xferUnit;
delete memUnit;
delete msgUnit;
}
PacketPtr
Dtu::generateRequest(Addr paddr, Addr size, MemCmd cmd)
{
Request::Flags flags;
auto req = new Request(paddr, size, flags, masterId);
auto pkt = new Packet(req, cmd);
auto pktData = new uint8_t[size];
pkt->dataDynamic(pktData);
return pkt;
}
void
Dtu::freeRequest(PacketPtr pkt)
{
delete pkt->req;
delete pkt;
}
Dtu::Command
Dtu::getCommand()
{
assert(numCmdEpidBits + numCmdOpcodeBits <= sizeof(RegFile::reg_t) * 8);
using reg_t = RegFile::reg_t;
/*
* COMMAND 0
* |--------------------|
* | epid | opcode |
* |--------------------|
*/
reg_t opcodeMask = ((reg_t)1 << numCmdOpcodeBits) - 1;
reg_t epidMask = (((reg_t)1 << numCmdEpidBits) - 1) << numCmdOpcodeBits;
auto reg = regFile.get(CmdReg::COMMAND);
Command cmd;
cmd.opcode = static_cast<CommandOpcode>(reg & opcodeMask);
cmd.epId = (reg & epidMask) >> numCmdOpcodeBits;
return cmd;
}
void
Dtu::executeCommand()
{
Command cmd = getCommand();
if(cmd.opcode == CommandOpcode::IDLE)
return;
assert(!cmdInProgress);
assert(cmd.epId < numEndpoints);
cmdInProgress = true;
DPRINTF(DtuCmd, "Starting command %s with EP%d\n",
cmdNames[static_cast<size_t>(cmd.opcode)], cmd.epId);
switch (cmd.opcode)
{
case CommandOpcode::SEND:
case CommandOpcode::REPLY:
msgUnit->startTransmission(cmd);
break;
case CommandOpcode::READ:
memUnit->startRead(cmd);
break;
case CommandOpcode::WRITE:
memUnit->startWrite(cmd);
break;
case CommandOpcode::INC_READ_PTR:
msgUnit->incrementReadPtr(cmd.epId);
finishCommand();
break;
case CommandOpcode::WAKEUP_CORE:
wakeupCore();
finishCommand();
break;
default:
// TODO error handling
panic("Invalid opcode %#x\n", static_cast<RegFile::reg_t>(cmd.opcode));
}
}
void
Dtu::finishCommand()
{
Command cmd = getCommand();
assert(cmdInProgress);
DPRINTF(DtuCmd, "Finished command %s with EP%d\n",
cmdNames[static_cast<size_t>(cmd.opcode)], cmd.epId);
// let the SW know that the command is finished
regFile.set(CmdReg::COMMAND, 0);
cmdInProgress = false;
}
void
Dtu::wakeupCore()
{
if(system->threadContexts.size() == 0)
return;
if(system->threadContexts[0]->status() == ThreadContext::Suspended)
{
DPRINTF(DtuPower, "Waking up core\n");
system->threadContexts[0]->activate();
}
}
void
Dtu::updateSuspendablePin()
{
if(system->threadContexts.size() == 0)
return;
bool pendingMsgs = regFile.get(DtuReg::MSG_CNT) > 0;
bool hadPending = system->threadContexts[0]->getCpuPtr()->_denySuspend;
system->threadContexts[0]->getCpuPtr()->_denySuspend = pendingMsgs;
if(hadPending && !pendingMsgs)
DPRINTF(DtuPower, "Core can be suspended\n");
}
void
Dtu::sendMemRequest(PacketPtr pkt,
unsigned epId,
MemReqType type,
Cycles delay)
{
pkt->setAddr(pkt->getAddr());
auto senderState = new MemSenderState();
senderState->epId = epId;
senderState->mid = pkt->req->masterId();
senderState->type = type;
// ensure that this packet has our master id (not the id of a master in a different PE)
pkt->req->setMasterId(masterId);
pkt->pushSenderState(senderState);
if (atomicMode)
{
sendAtomicMemRequest(pkt);
completeMemRequest(pkt);
}
else
{
schedMemRequest(pkt, clockEdge(delay));
}
}
void
Dtu::sendNocRequest(NocPacketType type, PacketPtr pkt, Cycles delay, bool functional)
{
auto senderState = new NocSenderState();
senderState->packetType = type;
pkt->pushSenderState(senderState);
if (functional)
{
sendFunctionalNocRequest(pkt);
completeNocRequest(pkt);
}
else if (atomicMode)
{
sendAtomicNocRequest(pkt);
completeNocRequest(pkt);
}
else
{
schedNocRequest(pkt, clockEdge(delay));
}
}
void
Dtu::startTransfer(TransferType type,
NocAddr targetAddr,
Addr sourceAddr,
Addr size,
PacketPtr pkt,
MessageHeader* header,
Cycles delay,
bool last)
{
xferUnit->startTransfer(type,
targetAddr,
sourceAddr,
size,
pkt,
header,
delay,
last);
}
void
Dtu::completeNocRequest(PacketPtr pkt)
{
auto senderState = dynamic_cast<NocSenderState*>(pkt->popSenderState());
if(senderState->packetType == NocPacketType::CACHE_MEM_REQ)
{
Addr targetAddr = regs().get(numEndpoints - 1, EpReg::REQ_REM_ADDR);
Addr reqAddr = NocAddr(pkt->getAddr()).offset - targetAddr;
pkt->setAddr(reqAddr);
pkt->req->setPaddr(reqAddr);
sendCacheMemResponse(pkt);
}
else if(senderState->packetType != NocPacketType::CACHE_MEM_REQ_FUNC)
{
if (pkt->isWrite())
memUnit->writeComplete(pkt);
else if (pkt->isRead())
memUnit->readComplete(pkt);
else
panic("unexpected packet type\n");
}
delete senderState;
}
void
Dtu::completeMemRequest(PacketPtr pkt)
{
assert(!pkt->isError());
assert(pkt->isResponse());
auto senderState = dynamic_cast<MemSenderState*>(pkt->popSenderState());
// set the old master id again
pkt->req->setMasterId(senderState->mid);
switch(senderState->type)
{
case MemReqType::TRANSFER:
xferUnit->recvMemResponse(senderState->epId,
pkt->getConstPtr<uint8_t>(),
pkt->getSize(),
pkt->headerDelay,
pkt->payloadDelay);
break;
case MemReqType::HEADER:
msgUnit->recvFromMem(getCommand(), pkt);
break;
}
delete senderState;
freeRequest(pkt);
}
void
Dtu::handleNocRequest(PacketPtr pkt)
{
assert(!pkt->isError());
auto senderState = dynamic_cast<NocSenderState*>(pkt->senderState);
switch (senderState->packetType)
{
case NocPacketType::MESSAGE:
msgUnit->recvFromNoc(pkt);
break;
case NocPacketType::READ_REQ:
case NocPacketType::WRITE_REQ:
case NocPacketType::CACHE_MEM_REQ:
memUnit->recvFromNoc(pkt);
break;
case NocPacketType::CACHE_MEM_REQ_FUNC:
memUnit->recvFunctionalFromNoc(pkt);
break;
default:
panic("Unexpected NocPacketType\n");
}
}
void
Dtu::handleCpuRequest(PacketPtr pkt)
{
forwardRequestToRegFile(pkt, true);
}
bool
Dtu::handleCacheMemRequest(PacketPtr pkt, bool functional)
{
if(pkt->cmd == MemCmd::CleanEvict)
{
assert(!pkt->needsResponse());
DPRINTF(DtuPackets, "Dropping CleanEvict packet\n");
return true;
}
// we don't have cache coherence. so we don't care about invalidate requests
if(pkt->cmd == MemCmd::InvalidateReq)
return false;
unsigned targetCoreId = regs().get(memEp, EpReg::TGT_COREID);
Addr targetAddr = regs().get(memEp, EpReg::REQ_REM_ADDR);
Addr remoteSize = regs().get(memEp, EpReg::REQ_REM_SIZE);
unsigned flags = regs().get(memEp, EpReg::REQ_FLAGS);
if((pkt->isWrite() && !(flags & WRITE)) ||
((pkt->isRead() && !(flags & READ))))
{
DPRINTF(Dtu, "Denying %s request @ %p:%lu because of insufficient permissions\n",
pkt->isRead() ? "read" : "write",
pkt->getAddr(), pkt->getSize());
return false;
}
if((pkt->getAddr() + pkt->getSize() <= pkt->getAddr()) ||
(pkt->getAddr() + pkt->getSize() > remoteSize))
{
DPRINTF(Dtu, "Denying %s request @ %p:%lu because it's out of bounds (%p..%p)\n",
pkt->isRead() ? "read" : "write",
pkt->getAddr(), pkt->getSize(),
0, remoteSize);
return false;
}
pkt->setAddr(NocAddr(targetCoreId, 0, targetAddr + pkt->getAddr()).getAddr());
auto type = functional ? Dtu::NocPacketType::CACHE_MEM_REQ_FUNC : Dtu::NocPacketType::CACHE_MEM_REQ;
sendNocRequest(type, pkt, Cycles(1), functional);
return true;
}
void
Dtu::forwardRequestToRegFile(PacketPtr pkt, bool isCpuRequest)
{
Addr oldAddr = pkt->getAddr();
// Strip the base address to handle requests based on the register address only.
pkt->setAddr(oldAddr - regFileBaseAddr);
bool commandWritten = regFile.handleRequest(pkt, isCpuRequest);
// restore old address
pkt->setAddr(oldAddr);
updateSuspendablePin();
if (!atomicMode)
{
/*
* We handle the request immediatly and do not care about timing. The
* delay is payed by scheduling the response at some point in the
* future. Additionaly a write operation on the command register needs
* to schedule an event that executes this command at a future tick.
*/
Cycles transportDelay =
ticksToCycles(pkt->headerDelay + pkt->payloadDelay);
Tick when = clockEdge(transportDelay + registerAccessLatency);
pkt->headerDelay = 0;
pkt->payloadDelay = 0;
if (isCpuRequest)
schedCpuResponse(pkt, when);
else
{
schedNocRequestFinished(clockEdge(Cycles(1)));
schedNocResponse(pkt, when);
}
if (commandWritten)
schedule(executeCommandEvent, when);
}
else if (commandWritten)
{
executeCommand();
}
}
Dtu*
DtuParams::create()
{
return new Dtu(this);
}
void
Dtu::printPacket(PacketPtr pkt) const
{
DDUMP(DtuPackets, pkt->getPtr<uint8_t>(), pkt->getSize());
}
<|endoftext|>
|
<commit_before>#include "messagehub/messagehub.h"
MessageHub::MessageHub(std::string id, std::string hostip, int listenPort) : context(1) , inSock(context, ZMQ_PULL), outSock(context, ZMQ_PUSH) {
identity = id;
inQueue = std::queue<Message>();
outQueue = std::queue<std::pair<std::string, zmq::message_t> >();
still_process = true;
still_send = true;
still_receive = true;
port = listenPort;
hostAddr = hostip;
waitingOnShake = true;
}
MessageHub::~MessageHub() {
still_send = false;
still_process = false;
still_receive = false;
if(msgProcessor->joinable())
msgProcessor->join();
if(sender->joinable())
sender->join();
if(receiver->joinable())
receiver->join();
}
void MessageHub::process(std::string s) {
std::cout << s << "\n";
}
void MessageHub::process(Message &msg) {
if (std::strcmp(msg.getMsg().c_str(), "HANDSHAKE") == 0) {
std::cout << "[INFO] Recevied handshake request\n";
send("SHAKEHAND", msg.returnAddr());
} else if (std::strcmp(msg.getMsg().c_str(), "SHAKEHAND") == 0) {
waitingOnShake = false;
} else {
process(msg.getMsg());
}
}
void MessageHub::run() {
msgProcessor = std::make_unique<std::thread>(std::thread(&MessageHub::_run, this));
std::cout << "MSGPROCESSOR INITIALIZED\n";
receiver = std::make_unique<std::thread>(std::thread(&MessageHub::_run_recevier, this));
std::cout << "RECEIVER INITIALIZED\n";
sender = std::make_unique<std::thread>(std::thread(&MessageHub::_run_sender, this));
std::cout << "SENDER INITIALIZED\n";
}
void MessageHub::_run() {
while (still_process) {
if(!inQueue.empty()) {
std::cout << "READING INBOX\n";
//zmq::message_t zmsg;
//zmsg.copy(&inQueue.front());
//std::string s = std::string(static_cast<char*>(inQueue.front().data()), inQueue.front().size());
Message msg = inQueue.front();
std::cout << "PROCESSING MESSAGE\n";
process(msg);
if (msg.needResponse()) {
std::cout << "SENDING RESPONSE\n";
Message m("YOUR MESSAGE WAS ACKNOWLEDGED");
m.writeHeader(DELIMITERS_V1, "TEST", fullAddr());
outQueue.push(std::make_pair(msg.returnAddr(), m.toZmqMsg()));
std::cout << "Message put in out queue\n";
}
inQueue.pop();
std::cout << "Popped inQueue\n";
}
}
}
void MessageHub::_run_sender() {
zmq::context_t ctx(1);
zmq::socket_t outSock(ctx, ZMQ_PUSH);
while (still_send) {
if (!outQueue.empty()) {
std::cout << "Connecting to " << outQueue.front().first << " ... \n";
outSock.connect("tcp://" + outQueue.front().first);
std::cout << "OK\n";
outSock.send(outQueue.front().second);
outQueue.pop();
outSock.close();
}
}
}
void MessageHub::_run_recevier() {
zmq::context_t ctx(1);
zmq::socket_t inSock(ctx, ZMQ_PULL);
std::cout << "ATTEMPTING TO BIND SOCKET\n";
inSock.bind("tcp://*:" + std::to_string(port));
std::cout << "BINDED INSOCK\n";
while (still_receive) {
std::cout << "0";
sleep(1);
zmq::message_t msg;
inSock.recv(&msg);
Message m(msg);
inQueue.push(m);
}
inSock.close();
}
std::string MessageHub::fullAddr() {
return identity + "::" + hostAddr + ":" + std::to_string(port);
}
void MessageHub::send(std::string m, std::string dst) {
Message msg(m);
msg.writeHeader(DELIMITERS_V1, "TEST2", fullAddr(), true);
std::cout << "Pushing to outQueue: <" + dst + ", " + m + ">\n";
outQueue.push(std::make_pair(dst, msg.toZmqMsg()));
}
bool MessageHub::handshake(std::string ip) {
bool connected = false;
send("HANDSHAKE", ip);
bool timeout = false;
std::thread timer(&MessageHub::_timer, this, 15, &timeout);
timer.detach();
while (waitingOnShake && !timeout) {}
connected = !waitingOnShake;
waitingOnShake = true;
if (timeout) std::cout << "[ERROR] Handshake timed out\n";
return connected;
}
void MessageHub::_timer(int time, bool * flag) {
sleep(time);
*flag = true;
}
void MessageHub::addConnection(const std::string & ipaddr, const int port, const std::string & name) {
std::string s = ipaddr + ":" + std::to_string(port);
addConnection(s, name);
}
void MessageHub::addConnection(const std::string & ipaddr, const std::string & name) {
connections.insert(std::make_pair(ipaddr, std::make_pair(name, true)));
std::cout << "[INFO] Added connection: " + ipaddr + "\n";
}
bool MessageHub::connect(const std::string &ipaddr, const int &port, const std::string &name) {
std::string s = ipaddr + ":" + std::to_string(port);
return connect(s, name);
}
bool MessageHub::connect(const std::string &ipaddr, const std::string &name) {
if (handshake(ipaddr)) {
std::cout << "[INFO] Successfully connected to " + name + "\n";
addConnection(ipaddr, name);
return true;
} else {
std::cout << "[ERROR] Connection timeout for " + name + "\n";
return false;
}
}
<commit_msg>Fix B<commit_after>#include "messagehub/messagehub.h"
MessageHub::MessageHub(std::string id, std::string hostip, int listenPort) : context(1) , inSock(context, ZMQ_PULL), outSock(context, ZMQ_PUSH) {
identity = id;
inQueue = std::queue<Message>();
outQueue = std::queue<std::pair<std::string, zmq::message_t> >();
still_process = true;
still_send = true;
still_receive = true;
port = listenPort;
hostAddr = hostip;
waitingOnShake = true;
}
MessageHub::~MessageHub() {
still_send = false;
still_process = false;
still_receive = false;
if(msgProcessor->joinable())
msgProcessor->join();
if(sender->joinable())
sender->join();
if(receiver->joinable())
receiver->join();
}
void MessageHub::process(std::string s) {
std::cout << s << "\n";
}
void MessageHub::process(Message &msg) {
if (std::strcmp(msg.getMsg().c_str(), "HANDSHAKE") == 0) {
std::cout << "[INFO] Recevied handshake request\n";
send("SHAKEHAND", msg.returnAddr());
} else if (std::strcmp(msg.getMsg().c_str(), "SHAKEHAND") == 0) {
waitingOnShake = false;
} else {
process(msg.getMsg());
}
}
void MessageHub::run() {
msgProcessor = std::make_unique<std::thread>(std::thread(&MessageHub::_run, this));
std::cout << "MSGPROCESSOR INITIALIZED\n";
receiver = std::make_unique<std::thread>(std::thread(&MessageHub::_run_recevier, this));
std::cout << "RECEIVER INITIALIZED\n";
sender = std::make_unique<std::thread>(std::thread(&MessageHub::_run_sender, this));
std::cout << "SENDER INITIALIZED\n";
}
void MessageHub::_run() {
while (still_process) {
if(!inQueue.empty()) {
std::cout << "READING INBOX\n";
//zmq::message_t zmsg;
//zmsg.copy(&inQueue.front());
//std::string s = std::string(static_cast<char*>(inQueue.front().data()), inQueue.front().size());
Message msg = inQueue.front();
std::cout << "PROCESSING MESSAGE\n";
process(msg);
if (msg.needResponse()) {
std::cout << "SENDING RESPONSE\n";
Message m("YOUR MESSAGE WAS ACKNOWLEDGED");
m.writeHeader(DELIMITERS_V1, "TEST", fullAddr());
outQueue.push(std::make_pair(msg.returnAddr(), m.toZmqMsg()));
std::cout << "Message put in out queue\n";
}
inQueue.pop();
std::cout << "Popped inQueue\n";
}
}
}
void MessageHub::_run_sender() {
zmq::context_t ctx(1);
zmq::socket_t outSock(ctx, ZMQ_PUSH);
while (still_send) {
if (!outQueue.empty()) {
std::cout << "Connecting to " << outQueue.front().first << " ... \n";
outSock.connect("tcp://" + outQueue.front().first);
std::cout << "OK\n";
outSock.send(outQueue.front().second);
outQueue.pop();
}
}
}
void MessageHub::_run_recevier() {
zmq::context_t ctx(1);
zmq::socket_t inSock(ctx, ZMQ_PULL);
std::cout << "ATTEMPTING TO BIND SOCKET\n";
inSock.bind("tcp://*:" + std::to_string(port));
std::cout << "BINDED INSOCK\n";
while (still_receive) {
std::cout << "0";
sleep(1);
zmq::message_t msg;
inSock.recv(&msg);
Message m(msg);
inQueue.push(m);
}
inSock.close();
}
std::string MessageHub::fullAddr() {
return identity + "::" + hostAddr + ":" + std::to_string(port);
}
void MessageHub::send(std::string m, std::string dst) {
Message msg(m);
msg.writeHeader(DELIMITERS_V1, "TEST2", fullAddr(), true);
std::cout << "Pushing to outQueue: <" + dst + ", " + m + ">\n";
outQueue.push(std::make_pair(dst, msg.toZmqMsg()));
}
bool MessageHub::handshake(std::string ip) {
bool connected = false;
send("HANDSHAKE", ip);
bool timeout = false;
std::thread timer(&MessageHub::_timer, this, 15, &timeout);
timer.detach();
while (waitingOnShake && !timeout) {}
connected = !waitingOnShake;
waitingOnShake = true;
if (timeout) std::cout << "[ERROR] Handshake timed out\n";
return connected;
}
void MessageHub::_timer(int time, bool * flag) {
sleep(time);
*flag = true;
}
void MessageHub::addConnection(const std::string & ipaddr, const int port, const std::string & name) {
std::string s = ipaddr + ":" + std::to_string(port);
addConnection(s, name);
}
void MessageHub::addConnection(const std::string & ipaddr, const std::string & name) {
connections.insert(std::make_pair(ipaddr, std::make_pair(name, true)));
std::cout << "[INFO] Added connection: " + ipaddr + "\n";
}
bool MessageHub::connect(const std::string &ipaddr, const int &port, const std::string &name) {
std::string s = ipaddr + ":" + std::to_string(port);
return connect(s, name);
}
bool MessageHub::connect(const std::string &ipaddr, const std::string &name) {
if (handshake(ipaddr)) {
std::cout << "[INFO] Successfully connected to " + name + "\n";
addConnection(ipaddr, name);
return true;
} else {
std::cout << "[ERROR] Connection timeout for " + name + "\n";
return false;
}
}
<|endoftext|>
|
<commit_before>//*****************************************************************************
/*!
* 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.
*
*****************************************************************************
*
* \file server.cpp
*
* \brief Superclass of all multithreaded servers.
*
* \version
* - S Panyam 10/02/2009
* Created
*
*****************************************************************************/
#include "net/server.h"
#include "net/connhandler.h"
#include "net/connpool.h"
#include "net/sockbuff.h"
#include <string.h>
#include <event.h>
//*****************************************************************************
/*!
* \brief Called to stop the server.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
int
SServer::RealStop()
{
serverStopped = true;
if (serverSocket >= 0)
{
shutdown(serverSocket, SHUT_RDWR);
close(serverSocket);
serverSocket = -1;
}
// Stop child threads first
SMutexLock mutexLock(handlerListMutex);
for (std::list<SConnHandler *>::iterator iter=connHandlers.begin();
iter != connHandlers.end();
++iter)
{
// stop the client first
if ((*iter)->Running())
{
(*iter)->Stop();
}
// then the client
delete (*iter);
}
// clear client list
connHandlers.clear();
return 0;
}
//*****************************************************************************
/*!
* \brief Creates the server socket.
*
* Here we can allow child classes to do custom socket creations
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::CreateSocket()
{
// Create an internet socket using streaming (tcp/ip)
// and save the handle for the server socket
int newSocket = socket(AF_INET, SOCK_STREAM, 0);
if (newSocket < 0)
{
cerr << "ERROR: Cannot create server socket: [" << errno << "]: " << strerror(errno) << endl << endl;
return -errno;
}
/*
if (setnonblocking(newSocket))
{
cerr << "ERROR: Cannot make socket non blocking: [" << errno << "]: " << strerror(errno) << endl << endl;
return -1;
}
*/
// set it so we can reuse the socket immediately after closing it.
int reuse = 1;
if (setsockopt(newSocket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != 0)
{
cerr << "ERROR: setsockopt failed: [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
int nodelay = 1;
if (setsockopt(newSocket, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
if (setsockopt(newSocket, SOL_SOCKET, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
if (setsockopt(newSocket, SOL_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
return newSocket;
}
//*****************************************************************************
/*!
* \brief Bind the socket to the host and port.
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::BindSocket()
{
// Setup the structure that defines the IP-adress, port and protocol
// family to use.
sockaddr_in srv_sock_addr;
// zero the srv sock addr structure
bzero(&srv_sock_addr, sizeof(srv_sock_addr));
// Use the internet domain.
srv_sock_addr.sin_family = AF_INET;
// Use this specific port.
srv_sock_addr.sin_port = htons(serverPort);
// Use any of the network cards IP addresses.
srv_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind the socket to the port number specified by (serverPort).
int retval = bind(serverSocket, (sockaddr*)(&srv_sock_addr), sizeof(sockaddr));
if (retval != 0)
{
cerr << "ERROR: Cannot bind to server on port: [" << errno << "]: "
<< strerror(errno) << endl;
cerr << "ERROR: --------------------------------------------------" << endl;
return errno;
}
return 0;
}
//*****************************************************************************
/*!
* \brief Starts listening on the socket for connections.
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::ListenOnSocket()
{
// Setup a limit of maximum 10 pending connections.
int retval = listen(serverSocket, 10);
if (retval != 0)
{
cerr << "ERROR: Cannot listen to connections: [" << errno << "]: "
<< strerror(errno) << endl;
return errno;
}
return 0;
}
//*****************************************************************************
/*!
* \brief Runs the server thread.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
int SServer::Run()
{
if ((serverSocket = CreateSocket()) < 0)
{
return serverSocket;
}
int result = BindSocket();
if (result != 0) return result;
result = ListenOnSocket();
if (result != 0) return result;
// now start accepting those connection thingies.
serverStopped = false;
// Ignore SIGPIPE' so we can ignore error's
// thrown by out of band data
signal(SIGPIPE, SIG_IGN);
while(!serverStopped)
{
// Accept will block until a request is detected on this socket - port 80 - HTTP
sockaddr_in client_sock_addr;
socklen_t addlen = sizeof(client_sock_addr);
// Handle for the socket taking the client request
// TODO: Limit max connections to avoid flooding -
// but this is an inhouse thing
int clientSocket = accept(serverSocket, (sockaddr*)(&client_sock_addr), &addlen);
int errnum = errno;
result = errnum;
cerr << "Accepted new connection on socket: " << serverSocket << endl;
if (!serverStopped)
{
if (clientSocket < 0)
{
cerr << "ERROR: Could not accept connection [" << errnum << "]: " << strerror(errnum) << "." << endl;
serverStopped = true;
}
else
{
HandleConnection(clientSocket);
}
}
else if (clientSocket >= 0)
{
// server being killed and we have a socket, so close the
// socket as well
shutdown(clientSocket, SHUT_RDWR);
close(clientSocket);
}
}
if (serverSocket >= 0)
{
shutdown(serverSocket, SHUT_RDWR);
close(serverSocket);
serverSocket = -1;
}
return result;
}
//*****************************************************************************
/*!
* \brief Called by the handler when it has finished in asynch mode.
*
* \param SConnHandler * The handler that has just finished.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
void SServer::HandlerFinished(SConnHandler *pHandler)
{
cerr << "Done Handling Connection: " << pHandler->Socket() << endl;
pHandler->Reset();
if (connFactory != NULL)
connFactory->ReleaseHandler(pHandler);
}
//*****************************************************************************
/*!
* \brief Handles a connection request by a client.
*
* \param int clientSocket The client socket being handled.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
void SServer::HandleConnection(int clientSocket)
{
bool handled = false;
std::cerr << "Handling Connection: " << clientSocket << std::endl;
if (connFactory != NULL)
{
SConnHandler *handler = connFactory->NewHandler();
if (handler != NULL)
{
handler->Init(this, clientSocket);
handled = handler->HandleConnection();
if (!handled)
{
// means handler is in asynchronous mode - so add it to our
// list so clients, so the handler will have to explicitly
// call back when it is done with
SMutexLock locker(handlerListMutex);
// TODO: assert if handler is already in the handler list!
connHandlers.push_back(handler);
}
else
{
connFactory->ReleaseHandler(handler);
}
}
}
if (handled)
{
shutdown(clientSocket, SHUT_RDWR);
close(clientSocket);
cerr << "Done Handling Connection: " << clientSocket << endl;
}
}
/**************************************************************************************
* \brief Destructor
*
* \version
* - Sri Panyam 10/02/2009
* Created
**************************************************************************************/
SServer::~SServer()
{
Stop();
}
/**************************************************************************************
* \brief Sets a socket as non blocking.
*
* \version
* - Sri Panyam 18/02/2009
* Created
**************************************************************************************/
int SServer::setnonblocking(int fd)
{
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, 0) | O_NONBLOCK) == -1)
return -1;
return 0;
}
<commit_msg>Removed invalid header<commit_after>//*****************************************************************************
/*!
* 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.
*
*****************************************************************************
*
* \file server.cpp
*
* \brief Superclass of all multithreaded servers.
*
* \version
* - S Panyam 10/02/2009
* Created
*
*****************************************************************************/
#include "net/server.h"
#include "net/connhandler.h"
#include "net/connpool.h"
#include "net/sockbuff.h"
#include <string.h>
//*****************************************************************************
/*!
* \brief Called to stop the server.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
int
SServer::RealStop()
{
serverStopped = true;
if (serverSocket >= 0)
{
shutdown(serverSocket, SHUT_RDWR);
close(serverSocket);
serverSocket = -1;
}
// Stop child threads first
SMutexLock mutexLock(handlerListMutex);
for (std::list<SConnHandler *>::iterator iter=connHandlers.begin();
iter != connHandlers.end();
++iter)
{
// stop the client first
if ((*iter)->Running())
{
(*iter)->Stop();
}
// then the client
delete (*iter);
}
// clear client list
connHandlers.clear();
return 0;
}
//*****************************************************************************
/*!
* \brief Creates the server socket.
*
* Here we can allow child classes to do custom socket creations
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::CreateSocket()
{
// Create an internet socket using streaming (tcp/ip)
// and save the handle for the server socket
int newSocket = socket(AF_INET, SOCK_STREAM, 0);
if (newSocket < 0)
{
cerr << "ERROR: Cannot create server socket: [" << errno << "]: " << strerror(errno) << endl << endl;
return -errno;
}
/*
if (setnonblocking(newSocket))
{
cerr << "ERROR: Cannot make socket non blocking: [" << errno << "]: " << strerror(errno) << endl << endl;
return -1;
}
*/
// set it so we can reuse the socket immediately after closing it.
int reuse = 1;
if (setsockopt(newSocket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != 0)
{
cerr << "ERROR: setsockopt failed: [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
int nodelay = 1;
if (setsockopt(newSocket, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
if (setsockopt(newSocket, SOL_SOCKET, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
if (setsockopt(newSocket, SOL_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay)) != 0)
{
cerr << "ERROR: Could not set TCP_NODELAY [" << errno << "]: "
<< strerror(errno) << endl << endl;
return -errno;
}
return newSocket;
}
//*****************************************************************************
/*!
* \brief Bind the socket to the host and port.
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::BindSocket()
{
// Setup the structure that defines the IP-adress, port and protocol
// family to use.
sockaddr_in srv_sock_addr;
// zero the srv sock addr structure
bzero(&srv_sock_addr, sizeof(srv_sock_addr));
// Use the internet domain.
srv_sock_addr.sin_family = AF_INET;
// Use this specific port.
srv_sock_addr.sin_port = htons(serverPort);
// Use any of the network cards IP addresses.
srv_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind the socket to the port number specified by (serverPort).
int retval = bind(serverSocket, (sockaddr*)(&srv_sock_addr), sizeof(sockaddr));
if (retval != 0)
{
cerr << "ERROR: Cannot bind to server on port: [" << errno << "]: "
<< strerror(errno) << endl;
cerr << "ERROR: --------------------------------------------------" << endl;
return errno;
}
return 0;
}
//*****************************************************************************
/*!
* \brief Starts listening on the socket for connections.
*
* \version
* - Sri Panyam 16/02/2009
* Created.
*
*****************************************************************************/
int SServer::ListenOnSocket()
{
// Setup a limit of maximum 10 pending connections.
int retval = listen(serverSocket, 10);
if (retval != 0)
{
cerr << "ERROR: Cannot listen to connections: [" << errno << "]: "
<< strerror(errno) << endl;
return errno;
}
return 0;
}
//*****************************************************************************
/*!
* \brief Runs the server thread.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
int SServer::Run()
{
if ((serverSocket = CreateSocket()) < 0)
{
return serverSocket;
}
int result = BindSocket();
if (result != 0) return result;
result = ListenOnSocket();
if (result != 0) return result;
// now start accepting those connection thingies.
serverStopped = false;
// Ignore SIGPIPE' so we can ignore error's
// thrown by out of band data
signal(SIGPIPE, SIG_IGN);
while(!serverStopped)
{
// Accept will block until a request is detected on this socket - port 80 - HTTP
sockaddr_in client_sock_addr;
socklen_t addlen = sizeof(client_sock_addr);
// Handle for the socket taking the client request
// TODO: Limit max connections to avoid flooding -
// but this is an inhouse thing
int clientSocket = accept(serverSocket, (sockaddr*)(&client_sock_addr), &addlen);
int errnum = errno;
result = errnum;
cerr << "Accepted new connection on socket: " << serverSocket << endl;
if (!serverStopped)
{
if (clientSocket < 0)
{
cerr << "ERROR: Could not accept connection [" << errnum << "]: " << strerror(errnum) << "." << endl;
serverStopped = true;
}
else
{
HandleConnection(clientSocket);
}
}
else if (clientSocket >= 0)
{
// server being killed and we have a socket, so close the
// socket as well
shutdown(clientSocket, SHUT_RDWR);
close(clientSocket);
}
}
if (serverSocket >= 0)
{
shutdown(serverSocket, SHUT_RDWR);
close(serverSocket);
serverSocket = -1;
}
return result;
}
//*****************************************************************************
/*!
* \brief Called by the handler when it has finished in asynch mode.
*
* \param SConnHandler * The handler that has just finished.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
void SServer::HandlerFinished(SConnHandler *pHandler)
{
cerr << "Done Handling Connection: " << pHandler->Socket() << endl;
pHandler->Reset();
if (connFactory != NULL)
connFactory->ReleaseHandler(pHandler);
}
//*****************************************************************************
/*!
* \brief Handles a connection request by a client.
*
* \param int clientSocket The client socket being handled.
*
* \version
* - Sri Panyam 10/02/2009
* Created.
*
*****************************************************************************/
void SServer::HandleConnection(int clientSocket)
{
bool handled = false;
std::cerr << "Handling Connection: " << clientSocket << std::endl;
if (connFactory != NULL)
{
SConnHandler *handler = connFactory->NewHandler();
if (handler != NULL)
{
handler->Init(this, clientSocket);
handled = handler->HandleConnection();
if (!handled)
{
// means handler is in asynchronous mode - so add it to our
// list so clients, so the handler will have to explicitly
// call back when it is done with
SMutexLock locker(handlerListMutex);
// TODO: assert if handler is already in the handler list!
connHandlers.push_back(handler);
}
else
{
connFactory->ReleaseHandler(handler);
}
}
}
if (handled)
{
shutdown(clientSocket, SHUT_RDWR);
close(clientSocket);
cerr << "Done Handling Connection: " << clientSocket << endl;
}
}
/**************************************************************************************
* \brief Destructor
*
* \version
* - Sri Panyam 10/02/2009
* Created
**************************************************************************************/
SServer::~SServer()
{
Stop();
}
/**************************************************************************************
* \brief Sets a socket as non blocking.
*
* \version
* - Sri Panyam 18/02/2009
* Created
**************************************************************************************/
int SServer::setnonblocking(int fd)
{
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, 0) | O_NONBLOCK) == -1)
return -1;
return 0;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "objectives.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "accounts.hpp"
#include "args.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "compute.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
static data_handler<objective> objectives { "objectives", "objectives.data" };
std::string get_status(const budget::status& status, const budget::objective& objective){
std::string result;
budget::money basis;
if(objective.source == "expenses"){
basis = status.expenses;
} else if (objective.source == "earnings") {
basis = status.earnings;
} else if (objective.source == "savings_rate") {
double savings_rate = 0.0;
if(status.balance.dollars() > 0){
savings_rate = 100 * (status.balance.dollars() / double((status.budget + status.earnings).dollars()));
}
basis = budget::money(int(savings_rate));
} else {
basis = status.balance;
}
result += to_string(basis.dollars());
result += "/";
result += to_string(objective.amount.dollars());
return result;
}
std::string get_success(const budget::status& status, const budget::objective& objective){
auto success = compute_success(status, objective);
return "::success" + std::to_string(success);
}
void edit(budget::objective& objective){
edit_string(objective.name, "Name", not_empty_checker());
edit_string_complete(objective.type, "Type", {"monthly","yearly"}, not_empty_checker(), one_of_checker({"monthly","yearly"}));
edit_string_complete(objective.source, "Source", {"balance", "earnings", "expenses", "savings_rate"}, not_empty_checker(), one_of_checker({"balance", "earnings", "expenses", "savings_rate"}));
edit_string_complete(objective.op, "Operator", {"min", "max"}, not_empty_checker(), one_of_checker({"min", "max"}));
edit_money(objective.amount, "Amount");
}
} //end of anonymous namespace
std::map<std::string, std::string> budget::objective::get_params(){
std::map<std::string, std::string> params;
params["input_id"] = budget::to_string(id);
params["input_guid"] = guid;
params["input_date"] = budget::to_string(date);
params["input_name"] = name;
params["input_type"] = type;
params["input_source"] = source;
params["input_op"] = op;
params["input_amount"] = budget::to_string(amount);
return params;
}
void budget::yearly_objective_status(budget::writer& w, bool lines, bool full_align){
size_t yearly = 0;
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
++yearly;
}
}
if (yearly) {
w << title_begin << "Year objectives" << title_end;
if (lines) {
w << end_of_line;
}
size_t width = 0;
if (full_align) {
for (auto& objective : objectives.data) {
width = std::max(rsize(objective.name), width);
}
} else {
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
width = std::max(rsize(objective.name), width);
}
}
}
//Compute the year status
auto year_status = budget::compute_year_status();
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
std::vector<std::string> columns = {objective.name, "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
contents.push_back({to_string(local_day().year()), get_status(year_status, objective), get_success(year_status, objective)});
w.display_table(columns, contents);
}
}
}
}
void budget::monthly_objective_status(budget::writer& w){
w << title_begin << "Month objectives" << title_end;
auto today = budget::local_day();
auto current_month = today.month();
auto current_year = today.year();
auto sm = start_month(current_year);
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
std::vector<std::string> columns = {objective.name, "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
for (unsigned short i = sm; i <= current_month; ++i) {
budget::month month = i;
// Compute the month status
auto status = budget::compute_month_status(current_year, month);
contents.push_back({to_string(month), get_status(status, objective), get_success(status, objective)});
}
w.display_table(columns, contents);
}
}
}
void budget::current_monthly_objective_status(budget::writer& w, bool full_align){
w << title_begin << "Month objectives" << title_end;
auto today = budget::local_day();
size_t width = 0;
if (full_align) {
for (auto& objective : objectives.data) {
width = std::max(rsize(objective.name), width);
}
} else {
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
width = std::max(rsize(objective.name), width);
}
}
}
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
std::vector<std::string> columns = {objective.name, "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
// Compute the month status
auto status = budget::compute_month_status(today.year(), today.month());
contents.push_back({to_string(today.month()), get_status(status, objective), get_success(status, objective)});
w.display_table(columns, contents);
}
}
}
int budget::compute_success(const budget::status& status, const budget::objective& objective){
auto amount = objective.amount;
budget::money basis;
if(objective.source == "expenses"){
basis = status.expenses;
} else if (objective.source == "earnings") {
basis = status.earnings;
} else if (objective.source == "savings_rate") {
double savings_rate = 0.0;
if(status.balance.dollars() > 0){
savings_rate = 100 * (status.balance.dollars() / double((status.budget + status.earnings).dollars()));
}
basis = budget::money(int(savings_rate));
} else {
basis = status.balance;
}
int success = 0;
if(objective.op == "min"){
auto percent = basis.dollars() / static_cast<double>(amount.dollars());
success = percent * 100;
} else if(objective.op == "max"){
auto percent = amount.dollars() / static_cast<double>(basis.dollars());
success = percent * 100;
}
success = std::max(0, success);
return success;
}
void budget::objectives_module::load(){
load_expenses();
load_earnings();
load_accounts();
load_fortunes();
load_objectives();
}
void budget::objectives_module::unload(){
save_objectives();
}
void budget::objectives_module::handle(const std::vector<std::string>& args){
if(args.size() == 1){
console_writer w(std::cout);
status_objectives(w);
} else {
auto& subcommand = args[1];
if(subcommand == "list"){
console_writer w(std::cout);
budget::list_objectives(w);
} else if(subcommand == "status"){
console_writer w(std::cout);
status_objectives(w);
} else if(subcommand == "add"){
objective objective;
objective.guid = generate_guid();
objective.date = budget::local_day();
edit(objective);
auto id = objectives.add(std::move(objective));
std::cout << "Objective " << id << " has been created" << std::endl;
} else if(subcommand == "delete"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!objectives.exists(id)){
throw budget_exception("There are no objective with id " + args[2]);
}
objectives.remove(id);
std::cout << "Objective " << id << " has been deleted" << std::endl;
} else if(subcommand == "edit"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!objectives.exists(id)){
throw budget_exception("There are no objective with id " + args[2]);
}
auto& objective = objectives[id];
edit(objective);
if (objectives.edit(objective)) {
std::cout << "Objective " << id << " has been modified" << std::endl;
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_objectives(){
objectives.load();
}
void budget::save_objectives(){
objectives.save();
}
std::ostream& budget::operator<<(std::ostream& stream, const objective& objective){
return stream
<< objective.id << ':'
<< objective.guid << ':'
<< objective.name << ':'
<< objective.type << ':'
<< objective.source << ':'
<< objective.op << ':'
<< objective.amount << ':'
<< to_string(objective.date);
}
void budget::operator>>(const std::vector<std::string>& parts, objective& objective){
bool random = config_contains("random");
objective.id = to_number<size_t>(parts[0]);
objective.guid = parts[1];
objective.name = parts[2];
objective.type = parts[3];
objective.source = parts[4];
objective.op = parts[5];
objective.date = from_string(parts[7]);
if(random){
objective.amount = budget::random_money(1000, 10000);
} else {
objective.amount = parse_money(parts[6]);
}
}
std::vector<objective>& budget::all_objectives(){
return objectives.data;
}
void budget::set_objectives_changed(){
objectives.set_changed();
}
void budget::set_objectives_next_id(size_t next_id){
objectives.next_id = next_id;
}
void budget::list_objectives(budget::writer& w){
w << title_begin << "Objectives " << add_button("objectives") << title_end;
if (objectives.data.size() == 0) {
w << "No objectives" << end_of_line;
} else {
std::vector<std::string> columns = {"ID", "Name", "Type", "Source", "Operator", "Amount", "Edit"};
std::vector<std::vector<std::string>> contents;
for (auto& objective : objectives.data) {
contents.push_back({to_string(objective.id), objective.name, objective.type, objective.source, objective.op, to_string(objective.amount), "::edit::objectives::" + to_string(objective.id)});
}
w.display_table(columns, contents);
}
}
void budget::status_objectives(budget::writer& w){
w << title_begin << "Objectives " << add_button("objectives") << title_end;
if(objectives.data.size() == 0){
w << "No objectives" << end_of_line;
} else {
auto today = budget::local_day();
if(today.day() < 12){
w << p_begin << "WARNING: It is early in the month, no one can know what may happen ;)" << p_end;
}
size_t monthly = 0;
size_t yearly = 0;
for(auto& objective : objectives.data){
if(objective.type == "yearly"){
++yearly;
} else if(objective.type == "monthly"){
++monthly;
}
}
if(yearly){
budget::yearly_objective_status(w, true, false);
if(monthly){
w << end_of_line;
}
}
if(monthly){
budget::monthly_objective_status(w);
}
}
}
bool budget::objective_exists(size_t id){
return objectives.exists(id);
}
void budget::objective_delete(size_t id) {
if (!objectives.exists(id)) {
throw budget_exception("There are no objective with id ");
}
objectives.remove(id);
}
objective& budget::objective_get(size_t id) {
if (!objectives.exists(id)) {
throw budget_exception("There are no objective with id ");
}
return objectives[id];
}
void budget::add_objective(budget::objective&& objective){
objectives.add(std::forward<budget::objective>(objective));
}
<commit_msg>Improve objective display when several objectives<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include "objectives.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "accounts.hpp"
#include "args.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "compute.hpp"
#include "writer.hpp"
using namespace budget;
namespace {
static data_handler<objective> objectives { "objectives", "objectives.data" };
std::string get_status(const budget::status& status, const budget::objective& objective){
std::string result;
budget::money basis;
if(objective.source == "expenses"){
basis = status.expenses;
} else if (objective.source == "earnings") {
basis = status.earnings;
} else if (objective.source == "savings_rate") {
double savings_rate = 0.0;
if(status.balance.dollars() > 0){
savings_rate = 100 * (status.balance.dollars() / double((status.budget + status.earnings).dollars()));
}
basis = budget::money(int(savings_rate));
} else {
basis = status.balance;
}
result += to_string(basis.dollars());
result += "/";
result += to_string(objective.amount.dollars());
return result;
}
std::string get_success(const budget::status& status, const budget::objective& objective){
auto success = compute_success(status, objective);
return "::success" + std::to_string(success);
}
void edit(budget::objective& objective){
edit_string(objective.name, "Name", not_empty_checker());
edit_string_complete(objective.type, "Type", {"monthly","yearly"}, not_empty_checker(), one_of_checker({"monthly","yearly"}));
edit_string_complete(objective.source, "Source", {"balance", "earnings", "expenses", "savings_rate"}, not_empty_checker(), one_of_checker({"balance", "earnings", "expenses", "savings_rate"}));
edit_string_complete(objective.op, "Operator", {"min", "max"}, not_empty_checker(), one_of_checker({"min", "max"}));
edit_money(objective.amount, "Amount");
}
} //end of anonymous namespace
std::map<std::string, std::string> budget::objective::get_params(){
std::map<std::string, std::string> params;
params["input_id"] = budget::to_string(id);
params["input_guid"] = guid;
params["input_date"] = budget::to_string(date);
params["input_name"] = name;
params["input_type"] = type;
params["input_source"] = source;
params["input_op"] = op;
params["input_amount"] = budget::to_string(amount);
return params;
}
void budget::yearly_objective_status(budget::writer& w, bool lines, bool full_align){
size_t yearly = 0;
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
++yearly;
}
}
if (yearly) {
w << title_begin << "Year objectives" << title_end;
if (lines) {
w << end_of_line;
}
size_t width = 0;
if (full_align) {
for (auto& objective : objectives.data) {
width = std::max(rsize(objective.name), width);
}
} else {
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
width = std::max(rsize(objective.name), width);
}
}
}
//Compute the year status
auto year_status = budget::compute_year_status();
std::vector<std::string> columns = {"Objective", "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
for (auto& objective : objectives.data) {
if (objective.type == "yearly") {
contents.push_back({objective.name, get_status(year_status, objective), get_success(year_status, objective)});
}
}
w.display_table(columns, contents);
}
}
void budget::monthly_objective_status(budget::writer& w){
w << title_begin << "Month objectives" << title_end;
auto today = budget::local_day();
auto current_month = today.month();
auto current_year = today.year();
auto sm = start_month(current_year);
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
std::vector<std::string> columns = {objective.name, "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
for (unsigned short i = sm; i <= current_month; ++i) {
budget::month month = i;
// Compute the month status
auto status = budget::compute_month_status(current_year, month);
contents.push_back({to_string(month), get_status(status, objective), get_success(status, objective)});
}
w.display_table(columns, contents);
}
}
}
void budget::current_monthly_objective_status(budget::writer& w, bool full_align){
if (objectives.data.empty()) {
w << title_begin << "No objectives" << title_end;
return;
}
auto monthly_objectives = std::count_if(objectives.data.begin(), objectives.data.end(), [](auto& objective) {
return objective.type == "monthly";
});
if (!monthly_objectives) {
w << title_begin << "No objectives" << title_end;
return;
}
w << title_begin << "Month objectives" << title_end;
auto today = budget::local_day();
size_t width = 0;
if (full_align) {
for (auto& objective : objectives.data) {
width = std::max(rsize(objective.name), width);
}
} else {
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
width = std::max(rsize(objective.name), width);
}
}
}
std::vector<std::string> columns = {"Objective", "Status", "Progress"};
std::vector<std::vector<std::string>> contents;
// Compute the month status
auto status = budget::compute_month_status(today.year(), today.month());
for (auto& objective : objectives.data) {
if (objective.type == "monthly") {
contents.push_back({objective.name, get_status(status, objective), get_success(status, objective)});
}
}
w.display_table(columns, contents);
}
int budget::compute_success(const budget::status& status, const budget::objective& objective){
auto amount = objective.amount;
budget::money basis;
if(objective.source == "expenses"){
basis = status.expenses;
} else if (objective.source == "earnings") {
basis = status.earnings;
} else if (objective.source == "savings_rate") {
double savings_rate = 0.0;
if(status.balance.dollars() > 0){
savings_rate = 100 * (status.balance.dollars() / double((status.budget + status.earnings).dollars()));
}
basis = budget::money(int(savings_rate));
} else {
basis = status.balance;
}
int success = 0;
if(objective.op == "min"){
auto percent = basis.dollars() / static_cast<double>(amount.dollars());
success = percent * 100;
} else if(objective.op == "max"){
auto percent = amount.dollars() / static_cast<double>(basis.dollars());
success = percent * 100;
}
success = std::max(0, success);
return success;
}
void budget::objectives_module::load(){
load_expenses();
load_earnings();
load_accounts();
load_fortunes();
load_objectives();
}
void budget::objectives_module::unload(){
save_objectives();
}
void budget::objectives_module::handle(const std::vector<std::string>& args){
if(args.size() == 1){
console_writer w(std::cout);
status_objectives(w);
} else {
auto& subcommand = args[1];
if(subcommand == "list"){
console_writer w(std::cout);
budget::list_objectives(w);
} else if(subcommand == "status"){
console_writer w(std::cout);
status_objectives(w);
} else if(subcommand == "add"){
objective objective;
objective.guid = generate_guid();
objective.date = budget::local_day();
edit(objective);
auto id = objectives.add(std::move(objective));
std::cout << "Objective " << id << " has been created" << std::endl;
} else if(subcommand == "delete"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!objectives.exists(id)){
throw budget_exception("There are no objective with id " + args[2]);
}
objectives.remove(id);
std::cout << "Objective " << id << " has been deleted" << std::endl;
} else if(subcommand == "edit"){
enough_args(args, 3);
size_t id = to_number<size_t>(args[2]);
if(!objectives.exists(id)){
throw budget_exception("There are no objective with id " + args[2]);
}
auto& objective = objectives[id];
edit(objective);
if (objectives.edit(objective)) {
std::cout << "Objective " << id << " has been modified" << std::endl;
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_objectives(){
objectives.load();
}
void budget::save_objectives(){
objectives.save();
}
std::ostream& budget::operator<<(std::ostream& stream, const objective& objective){
return stream
<< objective.id << ':'
<< objective.guid << ':'
<< objective.name << ':'
<< objective.type << ':'
<< objective.source << ':'
<< objective.op << ':'
<< objective.amount << ':'
<< to_string(objective.date);
}
void budget::operator>>(const std::vector<std::string>& parts, objective& objective){
bool random = config_contains("random");
objective.id = to_number<size_t>(parts[0]);
objective.guid = parts[1];
objective.name = parts[2];
objective.type = parts[3];
objective.source = parts[4];
objective.op = parts[5];
objective.date = from_string(parts[7]);
if(random){
objective.amount = budget::random_money(1000, 10000);
} else {
objective.amount = parse_money(parts[6]);
}
}
std::vector<objective>& budget::all_objectives(){
return objectives.data;
}
void budget::set_objectives_changed(){
objectives.set_changed();
}
void budget::set_objectives_next_id(size_t next_id){
objectives.next_id = next_id;
}
void budget::list_objectives(budget::writer& w){
w << title_begin << "Objectives " << add_button("objectives") << title_end;
if (objectives.data.size() == 0) {
w << "No objectives" << end_of_line;
} else {
std::vector<std::string> columns = {"ID", "Name", "Type", "Source", "Operator", "Amount", "Edit"};
std::vector<std::vector<std::string>> contents;
for (auto& objective : objectives.data) {
contents.push_back({to_string(objective.id), objective.name, objective.type, objective.source, objective.op, to_string(objective.amount), "::edit::objectives::" + to_string(objective.id)});
}
w.display_table(columns, contents);
}
}
void budget::status_objectives(budget::writer& w){
w << title_begin << "Objectives " << add_button("objectives") << title_end;
if(objectives.data.size() == 0){
w << "No objectives" << end_of_line;
} else {
auto today = budget::local_day();
if(today.day() < 12){
w << p_begin << "WARNING: It is early in the month, no one can know what may happen ;)" << p_end;
}
size_t monthly = 0;
size_t yearly = 0;
for(auto& objective : objectives.data){
if(objective.type == "yearly"){
++yearly;
} else if(objective.type == "monthly"){
++monthly;
}
}
if(yearly){
budget::yearly_objective_status(w, true, false);
if(monthly){
w << end_of_line;
}
}
if(monthly){
budget::monthly_objective_status(w);
}
}
}
bool budget::objective_exists(size_t id){
return objectives.exists(id);
}
void budget::objective_delete(size_t id) {
if (!objectives.exists(id)) {
throw budget_exception("There are no objective with id ");
}
objectives.remove(id);
}
objective& budget::objective_get(size_t id) {
if (!objectives.exists(id)) {
throw budget_exception("There are no objective with id ");
}
return objectives[id];
}
void budget::add_objective(budget::objective&& objective){
objectives.add(std::forward<budget::objective>(objective));
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.