text
stringlengths 54
60.6k
|
---|
<commit_before>/////////////////////////
/*
// stitching.cpp
// adapted from stitching.cpp sample distributed with openCV source.
// adapted by Foundry for iOS
*/
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//
M*/
#include "stitching.h"
#include <iostream>
#include <fstream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching/stitcher.hpp"
using namespace std;
using namespace cv;
bool try_use_gpu = false;
vector<Mat> imgs;
string result_name = "result.jpg";
void printUsage();
int parseCmdArgs(int argc, char** argv);
cv::Mat stitch (vector<Mat>& images)
{
imgs = images;
Mat pano;
Stitcher stitcher = Stitcher::createDefault(try_use_gpu);
Stitcher::Status status = stitcher.stitch(imgs, pano);
if (status != Stitcher::OK)
{
cout << "Can't stitch images, error code = " << int(status) << endl;
//return 0;
}
return pano;
}
//// DEPRECATED CODE //////
/*
the code below this line is unused.
it is derived from the openCV 'stitched' C++ sample
left in here only for illustration purposes
- refactor main loop as member function
- replace user input with iOS GUI
- replace ouput with return value to CVWrapper
*/
//refactored as stitch function
int deprecatedMain(int argc, char* argv[])
{
int retval = parseCmdArgs(argc, argv);
if (retval) return -1;
Mat pano;
Stitcher stitcher = Stitcher::createDefault(try_use_gpu);
Stitcher::Status status = stitcher.stitch(imgs, pano);
if (status != Stitcher::OK)
{
cout << "Can't stitch images, error code = " << int(status) << endl;
return -1;
}
imwrite(result_name, pano);
return 0;
}
//unused
void printUsage()
{
cout <<
"Rotation model images stitcher.\n\n"
"stitching img1 img2 [...imgN]\n\n"
"Flags:\n"
" --try_use_gpu (yes|no)\n"
" Try to use GPU. The default value is 'no'. All default values\n"
" are for CPU mode.\n"
" --output <result_img>\n"
" The default is 'result.jpg'.\n";
}
//all input passed in via CVWrapper to stitcher function
int parseCmdArgs(int argc, char** argv)
{
if (argc == 1)
{
printUsage();
return -1;
}
for (int i = 1; i < argc; ++i)
{
if (string(argv[i]) == "--help" || string(argv[i]) == "/?")
{
printUsage();
return -1;
}
else if (string(argv[i]) == "--try_use_gpu")
{
if (string(argv[i + 1]) == "no")
try_use_gpu = false;
else if (string(argv[i + 1]) == "yes")
try_use_gpu = true;
else
{
cout << "Bad --try_use_gpu flag value\n";
return -1;
}
i++;
}
else if (string(argv[i]) == "--output")
{
result_name = argv[i + 1];
i++;
}
else
{
Mat img = imread(argv[i]);
if (img.empty())
{
cout << "Can't read image '" << argv[i] << "'\n";
return -1;
}
imgs.push_back(img);
}
}
return 0;
}
<commit_msg>stitching.cpp include comments<commit_after>/////////////////////////
/*
// stitching.cpp
// adapted from stitching.cpp sample distributed with openCV source.
// adapted by Foundry for iOS
*/
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//
M*/
#include "stitching.h"
#include <iostream>
#include <fstream>
//openCV 2.4.x
#include "opencv2/stitching/stitcher.hpp"
//openCV 3.x
//#include "opencv2/stitching.hpp"
using namespace std;
using namespace cv;
bool try_use_gpu = false;
vector<Mat> imgs;
string result_name = "result.jpg";
void printUsage();
int parseCmdArgs(int argc, char** argv);
cv::Mat stitch (vector<Mat>& images)
{
imgs = images;
Mat pano;
Stitcher stitcher = Stitcher::createDefault(try_use_gpu);
Stitcher::Status status = stitcher.stitch(imgs, pano);
if (status != Stitcher::OK)
{
cout << "Can't stitch images, error code = " << int(status) << endl;
//return 0;
}
return pano;
}
//// DEPRECATED CODE //////
/*
the code below this line is unused.
it is derived from the openCV 'stitched' C++ sample
left in here only for illustration purposes
- refactor main loop as member function
- replace user input with iOS GUI
- replace ouput with return value to CVWrapper
*/
//refactored as stitch function
int deprecatedMain(int argc, char* argv[])
{
int retval = parseCmdArgs(argc, argv);
if (retval) return -1;
Mat pano;
Stitcher stitcher = Stitcher::createDefault(try_use_gpu);
Stitcher::Status status = stitcher.stitch(imgs, pano);
if (status != Stitcher::OK)
{
cout << "Can't stitch images, error code = " << int(status) << endl;
return -1;
}
imwrite(result_name, pano);
return 0;
}
//unused
void printUsage()
{
cout <<
"Rotation model images stitcher.\n\n"
"stitching img1 img2 [...imgN]\n\n"
"Flags:\n"
" --try_use_gpu (yes|no)\n"
" Try to use GPU. The default value is 'no'. All default values\n"
" are for CPU mode.\n"
" --output <result_img>\n"
" The default is 'result.jpg'.\n";
}
//all input passed in via CVWrapper to stitcher function
int parseCmdArgs(int argc, char** argv)
{
if (argc == 1)
{
printUsage();
return -1;
}
for (int i = 1; i < argc; ++i)
{
if (string(argv[i]) == "--help" || string(argv[i]) == "/?")
{
printUsage();
return -1;
}
else if (string(argv[i]) == "--try_use_gpu")
{
if (string(argv[i + 1]) == "no")
try_use_gpu = false;
else if (string(argv[i + 1]) == "yes")
try_use_gpu = true;
else
{
cout << "Bad --try_use_gpu flag value\n";
return -1;
}
i++;
}
else if (string(argv[i]) == "--output")
{
result_name = argv[i + 1];
i++;
}
else
{
Mat img = imread(argv[i]);
if (img.empty())
{
cout << "Can't read image '" << argv[i] << "'\n";
return -1;
}
imgs.push_back(img);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef JSONPP_VALUE_HPP
#define JSONPP_VALUE_HPP
#include "type_traits.hpp"
#include "dump.hpp"
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <cassert>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <iosfwd>
namespace json {
inline namespace v1 {
class value {
public:
using object = std::map<std::string, value>;
using array = std::vector<value>;
private:
union storage_t {
double number;
bool boolean;
std::string* str;
array* arr;
object* obj;
} storage;
type storage_type;
void copy(const value& other) {
switch(other.storage_type) {
case type::array:
storage.arr = new array(*(other.storage.arr));
break;
case type::string:
storage.str = new std::string(*(other.storage.str));
break;
case type::object:
storage.obj = new object(*(other.storage.obj));
break;
case type::number:
storage.number = other.storage.number;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
default:
break;
}
storage_type = other.storage_type;
}
template<typename T>
struct is_generic : And<Not<is_string<T>>, Not<is_bool<T>>, Not<is_number<T>>,
Not<is_null<T>>, Not<std::is_same<T, object>>, Not<std::is_same<T, array>>> {};
public:
value() noexcept: storage_type(type::null) {}
value(null) noexcept: storage_type(type::null) {}
~value() {
clear();
}
value(double v) noexcept: storage_type(type::number) {
storage.number = v;
}
template<typename T, EnableIf<is_bool<T>, Not<is_string<T>>> = 0>
value(const T& b) noexcept: storage_type(type::boolean) {
storage.boolean = b;
}
template<typename T, EnableIf<is_string<T>, Not<is_bool<T>>> = 0>
value(const T& str): storage_type(type::string) {
storage.str = new std::string(str);
}
template<typename T, EnableIf<has_to_json<T>, Not<is_string<T>>, Not<is_bool<T>>> = 0>
value(const T& t): value(to_json(t)) {}
value(const array& arr): storage_type(type::array) {
storage.arr = new array(arr);
}
value(const object& obj): storage_type(type::object) {
storage.obj = new object(obj);
}
value(std::initializer_list<array::value_type> l): storage_type(type::array) {
storage.arr = new array(l.begin(), l.end());
}
value(const value& other) {
copy(other);
}
value(value&& other) noexcept {
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
template<typename T, EnableIf<has_to_json<T>, Not<is_string<T>>, Not<is_bool<T>>> = 0>
value& operator=(const T& t) {
*this = to_json(t);
return *this;
}
value& operator=(const value& other) {
clear();
copy(other);
return *this;
}
value& operator=(value&& other) noexcept {
clear();
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
return *this;
}
std::string type_name() const {
switch(storage_type) {
case type::array:
return "array";
case type::string:
return "string";
case type::object:
return "object";
case type::number:
return "number";
case type::boolean:
return "boolean";
case type::null:
return "null";
default:
return "unknown";
}
}
void clear() noexcept {
switch(storage_type) {
case type::array:
delete storage.arr;
break;
case type::string:
delete storage.str;
break;
case type::object:
delete storage.obj;
break;
default:
break;
}
storage_type = type::null;
}
template<typename T, EnableIf<is_string<T>> = 0>
bool is() const noexcept {
return storage_type == type::string;
}
template<typename T, EnableIf<is_null<T>> = 0>
bool is() const noexcept {
return storage_type == type::null;
}
template<typename T, EnableIf<is_number<T>> = 0>
bool is() const noexcept {
return storage_type == type::number;
}
template<typename T, EnableIf<is_bool<T>> = 0>
bool is() const noexcept {
return storage_type == type::boolean;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
bool is() const noexcept {
return storage_type == type::object;
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
bool is() const noexcept {
return storage_type == type::array;
}
template<typename T, EnableIf<is_generic<T>> = 0>
bool is() const noexcept {
return false;
}
template<typename T, EnableIf<std::is_same<T, const char*>> = 0>
T as() const {
assert(is<T>());
return storage.str->c_str();
}
template<typename T, EnableIf<std::is_same<T, std::string>> = 0>
T as() const {
assert(is<T>());
return *(storage.str);
}
template<typename T, EnableIf<is_null<T>> = 0>
T as() const {
assert(is<T>());
return {};
}
template<typename T, EnableIf<is_bool<T>> = 0>
T as() const {
assert(is<T>());
return storage.boolean;
}
template<typename T, EnableIf<is_number<T>> = 0>
T as() const {
assert(is<T>());
return storage.number;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
T as() const {
assert(is<T>());
return *(storage.obj);
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
T as() const {
assert(is<T>());
return *(storage.arr);
}
template<typename T, EnableIf<is_generic<T>> = 0>
T as() const {
throw std::runtime_error("calling value::as<T>() on an invalid type (use a json type instead)");
}
template<typename T>
T as(Identity<T>&& def) const {
return is<T>() ? as<T>() : std::forward<T>(def);
}
template<typename T, EnableIf<is_string<T>> = 0>
value operator[](const T& str) const {
if(!is<object>()) {
return {};
}
auto it = storage.obj->find(str);
if(it != storage.obj->end()) {
return it->second;
}
return {};
}
template<typename T, EnableIf<is_number<T>> = 0>
value operator[](const T& index) const {
if(!is<array>()) {
return {};
}
auto&& arr = *storage.arr;
if(static_cast<size_t>(index) < arr.size()) {
return arr[index];
}
return {};
}
template<typename OStream>
friend OStream& dump(OStream& out, const value& val, format_options opt = {}) {
switch(val.storage_type) {
case type::array:
return dump(out, *val.storage.arr, opt);
case type::string:
return dump(out, *val.storage.str, opt);
case type::object:
return dump(out, *val.storage.obj, opt);
case type::boolean:
return dump(out, val.storage.boolean, opt);
case type::number:
return dump(out, val.storage.number, opt);
case type::null:
return dump(out, nullptr, opt);
default:
return out;
}
}
};
using array = value::array;
using object = value::object;
} // v1
} // json
#endif // JSONPP_VALUE_HPP
<commit_msg>Add value_cast. Fixes #11.<commit_after>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef JSONPP_VALUE_HPP
#define JSONPP_VALUE_HPP
#include "type_traits.hpp"
#include "dump.hpp"
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <cassert>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <iosfwd>
namespace json {
inline namespace v1 {
class value {
public:
using object = std::map<std::string, value>;
using array = std::vector<value>;
private:
union storage_t {
double number;
bool boolean;
std::string* str;
array* arr;
object* obj;
} storage;
type storage_type;
void copy(const value& other) {
switch(other.storage_type) {
case type::array:
storage.arr = new array(*(other.storage.arr));
break;
case type::string:
storage.str = new std::string(*(other.storage.str));
break;
case type::object:
storage.obj = new object(*(other.storage.obj));
break;
case type::number:
storage.number = other.storage.number;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
default:
break;
}
storage_type = other.storage_type;
}
template<typename T>
struct is_generic : And<Not<is_string<T>>, Not<is_bool<T>>, Not<is_number<T>>,
Not<is_null<T>>, Not<std::is_same<T, object>>, Not<std::is_same<T, array>>> {};
public:
value() noexcept: storage_type(type::null) {}
value(null) noexcept: storage_type(type::null) {}
~value() {
clear();
}
value(double v) noexcept: storage_type(type::number) {
storage.number = v;
}
template<typename T, EnableIf<is_bool<T>, Not<is_string<T>>> = 0>
value(const T& b) noexcept: storage_type(type::boolean) {
storage.boolean = b;
}
template<typename T, EnableIf<is_string<T>, Not<is_bool<T>>> = 0>
value(const T& str): storage_type(type::string) {
storage.str = new std::string(str);
}
template<typename T, EnableIf<has_to_json<T>, Not<is_string<T>>, Not<is_bool<T>>> = 0>
value(const T& t): value(to_json(t)) {}
value(const array& arr): storage_type(type::array) {
storage.arr = new array(arr);
}
value(const object& obj): storage_type(type::object) {
storage.obj = new object(obj);
}
value(std::initializer_list<array::value_type> l): storage_type(type::array) {
storage.arr = new array(l.begin(), l.end());
}
value(const value& other) {
copy(other);
}
value(value&& other) noexcept {
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
template<typename T, EnableIf<has_to_json<T>, Not<is_string<T>>, Not<is_bool<T>>> = 0>
value& operator=(const T& t) {
*this = to_json(t);
return *this;
}
value& operator=(const value& other) {
clear();
copy(other);
return *this;
}
value& operator=(value&& other) noexcept {
clear();
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
return *this;
}
std::string type_name() const {
switch(storage_type) {
case type::array:
return "array";
case type::string:
return "string";
case type::object:
return "object";
case type::number:
return "number";
case type::boolean:
return "boolean";
case type::null:
return "null";
default:
return "unknown";
}
}
void clear() noexcept {
switch(storage_type) {
case type::array:
delete storage.arr;
break;
case type::string:
delete storage.str;
break;
case type::object:
delete storage.obj;
break;
default:
break;
}
storage_type = type::null;
}
template<typename T, EnableIf<is_string<T>> = 0>
bool is() const noexcept {
return storage_type == type::string;
}
template<typename T, EnableIf<is_null<T>> = 0>
bool is() const noexcept {
return storage_type == type::null;
}
template<typename T, EnableIf<is_number<T>> = 0>
bool is() const noexcept {
return storage_type == type::number;
}
template<typename T, EnableIf<is_bool<T>> = 0>
bool is() const noexcept {
return storage_type == type::boolean;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
bool is() const noexcept {
return storage_type == type::object;
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
bool is() const noexcept {
return storage_type == type::array;
}
template<typename T, EnableIf<is_generic<T>> = 0>
bool is() const noexcept {
return false;
}
template<typename T, EnableIf<std::is_same<T, const char*>> = 0>
T as() const {
assert(is<T>());
return storage.str->c_str();
}
template<typename T, EnableIf<std::is_same<T, std::string>> = 0>
T as() const {
assert(is<T>());
return *(storage.str);
}
template<typename T, EnableIf<is_null<T>> = 0>
T as() const {
assert(is<T>());
return {};
}
template<typename T, EnableIf<is_bool<T>> = 0>
T as() const {
assert(is<T>());
return storage.boolean;
}
template<typename T, EnableIf<is_number<T>> = 0>
T as() const {
assert(is<T>());
return storage.number;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
T as() const {
assert(is<T>());
return *(storage.obj);
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
T as() const {
assert(is<T>());
return *(storage.arr);
}
template<typename T, EnableIf<is_generic<T>> = 0>
T as() const {
throw std::runtime_error("calling value::as<T>() on an invalid type (use a json type instead)");
}
template<typename T>
T as(Identity<T>&& def) const {
return is<T>() ? as<T>() : std::forward<T>(def);
}
template<typename T, EnableIf<is_string<T>> = 0>
value operator[](const T& str) const {
if(!is<object>()) {
return {};
}
auto it = storage.obj->find(str);
if(it != storage.obj->end()) {
return it->second;
}
return {};
}
template<typename T, EnableIf<is_number<T>> = 0>
value operator[](const T& index) const {
if(!is<array>()) {
return {};
}
auto&& arr = *storage.arr;
if(static_cast<size_t>(index) < arr.size()) {
return arr[index];
}
return {};
}
template<typename OStream>
friend OStream& dump(OStream& out, const value& val, format_options opt = {}) {
switch(val.storage_type) {
case type::array:
return dump(out, *val.storage.arr, opt);
case type::string:
return dump(out, *val.storage.str, opt);
case type::object:
return dump(out, *val.storage.obj, opt);
case type::boolean:
return dump(out, val.storage.boolean, opt);
case type::number:
return dump(out, val.storage.number, opt);
case type::null:
return dump(out, nullptr, opt);
default:
return out;
}
}
};
using array = value::array;
using object = value::object;
template<typename T>
inline auto value_cast(const value& v) -> decltype(v.as<T>()) {
return v.as<T>();
}
template<typename T>
inline auto value_cast(const value& v, T&& def) -> decltype(v.as<Unqualified<T>>(std::forward<T>(def))) {
return v.as<Unqualified<T>>(std::forward<T>(def));
}
} // v1
} // json
#endif // JSONPP_VALUE_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
*/
#include "base/trace.hh"
#include "debug/AddrRanges.hh"
#include "dev/io_device.hh"
#include "sim/system.hh"
PioPort::PioPort(PioDevice *dev)
: SimpleTimingPort(dev->name() + ".pio", dev), device(dev)
{
}
Tick
PioPort::recvAtomic(PacketPtr pkt)
{
// @todo: We need to pay for this and not just zero it out
pkt->firstWordDelay = pkt->lastWordDelay = 0;
return pkt->isRead() ? device->read(pkt) : device->write(pkt);
}
AddrRangeList
PioPort::getAddrRanges() const
{
return device->getAddrRanges();
}
PioDevice::PioDevice(const Params *p)
: MemObject(p), sys(p->system), pioPort(this)
{}
PioDevice::~PioDevice()
{
}
void
PioDevice::init()
{
if (!pioPort.isConnected())
panic("Pio port of %s not connected to anything!", name());
pioPort.sendRangeChange();
}
BaseSlavePort &
PioDevice::getSlavePort(const std::string &if_name, PortID idx)
{
if (if_name == "pio") {
return pioPort;
}
return MemObject::getSlavePort(if_name, idx);
}
unsigned int
PioDevice::drain(DrainManager *dm)
{
unsigned int count;
count = pioPort.drain(dm);
if (count)
setDrainState(Drainable::Draining);
else
setDrainState(Drainable::Drained);
return count;
}
BasicPioDevice::BasicPioDevice(const Params *p, Addr size)
: PioDevice(p), pioAddr(p->pio_addr), pioSize(size),
pioDelay(p->pio_latency)
{}
AddrRangeList
BasicPioDevice::getAddrRanges() const
{
assert(pioSize != 0);
AddrRangeList ranges;
DPRINTF(AddrRanges, "registering range: %#x-%#x\n", pioAddr, pioSize);
ranges.push_back(RangeSize(pioAddr, pioSize));
return ranges;
}
<commit_msg>dev: Add response sanity checks in PioPort<commit_after>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Nathan Binkert
*/
#include "base/trace.hh"
#include "debug/AddrRanges.hh"
#include "dev/io_device.hh"
#include "sim/system.hh"
PioPort::PioPort(PioDevice *dev)
: SimpleTimingPort(dev->name() + ".pio", dev), device(dev)
{
}
Tick
PioPort::recvAtomic(PacketPtr pkt)
{
// @todo: We need to pay for this and not just zero it out
pkt->firstWordDelay = pkt->lastWordDelay = 0;
const Tick delay(pkt->isRead() ? device->read(pkt) : device->write(pkt));
assert(pkt->isResponse() || pkt->isError());
return delay;
}
AddrRangeList
PioPort::getAddrRanges() const
{
return device->getAddrRanges();
}
PioDevice::PioDevice(const Params *p)
: MemObject(p), sys(p->system), pioPort(this)
{}
PioDevice::~PioDevice()
{
}
void
PioDevice::init()
{
if (!pioPort.isConnected())
panic("Pio port of %s not connected to anything!", name());
pioPort.sendRangeChange();
}
BaseSlavePort &
PioDevice::getSlavePort(const std::string &if_name, PortID idx)
{
if (if_name == "pio") {
return pioPort;
}
return MemObject::getSlavePort(if_name, idx);
}
unsigned int
PioDevice::drain(DrainManager *dm)
{
unsigned int count;
count = pioPort.drain(dm);
if (count)
setDrainState(Drainable::Draining);
else
setDrainState(Drainable::Drained);
return count;
}
BasicPioDevice::BasicPioDevice(const Params *p, Addr size)
: PioDevice(p), pioAddr(p->pio_addr), pioSize(size),
pioDelay(p->pio_latency)
{}
AddrRangeList
BasicPioDevice::getAddrRanges() const
{
assert(pioSize != 0);
AddrRangeList ranges;
DPRINTF(AddrRanges, "registering range: %#x-%#x\n", pioAddr, pioSize);
ranges.push_back(RangeSize(pioAddr, pioSize));
return ranges;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/dispatch.hpp>
#include <metaverse/explorer/extensions/commands/getnewaddress.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ getnewaddress *************************/
console_result getnewaddress::invoke (std::ostream& output,
std::ostream& cerr, libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
auto acc = blockchain.is_account_passwd_valid(auth_.name, auth_.auth);
std::string mnemonic;
acc->get_mnemonic(auth_.auth, mnemonic);
if (mnemonic.empty()) { throw mnemonicwords_empty_exception("mnemonic empty"); }
if (!option_.count) { throw address_amount_exception("invalid address number parameter"); }
std::vector<std::string> words;
words.reserve(24);
//split mnemonic to words
string::size_type pos1, pos2;
std::string c{" "};
pos2 = mnemonic.find(c);
pos1 = 0;
while(string::npos != pos2)
{
words.push_back(mnemonic.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = mnemonic.find(c, pos1);
}
if(pos1 != mnemonic.length())
words.push_back(mnemonic.substr(pos1));
//end split
if ((words.size() % bc::wallet::mnemonic_word_multiple) != 0) {
return console_result::failure;
}
uint32_t idx = 0;
Json::Value aroot;
Json::Value addresses;
std::vector<std::shared_ptr<account_address>> account_addresses;
account_addresses.reserve(option_.count);
const auto seed = decode_mnemonic(words);
libbitcoin::config::base16 bs(seed);
const data_chunk& ds = static_cast<const data_chunk&>(bs);
const auto prefixes = bc::wallet::hd_private::to_prefixes(76066276, 0);//76066276 is HD private key version
const bc::wallet::hd_private private_key(ds, prefixes);
// mainnet payment address version
auto payment_version = 50;
if (blockchain.chain_settings().use_testnet_rules){
// testnetpayment address version
payment_version = 127;
}
for ( idx = 0; idx < option_.count; idx++ ) {
auto addr = std::make_shared<bc::chain::account_address>();
addr->set_name(auth_.name);
const auto child_private_key = private_key.derive_private(acc->get_hd_index());
auto hk = child_private_key.encoded();
// Create the private key from hd_key and the public version.
const auto derive_private_key = bc::wallet::hd_private(hk, prefixes);
auto pk = encode_base16(derive_private_key.secret());
addr->set_prv_key(pk.c_str(), auth_.auth);
// not store public key now
ec_compressed point;
libbitcoin::secret_to_public(point, derive_private_key.secret());
// Serialize to the original compression state.
auto ep = ec_public(point, true);
payment_address pa(ep, payment_version);
addr->set_address(pa.encoded());
addr->set_status(1); // 1 -- enable address
acc->increase_hd_index();
addr->set_hd_index(acc->get_hd_index());
account_addresses.push_back(addr);
// write to output json
addresses.append(addr->get_address());
if(option_.count == 1)
output<<addr->get_address();
}
blockchain.safe_store_account(*acc, account_addresses);
aroot["addresses"] = addresses;
if(option_.count != 1)
output << aroot.toStyledString();
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<commit_msg>compatible for getnewaddress<commit_after>/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/dispatch.hpp>
#include <metaverse/explorer/extensions/commands/getnewaddress.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ getnewaddress *************************/
console_result getnewaddress::invoke (std::ostream& output,
std::ostream& cerr, libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
auto acc = blockchain.is_account_passwd_valid(auth_.name, auth_.auth);
std::string mnemonic;
acc->get_mnemonic(auth_.auth, mnemonic);
if (mnemonic.empty()) { throw mnemonicwords_empty_exception("mnemonic empty"); }
if (!option_.count) { throw address_amount_exception("invalid address number parameter"); }
std::vector<std::string> words;
words.reserve(24);
//split mnemonic to words
string::size_type pos1, pos2;
std::string c{" "};
pos2 = mnemonic.find(c);
pos1 = 0;
while(string::npos != pos2)
{
words.push_back(mnemonic.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = mnemonic.find(c, pos1);
}
if(pos1 != mnemonic.length())
words.push_back(mnemonic.substr(pos1));
//end split
if ((words.size() % bc::wallet::mnemonic_word_multiple) != 0) {
return console_result::failure;
}
uint32_t idx = 0;
Json::Value aroot;
Json::Value addresses;
std::vector<std::shared_ptr<account_address>> account_addresses;
account_addresses.reserve(option_.count);
const auto seed = decode_mnemonic(words);
libbitcoin::config::base16 bs(seed);
const data_chunk& ds = static_cast<const data_chunk&>(bs);
const auto prefixes = bc::wallet::hd_private::to_prefixes(76066276, 0);//76066276 is HD private key version
const bc::wallet::hd_private private_key(ds, prefixes);
// mainnet payment address version
auto payment_version = 50;
if (blockchain.chain_settings().use_testnet_rules){
// testnetpayment address version
payment_version = 127;
}
for ( idx = 0; idx < option_.count; idx++ ) {
auto addr = std::make_shared<bc::chain::account_address>();
addr->set_name(auth_.name);
const auto child_private_key = private_key.derive_private(acc->get_hd_index());
auto hk = child_private_key.encoded();
// Create the private key from hd_key and the public version.
const auto derive_private_key = bc::wallet::hd_private(hk, prefixes);
auto pk = encode_base16(derive_private_key.secret());
addr->set_prv_key(pk.c_str(), auth_.auth);
// not store public key now
ec_compressed point;
libbitcoin::secret_to_public(point, derive_private_key.secret());
// Serialize to the original compression state.
auto ep = ec_public(point, true);
payment_address pa(ep, payment_version);
addr->set_address(pa.encoded());
addr->set_status(1); // 1 -- enable address
acc->increase_hd_index();
addr->set_hd_index(acc->get_hd_index());
account_addresses.push_back(addr);
// write to output json
addresses.append(addr->get_address());
if(get_api_version() == 1 && option_.count == 1)
output<<addr->get_address();
}
blockchain.safe_store_account(*acc, account_addresses);
aroot["addresses"] = addresses;
if(get_api_version() == 2 || option_.count != 1)
output << aroot.toStyledString();
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/json_helper.hpp>
#include <metaverse/explorer/extensions/commands/importkeyfile.hpp>
#include <metaverse/explorer/extensions/account_info.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
namespace fs = boost::filesystem;
using namespace bc::explorer::config;
/************************ importkeyfile *************************/
console_result importkeyfile::invoke (std::ostream& output,
std::ostream& cerr, libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
fs::file_status status = fs::status(option_.file);
if(!fs::exists(status)) // not process filesystem exception here
throw argument_legality_exception{option_.file.string() + std::string(" not exist.")};
if(fs::is_directory(status)) // directory not allowed
throw argument_legality_exception{option_.file.string() + std::string(" is directory not a file.")};
if(!fs::is_regular_file(status))
throw argument_legality_exception{option_.file.string() + std::string(" not a regular file.")};
// decrypt account info file first
account_info all_info(blockchain, option_.depasswd);
std::ifstream file_input(option_.file.string(), std::ofstream::in);
file_input >> all_info;
file_input.close();
// name check
auto acc = all_info.get_account();
auto name = acc.get_name();
auto mnemonic = acc.get_mnemonic();
if (blockchain.is_account_exist(name))
throw account_existed_exception{name + std::string(" account is already exist")};
// store account info to db
all_info.store(name, option_.depasswd);
Json::Value root;
root["name"] = name;
if (get_api_version() == 1) {
root["address-count"] += acc.get_hd_index();
root["unissued-asset-count"] += all_info.get_account_asset().size();
} else {
root["address-count"] = acc.get_hd_index();
root["unissued-asset-count"] = all_info.get_account_asset().size();
}
output << root.toStyledString();
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<commit_msg>fix macos compiling compatible<commit_after>/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/json_helper.hpp>
#include <metaverse/explorer/extensions/commands/importkeyfile.hpp>
#include <metaverse/explorer/extensions/account_info.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
namespace fs = boost::filesystem;
using namespace bc::explorer::config;
/************************ importkeyfile *************************/
console_result importkeyfile::invoke (std::ostream& output,
std::ostream& cerr, libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
fs::file_status status = fs::status(option_.file);
if(!fs::exists(status)) // not process filesystem exception here
throw argument_legality_exception{option_.file.string() + std::string(" not exist.")};
if(fs::is_directory(status)) // directory not allowed
throw argument_legality_exception{option_.file.string() + std::string(" is directory not a file.")};
if(!fs::is_regular_file(status))
throw argument_legality_exception{option_.file.string() + std::string(" not a regular file.")};
// decrypt account info file first
account_info all_info(blockchain, option_.depasswd);
std::ifstream file_input(option_.file.string(), std::ofstream::in);
file_input >> all_info;
file_input.close();
// name check
auto acc = all_info.get_account();
auto name = acc.get_name();
auto mnemonic = acc.get_mnemonic();
if (blockchain.is_account_exist(name))
throw account_existed_exception{name + std::string(" account is already exist")};
// store account info to db
all_info.store(name, option_.depasswd);
Json::Value root;
root["name"] = name;
if (get_api_version() == 1) {
root["address-count"] += acc.get_hd_index();
root["unissued-asset-count"] += all_info.get_account_asset().size();
} else {
root["address-count"] = acc.get_hd_index();
root["unissued-asset-count"] = static_cast<uint64_t>(all_info.get_account_asset().size());
}
output << root.toStyledString();
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<|endoftext|>
|
<commit_before>#include "lineup_node.h"
#include "text_node.h"
#include <cassert>
using namespace liven;
int main() {
auto ln = std::make_shared<lineup_node>(dimension::x);
auto hi = std::make_shared<text_node>("hi");
auto there = std::make_shared<text_node>("there");
ln->push_back(hi);
assert(ln->get_children().size() == 1);
ln->push_back(there);
assert(ln->get_children().size() == 2);
assert(hi->get_location() == point<3>(0,0,0));
auto x = hi->own_bounding_rect().width;
assert(there->get_location() == point<3>(x,0,0));
auto ln2 = std::make_shared<lineup_node>(dimension::y);
ln2->splice(ln2->end(),ln);
auto y = hi->own_bounding_rect().height;
assert(hi->get_parent().lock() == ln2);
assert(there->get_parent().lock() == ln2);
assert(hi->get_location() == point<3>(0,0,0));
assert(there->get_location() == point<3>(0,y,0));
ln2->remove(hi);
assert(ln2->get_children().size() == 1);
assert(there->get_location() == point<3>(0,0,0));
}<commit_msg>test erase and split<commit_after>#include "lineup_node.h"
#include "text_node.h"
#include <cassert>
using namespace liven;
int main() {
auto ln = std::make_shared<lineup_node>(dimension::x);
auto hi = std::make_shared<text_node>("hi");
auto there = std::make_shared<text_node>("there");
ln->push_back(hi);
assert(ln->get_children().size() == 1);
ln->push_back(there);
assert(ln->get_children().size() == 2);
assert(hi->get_location() == point<3>(0,0,0));
auto x = hi->own_bounding_rect().width;
assert(there->get_location() == point<3>(x,0,0));
auto ln2 = std::make_shared<lineup_node>(dimension::y);
ln2->splice(ln2->end(),ln);
auto y = hi->own_bounding_rect().height;
assert(hi->get_parent().lock() == ln2);
assert(there->get_parent().lock() == ln2);
assert(hi->get_location() == point<3>(0,0,0));
assert(there->get_location() == point<3>(0,y,0));
ln2->remove(hi);
assert(ln2->get_children().size() == 1);
assert(there->get_location() == point<3>(0,0,0));
auto root = std::make_shared<node>();
ln2->set_parent(root);
assert(ln2->get_parent().lock() == root);
ln2->push_back(hi);
auto ln3 = ln2->split(--ln2->end());
assert(ln3->get_parent().lock() == ln2->get_parent().lock());
assert(ln3->dim == ln2->dim);
assert(ln3->get_location().get_coordinate(ln3->dim) == ln2->own_bounding_rect().get_size(ln2->dim));
assert(*ln3->begin() == hi);
assert(ln3->get_lineup().size() == 1);
assert(*ln2->begin() == there);
assert(ln2->get_lineup().size() == 1);
}<|endoftext|>
|
<commit_before>// Copyright (c) 2016-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <amount.h>
#include <policy/feerate.h>
#include <test/setup_common.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(MoneyRangeTest)
{
BOOST_CHECK_EQUAL(MoneyRange(CAmount(-1)), false);
BOOST_CHECK_EQUAL(MoneyRange(CAmount(0)), true);
BOOST_CHECK_EQUAL(MoneyRange(CAmount(1)), true);
BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY), true);
BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY + CAmount(1)), false);
}
BOOST_AUTO_TEST_CASE(GetFeeTest)
{
CFeeRate feeRate, altFeeRate;
feeRate = CFeeRate(0);
// Must always return 0
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), CAmount(0));
feeRate = CFeeRate(1000);
// Must always just return the arg
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(121));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(999));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(1e3));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(9e3));
feeRate = CFeeRate(-1000);
// Must always just return -1 * arg
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(-1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(-121));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(-999));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(-1e3));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(-9e3));
feeRate = CFeeRate(123);
// Truncates the result, if not integer
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(1)); // Special case: returns 1 instead of 0
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(14));
BOOST_CHECK_EQUAL(feeRate.GetFee(122), CAmount(15));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(122));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(123));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(1107));
feeRate = CFeeRate(-123);
// Truncates the result, if not integer
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(-1)); // Special case: returns -1 instead of 0
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(-1));
// check alternate constructor
feeRate = CFeeRate(1000);
altFeeRate = CFeeRate(feeRate);
BOOST_CHECK_EQUAL(feeRate.GetFee(100), altFeeRate.GetFee(100));
// Check full constructor
BOOST_CHECK(CFeeRate(CAmount(-1), 0) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(0), 0) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(1), 0) == CFeeRate(0));
// default value
BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1));
BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1));
// lost precision (can only resolve satoshis per kB)
BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1));
// some more integer checks
BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32));
BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34));
// Maximum size in bytes, should not crash
CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();
}
BOOST_AUTO_TEST_CASE(BinaryOperatorTest)
{
CFeeRate a, b;
a = CFeeRate(1);
b = CFeeRate(2);
BOOST_CHECK(a < b);
BOOST_CHECK(b > a);
BOOST_CHECK(a == a);
BOOST_CHECK(a <= b);
BOOST_CHECK(a <= a);
BOOST_CHECK(b >= a);
BOOST_CHECK(b >= b);
// a should be 0.00000002 BTC/kB now
a += a;
BOOST_CHECK(a == b);
}
BOOST_AUTO_TEST_CASE(ToStringTest)
{
CFeeRate feeRate;
feeRate = CFeeRate(1);
BOOST_CHECK_EQUAL(feeRate.ToString(), "0.00000001 FTC/kB");
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[tests] Skip due to MAX_MONEY causing overflow<commit_after>// Copyright (c) 2016-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <amount.h>
#include <policy/feerate.h>
#include <test/setup_common.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(MoneyRangeTest)
{
BOOST_CHECK_EQUAL(MoneyRange(CAmount(-1)), false);
BOOST_CHECK_EQUAL(MoneyRange(CAmount(0)), true);
BOOST_CHECK_EQUAL(MoneyRange(CAmount(1)), true);
BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY), true);
BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY + CAmount(1)), false);
}
BOOST_AUTO_TEST_CASE(GetFeeTest)
{
CFeeRate feeRate, altFeeRate;
feeRate = CFeeRate(0);
// Must always return 0
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), CAmount(0));
feeRate = CFeeRate(1000);
// Must always just return the arg
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(121));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(999));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(1e3));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(9e3));
feeRate = CFeeRate(-1000);
// Must always just return -1 * arg
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(-1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(-121));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(-999));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(-1e3));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(-9e3));
feeRate = CFeeRate(123);
// Truncates the result, if not integer
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(1)); // Special case: returns 1 instead of 0
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(1));
BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(14));
BOOST_CHECK_EQUAL(feeRate.GetFee(122), CAmount(15));
BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(122));
BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(123));
BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(1107));
feeRate = CFeeRate(-123);
// Truncates the result, if not integer
BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(-1)); // Special case: returns -1 instead of 0
BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(-1));
// check alternate constructor
feeRate = CFeeRate(1000);
altFeeRate = CFeeRate(feeRate);
BOOST_CHECK_EQUAL(feeRate.GetFee(100), altFeeRate.GetFee(100));
// Check full constructor
BOOST_CHECK(CFeeRate(CAmount(-1), 0) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(0), 0) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(1), 0) == CFeeRate(0));
// default value
BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1));
BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1));
// lost precision (can only resolve satoshis per kB)
BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0));
BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1));
// some more integer checks
BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32));
BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34));
// Maximum size in bytes, should not crash
// Skip: MAX_MONEY too big
//CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();
}
BOOST_AUTO_TEST_CASE(BinaryOperatorTest)
{
CFeeRate a, b;
a = CFeeRate(1);
b = CFeeRate(2);
BOOST_CHECK(a < b);
BOOST_CHECK(b > a);
BOOST_CHECK(a == a);
BOOST_CHECK(a <= b);
BOOST_CHECK(a <= a);
BOOST_CHECK(b >= a);
BOOST_CHECK(b >= b);
// a should be 0.00000002 BTC/kB now
a += a;
BOOST_CHECK(a == b);
}
BOOST_AUTO_TEST_CASE(ToStringTest)
{
CFeeRate feeRate;
feeRate = CFeeRate(1);
BOOST_CHECK_EQUAL(feeRate.ToString(), "0.00000001 FTC/kB");
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#include "search-images-cli-command.h"
#include <QCoreApplication>
#include <QEventLoop>
#include <QSet>
#include <QSettings>
#include <utility>
#include "downloader/download-query-group.h"
#include "loader/pack-loader.h"
#include "logger.h"
#include "models/image.h"
#include "models/page.h"
#include "models/profile.h"
SearchImagesCliCommand::SearchImagesCliCommand(Profile *profile, QStringList tags, QStringList postFiltering, QList<Site*> sites, int page, int perPage, QString filename, QString folder, int max, bool login, bool noDuplicates, bool getBlacklisted, QObject *parent)
: SearchCliCommand(profile, std::move(tags), std::move(postFiltering), std::move(sites), page, perPage, parent), m_filename(filename), m_folder(folder), m_max(max), m_login(login), m_noDuplicates(noDuplicates), m_getBlacklisted(getBlacklisted)
{}
bool SearchImagesCliCommand::validate()
{
if (m_sites.isEmpty()) {
log("You must provide at least one source to load the images from", Logger::Error);
return false;
}
if (m_perPage <= 0) {
log("The number of images per page must be more than 0", Logger::Error);
return false;
}
if (m_max <= 0) {
log("The image limit must be more than 0", Logger::Error);
return false;
}
return true;
}
QList<QSharedPointer<Image>> SearchImagesCliCommand::getAllImages()
{
const bool usePacking = m_profile->getSettings()->value("packing_enable", true).toBool();
const int imagesPerPack = m_profile->getSettings()->value("packing_size", 1000).toInt();
const int packSize = usePacking ? imagesPerPack : -1;
QSet<QString> md5s;
QList<QSharedPointer<Image>> images;
for (auto *site : m_sites) {
DownloadQueryGroup query(m_tags, m_page, m_perPage, m_max, m_postFiltering, m_getBlacklisted, site, m_filename, m_folder);
PackLoader loader(m_profile, query, packSize, nullptr);
loader.start(m_login);
while (loader.hasNext()) {
const auto next = loader.next();
for (const auto &img : next) {
if (m_noDuplicates) {
if (md5s.contains(img->md5())) {
continue;
}
md5s.insert(img->md5());
}
images.append(img);
}
}
}
return images;
}
void SearchImagesCliCommand::loadMoreDetails(const QList<QSharedPointer<Image>> &images)
{
int work = images.length();
int requestsLimit = 5; // Simultaneous requests
int runningRequests = 0;
QEventLoop loop;
for (auto& image : images) {
while (runningRequests >= requestsLimit) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
runningRequests++;
image->loadDetails();
QObject::connect(image.data(), &Image::finishedLoadingTags, [&](){
work--;
runningRequests--;
if (!work) {
loop.quit();
}
});
}
loop.exec();
}
<commit_msg>Fix freeze in CLI when loading details for no images<commit_after>#include "search-images-cli-command.h"
#include <QCoreApplication>
#include <QEventLoop>
#include <QSet>
#include <QSettings>
#include <utility>
#include "downloader/download-query-group.h"
#include "loader/pack-loader.h"
#include "logger.h"
#include "models/image.h"
#include "models/page.h"
#include "models/profile.h"
SearchImagesCliCommand::SearchImagesCliCommand(Profile *profile, QStringList tags, QStringList postFiltering, QList<Site*> sites, int page, int perPage, QString filename, QString folder, int max, bool login, bool noDuplicates, bool getBlacklisted, QObject *parent)
: SearchCliCommand(profile, std::move(tags), std::move(postFiltering), std::move(sites), page, perPage, parent), m_filename(filename), m_folder(folder), m_max(max), m_login(login), m_noDuplicates(noDuplicates), m_getBlacklisted(getBlacklisted)
{}
bool SearchImagesCliCommand::validate()
{
if (m_sites.isEmpty()) {
log("You must provide at least one source to load the images from", Logger::Error);
return false;
}
if (m_perPage <= 0) {
log("The number of images per page must be more than 0", Logger::Error);
return false;
}
if (m_max <= 0) {
log("The image limit must be more than 0", Logger::Error);
return false;
}
return true;
}
QList<QSharedPointer<Image>> SearchImagesCliCommand::getAllImages()
{
const bool usePacking = m_profile->getSettings()->value("packing_enable", true).toBool();
const int imagesPerPack = m_profile->getSettings()->value("packing_size", 1000).toInt();
const int packSize = usePacking ? imagesPerPack : -1;
QSet<QString> md5s;
QList<QSharedPointer<Image>> images;
for (auto *site : m_sites) {
DownloadQueryGroup query(m_tags, m_page, m_perPage, m_max, m_postFiltering, m_getBlacklisted, site, m_filename, m_folder);
PackLoader loader(m_profile, query, packSize, nullptr);
loader.start(m_login);
while (loader.hasNext()) {
const auto next = loader.next();
for (const auto &img : next) {
if (m_noDuplicates) {
if (md5s.contains(img->md5())) {
continue;
}
md5s.insert(img->md5());
}
images.append(img);
}
}
}
return images;
}
void SearchImagesCliCommand::loadMoreDetails(const QList<QSharedPointer<Image>> &images)
{
if (images.isEmpty()) {
return;
}
int work = images.length();
int requestsLimit = 5; // Simultaneous requests
int runningRequests = 0;
QEventLoop loop;
for (auto& image : images) {
while (runningRequests >= requestsLimit) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
runningRequests++;
image->loadDetails();
QObject::connect(image.data(), &Image::finishedLoadingTags, [&](){
work--;
runningRequests--;
if (!work) {
loop.quit();
}
});
}
loop.exec();
}
<|endoftext|>
|
<commit_before>#include "Util.h"
#include "resources/ResourceManager.h"
#include "platform.h"
namespace fs = boost::filesystem;
std::string strToUpper(const char* from)
{
std::string str(from);
for(unsigned int i = 0; i < str.size(); i++)
str[i] = toupper(from[i]);
return str;
}
std::string& strToUpper(std::string& str)
{
for(unsigned int i = 0; i < str.size(); i++)
str[i] = toupper(str[i]);
return str;
}
std::string strToUpper(const std::string& str)
{
return strToUpper(str.c_str());
}
#if _MSC_VER < 1800
float round(float num)
{
return (float)((int)(num + 0.5f));
}
#endif
Eigen::Affine3f& roundMatrix(Eigen::Affine3f& mat)
{
mat.translation()[0] = round(mat.translation()[0]);
mat.translation()[1] = round(mat.translation()[1]);
return mat;
}
Eigen::Affine3f roundMatrix(const Eigen::Affine3f& mat)
{
Eigen::Affine3f ret = mat;
roundMatrix(ret);
return ret;
}
Eigen::Vector3f roundVector(const Eigen::Vector3f& vec)
{
Eigen::Vector3f ret = vec;
ret[0] = round(ret[0]);
ret[1] = round(ret[1]);
ret[2] = round(ret[2]);
return ret;
}
Eigen::Vector2f roundVector(const Eigen::Vector2f& vec)
{
Eigen::Vector2f ret = vec;
ret[0] = round(ret[0]);
ret[1] = round(ret[1]);
return ret;
}
// embedded resources, e.g. ":/font.ttf", need to be properly handled too
std::string getCanonicalPath(const std::string& path)
{
if(path.empty() || !boost::filesystem::exists(path))
return path;
return boost::filesystem::canonical(path).generic_string();
}
// expands "./my/path.sfc" to "[relativeTo]/my/path.sfc"
// if allowHome is true, also expands "~/my/path.sfc" to "/home/pi/my/path.sfc"
fs::path resolvePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
// nothing here
if(path.begin() == path.end())
return path;
if(*path.begin() == ".")
{
fs::path ret = relativeTo;
for(auto it = ++path.begin(); it != path.end(); ++it)
ret /= *it;
return ret;
}
if(allowHome && *path.begin() == "~")
{
fs::path ret = getHomePath();
for(auto it = ++path.begin(); it != path.end(); ++it)
ret /= *it;
return ret;
}
return path;
}
// example: removeCommonPath("/home/pi/roms/nes/foo/bar.nes", "/home/pi/roms/nes/") returns "foo/bar.nes"
fs::path removeCommonPath(const fs::path& path, const fs::path& relativeTo, bool& contains)
{
// if either of these doesn't exist, fs::canonical() is going to throw an error
if(!fs::exists(path) || !fs::exists(relativeTo))
{
contains = false;
return path;
}
fs::path p = fs::canonical(path);
fs::path r = fs::canonical(relativeTo);
if(p.root_path() != r.root_path())
{
contains = false;
return p;
}
fs::path result;
// find point of divergence
auto itr_path = p.begin();
auto itr_relative_to = r.begin();
while(*itr_path == *itr_relative_to && itr_path != p.end() && itr_relative_to != r.end())
{
++itr_path;
++itr_relative_to;
}
if(itr_relative_to != r.end())
{
contains = false;
return p;
}
while(itr_path != p.end())
{
if(*itr_path != fs::path("."))
result = result / *itr_path;
++itr_path;
}
contains = true;
return result;
}
// usage: makeRelativePath("/path/to/my/thing.sfc", "/path/to") -> "./my/thing.sfc"
// usage: makeRelativePath("/home/pi/my/thing.sfc", "/path/to", true) -> "~/my/thing.sfc"
fs::path makeRelativePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
bool contains = false;
fs::path ret = removeCommonPath(path, relativeTo, contains);
if(contains)
{
// success
ret = "." / ret;
return ret;
}
if(allowHome)
{
contains = false;
std::string homePath = getHomePath();
ret = removeCommonPath(path, homePath, contains);
if(contains)
{
// success
ret = "~" / ret;
return ret;
}
}
// nothing could be resolved
return path;
}
boost::posix_time::ptime string_to_ptime(const std::string& str, const std::string& fmt)
{
std::istringstream ss(str);
ss.imbue(std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(fmt))); //std::locale handles deleting the facet
boost::posix_time::ptime time;
ss >> time;
return time;
}
<commit_msg>Added symlink support on removeCommonPath<commit_after>#include "Util.h"
#include "resources/ResourceManager.h"
#include "platform.h"
namespace fs = boost::filesystem;
std::string strToUpper(const char* from)
{
std::string str(from);
for(unsigned int i = 0; i < str.size(); i++)
str[i] = toupper(from[i]);
return str;
}
std::string& strToUpper(std::string& str)
{
for(unsigned int i = 0; i < str.size(); i++)
str[i] = toupper(str[i]);
return str;
}
std::string strToUpper(const std::string& str)
{
return strToUpper(str.c_str());
}
#if _MSC_VER < 1800
float round(float num)
{
return (float)((int)(num + 0.5f));
}
#endif
Eigen::Affine3f& roundMatrix(Eigen::Affine3f& mat)
{
mat.translation()[0] = round(mat.translation()[0]);
mat.translation()[1] = round(mat.translation()[1]);
return mat;
}
Eigen::Affine3f roundMatrix(const Eigen::Affine3f& mat)
{
Eigen::Affine3f ret = mat;
roundMatrix(ret);
return ret;
}
Eigen::Vector3f roundVector(const Eigen::Vector3f& vec)
{
Eigen::Vector3f ret = vec;
ret[0] = round(ret[0]);
ret[1] = round(ret[1]);
ret[2] = round(ret[2]);
return ret;
}
Eigen::Vector2f roundVector(const Eigen::Vector2f& vec)
{
Eigen::Vector2f ret = vec;
ret[0] = round(ret[0]);
ret[1] = round(ret[1]);
return ret;
}
// embedded resources, e.g. ":/font.ttf", need to be properly handled too
std::string getCanonicalPath(const std::string& path)
{
if(path.empty() || !boost::filesystem::exists(path))
return path;
return boost::filesystem::canonical(path).generic_string();
}
// expands "./my/path.sfc" to "[relativeTo]/my/path.sfc"
// if allowHome is true, also expands "~/my/path.sfc" to "/home/pi/my/path.sfc"
fs::path resolvePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
// nothing here
if(path.begin() == path.end())
return path;
if(*path.begin() == ".")
{
fs::path ret = relativeTo;
for(auto it = ++path.begin(); it != path.end(); ++it)
ret /= *it;
return ret;
}
if(allowHome && *path.begin() == "~")
{
fs::path ret = getHomePath();
for(auto it = ++path.begin(); it != path.end(); ++it)
ret /= *it;
return ret;
}
return path;
}
// example: removeCommonPath("/home/pi/roms/nes/foo/bar.nes", "/home/pi/roms/nes/") returns "foo/bar.nes"
fs::path removeCommonPath(const fs::path& path, const fs::path& relativeTo, bool& contains)
{
// if either of these doesn't exist, fs::canonical() is going to throw an error
if(!fs::exists(path) || !fs::exists(relativeTo))
{
contains = false;
return path;
}
// if it's a symlink we don't want to apply fs::canonical on it, otherwise we'll lose the current parent_path
fs::path p = (fs::is_symlink(path) ? fs::canonical(path.parent_path()) / path.filename() : fs::canonical(path));
fs::path r = fs::canonical(relativeTo);
if(p.root_path() != r.root_path())
{
contains = false;
return p;
}
fs::path result;
// find point of divergence
auto itr_path = p.begin();
auto itr_relative_to = r.begin();
while(*itr_path == *itr_relative_to && itr_path != p.end() && itr_relative_to != r.end())
{
++itr_path;
++itr_relative_to;
}
if(itr_relative_to != r.end())
{
contains = false;
return p;
}
while(itr_path != p.end())
{
if(*itr_path != fs::path("."))
result = result / *itr_path;
++itr_path;
}
contains = true;
return result;
}
// usage: makeRelativePath("/path/to/my/thing.sfc", "/path/to") -> "./my/thing.sfc"
// usage: makeRelativePath("/home/pi/my/thing.sfc", "/path/to", true) -> "~/my/thing.sfc"
fs::path makeRelativePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
bool contains = false;
fs::path ret = removeCommonPath(path, relativeTo, contains);
if(contains)
{
// success
ret = "." / ret;
return ret;
}
if(allowHome)
{
contains = false;
std::string homePath = getHomePath();
ret = removeCommonPath(path, homePath, contains);
if(contains)
{
// success
ret = "~" / ret;
return ret;
}
}
// nothing could be resolved
return path;
}
boost::posix_time::ptime string_to_ptime(const std::string& str, const std::string& fmt)
{
std::istringstream ss(str);
ss.imbue(std::locale(std::locale::classic(), new boost::posix_time::time_input_facet(fmt))); //std::locale handles deleting the facet
boost::posix_time::ptime time;
ss >> time;
return time;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test_pivx.h"
#include "budget/budgetmanager.h"
#include "tinyformat.h"
#include "utilmoneystr.h"
#include "validation.h"
#include <boost/test/unit_test.hpp>
class BudgetManagerTest : CBudgetManager
{
public:
void ForceAddFinalizedBudget(CFinalizedBudget& finalizedBudget)
{
LOCK(cs_budgets);
const uint256& nHash = finalizedBudget.GetHash();
mapFinalizedBudgets.emplace(nHash, finalizedBudget);
mapFeeTxToBudget.emplace(finalizedBudget.GetFeeTXHash(), nHash);
}
bool IsBlockValueValid(int nHeight, CAmount nExpectedValue, CAmount nMinted, bool fSporkActive = true)
{
// suppose masternodeSync is complete
if (fSporkActive) {
// add current payee amount to the expected block value
CAmount expectedPayAmount;
if (GetExpectedPayeeAmount(nHeight, expectedPayAmount)) {
nExpectedValue += expectedPayAmount;
}
}
return nMinted <= nExpectedValue;
}
};
BOOST_FIXTURE_TEST_SUITE(budget_tests, TestingSetup)
void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue)
{
CBudgetManager budget;
CAmount nBudget = g_budgetman.GetTotalBudget(nHeight);
std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue));
BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError);
}
BOOST_AUTO_TEST_CASE(budget_value)
{
SelectParams(CBaseChainParams::TESTNET);
int nHeightTest = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_ZC_V2].nActivationHeight + 1;
CheckBudgetValue(nHeightTest-1, "testnet", 7200*COIN);
CheckBudgetValue(nHeightTest, "testnet", 144*COIN);
SelectParams(CBaseChainParams::MAIN);
nHeightTest = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_ZC_V2].nActivationHeight + 1;
CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN);
}
BOOST_AUTO_TEST_CASE(block_value)
{
BudgetManagerTest t_budgetman;
SelectParams(CBaseChainParams::TESTNET);
std::string strError;
// regular block
int nHeight = 100;
volatile CAmount nExpected = GetBlockValue(nHeight);
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected-1));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+1));
// superblock - create the finalized budget with a proposal, and vote on it
nHeight = 144;
nExpected = GetBlockValue(nHeight);
const CTxIn mnVin(GetRandHash(), 0);
const CScript payee = GetScriptForDestination(CKeyID(uint160(ParseHex("816115944e077fe7c803cfa57f29b36bf87c1d35"))));
const CAmount propAmt = 100 * COIN;
const uint256& propHash = GetRandHash(), finTxId = GetRandHash();
const CTxBudgetPayment txBudgetPayment(propHash, payee, propAmt);
CFinalizedBudget fin("main (test)", 144, {txBudgetPayment}, finTxId);
const CFinalizedBudgetVote fvote(mnVin, fin.GetHash());
BOOST_CHECK(fin.AddOrUpdateVote(fvote, strError));
t_budgetman.ForceAddFinalizedBudget(fin);
// check superblock's block-value
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt-1));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt+1));
// check with spork disabled
nExpected = GetBlockValue(nHeight);
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected-1, false));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected, false));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+1, false));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt, false));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[Tests] Add IsCoinbaseValueValid_test unit test case in budget_tests<commit_after>// Copyright (c) 2018-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "test_pivx.h"
#include "budget/budgetmanager.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "spork.h"
#include "tinyformat.h"
#include "utilmoneystr.h"
#include "validation.h"
#include <boost/test/unit_test.hpp>
class BudgetManagerTest : CBudgetManager
{
public:
void ForceAddFinalizedBudget(CFinalizedBudget& finalizedBudget)
{
LOCK(cs_budgets);
const uint256& nHash = finalizedBudget.GetHash();
mapFinalizedBudgets.emplace(nHash, finalizedBudget);
mapFeeTxToBudget.emplace(finalizedBudget.GetFeeTXHash(), nHash);
}
bool IsBlockValueValid(int nHeight, CAmount nExpectedValue, CAmount nMinted, bool fSporkActive = true)
{
// suppose masternodeSync is complete
if (fSporkActive) {
// add current payee amount to the expected block value
CAmount expectedPayAmount;
if (GetExpectedPayeeAmount(nHeight, expectedPayAmount)) {
nExpectedValue += expectedPayAmount;
}
}
return nMinted <= nExpectedValue;
}
};
BOOST_FIXTURE_TEST_SUITE(budget_tests, TestingSetup)
void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue)
{
CBudgetManager budget;
CAmount nBudget = g_budgetman.GetTotalBudget(nHeight);
std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue));
BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError);
}
BOOST_AUTO_TEST_CASE(budget_value)
{
SelectParams(CBaseChainParams::TESTNET);
int nHeightTest = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_ZC_V2].nActivationHeight + 1;
CheckBudgetValue(nHeightTest-1, "testnet", 7200*COIN);
CheckBudgetValue(nHeightTest, "testnet", 144*COIN);
SelectParams(CBaseChainParams::MAIN);
nHeightTest = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_ZC_V2].nActivationHeight + 1;
CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN);
}
BOOST_AUTO_TEST_CASE(block_value)
{
BudgetManagerTest t_budgetman;
SelectParams(CBaseChainParams::TESTNET);
std::string strError;
// regular block
int nHeight = 100;
volatile CAmount nExpected = GetBlockValue(nHeight);
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected-1));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+1));
// superblock - create the finalized budget with a proposal, and vote on it
nHeight = 144;
nExpected = GetBlockValue(nHeight);
const CTxIn mnVin(GetRandHash(), 0);
const CScript payee = GetScriptForDestination(CKeyID(uint160(ParseHex("816115944e077fe7c803cfa57f29b36bf87c1d35"))));
const CAmount propAmt = 100 * COIN;
const uint256& propHash = GetRandHash(), finTxId = GetRandHash();
const CTxBudgetPayment txBudgetPayment(propHash, payee, propAmt);
CFinalizedBudget fin("main (test)", 144, {txBudgetPayment}, finTxId);
const CFinalizedBudgetVote fvote(mnVin, fin.GetHash());
BOOST_CHECK(fin.AddOrUpdateVote(fvote, strError));
t_budgetman.ForceAddFinalizedBudget(fin);
// check superblock's block-value
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt-1));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt+1));
// check with spork disabled
nExpected = GetBlockValue(nHeight);
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected-1, false));
BOOST_CHECK(t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected, false));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+1, false));
BOOST_CHECK(!t_budgetman.IsBlockValueValid(nHeight, nExpected, nExpected+propAmt, false));
}
static CScript GetRandomP2PKH()
{
CKey key;
key.MakeNewKey(false);
return GetScriptForDestination(key.GetPubKey().GetID());
}
static CMutableTransaction NewCoinBase(int nHeight, CAmount cbaseAmt, const CScript& cbaseScript)
{
CMutableTransaction tx;
tx.vout.emplace_back(cbaseAmt, cbaseScript);
tx.vin.emplace_back();
tx.vin[0].scriptSig = CScript() << nHeight << OP_0;
return tx;
}
BOOST_AUTO_TEST_CASE(IsCoinbaseValueValid_test)
{
const CAmount mnAmt = GetMasternodePayment();
const CScript& cbaseScript = GetRandomP2PKH();
CValidationState state;
// force mnsync complete
masternodeSync.RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;
// -- Regular blocks
// Exact
CMutableTransaction cbase = NewCoinBase(1, mnAmt, cbaseScript);
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
cbase.vout[0].nValue /= 2;
cbase.vout.emplace_back(cbase.vout[0]);
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
// Underpaying with SPORK_8 disabled (good)
cbase.vout.clear();
cbase.vout.emplace_back(mnAmt - 1, cbaseScript);
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
cbase.vout[0].nValue = mnAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = mnAmt/2 - 1;
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
// Overpaying with SPORK_8 disabled
cbase.vout.clear();
cbase.vout.emplace_back(mnAmt + 1, cbaseScript);
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt-spork8-disabled");
state = CValidationState();
cbase.vout[0].nValue = mnAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = mnAmt/2 + 1;
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt-spork8-disabled");
state = CValidationState();
// enable SPORK_8
int64_t nTime = GetTime() - 10;
const CSporkMessage& spork = CSporkMessage(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, nTime + 1, nTime);
sporkManager.AddSporkMessage(spork);
BOOST_CHECK(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT));
// Underpaying with SPORK_8 enabled
cbase.vout.clear();
cbase.vout.emplace_back(mnAmt - 1, cbaseScript);
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt");
state = CValidationState();
cbase.vout[0].nValue = mnAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = mnAmt/2 - 1;
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt");
state = CValidationState();
// Overpaying with SPORK_8 enabled
cbase.vout.clear();
cbase.vout.emplace_back(mnAmt + 1, cbaseScript);
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt");
state = CValidationState();
cbase.vout[0].nValue = mnAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = mnAmt/2 + 1;
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), 0, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-cb-amt");
state = CValidationState();
const CAmount budgAmt = 200 * COIN;
// -- Superblocks
// Exact
cbase.vout.clear();
cbase.vout.emplace_back(budgAmt, cbaseScript);
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
cbase.vout[0].nValue /= 2;
cbase.vout.emplace_back(cbase.vout[0]);
BOOST_CHECK(IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
// Underpaying
cbase.vout.clear();
cbase.vout.emplace_back(budgAmt - 1, cbaseScript);
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-superblock-cb-amt");
state = CValidationState();
cbase.vout[0].nValue = budgAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = budgAmt/2 - 1;
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-superblock-cb-amt");
state = CValidationState();
// Overpaying
cbase.vout.clear();
cbase.vout.emplace_back(budgAmt + 1, cbaseScript);
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-superblock-cb-amt");
state = CValidationState();
cbase.vout[0].nValue = budgAmt/2;
cbase.vout.emplace_back(cbase.vout[0]);
cbase.vout[1].nValue = budgAmt/2 + 1;
BOOST_CHECK(!IsCoinbaseValueValid(MakeTransactionRef(cbase), budgAmt, state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-superblock-cb-amt");
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/**
** Copyright (c) 2011 Illumina, Inc.
**
**
** This software is covered by the "Illumina Non-Commercial Use Software
** and Source Code License Agreement" and any user of this software or
** source file is bound by the terms therein (see accompanying file
** Illumina_Non-Commercial_Use_Software_and_Source_Code_License_Agreement.pdf)
**
** This file is part of the BEETL software package.
**
** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone
** Lightweight BWT Construction for Very Large String Collections.
** Proceedings of CPM 2011, pp.219-231
**
**/
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include "Beetl.hh" // own declarations
#include "Algorithm.hh" // framework class declaration
#include "BWTCollection.h" // interface to BCR
#include "CountWords.hh" // interface to countwords
#include "BCRext.hh" // interface to BCRext
using namespace std;
//#define BEETL_ID "$Id$"
const string BEETL_ID("0.0.2");
int main(int numArgs, char** args) {
if (numArgs < 2) {
print_usage(args[0]);
}
if (strcmp(args[1],COMMAND_BCR) == 0) {
CompressionFormatType bcrCompression(compressionASCII);
// start at 2, 0 is the executable, 1 the command name parsed above
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
switch (args[i][1]) {
case 'i':
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
bcrFileIn = args[i + 1]; // this should be the name
cout << "-> input file is " << bcrFileIn << endl;
break;
case 'o':
isArgumentOrExit(i + 1, numArgs);
bcrFileOut = args[i + 1];
cout << "-> output prefix is " << bcrFileOut << endl;
break;
case 'm':
isArgumentOrExit(i + 1, numArgs);
bcrMode = atoi(args[i + 1]);
if (bcrMode > 2 || bcrMode < 0) {
cerr << bcrMode << " is no valid bcr mode " << endl;
exit(-1);
}
cout << "-> working mode set to \""
<< bcrModes[bcrMode]
<< "\""
<< endl;
break;
case 'a':
bcrCompression=compressionASCII;;
cout << "-> writing ASCII encoded output"
<< endl;
break;
case 'h':
bcrCompression=compressionHuffman;
cout << "Huffman encoding not yet supported, sorry."
<< endl;
exit(-1);
//cout << "-> writing huffman encoded output"
// << endl;
break;
case 'r':
bcrCompression=compressionRunLength;
cout << "-> writing runlength encoded output"
<< endl;
break;
default:
cout << "!! unknown flag \""
<< args[i][1] << "\"" << endl;
print_usage(args[0]);
}
}
// check if all arguments are given
if (bcrFileIn.length() > 0 && bcrMode >= 0) {
if (bcrFileOut.length() == 0){
bcrFileOut=bcrFileOutPrefixDefault;
}
if (bcrMode == 0){
isValidFastaFile(bcrFileIn.c_str());
}
// created new tool object
Algorithm * pBCR
= new BCR(bcrMode, bcrFileIn, bcrFileOut, bcrCompression);
// run previous main method
pBCR->run();
// clean up
delete pBCR;
// die
exit(0);
} else {
// something wrong happened
print_usage(args[0]);
}
} else if (strcmp(args[1], COMMAND_BCR_EXT) == 0) {
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
switch (args[i][1]) {
case 'i':
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
bcrExtFileIn = args[i + 1]; // this should be the name
cout << "-> input file is " << bcrExtFileIn << endl;
break;
case 'p':
isArgumentOrExit(i + 1, numArgs);
bcrFileOut = args[i + 1];
cout << "-> output prefix set to "
<< bcrFileOut << endl;
break;
case 'a':
if (!bcrExtRunlengthOutput && !bcrExtHuffmanOutput) {
bcrExtAsciiOutput = true;
}
cout << "-> writing ASCII encoded output"
<< endl;
break;
case 'h':
if (!bcrExtRunlengthOutput && !bcrExtAsciiOutput) {
bcrExtHuffmanOutput = true;
}
cout << "-> writing huffman encoded output"
<< endl;
break;
case 'r':
if (!bcrExtHuffmanOutput && !bcrExtAsciiOutput) {
bcrExtRunlengthOutput = true;
}
cout << "-> writing runlength encoded output"
<< endl;
break;
default:
cout << "!! unknown flag \""
<< args[i][1] << "\"" << endl;
print_usage(args[0]);
}
}
// check if all arguments are given
if ((bcrExtRunlengthOutput || bcrExtAsciiOutput || bcrExtHuffmanOutput) // no huffman for now
&& isValidReadFile(bcrExtFileIn.c_str())) {
if (bcrExtFileOutPrefix.length()==0){
bcrExtFileOutPrefix=bcrExtFileOutPrefixDefault;
}
// created new tool object
Algorithm * pBCRext = new BCRext(bcrExtHuffmanOutput,
bcrExtRunlengthOutput,
bcrExtAsciiOutput,
bcrExtFileIn,
bcrExtFileOutPrefix);
// run previous main method
pBCRext->run();
// clean up
delete pBCRext;
// die
exit(0);
} else {
// something wrong happened
print_usage(args[0]);
}
} else if (strcmp(args[1], COMMAND_COUNTWORDS) == 0) {
vector<string> filesA, filesB;
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
cout << "blah" << endl;
switch (args[i][1]) {
case 'a':
while (args[++i][0]!='-')
{
cout << args[i] << " fred " << endl;
fileIsReadableOrExit(args[i]);
filesA.push_back(args[i]);
cout << "-> input file A is "
<< filesA.back()
<< endl;
}
i--;
break;
#ifdef OLD
// next param should be the filename, checking
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
countWordsInputA = args[i + 1]; // should be the name
cout << "-> input file A is "
<< countWordsInputA
<< endl;
break;
#endif
case 'b':
while ((++i)!=numArgs)
{
fileIsReadableOrExit(args[i]);
filesB.push_back(args[i]);
cout << "-> input file B is "
<< filesB.back()
<< endl;
}
// i--;
break;
#ifdef OLD
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
countWordsInputB = args[i + 1]; // should be the name
cout << "-> input file B is "
<< countWordsInputB
<< endl;
break;
#endif
case 'k':
isArgumentOrExit(i + 1, numArgs);
minimalLengthK = atoi(args[i + 1]);
if (minimalLengthK < 0) {
cerr << "!! "
<< minimalLengthK
<< " is no valid length "
<< endl;
exit(-1);
}
cout << "-> minimal length k set to \""
<< minimalLengthK
<< "\""
<< endl;
break;
case 'n':
isArgumentOrExit(i + 1, numArgs);
minimalOccurencesN = atoi(args[i + 1]);
if (minimalOccurencesN < 0) {
cerr << "!! "
<< minimalOccurencesN
<< " is no valid value "
<< endl;
exit(-1);
}
cout << "-> maximal occurences n set to \""
<< minimalOccurencesN
<< "\""
<< endl;
break;
case 'r':
cout << "-> reference genome mode for set B " << endl;
ReferenceGenomeInputB = true;
break;
case 'A':
cout << "-> assuming set A is compressed" << endl;
compressedInputA = true;
break;
case 'B':
cout << "-> assuming set B is compressed" << endl;
compressedInputB = true;
break;
case 'C':
cout << "-> assuming set A&B are compressed" << endl;
compressedBoth = true;
break;
default:
cout << "!! unknown flag \"" << args[i][1]
<< "\"" << endl;
print_usage(args[0]);
}
}
// check for required arguments
if ( (minimalLengthK>0) && (minimalOccurencesN>0) &&
(filesA.size()>0) && (filesA.size()==filesB.size())) {
// create new tool object
Algorithm * pcountWords = new countWords(compressedBoth, compressedInputA,
compressedInputB, ReferenceGenomeInputB, minimalOccurencesN,
minimalLengthK, filesA, filesB);
// run the "main" method
pcountWords->run();
// clean up
delete pcountWords;
// closing time
exit(0);
} else {
// oops
print_usage(args[0]);
}
} else {
cerr << "!! \"" << args[1] << "\" is no known command" << endl;
print_usage(args[0]);
}
return 0;
}
void fileIsReadableOrExit(string filename) {
FILE * pFile;
// test file for read access
pFile = fopen(filename.c_str(), "r");
if (pFile != NULL) {
fclose(pFile);
return;
} else {
cerr << "!! \"" << filename << "\" is NOT readable!" << endl;
exit(-1);
}
}
void isArgumentOrExit(int num, int numArgs) {
if ((num) > (numArgs - 1)) {
cerr << "!! CLI parsing error. Wrong number of arguments?" << endl;
exit(-1);
}
}
void print_usage(char *args) {
cerr << endl << "- This is the BEETL software library -" << endl
<< endl
<< "Framework version " << BEETL_ID << endl
<< endl
<< "Included in this framework are the following algorithms" << endl
<< endl
<< endl
<< "-> BCRext - command \"" << COMMAND_BCR_EXT << "\"" << endl
<< "========================================================" << endl
<< "improved version of the orginal algorithm" << endl
<< "uses significantly less RAM (a.k.a. none) but depends heavily on I/O" << endl
<< endl
<< "Usage: " << args << " "
//<< COMMAND_BCR_EXT <<" -i <read file> -p <output file prefix> [-r -a]" << endl
// below: for huffman encoding uncomment when implemented
<< COMMAND_BCR_EXT <<" -i <read file> -p <output file prefix> [-h -r -a]" << endl
<< endl
<< "-i <file>:\tinput set of , 1 read per line, no fasta" << endl
<< "-p <string>:\toutput file names will start with \"prefix\"" << endl
<< "-a:\t\toutput ASCII encoded files" << endl
<< "-r:\t\toutput runlength encoded files [recommended]" << endl
<< "-h:\t\toutput Hufmann encoded files" << endl
<< endl
<< endl
<< "-> BCR - command \"" << COMMAND_BCR << "\"" << endl
<< "========================================================" << endl
<< "original algorithm to construct the BWT of a set of reads" << endl
<< "needs approximately 14GB of RAM for 1 billion reads" << endl
<< endl
<< "Usage: " << args << " "
<< COMMAND_BCR <<" -i <fasta read file> -o <output file> -m <[0,1,2]>" << endl
<< endl
<< "-i <file>:\tinput set of reads" << endl
<< "-o <file>:\toutput file" << endl
<< "-m <n>:\t\tmode = 0 --> BCR " << endl
<< "\t\tmode = 1 --> unBCR " << endl
<< "\t\tmode = 2 --> Backward search + Locate SeqID " << endl
<< endl
<< endl
<< "-> countWords - command \"" << COMMAND_COUNTWORDS << "\"" << endl
<< "========================================================" << endl
<< "find all words of length at least k that occur" << endl
<< "at least n times in string set A and never in string set B" << endl
<< endl
<< "Usage: " << args << " "
<< COMMAND_COUNTWORDS <<" [-A -B -C -r] -k <n> -n <n> -a <set A> -b <set B>" << endl
<< endl
<< "-A:\t\tassume BWT files for set A are in compressed format" << endl
<< "-B:\t\tassume BWT files for set B are in compressed format" << endl
<< "-C:\t\tassume BWT files for sets A and B are in compressed format" << endl
<< "-r:\t\tassume set B is a reference genome" << endl
<< "-k <n>:\t\tminimal length" << endl
<< "-n <n>:\t\tminimal occurences" << endl
<< "-a <file>:\tinput set A" << endl
<< "-b <file>:\tinput set B" << endl
<< endl
<< endl
<< "If you had fun using these algorithms you may cite:" << endl
<< "---------------------------------------------------" << endl
<< "Markus J. Bauer, Anthony J. Cox and Giovanna Rosone" << endl
<< "Lightweight BWT Construction for Very Large String Collections. " << endl
<< "Proceedings of CPM 2011, pp.219-231" << endl;
exit(0);
}
<commit_msg>Fixed -p parameter of BCRext<commit_after>/**
** Copyright (c) 2011 Illumina, Inc.
**
**
** This software is covered by the "Illumina Non-Commercial Use Software
** and Source Code License Agreement" and any user of this software or
** source file is bound by the terms therein (see accompanying file
** Illumina_Non-Commercial_Use_Software_and_Source_Code_License_Agreement.pdf)
**
** This file is part of the BEETL software package.
**
** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone
** Lightweight BWT Construction for Very Large String Collections.
** Proceedings of CPM 2011, pp.219-231
**
**/
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include "Beetl.hh" // own declarations
#include "Algorithm.hh" // framework class declaration
#include "BWTCollection.h" // interface to BCR
#include "CountWords.hh" // interface to countwords
#include "BCRext.hh" // interface to BCRext
using namespace std;
//#define BEETL_ID "$Id$"
const string BEETL_ID("0.0.2");
int main(int numArgs, char** args) {
if (numArgs < 2) {
print_usage(args[0]);
}
if (strcmp(args[1],COMMAND_BCR) == 0) {
CompressionFormatType bcrCompression(compressionASCII);
// start at 2, 0 is the executable, 1 the command name parsed above
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
switch (args[i][1]) {
case 'i':
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
bcrFileIn = args[i + 1]; // this should be the name
cout << "-> input file is " << bcrFileIn << endl;
break;
case 'o':
isArgumentOrExit(i + 1, numArgs);
bcrFileOut = args[i + 1];
cout << "-> output prefix is " << bcrFileOut << endl;
break;
case 'm':
isArgumentOrExit(i + 1, numArgs);
bcrMode = atoi(args[i + 1]);
if (bcrMode > 2 || bcrMode < 0) {
cerr << bcrMode << " is no valid bcr mode " << endl;
exit(-1);
}
cout << "-> working mode set to \""
<< bcrModes[bcrMode]
<< "\""
<< endl;
break;
case 'a':
bcrCompression=compressionASCII;;
cout << "-> writing ASCII encoded output"
<< endl;
break;
case 'h':
bcrCompression=compressionHuffman;
cout << "Huffman encoding not yet supported, sorry."
<< endl;
exit(-1);
//cout << "-> writing huffman encoded output"
// << endl;
break;
case 'r':
bcrCompression=compressionRunLength;
cout << "-> writing runlength encoded output"
<< endl;
break;
default:
cout << "!! unknown flag \""
<< args[i][1] << "\"" << endl;
print_usage(args[0]);
}
}
// check if all arguments are given
if (bcrFileIn.length() > 0 && bcrMode >= 0) {
if (bcrFileOut.length() == 0){
bcrFileOut=bcrFileOutPrefixDefault;
}
if (bcrMode == 0){
isValidFastaFile(bcrFileIn.c_str());
}
// created new tool object
Algorithm * pBCR
= new BCR(bcrMode, bcrFileIn, bcrFileOut, bcrCompression);
// run previous main method
pBCR->run();
// clean up
delete pBCR;
// die
exit(0);
} else {
// something wrong happened
print_usage(args[0]);
}
} else if (strcmp(args[1], COMMAND_BCR_EXT) == 0) {
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
switch (args[i][1]) {
case 'i':
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
bcrExtFileIn = args[i + 1]; // this should be the name
cout << "-> input file is " << bcrExtFileIn << endl;
break;
case 'p':
isArgumentOrExit(i + 1, numArgs);
bcrExtFileOutPrefix = args[i + 1];
cout << "-> output prefix set to "
<< bcrExtFileOutPrefix << endl;
break;
case 'a':
if (!bcrExtRunlengthOutput && !bcrExtHuffmanOutput) {
bcrExtAsciiOutput = true;
}
cout << "-> writing ASCII encoded output"
<< endl;
break;
case 'h':
if (!bcrExtRunlengthOutput && !bcrExtAsciiOutput) {
bcrExtHuffmanOutput = true;
}
cout << "-> writing huffman encoded output"
<< endl;
break;
case 'r':
if (!bcrExtHuffmanOutput && !bcrExtAsciiOutput) {
bcrExtRunlengthOutput = true;
}
cout << "-> writing runlength encoded output"
<< endl;
break;
default:
cout << "!! unknown flag \""
<< args[i][1] << "\"" << endl;
print_usage(args[0]);
}
}
// check if all arguments are given
if ((bcrExtRunlengthOutput || bcrExtAsciiOutput || bcrExtHuffmanOutput) // no huffman for now
&& isValidReadFile(bcrExtFileIn.c_str())) {
if (bcrExtFileOutPrefix.length()==0){
bcrExtFileOutPrefix=bcrExtFileOutPrefixDefault;
}
// created new tool object
Algorithm * pBCRext = new BCRext(bcrExtHuffmanOutput,
bcrExtRunlengthOutput,
bcrExtAsciiOutput,
bcrExtFileIn,
bcrExtFileOutPrefix);
// run previous main method
pBCRext->run();
// clean up
delete pBCRext;
// die
exit(0);
} else {
// something wrong happened
print_usage(args[0]);
}
} else if (strcmp(args[1], COMMAND_COUNTWORDS) == 0) {
vector<string> filesA, filesB;
for (int i = 2; i < numArgs; i++)
if (args[i][0] == '-') { // only flags here "-X etc."
cout << "blah" << endl;
switch (args[i][1]) {
case 'a':
while (args[++i][0]!='-')
{
cout << args[i] << " fred " << endl;
fileIsReadableOrExit(args[i]);
filesA.push_back(args[i]);
cout << "-> input file A is "
<< filesA.back()
<< endl;
}
i--;
break;
#ifdef OLD
// next param should be the filename, checking
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
countWordsInputA = args[i + 1]; // should be the name
cout << "-> input file A is "
<< countWordsInputA
<< endl;
break;
#endif
case 'b':
while ((++i)!=numArgs)
{
fileIsReadableOrExit(args[i]);
filesB.push_back(args[i]);
cout << "-> input file B is "
<< filesB.back()
<< endl;
}
// i--;
break;
#ifdef OLD
// next param should be the filename, checking now
isArgumentOrExit(i + 1, numArgs);
fileIsReadableOrExit(args[i + 1]);
countWordsInputB = args[i + 1]; // should be the name
cout << "-> input file B is "
<< countWordsInputB
<< endl;
break;
#endif
case 'k':
isArgumentOrExit(i + 1, numArgs);
minimalLengthK = atoi(args[i + 1]);
if (minimalLengthK < 0) {
cerr << "!! "
<< minimalLengthK
<< " is no valid length "
<< endl;
exit(-1);
}
cout << "-> minimal length k set to \""
<< minimalLengthK
<< "\""
<< endl;
break;
case 'n':
isArgumentOrExit(i + 1, numArgs);
minimalOccurencesN = atoi(args[i + 1]);
if (minimalOccurencesN < 0) {
cerr << "!! "
<< minimalOccurencesN
<< " is no valid value "
<< endl;
exit(-1);
}
cout << "-> maximal occurences n set to \""
<< minimalOccurencesN
<< "\""
<< endl;
break;
case 'r':
cout << "-> reference genome mode for set B " << endl;
ReferenceGenomeInputB = true;
break;
case 'A':
cout << "-> assuming set A is compressed" << endl;
compressedInputA = true;
break;
case 'B':
cout << "-> assuming set B is compressed" << endl;
compressedInputB = true;
break;
case 'C':
cout << "-> assuming set A&B are compressed" << endl;
compressedBoth = true;
break;
default:
cout << "!! unknown flag \"" << args[i][1]
<< "\"" << endl;
print_usage(args[0]);
}
}
// check for required arguments
if ( (minimalLengthK>0) && (minimalOccurencesN>0) &&
(filesA.size()>0) && (filesA.size()==filesB.size())) {
// create new tool object
Algorithm * pcountWords = new countWords(compressedBoth, compressedInputA,
compressedInputB, ReferenceGenomeInputB, minimalOccurencesN,
minimalLengthK, filesA, filesB);
// run the "main" method
pcountWords->run();
// clean up
delete pcountWords;
// closing time
exit(0);
} else {
// oops
print_usage(args[0]);
}
} else {
cerr << "!! \"" << args[1] << "\" is no known command" << endl;
print_usage(args[0]);
}
return 0;
}
void fileIsReadableOrExit(string filename) {
FILE * pFile;
// test file for read access
pFile = fopen(filename.c_str(), "r");
if (pFile != NULL) {
fclose(pFile);
return;
} else {
cerr << "!! \"" << filename << "\" is NOT readable!" << endl;
exit(-1);
}
}
void isArgumentOrExit(int num, int numArgs) {
if ((num) > (numArgs - 1)) {
cerr << "!! CLI parsing error. Wrong number of arguments?" << endl;
exit(-1);
}
}
void print_usage(char *args) {
cerr << endl << "- This is the BEETL software library -" << endl
<< endl
<< "Framework version " << BEETL_ID << endl
<< endl
<< "Included in this framework are the following algorithms" << endl
<< endl
<< endl
<< "-> BCRext - command \"" << COMMAND_BCR_EXT << "\"" << endl
<< "========================================================" << endl
<< "improved version of the orginal algorithm" << endl
<< "uses significantly less RAM (a.k.a. none) but depends heavily on I/O" << endl
<< endl
<< "Usage: " << args << " "
//<< COMMAND_BCR_EXT <<" -i <read file> -p <output file prefix> [-r -a]" << endl
// below: for huffman encoding uncomment when implemented
<< COMMAND_BCR_EXT <<" -i <read file> -p <output file prefix> [-h -r -a]" << endl
<< endl
<< "-i <file>:\tinput set of , 1 read per line, no fasta" << endl
<< "-p <string>:\toutput file names will start with \"prefix\"" << endl
<< "-a:\t\toutput ASCII encoded files" << endl
<< "-r:\t\toutput runlength encoded files [recommended]" << endl
<< "-h:\t\toutput Hufmann encoded files" << endl
<< endl
<< endl
<< "-> BCR - command \"" << COMMAND_BCR << "\"" << endl
<< "========================================================" << endl
<< "original algorithm to construct the BWT of a set of reads" << endl
<< "needs approximately 14GB of RAM for 1 billion reads" << endl
<< endl
<< "Usage: " << args << " "
<< COMMAND_BCR <<" -i <fasta read file> -o <output file> -m <[0,1,2]>" << endl
<< endl
<< "-i <file>:\tinput set of reads" << endl
<< "-o <file>:\toutput file" << endl
<< "-m <n>:\t\tmode = 0 --> BCR " << endl
<< "\t\tmode = 1 --> unBCR " << endl
<< "\t\tmode = 2 --> Backward search + Locate SeqID " << endl
<< endl
<< endl
<< "-> countWords - command \"" << COMMAND_COUNTWORDS << "\"" << endl
<< "========================================================" << endl
<< "find all words of length at least k that occur" << endl
<< "at least n times in string set A and never in string set B" << endl
<< endl
<< "Usage: " << args << " "
<< COMMAND_COUNTWORDS <<" [-A -B -C -r] -k <n> -n <n> -a <set A> -b <set B>" << endl
<< endl
<< "-A:\t\tassume BWT files for set A are in compressed format" << endl
<< "-B:\t\tassume BWT files for set B are in compressed format" << endl
<< "-C:\t\tassume BWT files for sets A and B are in compressed format" << endl
<< "-r:\t\tassume set B is a reference genome" << endl
<< "-k <n>:\t\tminimal length" << endl
<< "-n <n>:\t\tminimal occurences" << endl
<< "-a <file>:\tinput set A" << endl
<< "-b <file>:\tinput set B" << endl
<< endl
<< endl
<< "If you had fun using these algorithms you may cite:" << endl
<< "---------------------------------------------------" << endl
<< "Markus J. Bauer, Anthony J. Cox and Giovanna Rosone" << endl
<< "Lightweight BWT Construction for Very Large String Collections. " << endl
<< "Proceedings of CPM 2011, pp.219-231" << endl;
exit(0);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "Pipeline.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "PipelineWorker.h"
#include "Utilities.h"
#include <QObject>
#include <QTimer>
#include <pqView.h>
#include <vtkSMViewProxy.h>
#include <vtkTrivialProducer.h>
namespace tomviz {
Pipeline::Pipeline(DataSource* dataSource, QObject* parent)
: QObject(parent)
{
m_data = dataSource;
m_worker = new PipelineWorker(this);
m_data->setParent(this);
addDataSource(dataSource);
}
Pipeline::~Pipeline() = default;
void Pipeline::execute()
{
emit started();
executePipelineBranch(m_data);
}
void Pipeline::execute(DataSource* start, bool last)
{
emit started();
Operator* lastOp = nullptr;
if (last) {
lastOp = start->operators().last();
}
executePipelineBranch(start, lastOp);
}
void Pipeline::execute(DataSource* start)
{
emit started();
executePipelineBranch(start);
}
void Pipeline::executePipelineBranch(DataSource* dataSource, Operator* start)
{
if (m_paused) {
return;
}
auto operators = dataSource->operators();
if (operators.isEmpty()) {
emit finished();
return;
}
// Cancel any running operators. TODO in the future we should be able to add
// operators to end of a running pipeline.
if (m_future && m_future->isRunning()) {
m_future->cancel();
}
vtkDataObject* data = nullptr;
if (start != nullptr) {
// Use the transform DataSource as the starting point, if we have one.
auto transformDataSource = findTransformedDataSource(dataSource);
if (transformDataSource) {
data = transformDataSource->copyData();
}
// See if we have any canceled operators in the pipeline, if so we have to
// re-run this branch of the pipeline.
bool haveCanceled = false;
for (auto itr = dataSource->operators().begin(); *itr != start; ++itr) {
auto currentOp = *itr;
if (currentOp->isCanceled()) {
currentOp->resetState();
haveCanceled = true;
break;
}
}
// If we have canceled operators we have to run call operators.
if (!haveCanceled) {
operators = operators.mid(operators.indexOf(start));
start->resetState();
}
}
// Use the original
if (data == nullptr) {
data = dataSource->copyData();
}
m_future = m_worker->run(data, operators);
connect(m_future, &PipelineWorker::Future::finished, this,
&Pipeline::pipelineBranchFinished);
connect(m_future, &PipelineWorker::Future::canceled, this,
&Pipeline::pipelineBranchCanceled);
}
void Pipeline::pipelineBranchFinished(bool result)
{
PipelineWorker::Future* future =
qobject_cast<PipelineWorker::Future*>(sender());
if (result) {
auto lastOp = future->operators().last();
// We only add the transformed child data source if the last operator
// doesn't already have an explicit child data source i.e.
// hasChildDataSource
// is true.
if (!lastOp->hasChildDataSource()) {
DataSource* newChildDataSource = nullptr;
if (lastOp->childDataSource() == nullptr) {
newChildDataSource = new DataSource("Output");
newChildDataSource->setProperty("output", true);
newChildDataSource->setParent(this);
addDataSource(newChildDataSource);
lastOp->setChildDataSource(newChildDataSource);
}
lastOp->childDataSource()->setData(future->result());
lastOp->childDataSource()->dataModified();
if (newChildDataSource != nullptr) {
emit lastOp->newChildDataSource(newChildDataSource);
// Move modules from root data source.
bool oldMoveObjectsEnabled =
ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
foreach (Module* module, ModuleManager::instance().findModules<Module*>(
m_data, nullptr)) {
// TODO: We should really copy the module properties as well.
ModuleManager::instance().createAndAddModule(
module->label(), newChildDataSource, view);
ModuleManager::instance().removeModule(module);
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
}
}
// Do we have another branch to execute
if (lastOp->childDataSource() != nullptr) {
execute(lastOp->childDataSource());
lastOp->childDataSource()->setParent(this);
}
// The pipeline execution is finished
else {
emit finished();
}
future->deleteLater();
if (m_future == future) {
m_future = nullptr;
}
} else {
future->result()->Delete();
}
}
void Pipeline::pipelineBranchCanceled()
{
PipelineWorker::Future* future =
qobject_cast<PipelineWorker::Future*>(sender());
future->result()->Delete();
future->deleteLater();
if (m_future == future) {
m_future = nullptr;
}
}
void Pipeline::pause()
{
m_paused = true;
}
void Pipeline::resume(bool run)
{
m_paused = false;
if (run) {
execute();
}
}
void Pipeline::cancel(std::function<void()> canceled)
{
if (m_future) {
if (canceled) {
connect(m_future, &PipelineWorker::Future::canceled, canceled);
}
m_future->cancel();
}
}
bool Pipeline::isRunning()
{
return m_future != nullptr && m_future->isRunning();
}
DataSource* Pipeline::findTransformedDataSource(DataSource* dataSource)
{
auto op = findTransformedDataSourceOperator(dataSource);
if (op != nullptr) {
return op->childDataSource();
}
return nullptr;
}
Operator* Pipeline::findTransformedDataSourceOperator(DataSource* dataSource)
{
if (dataSource == nullptr) {
return nullptr;
}
auto operators = dataSource->operators();
for (auto itr = operators.rbegin(); itr != operators.rend(); ++itr) {
auto op = *itr;
// hasChildDataSource is only set by operators that explicitly produce child
// data sources
// such as a reconstruction operator. As part of the pipeline execution we
// do not
// set that flag, so we currently use it to tell the difference between
// "explicit"
// child data sources and those used to represent the transform data source.
if (!op->hasChildDataSource() && op->childDataSource() != nullptr) {
return op;
}
}
return nullptr;
}
void Pipeline::addDataSource(DataSource* dataSource)
{
connect(dataSource, &DataSource::operatorAdded,
[this](Operator* op) { this->execute(op->dataSource(), true); });
// Wire up transformModified to execute pipeline
connect(dataSource, &DataSource::operatorAdded, [this](Operator* op) {
// Extract out source and execute all.
connect(op, &Operator::transformModified, this,
[this]() { this->execute(); });
// We need to ensure we move add datasource to the end of the branch
auto operators = op->dataSource()->operators();
if (operators.size() > 1) {
auto transformedDataSourceOp =
this->findTransformedDataSourceOperator(op->dataSource());
if (transformedDataSourceOp != nullptr) {
auto transformedDataSource = transformedDataSourceOp->childDataSource();
transformedDataSourceOp->setChildDataSource(nullptr);
op->setChildDataSource(transformedDataSource);
// Delay emitting signal until next event loop
emit this->operatorAdded(op, transformedDataSource);
} else {
emit this->operatorAdded(op);
}
} else {
emit this->operatorAdded(op);
}
});
// Wire up operatorRemoved. TODO We need to check the branch of the
// pipeline we are currently executing.
connect(dataSource, &DataSource::operatorRemoved, [this](Operator* op) {
// Do we need to move the transformed data source, !hasChildDataSource as we
// don't want to move "explicit" child data sources.
if (!op->hasChildDataSource() && op->childDataSource() != nullptr) {
auto transformedDataSource = op->childDataSource();
auto operators = op->dataSource()->operators();
// We have an operator to move it to.
if (!operators.isEmpty()) {
auto newOp = operators.last();
op->setChildDataSource(nullptr);
newOp->setChildDataSource(transformedDataSource);
emit newOp->dataSourceMoved(transformedDataSource);
}
// Clean it up
else {
transformedDataSource->removeAllOperators();
transformedDataSource->deleteLater();
}
}
// If pipeline is running see if we can safely remove the operator
if (m_future && m_future->isRunning()) {
// If we can't safely cancel the execution then trigger the rerun of the
// pipeline.
if (!m_future->cancel(op)) {
this->execute(op->dataSource());
}
} else {
// Trigger the pipeline to run
this->execute(op->dataSource());
}
});
}
void Pipeline::addDefaultModules(DataSource* dataSource)
{
// Note: In the future we can pull this out into a setting.
QStringList defaultModules = { "Outline", "Orthogonal Slice" };
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
Module* module = nullptr;
foreach (QString name, defaultModules) {
module =
ModuleManager::instance().createAndAddModule(name, dataSource, view);
}
ActiveObjects::instance().setActiveModule(module);
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
auto pqview = tomviz::convert<pqView*>(view);
pqview->resetDisplay();
pqview->render();
}
Pipeline::ImageFuture::ImageFuture(Operator* op,
vtkSmartPointer<vtkImageData> imageData,
PipelineWorker::Future* future,
QObject* parent)
: QObject(parent), m_operator(op), m_imageData(imageData), m_future(future)
{
if (m_future != nullptr) {
connect(m_future, &PipelineWorker::Future::finished, this,
&Pipeline::ImageFuture::finished);
connect(m_future, &PipelineWorker::Future::canceled, this,
&Pipeline::ImageFuture::canceled);
}
}
Pipeline::ImageFuture::~ImageFuture()
{
if (m_future != nullptr) {
m_future->deleteLater();
}
}
Pipeline::ImageFuture* Pipeline::getCopyOfImagePriorTo(Operator* op)
{
auto operators = m_data->operators();
// If the op has not been added then we can just use the "Output" data source.
if (!operators.isEmpty() && !operators.contains(op)) {
auto transformed = this->findTransformedDataSource(m_data);
auto dataObject = transformed->copyData();
vtkSmartPointer<vtkImageData> result(
vtkImageData::SafeDownCast(dataObject));
auto imageFuture = new ImageFuture(op, result);
// Delay emitting signal until next event loop
QTimer::singleShot(0, [=] { emit imageFuture->finished(true); });
return imageFuture;
} else {
auto dataSource = m_data;
auto dataObject = dataSource->copyData();
vtkSmartPointer<vtkImageData> result(
vtkImageData::SafeDownCast(dataObject));
if (operators.size() > 1) {
auto index = operators.indexOf(op);
// Only run operators if we have some to run
if (index > 0) {
auto future = m_worker->run(result, operators.mid(0, index));
auto imageFuture = new ImageFuture(op, result, future);
return imageFuture;
}
}
auto imageFuture = new ImageFuture(op, result);
// Delay emitting signal until next event loop
QTimer::singleShot(0, [=] { emit imageFuture->finished(true); });
return imageFuture;
}
}
DataSource* Pipeline::transformedDataSource(DataSource* dataSource)
{
if (dataSource == nullptr) {
dataSource = this->dataSource();
}
auto transformed = this->findTransformedDataSource(dataSource);
if (transformed != nullptr) {
return transformed;
}
// Default to dataSource at being of pipeline
return dataSource;
}
} // tomviz namespace
<commit_msg>Use serialization code to copy over module properties<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "Pipeline.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "PipelineWorker.h"
#include "Utilities.h"
#include <QObject>
#include <QTimer>
#include <pqView.h>
#include <vtkSMViewProxy.h>
#include <vtkTrivialProducer.h>
namespace tomviz {
Pipeline::Pipeline(DataSource* dataSource, QObject* parent)
: QObject(parent)
{
m_data = dataSource;
m_worker = new PipelineWorker(this);
m_data->setParent(this);
addDataSource(dataSource);
}
Pipeline::~Pipeline() = default;
void Pipeline::execute()
{
emit started();
executePipelineBranch(m_data);
}
void Pipeline::execute(DataSource* start, bool last)
{
emit started();
Operator* lastOp = nullptr;
if (last) {
lastOp = start->operators().last();
}
executePipelineBranch(start, lastOp);
}
void Pipeline::execute(DataSource* start)
{
emit started();
executePipelineBranch(start);
}
void Pipeline::executePipelineBranch(DataSource* dataSource, Operator* start)
{
if (m_paused) {
return;
}
auto operators = dataSource->operators();
if (operators.isEmpty()) {
emit finished();
return;
}
// Cancel any running operators. TODO in the future we should be able to add
// operators to end of a running pipeline.
if (m_future && m_future->isRunning()) {
m_future->cancel();
}
vtkDataObject* data = nullptr;
if (start != nullptr) {
// Use the transform DataSource as the starting point, if we have one.
auto transformDataSource = findTransformedDataSource(dataSource);
if (transformDataSource) {
data = transformDataSource->copyData();
}
// See if we have any canceled operators in the pipeline, if so we have to
// re-run this branch of the pipeline.
bool haveCanceled = false;
for (auto itr = dataSource->operators().begin(); *itr != start; ++itr) {
auto currentOp = *itr;
if (currentOp->isCanceled()) {
currentOp->resetState();
haveCanceled = true;
break;
}
}
// If we have canceled operators we have to run call operators.
if (!haveCanceled) {
operators = operators.mid(operators.indexOf(start));
start->resetState();
}
}
// Use the original
if (data == nullptr) {
data = dataSource->copyData();
}
m_future = m_worker->run(data, operators);
connect(m_future, &PipelineWorker::Future::finished, this,
&Pipeline::pipelineBranchFinished);
connect(m_future, &PipelineWorker::Future::canceled, this,
&Pipeline::pipelineBranchCanceled);
}
void Pipeline::pipelineBranchFinished(bool result)
{
PipelineWorker::Future* future =
qobject_cast<PipelineWorker::Future*>(sender());
if (result) {
auto lastOp = future->operators().last();
// We only add the transformed child data source if the last operator
// doesn't already have an explicit child data source i.e.
// hasChildDataSource
// is true.
if (!lastOp->hasChildDataSource()) {
DataSource* newChildDataSource = nullptr;
if (lastOp->childDataSource() == nullptr) {
newChildDataSource = new DataSource("Output");
newChildDataSource->setProperty("output", true);
newChildDataSource->setParent(this);
addDataSource(newChildDataSource);
lastOp->setChildDataSource(newChildDataSource);
}
lastOp->childDataSource()->setData(future->result());
lastOp->childDataSource()->dataModified();
if (newChildDataSource != nullptr) {
emit lastOp->newChildDataSource(newChildDataSource);
// Move modules from root data source.
bool oldMoveObjectsEnabled =
ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
foreach (Module* module, ModuleManager::instance().findModules<Module*>(
m_data, nullptr)) {
// TODO: We should really copy the module properties as well.
auto newModule = ModuleManager::instance().createAndAddModule(
module->label(), newChildDataSource, view);
// Copy over properties using the serialization code.
newModule->deserialize(module->serialize());
ModuleManager::instance().removeModule(module);
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
}
}
// Do we have another branch to execute
if (lastOp->childDataSource() != nullptr) {
execute(lastOp->childDataSource());
lastOp->childDataSource()->setParent(this);
}
// The pipeline execution is finished
else {
emit finished();
}
future->deleteLater();
if (m_future == future) {
m_future = nullptr;
}
} else {
future->result()->Delete();
}
}
void Pipeline::pipelineBranchCanceled()
{
PipelineWorker::Future* future =
qobject_cast<PipelineWorker::Future*>(sender());
future->result()->Delete();
future->deleteLater();
if (m_future == future) {
m_future = nullptr;
}
}
void Pipeline::pause()
{
m_paused = true;
}
void Pipeline::resume(bool run)
{
m_paused = false;
if (run) {
execute();
}
}
void Pipeline::cancel(std::function<void()> canceled)
{
if (m_future) {
if (canceled) {
connect(m_future, &PipelineWorker::Future::canceled, canceled);
}
m_future->cancel();
}
}
bool Pipeline::isRunning()
{
return m_future != nullptr && m_future->isRunning();
}
DataSource* Pipeline::findTransformedDataSource(DataSource* dataSource)
{
auto op = findTransformedDataSourceOperator(dataSource);
if (op != nullptr) {
return op->childDataSource();
}
return nullptr;
}
Operator* Pipeline::findTransformedDataSourceOperator(DataSource* dataSource)
{
if (dataSource == nullptr) {
return nullptr;
}
auto operators = dataSource->operators();
for (auto itr = operators.rbegin(); itr != operators.rend(); ++itr) {
auto op = *itr;
// hasChildDataSource is only set by operators that explicitly produce child
// data sources
// such as a reconstruction operator. As part of the pipeline execution we
// do not
// set that flag, so we currently use it to tell the difference between
// "explicit"
// child data sources and those used to represent the transform data source.
if (!op->hasChildDataSource() && op->childDataSource() != nullptr) {
return op;
}
}
return nullptr;
}
void Pipeline::addDataSource(DataSource* dataSource)
{
connect(dataSource, &DataSource::operatorAdded,
[this](Operator* op) { this->execute(op->dataSource(), true); });
// Wire up transformModified to execute pipeline
connect(dataSource, &DataSource::operatorAdded, [this](Operator* op) {
// Extract out source and execute all.
connect(op, &Operator::transformModified, this,
[this]() { this->execute(); });
// We need to ensure we move add datasource to the end of the branch
auto operators = op->dataSource()->operators();
if (operators.size() > 1) {
auto transformedDataSourceOp =
this->findTransformedDataSourceOperator(op->dataSource());
if (transformedDataSourceOp != nullptr) {
auto transformedDataSource = transformedDataSourceOp->childDataSource();
transformedDataSourceOp->setChildDataSource(nullptr);
op->setChildDataSource(transformedDataSource);
// Delay emitting signal until next event loop
emit this->operatorAdded(op, transformedDataSource);
} else {
emit this->operatorAdded(op);
}
} else {
emit this->operatorAdded(op);
}
});
// Wire up operatorRemoved. TODO We need to check the branch of the
// pipeline we are currently executing.
connect(dataSource, &DataSource::operatorRemoved, [this](Operator* op) {
// Do we need to move the transformed data source, !hasChildDataSource as we
// don't want to move "explicit" child data sources.
if (!op->hasChildDataSource() && op->childDataSource() != nullptr) {
auto transformedDataSource = op->childDataSource();
auto operators = op->dataSource()->operators();
// We have an operator to move it to.
if (!operators.isEmpty()) {
auto newOp = operators.last();
op->setChildDataSource(nullptr);
newOp->setChildDataSource(transformedDataSource);
emit newOp->dataSourceMoved(transformedDataSource);
}
// Clean it up
else {
transformedDataSource->removeAllOperators();
transformedDataSource->deleteLater();
}
}
// If pipeline is running see if we can safely remove the operator
if (m_future && m_future->isRunning()) {
// If we can't safely cancel the execution then trigger the rerun of the
// pipeline.
if (!m_future->cancel(op)) {
this->execute(op->dataSource());
}
} else {
// Trigger the pipeline to run
this->execute(op->dataSource());
}
});
}
void Pipeline::addDefaultModules(DataSource* dataSource)
{
// Note: In the future we can pull this out into a setting.
QStringList defaultModules = { "Outline", "Orthogonal Slice" };
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
Module* module = nullptr;
foreach (QString name, defaultModules) {
module =
ModuleManager::instance().createAndAddModule(name, dataSource, view);
}
ActiveObjects::instance().setActiveModule(module);
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
auto pqview = tomviz::convert<pqView*>(view);
pqview->resetDisplay();
pqview->render();
}
Pipeline::ImageFuture::ImageFuture(Operator* op,
vtkSmartPointer<vtkImageData> imageData,
PipelineWorker::Future* future,
QObject* parent)
: QObject(parent), m_operator(op), m_imageData(imageData), m_future(future)
{
if (m_future != nullptr) {
connect(m_future, &PipelineWorker::Future::finished, this,
&Pipeline::ImageFuture::finished);
connect(m_future, &PipelineWorker::Future::canceled, this,
&Pipeline::ImageFuture::canceled);
}
}
Pipeline::ImageFuture::~ImageFuture()
{
if (m_future != nullptr) {
m_future->deleteLater();
}
}
Pipeline::ImageFuture* Pipeline::getCopyOfImagePriorTo(Operator* op)
{
auto operators = m_data->operators();
// If the op has not been added then we can just use the "Output" data source.
if (!operators.isEmpty() && !operators.contains(op)) {
auto transformed = this->findTransformedDataSource(m_data);
auto dataObject = transformed->copyData();
vtkSmartPointer<vtkImageData> result(
vtkImageData::SafeDownCast(dataObject));
auto imageFuture = new ImageFuture(op, result);
// Delay emitting signal until next event loop
QTimer::singleShot(0, [=] { emit imageFuture->finished(true); });
return imageFuture;
} else {
auto dataSource = m_data;
auto dataObject = dataSource->copyData();
vtkSmartPointer<vtkImageData> result(
vtkImageData::SafeDownCast(dataObject));
if (operators.size() > 1) {
auto index = operators.indexOf(op);
// Only run operators if we have some to run
if (index > 0) {
auto future = m_worker->run(result, operators.mid(0, index));
auto imageFuture = new ImageFuture(op, result, future);
return imageFuture;
}
}
auto imageFuture = new ImageFuture(op, result);
// Delay emitting signal until next event loop
QTimer::singleShot(0, [=] { emit imageFuture->finished(true); });
return imageFuture;
}
}
DataSource* Pipeline::transformedDataSource(DataSource* dataSource)
{
if (dataSource == nullptr) {
dataSource = this->dataSource();
}
auto transformed = this->findTransformedDataSource(dataSource);
if (transformed != nullptr) {
return transformed;
}
// Default to dataSource at being of pipeline
return dataSource;
}
} // tomviz namespace
<|endoftext|>
|
<commit_before>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <memory>
#include <iostream>
#include <boost/program_options.hpp>
#include <fmi4cpp/fmi2/fmi4cpp.hpp>
using namespace std;
using namespace fmi4cpp::fmi2;
namespace {
const int SUCCESS = 0;
const int COMMANDLINE_ERROR = 1;
const int UNHANDLED_ERROR = 2;
}
int main(int argc, char** argv) {
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print this help message and quits.")
("fmu,f", po::value<string>(), "Path to FMU.")
("startTime,start", po::value<string>(), "Start time.")
("stopTime,stop", po::value<string>(), "Stop time.")
("stepSize,dt", po::value<string>(), "StepSize.");
if (argc == 1) {
cout << "fmudriver" << endl << desc << endl;
}
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
if ( vm.count("help") ) {
cout << "fmudriver" << endl << desc << endl;
return SUCCESS;
}
po::notify(vm);
} catch(po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return COMMANDLINE_ERROR;
}
return 0;
}
class FmuDriver {
private:
const string fmuPath;
public:
double start;
double stop;
double stepSize;
bool modelExchange;
explicit FmuDriver(const string &fmuPath) : fmuPath(fmuPath) {}
void simulate(unique_ptr<FmuSlave> slave) {
slave->setupExperiment(start);
slave->enterInitializationMode();
slave->exitInitializationMode();
double t;
string outputData = "";
while ( (t = slave->getSimulationTime()) <= (stop - stepSize) ) {
if (!slave->doStep(stepSize)) {
break;
}
}
slave->terminate();
}
void run() {
if (modelExchange) {
auto solver = make_solver<RK4ClassicSolver>(1E-3);
simulate(Fmu(fmuPath).asModelExchangeFmu()->newInstance(solver));
} else {
simulate(Fmu(fmuPath).asCoSimulationFmu()->newInstance());
}
}
};<commit_msg>fmudriver WIP<commit_after>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <memory>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <fmi4cpp/fmi2/fmi4cpp.hpp>
using namespace std;
using namespace fmi4cpp::fmi2;
namespace {
const int SUCCESS = 0;
const int COMMANDLINE_ERROR = 1;
const int UNHANDLED_ERROR = 2;
}
int main(int argc, char** argv) {
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print this help message and quits.")
("fmu,f", po::value<string>(), "Path to FMU.")
("startTime,start", po::value<string>(), "Start time.")
("stopTime,stop", po::value<string>(), "Stop time.")
("stepSize,dt", po::value<string>(), "StepSize.");
if (argc == 1) {
cout << "fmudriver" << endl << desc << endl;
}
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
if ( vm.count("help") ) {
cout << "fmudriver" << endl << desc << endl;
return SUCCESS;
}
po::notify(vm);
} catch(po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return COMMANDLINE_ERROR;
}
return 0;
}
struct DriverOptions {
double startTime = 0.0;
double stopTime = 0.0;
double stepSize = 1e-3;
bool modelExchange = false;
string outputFolder;
vector<string> variables;
};
class FmuDriver {
public:
FmuDriver(const string &fmuPath, DriverOptions &options) : fmuPath(fmuPath), options(options) {
for (const auto v : )
}
void run() {
if (options.modelExchange) {
auto solver = make_solver<RK4ClassicSolver>(1E-3);
simulate(Fmu(fmuPath).asModelExchangeFmu()->newInstance(solver));
} else {
simulate(Fmu(fmuPath).asCoSimulationFmu()->newInstance());
}
}
private:
const string fmuPath;
const DriverOptions options;
vector<ScalarVariable> variables;
void addHeader(string &data) {
data += "\"Time\"";
auto variables = options.variables;
for (unsigned long i = 0; i < variables.size(); i++) {
data += "\"" + variables[i] + "\"";
if (i != variables.size()-1) {
data += ",";
}
}
data += "\n";
}
void addRow(FmuSlave &slave, string &data) {
data += to_string(slave.getSimulationTime());
auto variables = options.variables;
for (unsigned long i = 0; i < variables.size(); i++) {
data += "\"" + variables[i] + "\"";
if (i != variables.size()-1) {
data += ",";
}
}
data += "\n";
}
void simulate(unique_ptr<FmuSlave> slave) {
auto startTime = options.startTime;
auto stopTime = options.stopTime;
auto stepSize = options.stepSize;
slave->setupExperiment(startTime);
slave->enterInitializationMode();
slave->exitInitializationMode();
double t;
string data = "";
addHeader(data);
while ( (t = slave->getSimulationTime()) <= (stopTime - stepSize) ) {
addRow(*slave, data);
if (!slave->doStep(stepSize)) {
break;
}
}
slave->terminate();
}
};<|endoftext|>
|
<commit_before>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#define ID 0x802 // ID
#define VER 0x803 // Version
#define TPR 0x808 // Task Priority
#define EOI 0x80b // EOI
#define SVR 0x80f // Spurious Interrupt Vector
#define ENABLE 0x00000100 // Unit Enable
#define IRR 0x820
#define ISR 0x810
#define ISR_NR 0x8
#define ESR 0x828ull // Error Status
#define ICR 0x830ull // Interrupt Command
#define INIT 0x00000500ull // INIT/RESET
#define STARTUP 0x00000600 // Startup IPI
#define BCAST 0x00080000 // Send to all APICs, including self.
#define LEVEL 0x00008000ull // Level triggered
#define ASSERT 0x00004000 // Assert interrupt (vs deassert)
#define TIMER 0x832 // Local Vector Table 0 (TIMER)
#define X1 0x0000000B // divide counts by 1
#define PERIODIC 0x00020000 // Periodic
#define PCINT 0x834 // Performance Counter LVT
#define LINT0 0x835 // Local Vector Table 1 (LINT0)
#define LINT1 0x836 // Local Vector Table 2 (LINT1)
#define ERROR 0x837 // Local Vector Table 3 (ERROR)
#define MASKED 0x00010000 // Interrupt masked
#define MT_EXTINT 0x00000500
#define MT_NMI 0x00000400 // NMI message type
#define MT_FIX 0x00000000 // Fixed message type
#define TICR 0x838 // Timer Initial Count
#define TCCR 0x839 // Timer Current Count
#define TDCR 0x83e // Timer Divide Configuration
static console_stream verbose(true);
static u64 x2apichz;
class x2apic_lapic : public abstract_lapic
{
public:
void cpu_init();
hwid_t id();
void eoi();
void send_ipi(struct cpu *c, int ino);
void mask_pc(bool mask);
void start_ap(struct cpu *c, u32 addr);
private:
void clearintr();
};
static int
x2apicmaxlvt(void)
{
unsigned int v;
v = readmsr(VER);
return (((v) >> 16) & 0xFFu);
}
void
x2apic_lapic::eoi()
{
writemsr(EOI, 0);
}
static int
x2apicwait(void)
{
// Do nothing on x2apic
return 0;
}
// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
int i;
// Be paranoid about clearing APIC errors
writemsr(ESR, 0);
readmsr(ESR);
unsigned long accept_status;
int maxlvt = x2apicmaxlvt();
if (maxlvt > 3)
writemsr(ESR, 0);
readmsr(ESR);
// "Universal startup algorithm."
// Send INIT (level-triggered) interrupt to reset other CPU.
// Asserting INIT
writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
microdelay(10000);
// Deasserting INIT
writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
x2apicwait();
// Send startup IPI (twice!) to enter bootstrap code.
// Regular hardware is supposed to only accept a STARTUP
// when it is in the halted state due to an INIT. So the second
// should be ignored, but it is part of the official Intel algorithm.
for(i = 0; i < 2; i++){
writemsr(ESR, 0);
readmsr(ESR);
// Kick the target chip
writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
// Linux gives 300 usecs to accept the IPI..
microdelay(300);
x2apicwait();
// ..then it gives some more time
microdelay(200);
if (maxlvt > 3)
writemsr(ESR, 0);
accept_status = (readmsr(ESR) & 0xEF);
if (accept_status)
panic("x2apicstartap: accept status %lx", accept_status);
}
}
void
x2apic_lapic::mask_pc(bool mask)
{
writemsr(PCINT, mask ? MASKED : MT_NMI);
}
void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
panic("x2apic_lapic::send_ipi not implemented");
}
hwid_t
x2apic_lapic::id()
{
u64 id = readmsr(ID);
return HWID((u32)id);
}
void
x2apic_lapic::clearintr()
{
// Clear any pending interrupts. Linux does this.
unsigned int value, queued;
int i, j, acked = 0;
unsigned long long tsc = 0, ntsc;
long long max_loops = 2400000;
tsc = rdtsc();
do {
queued = 0;
for (i = ISR_NR - 1; i >= 0; i--)
queued |= readmsr(IRR + i*0x1);
for (i = ISR_NR - 1; i >= 0; i--) {
value = readmsr(ISR + i*0x1);
for (j = 31; j >= 0; j--) {
if (value & (1<<j)) {
eoi();
acked++;
}
}
}
if (acked > 256) {
cprintf("x2apic pending interrupts after %d EOI\n",
acked);
break;
}
ntsc = rdtsc();
max_loops = (2400000 << 10) - (ntsc - tsc);
} while (queued && max_loops > 0);
}
// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
u64 count;
u32 value;
int maxlvt;
verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");
// Enable performance counter overflow interrupts for sampler.cc
mask_pc(false);
// Enable interrupts on the APIC (but not on the processor).
value = readmsr(TPR);
value &= ~0xffU;
writemsr(TPR, value);
clearintr();
// Enable local APIC; set spurious interrupt vector.
value = readmsr(SVR);
value &= ~0x000FF;
value |= ENABLE;
value |= T_IRQ0 + IRQ_SPURIOUS;
writemsr(SVR, value);
writemsr(LINT0, MT_EXTINT | MASKED);
if (readmsr(ID) == 0)
writemsr(LINT1, MT_NMI);
else
writemsr(LINT1, MT_NMI | MASKED);
maxlvt = x2apicmaxlvt();
if (maxlvt > 3)
writemsr(ESR, 0);
// enables sending errors
value = T_IRQ0 + IRQ_ERROR;
writemsr(ERROR, value);
if (maxlvt > 3)
writemsr(ESR, 0);
readmsr(ESR);
// Send an Init Level De-Assert to synchronise arbitration ID's.
writemsr(ICR, BCAST | INIT | LEVEL);
if (x2apichz == 0) {
// Measure the TICR frequency
writemsr(TDCR, X1);
writemsr(TICR, 0xffffffff);
u64 ccr0 = readmsr(TCCR);
microdelay(10 * 1000); // 1/100th of a second
u64 ccr1 = readmsr(TCCR);
x2apichz = 100 * (ccr0 - ccr1);
}
count = (QUANTUM*x2apichz) / 1000;
if (count > 0xffffffff)
panic("initx2apic: QUANTUM too large");
// The timer repeatedly counts down at bus frequency
// from xapic[TICR] and then issues an interrupt.
writemsr(TDCR, X1);
writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
writemsr(TICR, count);
// Clear error status register (requires back-to-back writes).
writemsr(ESR, 0);
writemsr(ESR, 0);
// Ack any outstanding interrupts.
writemsr(EOI, 0);
return;
}
bool
initlapic_x2apic(void)
{
u32 edx;
cpuid(CPUID_FEATURES, nullptr, nullptr, nullptr, &edx);
if (!(edx & FEATURE_ECX_X2APIC))
return false;
// According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
// logical processors with APIC IDs greater than 255, then it should
// enable the x2APIC.
u64 apic_bar = readmsr(MSR_APIC_BAR);
if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
return false;
verbose.println("x2apic: Using x2APIC LAPIC");
static x2apic_lapic apic;
lapic = &apic;
return true;
}
<commit_msg>x2apic: Implement send_ipi<commit_after>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#define ID 0x802 // ID
#define VER 0x803 // Version
#define TPR 0x808 // Task Priority
#define EOI 0x80b // EOI
#define SVR 0x80f // Spurious Interrupt Vector
#define ENABLE 0x00000100 // Unit Enable
#define IRR 0x820
#define ISR 0x810
#define ISR_NR 0x8
#define ESR 0x828ull // Error Status
#define ICR 0x830ull // Interrupt Command
#define INIT 0x00000500ull // INIT/RESET
#define STARTUP 0x00000600 // Startup IPI
#define BCAST 0x00080000 // Send to all APICs, including self.
#define LEVEL 0x00008000ull // Level triggered
#define ASSERT 0x00004000 // Assert interrupt (vs deassert)
#define DEASSERT 0x00000000
#define FIXED 0x00000000
#define TIMER 0x832 // Local Vector Table 0 (TIMER)
#define X1 0x0000000B // divide counts by 1
#define PERIODIC 0x00020000 // Periodic
#define PCINT 0x834 // Performance Counter LVT
#define LINT0 0x835 // Local Vector Table 1 (LINT0)
#define LINT1 0x836 // Local Vector Table 2 (LINT1)
#define ERROR 0x837 // Local Vector Table 3 (ERROR)
#define MASKED 0x00010000 // Interrupt masked
#define MT_EXTINT 0x00000500
#define MT_NMI 0x00000400 // NMI message type
#define MT_FIX 0x00000000 // Fixed message type
#define TICR 0x838 // Timer Initial Count
#define TCCR 0x839 // Timer Current Count
#define TDCR 0x83e // Timer Divide Configuration
static console_stream verbose(true);
static u64 x2apichz;
class x2apic_lapic : public abstract_lapic
{
public:
void cpu_init();
hwid_t id();
void eoi();
void send_ipi(struct cpu *c, int ino);
void mask_pc(bool mask);
void start_ap(struct cpu *c, u32 addr);
private:
void clearintr();
};
static int
x2apicmaxlvt(void)
{
unsigned int v;
v = readmsr(VER);
return (((v) >> 16) & 0xFFu);
}
void
x2apic_lapic::eoi()
{
writemsr(EOI, 0);
}
static int
x2apicwait(void)
{
// Do nothing on x2apic
return 0;
}
// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
int i;
// Be paranoid about clearing APIC errors
writemsr(ESR, 0);
readmsr(ESR);
unsigned long accept_status;
int maxlvt = x2apicmaxlvt();
if (maxlvt > 3)
writemsr(ESR, 0);
readmsr(ESR);
// "Universal startup algorithm."
// Send INIT (level-triggered) interrupt to reset other CPU.
// Asserting INIT
writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
microdelay(10000);
// Deasserting INIT
writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
x2apicwait();
// Send startup IPI (twice!) to enter bootstrap code.
// Regular hardware is supposed to only accept a STARTUP
// when it is in the halted state due to an INIT. So the second
// should be ignored, but it is part of the official Intel algorithm.
for(i = 0; i < 2; i++){
writemsr(ESR, 0);
readmsr(ESR);
// Kick the target chip
writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
// Linux gives 300 usecs to accept the IPI..
microdelay(300);
x2apicwait();
// ..then it gives some more time
microdelay(200);
if (maxlvt > 3)
writemsr(ESR, 0);
accept_status = (readmsr(ESR) & 0xEF);
if (accept_status)
panic("x2apicstartap: accept status %lx", accept_status);
}
}
void
x2apic_lapic::mask_pc(bool mask)
{
writemsr(PCINT, mask ? MASKED : MT_NMI);
}
void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
writemsr(ICR, (((u64)c->hwid.num)<<32) | FIXED | DEASSERT | ino);
}
hwid_t
x2apic_lapic::id()
{
u64 id = readmsr(ID);
return HWID((u32)id);
}
void
x2apic_lapic::clearintr()
{
// Clear any pending interrupts. Linux does this.
unsigned int value, queued;
int i, j, acked = 0;
unsigned long long tsc = 0, ntsc;
long long max_loops = 2400000;
tsc = rdtsc();
do {
queued = 0;
for (i = ISR_NR - 1; i >= 0; i--)
queued |= readmsr(IRR + i*0x1);
for (i = ISR_NR - 1; i >= 0; i--) {
value = readmsr(ISR + i*0x1);
for (j = 31; j >= 0; j--) {
if (value & (1<<j)) {
eoi();
acked++;
}
}
}
if (acked > 256) {
cprintf("x2apic pending interrupts after %d EOI\n",
acked);
break;
}
ntsc = rdtsc();
max_loops = (2400000 << 10) - (ntsc - tsc);
} while (queued && max_loops > 0);
}
// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
u64 count;
u32 value;
int maxlvt;
verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");
// Enable performance counter overflow interrupts for sampler.cc
mask_pc(false);
// Enable interrupts on the APIC (but not on the processor).
value = readmsr(TPR);
value &= ~0xffU;
writemsr(TPR, value);
clearintr();
// Enable local APIC; set spurious interrupt vector.
value = readmsr(SVR);
value &= ~0x000FF;
value |= ENABLE;
value |= T_IRQ0 + IRQ_SPURIOUS;
writemsr(SVR, value);
writemsr(LINT0, MT_EXTINT | MASKED);
if (readmsr(ID) == 0)
writemsr(LINT1, MT_NMI);
else
writemsr(LINT1, MT_NMI | MASKED);
maxlvt = x2apicmaxlvt();
if (maxlvt > 3)
writemsr(ESR, 0);
// enables sending errors
value = T_IRQ0 + IRQ_ERROR;
writemsr(ERROR, value);
if (maxlvt > 3)
writemsr(ESR, 0);
readmsr(ESR);
// Send an Init Level De-Assert to synchronise arbitration ID's.
writemsr(ICR, BCAST | INIT | LEVEL);
if (x2apichz == 0) {
// Measure the TICR frequency
writemsr(TDCR, X1);
writemsr(TICR, 0xffffffff);
u64 ccr0 = readmsr(TCCR);
microdelay(10 * 1000); // 1/100th of a second
u64 ccr1 = readmsr(TCCR);
x2apichz = 100 * (ccr0 - ccr1);
}
count = (QUANTUM*x2apichz) / 1000;
if (count > 0xffffffff)
panic("initx2apic: QUANTUM too large");
// The timer repeatedly counts down at bus frequency
// from xapic[TICR] and then issues an interrupt.
writemsr(TDCR, X1);
writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
writemsr(TICR, count);
// Clear error status register (requires back-to-back writes).
writemsr(ESR, 0);
writemsr(ESR, 0);
// Ack any outstanding interrupts.
writemsr(EOI, 0);
return;
}
bool
initlapic_x2apic(void)
{
u32 edx;
cpuid(CPUID_FEATURES, nullptr, nullptr, nullptr, &edx);
if (!(edx & FEATURE_ECX_X2APIC))
return false;
// According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
// logical processors with APIC IDs greater than 255, then it should
// enable the x2APIC.
u64 apic_bar = readmsr(MSR_APIC_BAR);
if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
return false;
verbose.println("x2apic: Using x2APIC LAPIC");
static x2apic_lapic apic;
lapic = &apic;
return true;
}
<|endoftext|>
|
<commit_before>#include "sstream.h"
#include "vendor/Catch/catch.hpp"
namespace
{
TEST_CASE("sstream", "[string][stream]")
{
SECTION("Initialization")
{
SECTION("Default ctor")
{
rde::stringstream ss1;
CHECK(!ss1.good());
auto ss2 = rde::stringstream();
CHECK(!ss2.good());
}
SECTION("With value_type ctor")
{
rde::stringstream ss("1");
CHECK(ss.good());
}
SECTION("With string_type ctor")
{
rde::string s("1");
rde::stringstream ss(s);
CHECK(ss.good());
}
SECTION("With inline string_type ctor")
{
rde::stringstream ss(rde::string("1"));
CHECK(ss.good());
}
}
SECTION("Good/EOF")
{
rde::stringstream ss1("1");
CHECK(ss1.good() == true);
CHECK(ss1.eof() == false);
rde::stringstream ss2;
CHECK(ss2.good() == false);
CHECK(ss2.eof() == true);
}
SECTION("Whitespace/Trim")
{
rde::stringstream ss("1");
REQUIRE(ss.good() == true);
SECTION("A non-null string with strlen > 0 containing only whitespace characters != good()")
{
ss = rde::stringstream();
CHECK(ss.good() == false);
ss = rde::stringstream(" ");
CHECK(ss.good() == false);
ss = rde::stringstream(" ");
CHECK(ss.good() == false);
ss = rde::stringstream(" \t\r\n");
CHECK(ss.good() == false);
}
}
SECTION("Reset")
{
rde::stringstream ss("1");
REQUIRE(ss.good() == true);
ss.reset();
CHECK(ss.good() == false);
ss.reset("1");
CHECK(ss.good() == true);
ss.reset("");
CHECK(ss.good() == false);
}
SECTION("Operator bool and !bool")
{
bool isgood = false;
bool isbad = true;
SECTION("implicit bool conversions work as expected")
{
rde::stringstream ssGood("1");
CHECK(ssGood);
rde::stringstream ssBad("");
CHECK(!ssBad);
CHECK(rde::stringstream("1"));
CHECK(!rde::stringstream(""));
}
SECTION("ternary operator")
{
rde::stringstream ssGood("1");
rde::stringstream ssBad;
isgood = ssGood ? true : false;
isbad = !ssGood ? true : false;
CHECK(isgood == true);
CHECK(isbad == false);
isgood = ssBad ? true : false;
isbad = !ssBad ? true : false;
CHECK(isgood == false);
CHECK(isbad == true);
}
SECTION("if statement")
{
rde::stringstream ssGood("1");
if (ssGood)
isgood = true;
else isgood = false;
CHECK(isgood == true);
rde::stringstream ssBad;
if (ssBad)
isbad = false;
else isbad = true;
CHECK(isbad == true);
}
SECTION("inline assignment inside if statement")
{
rde::stringstream ss;
if ((ss = rde::stringstream("1")))
isgood = true;
else isgood = false;
REQUIRE(ss.good() == true);
CHECK(isgood == true);
if (!(ss = rde::stringstream("1")))
isgood = false;
else isgood = true;
REQUIRE(ss.good() == true);
CHECK(isgood == true);
if ((ss = rde::stringstream()))
isbad = false;
else isbad = true;
REQUIRE(ss.good() == false);
CHECK(isbad == true);
if (!(ss = rde::stringstream()))
isbad = true;
else isbad = false;
REQUIRE(ss.good() == false);
CHECK(isbad == true);
}
SECTION("illegal comparisons should not compile")
{
rde::stringstream ssGood("1");
rde::stringstream ssBad("");
bool shouldbefalse = false;
//
// NOTE:
// The following assertions should not compile!
// If tests build with them uncommented, that means
// the compiler is incorrectly performing an implicit conversion
// from `stringstream` to `bool` in order to satisfy an illegal
// comparison between different types. ~SK
//
//shouldbefalse = ssBad == false;
//shouldbefalse = ssBad != true;
//shouldbefalse = ssGood == true;
//shouldbefalse = ssGood != false;
//CHECK(ssGood == true);
//CHECK(ssBad == false);
REQUIRE(shouldbefalse == false);
}
}
SECTION("Output Operators with empty stringstream")
{
rde::stringstream ss("");
int x(123);
ss >> x;
REQUIRE(x == 123);
x = 321;
ss.reset(NULL);
ss >> x;
REQUIRE(x == 321);
x = 321;
ss.reset("456");
ss >> x;
REQUIRE(x == 456);
}
SECTION("Basic")
{
rde::stringstream ss("42");
int x(0);
ss >> x;
REQUIRE(x == 42);
ss.reset("4242.4242");
float y(0);
ss >> y;
REQUIRE(y == 4242.4242f);
ss.reset("-1");
long z(0);
ss >> z;
REQUIRE(z == -1);
ss.reset("helloworld");
rde::string w;
ss >> w;
REQUIRE(w.compare(rde::string("helloworld")) == 0);
}
SECTION("Mixed")
{
int x(0);
float y(0.0f);
rde::string z;
rde::stringstream ss(" 1 2.34 hello\r\nworld 4 ");
ss >> x;
REQUIRE(x == 1);
ss >> y;
REQUIRE(y == 2.34f);
ss >> z;
REQUIRE(z.compare(rde::string("hello")) == 0);
ss >> z;
REQUIRE(z.compare(rde::string("world")) == 0);
ss >> x;
REQUIRE(x == 4);
}
}
} //namespace
<commit_msg>Update StringStreamTest.cpp<commit_after>#include "sstream.h"
#include "vendor/Catch/catch.hpp"
namespace
{
TEST_CASE("sstream", "[string][stream]")
{
SECTION("Initialization")
{
int x(0);
SECTION("Default ctor")
{
rde::stringstream ss;
CHECK(!ss.good());
ss >> x;
CHECK(x == 0);
}
SECTION("With value_type ctor")
{
const char* ch = "1";
rde::stringstream ss1(ch);
CHECK(ss1.good());
ss1 >> x;
CHECK(x == 1);
rde::stringstream ss2("2");
CHECK(ss2.good());
ss2 >> x;
CHECK(x == 2);
}
SECTION("With string_type ctor")
{
rde::string s("1");
rde::stringstream ss1(s);
CHECK(ss1.good());
ss1 >> x;
CHECK(x == 1);
rde::stringstream ss2(rde::string("2"));
CHECK(ss2.good());
ss2 >> x;
CHECK(x == 2);
}
}
SECTION("Good/EOF")
{
rde::stringstream ss1("1");
CHECK(ss1.good() == true);
CHECK(ss1.eof() == false);
rde::stringstream ss2;
CHECK(ss2.good() == false);
CHECK(ss2.eof() == true);
}
SECTION("Whitespace/Trim")
{
rde::stringstream ss("1");
REQUIRE(ss.good() == true);
SECTION("A non-null string with strlen > 0 containing only whitespace characters != good()")
{
ss = rde::stringstream();
CHECK(ss.good() == false);
ss = rde::stringstream(" ");
CHECK(ss.good() == false);
ss = rde::stringstream(" ");
CHECK(ss.good() == false);
ss = rde::stringstream(" \t\r\n");
CHECK(ss.good() == false);
}
}
SECTION("Reset")
{
rde::stringstream ss("1");
REQUIRE(ss.good() == true);
ss.reset();
CHECK(ss.good() == false);
ss.reset("1");
CHECK(ss.good() == true);
ss.reset("");
CHECK(ss.good() == false);
}
// https://github.com/msinilo/rdestl/issues/13
SECTION("Operator bool and !bool")
{
bool isgood = false;
bool isbad = true;
SECTION("Implicit bool conversions work as expected")
{
rde::stringstream ssGood("1");
CHECK(ssGood);
rde::stringstream ssBad("");
CHECK(!ssBad);
CHECK(rde::stringstream("1"));
CHECK(!rde::stringstream(""));
}
SECTION("Ternary operator")
{
rde::stringstream ssGood("1");
rde::stringstream ssBad;
isgood = ssGood ? true : false;
isbad = !ssGood ? true : false;
CHECK(isgood == true);
CHECK(isbad == false);
isgood = ssBad ? true : false;
isbad = !ssBad ? true : false;
CHECK(isgood == false);
CHECK(isbad == true);
}
SECTION("If statement")
{
rde::stringstream ssGood("1");
if (ssGood)
isgood = true;
else isgood = false;
CHECK(isgood == true);
rde::stringstream ssBad;
if (ssBad)
isbad = false;
else isbad = true;
CHECK(isbad == true);
}
SECTION("Inline assignment inside if statement")
{
rde::stringstream ss;
if ((ss = rde::stringstream("1")))
isgood = true;
else isgood = false;
REQUIRE(ss.good() == true);
CHECK(isgood == true);
if (!(ss = rde::stringstream("1")))
isgood = false;
else isgood = true;
REQUIRE(ss.good() == true);
CHECK(isgood == true);
if ((ss = rde::stringstream()))
isbad = false;
else isbad = true;
REQUIRE(ss.good() == false);
CHECK(isbad == true);
if (!(ss = rde::stringstream()))
isbad = true;
else isbad = false;
REQUIRE(ss.good() == false);
CHECK(isbad == true);
}
SECTION("Illegal comparisons should not compile")
{
rde::stringstream ssGood("1");
rde::stringstream ssBad("");
bool shouldbefalse = false;
//
// NOTE:
// The following assertions should not compile!
// If tests build with them uncommented, that means
// the compiler is incorrectly performing an implicit conversion
// from `stringstream` to `bool` in order to satisfy an illegal
// comparison between different types. ~SK
//
//shouldbefalse = ssBad == false;
//shouldbefalse = ssBad != true;
//shouldbefalse = ssGood == true;
//shouldbefalse = ssGood != false;
//CHECK(ssGood == true);
//CHECK(ssBad == false);
REQUIRE(shouldbefalse == false);
}
}
SECTION("Output Operators with empty stringstream")
{
rde::stringstream ss("");
int x(123);
ss >> x;
REQUIRE(x == 123);
x = 321;
ss.reset(NULL);
ss >> x;
REQUIRE(x == 321);
x = 321;
ss.reset("456");
ss >> x;
REQUIRE(x == 456);
}
SECTION("Basic")
{
rde::stringstream ss("42");
int x(0);
ss >> x;
REQUIRE(x == 42);
ss.reset("4242.4242");
float y(0);
ss >> y;
REQUIRE(y == 4242.4242f);
ss.reset("-1");
long z(0);
ss >> z;
REQUIRE(z == -1);
ss.reset("helloworld");
rde::string w;
ss >> w;
REQUIRE(w.compare(rde::string("helloworld")) == 0);
}
SECTION("Mixed")
{
int x(0);
float y(0.0f);
rde::string z;
rde::stringstream ss(" 1 2.34 hello\r\nworld 4 ");
ss >> x;
REQUIRE(x == 1);
ss >> y;
REQUIRE(y == 2.34f);
ss >> z;
REQUIRE(z.compare(rde::string("hello")) == 0);
ss >> z;
REQUIRE(z.compare(rde::string("world")) == 0);
ss >> x;
REQUIRE(x == 4);
}
}
} //namespace
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
void Shutdown(void* parg)
{
exit(0);
}
<commit_msg>Global fixture to send output to console instead of debug.log<commit_after>#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "main.h"
#include "wallet.h"
extern bool fPrintToConsole;
struct TestingSetup {
TestingSetup() {
fPrintToConsole = true; // don't want to write to debug.log file
}
~TestingSetup() { }
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
CWallet* pwalletMain;
void Shutdown(void* parg)
{
exit(0);
}
<|endoftext|>
|
<commit_before>#ifndef VG_SNARL_CALLER_HPP_INCLUDED
#define VG_SNARL_CALLER_HPP_INCLUDED
#include <iostream>
#include <algorithm>
#include <functional>
#include <cmath>
#include <limits>
#include <unordered_set>
#include <tuple>
#include "handle.hpp"
#include "snarls.hpp"
#include "genotypekit.hpp"
#include "packer.hpp"
namespace vg {
using namespace std;
/**
* SnarlCaller: Given a list of traversals through a site, come up with a genotype
* come up with a genotype
*/
class SnarlCaller {
public:
virtual ~SnarlCaller();
/// Get the genotype of a site
virtual vector<int> genotype(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
int ref_trav_idx,
int ploidy) = 0;
/// Update INFO and FORMAT fields of the called variant
virtual void update_vcf_info(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
const vector<int>& genotype,
const string& sample_name,
vcflib::Variant& variant) = 0;
/// Define any header fields needed by the above
virtual void update_vcf_header(string& header) const = 0;
};
/**
* Find the genotype of some traversals in a site using read support
*/
class SupportBasedSnarlCaller : public SnarlCaller {
public:
SupportBasedSnarlCaller(const PathHandleGraph& graph, SnarlManager& snarl_manager);
virtual ~SupportBasedSnarlCaller();
/// Support of an edge
virtual Support get_edge_support(const edge_t& edge) const = 0;
virtual Support get_edge_support(id_t from, bool from_reverse, id_t to, bool to_reverse) const = 0;
/// Effective length of an edge
virtual int64_t get_edge_length(const edge_t& edge) const;
/// Minimum support of a node
virtual Support get_min_node_support(id_t node) const = 0;
/// Average support of a node
virtual Support get_avg_node_support(id_t node) const = 0;
/// Use node or edge support as proxy for child support (as was done in original calling code)
virtual tuple<Support, Support, int> get_child_support(const Snarl& snarl) const;
/// Get the genotype of a site
virtual vector<int> genotype(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
int ref_trav_idx,
int ploidy);
/// Update INFO and FORMAT fields of the called variant
virtual void update_vcf_info(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
const vector<int>& genotype,
const string& sample_name,
vcflib::Variant& variant);
/// Define any header fields needed by the above
virtual void update_vcf_header(string& header) const;
/// Get the support of a traversal
/// Child snarls are handled as in the old call code: their maximum support is used
virtual Support get_traversal_support(const SnarlTraversal& traversal) const;
/// Get the support of a set of traversals. Any support overlapping traversals in shared_travs
/// will have their support split. If exclusive_only is true, then any split support gets
/// rounded down to 0
virtual vector<Support> get_traversal_set_support(const vector<SnarlTraversal>& traversals,
const vector<int>& shared_travs,
bool exclusive_only) const;
/// Get the total length of all nodes in the traversal
virtual vector<int> get_traversal_sizes(const vector<SnarlTraversal>& traversals) const;
protected:
/// Get the best support out of a list of supports, ignoring skips
static int get_best_support(const vector<Support>& supports, const vector<int>& skips);
/// Relic from old code
static double support_val(const Support& support) { return total(support); };
/// Get the bias used to for comparing two traversals
/// (It differrs heuristically depending whether they are alt/ref/het/hom/snp/indel
/// see tuning parameters below)
double get_bias(const vector<int>& traversal_sizes, int best_trav,
int second_best_trav, int ref_trav_idx) const;
/// Tuning
/// What's the minimum integer number of reads that must support a call? We
/// don't necessarily want to call a SNP as het because we have a single
// supporting read, even if there are only 10 reads on the site.
int min_total_support_for_call = 1;
/// What fraction of the reads supporting an alt are we willing to discount?
/// At 2, if twice the reads support one allele as the other, we'll call
/// homozygous instead of heterozygous. At infinity, every call will be
/// heterozygous if even one read supports each allele.
double max_het_bias = 10;
/// Like above, but applied to ref / alt ratio (instead of alt / ref)
double max_ref_het_bias = 4.5;
/// Like the max het bias, but applies to novel indels.
double max_indel_het_bias =3;
/// what's the minimum ref or alt allele depth to give a PASS in the filter
/// column? Also used as a min actual support for a second-best allele call
size_t min_mad_for_filter = 1;
/// what's the min log likelihood for allele depth assignments to PASS?
double min_ad_log_likelihood_for_filter = -9;
/// Use average instead of minimum support when determining a traversal's support
/// its node and edge supports.
size_t average_traversal_support_switch_threshold = 10;
/// Use average instead of minimum support when determining a node's support
/// its position supports.
size_t average_node_support_switch_threshold = 10;
const PathHandleGraph& graph;
SnarlManager& snarl_manager;
// todo: background support
};
/**
* Get the read support from a Packer object
*/
class PackedSupportSnarlCaller : public SupportBasedSnarlCaller {
public:
PackedSupportSnarlCaller(const Packer& packer, SnarlManager& snarl_manager);
virtual ~PackedSupportSnarlCaller();
/// Support of an edge
virtual Support get_edge_support(const edge_t& edge) const;
virtual Support get_edge_support(id_t from, bool from_reverse, id_t to, bool to_reverse) const;
/// Minimum support of a node
virtual Support get_min_node_support(id_t node) const;
/// Average support of a node
virtual Support get_avg_node_support(id_t node) const;
protected:
/// Derive supports from this pack index
const Packer& packer;
};
// debug helpers
inline string to_string(const HandleGraph& graph, handle_t handle) {
return std::to_string(graph.get_id(handle)) + ":" + std::to_string(graph.get_is_reverse(handle));
}
inline string to_string(const HandleGraph& graph, edge_t edge) {
return to_string(graph, edge.first) + " -> " + to_string(graph, edge.second);
}
}
#endif
<commit_msg>adjust indel bias to work better on sv tests<commit_after>#ifndef VG_SNARL_CALLER_HPP_INCLUDED
#define VG_SNARL_CALLER_HPP_INCLUDED
#include <iostream>
#include <algorithm>
#include <functional>
#include <cmath>
#include <limits>
#include <unordered_set>
#include <tuple>
#include "handle.hpp"
#include "snarls.hpp"
#include "genotypekit.hpp"
#include "packer.hpp"
namespace vg {
using namespace std;
/**
* SnarlCaller: Given a list of traversals through a site, come up with a genotype
* come up with a genotype
*/
class SnarlCaller {
public:
virtual ~SnarlCaller();
/// Get the genotype of a site
virtual vector<int> genotype(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
int ref_trav_idx,
int ploidy) = 0;
/// Update INFO and FORMAT fields of the called variant
virtual void update_vcf_info(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
const vector<int>& genotype,
const string& sample_name,
vcflib::Variant& variant) = 0;
/// Define any header fields needed by the above
virtual void update_vcf_header(string& header) const = 0;
};
/**
* Find the genotype of some traversals in a site using read support
*/
class SupportBasedSnarlCaller : public SnarlCaller {
public:
SupportBasedSnarlCaller(const PathHandleGraph& graph, SnarlManager& snarl_manager);
virtual ~SupportBasedSnarlCaller();
/// Support of an edge
virtual Support get_edge_support(const edge_t& edge) const = 0;
virtual Support get_edge_support(id_t from, bool from_reverse, id_t to, bool to_reverse) const = 0;
/// Effective length of an edge
virtual int64_t get_edge_length(const edge_t& edge) const;
/// Minimum support of a node
virtual Support get_min_node_support(id_t node) const = 0;
/// Average support of a node
virtual Support get_avg_node_support(id_t node) const = 0;
/// Use node or edge support as proxy for child support (as was done in original calling code)
virtual tuple<Support, Support, int> get_child_support(const Snarl& snarl) const;
/// Get the genotype of a site
virtual vector<int> genotype(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
int ref_trav_idx,
int ploidy);
/// Update INFO and FORMAT fields of the called variant
virtual void update_vcf_info(const Snarl& snarl,
const vector<SnarlTraversal>& traversals,
const vector<int>& genotype,
const string& sample_name,
vcflib::Variant& variant);
/// Define any header fields needed by the above
virtual void update_vcf_header(string& header) const;
/// Get the support of a traversal
/// Child snarls are handled as in the old call code: their maximum support is used
virtual Support get_traversal_support(const SnarlTraversal& traversal) const;
/// Get the support of a set of traversals. Any support overlapping traversals in shared_travs
/// will have their support split. If exclusive_only is true, then any split support gets
/// rounded down to 0
virtual vector<Support> get_traversal_set_support(const vector<SnarlTraversal>& traversals,
const vector<int>& shared_travs,
bool exclusive_only) const;
/// Get the total length of all nodes in the traversal
virtual vector<int> get_traversal_sizes(const vector<SnarlTraversal>& traversals) const;
protected:
/// Get the best support out of a list of supports, ignoring skips
static int get_best_support(const vector<Support>& supports, const vector<int>& skips);
/// Relic from old code
static double support_val(const Support& support) { return total(support); };
/// Get the bias used to for comparing two traversals
/// (It differrs heuristically depending whether they are alt/ref/het/hom/snp/indel
/// see tuning parameters below)
double get_bias(const vector<int>& traversal_sizes, int best_trav,
int second_best_trav, int ref_trav_idx) const;
/// Tuning
/// What's the minimum integer number of reads that must support a call? We
/// don't necessarily want to call a SNP as het because we have a single
// supporting read, even if there are only 10 reads on the site.
int min_total_support_for_call = 1;
/// What fraction of the reads supporting an alt are we willing to discount?
/// At 2, if twice the reads support one allele as the other, we'll call
/// homozygous instead of heterozygous. At infinity, every call will be
/// heterozygous if even one read supports each allele.
double max_het_bias = 10;
/// Like above, but applied to ref / alt ratio (instead of alt / ref)
double max_ref_het_bias = 4.5;
/// Like the max het bias, but applies to novel indels.
double max_indel_het_bias = 6;
/// what's the minimum ref or alt allele depth to give a PASS in the filter
/// column? Also used as a min actual support for a second-best allele call
size_t min_mad_for_filter = 1;
/// what's the min log likelihood for allele depth assignments to PASS?
double min_ad_log_likelihood_for_filter = -9;
/// Use average instead of minimum support when determining a traversal's support
/// its node and edge supports.
size_t average_traversal_support_switch_threshold = 10;
/// Use average instead of minimum support when determining a node's support
/// its position supports.
size_t average_node_support_switch_threshold = 10;
const PathHandleGraph& graph;
SnarlManager& snarl_manager;
// todo: background support
};
/**
* Get the read support from a Packer object
*/
class PackedSupportSnarlCaller : public SupportBasedSnarlCaller {
public:
PackedSupportSnarlCaller(const Packer& packer, SnarlManager& snarl_manager);
virtual ~PackedSupportSnarlCaller();
/// Support of an edge
virtual Support get_edge_support(const edge_t& edge) const;
virtual Support get_edge_support(id_t from, bool from_reverse, id_t to, bool to_reverse) const;
/// Minimum support of a node
virtual Support get_min_node_support(id_t node) const;
/// Average support of a node
virtual Support get_avg_node_support(id_t node) const;
protected:
/// Derive supports from this pack index
const Packer& packer;
};
// debug helpers
inline string to_string(const HandleGraph& graph, handle_t handle) {
return std::to_string(graph.get_id(handle)) + ":" + std::to_string(graph.get_is_reverse(handle));
}
inline string to_string(const HandleGraph& graph, edge_t edge) {
return to_string(graph, edge.first) + " -> " + to_string(graph, edge.second);
}
}
#endif
<|endoftext|>
|
<commit_before>//
// dfa_single_regex.cpp
// Parse
//
// Created by Andrew Hunter on 28/04/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <string>
#include <sstream>
#include "dfa_single_regex.h"
#include "Dfa/lexer.h"
using namespace std;
using namespace dfa;
void test_dfa_single_regex::test(std::string name, std::string regex, std::string accepting, std::string rejecting) {
// Create a lexer that accepts the regular expression
lexer myLexer;
myLexer.add_symbol(regex, 1);
lexer myCompactLexer;
myCompactLexer.add_symbol(regex, 1);
// Compile it
myLexer.compile(false);
myCompactLexer.compile(true);
// Try the accepting phrase
stringstream acceptIn(accepting);
lexeme_stream* stream = myLexer.create_stream_from(acceptIn);
// Get the first lexeme
lexeme* first;
(*stream) >> first;
delete stream;
// Try again with the compact lexer
stringstream acceptCompactIn(accepting);
stream = myCompactLexer.create_stream_from(acceptCompactIn);
lexeme* firstCompact;
(*stream) >> firstCompact;
delete stream;
// Try the rejecting phrase
stringstream rejectIn(rejecting);
stream = myLexer.create_stream_from(rejectIn);
lexeme* fail;
(*stream) >> fail;
delete stream;
// first lexeme should be an accepting lexeme, second should be a rejection
if (first != NULL && fail != NULL && first->matched() == 1 && first->content<char>() == accepting
&& firstCompact != NULL && firstCompact->matched() == 1 && firstCompact->content<char>() == accepting
&& fail != NULL && fail->matched() == -1 && fail->content().size() == 1) {
report(name, true);
} else {
// Break things down if we get a failure
report(name + "-accept", first != NULL && first->matched() == 1);
report(name + "-content", first != NULL && first->content<char>() == accepting);
report(name + "-compact-accept", firstCompact != NULL && firstCompact->matched() == 1);
report(name + "-compact-content", firstCompact != NULL && firstCompact->content<char>() == accepting);
report(name + "-reject", fail != NULL && fail->matched() == -1);
report(name + "-rejectone", fail != NULL && fail->content().size() == 1);
}
delete first;
delete firstCompact;
delete fail;
}
void test_dfa_single_regex::run_tests() {
test("basic", "a", "a", "b");
test("sayaaaa", "a*", "aaaaa", "b");
test("ababab", "(ab)+", "ababab", "aaaaaa");
test("nothing1", "a", "a", "");
test("nothing2", "[a]", "a", "");
test("nothing3", "[^a]", "b", "");
test("nothing4", "[a]+", "aaa", "");
// test("nothing5", "[^a]+", "aaa", ""); // Infinite loop!
test("nothing6", "(a|b)", "a", "");
test("nothing7", "(a|\\ufffe)", "a", "");
test("nothing8", "(a|\\uffff)", "a", "");
test("a-or-b1", "a|b", "a", "c");
test("a-or-b2", "a|b", "b", "c");
test("a-or-b3", "a+|b+", "aaaaa", "c");
test("a-or-b4", "a+|b+", "bbbbb", "c");
test("a-or-b5", "a*|b*", "aaaaa", "c");
test("a-or-b6", "a*|b*", "bbbbb", "c");
test("a-or-b7", "(a*)|(b*)", "bbbbb", "c");
test("a-or-b8", "(a+)|(b+)", "bbbbb", "c");
test("ab-or-cd1", "ab|cd", "ab", "a");
test("ab-or-cd2", "ab|cd", "cd", "a");
test("ab-or-cd3", "(ab)+|(cd)+", "ababab", "a");
test("ab-or-cd4", "(ab)+|(cd)+", "cdcdcd", "c");
test("ab-or-cd5", "(ab)+|((cd)+)", "cdcdcd", "c");
test("ab-or-cd-or-ef1", "ab|cd|ef", "ab", "af");
test("ab-or-cd-or-ef2", "ab|cd|ef", "cd", "c");
test("ab-or-cd-or-ef3", "ab|cd|ef", "ef", "d");
test("a-or-b-c1", "(a|b?)c", "ac", "a");
test("a-or-b-c2", "(a|b?)c", "bc", "b");
test("a-or-b-c3", "(a|b?)c", "c", "b");
test("escape1", "\\a", "\a", "b");
test("escape2", "\\e", "\e", "b");
test("escape3", "\\n", "\n", "b");
test("escape4", "\\r", "\r", "b");
test("escape5", "\\f", "\f", "b");
test("escape6", "\\t", "\t", "b");
test("escape7", "\\101", "A", "b");
test("escape8", "\\x41", "A", "b");
test("escape9", "\\u0041", "A", "b");
test("escape10", "\\o000101", "A", "b");
test("escape11", "\\u0041A", "AA", "Ab");
test("range1", "[a-z]", "a", "0");
test("range2", "[a-z]", "z", "0");
test("range3", "[^a-z]", "0", "a");
test("range4", "[abc]+", "abc", "d");
test("range5", "[a-zA-Z]+", "azAZ", "0");
test("range5-withor", "([a-z]|[A-Z])+", "azAZ", "0");
test("range6", "[a-c]+", "abc", "d");
test("range7", "[azAZ]+", "azAZ", "0");
test("range8", "[azAZ]+", "a", "0");
test("range9", "[azAZ]+", "z", "0");
test("range10", "[azAZ]+", "A", "0");
test("range11", "[azAZ]+", "Z", "0");
test("range12", "([a-f][c-h])+", "ccah", "ha");
test("anything1", ".", "a", "");
test("anything2", "[^a]", "b", "a");
test("anything3", "[^ab]", "c", "b");
test("anything4", "[^ab]", "d", "a");
test("anything5", "([^ab]|b)", "b", "a");
// test("anything6", "([^ab]|b)+", "bcde", "a"); // Infinite loop!
test("anything7", "[ -\\u00ff]", "a", "");
test("anything8", "[ -\\ufffc]", "a", "");
test("anything9", "[ -\\ufffd]", "a", "");
test("anything10", "[ -\\uffff]", "a", "");
test("bootstrap-identifier1", "[A-Za-z\\-][A-Za-z\\-0-9]*", "some-identifier", "0");
test("bootstrap-identifier2", "[A-Za-z\\-][A-Za-z\\-0-9]*", "language", "0");
test("bootstrap-identifier3", "([A-Za-z\\-][A-Za-z\\-0-9]*)|(language)", "language", "0");
test("bootstrap-identifier4", "([A-Za-z\\-][A-Za-z\\-0-9]*)|(language)", "some-identifier", "0");
}
<commit_msg>Heh, found that 0xfffd seems to be the *precise* character where a malfunction occurs<commit_after>//
// dfa_single_regex.cpp
// Parse
//
// Created by Andrew Hunter on 28/04/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <string>
#include <sstream>
#include "dfa_single_regex.h"
#include "Dfa/lexer.h"
using namespace std;
using namespace dfa;
void test_dfa_single_regex::test(std::string name, std::string regex, std::string accepting, std::string rejecting) {
// Create a lexer that accepts the regular expression
lexer myLexer;
myLexer.add_symbol(regex, 1);
lexer myCompactLexer;
myCompactLexer.add_symbol(regex, 1);
// Compile it
myLexer.compile(false);
myCompactLexer.compile(true);
// Try the accepting phrase
stringstream acceptIn(accepting);
lexeme_stream* stream = myLexer.create_stream_from(acceptIn);
// Get the first lexeme
lexeme* first;
(*stream) >> first;
delete stream;
// Try again with the compact lexer
stringstream acceptCompactIn(accepting);
stream = myCompactLexer.create_stream_from(acceptCompactIn);
lexeme* firstCompact;
(*stream) >> firstCompact;
delete stream;
// Try the rejecting phrase
stringstream rejectIn(rejecting);
stream = myLexer.create_stream_from(rejectIn);
lexeme* fail;
(*stream) >> fail;
delete stream;
// first lexeme should be an accepting lexeme, second should be a rejection
if (first != NULL && fail != NULL && first->matched() == 1 && first->content<char>() == accepting
&& firstCompact != NULL && firstCompact->matched() == 1 && firstCompact->content<char>() == accepting
&& fail != NULL && fail->matched() == -1 && fail->content().size() == 1) {
report(name, true);
} else {
// Break things down if we get a failure
report(name + "-accept", first != NULL && first->matched() == 1);
report(name + "-content", first != NULL && first->content<char>() == accepting);
report(name + "-compact-accept", firstCompact != NULL && firstCompact->matched() == 1);
report(name + "-compact-content", firstCompact != NULL && firstCompact->content<char>() == accepting);
report(name + "-reject", fail != NULL && fail->matched() == -1);
report(name + "-rejectone", fail != NULL && fail->content().size() == 1);
}
delete first;
delete firstCompact;
delete fail;
}
void test_dfa_single_regex::run_tests() {
test("basic", "a", "a", "b");
test("sayaaaa", "a*", "aaaaa", "b");
test("ababab", "(ab)+", "ababab", "aaaaaa");
test("nothing1", "a", "a", "");
test("nothing2", "[a]", "a", "");
test("nothing3", "[^a]", "b", "");
test("nothing4", "[a]+", "aaa", "");
// test("nothing5", "[^a]+", "aaa", ""); // Infinite loop!
test("nothing6", "(a|b)", "a", "");
test("nothing7", "(a|\\ufffd)", "a", "");
test("nothing8", "(a|\\uffff)", "a", "");
test("a-or-b1", "a|b", "a", "c");
test("a-or-b2", "a|b", "b", "c");
test("a-or-b3", "a+|b+", "aaaaa", "c");
test("a-or-b4", "a+|b+", "bbbbb", "c");
test("a-or-b5", "a*|b*", "aaaaa", "c");
test("a-or-b6", "a*|b*", "bbbbb", "c");
test("a-or-b7", "(a*)|(b*)", "bbbbb", "c");
test("a-or-b8", "(a+)|(b+)", "bbbbb", "c");
test("ab-or-cd1", "ab|cd", "ab", "a");
test("ab-or-cd2", "ab|cd", "cd", "a");
test("ab-or-cd3", "(ab)+|(cd)+", "ababab", "a");
test("ab-or-cd4", "(ab)+|(cd)+", "cdcdcd", "c");
test("ab-or-cd5", "(ab)+|((cd)+)", "cdcdcd", "c");
test("ab-or-cd-or-ef1", "ab|cd|ef", "ab", "af");
test("ab-or-cd-or-ef2", "ab|cd|ef", "cd", "c");
test("ab-or-cd-or-ef3", "ab|cd|ef", "ef", "d");
test("a-or-b-c1", "(a|b?)c", "ac", "a");
test("a-or-b-c2", "(a|b?)c", "bc", "b");
test("a-or-b-c3", "(a|b?)c", "c", "b");
test("escape1", "\\a", "\a", "b");
test("escape2", "\\e", "\e", "b");
test("escape3", "\\n", "\n", "b");
test("escape4", "\\r", "\r", "b");
test("escape5", "\\f", "\f", "b");
test("escape6", "\\t", "\t", "b");
test("escape7", "\\101", "A", "b");
test("escape8", "\\x41", "A", "b");
test("escape9", "\\u0041", "A", "b");
test("escape10", "\\o000101", "A", "b");
test("escape11", "\\u0041A", "AA", "Ab");
test("range1", "[a-z]", "a", "0");
test("range2", "[a-z]", "z", "0");
test("range3", "[^a-z]", "0", "a");
test("range4", "[abc]+", "abc", "d");
test("range5", "[a-zA-Z]+", "azAZ", "0");
test("range5-withor", "([a-z]|[A-Z])+", "azAZ", "0");
test("range6", "[a-c]+", "abc", "d");
test("range7", "[azAZ]+", "azAZ", "0");
test("range8", "[azAZ]+", "a", "0");
test("range9", "[azAZ]+", "z", "0");
test("range10", "[azAZ]+", "A", "0");
test("range11", "[azAZ]+", "Z", "0");
test("range12", "([a-f][c-h])+", "ccah", "ha");
test("anything1", ".", "a", "");
test("anything2", "[^a]", "b", "a");
test("anything3", "[^ab]", "c", "b");
test("anything4", "[^ab]", "d", "a");
test("anything5", "([^ab]|b)", "b", "a");
// test("anything6", "([^ab]|b)+", "bcde", "a"); // Infinite loop!
test("anything7", "[ -\\u00ff]", "a", "");
test("anything8", "[ -\\ufffc]", "a", "");
test("anything9", "[ -\\ufffd]", "a", "");
test("anything10", "[ -\\uffff]", "a", "");
test("bootstrap-identifier1", "[A-Za-z\\-][A-Za-z\\-0-9]*", "some-identifier", "0");
test("bootstrap-identifier2", "[A-Za-z\\-][A-Za-z\\-0-9]*", "language", "0");
test("bootstrap-identifier3", "([A-Za-z\\-][A-Za-z\\-0-9]*)|(language)", "language", "0");
test("bootstrap-identifier4", "([A-Za-z\\-][A-Za-z\\-0-9]*)|(language)", "some-identifier", "0");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "greenworks_async_workers.h"
#include <sstream>
#include <iomanip>
#include "nan.h"
#include "steam/steam_api.h"
#include "v8.h"
#include "greenworks_unzip.h"
#include "greenworks_zip.h"
namespace {
struct FilesContentContainer {
std::vector<char*> files_content;
~FilesContentContainer() {
for (size_t i = 0; i < files_content.size(); ++i) {
delete files_content[i];
}
}
};
}; // namespace
namespace greenworks {
FileContentSaveWorker::FileContentSaveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, std::string file_name, std::string content):
SteamAsyncWorker(success_callback, error_callback),
file_name_(file_name),
content_(content) {
}
void FileContentSaveWorker::Execute() {
if (!SteamRemoteStorage()->FileWrite(
file_name_.c_str(), content_.c_str(), content_.size()))
SetErrorMessage("Error on writing to file.");
}
FilesSaveWorker::FilesSaveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::vector<std::string>& files_path):
SteamAsyncWorker(success_callback, error_callback),
files_path_(files_path) {
}
void FilesSaveWorker::Execute() {
FilesContentContainer container;
std::vector<int> files_content_length;
for (size_t i = 0; i < files_path_.size(); ++i) {
char* content = NULL;
int length = 0;
if (!utils::ReadFile(files_path_[i].c_str(), content, length))
break;
container.files_content.push_back(content);
files_content_length.push_back(length);
}
if (container.files_content.size() != files_path_.size()) {
SetErrorMessage("Error on reading files.");
return;
}
for (size_t i = 0; i < files_path_.size(); ++i) {
std::string file_name = utils::GetFileNameFromPath(files_path_[i]);
if (!SteamRemoteStorage()->FileWrite(file_name.c_str(),
container.files_content[i], files_content_length[i])) {
SetErrorMessage("Error on writing file on Steam Cloud.");
return;
}
}
}
FileReadWorker::FileReadWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, std::string file_name):
SteamAsyncWorker(success_callback, error_callback),
file_name_(file_name) {
}
void FileReadWorker::Execute() {
ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();
if (!steam_remote_storage->FileExists(file_name_.c_str())) {
SetErrorMessage("File doesn't exist.");
return;
}
int32 file_size = steam_remote_storage->GetFileSize(file_name_.c_str());
char* content = new char[file_size+1];
int32 end_pos = steam_remote_storage->FileRead(
file_name_.c_str(), content, file_size);
content[end_pos] = '\0';
if (end_pos == 0 && file_size > 0) {
SetErrorMessage("Error on reading file.");
} else {
content_ = std::string(content);
}
delete content;
}
void FileReadWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(content_).ToLocalChecked() };
callback->Call(1, argv);
}
CloudQuotaGetWorker::CloudQuotaGetWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback):SteamAsyncWorker(success_callback,
error_callback), total_bytes_(-1), available_bytes_(-1) {
}
void CloudQuotaGetWorker::Execute() {
ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();
if (!steam_remote_storage->GetQuota(&total_bytes_, &available_bytes_)) {
SetErrorMessage("Error on getting cloud quota.");
return;
}
}
void CloudQuotaGetWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(total_bytes_)).ToLocalChecked(),
Nan::New(utils::uint64ToString(available_bytes_)).ToLocalChecked() };
callback->Call(2, argv);
}
ActivateAchievementWorker::ActivateAchievementWorker(
Nan::Callback* success_callback, Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback,
error_callback), achievement_(achievement) {
}
void ActivateAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
if (!steam_user_stats->SetAchievement(achievement_.c_str())) {
SetErrorMessage("Achievement name is not valid.");
} else if (!steam_user_stats->StoreStats()) {
SetErrorMessage("Error on storing user achievement");
}
}
void ActivateAchievementWorker::HandleOKCallback() {
Nan::HandleScope scope;
callback->Call(0, NULL);
}
GetAchievementWorker::GetAchievementWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback, error_callback),
achievement_(achievement),
is_achieved_(false) {
}
void GetAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
bool success = steam_user_stats->GetAchievement(achievement_.c_str(),
&is_achieved_);
if (!success) {
SetErrorMessage("Achivement name is not valid.");
}
}
void GetAchievementWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(is_achieved_) };
callback->Call(1, argv);
}
ClearAchievementWorker::ClearAchievementWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback, error_callback),
achievement_(achievement),
success_(false) {
}
void ClearAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
success_ = steam_user_stats->ClearAchievement(achievement_.c_str());
if (!success_) {
SetErrorMessage("Achievement name is not valid.");
} else if (!steam_user_stats->StoreStats()) {
SetErrorMessage("Fails on uploading user stats to server.");
}
}
void ClearAchievementWorker::HandleOKCallback() {
Nan::HandleScope scope;
callback->Call(0, NULL);
}
GetNumberOfPlayersWorker::GetNumberOfPlayersWorker(
Nan::Callback* success_callback, Nan::Callback* error_callback)
:SteamCallbackAsyncWorker(success_callback, error_callback),
num_of_players_(-1) {
}
void GetNumberOfPlayersWorker::Execute() {
SteamAPICall_t steam_api_call = SteamUserStats()->GetNumberOfCurrentPlayers();
call_result_.Set(steam_api_call, this,
&GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted);
WaitForCompleted();
}
void GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted(
NumberOfCurrentPlayers_t* result, bool io_failure) {
if (io_failure) {
SetErrorMessage("Error on getting number of players: Steam API IO Failure");
} else if (result->m_bSuccess) {
num_of_players_ = result->m_cPlayers;
} else {
SetErrorMessage("Error on getting number of players.");
}
is_completed_ = true;
}
void GetNumberOfPlayersWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(num_of_players_) };
callback->Call(1, argv);
}
CreateArchiveWorker::CreateArchiveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::string& zip_file_path,
const std::string& source_dir, const std::string& password,
int compress_level)
:SteamAsyncWorker(success_callback, error_callback),
zip_file_path_(zip_file_path),
source_dir_(source_dir),
password_(password),
compress_level_(compress_level) {
}
void CreateArchiveWorker::Execute() {
int result = zip(zip_file_path_.c_str(),
source_dir_.c_str(),
compress_level_,
password_.empty()?NULL:password_.c_str());
if (result)
SetErrorMessage("Error on creating zip file.");
}
ExtractArchiveWorker::ExtractArchiveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::string& zip_file_path,
const std::string& extract_path, const std::string& password)
: SteamAsyncWorker(success_callback, error_callback),
zip_file_path_(zip_file_path),
extract_path_(extract_path),
password_(password) {
}
void ExtractArchiveWorker::Execute() {
int result = unzip(zip_file_path_.c_str(), extract_path_.c_str(),
password_.empty()?NULL:password_.c_str());
if (result)
SetErrorMessage("Error on extracting zip file.");
}
GetAuthSessionTicketWorker::GetAuthSessionTicketWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback )
: SteamCallbackAsyncWorker(success_callback, error_callback),
result(this, &GetAuthSessionTicketWorker::OnGetAuthSessionCompleted),
handle_(0), ticket_buf_size_(0) {
}
void GetAuthSessionTicketWorker::Execute() {
handle_ = SteamUser()->GetAuthSessionTicket(ticket_buf_,
sizeof(ticket_buf_),
&ticket_buf_size_);
WaitForCompleted();
}
void GetAuthSessionTicketWorker::OnGetAuthSessionCompleted(
GetAuthSessionTicketResponse_t *inCallback) {
if (inCallback->m_eResult != k_EResultOK)
SetErrorMessage("Error on getting auth session ticket.");
is_completed_ = true;
}
void GetAuthSessionTicketWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Object> ticket = Nan::New<v8::Object>();
ticket->Set(
Nan::New("ticket").ToLocalChecked(),
Nan::CopyBuffer(reinterpret_cast<char*>(ticket_buf_), ticket_buf_size_)
.ToLocalChecked());
ticket->Set(Nan::New("handle").ToLocalChecked(), Nan::New(handle_));
v8::Local<v8::Value> argv[] = { ticket };
callback->Call(1, argv);
}
RequestEncryptedAppTicketWorker::RequestEncryptedAppTicketWorker(
std::string user_data,
Nan::Callback* success_callback,
Nan::Callback* error_callback)
: SteamCallbackAsyncWorker(success_callback, error_callback),
user_data_(user_data), ticket_buf_size_(0) {
}
void RequestEncryptedAppTicketWorker::Execute() {
SteamAPICall_t steam_api_call = SteamUser()->RequestEncryptedAppTicket(
static_cast<void*>(const_cast<char*>(user_data_.c_str())),
user_data_.length());
call_result_.Set(steam_api_call, this,
&RequestEncryptedAppTicketWorker::OnRequestEncryptedAppTicketCompleted);
WaitForCompleted();
}
void RequestEncryptedAppTicketWorker::OnRequestEncryptedAppTicketCompleted(
EncryptedAppTicketResponse_t *inCallback, bool io_failure) {
if (!io_failure && inCallback->m_eResult == k_EResultOK) {
SteamUser()->GetEncryptedAppTicket(ticket_buf_, sizeof(ticket_buf_),
&ticket_buf_size_);
} else {
SetErrorMessage("Error on getting encrypted app ticket.");
}
is_completed_ = true;
}
void RequestEncryptedAppTicketWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::CopyBuffer(reinterpret_cast<char *>(ticket_buf_), ticket_buf_size_)
.ToLocalChecked() };
callback->Call(1, argv);
}
} // namespace greenworks
<commit_msg>code standardization<commit_after>// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "greenworks_async_workers.h"
#include <sstream>
#include <iomanip>
#include "nan.h"
#include "steam/steam_api.h"
#include "v8.h"
#include "greenworks_unzip.h"
#include "greenworks_zip.h"
namespace {
struct FilesContentContainer {
std::vector<char*> files_content;
~FilesContentContainer() {
for (size_t i = 0; i < files_content.size(); ++i) {
delete files_content[i];
}
}
};
}; // namespace
namespace greenworks {
FileContentSaveWorker::FileContentSaveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, std::string file_name, std::string content):
SteamAsyncWorker(success_callback, error_callback),
file_name_(file_name),
content_(content) {
}
void FileContentSaveWorker::Execute() {
if (!SteamRemoteStorage()->FileWrite(
file_name_.c_str(), content_.c_str(), content_.size()))
SetErrorMessage("Error on writing to file.");
}
FilesSaveWorker::FilesSaveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::vector<std::string>& files_path):
SteamAsyncWorker(success_callback, error_callback),
files_path_(files_path) {
}
void FilesSaveWorker::Execute() {
FilesContentContainer container;
std::vector<int> files_content_length;
for (size_t i = 0; i < files_path_.size(); ++i) {
char* content = NULL;
int length = 0;
if (!utils::ReadFile(files_path_[i].c_str(), content, length))
break;
container.files_content.push_back(content);
files_content_length.push_back(length);
}
if (container.files_content.size() != files_path_.size()) {
SetErrorMessage("Error on reading files.");
return;
}
for (size_t i = 0; i < files_path_.size(); ++i) {
std::string file_name = utils::GetFileNameFromPath(files_path_[i]);
if (!SteamRemoteStorage()->FileWrite(file_name.c_str(),
container.files_content[i], files_content_length[i])) {
SetErrorMessage("Error on writing file on Steam Cloud.");
return;
}
}
}
FileReadWorker::FileReadWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, std::string file_name):
SteamAsyncWorker(success_callback, error_callback),
file_name_(file_name) {
}
void FileReadWorker::Execute() {
ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();
if (!steam_remote_storage->FileExists(file_name_.c_str())) {
SetErrorMessage("File doesn't exist.");
return;
}
int32 file_size = steam_remote_storage->GetFileSize(file_name_.c_str());
char* content = new char[file_size+1];
int32 end_pos = steam_remote_storage->FileRead(
file_name_.c_str(), content, file_size);
content[end_pos] = '\0';
if (end_pos == 0 && file_size > 0) {
SetErrorMessage("Error on reading file.");
} else {
content_ = std::string(content);
}
delete content;
}
void FileReadWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(content_).ToLocalChecked() };
callback->Call(1, argv);
}
CloudQuotaGetWorker::CloudQuotaGetWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback):SteamAsyncWorker(success_callback,
error_callback), total_bytes_(-1), available_bytes_(-1) {
}
void CloudQuotaGetWorker::Execute() {
ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();
if (!steam_remote_storage->GetQuota(&total_bytes_, &available_bytes_)) {
SetErrorMessage("Error on getting cloud quota.");
return;
}
}
void CloudQuotaGetWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(total_bytes_)).ToLocalChecked(),
Nan::New(utils::uint64ToString(available_bytes_)).ToLocalChecked() };
callback->Call(2, argv);
}
ActivateAchievementWorker::ActivateAchievementWorker(
Nan::Callback* success_callback, Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback,
error_callback), achievement_(achievement) {
}
void ActivateAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
if (!steam_user_stats->SetAchievement(achievement_.c_str())) {
SetErrorMessage("Achievement name is not valid.");
return;
}
if (!steam_user_stats->StoreStats()) {
SetErrorMessage("Error on storing user achievement");
return;
}
}
GetAchievementWorker::GetAchievementWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback, error_callback),
achievement_(achievement),
is_achieved_(false) {
}
void GetAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
bool success = steam_user_stats->GetAchievement(achievement_.c_str(),
&is_achieved_);
if (!success) {
SetErrorMessage("Achivement name is not valid.");
}
}
void GetAchievementWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(is_achieved_) };
callback->Call(1, argv);
}
ClearAchievementWorker::ClearAchievementWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback,
const std::string& achievement):
SteamAsyncWorker(success_callback, error_callback),
achievement_(achievement),
success_(false) {
}
void ClearAchievementWorker::Execute() {
ISteamUserStats* steam_user_stats = SteamUserStats();
success_ = steam_user_stats->ClearAchievement(achievement_.c_str());
if (!success_) {
SetErrorMessage("Achievement name is not valid.");
return;
}
if (!steam_user_stats->StoreStats()) {
SetErrorMessage("Fails on uploading user stats to server.");
return;
}
}
GetNumberOfPlayersWorker::GetNumberOfPlayersWorker(
Nan::Callback* success_callback, Nan::Callback* error_callback)
:SteamCallbackAsyncWorker(success_callback, error_callback),
num_of_players_(-1) {
}
void GetNumberOfPlayersWorker::Execute() {
SteamAPICall_t steam_api_call = SteamUserStats()->GetNumberOfCurrentPlayers();
call_result_.Set(steam_api_call, this,
&GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted);
WaitForCompleted();
}
void GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted(
NumberOfCurrentPlayers_t* result, bool io_failure) {
if (io_failure) {
SetErrorMessage("Error on getting number of players: Steam API IO Failure");
} else if (result->m_bSuccess) {
num_of_players_ = result->m_cPlayers;
} else {
SetErrorMessage("Error on getting number of players.");
}
is_completed_ = true;
}
void GetNumberOfPlayersWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::New(num_of_players_) };
callback->Call(1, argv);
}
CreateArchiveWorker::CreateArchiveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::string& zip_file_path,
const std::string& source_dir, const std::string& password,
int compress_level)
:SteamAsyncWorker(success_callback, error_callback),
zip_file_path_(zip_file_path),
source_dir_(source_dir),
password_(password),
compress_level_(compress_level) {
}
void CreateArchiveWorker::Execute() {
int result = zip(zip_file_path_.c_str(),
source_dir_.c_str(),
compress_level_,
password_.empty()?NULL:password_.c_str());
if (result)
SetErrorMessage("Error on creating zip file.");
}
ExtractArchiveWorker::ExtractArchiveWorker(Nan::Callback* success_callback,
Nan::Callback* error_callback, const std::string& zip_file_path,
const std::string& extract_path, const std::string& password)
: SteamAsyncWorker(success_callback, error_callback),
zip_file_path_(zip_file_path),
extract_path_(extract_path),
password_(password) {
}
void ExtractArchiveWorker::Execute() {
int result = unzip(zip_file_path_.c_str(), extract_path_.c_str(),
password_.empty()?NULL:password_.c_str());
if (result)
SetErrorMessage("Error on extracting zip file.");
}
GetAuthSessionTicketWorker::GetAuthSessionTicketWorker(
Nan::Callback* success_callback,
Nan::Callback* error_callback )
: SteamCallbackAsyncWorker(success_callback, error_callback),
result(this, &GetAuthSessionTicketWorker::OnGetAuthSessionCompleted),
handle_(0), ticket_buf_size_(0) {
}
void GetAuthSessionTicketWorker::Execute() {
handle_ = SteamUser()->GetAuthSessionTicket(ticket_buf_,
sizeof(ticket_buf_),
&ticket_buf_size_);
WaitForCompleted();
}
void GetAuthSessionTicketWorker::OnGetAuthSessionCompleted(
GetAuthSessionTicketResponse_t *inCallback) {
if (inCallback->m_eResult != k_EResultOK)
SetErrorMessage("Error on getting auth session ticket.");
is_completed_ = true;
}
void GetAuthSessionTicketWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Object> ticket = Nan::New<v8::Object>();
ticket->Set(
Nan::New("ticket").ToLocalChecked(),
Nan::CopyBuffer(reinterpret_cast<char*>(ticket_buf_), ticket_buf_size_)
.ToLocalChecked());
ticket->Set(Nan::New("handle").ToLocalChecked(), Nan::New(handle_));
v8::Local<v8::Value> argv[] = { ticket };
callback->Call(1, argv);
}
RequestEncryptedAppTicketWorker::RequestEncryptedAppTicketWorker(
std::string user_data,
Nan::Callback* success_callback,
Nan::Callback* error_callback)
: SteamCallbackAsyncWorker(success_callback, error_callback),
user_data_(user_data), ticket_buf_size_(0) {
}
void RequestEncryptedAppTicketWorker::Execute() {
SteamAPICall_t steam_api_call = SteamUser()->RequestEncryptedAppTicket(
static_cast<void*>(const_cast<char*>(user_data_.c_str())),
user_data_.length());
call_result_.Set(steam_api_call, this,
&RequestEncryptedAppTicketWorker::OnRequestEncryptedAppTicketCompleted);
WaitForCompleted();
}
void RequestEncryptedAppTicketWorker::OnRequestEncryptedAppTicketCompleted(
EncryptedAppTicketResponse_t *inCallback, bool io_failure) {
if (!io_failure && inCallback->m_eResult == k_EResultOK) {
SteamUser()->GetEncryptedAppTicket(ticket_buf_, sizeof(ticket_buf_),
&ticket_buf_size_);
} else {
SetErrorMessage("Error on getting encrypted app ticket.");
}
is_completed_ = true;
}
void RequestEncryptedAppTicketWorker::HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::CopyBuffer(reinterpret_cast<char *>(ticket_buf_), ticket_buf_size_)
.ToLocalChecked() };
callback->Call(1, argv);
}
} // namespace greenworks
<|endoftext|>
|
<commit_before>#include "compiler/prepare_grammar/expand_repeats.h"
#include "compiler/prepare_grammar/expand_tokens.h"
#include "compiler/prepare_grammar/extract_tokens.h"
#include "compiler/prepare_grammar/intern_symbols.h"
#include "compiler/prepare_grammar/prepare_grammar.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
namespace prepare_grammar {
using std::tuple;
using std::get;
using std::make_tuple;
tuple<SyntaxGrammar, LexicalGrammar, const GrammarError *> prepare_grammar(
const Grammar &input_grammar) {
auto result = intern_symbols(input_grammar);
const Grammar &grammar = result.first;
const GrammarError *error = result.second;
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
auto grammars = extract_tokens(grammar);
const SyntaxGrammar &rule_grammar = expand_repeats(get<0>(grammars));
error = get<2>(grammars);
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
auto expand_tokens_result = expand_tokens(get<1>(grammars));
const LexicalGrammar &lex_grammar = expand_tokens_result.first;
error = expand_tokens_result.second;
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
return make_tuple(rule_grammar, lex_grammar, nullptr);
}
} // namespace prepare_grammar
} // namespace tree_sitter
<commit_msg>Clean up prepare_grammar function<commit_after>#include "compiler/prepare_grammar/expand_repeats.h"
#include "compiler/prepare_grammar/expand_tokens.h"
#include "compiler/prepare_grammar/extract_tokens.h"
#include "compiler/prepare_grammar/intern_symbols.h"
#include "compiler/prepare_grammar/prepare_grammar.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
namespace prepare_grammar {
using std::tuple;
using std::get;
using std::make_tuple;
tuple<SyntaxGrammar, LexicalGrammar, const GrammarError *> prepare_grammar(
const Grammar &input_grammar) {
// Convert all string-based `NamedSymbols` into numerical `Symbols`
auto intern_result = intern_symbols(input_grammar);
const GrammarError *error = intern_result.second;
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
// Separate grammar into lexical and syntactic components
auto extract_result = extract_tokens(intern_result.first);
error = get<2>(extract_result);
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
// Replace `Repeat` rules with pairs of recursive rules
const SyntaxGrammar &syntax_grammar = expand_repeats(get<0>(extract_result));
// Expand `String` and `Pattern` rules into full rule trees
auto expand_tokens_result = expand_tokens(get<1>(extract_result));
const LexicalGrammar &lex_grammar = expand_tokens_result.first;
error = expand_tokens_result.second;
if (error)
return make_tuple(SyntaxGrammar(), LexicalGrammar(), error);
return make_tuple(syntax_grammar, lex_grammar, nullptr);
}
} // namespace prepare_grammar
} // namespace tree_sitter
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.org> <[email protected]>
**
****************************************************************************/
#include "qxtwindowsystem.h"
#include <qt_windows.h>
#include <qglobal.h> // QT_WA
static WindowList qxt_Windows;
BOOL CALLBACK qxt_EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
Q_UNUSED(lParam);
if (::IsWindowVisible(hwnd))
qxt_Windows += hwnd;
return TRUE;
}
WindowList QxtWindowSystem::windows()
{
qxt_Windows.clear();
HDESK hdesk = ::OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS);
::EnumDesktopWindows(hdesk, qxt_EnumWindowsProc, 0);
::CloseDesktop(hdesk);
return qxt_Windows;
}
WId QxtWindowSystem::activeWindow()
{
return ::GetForegroundWindow();
}
WId QxtWindowSystem::findWindow(const QString& title)
{
QT_WA({
return ::FindWindow(NULL, (TCHAR*)title.utf16());
}, {
return ::FindWindowA(NULL, title.toLocal8Bit());
});
}
WId QxtWindowSystem::windowAt(const QPoint& pos)
{
POINT pt;
pt.x = pos.x();
pt.y = pos.y();
return ::WindowFromPoint(pt);
}
QString QxtWindowSystem::windowTitle(WId window)
{
QString title;
int len = ::GetWindowTextLength(window);
if (len >= 0)
{
TCHAR* buf = new TCHAR[len+1];
len = ::GetWindowText(window, buf, len+1);
QT_WA({
title = QString::fromUtf16((const ushort*)buf, len);
}, {
title = QString::fromLocal8Bit((const char*)buf, len);
});
delete[] buf;
}
return title;
}
QRect QxtWindowSystem::windowGeometry(WId window)
{
RECT rc;
QRect rect;
if (::GetWindowRect(window, &rc))
{
rect.setTop(rc.top);
rect.setBottom(rc.bottom);
rect.setLeft(rc.left);
rect.setRight(rc.right);
}
return rect;
}
uint QxtWindowSystem::idleTime()
{
return -1;
}
<commit_msg>Implemented Windows version of QxtWindowSystem::idleTime().<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.org> <[email protected]>
**
****************************************************************************/
#include "qxtwindowsystem.h"
#include <qt_windows.h>
#include <qglobal.h> // QT_WA
static WindowList qxt_Windows;
BOOL CALLBACK qxt_EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
Q_UNUSED(lParam);
if (::IsWindowVisible(hwnd))
qxt_Windows += hwnd;
return TRUE;
}
WindowList QxtWindowSystem::windows()
{
qxt_Windows.clear();
HDESK hdesk = ::OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS);
::EnumDesktopWindows(hdesk, qxt_EnumWindowsProc, 0);
::CloseDesktop(hdesk);
return qxt_Windows;
}
WId QxtWindowSystem::activeWindow()
{
return ::GetForegroundWindow();
}
WId QxtWindowSystem::findWindow(const QString& title)
{
QT_WA({
return ::FindWindow(NULL, (TCHAR*)title.utf16());
}, {
return ::FindWindowA(NULL, title.toLocal8Bit());
});
}
WId QxtWindowSystem::windowAt(const QPoint& pos)
{
POINT pt;
pt.x = pos.x();
pt.y = pos.y();
return ::WindowFromPoint(pt);
}
QString QxtWindowSystem::windowTitle(WId window)
{
QString title;
int len = ::GetWindowTextLength(window);
if (len >= 0)
{
TCHAR* buf = new TCHAR[len+1];
len = ::GetWindowText(window, buf, len+1);
QT_WA({
title = QString::fromUtf16((const ushort*)buf, len);
}, {
title = QString::fromLocal8Bit((const char*)buf, len);
});
delete[] buf;
}
return title;
}
QRect QxtWindowSystem::windowGeometry(WId window)
{
RECT rc;
QRect rect;
if (::GetWindowRect(window, &rc))
{
rect.setTop(rc.top);
rect.setBottom(rc.bottom);
rect.setLeft(rc.left);
rect.setRight(rc.right);
}
return rect;
}
uint QxtWindowSystem::idleTime()
{
uint idle = -1;
LASTINPUTINFO info;
info.cbSize = sizeof(LASTINPUTINFO);
if (::GetLastInputInfo(&info))
idle = ::GetTickCount() - info.dwTime;
return idle;
}
<|endoftext|>
|
<commit_before>#include "util/sync_log.h"
#include "util/auto_proc.h"
#include <cstdlib>
#include <vector>
#include <sstream>
#include <memory>
using namespace util;
using namespace std;
int main(int argc, char** argv) {
sync_log log("SPAWNER");
log.info("Starting");
if (argc < 2) {
log.error("I don't know the amount of processes to spawn");
return EXIT_FAILURE;
}
auto processes = atoi(argv[1]);
log.info("I will spawn $ CHILD processes", processes);
vector<string> args;
{
vector<shared_ptr<auto_proc>> children(processes);
for (int i = 0; i < processes; i++) {
auto child = make_shared<auto_proc>("build/exec/child", args);
children.push_back(child);
log.info("Launched CHILD process with pid $", child->pid());
}
log.info("All CHILD processes launched, waiting for termination");
}
log.info("Finishing");
return EXIT_SUCCESS;
}
<commit_msg>Removes unnecessary shared pointer out of the children vector<commit_after>#include "util/sync_log.h"
#include "util/auto_proc.h"
#include <cstdlib>
#include <vector>
using namespace util;
using namespace std;
int main(int argc, char** argv) {
sync_log log("SPAWNER");
log.info("Starting");
if (argc < 2) {
log.error("I don't know the amount of processes to spawn");
return EXIT_FAILURE;
}
auto processes = atoi(argv[1]);
log.info("I will spawn $ CHILD processes", processes);
vector<string> args;
{
vector<auto_proc> children;
for (int i = 0; i < processes; i++) {
children.emplace_back("build/exec/child", args);
log.info("Launched CHILD process $", children.back().pid());
}
log.info("All CHILD processes launched, waiting for termination");
}
log.info("Finishing");
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <list>
#include <string>
#include <process/clock.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>
#include "configurator/configurator.hpp"
#include "tests/environment.hpp"
#include "tests/filter.hpp"
using std::list;
using std::string;
namespace mesos {
namespace internal {
namespace tests {
// A simple test event listener that makes sure to resume the clock
// after each test even if the previous test had a partial result
// (i.e., an ASSERT_* failed).
class ClockTestEventListener : public ::testing::EmptyTestEventListener
{
public:
virtual void OnTestEnd(const ::testing::TestInfo&)
{
if (process::Clock::paused()) {
process::Clock::resume();
}
}
};
// Returns true if we should enable the provided test. For now, this
// ONLY disables test cases and tests in three circumstances:
// (1) The test case, test, or type parameter contains the string
// 'ROOT' but the test is being run via a non-root user.
// (2) The test case, test, or type parameter contains the string
// 'CGROUPS' but cgroups are not supported on this machine.
// (3) The test case, test, or type parameter contains the string
// 'CgroupsIsolationModule', but is being run via a non-root
// user, or cgroups are not supported on this machine.
// TODO(benh): Provide a generic way to enable/disable tests by
// registering "filter" functions.
static bool enable(const ::testing::TestInfo& test)
{
// We check (1), (2), and (3) from above against the test case
// name, the test name, and the type parameter (when present).
list<string> names;
names.push_back(test.test_case_name());
names.push_back(test.name());
if (test.type_param() != NULL) {
names.push_back(test.type_param());
}
foreach (const string& name, names) {
if (strings::contains(name, "ROOT") && os::user() != "root") {
return false;
}
if (strings::contains(name, "CGROUPS") && !os::exists("/proc/cgroups")) {
return false;
}
if (strings::contains(name, "CgroupsIsolationModule") &&
(os::user() != "root" || !os::exists("/proc/cgroups"))) {
return false;
}
}
return true;
}
// We use the constructor to setup specific tests by updating the
// gtest filter. We do this so that we can selectively run tests that
// require root or specific OS support (e.g., cgroups). Note that this
// should not effect any other filters that have been put in place
// either on the command line or via an environment variable.
// N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.
Environment::Environment()
{
// First we split the current filter into positive and negative
// components (which are separated by a '-').
const string& filter = ::testing::GTEST_FLAG(filter);
string positive;
string negative;
size_t dash = filter.find('-');
if (dash != string::npos) {
positive = filter.substr(0, dash);
negative = filter.substr(dash + 1);
} else {
positive = filter;
}
// Use universal filter if not specified.
if (positive.empty()) {
positive = "*";
}
// Construct the filter string to handle system or platform specific tests.
::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();
for (int i = 0; i < unitTest->total_test_case_count(); i++) {
const ::testing::TestCase* testCase = unitTest->GetTestCase(i);
for (int j = 0; j < testCase->total_test_count(); j++) {
const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);
if (!enable(*testCase->GetTestInfo(j))) {
negative.append(testInfo->test_case_name());
negative.append(".");
negative.append(testInfo->name());
negative.append(":");
}
}
}
// Now update the gtest flag.
::testing::GTEST_FLAG(filter) = positive + "-" + negative;
}
void Environment::SetUp()
{
// Clear any MESOS_ environment variables so they don't affect our tests.
Configurator::clearMesosEnvironmentVars();
// Add our test event listeners.
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Append(new FilterTestEventListener());
listeners.Append(new ClockTestEventListener());
}
void Environment::TearDown() {}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Explicitly disabled tests with the CgroupsIsolationModule type parameter.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <list>
#include <string>
#include <process/clock.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>
#include "configurator/configurator.hpp"
#include "tests/environment.hpp"
#include "tests/filter.hpp"
using std::list;
using std::string;
namespace mesos {
namespace internal {
namespace tests {
// A simple test event listener that makes sure to resume the clock
// after each test even if the previous test had a partial result
// (i.e., an ASSERT_* failed).
class ClockTestEventListener : public ::testing::EmptyTestEventListener
{
public:
virtual void OnTestEnd(const ::testing::TestInfo&)
{
if (process::Clock::paused()) {
process::Clock::resume();
}
}
};
// Returns true if we should enable the provided test. Similar to how
// tests can be disabled using the 'DISABLED_' prefix on a test case
// name or test name, we use 'ROOT_' and 'CGROUPS_' prefixes to only
// enable tests based on whether or not the current user is root or
// cgroups support is detected. Both 'ROOT_' and 'CGROUPS_' can be
// composed in any order, but must come after 'DISABLED_'. In
// addition, we disable tests that attempt to use the
// CgroupsIsolationModule type parameter if the current user is not
// root or cgroups is not supported.
// TODO(benh): Provide a generic way to enable/disable tests by
// registering "filter" functions.
static bool enable(const ::testing::TestInfo& test)
{
// First check the test case name and test name.
list<string> names;
names.push_back(test.test_case_name());
names.push_back(test.name());
foreach (const string& name, names) {
if (strings::contains(name, "ROOT_") && os::user() != "root") {
return false;
}
if (strings::contains(name, "CGROUPS_") && !os::exists("/proc/cgroups")) {
return false;
}
}
// Now check the type parameter.
if (test.type_param() != NULL) {
if (string(test.type_param()) == "CgroupsIsolationModule" &&
(os::user() != "root" || !os::exists("/proc/cgroups"))) {
return false;
}
}
return true;
}
// We use the constructor to setup specific tests by updating the
// gtest filter. We do this so that we can selectively run tests that
// require root or specific OS support (e.g., cgroups). Note that this
// should not effect any other filters that have been put in place
// either on the command line or via an environment variable.
// N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.
Environment::Environment()
{
// First we split the current filter into positive and negative
// components (which are separated by a '-').
const string& filter = ::testing::GTEST_FLAG(filter);
string positive;
string negative;
size_t dash = filter.find('-');
if (dash != string::npos) {
positive = filter.substr(0, dash);
negative = filter.substr(dash + 1);
} else {
positive = filter;
}
// Use universal filter if not specified.
if (positive.empty()) {
positive = "*";
}
// Construct the filter string to handle system or platform specific tests.
::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();
for (int i = 0; i < unitTest->total_test_case_count(); i++) {
const ::testing::TestCase* testCase = unitTest->GetTestCase(i);
for (int j = 0; j < testCase->total_test_count(); j++) {
const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);
if (!enable(*testCase->GetTestInfo(j))) {
// Append 'TestCase.TestName:'.
negative.append(testInfo->test_case_name());
negative.append(".");
negative.append(testInfo->name());
negative.append(":");
}
}
}
// Now update the gtest flag.
::testing::GTEST_FLAG(filter) = positive + "-" + negative;
}
void Environment::SetUp()
{
// Clear any MESOS_ environment variables so they don't affect our tests.
Configurator::clearMesosEnvironmentVars();
// Add our test event listeners.
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Append(new FilterTestEventListener());
listeners.Append(new ClockTestEventListener());
}
void Environment::TearDown() {}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010 Volker Krause <[email protected]>
Copyright (c) 2013 Daniel Vrátil <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "searchmanager.h"
#include "abstractsearchplugin.h"
#include "searchmanageradaptor.h"
#include "akdebug.h"
#include "agentsearchengine.h"
#include "nepomuksearchengine.h"
#include "notificationmanager.h"
#include "searchrequest.h"
#include "searchtaskmanager.h"
#include "storage/datastore.h"
#include "storage/querybuilder.h"
#include "storage/transaction.h"
#include "storage/selectquerybuilder.h"
#include "searchhelper.h"
#include "libs/xdgbasedirs_p.h"
#include "libs/protocol_p.h"
#include <QDir>
#include <QPluginLoader>
#include <QDBusConnection>
#include <QTimer>
Q_DECLARE_METATYPE( Akonadi::Server::NotificationCollector* )
using namespace Akonadi;
using namespace Akonadi::Server;
SearchManager *SearchManager::sInstance = 0;
Q_DECLARE_METATYPE( Collection )
Q_DECLARE_METATYPE( QSet<qint64> )
Q_DECLARE_METATYPE( QWaitCondition* )
SearchManagerThread::SearchManagerThread( const QStringList &searchEngines, QObject *parent )
: QThread( parent )
, mSearchEngines( searchEngines )
{
Q_ASSERT( QThread::currentThread() == QCoreApplication::instance()->thread() );
}
SearchManagerThread::~SearchManagerThread()
{
}
void SearchManagerThread::run()
{
SearchManager *manager = new SearchManager( mSearchEngines );
exec();
delete manager;
}
SearchManager::SearchManager( const QStringList &searchEngines, QObject *parent )
: QObject( parent )
{
qRegisterMetaType< QSet<qint64> >();
qRegisterMetaType<Collection>();
qRegisterMetaType<QWaitCondition*>();
Q_ASSERT( sInstance == 0 );
sInstance = this;
mEngines.reserve( searchEngines.size() );
Q_FOREACH ( const QString &engineName, searchEngines ) {
if ( engineName == QLatin1String( "Nepomuk" ) ) {
#ifdef HAVE_SOPRANO
m_engines.append( new NepomukSearchEngine );
#endif
} else if ( engineName == QLatin1String( "Agent" ) ) {
mEngines.append( new AgentSearchEngine );
} else {
akError() << "Unknown search engine type: " << engineName;
}
}
loadSearchPlugins();
new SearchManagerAdaptor( this );
QDBusConnection::sessionBus().registerObject(
QLatin1String( "/SearchManager" ),
this,
QDBusConnection::ExportAdaptors );
// The timer will tick 15 seconds after last change notification. If a new notification
// is delivered in the meantime, the timer is reset
mSearchUpdateTimer = new QTimer( this );
mSearchUpdateTimer->setInterval( 15 * 1000 );
mSearchUpdateTimer->setSingleShot( true );
connect( mSearchUpdateTimer, SIGNAL(timeout()),
this, SLOT(searchUpdateTimeout()) );
DataStore::self();
}
SearchManager::~SearchManager()
{
qDeleteAll( mEngines );
DataStore::self()->close();
sInstance = 0;
}
SearchManager *SearchManager::instance()
{
Q_ASSERT( sInstance );
return sInstance;
}
void SearchManager::registerInstance( const QString &id )
{
SearchTaskManager::instance()->registerInstance( id );
}
void SearchManager::unregisterInstance( const QString &id )
{
SearchTaskManager::instance()->unregisterInstance( id );
}
QVector<AbstractSearchPlugin *> SearchManager::searchPlugins() const
{
return mPlugins;
}
void SearchManager::loadSearchPlugins()
{
QStringList loadedPlugins;
const QString pluginOverride = QString::fromLatin1( qgetenv( "AKONADI_OVERRIDE_SEARCHPLUGIN" ) );
if ( !pluginOverride.isEmpty() ) {
akDebug() << "Overriding the search plugins with: " << pluginOverride;
}
const QStringList dirs = XdgBaseDirs::findPluginDirs();
Q_FOREACH ( const QString &pluginDir, dirs ) {
QDir dir( pluginDir + QLatin1String( "/akonadi" ) );
const QStringList desktopFiles = dir.entryList( QStringList() << QLatin1String( "*.desktop" ), QDir::Files );
qDebug() << "SEARCH MANAGER: searching in " << pluginDir + QLatin1String( "/akonadi" ) << ":" << desktopFiles;
Q_FOREACH ( const QString &desktopFileName, desktopFiles ) {
QSettings desktop( pluginDir + QLatin1String( "/akonadi/" ) + desktopFileName, QSettings::IniFormat );
desktop.beginGroup( QLatin1String( "Desktop Entry" ) );
if ( desktop.value( QLatin1String( "Type" ) ).toString() != QLatin1String( "AkonadiSearchPlugin" ) ) {
continue;
}
const QString libraryName = desktop.value( QLatin1String( "X-Akonadi-Library" ) ).toString();
if ( loadedPlugins.contains( libraryName ) ) {
qDebug() << "Already loaded one version of this plugin, skipping: " << libraryName;
continue;
}
// When search plugin override is active, ignore all plugins except for the override
if ( !pluginOverride.isEmpty() ) {
if ( libraryName != pluginOverride ) {
qDebug() << desktopFileName << "skipped because of AKONADI_OVERRIDE_SEARCHPLUGIN";
continue;
}
// When there's no override, only load plugins enabled by default
} else if ( !desktop.value( QLatin1String( "X-Akonadi-LoadByDefault" ), true ).toBool() ) {
continue;
}
const QString pluginFile = XdgBaseDirs::findPluginFile( libraryName, QStringList() << pluginDir + QLatin1String( "/akonadi") );
QPluginLoader loader( pluginFile );
if ( !loader.load() ) {
akError() << "Failed to load search plugin" << libraryName << ":" << loader.errorString();
continue;
}
AbstractSearchPlugin *plugin = qobject_cast<AbstractSearchPlugin *>( loader.instance() );
if ( !plugin ) {
akError() << libraryName << "is not a valid Akonadi search plugin";
continue;
}
qDebug() << "SearchManager: loaded search plugin" << libraryName;
mPlugins << plugin;
loadedPlugins << libraryName;
}
}
}
void SearchManager::scheduleSearchUpdate()
{
// Reset if the timer is active
mSearchUpdateTimer->start();
}
void SearchManager::searchUpdateTimeout()
{
// Get all search collections, that is subcollections of "Search", which always has ID 1
const Collection::List collections = Collection::retrieveFiltered( Collection::parentIdFullColumnName(), 1 );
Q_FOREACH ( const Collection &collection, collections ) {
updateSearchAsync( collection );
}
}
void SearchManager::updateSearchAsync( const Collection& collection )
{
QMetaObject::invokeMethod( this, "updateSearchImpl",
Qt::QueuedConnection,
Q_ARG( Collection, collection ),
Q_ARG( QWaitCondition*, 0 ) );
}
void SearchManager::updateSearch( const Collection &collection )
{
QMutex mutex;
QWaitCondition cond;
mLock.lock();
if ( mUpdatingCollections.contains( collection.id() ) ) {
mLock.unlock();
return;
}
mUpdatingCollections.insert( collection.id() );
mLock.unlock();
QMetaObject::invokeMethod( this, "updateSearchImpl",
Qt::QueuedConnection,
Q_ARG( Collection, collection ),
Q_ARG( QWaitCondition*, &cond ) );
// Now wait for updateSearchImpl to wake us.
mutex.lock();
cond.wait( &mutex );
mutex.unlock();
mLock.lock();
mUpdatingCollections.remove( collection.id() );
mLock.unlock();
}
#define wakeUpCaller(cond) \
if (cond) { \
cond->wakeAll(); \
}
void SearchManager::updateSearchImpl( const Collection &collection, QWaitCondition *cond )
{
if ( collection.queryString().size() >= 32768 ) {
qWarning() << "The query is at least 32768 chars long, which is the maximum size supported by the akonadi db schema. The query is therefore most likely truncated and will not be executed.";
wakeUpCaller(cond);
return;
}
if ( collection.queryString().isEmpty() ) {
wakeUpCaller(cond);
return;
}
const QStringList queryAttributes = collection.queryAttributes().split( QLatin1Char (' ') );
const bool remoteSearch = queryAttributes.contains( QLatin1String( AKONADI_PARAM_REMOTE ) );
bool recursive = queryAttributes.contains( QLatin1String( AKONADI_PARAM_RECURSIVE ) );
QStringList queryMimeTypes;
Q_FOREACH ( const MimeType &mt, collection.mimeTypes() ) {
queryMimeTypes << mt.name();
}
QVector<qint64> queryCollections, queryAncestors;
if ( collection.queryCollections().isEmpty() ) {
queryAncestors << 0;
recursive = true;
} else {
Q_FOREACH ( const QString &colId, collection.queryCollections().split( QLatin1Char( ' ' ) ) ) {
queryAncestors << colId.toLongLong();
}
}
if ( recursive ) {
queryCollections = SearchHelper::listCollectionsRecursive( queryAncestors, queryMimeTypes );
} else {
queryCollections = queryAncestors;
}
//This happens if we try to search a virtual collection in recursive mode (because virtual collections are excluded from listCollectionsRecursive)
if ( queryCollections.isEmpty() ) {
akDebug() << "No collections to search, you're probably trying to search a virtual collection.";
wakeUpCaller(cond);
return;
}
// Query all plugins for search results
SearchRequest request( "searchUpdate-" + QByteArray::number( QDateTime::currentDateTime().toTime_t() ) );
request.setCollections( queryCollections );
request.setMimeTypes( queryMimeTypes );
request.setQuery( collection.queryString() );
request.setRemoteSearch( remoteSearch );
request.setStoreResults( true );
request.setProperty( "SearchCollection", QVariant::fromValue( collection ) );
connect( &request, SIGNAL(resultsAvailable(QSet<qint64>)),
this, SLOT(searchUpdateResultsAvailable(QSet<qint64>)) );
request.exec(); // blocks until all searches are done
const QSet<qint64> results = request.results();
// Get all items in the collection
QueryBuilder qb( CollectionPimItemRelation::tableName() );
qb.addColumn( CollectionPimItemRelation::rightColumn() );
qb.addValueCondition( CollectionPimItemRelation::leftColumn(), Query::Equals, collection.id() );
if ( !qb.exec() ) {
wakeUpCaller(cond);
return;
}
DataStore::self()->beginTransaction();
// Unlink all items that were not in search results from the collection
QVariantList toRemove;
while ( qb.query().next() ) {
const qint64 id = qb.query().value( 0 ).toLongLong();
if ( !results.contains( id ) ) {
toRemove << id;
Collection::removePimItem( collection.id(), id );
}
}
if ( !DataStore::self()->commitTransaction() ) {
wakeUpCaller(cond);
return;
}
if ( !toRemove.isEmpty() ) {
SelectQueryBuilder<PimItem> qb;
qb.addValueCondition( PimItem::idFullColumnName(), Query::In, toRemove );
if ( !qb.exec() ) {
wakeUpCaller(cond);
return;
}
const QVector<PimItem> removedItems = qb.result();
DataStore::self()->notificationCollector()->itemsUnlinked( removedItems, collection );
}
akDebug() << "Search update finished";
akDebug() << "All results:" << results.count();
akDebug() << "Removed results:" << toRemove.count();
wakeUpCaller(cond);
}
void SearchManager::searchUpdateResultsAvailable( const QSet<qint64> &results )
{
const Collection collection = sender()->property( "SearchCollection" ).value<Collection>();
akDebug() << "searchUpdateResultsAvailable" << collection.id() << results.count() << "results";
QSet<qint64> newMatches = results;
QSet<qint64> existingMatches;
{
QueryBuilder qb( CollectionPimItemRelation::tableName() );
qb.addColumn( CollectionPimItemRelation::rightColumn() );
qb.addValueCondition( CollectionPimItemRelation::leftColumn(), Query::Equals, collection.id() );
if ( !qb.exec() ) {
return;
}
while ( qb.query().next() ) {
const qint64 id = qb.query().value( 0 ).toLongLong();
if ( newMatches.contains( id ) ) {
existingMatches << id;
}
}
}
qDebug() << "Got" << newMatches.count() << "results, out of which" << existingMatches.count() << "are already in the collection";
newMatches = newMatches - existingMatches;
const bool existingTransaction = DataStore::self()->inTransaction();
if ( !existingTransaction ) {
DataStore::self()->beginTransaction();
}
QVariantList newMatchesVariant;
Q_FOREACH ( qint64 id, newMatches ) {
newMatchesVariant << id;
Collection::addPimItem( collection.id(), id );
}
qDebug() << "Added" << newMatches.count();
if ( !existingTransaction && !DataStore::self()->commitTransaction() ) {
akDebug() << "Failed to commit transaction";
return;
}
if ( !newMatchesVariant.isEmpty() ) {
SelectQueryBuilder<PimItem> qb;
qb.addValueCondition( PimItem::idFullColumnName(), Query::In, newMatchesVariant );
if ( !qb.exec() ) {
return ;
}
const QVector<PimItem> newItems = qb.result();
DataStore::self()->notificationCollector()->itemsLinked( newItems, collection );
// Force collector to dispatch the notification now
DataStore::self()->notificationCollector()->dispatchNotifications();
}
}
<commit_msg>Make sure mSearchUpdateTimer is started from the right thread<commit_after>/*
Copyright (c) 2010 Volker Krause <[email protected]>
Copyright (c) 2013 Daniel Vrátil <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "searchmanager.h"
#include "abstractsearchplugin.h"
#include "searchmanageradaptor.h"
#include "akdebug.h"
#include "agentsearchengine.h"
#include "nepomuksearchengine.h"
#include "notificationmanager.h"
#include "searchrequest.h"
#include "searchtaskmanager.h"
#include "storage/datastore.h"
#include "storage/querybuilder.h"
#include "storage/transaction.h"
#include "storage/selectquerybuilder.h"
#include "searchhelper.h"
#include "libs/xdgbasedirs_p.h"
#include "libs/protocol_p.h"
#include <QDir>
#include <QPluginLoader>
#include <QDBusConnection>
#include <QTimer>
Q_DECLARE_METATYPE( Akonadi::Server::NotificationCollector* )
using namespace Akonadi;
using namespace Akonadi::Server;
SearchManager *SearchManager::sInstance = 0;
Q_DECLARE_METATYPE( Collection )
Q_DECLARE_METATYPE( QSet<qint64> )
Q_DECLARE_METATYPE( QWaitCondition* )
SearchManagerThread::SearchManagerThread( const QStringList &searchEngines, QObject *parent )
: QThread( parent )
, mSearchEngines( searchEngines )
{
Q_ASSERT( QThread::currentThread() == QCoreApplication::instance()->thread() );
}
SearchManagerThread::~SearchManagerThread()
{
}
void SearchManagerThread::run()
{
SearchManager *manager = new SearchManager( mSearchEngines );
exec();
delete manager;
}
SearchManager::SearchManager( const QStringList &searchEngines, QObject *parent )
: QObject( parent )
{
qRegisterMetaType< QSet<qint64> >();
qRegisterMetaType<Collection>();
qRegisterMetaType<QWaitCondition*>();
Q_ASSERT( sInstance == 0 );
sInstance = this;
mEngines.reserve( searchEngines.size() );
Q_FOREACH ( const QString &engineName, searchEngines ) {
if ( engineName == QLatin1String( "Nepomuk" ) ) {
#ifdef HAVE_SOPRANO
m_engines.append( new NepomukSearchEngine );
#endif
} else if ( engineName == QLatin1String( "Agent" ) ) {
mEngines.append( new AgentSearchEngine );
} else {
akError() << "Unknown search engine type: " << engineName;
}
}
loadSearchPlugins();
new SearchManagerAdaptor( this );
QDBusConnection::sessionBus().registerObject(
QLatin1String( "/SearchManager" ),
this,
QDBusConnection::ExportAdaptors );
// The timer will tick 15 seconds after last change notification. If a new notification
// is delivered in the meantime, the timer is reset
mSearchUpdateTimer = new QTimer( this );
mSearchUpdateTimer->setInterval( 15 * 1000 );
mSearchUpdateTimer->setSingleShot( true );
connect( mSearchUpdateTimer, SIGNAL(timeout()),
this, SLOT(searchUpdateTimeout()) );
DataStore::self();
}
SearchManager::~SearchManager()
{
qDeleteAll( mEngines );
DataStore::self()->close();
sInstance = 0;
}
SearchManager *SearchManager::instance()
{
Q_ASSERT( sInstance );
return sInstance;
}
void SearchManager::registerInstance( const QString &id )
{
SearchTaskManager::instance()->registerInstance( id );
}
void SearchManager::unregisterInstance( const QString &id )
{
SearchTaskManager::instance()->unregisterInstance( id );
}
QVector<AbstractSearchPlugin *> SearchManager::searchPlugins() const
{
return mPlugins;
}
void SearchManager::loadSearchPlugins()
{
QStringList loadedPlugins;
const QString pluginOverride = QString::fromLatin1( qgetenv( "AKONADI_OVERRIDE_SEARCHPLUGIN" ) );
if ( !pluginOverride.isEmpty() ) {
akDebug() << "Overriding the search plugins with: " << pluginOverride;
}
const QStringList dirs = XdgBaseDirs::findPluginDirs();
Q_FOREACH ( const QString &pluginDir, dirs ) {
QDir dir( pluginDir + QLatin1String( "/akonadi" ) );
const QStringList desktopFiles = dir.entryList( QStringList() << QLatin1String( "*.desktop" ), QDir::Files );
qDebug() << "SEARCH MANAGER: searching in " << pluginDir + QLatin1String( "/akonadi" ) << ":" << desktopFiles;
Q_FOREACH ( const QString &desktopFileName, desktopFiles ) {
QSettings desktop( pluginDir + QLatin1String( "/akonadi/" ) + desktopFileName, QSettings::IniFormat );
desktop.beginGroup( QLatin1String( "Desktop Entry" ) );
if ( desktop.value( QLatin1String( "Type" ) ).toString() != QLatin1String( "AkonadiSearchPlugin" ) ) {
continue;
}
const QString libraryName = desktop.value( QLatin1String( "X-Akonadi-Library" ) ).toString();
if ( loadedPlugins.contains( libraryName ) ) {
qDebug() << "Already loaded one version of this plugin, skipping: " << libraryName;
continue;
}
// When search plugin override is active, ignore all plugins except for the override
if ( !pluginOverride.isEmpty() ) {
if ( libraryName != pluginOverride ) {
qDebug() << desktopFileName << "skipped because of AKONADI_OVERRIDE_SEARCHPLUGIN";
continue;
}
// When there's no override, only load plugins enabled by default
} else if ( !desktop.value( QLatin1String( "X-Akonadi-LoadByDefault" ), true ).toBool() ) {
continue;
}
const QString pluginFile = XdgBaseDirs::findPluginFile( libraryName, QStringList() << pluginDir + QLatin1String( "/akonadi") );
QPluginLoader loader( pluginFile );
if ( !loader.load() ) {
akError() << "Failed to load search plugin" << libraryName << ":" << loader.errorString();
continue;
}
AbstractSearchPlugin *plugin = qobject_cast<AbstractSearchPlugin *>( loader.instance() );
if ( !plugin ) {
akError() << libraryName << "is not a valid Akonadi search plugin";
continue;
}
qDebug() << "SearchManager: loaded search plugin" << libraryName;
mPlugins << plugin;
loadedPlugins << libraryName;
}
}
}
void SearchManager::scheduleSearchUpdate()
{
// Reset if the timer is active (use QueuedConnection to invoke start() from
// the thread the QTimer lives in instead of caller's thread, otherwise crashes
// and weird things can happen.
QMetaObject::invokeMethod( mSearchUpdateTimer, "start", Qt::QueuedConnection );
}
void SearchManager::searchUpdateTimeout()
{
// Get all search collections, that is subcollections of "Search", which always has ID 1
const Collection::List collections = Collection::retrieveFiltered( Collection::parentIdFullColumnName(), 1 );
Q_FOREACH ( const Collection &collection, collections ) {
updateSearchAsync( collection );
}
}
void SearchManager::updateSearchAsync( const Collection& collection )
{
QMetaObject::invokeMethod( this, "updateSearchImpl",
Qt::QueuedConnection,
Q_ARG( Collection, collection ),
Q_ARG( QWaitCondition*, 0 ) );
}
void SearchManager::updateSearch( const Collection &collection )
{
QMutex mutex;
QWaitCondition cond;
mLock.lock();
if ( mUpdatingCollections.contains( collection.id() ) ) {
mLock.unlock();
return;
}
mUpdatingCollections.insert( collection.id() );
mLock.unlock();
QMetaObject::invokeMethod( this, "updateSearchImpl",
Qt::QueuedConnection,
Q_ARG( Collection, collection ),
Q_ARG( QWaitCondition*, &cond ) );
// Now wait for updateSearchImpl to wake us.
mutex.lock();
cond.wait( &mutex );
mutex.unlock();
mLock.lock();
mUpdatingCollections.remove( collection.id() );
mLock.unlock();
}
#define wakeUpCaller(cond) \
if (cond) { \
cond->wakeAll(); \
}
void SearchManager::updateSearchImpl( const Collection &collection, QWaitCondition *cond )
{
if ( collection.queryString().size() >= 32768 ) {
qWarning() << "The query is at least 32768 chars long, which is the maximum size supported by the akonadi db schema. The query is therefore most likely truncated and will not be executed.";
wakeUpCaller(cond);
return;
}
if ( collection.queryString().isEmpty() ) {
wakeUpCaller(cond);
return;
}
const QStringList queryAttributes = collection.queryAttributes().split( QLatin1Char (' ') );
const bool remoteSearch = queryAttributes.contains( QLatin1String( AKONADI_PARAM_REMOTE ) );
bool recursive = queryAttributes.contains( QLatin1String( AKONADI_PARAM_RECURSIVE ) );
QStringList queryMimeTypes;
Q_FOREACH ( const MimeType &mt, collection.mimeTypes() ) {
queryMimeTypes << mt.name();
}
QVector<qint64> queryCollections, queryAncestors;
if ( collection.queryCollections().isEmpty() ) {
queryAncestors << 0;
recursive = true;
} else {
Q_FOREACH ( const QString &colId, collection.queryCollections().split( QLatin1Char( ' ' ) ) ) {
queryAncestors << colId.toLongLong();
}
}
if ( recursive ) {
queryCollections = SearchHelper::listCollectionsRecursive( queryAncestors, queryMimeTypes );
} else {
queryCollections = queryAncestors;
}
//This happens if we try to search a virtual collection in recursive mode (because virtual collections are excluded from listCollectionsRecursive)
if ( queryCollections.isEmpty() ) {
akDebug() << "No collections to search, you're probably trying to search a virtual collection.";
wakeUpCaller(cond);
return;
}
// Query all plugins for search results
SearchRequest request( "searchUpdate-" + QByteArray::number( QDateTime::currentDateTime().toTime_t() ) );
request.setCollections( queryCollections );
request.setMimeTypes( queryMimeTypes );
request.setQuery( collection.queryString() );
request.setRemoteSearch( remoteSearch );
request.setStoreResults( true );
request.setProperty( "SearchCollection", QVariant::fromValue( collection ) );
connect( &request, SIGNAL(resultsAvailable(QSet<qint64>)),
this, SLOT(searchUpdateResultsAvailable(QSet<qint64>)) );
request.exec(); // blocks until all searches are done
const QSet<qint64> results = request.results();
// Get all items in the collection
QueryBuilder qb( CollectionPimItemRelation::tableName() );
qb.addColumn( CollectionPimItemRelation::rightColumn() );
qb.addValueCondition( CollectionPimItemRelation::leftColumn(), Query::Equals, collection.id() );
if ( !qb.exec() ) {
wakeUpCaller(cond);
return;
}
DataStore::self()->beginTransaction();
// Unlink all items that were not in search results from the collection
QVariantList toRemove;
while ( qb.query().next() ) {
const qint64 id = qb.query().value( 0 ).toLongLong();
if ( !results.contains( id ) ) {
toRemove << id;
Collection::removePimItem( collection.id(), id );
}
}
if ( !DataStore::self()->commitTransaction() ) {
wakeUpCaller(cond);
return;
}
if ( !toRemove.isEmpty() ) {
SelectQueryBuilder<PimItem> qb;
qb.addValueCondition( PimItem::idFullColumnName(), Query::In, toRemove );
if ( !qb.exec() ) {
wakeUpCaller(cond);
return;
}
const QVector<PimItem> removedItems = qb.result();
DataStore::self()->notificationCollector()->itemsUnlinked( removedItems, collection );
}
akDebug() << "Search update finished";
akDebug() << "All results:" << results.count();
akDebug() << "Removed results:" << toRemove.count();
wakeUpCaller(cond);
}
void SearchManager::searchUpdateResultsAvailable( const QSet<qint64> &results )
{
const Collection collection = sender()->property( "SearchCollection" ).value<Collection>();
akDebug() << "searchUpdateResultsAvailable" << collection.id() << results.count() << "results";
QSet<qint64> newMatches = results;
QSet<qint64> existingMatches;
{
QueryBuilder qb( CollectionPimItemRelation::tableName() );
qb.addColumn( CollectionPimItemRelation::rightColumn() );
qb.addValueCondition( CollectionPimItemRelation::leftColumn(), Query::Equals, collection.id() );
if ( !qb.exec() ) {
return;
}
while ( qb.query().next() ) {
const qint64 id = qb.query().value( 0 ).toLongLong();
if ( newMatches.contains( id ) ) {
existingMatches << id;
}
}
}
qDebug() << "Got" << newMatches.count() << "results, out of which" << existingMatches.count() << "are already in the collection";
newMatches = newMatches - existingMatches;
const bool existingTransaction = DataStore::self()->inTransaction();
if ( !existingTransaction ) {
DataStore::self()->beginTransaction();
}
QVariantList newMatchesVariant;
Q_FOREACH ( qint64 id, newMatches ) {
newMatchesVariant << id;
Collection::addPimItem( collection.id(), id );
}
qDebug() << "Added" << newMatches.count();
if ( !existingTransaction && !DataStore::self()->commitTransaction() ) {
akDebug() << "Failed to commit transaction";
return;
}
if ( !newMatchesVariant.isEmpty() ) {
SelectQueryBuilder<PimItem> qb;
qb.addValueCondition( PimItem::idFullColumnName(), Query::In, newMatchesVariant );
if ( !qb.exec() ) {
return ;
}
const QVector<PimItem> newItems = qb.result();
DataStore::self()->notificationCollector()->itemsLinked( newItems, collection );
// Force collector to dispatch the notification now
DataStore::self()->notificationCollector()->dispatchNotifications();
}
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include "../rwbase.h"
#include "../rwerror.h"
#include "../rwplg.h"
#include "../rwpipeline.h"
#include "../rwobjects.h"
#include "../rwengine.h"
#ifdef RW_OPENGL
#include <GL/glew.h>
#endif
#include "rwgl3.h"
#include "rwgl3shader.h"
#define PLUGIN_ID ID_DRIVER
namespace rw {
namespace gl3 {
int32 nativeRasterOffset;
#ifdef RW_OPENGL
static Raster*
rasterCreateTexture(Raster *raster)
{
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(raster->format & 0xF00){
case Raster::C8888:
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case Raster::C888:
natras->internalFormat = GL_RGB;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case Raster::C1555:
// TODO: check if this is correct
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
default:
RWERROR((ERR_INVRASTER));
return nil;
}
glGenTextures(1, &natras->texid);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, nil);
natras->filterMode = 0;
natras->addressU = 0;
natras->addressV = 0;
glBindTexture(GL_TEXTURE_2D, 0);
return raster;
}
// This is totally fake right now, can't render to it. Only used to copy into from FB
// For rendering the idea would probably be to render to the backbuffer and copy it here afterwards.
// alternatively just use FBOs but that probably needs some more infrastructure.
static Raster*
rasterCreateCameraTexture(Raster *raster)
{
if(raster->format & (Raster::PAL4 | Raster::PAL8)){
RWERROR((ERR_NOTEXTURE));
return nil;
}
// TODO: figure out what the backbuffer is and use that as a default
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(raster->format & 0xF00){
case Raster::C8888:
default:
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case Raster::C888:
natras->internalFormat = GL_RGB;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case Raster::C1555:
// TODO: check if this is correct
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
}
glGenTextures(1, &natras->texid);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, nil);
natras->filterMode = 0;
natras->addressU = 0;
natras->addressV = 0;
glBindTexture(GL_TEXTURE_2D, 0);
return raster;
}
static Raster*
rasterCreateCamera(Raster *raster)
{
// TODO: set/check width, height, depth, format?
raster->flags |= Raster::DONTALLOCATE;
raster->originalWidth = raster->width;
raster->originalHeight = raster->height;
raster->stride = 0;
raster->pixels = nil;
return raster;
}
static Raster*
rasterCreateZbuffer(Raster *raster)
{
// TODO: set/check width, height, depth, format?
raster->flags |= Raster::DONTALLOCATE;
return raster;
}
#endif
Raster*
rasterCreate(Raster *raster)
{
switch(raster->type){
#ifdef RW_OPENGL
case Raster::NORMAL:
case Raster::TEXTURE:
// Dummy to use as subraster
// ^ what did i do there?
if(raster->width == 0 || raster->height == 0){
raster->flags |= Raster::DONTALLOCATE;
raster->stride = 0;
return raster;
}
if(raster->flags & Raster::DONTALLOCATE)
return raster;
return rasterCreateTexture(raster);
case Raster::CAMERATEXTURE:
if(raster->flags & Raster::DONTALLOCATE)
return raster;
return rasterCreateCameraTexture(raster);
case Raster::ZBUFFER:
return rasterCreateZbuffer(raster);
case Raster::CAMERA:
return rasterCreateCamera(raster);
#endif
default:
RWERROR((ERR_INVRASTER));
return nil;
}
}
uint8*
rasterLock(Raster*, int32 level, int32 lockMode)
{
printf("locking\n");
return nil;
}
void
rasterUnlock(Raster*, int32)
{
printf("unlocking\n");
}
int32
rasterNumLevels(Raster*)
{
printf("numlevels\n");
return 0;
}
// Almost the same as d3d9 and ps2 function
bool32
imageFindRasterFormat(Image *img, int32 type,
int32 *pWidth, int32 *pHeight, int32 *pDepth, int32 *pFormat)
{
int32 width, height, depth, format;
assert((type&0xF) == Raster::TEXTURE);
for(width = 1; width < img->width; width <<= 1);
for(height = 1; height < img->height; height <<= 1);
depth = img->depth;
if(depth <= 8)
depth = 32;
switch(depth){
case 32:
if(img->hasAlpha())
format = Raster::C8888;
else{
format = Raster::C888;
depth = 24;
}
break;
case 24:
format = Raster::C888;
break;
case 16:
format = Raster::C1555;
break;
case 8:
case 4:
default:
RWERROR((ERR_INVRASTER));
return 0;
}
format |= type;
*pWidth = width;
*pHeight = height;
*pDepth = depth;
*pFormat = format;
return 1;
}
static uint8*
flipImage(Image *image)
{
int i;
uint8 *newPx = (uint8*)rwMalloc(image->stride*image->height, 0);
for(i = 0; i < image->height; i++)
memcpy(&newPx[i*image->stride], &image->pixels[(image->height-1-i)*image->stride], image->stride);
return newPx;
}
bool32
rasterFromImage(Raster *raster, Image *image)
{
if((raster->type&0xF) != Raster::TEXTURE)
return 0;
#ifdef RW_OPENGL
// Unpalettize image if necessary but don't change original
Image *truecolimg = nil;
if(image->depth <= 8){
truecolimg = Image::create(image->width, image->height, image->depth);
truecolimg->pixels = image->pixels;
truecolimg->stride = image->stride;
truecolimg->palette = image->palette;
truecolimg->unindex();
image = truecolimg;
}
// NB: important to set the format of the input data here!
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(image->depth){
case 32:
if(raster->format != Raster::C8888 &&
raster->format != Raster::C888)
goto err;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case 24:
if(raster->format != Raster::C888) goto err;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case 16:
if(raster->format != Raster::C1555) goto err;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
case 8:
case 4:
default:
err:
RWERROR((ERR_INVRASTER));
return 0;
}
natras->hasAlpha = image->hasAlpha();
uint8 *flipped = flipImage(image);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, flipped);
glBindTexture(GL_TEXTURE_2D, 0);
rwFree(flipped);
#endif
return 1;
}
static void*
createNativeRaster(void *object, int32 offset, int32)
{
Gl3Raster *ras = PLUGINOFFSET(Gl3Raster, object, offset);
ras->texid = 0;
return object;
}
static void*
destroyNativeRaster(void *object, int32, int32)
{
//Gl3Raster *ras = PLUGINOFFSET(Gl3Raster, object, offset);
// TODO
return object;
}
static void*
copyNativeRaster(void *dst, void *, int32 offset, int32)
{
Gl3Raster *d = PLUGINOFFSET(Gl3Raster, dst, offset);
d->texid = 0;
return dst;
}
void registerNativeRaster(void)
{
nativeRasterOffset = Raster::registerPlugin(sizeof(Gl3Raster),
ID_RASTERGL3,
createNativeRaster,
destroyNativeRaster,
copyNativeRaster);
}
}
}
<commit_msg>changed camtex format<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include "../rwbase.h"
#include "../rwerror.h"
#include "../rwplg.h"
#include "../rwpipeline.h"
#include "../rwobjects.h"
#include "../rwengine.h"
#ifdef RW_OPENGL
#include <GL/glew.h>
#endif
#include "rwgl3.h"
#include "rwgl3shader.h"
#define PLUGIN_ID ID_DRIVER
namespace rw {
namespace gl3 {
int32 nativeRasterOffset;
#ifdef RW_OPENGL
static Raster*
rasterCreateTexture(Raster *raster)
{
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(raster->format & 0xF00){
case Raster::C8888:
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case Raster::C888:
natras->internalFormat = GL_RGB;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case Raster::C1555:
// TODO: check if this is correct
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
default:
RWERROR((ERR_INVRASTER));
return nil;
}
glGenTextures(1, &natras->texid);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, nil);
natras->filterMode = 0;
natras->addressU = 0;
natras->addressV = 0;
glBindTexture(GL_TEXTURE_2D, 0);
return raster;
}
// This is totally fake right now, can't render to it. Only used to copy into from FB
// For rendering the idea would probably be to render to the backbuffer and copy it here afterwards.
// alternatively just use FBOs but that probably needs some more infrastructure.
static Raster*
rasterCreateCameraTexture(Raster *raster)
{
if(raster->format & (Raster::PAL4 | Raster::PAL8)){
RWERROR((ERR_NOTEXTURE));
return nil;
}
// TODO: figure out what the backbuffer is and use that as a default
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(raster->format & 0xF00){
case Raster::C8888:
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case Raster::C888:
default:
natras->internalFormat = GL_RGB;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case Raster::C1555:
// TODO: check if this is correct
natras->internalFormat = GL_RGBA;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
}
glGenTextures(1, &natras->texid);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, nil);
natras->filterMode = 0;
natras->addressU = 0;
natras->addressV = 0;
glBindTexture(GL_TEXTURE_2D, 0);
return raster;
}
static Raster*
rasterCreateCamera(Raster *raster)
{
// TODO: set/check width, height, depth, format?
raster->flags |= Raster::DONTALLOCATE;
raster->originalWidth = raster->width;
raster->originalHeight = raster->height;
raster->stride = 0;
raster->pixels = nil;
return raster;
}
static Raster*
rasterCreateZbuffer(Raster *raster)
{
// TODO: set/check width, height, depth, format?
raster->flags |= Raster::DONTALLOCATE;
return raster;
}
#endif
Raster*
rasterCreate(Raster *raster)
{
switch(raster->type){
#ifdef RW_OPENGL
case Raster::NORMAL:
case Raster::TEXTURE:
// Dummy to use as subraster
// ^ what did i do there?
if(raster->width == 0 || raster->height == 0){
raster->flags |= Raster::DONTALLOCATE;
raster->stride = 0;
return raster;
}
if(raster->flags & Raster::DONTALLOCATE)
return raster;
return rasterCreateTexture(raster);
case Raster::CAMERATEXTURE:
if(raster->flags & Raster::DONTALLOCATE)
return raster;
return rasterCreateCameraTexture(raster);
case Raster::ZBUFFER:
return rasterCreateZbuffer(raster);
case Raster::CAMERA:
return rasterCreateCamera(raster);
#endif
default:
RWERROR((ERR_INVRASTER));
return nil;
}
}
uint8*
rasterLock(Raster*, int32 level, int32 lockMode)
{
printf("locking\n");
return nil;
}
void
rasterUnlock(Raster*, int32)
{
printf("unlocking\n");
}
int32
rasterNumLevels(Raster*)
{
printf("numlevels\n");
return 0;
}
// Almost the same as d3d9 and ps2 function
bool32
imageFindRasterFormat(Image *img, int32 type,
int32 *pWidth, int32 *pHeight, int32 *pDepth, int32 *pFormat)
{
int32 width, height, depth, format;
assert((type&0xF) == Raster::TEXTURE);
for(width = 1; width < img->width; width <<= 1);
for(height = 1; height < img->height; height <<= 1);
depth = img->depth;
if(depth <= 8)
depth = 32;
switch(depth){
case 32:
if(img->hasAlpha())
format = Raster::C8888;
else{
format = Raster::C888;
depth = 24;
}
break;
case 24:
format = Raster::C888;
break;
case 16:
format = Raster::C1555;
break;
case 8:
case 4:
default:
RWERROR((ERR_INVRASTER));
return 0;
}
format |= type;
*pWidth = width;
*pHeight = height;
*pDepth = depth;
*pFormat = format;
return 1;
}
static uint8*
flipImage(Image *image)
{
int i;
uint8 *newPx = (uint8*)rwMalloc(image->stride*image->height, 0);
for(i = 0; i < image->height; i++)
memcpy(&newPx[i*image->stride], &image->pixels[(image->height-1-i)*image->stride], image->stride);
return newPx;
}
bool32
rasterFromImage(Raster *raster, Image *image)
{
if((raster->type&0xF) != Raster::TEXTURE)
return 0;
#ifdef RW_OPENGL
// Unpalettize image if necessary but don't change original
Image *truecolimg = nil;
if(image->depth <= 8){
truecolimg = Image::create(image->width, image->height, image->depth);
truecolimg->pixels = image->pixels;
truecolimg->stride = image->stride;
truecolimg->palette = image->palette;
truecolimg->unindex();
image = truecolimg;
}
// NB: important to set the format of the input data here!
Gl3Raster *natras = PLUGINOFFSET(Gl3Raster, raster, nativeRasterOffset);
switch(image->depth){
case 32:
if(raster->format != Raster::C8888 &&
raster->format != Raster::C888)
goto err;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 1;
break;
case 24:
if(raster->format != Raster::C888) goto err;
natras->format = GL_RGB;
natras->type = GL_UNSIGNED_BYTE;
natras->hasAlpha = 0;
break;
case 16:
if(raster->format != Raster::C1555) goto err;
natras->format = GL_RGBA;
natras->type = GL_UNSIGNED_SHORT_1_5_5_5_REV;
natras->hasAlpha = 1;
break;
case 8:
case 4:
default:
err:
RWERROR((ERR_INVRASTER));
return 0;
}
natras->hasAlpha = image->hasAlpha();
uint8 *flipped = flipImage(image);
glBindTexture(GL_TEXTURE_2D, natras->texid);
glTexImage2D(GL_TEXTURE_2D, 0, natras->internalFormat,
raster->width, raster->height,
0, natras->format, natras->type, flipped);
glBindTexture(GL_TEXTURE_2D, 0);
rwFree(flipped);
#endif
return 1;
}
static void*
createNativeRaster(void *object, int32 offset, int32)
{
Gl3Raster *ras = PLUGINOFFSET(Gl3Raster, object, offset);
ras->texid = 0;
return object;
}
static void*
destroyNativeRaster(void *object, int32, int32)
{
//Gl3Raster *ras = PLUGINOFFSET(Gl3Raster, object, offset);
// TODO
return object;
}
static void*
copyNativeRaster(void *dst, void *, int32 offset, int32)
{
Gl3Raster *d = PLUGINOFFSET(Gl3Raster, dst, offset);
d->texid = 0;
return dst;
}
void registerNativeRaster(void)
{
nativeRasterOffset = Raster::registerPlugin(sizeof(Gl3Raster),
ID_RASTERGL3,
createNativeRaster,
destroyNativeRaster,
copyNativeRaster);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Internal.hxx"
#include "Handler.hxx"
#include "Request.hxx"
#include "strmap.hxx"
#include "address_string.hxx"
#include "pool/pool.hxx"
#include "pool/PSocketAddress.hxx"
#include "istream/Bucket.hxx"
#include "system/Error.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "util/StringView.hxx"
#include "util/StaticArray.hxx"
#include "util/RuntimeError.hxx"
#include <assert.h>
#include <unistd.h>
const Event::Duration http_server_idle_timeout = std::chrono::seconds(30);
const Event::Duration http_server_read_timeout = std::chrono::seconds(30);
const Event::Duration http_server_write_timeout = std::chrono::seconds(30);
void
HttpServerConnection::Log() noexcept
{
if (handler == nullptr)
/* this can happen when called via
http_server_connection_close() (during daemon shutdown) */
return;
handler->LogHttpRequest(*request.request,
response.status,
response.length,
request.bytes_received,
response.bytes_sent);
}
HttpServerRequest *
http_server_request_new(HttpServerConnection *connection,
http_method_t method,
StringView uri) noexcept
{
assert(connection != nullptr);
connection->response.status = http_status_t(0);
auto pool = pool_new_linear(connection->pool,
"http_server_request", 8192);
pool_set_major(pool);
return NewFromPool<HttpServerRequest>(std::move(pool),
*connection,
connection->local_address,
connection->remote_address,
connection->local_host_and_port,
connection->remote_host,
method, uri);
}
HttpServerConnection::BucketResult
HttpServerConnection::TryWriteBuckets2()
{
assert(IsValid());
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
if (socket.HasFilter())
return BucketResult::UNAVAILABLE;
IstreamBucketList list;
try {
response.istream.FillBucketList(list);
} catch (...) {
std::throw_with_nested(std::runtime_error("error on HTTP response stream"));
}
StaticArray<struct iovec, 64> v;
for (const auto &bucket : list) {
if (bucket.GetType() != IstreamBucket::Type::BUFFER)
break;
const auto buffer = bucket.GetBuffer();
auto &tail = v.append();
tail.iov_base = const_cast<void *>(buffer.data);
tail.iov_len = buffer.size;
if (v.full())
break;
}
if (v.empty()) {
return list.HasMore()
? BucketResult::UNAVAILABLE
: BucketResult::DEPLETED;
}
ssize_t nbytes = socket.WriteV(v.begin(), v.size());
if (nbytes < 0) {
if (gcc_likely(nbytes == WRITE_BLOCKING))
return BucketResult::BLOCKING;
if (nbytes == WRITE_DESTROYED)
return BucketResult::DESTROYED;
SocketErrorErrno("write error on HTTP connection");
return BucketResult::DESTROYED;
}
response.bytes_sent += nbytes;
response.length += nbytes;
size_t consumed = response.istream.ConsumeBucketList(nbytes);
assert(consumed == (size_t)nbytes);
return list.IsDepleted(consumed)
? BucketResult::DEPLETED
: BucketResult::MORE;
}
HttpServerConnection::BucketResult
HttpServerConnection::TryWriteBuckets() noexcept
{
BucketResult result;
try {
result = TryWriteBuckets2();
} catch (...) {
assert(!response.istream.IsDefined());
/* we clear this CancellablePointer here so CloseRequest()
won't think we havn't sent a response yet */
request.cancel_ptr = nullptr;
Error(std::current_exception());
return BucketResult::DESTROYED;
}
switch (result) {
case BucketResult::UNAVAILABLE:
case BucketResult::MORE:
assert(response.istream.IsDefined());
break;
case BucketResult::BLOCKING:
assert(response.istream.IsDefined());
response.want_write = true;
ScheduleWrite();
break;
case BucketResult::DEPLETED:
assert(response.istream.IsDefined());
response.istream.ClearAndClose();
if (!ResponseIstreamFinished())
result = BucketResult::DESTROYED;
break;
case BucketResult::DESTROYED:
break;
}
return result;
}
bool
HttpServerConnection::TryWrite() noexcept
{
assert(IsValid());
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
switch (TryWriteBuckets()) {
case BucketResult::UNAVAILABLE:
case BucketResult::MORE:
break;
case BucketResult::BLOCKING:
case BucketResult::DEPLETED:
return true;
case BucketResult::DESTROYED:
return false;
}
const DestructObserver destructed(*this);
response.istream.Read();
return !destructed;
}
/*
* buffered_socket handler
*
*/
BufferedResult
HttpServerConnection::OnBufferedData()
{
auto r = socket.ReadBuffer();
assert(!r.empty());
if (response.pending_drained) {
/* discard all incoming data while we're waiting for the
(filtered) response to be drained */
socket.DisposeConsumed(r.size);
return BufferedResult::OK;
}
return Feed(r.data, r.size);
}
DirectResult
HttpServerConnection::OnBufferedDirect(SocketDescriptor fd, FdType fd_type)
{
assert(request.read_state != Request::END);
assert(!response.pending_drained);
return TryRequestBodyDirect(fd, fd_type);
}
bool
HttpServerConnection::OnBufferedWrite()
{
assert(!response.pending_drained);
response.want_write = false;
if (!TryWrite())
return false;
if (!response.want_write)
socket.UnscheduleWrite();
return true;
}
bool
HttpServerConnection::OnBufferedDrained() noexcept
{
if (response.pending_drained) {
Done();
return false;
}
return true;
}
bool
HttpServerConnection::OnBufferedClosed() noexcept
{
Cancel();
return false;
}
void
HttpServerConnection::OnBufferedError(std::exception_ptr ep) noexcept
{
SocketError(ep);
}
inline void
HttpServerConnection::IdleTimeoutCallback() noexcept
{
assert(request.read_state == Request::START ||
request.read_state == Request::HEADERS);
Cancel();
}
inline
HttpServerConnection::HttpServerConnection(struct pool &_pool,
EventLoop &_loop,
UniqueSocketDescriptor &&fd, FdType fd_type,
SocketFilterPtr &&filter,
SocketAddress _local_address,
SocketAddress _remote_address,
bool _date_header,
HttpServerConnectionHandler &_handler)
:pool(&_pool), socket(_loop),
idle_timeout(_loop, BIND_THIS_METHOD(IdleTimeoutCallback)),
defer_read(_loop, BIND_THIS_METHOD(OnDeferredRead)),
handler(&_handler),
local_address(DupAddress(*pool, _local_address)),
remote_address(DupAddress(*pool, _remote_address)),
local_host_and_port(address_to_string(*pool, _local_address)),
remote_host(address_to_host_string(*pool, _remote_address)),
date_header(_date_header)
{
socket.Init(fd.Release(), fd_type,
Event::Duration(-1), http_server_write_timeout,
std::move(filter),
*this);
idle_timeout.Schedule(http_server_idle_timeout);
/* read the first request, but not in this stack frame, because a
failure may destroy the HttpServerConnection before it gets
passed to the caller */
defer_read.Schedule();
}
void
HttpServerConnection::Delete() noexcept
{
this->~HttpServerConnection();
}
HttpServerConnection *
http_server_connection_new(struct pool *pool,
EventLoop &loop,
UniqueSocketDescriptor fd, FdType fd_type,
SocketFilterPtr filter,
SocketAddress local_address,
SocketAddress remote_address,
bool date_header,
HttpServerConnectionHandler &handler) noexcept
{
assert(fd.IsDefined());
return NewFromPool<HttpServerConnection>(*pool, *pool, loop,
std::move(fd), fd_type,
std::move(filter),
local_address, remote_address,
date_header,
handler);
}
inline void
HttpServerConnection::CloseSocket() noexcept
{
assert(socket.IsConnected());
socket.Close();
idle_timeout.Cancel();
}
void
HttpServerConnection::DestroySocket() noexcept
{
assert(socket.IsValid());
if (socket.IsConnected())
CloseSocket();
socket.Destroy();
}
void
HttpServerConnection::CloseRequest() noexcept
{
assert(request.read_state != Request::START);
assert(request.request != nullptr);
if (response.status != http_status_t(0))
Log();
request.request->Destroy();
request.request = nullptr;
if ((request.read_state == Request::BODY ||
request.read_state == Request::END)) {
if (response.istream.IsDefined())
response.istream.ClearAndClose();
else if (request.cancel_ptr)
/* don't call this if coming from
_response_stream_abort() */
request.cancel_ptr.Cancel();
}
/* the handler must have closed the request body */
assert(request.read_state != Request::BODY);
}
void
HttpServerConnection::Done() noexcept
{
assert(handler != nullptr);
assert(request.read_state == Request::START);
/* shut down the socket gracefully to allow the TCP stack to
transfer remaining response data */
socket.Shutdown();
DestroySocket();
auto *_handler = handler;
handler = nullptr;
Delete();
_handler->HttpConnectionClosed();
}
void
HttpServerConnection::Cancel() noexcept
{
assert(handler != nullptr);
DestroySocket();
if (request.read_state != Request::START)
CloseRequest();
auto *_handler = std::exchange(handler, nullptr);
Delete();
if (_handler != nullptr)
_handler->HttpConnectionClosed();
}
void
HttpServerConnection::Error(std::exception_ptr e) noexcept
{
assert(handler != nullptr);
DestroySocket();
if (request.read_state != Request::START)
CloseRequest();
auto *_handler = std::exchange(handler, nullptr);
Delete();
if (_handler != nullptr)
_handler->HttpConnectionError(e);
}
void
HttpServerConnection::Error(const char *msg) noexcept
{
Error(std::make_exception_ptr(std::runtime_error(msg)));
}
void
http_server_connection_close(HttpServerConnection *connection) noexcept
{
assert(connection != nullptr);
connection->DestroySocket();
connection->handler = nullptr;
if (connection->request.read_state != HttpServerConnection::Request::START)
connection->CloseRequest();
connection->Delete();
}
void
HttpServerConnection::SocketErrorErrno(const char *msg) noexcept
{
if (errno == EPIPE || errno == ECONNRESET) {
/* don't report this common problem */
Cancel();
return;
}
try {
throw MakeErrno(msg);
} catch (...) {
Error(std::make_exception_ptr(HttpServerSocketError()));
}
}
void
http_server_connection_graceful(HttpServerConnection *connection) noexcept
{
assert(connection != nullptr);
if (connection->request.read_state == HttpServerConnection::Request::START)
/* there is no request currently; close the connection
immediately */
connection->Done();
else
/* a request is currently being handled; disable keep_alive so
the connection will be closed after this last request */
connection->keep_alive = false;
}
enum http_server_score
http_server_connection_score(const HttpServerConnection *connection) noexcept
{
return connection->score;
}
<commit_msg>http_server: destroy the request after closing it<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "Internal.hxx"
#include "Handler.hxx"
#include "Request.hxx"
#include "strmap.hxx"
#include "address_string.hxx"
#include "pool/pool.hxx"
#include "pool/PSocketAddress.hxx"
#include "istream/Bucket.hxx"
#include "system/Error.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "util/StringView.hxx"
#include "util/StaticArray.hxx"
#include "util/RuntimeError.hxx"
#include <assert.h>
#include <unistd.h>
const Event::Duration http_server_idle_timeout = std::chrono::seconds(30);
const Event::Duration http_server_read_timeout = std::chrono::seconds(30);
const Event::Duration http_server_write_timeout = std::chrono::seconds(30);
void
HttpServerConnection::Log() noexcept
{
if (handler == nullptr)
/* this can happen when called via
http_server_connection_close() (during daemon shutdown) */
return;
handler->LogHttpRequest(*request.request,
response.status,
response.length,
request.bytes_received,
response.bytes_sent);
}
HttpServerRequest *
http_server_request_new(HttpServerConnection *connection,
http_method_t method,
StringView uri) noexcept
{
assert(connection != nullptr);
connection->response.status = http_status_t(0);
auto pool = pool_new_linear(connection->pool,
"http_server_request", 8192);
pool_set_major(pool);
return NewFromPool<HttpServerRequest>(std::move(pool),
*connection,
connection->local_address,
connection->remote_address,
connection->local_host_and_port,
connection->remote_host,
method, uri);
}
HttpServerConnection::BucketResult
HttpServerConnection::TryWriteBuckets2()
{
assert(IsValid());
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
if (socket.HasFilter())
return BucketResult::UNAVAILABLE;
IstreamBucketList list;
try {
response.istream.FillBucketList(list);
} catch (...) {
std::throw_with_nested(std::runtime_error("error on HTTP response stream"));
}
StaticArray<struct iovec, 64> v;
for (const auto &bucket : list) {
if (bucket.GetType() != IstreamBucket::Type::BUFFER)
break;
const auto buffer = bucket.GetBuffer();
auto &tail = v.append();
tail.iov_base = const_cast<void *>(buffer.data);
tail.iov_len = buffer.size;
if (v.full())
break;
}
if (v.empty()) {
return list.HasMore()
? BucketResult::UNAVAILABLE
: BucketResult::DEPLETED;
}
ssize_t nbytes = socket.WriteV(v.begin(), v.size());
if (nbytes < 0) {
if (gcc_likely(nbytes == WRITE_BLOCKING))
return BucketResult::BLOCKING;
if (nbytes == WRITE_DESTROYED)
return BucketResult::DESTROYED;
SocketErrorErrno("write error on HTTP connection");
return BucketResult::DESTROYED;
}
response.bytes_sent += nbytes;
response.length += nbytes;
size_t consumed = response.istream.ConsumeBucketList(nbytes);
assert(consumed == (size_t)nbytes);
return list.IsDepleted(consumed)
? BucketResult::DEPLETED
: BucketResult::MORE;
}
HttpServerConnection::BucketResult
HttpServerConnection::TryWriteBuckets() noexcept
{
BucketResult result;
try {
result = TryWriteBuckets2();
} catch (...) {
assert(!response.istream.IsDefined());
/* we clear this CancellablePointer here so CloseRequest()
won't think we havn't sent a response yet */
request.cancel_ptr = nullptr;
Error(std::current_exception());
return BucketResult::DESTROYED;
}
switch (result) {
case BucketResult::UNAVAILABLE:
case BucketResult::MORE:
assert(response.istream.IsDefined());
break;
case BucketResult::BLOCKING:
assert(response.istream.IsDefined());
response.want_write = true;
ScheduleWrite();
break;
case BucketResult::DEPLETED:
assert(response.istream.IsDefined());
response.istream.ClearAndClose();
if (!ResponseIstreamFinished())
result = BucketResult::DESTROYED;
break;
case BucketResult::DESTROYED:
break;
}
return result;
}
bool
HttpServerConnection::TryWrite() noexcept
{
assert(IsValid());
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
switch (TryWriteBuckets()) {
case BucketResult::UNAVAILABLE:
case BucketResult::MORE:
break;
case BucketResult::BLOCKING:
case BucketResult::DEPLETED:
return true;
case BucketResult::DESTROYED:
return false;
}
const DestructObserver destructed(*this);
response.istream.Read();
return !destructed;
}
/*
* buffered_socket handler
*
*/
BufferedResult
HttpServerConnection::OnBufferedData()
{
auto r = socket.ReadBuffer();
assert(!r.empty());
if (response.pending_drained) {
/* discard all incoming data while we're waiting for the
(filtered) response to be drained */
socket.DisposeConsumed(r.size);
return BufferedResult::OK;
}
return Feed(r.data, r.size);
}
DirectResult
HttpServerConnection::OnBufferedDirect(SocketDescriptor fd, FdType fd_type)
{
assert(request.read_state != Request::END);
assert(!response.pending_drained);
return TryRequestBodyDirect(fd, fd_type);
}
bool
HttpServerConnection::OnBufferedWrite()
{
assert(!response.pending_drained);
response.want_write = false;
if (!TryWrite())
return false;
if (!response.want_write)
socket.UnscheduleWrite();
return true;
}
bool
HttpServerConnection::OnBufferedDrained() noexcept
{
if (response.pending_drained) {
Done();
return false;
}
return true;
}
bool
HttpServerConnection::OnBufferedClosed() noexcept
{
Cancel();
return false;
}
void
HttpServerConnection::OnBufferedError(std::exception_ptr ep) noexcept
{
SocketError(ep);
}
inline void
HttpServerConnection::IdleTimeoutCallback() noexcept
{
assert(request.read_state == Request::START ||
request.read_state == Request::HEADERS);
Cancel();
}
inline
HttpServerConnection::HttpServerConnection(struct pool &_pool,
EventLoop &_loop,
UniqueSocketDescriptor &&fd, FdType fd_type,
SocketFilterPtr &&filter,
SocketAddress _local_address,
SocketAddress _remote_address,
bool _date_header,
HttpServerConnectionHandler &_handler)
:pool(&_pool), socket(_loop),
idle_timeout(_loop, BIND_THIS_METHOD(IdleTimeoutCallback)),
defer_read(_loop, BIND_THIS_METHOD(OnDeferredRead)),
handler(&_handler),
local_address(DupAddress(*pool, _local_address)),
remote_address(DupAddress(*pool, _remote_address)),
local_host_and_port(address_to_string(*pool, _local_address)),
remote_host(address_to_host_string(*pool, _remote_address)),
date_header(_date_header)
{
socket.Init(fd.Release(), fd_type,
Event::Duration(-1), http_server_write_timeout,
std::move(filter),
*this);
idle_timeout.Schedule(http_server_idle_timeout);
/* read the first request, but not in this stack frame, because a
failure may destroy the HttpServerConnection before it gets
passed to the caller */
defer_read.Schedule();
}
void
HttpServerConnection::Delete() noexcept
{
this->~HttpServerConnection();
}
HttpServerConnection *
http_server_connection_new(struct pool *pool,
EventLoop &loop,
UniqueSocketDescriptor fd, FdType fd_type,
SocketFilterPtr filter,
SocketAddress local_address,
SocketAddress remote_address,
bool date_header,
HttpServerConnectionHandler &handler) noexcept
{
assert(fd.IsDefined());
return NewFromPool<HttpServerConnection>(*pool, *pool, loop,
std::move(fd), fd_type,
std::move(filter),
local_address, remote_address,
date_header,
handler);
}
inline void
HttpServerConnection::CloseSocket() noexcept
{
assert(socket.IsConnected());
socket.Close();
idle_timeout.Cancel();
}
void
HttpServerConnection::DestroySocket() noexcept
{
assert(socket.IsValid());
if (socket.IsConnected())
CloseSocket();
socket.Destroy();
}
void
HttpServerConnection::CloseRequest() noexcept
{
assert(request.read_state != Request::START);
assert(request.request != nullptr);
if (response.status != http_status_t(0))
Log();
auto *_request = std::exchange(request.request, nullptr);
if ((request.read_state == Request::BODY ||
request.read_state == Request::END)) {
if (response.istream.IsDefined())
response.istream.ClearAndClose();
else if (request.cancel_ptr)
/* don't call this if coming from
_response_stream_abort() */
request.cancel_ptr.Cancel();
}
_request->Destroy();
/* the handler must have closed the request body */
assert(request.read_state != Request::BODY);
}
void
HttpServerConnection::Done() noexcept
{
assert(handler != nullptr);
assert(request.read_state == Request::START);
/* shut down the socket gracefully to allow the TCP stack to
transfer remaining response data */
socket.Shutdown();
DestroySocket();
auto *_handler = handler;
handler = nullptr;
Delete();
_handler->HttpConnectionClosed();
}
void
HttpServerConnection::Cancel() noexcept
{
assert(handler != nullptr);
DestroySocket();
if (request.read_state != Request::START)
CloseRequest();
auto *_handler = std::exchange(handler, nullptr);
Delete();
if (_handler != nullptr)
_handler->HttpConnectionClosed();
}
void
HttpServerConnection::Error(std::exception_ptr e) noexcept
{
assert(handler != nullptr);
DestroySocket();
if (request.read_state != Request::START)
CloseRequest();
auto *_handler = std::exchange(handler, nullptr);
Delete();
if (_handler != nullptr)
_handler->HttpConnectionError(e);
}
void
HttpServerConnection::Error(const char *msg) noexcept
{
Error(std::make_exception_ptr(std::runtime_error(msg)));
}
void
http_server_connection_close(HttpServerConnection *connection) noexcept
{
assert(connection != nullptr);
connection->DestroySocket();
connection->handler = nullptr;
if (connection->request.read_state != HttpServerConnection::Request::START)
connection->CloseRequest();
connection->Delete();
}
void
HttpServerConnection::SocketErrorErrno(const char *msg) noexcept
{
if (errno == EPIPE || errno == ECONNRESET) {
/* don't report this common problem */
Cancel();
return;
}
try {
throw MakeErrno(msg);
} catch (...) {
Error(std::make_exception_ptr(HttpServerSocketError()));
}
}
void
http_server_connection_graceful(HttpServerConnection *connection) noexcept
{
assert(connection != nullptr);
if (connection->request.read_state == HttpServerConnection::Request::START)
/* there is no request currently; close the connection
immediately */
connection->Done();
else
/* a request is currently being handled; disable keep_alive so
the connection will be closed after this last request */
connection->keep_alive = false;
}
enum http_server_score
http_server_connection_score(const HttpServerConnection *connection) noexcept
{
return connection->score;
}
<|endoftext|>
|
<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_CURVE_25519)
#include "test_pubkey.h"
#include <botan/curve25519.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>
using namespace Botan;
namespace {
size_t curve25519_scalar_kat(const std::string& secret_h,
const std::string& basepoint_h,
const std::string& out_h)
{
const std::vector<byte> secret = hex_decode(secret_h);
const std::vector<byte> basepoint = hex_decode(basepoint_h);
const std::vector<byte> out = hex_decode(out_h);
std::vector<byte> got(32);
curve25519_donna(got.data(), secret.data(), basepoint.data());
if(got != out)
{
std::cout << "Got " << hex_encode(got) << " exp " << hex_encode(out) << std::endl;
return 1;
}
return 0;
}
}
size_t test_curve25519()
{
size_t fails = 0;
std::ifstream c25519_scalar(PK_TEST_DATA_DIR "/c25519_scalar.vec");
fails += run_tests_bb(c25519_scalar, "Curve25519 ScalarMult", "Out", true,
[](std::map<std::string, std::string> m) -> size_t
{
return curve25519_scalar_kat(m["Secret"], m["Basepoint"], m["Out"]);
});
return fails;
}
#else
SKIP_TEST(curve25519);
#endif // BOTAN_HAS_CURVE_25519
<commit_msg>Add a roundtrip test of curve25519 keys<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "tests.h"
#if defined(BOTAN_HAS_CURVE_25519)
#include "test_pubkey.h"
#include <botan/curve25519.h>
#include <botan/pkcs8.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>
using namespace Botan;
namespace {
size_t curve25519_scalar_kat(const std::string& secret_h,
const std::string& basepoint_h,
const std::string& out_h)
{
const std::vector<byte> secret = hex_decode(secret_h);
const std::vector<byte> basepoint = hex_decode(basepoint_h);
const std::vector<byte> out = hex_decode(out_h);
std::vector<byte> got(32);
curve25519_donna(got.data(), secret.data(), basepoint.data());
if(got != out)
{
std::cout << "Got " << hex_encode(got) << " exp " << hex_encode(out) << std::endl;
return 1;
}
return 0;
}
size_t c25519_roundtrip()
{
auto& rng = test_rng();
try
{
// First create keys
Curve25519_PrivateKey a_priv_gen(rng);
Curve25519_PrivateKey b_priv_gen(rng);
// Then serialize to encrypted storage
const auto pbe_time = std::chrono::milliseconds(10);
const std::string a_priv_pem = PKCS8::PEM_encode(a_priv_gen, rng, "alice pass", pbe_time);
const std::string b_priv_pem = PKCS8::PEM_encode(b_priv_gen, rng, "bob pass", pbe_time);
// Reload back into memory
DataSource_Memory a_priv_ds(a_priv_pem);
DataSource_Memory b_priv_ds(b_priv_pem);
std::unique_ptr<Private_Key> a_priv(PKCS8::load_key(a_priv_ds, rng, []() { return "alice pass"; }));
std::unique_ptr<Private_Key> b_priv(PKCS8::load_key(b_priv_ds, rng, "bob pass"));
// Export public keys as PEM
const std::string a_pub_pem = X509::PEM_encode(*a_priv);
const std::string b_pub_pem = X509::PEM_encode(*b_priv);
DataSource_Memory a_pub_ds(a_pub_pem);
DataSource_Memory b_pub_ds(b_pub_pem);
std::unique_ptr<Public_Key> a_pub(X509::load_key(a_pub_ds));
std::unique_ptr<Public_Key> b_pub(X509::load_key(b_pub_ds));
Curve25519_PublicKey* a_pub_key = dynamic_cast<Curve25519_PublicKey*>(a_pub.get());
Curve25519_PublicKey* b_pub_key = dynamic_cast<Curve25519_PublicKey*>(b_pub.get());
PK_Key_Agreement a_ka(*a_priv, "KDF2(SHA-256)");
PK_Key_Agreement b_ka(*b_priv, "KDF2(SHA-256)");
const std::string context = "shared context value";
SymmetricKey a_key = a_ka.derive_key(32, b_pub_key->public_value(), context);
SymmetricKey b_key = b_ka.derive_key(32, a_pub_key->public_value(), context);
if(a_key != b_key)
return 1;
}
catch(std::exception& e)
{
std::cout << "C25519 rt fail: " << e.what() << std::endl;
return 1;
}
return 0;
}
}
size_t test_curve25519()
{
test_report("Curve25519", 1, c25519_roundtrip());
size_t fails = 0;
std::ifstream c25519_scalar(PK_TEST_DATA_DIR "/c25519_scalar.vec");
fails += run_tests_bb(c25519_scalar, "Curve25519 ScalarMult", "Out", true,
[](std::map<std::string, std::string> m) -> size_t
{
return curve25519_scalar_kat(m["Secret"], m["Basepoint"], m["Out"]);
});
return fails;
}
#else
SKIP_TEST(curve25519);
#endif // BOTAN_HAS_CURVE_25519
<|endoftext|>
|
<commit_before>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
#include "precomp.hxx"
__override
HRESULT
ASPNET_CORE_PROXY_MODULE_FACTORY::GetHttpModule(
CHttpModule ** ppModule,
IModuleAllocator * pAllocator
)
{
ASPNET_CORE_PROXY_MODULE *pModule = new (pAllocator) ASPNET_CORE_PROXY_MODULE();
if (pModule == NULL)
{
return E_OUTOFMEMORY;
}
*ppModule = pModule;
return S_OK;
}
__override
VOID
ASPNET_CORE_PROXY_MODULE_FACTORY::Terminate(
VOID
)
/*++
Routine description:
Function called by IIS for global (non-request-specific) notifications
Arguments:
None.
Return value:
None
--*/
{
/* FORWARDING_HANDLER::StaticTerminate();
WEBSOCKET_HANDLER::StaticTerminate();*/
ALLOC_CACHE_HANDLER::StaticTerminate();
delete this;
}
ASPNET_CORE_PROXY_MODULE::ASPNET_CORE_PROXY_MODULE(
) : m_pApplicationInfo(NULL), m_pHandler(NULL)
{
}
ASPNET_CORE_PROXY_MODULE::~ASPNET_CORE_PROXY_MODULE()
{
if (m_pApplicationInfo != NULL)
{
m_pApplicationInfo->DereferenceApplicationInfo();
m_pApplicationInfo = NULL;
}
if (m_pHandler != NULL)
{
m_pHandler->DereferenceRequestHandler();
m_pHandler = NULL;
}
}
__override
REQUEST_NOTIFICATION_STATUS
ASPNET_CORE_PROXY_MODULE::OnExecuteRequestHandler(
IHttpContext * pHttpContext,
IHttpEventProvider *
)
{
HRESULT hr = S_OK;
ASPNETCORE_CONFIG *pConfig = NULL;
APPLICATION_MANAGER *pApplicationManager = NULL;
REQUEST_NOTIFICATION_STATUS retVal = RQ_NOTIFICATION_CONTINUE;
APPLICATION* pApplication = NULL;
STACK_STRU(struFileName, 256);
hr = ASPNETCORE_CONFIG::GetConfig(g_pHttpServer, g_pModuleId, pHttpContext, g_hEventLog, &pConfig);
if (FAILED(hr))
{
goto Finished;
}
pApplicationManager = APPLICATION_MANAGER::GetInstance();
if (pApplicationManager == NULL)
{
hr = E_OUTOFMEMORY;
goto Finished;
}
hr = pApplicationManager->GetOrCreateApplicationInfo(
g_pHttpServer,
pConfig,
&m_pApplicationInfo);
if (FAILED(hr))
{
goto Finished;
}
// app_offline check to avoid loading aspnetcorerh.dll unnecessarily
if (m_pApplicationInfo->AppOfflineFound())
{
// servicing app_offline
HTTP_DATA_CHUNK DataChunk;
IHttpResponse *pResponse = NULL;
APP_OFFLINE_HTM *pAppOfflineHtm = NULL;
pResponse = pHttpContext->GetResponse();
pAppOfflineHtm = m_pApplicationInfo->QueryAppOfflineHtm();
DBG_ASSERT(pAppOfflineHtm);
DBG_ASSERT(pResponse);
// Ignore failure hresults as nothing we can do
// Set fTrySkipCustomErrors to true as we want client see the offline content
pResponse->SetStatus(503, "Service Unavailable", 0, hr, NULL, TRUE);
pResponse->SetHeader("Content-Type",
"text/html",
(USHORT)strlen("text/html"),
FALSE
);
DataChunk.DataChunkType = HttpDataChunkFromMemory;
DataChunk.FromMemory.pBuffer = (PVOID)pAppOfflineHtm->m_Contents.QueryStr();
DataChunk.FromMemory.BufferLength = pAppOfflineHtm->m_Contents.QueryCB();
pResponse->WriteEntityChunkByReference(&DataChunk);
retVal = RQ_NOTIFICATION_FINISH_REQUEST;
goto Finished;
}
// make sure assmebly is loaded and application is created
hr = m_pApplicationInfo->EnsureApplicationCreated();
if (FAILED(hr))
{
goto Finished;
}
m_pApplicationInfo->ExtractApplication(&pApplication);
// make sure application is in running state
// cannot recreate the application as we cannot reload clr for inprocess
if (pApplication != NULL &&
pApplication->QueryStatus() != APPLICATION_STATUS::RUNNING &&
pApplication->QueryStatus() != APPLICATION_STATUS::STARTING)
{
hr = HRESULT_FROM_WIN32(ERROR_SERVER_DISABLED);
goto Finished;
}
// Create RequestHandler and process the request
hr = m_pApplicationInfo->QueryCreateRequestHandler()(pHttpContext,
(HTTP_MODULE_ID*) &g_pModuleId,
pApplication,
&m_pHandler);
if (FAILED(hr))
{
goto Finished;
}
retVal = m_pHandler->OnExecuteRequestHandler();
Finished:
if (FAILED(hr))
{
pHttpContext->GetResponse()->SetStatus(500, "Internal Server Error", 0, hr);
retVal = RQ_NOTIFICATION_FINISH_REQUEST;
}
if (pApplication != NULL)
{
pApplication->DereferenceApplication();
}
return retVal;
}
__override
REQUEST_NOTIFICATION_STATUS
ASPNET_CORE_PROXY_MODULE::OnAsyncCompletion(
IHttpContext *,
DWORD,
BOOL,
IHttpEventProvider *,
IHttpCompletionInfo * pCompletionInfo
)
{
return m_pHandler->OnAsyncCompletion(
pCompletionInfo->GetCompletionBytes(),
pCompletionInfo->GetCompletionStatus());
}
<commit_msg>do shutdown check before processing request (#677)<commit_after>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
#include "precomp.hxx"
__override
HRESULT
ASPNET_CORE_PROXY_MODULE_FACTORY::GetHttpModule(
CHttpModule ** ppModule,
IModuleAllocator * pAllocator
)
{
ASPNET_CORE_PROXY_MODULE *pModule = new (pAllocator) ASPNET_CORE_PROXY_MODULE();
if (pModule == NULL)
{
return E_OUTOFMEMORY;
}
*ppModule = pModule;
return S_OK;
}
__override
VOID
ASPNET_CORE_PROXY_MODULE_FACTORY::Terminate(
VOID
)
/*++
Routine description:
Function called by IIS for global (non-request-specific) notifications
Arguments:
None.
Return value:
None
--*/
{
/* FORWARDING_HANDLER::StaticTerminate();
WEBSOCKET_HANDLER::StaticTerminate();*/
ALLOC_CACHE_HANDLER::StaticTerminate();
delete this;
}
ASPNET_CORE_PROXY_MODULE::ASPNET_CORE_PROXY_MODULE(
) : m_pApplicationInfo(NULL), m_pHandler(NULL)
{
}
ASPNET_CORE_PROXY_MODULE::~ASPNET_CORE_PROXY_MODULE()
{
if (m_pApplicationInfo != NULL)
{
m_pApplicationInfo->DereferenceApplicationInfo();
m_pApplicationInfo = NULL;
}
if (m_pHandler != NULL)
{
m_pHandler->DereferenceRequestHandler();
m_pHandler = NULL;
}
}
__override
REQUEST_NOTIFICATION_STATUS
ASPNET_CORE_PROXY_MODULE::OnExecuteRequestHandler(
IHttpContext * pHttpContext,
IHttpEventProvider *
)
{
HRESULT hr = S_OK;
ASPNETCORE_CONFIG *pConfig = NULL;
APPLICATION_MANAGER *pApplicationManager = NULL;
REQUEST_NOTIFICATION_STATUS retVal = RQ_NOTIFICATION_CONTINUE;
APPLICATION* pApplication = NULL;
STACK_STRU(struFileName, 256);
if (g_fInShutdown)
{
hr = HRESULT_FROM_WIN32(ERROR_SERVER_SHUTDOWN_IN_PROGRESS);
goto Finished;
}
hr = ASPNETCORE_CONFIG::GetConfig(g_pHttpServer, g_pModuleId, pHttpContext, g_hEventLog, &pConfig);
if (FAILED(hr))
{
goto Finished;
}
pApplicationManager = APPLICATION_MANAGER::GetInstance();
if (pApplicationManager == NULL)
{
hr = E_OUTOFMEMORY;
goto Finished;
}
hr = pApplicationManager->GetOrCreateApplicationInfo(
g_pHttpServer,
pConfig,
&m_pApplicationInfo);
if (FAILED(hr))
{
goto Finished;
}
// app_offline check to avoid loading aspnetcorerh.dll unnecessarily
if (m_pApplicationInfo->AppOfflineFound())
{
// servicing app_offline
HTTP_DATA_CHUNK DataChunk;
IHttpResponse *pResponse = NULL;
APP_OFFLINE_HTM *pAppOfflineHtm = NULL;
pResponse = pHttpContext->GetResponse();
pAppOfflineHtm = m_pApplicationInfo->QueryAppOfflineHtm();
DBG_ASSERT(pAppOfflineHtm);
DBG_ASSERT(pResponse);
// Ignore failure hresults as nothing we can do
// Set fTrySkipCustomErrors to true as we want client see the offline content
pResponse->SetStatus(503, "Service Unavailable", 0, hr, NULL, TRUE);
pResponse->SetHeader("Content-Type",
"text/html",
(USHORT)strlen("text/html"),
FALSE
);
DataChunk.DataChunkType = HttpDataChunkFromMemory;
DataChunk.FromMemory.pBuffer = (PVOID)pAppOfflineHtm->m_Contents.QueryStr();
DataChunk.FromMemory.BufferLength = pAppOfflineHtm->m_Contents.QueryCB();
pResponse->WriteEntityChunkByReference(&DataChunk);
retVal = RQ_NOTIFICATION_FINISH_REQUEST;
goto Finished;
}
// make sure assmebly is loaded and application is created
hr = m_pApplicationInfo->EnsureApplicationCreated();
if (FAILED(hr))
{
goto Finished;
}
m_pApplicationInfo->ExtractApplication(&pApplication);
// make sure application is in running state
// cannot recreate the application as we cannot reload clr for inprocess
if (pApplication != NULL &&
pApplication->QueryStatus() != APPLICATION_STATUS::RUNNING &&
pApplication->QueryStatus() != APPLICATION_STATUS::STARTING)
{
hr = HRESULT_FROM_WIN32(ERROR_SERVER_DISABLED);
goto Finished;
}
// Create RequestHandler and process the request
hr = m_pApplicationInfo->QueryCreateRequestHandler()(pHttpContext,
(HTTP_MODULE_ID*) &g_pModuleId,
pApplication,
&m_pHandler);
if (FAILED(hr))
{
goto Finished;
}
retVal = m_pHandler->OnExecuteRequestHandler();
Finished:
if (FAILED(hr))
{
retVal = RQ_NOTIFICATION_FINISH_REQUEST;
if (hr == HRESULT_FROM_WIN32(ERROR_SERVER_SHUTDOWN_IN_PROGRESS))
{
pHttpContext->GetResponse()->SetStatus(503, "Service Unavailable", 0, hr);
}
else
{
pHttpContext->GetResponse()->SetStatus(500, "Internal Server Error", 0, hr);
}
}
if (pApplication != NULL)
{
pApplication->DereferenceApplication();
}
return retVal;
}
__override
REQUEST_NOTIFICATION_STATUS
ASPNET_CORE_PROXY_MODULE::OnAsyncCompletion(
IHttpContext *,
DWORD,
BOOL,
IHttpEventProvider *,
IHttpCompletionInfo * pCompletionInfo
)
{
return m_pHandler->OnAsyncCompletion(
pCompletionInfo->GetCompletionBytes(),
pCompletionInfo->GetCompletionStatus());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <memory>
#include <vector>
extern "C" {
#include <unistd.h>
#include <stdarg.h>
#include <sys/time.h>
#include "h2o/memory.h"
#include "h2o/version.h"
}
#include "h2olog.h"
#define POLL_TIMEOUT (1000)
#define PERF_BUFFER_PAGE_COUNT 256
static void usage(void)
{
printf(R"(h2olog (h2o v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -s response_header_name -p PID
Other options:
-h Print this help and exit
-d Print debugging information (-dd shows more)
-r Run without dropping root privilege
-w Path to write the output (default: stdout)
)",
H2O_VERSION);
return;
}
static void make_timestamp(char *buf, size_t buf_len)
{
time_t t = time(NULL);
struct tm tms;
localtime_r(&t, &tms);
const char *iso8601format = "%FT%TZ";
strftime(buf, buf_len, iso8601format, &tms);
}
static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void infof(const char *fmt, ...)
{
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
char timestamp[128];
make_timestamp(timestamp, sizeof(timestamp));
fprintf(stderr, "%s %s\n", timestamp, buf);
}
uint64_t h2o_tracer::time_milliseconds()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
void h2o_tracer::show_event_per_sec(time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = stats_.num_events / d;
if (c > 0) {
if (stats_.num_lost > 0) {
infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost);
stats_.num_lost = 0;
} else {
infof("%20" PRIu64 " events/s", c);
}
stats_.num_events = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
if (nread == 0) {
fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
nread--; // skip trailing nul
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
infof("Attaching pid=%d (%s)", pid, cmdline);
}
static void drop_root_privilege(void)
{
if (getuid() == 0) {
if (getgid() == 0) {
const char *sudo_gid = getenv("SUDO_GID");
if (sudo_gid == NULL) {
fprintf(stderr, "Error: failed to read the SUDO_GID env variable\n");
exit(EXIT_FAILURE);
}
errno = 0;
gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10);
if (errno != 0) {
fprintf(stderr, "Error: overflow while parsing SUDO_GID\n");
exit(EXIT_FAILURE);
}
if (gid != 0 && setgid(gid) != 0) {
fprintf(stderr, "Error: failed to drop the root group\n");
exit(EXIT_FAILURE);
}
}
const char *sudo_uid = getenv("SUDO_UID");
if (sudo_uid == NULL) {
fprintf(stderr, "Error: failed to read the SUDO_UID env variable\n");
exit(EXIT_FAILURE);
}
errno = 0;
uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10);
if (errno != 0) {
fprintf(stderr, "Error: overflow while parsing SUDO_UID\n");
exit(EXIT_FAILURE);
}
if (uid != 0 && setuid(uid) != 0) {
fprintf(stderr, "Error: failed to drop the root user\n");
exit(EXIT_FAILURE);
}
}
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
static std::string make_pid_cflag(const char *macro_name, pid_t pid)
{
char buf[256];
snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid);
return std::string(buf);
}
static void event_cb(void *context, void *data, int len)
{
h2o_tracer *tracer = (h2o_tracer *)context;
tracer->handle_event(data, len);
}
static void lost_cb(void *context, uint64_t lost)
{
h2o_tracer *tracer = (h2o_tracer *)context;
tracer->handle_lost(lost);
}
int main(int argc, char **argv)
{
std::unique_ptr<h2o_tracer> tracer;
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
tracer.reset(create_quic_tracer());
--argc;
++argv;
} else {
tracer.reset(create_http_tracer());
}
int debug = 0;
int drop_root = 1;
FILE *outfp = stdout;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdrp:t:s:w:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'w':
if ((outfp = fopen(optarg, "w")) == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'd':
debug++;
break;
case 'r':
drop_root = 0;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
tracer->init(outfp);
std::vector<std::string> cflags({
make_pid_cflag("H2OLOG_H2O_PID", h2o_pid),
});
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
if (debug >= 2) {
fprintf(stderr, "cflags=");
for (size_t i = 0; i < cflags.size(); i++) {
if (i > 0) {
fprintf(stderr, " ");
}
fprintf(stderr, "%s", cflags[i].c_str());
}
fprintf(stderr, "\n");
fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str());
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "Error: init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit");
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);
if (ret.code() != 0) {
fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
if (drop_root) {
drop_root_privilege();
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
tracer->flush();
if (debug) {
tracer->show_event_per_sec(&t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<commit_msg>h2olog: rename drop_root to preserve_root<commit_after>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <memory>
#include <vector>
extern "C" {
#include <unistd.h>
#include <stdarg.h>
#include <sys/time.h>
#include "h2o/memory.h"
#include "h2o/version.h"
}
#include "h2olog.h"
#define POLL_TIMEOUT (1000)
#define PERF_BUFFER_PAGE_COUNT 256
static void usage(void)
{
printf(R"(h2olog (h2o v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -s response_header_name -p PID
Other options:
-h Print this help and exit
-d Print debugging information (-dd shows more)
-r Run without dropping root privilege
-w Path to write the output (default: stdout)
)",
H2O_VERSION);
return;
}
static void make_timestamp(char *buf, size_t buf_len)
{
time_t t = time(NULL);
struct tm tms;
localtime_r(&t, &tms);
const char *iso8601format = "%FT%TZ";
strftime(buf, buf_len, iso8601format, &tms);
}
static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void infof(const char *fmt, ...)
{
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
char timestamp[128];
make_timestamp(timestamp, sizeof(timestamp));
fprintf(stderr, "%s %s\n", timestamp, buf);
}
uint64_t h2o_tracer::time_milliseconds()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
void h2o_tracer::show_event_per_sec(time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = stats_.num_events / d;
if (c > 0) {
if (stats_.num_lost > 0) {
infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost);
stats_.num_lost = 0;
} else {
infof("%20" PRIu64 " events/s", c);
}
stats_.num_events = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
if (nread == 0) {
fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
nread--; // skip trailing nul
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
infof("Attaching pid=%d (%s)", pid, cmdline);
}
static void drop_root_privilege(void)
{
if (getuid() == 0) {
if (getgid() == 0) {
const char *sudo_gid = getenv("SUDO_GID");
if (sudo_gid == NULL) {
fprintf(stderr, "Error: failed to read the SUDO_GID env variable\n");
exit(EXIT_FAILURE);
}
errno = 0;
gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10);
if (errno != 0) {
fprintf(stderr, "Error: overflow while parsing SUDO_GID\n");
exit(EXIT_FAILURE);
}
if (gid != 0 && setgid(gid) != 0) {
fprintf(stderr, "Error: failed to drop the root group\n");
exit(EXIT_FAILURE);
}
}
const char *sudo_uid = getenv("SUDO_UID");
if (sudo_uid == NULL) {
fprintf(stderr, "Error: failed to read the SUDO_UID env variable\n");
exit(EXIT_FAILURE);
}
errno = 0;
uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10);
if (errno != 0) {
fprintf(stderr, "Error: overflow while parsing SUDO_UID\n");
exit(EXIT_FAILURE);
}
if (uid != 0 && setuid(uid) != 0) {
fprintf(stderr, "Error: failed to drop the root user\n");
exit(EXIT_FAILURE);
}
}
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
static std::string make_pid_cflag(const char *macro_name, pid_t pid)
{
char buf[256];
snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid);
return std::string(buf);
}
static void event_cb(void *context, void *data, int len)
{
h2o_tracer *tracer = (h2o_tracer *)context;
tracer->handle_event(data, len);
}
static void lost_cb(void *context, uint64_t lost)
{
h2o_tracer *tracer = (h2o_tracer *)context;
tracer->handle_lost(lost);
}
int main(int argc, char **argv)
{
std::unique_ptr<h2o_tracer> tracer;
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
tracer.reset(create_quic_tracer());
--argc;
++argv;
} else {
tracer.reset(create_http_tracer());
}
int debug = 0;
int preserve_root = 0;
FILE *outfp = stdout;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdrp:t:s:w:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'w':
if ((outfp = fopen(optarg, "w")) == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'd':
debug++;
break;
case 'r':
preserve_root = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
tracer->init(outfp);
std::vector<std::string> cflags({
make_pid_cflag("H2OLOG_H2O_PID", h2o_pid),
});
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
if (debug >= 2) {
fprintf(stderr, "cflags=");
for (size_t i = 0; i < cflags.size(); i++) {
if (i > 0) {
fprintf(stderr, " ");
}
fprintf(stderr, "%s", cflags[i].c_str());
}
fprintf(stderr, "\n");
fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str());
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "Error: init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit");
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);
if (ret.code() != 0) {
fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
if (!preserve_root) {
drop_root_privilege();
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
tracer->flush();
if (debug) {
tracer->show_event_per_sec(&t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>/*
|---------------------------------------------------------|
| ___ ___ _ _ |
| / _ \ _ __ ___ _ __ |_ _|_ __ | |_ ___ _ __ | |_ |
| | | | | '_ \ / _ \ '_ \ | || '_ \| __/ _ \ '_ \| __| |
| | |_| | |_) | __/ | | || || | | | || __/ | | | |_ |
| \___/| .__/ \___|_| |_|___|_| |_|\__\___|_| |_|\__| |
| |_| |
| |
| - The users first... |
| |
| Authors: |
| - Clement Michaud |
| - Sergei Kireev |
| |
| Version: 1.0.0 |
| |
|---------------------------------------------------------|
The MIT License (MIT)
Copyright (c) 2016 - Clement Michaud, Sergei Kireev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "intent/interpreter/Interpreter.hpp"
#include "intent/intent_service/EntitiesMatcher.hpp"
#include "intent/interpreter/EdgeParser.hpp"
#include "intent/interpreter/SentenceToIntentTranslator.hpp"
#include "intent/interpreter/ReplyTemplateInterpreter.hpp"
#include <boost/algorithm/string.hpp>
#include <cassert>
#include <fstream>
#include <intent/chatbot/ChatbotModel.hpp>
namespace intent {
namespace {
typedef IntentModel::IndexType IndexType;
typedef IntentModel::Intent Intent;
const std::string DEFAULT_REPLY_ID = "#reply";
void indexScenario(const Scenario& scenario,
std::map<int, int>& inquiryToReply) {
int index = 0;
int counter = 0;
std::pair<int, int> pair;
std::for_each(
scenario.begin(), scenario.end(),
[&pair, &index, &counter, &inquiryToReply](const ScriptLine& line) {
if (isLine<SAYING>(line)) {
if (counter % 2 == 0) {
pair.first = index;
}
if (counter % 2 == 1) {
pair.second = index;
inquiryToReply.insert(pair);
}
++counter;
}
++index;
});
}
std::string extractSentence(const ScriptLine& scriptLine) {
std::string content = scriptLine.content;
assert(content.size() > 1);
return content.substr(1, content.size() - 1);
}
struct IntentInserter {
IntentInserter(const DictionaryModel& dictionaryModel,
const Scenario& scenario, IntentModel& intentModel)
: m_dictionaryModel(dictionaryModel),
m_intentModel(intentModel),
m_scenario(scenario) {}
void operator()(const std::pair<int, int> inquiryToReply) {
std::string inquiry = extractSentence(m_scenario[inquiryToReply.first]);
std::pair<IndexType, Intent> intent =
SentenceToIntentTranslator::translate(inquiry, m_dictionaryModel);
m_intentModel.intentsByIntentId.insert(intent);
}
IntentModel& m_intentModel;
const Scenario& m_scenario;
const DictionaryModel& m_dictionaryModel;
};
struct EdgeParserWrapper {
EdgeParserWrapper(const Scenario& scenario,
std::unique_ptr<std::string>& previousStateInScenario,
EdgeParser& edgeParser)
: m_scenario(scenario),
m_previousStateInScenario(previousStateInScenario),
m_edgeParser(edgeParser) {}
EdgeDefinition operator()(const std::pair<int, int> inquiryToReply) {
return m_edgeParser.parse(m_scenario, inquiryToReply,
m_previousStateInScenario);
}
const Scenario& m_scenario;
EdgeParser& m_edgeParser;
std::unique_ptr<std::string>& m_previousStateInScenario;
};
struct FallbackEdgesRetriever {
FallbackEdgesRetriever(const Scenario& scenario,
std::unique_ptr<std::string>& previousStateInScenario,
EdgeParser& edgeParser,
std::vector<EdgeDefinition>& edgesToInsert)
: m_scenario(scenario),
m_previousStateInScenario(previousStateInScenario),
m_edgeParser(edgeParser),
m_edgesToInsert(edgesToInsert) {}
void operator()(const std::pair<int, int> inquiryToReply) {
std::unique_ptr<EdgeDefinition> edge;
edge = m_edgeParser.parseFallback(m_scenario, inquiryToReply,
m_previousStateInScenario);
if (edge.get()) m_edgesToInsert.push_back(*edge);
}
const Scenario& m_scenario;
EdgeParser& m_edgeParser;
std::unique_ptr<std::string>& m_previousStateInScenario;
std::vector<EdgeDefinition>& m_edgesToInsert;
};
struct ActionInserter {
ActionInserter(ChatbotActionModel& chatbotActionModel, int& repliesCounter)
: m_chatbotActionModel(chatbotActionModel),
m_repliesCounter(repliesCounter) {}
void operator()(EdgeDefinition& edge) {
const std::string replyId = DEFAULT_REPLY_ID + "_" + edge.edge.actionId;
ReplyTemplateInterpreter::adapt(edge.replyTemplate);
m_chatbotActionModel.replyContentByReplyIdIndex[replyId] =
edge.replyTemplate;
if (m_chatbotActionModel.replyIdsByActionId[edge.edge.actionId].empty()) {
m_chatbotActionModel.replyIdsByActionId[edge.edge.actionId].push_back(
replyId);
}
++m_repliesCounter;
}
int& m_repliesCounter;
ChatbotActionModel& m_chatbotActionModel;
};
} // anonymous
std::vector<ScriptLine> tokenizeInLines(const std::string& input) {
std::vector<std::string> lines;
std::vector<char> delimiters = {'\n'};
Tokenizer::tokenize(input, delimiters, lines);
std::vector<ScriptLine> scriptLines;
for (unsigned int i = 0; i < lines.size(); ++i) {
scriptLines.push_back({lines[i], i});
}
return scriptLines;
}
void extractScenarios(const std::string& script, Scenarios& scenarios) {
int braceCounter = 0;
Scenario scenario;
std::vector<ScriptLine> lines = tokenizeInLines(script);
std::for_each(lines.begin(), lines.end(),
[&scenarios, &scenario, &braceCounter](ScriptLine& line) {
boost::trim(line.content);
if (isLine<CLOSE_SCENARIO>(line)) {
--braceCounter;
}
if (braceCounter == 1) {
scenario.push_back(line);
}
if (isLine<START_SCENARIO>(line)) {
++braceCounter;
}
if (braceCounter == 0) {
if (!scenario.empty()) scenarios.push_back(scenario);
scenario.clear();
}
});
}
void addEdgeDefinitionToModel(
const EdgeDefinition& edge, IntentStoryModel& intentStoryModel,
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>&
vertexIndex) {
std::string sourceId = edge.source.stateId;
std::string targetId = edge.target.stateId;
// add source and target to vertex index if not there yet
if (vertexIndex.find(sourceId) == vertexIndex.end())
vertexIndex[sourceId] = intentStoryModel.graph.addVertex(edge.source);
if (vertexIndex.find(targetId) == vertexIndex.end())
vertexIndex[targetId] = intentStoryModel.graph.addVertex(edge.target);
// add edge to graph
intentStoryModel.graph.addEdge(vertexIndex[sourceId], vertexIndex[targetId],
edge.edge);
intentStoryModel.vertexByStateId[sourceId] = vertexIndex[sourceId];
intentStoryModel.vertexByStateId[targetId] = vertexIndex[targetId];
}
void completeModelFromScenario(
const Scenario& scenario, const DictionaryModel& dictionaryModel,
IntentStoryModel& intentStoryModel, IntentModel& intentModel,
ChatbotActionModel& chatbotActionModel, int& repliesCounter,
int& vertexCounter,
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>&
vertexIndex,
InterpreterFeedback& interpreterFeedback) {
// link inquiries to replies which naturally represents an edge
std::map<int, int> inquiryToReplies;
indexScenario(scenario, inquiryToReplies);
// Add all intents of the scenario to the IntentModel
IntentInserter intentInserter(dictionaryModel, scenario, intentModel);
std::for_each(inquiryToReplies.begin(), inquiryToReplies.end(),
intentInserter);
// Transform inquiry to reply into an edgeDefinition
std::vector<EdgeDefinition> edgesToInsert;
std::unique_ptr<std::string> previousStateInScenario;
EdgeParser edgeParser(dictionaryModel, vertexCounter, interpreterFeedback);
EdgeParserWrapper edgeParserWrapper(scenario, previousStateInScenario,
edgeParser);
std::transform(inquiryToReplies.begin(), inquiryToReplies.end(),
std::back_inserter(edgesToInsert), edgeParserWrapper);
// Retrieve fallback replies on the edges
previousStateInScenario.reset(NULL);
edgeParser.m_interpreterFeedback = InterpreterFeedback();
FallbackEdgesRetriever fallbackEdgesRetriever(
scenario, previousStateInScenario, edgeParser, edgesToInsert);
std::for_each(inquiryToReplies.begin(), inquiryToReplies.end(),
fallbackEdgesRetriever);
// adapt the replies format to chatbot model format
ActionInserter actionInserter(chatbotActionModel, repliesCounter);
std::for_each(edgesToInsert.begin(), edgesToInsert.end(), actionInserter);
// Add all calculated edges to the graph
std::for_each(edgesToInsert.begin(), edgesToInsert.end(),
[&intentStoryModel, &vertexIndex](const EdgeDefinition& edge) {
addEdgeDefinitionToModel(edge, intentStoryModel, vertexIndex);
});
}
ChatbotModel Interpreter::build(const std::string& script,
DictionaryModel::SharedPtr dictionaryModel,
InterpreterFeedback& interpreterFeedback) {
ChatbotModel chatbotModel;
chatbotModel.intentStoryServiceModel.intentServiceModel.dictionaryModel =
dictionaryModel;
chatbotModel.chatbotActionModel.reset(new ChatbotActionModel());
chatbotModel.intentStoryServiceModel.intentStoryModel.reset(
new IntentStoryModel());
chatbotModel.intentStoryServiceModel.intentServiceModel.intentModel.reset(
new IntentModel());
ChatbotActionModel& chatbotActionModel = *chatbotModel.chatbotActionModel;
IntentStoryModel& intentStoryModel =
*chatbotModel.intentStoryServiceModel.intentStoryModel;
IntentModel& intentModel =
*chatbotModel.intentStoryServiceModel.intentServiceModel.intentModel;
int repliesCounter = 0;
int vertexCounter = 0;
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>
vertexIndex;
Scenarios scenarios;
extractScenarios(script, scenarios);
assert(scenarios.size() > 0);
Scenario firstScenario = scenarios[0];
// Change or document this constraint: root state is first state of first
// scenario, and terminal state last state from first scenario
assert(firstScenario.size() > 0);
intentStoryModel.rootStateId = firstScenario[0].content;
if (!isLine<STATE>(firstScenario[0].content))
interpreterFeedback.push_back(
InterpreterMessage(ROOT_STATE_MSG, firstScenario[0], ERROR));
const DictionaryModel& dict = *dictionaryModel;
intentStoryModel.terminalStateIds.insert(
firstScenario[firstScenario.size() - 1].content);
if (!isLine<STATE>(firstScenario[firstScenario.size() - 1].content))
interpreterFeedback.push_back(InterpreterMessage(
TERMINAL_STATE_MSG, firstScenario[firstScenario.size() - 1], ERROR));
std::for_each(scenarios.begin(), scenarios.end(),
[&intentStoryModel, &intentModel, &chatbotActionModel,
&repliesCounter, &vertexCounter, &dict, &vertexIndex,
&interpreterFeedback](const Scenario& scenario) {
completeModelFromScenario(scenario, dict, intentStoryModel,
intentModel, chatbotActionModel,
repliesCounter, vertexCounter,
vertexIndex, interpreterFeedback);
});
return chatbotModel;
}
}
<commit_msg>fix compilation issue<commit_after>/*
|---------------------------------------------------------|
| ___ ___ _ _ |
| / _ \ _ __ ___ _ __ |_ _|_ __ | |_ ___ _ __ | |_ |
| | | | | '_ \ / _ \ '_ \ | || '_ \| __/ _ \ '_ \| __| |
| | |_| | |_) | __/ | | || || | | | || __/ | | | |_ |
| \___/| .__/ \___|_| |_|___|_| |_|\__\___|_| |_|\__| |
| |_| |
| |
| - The users first... |
| |
| Authors: |
| - Clement Michaud |
| - Sergei Kireev |
| |
| Version: 1.0.0 |
| |
|---------------------------------------------------------|
The MIT License (MIT)
Copyright (c) 2016 - Clement Michaud, Sergei Kireev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "intent/interpreter/Interpreter.hpp"
#include "intent/intent_service/EntitiesMatcher.hpp"
#include "intent/interpreter/EdgeParser.hpp"
#include "intent/interpreter/SentenceToIntentTranslator.hpp"
#include "intent/interpreter/ReplyTemplateInterpreter.hpp"
#include <boost/algorithm/string.hpp>
#include <cassert>
#include <fstream>
#include <intent/chatbot/ChatbotModel.hpp>
namespace intent {
namespace {
typedef IntentModel::IndexType IndexType;
typedef IntentModel::Intent Intent;
const std::string DEFAULT_REPLY_ID = "#reply";
void indexScenario(const Scenario& scenario,
std::map<int, int>& inquiryToReply) {
int index = 0;
int counter = 0;
std::pair<int, int> pair;
std::for_each(
scenario.begin(), scenario.end(),
[&pair, &index, &counter, &inquiryToReply](const ScriptLine& line) {
if (isLine<SAYING>(line)) {
if (counter % 2 == 0) {
pair.first = index;
}
if (counter % 2 == 1) {
pair.second = index;
inquiryToReply.insert(pair);
}
++counter;
}
++index;
});
}
std::string extractSentence(const ScriptLine& scriptLine) {
std::string content = scriptLine.content;
assert(content.size() > 1);
return content.substr(1, content.size() - 1);
}
struct IntentInserter {
IntentInserter(const DictionaryModel& dictionaryModel,
const Scenario& scenario, IntentModel& intentModel)
: m_dictionaryModel(dictionaryModel),
m_intentModel(intentModel),
m_scenario(scenario) {}
void operator()(const std::pair<int, int> inquiryToReply) {
std::string inquiry = extractSentence(m_scenario[inquiryToReply.first]);
std::pair<IndexType, Intent> intent =
SentenceToIntentTranslator::translate(inquiry, m_dictionaryModel);
m_intentModel.intentsByIntentId.insert(intent);
}
IntentModel& m_intentModel;
const Scenario& m_scenario;
const DictionaryModel& m_dictionaryModel;
};
struct EdgeParserWrapper {
EdgeParserWrapper(const Scenario& scenario,
std::unique_ptr<std::string>& previousStateInScenario,
EdgeParser& edgeParser)
: m_scenario(scenario),
m_previousStateInScenario(previousStateInScenario),
m_edgeParser(edgeParser) {}
EdgeDefinition operator()(const std::pair<int, int> inquiryToReply) {
return m_edgeParser.parse(m_scenario, inquiryToReply,
m_previousStateInScenario);
}
const Scenario& m_scenario;
EdgeParser& m_edgeParser;
std::unique_ptr<std::string>& m_previousStateInScenario;
};
struct FallbackEdgesRetriever {
FallbackEdgesRetriever(const Scenario& scenario,
std::unique_ptr<std::string>& previousStateInScenario,
EdgeParser& edgeParser,
std::vector<EdgeDefinition>& edgesToInsert)
: m_scenario(scenario),
m_previousStateInScenario(previousStateInScenario),
m_edgeParser(edgeParser),
m_edgesToInsert(edgesToInsert) {}
void operator()(const std::pair<int, int> inquiryToReply) {
std::unique_ptr<EdgeDefinition> edge;
edge = m_edgeParser.parseFallback(m_scenario, inquiryToReply,
m_previousStateInScenario);
if (edge.get()) m_edgesToInsert.push_back(*edge);
}
const Scenario& m_scenario;
EdgeParser& m_edgeParser;
std::unique_ptr<std::string>& m_previousStateInScenario;
std::vector<EdgeDefinition>& m_edgesToInsert;
};
struct ActionInserter {
ActionInserter(ChatbotActionModel& chatbotActionModel, int& repliesCounter)
: m_chatbotActionModel(chatbotActionModel),
m_repliesCounter(repliesCounter) {}
void operator()(EdgeDefinition& edge) {
const std::string replyId = DEFAULT_REPLY_ID + "_" + edge.edge.actionId;
ReplyTemplateInterpreter::adapt(edge.replyTemplate);
m_chatbotActionModel.replyContentByReplyIdIndex[replyId] =
edge.replyTemplate;
if (m_chatbotActionModel.replyIdsByActionId[edge.edge.actionId].empty()) {
m_chatbotActionModel.replyIdsByActionId[edge.edge.actionId].push_back(
replyId);
}
++m_repliesCounter;
}
int& m_repliesCounter;
ChatbotActionModel& m_chatbotActionModel;
};
} // anonymous
std::vector<ScriptLine> tokenizeInLines(const std::string& input) {
std::vector<std::string> lines;
std::vector<char> delimiters = {'\n'};
Tokenizer::tokenize(input, delimiters, lines);
std::vector<ScriptLine> scriptLines;
for (unsigned int i = 0; i < lines.size(); ++i) {
scriptLines.push_back({lines[i], i});
}
return scriptLines;
}
void extractScenarios(const std::string& script, Scenarios& scenarios) {
int braceCounter = 0;
Scenario scenario;
std::vector<ScriptLine> lines = tokenizeInLines(script);
std::for_each(lines.begin(), lines.end(),
[&scenarios, &scenario, &braceCounter](ScriptLine& line) {
boost::trim(line.content);
if (isLine<CLOSE_SCENARIO>(line)) {
--braceCounter;
}
if (braceCounter == 1) {
scenario.push_back(line);
}
if (isLine<START_SCENARIO>(line)) {
++braceCounter;
}
if (braceCounter == 0) {
if (!scenario.empty()) scenarios.push_back(scenario);
scenario.clear();
}
});
}
void addEdgeDefinitionToModel(
const EdgeDefinition& edge, IntentStoryModel& intentStoryModel,
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>&
vertexIndex) {
std::string sourceId = edge.source.stateId;
std::string targetId = edge.target.stateId;
// add source and target to vertex index if not there yet
if (vertexIndex.find(sourceId) == vertexIndex.end())
vertexIndex[sourceId] = intentStoryModel.graph.addVertex(edge.source);
if (vertexIndex.find(targetId) == vertexIndex.end())
vertexIndex[targetId] = intentStoryModel.graph.addVertex(edge.target);
// add edge to graph
intentStoryModel.graph.addEdge(vertexIndex[sourceId], vertexIndex[targetId],
edge.edge);
intentStoryModel.vertexByStateId[sourceId] = vertexIndex[sourceId];
intentStoryModel.vertexByStateId[targetId] = vertexIndex[targetId];
}
void completeModelFromScenario(
const Scenario& scenario, const DictionaryModel& dictionaryModel,
IntentStoryModel& intentStoryModel, IntentModel& intentModel,
ChatbotActionModel& chatbotActionModel, int& repliesCounter,
int& vertexCounter,
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>&
vertexIndex,
InterpreterFeedback& interpreterFeedback) {
// link inquiries to replies which naturally represents an edge
std::map<int, int> inquiryToReplies;
indexScenario(scenario, inquiryToReplies);
// Add all intents of the scenario to the IntentModel
IntentInserter intentInserter(dictionaryModel, scenario, intentModel);
std::for_each(inquiryToReplies.begin(), inquiryToReplies.end(),
intentInserter);
// Transform inquiry to reply into an edgeDefinition
std::vector<EdgeDefinition> edgesToInsert;
std::unique_ptr<std::string> previousStateInScenario;
EdgeParser edgeParser(dictionaryModel, vertexCounter, interpreterFeedback);
EdgeParserWrapper edgeParserWrapper(scenario, previousStateInScenario,
edgeParser);
std::transform(inquiryToReplies.begin(), inquiryToReplies.end(),
std::back_inserter(edgesToInsert), edgeParserWrapper);
// Retrieve fallback replies on the edges
previousStateInScenario.reset(NULL);
InterpreterFeedback dummyFeedback;
EdgeParser fallbackEdgeParser(dictionaryModel, vertexCounter, dummyFeedback);
FallbackEdgesRetriever fallbackEdgesRetriever(
scenario, previousStateInScenario, fallbackEdgeParser, edgesToInsert);
std::for_each(inquiryToReplies.begin(), inquiryToReplies.end(),
fallbackEdgesRetriever);
// adapt the replies format to chatbot model format
ActionInserter actionInserter(chatbotActionModel, repliesCounter);
std::for_each(edgesToInsert.begin(), edgesToInsert.end(), actionInserter);
// Add all calculated edges to the graph
std::for_each(edgesToInsert.begin(), edgesToInsert.end(),
[&intentStoryModel, &vertexIndex](const EdgeDefinition& edge) {
addEdgeDefinitionToModel(edge, intentStoryModel, vertexIndex);
});
}
ChatbotModel Interpreter::build(const std::string& script,
DictionaryModel::SharedPtr dictionaryModel,
InterpreterFeedback& interpreterFeedback) {
ChatbotModel chatbotModel;
chatbotModel.intentStoryServiceModel.intentServiceModel.dictionaryModel =
dictionaryModel;
chatbotModel.chatbotActionModel.reset(new ChatbotActionModel());
chatbotModel.intentStoryServiceModel.intentStoryModel.reset(
new IntentStoryModel());
chatbotModel.intentStoryServiceModel.intentServiceModel.intentModel.reset(
new IntentModel());
ChatbotActionModel& chatbotActionModel = *chatbotModel.chatbotActionModel;
IntentStoryModel& intentStoryModel =
*chatbotModel.intentStoryServiceModel.intentStoryModel;
IntentModel& intentModel =
*chatbotModel.intentStoryServiceModel.intentServiceModel.intentModel;
int repliesCounter = 0;
int vertexCounter = 0;
std::unordered_map<std::string, IntentStoryModel::StoryGraph::Vertex>
vertexIndex;
Scenarios scenarios;
extractScenarios(script, scenarios);
assert(scenarios.size() > 0);
Scenario firstScenario = scenarios[0];
// Change or document this constraint: root state is first state of first
// scenario, and terminal state last state from first scenario
assert(firstScenario.size() > 0);
intentStoryModel.rootStateId = firstScenario[0].content;
if (!isLine<STATE>(firstScenario[0].content))
interpreterFeedback.push_back(
InterpreterMessage(ROOT_STATE_MSG, firstScenario[0], ERROR));
const DictionaryModel& dict = *dictionaryModel;
intentStoryModel.terminalStateIds.insert(
firstScenario[firstScenario.size() - 1].content);
if (!isLine<STATE>(firstScenario[firstScenario.size() - 1].content))
interpreterFeedback.push_back(InterpreterMessage(
TERMINAL_STATE_MSG, firstScenario[firstScenario.size() - 1], ERROR));
std::for_each(scenarios.begin(), scenarios.end(),
[&intentStoryModel, &intentModel, &chatbotActionModel,
&repliesCounter, &vertexCounter, &dict, &vertexIndex,
&interpreterFeedback](const Scenario& scenario) {
completeModelFromScenario(scenario, dict, intentStoryModel,
intentModel, chatbotActionModel,
repliesCounter, vertexCounter,
vertexIndex, interpreterFeedback);
});
return chatbotModel;
}
}
<|endoftext|>
|
<commit_before>/* ************************************************************************* */
/* This file is part of Shard. */
/* */
/* Shard is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU Affero General Public License as */
/* published by the Free Software Foundation. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Affero General Public License for more details. */
/* */
/* You should have received a copy of the GNU Affero General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* ************************************************************************* */
// Declaration
#include "shard/interpreter/Interpreter.hpp"
// C++
#include <cstdio>
// Shard
#include "shard/Assert.hpp"
#include "shard/ast/Decl.hpp"
#include "shard/ast/Stmt.hpp"
#include "shard/ast/Expr.hpp"
#include "shard/ast/Module.hpp"
#include "shard/interpreter/Exception.hpp"
#include "shard/interpreter/Context.hpp"
/* ************************************************************************* */
//#define PRINT_CALL printf("%s\n", __PRETTY_FUNCTION__);
#define PRINT_CALL
/* ************************************************************************* */
namespace shard {
inline namespace v1 {
namespace interpreter {
/* ************************************************************************* */
namespace {
/* ************************************************************************* */
void interpretExprStmt(ViewPtr<const ast::ExprStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
interpret(stmt->getExpr(), ctx);
}
/* ************************************************************************* */
void interpretDeclStmt(ViewPtr<const ast::DeclStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
// Get declaration
const auto& decl = stmt->getDecl();
SHARD_ASSERT(decl);
// Only variable is supported
if (!ast::VariableDecl::is(decl))
throw Exception("Only variable can be declared in statement");
auto varDecl = ast::VariableDecl::cast(decl);
// Create variable
auto var = ctx.addSymbol(varDecl->getName(), SymbolKind::Variable);
if (varDecl->getInitExpr())
var->setValue(interpret(varDecl->getInitExpr(), ctx));
}
/* ************************************************************************* */
void interpretCompoundStmt(ViewPtr<const ast::CompoundStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
ctx.push();
for (const auto& s : *stmt)
interpret(makeView(s), ctx);
ctx.pop();
}
/* ************************************************************************* */
void interpretIfStmt(ViewPtr<const ast::IfStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretWhileStmt(ViewPtr<const ast::WhileStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretDoWhileStmt(ViewPtr<const ast::DoWhileStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretForStmt(ViewPtr<const ast::ForStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretSwitchStmt(ViewPtr<const ast::SwitchStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretCaseStmt(ViewPtr<const ast::CaseStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretDefaultStmt(ViewPtr<const ast::DefaultStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretContinueStmt(ViewPtr<const ast::ContinueStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretBreakStmt(ViewPtr<const ast::BreakStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretReturnStmt(ViewPtr<const ast::ReturnStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
// Evaluate return expr
auto ret = interpret(stmt->getResExpr(), ctx);
auto retSym = ctx.findSymbol("return");
SHARD_ASSERT(retSym);
retSym->setValue(moveValue(ret));
}
/* ************************************************************************* */
Value interpretNullLiteralExpr(ViewPtr<const ast::NullLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretBoolLiteralExpr(ViewPtr<const ast::BoolLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretIntLiteralExpr(ViewPtr<const ast::IntLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretFloatLiteralExpr(ViewPtr<const ast::FloatLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretCharLiteralExpr(ViewPtr<const ast::CharLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretStringLiteralExpr(ViewPtr<const ast::StringLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretBinaryExpr(ViewPtr<const ast::BinaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate operands
auto lhs = interpret(expr->getLhs(), ctx);
auto rhs = interpret(expr->getRhs(), ctx);
switch (expr->getOpKind())
{
// Equality operators
case ast::BinaryExpr::OpKind::EQ: return Value(lhs == rhs);
case ast::BinaryExpr::OpKind::NE: return Value(lhs != rhs);
// Relational operators
case ast::BinaryExpr::OpKind::LT: return Value(lhs < rhs);
case ast::BinaryExpr::OpKind::LE: return Value(lhs <= rhs);
case ast::BinaryExpr::OpKind::GT: return Value(lhs > rhs);
case ast::BinaryExpr::OpKind::GE: return Value(lhs >= rhs);
// Additive operators
case ast::BinaryExpr::OpKind::Add: return lhs + rhs;
case ast::BinaryExpr::OpKind::Sub: return lhs - rhs;
// Multiplicative operators
case ast::BinaryExpr::OpKind::Mul: return lhs * rhs;
case ast::BinaryExpr::OpKind::Div: return lhs / rhs;
case ast::BinaryExpr::OpKind::Rem: break;
// Assignment operators
case ast::BinaryExpr::OpKind::Assign: break;
case ast::BinaryExpr::OpKind::MulAssign: break;
case ast::BinaryExpr::OpKind::DivAssign: break;
case ast::BinaryExpr::OpKind::RemAssign: break;
case ast::BinaryExpr::OpKind::AddAssign: break;
case ast::BinaryExpr::OpKind::SubAssign: break;
}
return {};
}
/* ************************************************************************* */
Value interpretUnaryExpr(ViewPtr<const ast::UnaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate
auto res = interpret(expr->getExpr(), ctx);
switch (expr->getOpKind())
{
case ast::UnaryExpr::OpKind::PostInc: break;
case ast::UnaryExpr::OpKind::PostDec: break;
case ast::UnaryExpr::OpKind::PreInc: break;
case ast::UnaryExpr::OpKind::PreDec: break;
case ast::UnaryExpr::OpKind::Plus: break;
case ast::UnaryExpr::OpKind::Minus: break;
case ast::UnaryExpr::OpKind::Not: break;
}
return {};
}
/* ************************************************************************* */
Value interpretTernaryExpr(ViewPtr<const ast::TernaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretParenExpr(ViewPtr<const ast::ParenExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return interpret(expr->getExpr(), ctx);
}
/* ************************************************************************* */
Value interpretIdentifierExpr(ViewPtr<const ast::IdentifierExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Try to find required symbol
auto sym = ctx.findSymbol(expr->getName());
if (sym == nullptr)
throw Exception("Symbol '" + expr->getName() + "' not defined in within current scope");
return sym->getValue();
}
/* ************************************************************************* */
Value interpretFunctionCallExpr(ViewPtr<const ast::FunctionCallExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate expr before arguments
auto res = interpret(expr->getExpr(), ctx);
if (res.getKind() != ValueKind::Function)
throw Exception("Not a function");
// Get function info
auto fn = res.asFunction();
// Builtin function
if (fn.getName() == "print")
{
for (auto& arg : expr->getArguments())
{
// Evaluate argument
auto val = interpret(makeView(arg), ctx);
switch (val.getKind())
{
case ValueKind::Null: printf("null"); break;
case ValueKind::Bool: printf("%s", val.asBool() ? "true" : "false"); break;
case ValueKind::Int: printf("%d", val.asInt()); break;
case ValueKind::Float: printf("%f", val.asFloat()); break;
case ValueKind::Char: printf("%c", static_cast<char>(val.asChar())); break;
case ValueKind::String: printf("%s", val.asString().c_str()); break;
case ValueKind::Function: printf("<callable>"); break;
}
}
printf("\n");
return {};
}
if (fn.getDecl() == nullptr)
throw Exception("Missing function declaration");
// FIXME: Function context
// Arguments context
ctx.push();
// Return value
auto retSym = ctx.addSymbol("return", SymbolKind::Variable);
// Parameters & Arguments
const auto& params = fn.getDecl()->getParameters();
const auto& args = expr->getArguments();
if (args.size() != params.size())
throw Exception("Function call argument count mismatch");
// Register arguments
for (int i = 0; i < params.size(); ++i)
{
auto param = ctx.addSymbol(params[i]->getName(), SymbolKind::Variable);
SHARD_ASSERT(param);
param->setValue(interpret(makeView(args[i]), ctx));
}
// Intepret function body
interpretCompoundStmt(fn.getDecl()->getBodyStmt(), ctx);
// Get return value
auto ret = retSym->getValue();
ctx.pop();
return ret;
}
/* ************************************************************************* */
Value interpretMemberAccessExpr(ViewPtr<const ast::MemberAccessExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretSubscriptExpr(ViewPtr<const ast::SubscriptExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Module> unit, Context& ctx)
{
SHARD_ASSERT(unit);
PRINT_CALL;
// Register declarations
for (const auto& decl : unit->getDeclarations())
{
SHARD_ASSERT(decl);
// Is variable
if (ast::VariableDecl::is(decl))
{
const auto varDecl = ast::VariableDecl::cast(decl);
SHARD_ASSERT(varDecl);
// Register symbol as variable
auto var = ctx.addSymbol(varDecl->getName(), SymbolKind::Variable);
SHARD_ASSERT(var);
// Define variable initial value
if (varDecl->getInitExpr())
var->setValue(interpret(varDecl->getInitExpr(), ctx));
}
else if (ast::FunctionDecl::is(decl))
{
const auto fnDecl = ast::FunctionDecl::cast(decl);
SHARD_ASSERT(fnDecl);
// Register symbol as function
auto fn = ctx.addSymbol(fnDecl->getName(), SymbolKind::Function);
SHARD_ASSERT(fn);
// Store function definition
fn->setValue(Function(fnDecl->getName(), fnDecl));
}
}
// Find main function
auto main = ctx.findSymbol("main");
if (main == nullptr || main->getValue().getKind() != ValueKind::Function)
throw Exception("No 'main' function in the compilation unit");
// Parameters
ctx.push();
// Main function info
auto mainFn = main->getValue().asFunction();
SHARD_ASSERT(mainFn.getDecl());
// Call function
interpret(mainFn.getDecl()->getBodyStmt(), ctx);
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Module> unit)
{
SHARD_ASSERT(unit);
PRINT_CALL;
Context ctx;
interpret(unit, ctx);
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Stmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
#define CASE(name) \
case ast::StmtKind::name: interpret ## name ## Stmt(ast::name ## Stmt::cast(stmt), ctx); break;
switch (stmt->getKind())
{
CASE(Expr)
CASE(Decl)
CASE(Compound)
CASE(If)
CASE(While)
CASE(DoWhile)
CASE(For)
CASE(Switch)
CASE(Case)
CASE(Default)
CASE(Continue)
CASE(Break)
CASE(Return)
}
#undef CASE
}
/* ************************************************************************* */
Value interpret(ViewPtr<const ast::Expr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
#define CASE(name) \
case ast::ExprKind::name: return interpret ## name ## Expr(ast::name ## Expr::cast(expr), ctx);
switch (expr->getKind())
{
CASE(NullLiteral)
CASE(BoolLiteral)
CASE(IntLiteral)
CASE(FloatLiteral)
CASE(CharLiteral)
CASE(StringLiteral)
CASE(Binary)
CASE(Unary)
CASE(Ternary)
CASE(Paren)
CASE(Identifier)
CASE(FunctionCall)
CASE(MemberAccess)
CASE(Subscript)
}
#undef CASE
return {};
}
/* ************************************************************************* */
}
}
}
/* ************************************************************************* */
<commit_msg>interpreter - unit and is()<commit_after>/* ************************************************************************* */
/* This file is part of Shard. */
/* */
/* Shard is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU Affero General Public License as */
/* published by the Free Software Foundation. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Affero General Public License for more details. */
/* */
/* You should have received a copy of the GNU Affero General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* ************************************************************************* */
// Declaration
#include "shard/interpreter/Interpreter.hpp"
// C++
#include <cstdio>
// Shard
#include "shard/Assert.hpp"
#include "shard/ast/Decl.hpp"
#include "shard/ast/Stmt.hpp"
#include "shard/ast/Expr.hpp"
#include "shard/ast/Unit.hpp"
#include "shard/interpreter/Exception.hpp"
#include "shard/interpreter/Context.hpp"
/* ************************************************************************* */
//#define PRINT_CALL printf("%s\n", __PRETTY_FUNCTION__);
#define PRINT_CALL
/* ************************************************************************* */
namespace shard {
inline namespace v1 {
namespace interpreter {
/* ************************************************************************* */
namespace {
/* ************************************************************************* */
void interpretExprStmt(ViewPtr<const ast::ExprStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
interpret(stmt->getExpr(), ctx);
}
/* ************************************************************************* */
void interpretDeclStmt(ViewPtr<const ast::DeclStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
// Get declaration
const auto& decl = stmt->getDecl();
SHARD_ASSERT(decl);
// Only variable is supported
if (!decl->is<ast::VariableDecl>())
throw Exception("Only variable can be declared in statement");
auto varDecl = ast::VariableDecl::cast(decl);
// Create variable
auto var = ctx.addSymbol(varDecl->getName(), SymbolKind::Variable);
if (varDecl->getInitExpr())
var->setValue(interpret(varDecl->getInitExpr(), ctx));
}
/* ************************************************************************* */
void interpretCompoundStmt(ViewPtr<const ast::CompoundStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
ctx.push();
for (const auto& s : *stmt)
interpret(makeView(s), ctx);
ctx.pop();
}
/* ************************************************************************* */
void interpretIfStmt(ViewPtr<const ast::IfStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretWhileStmt(ViewPtr<const ast::WhileStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretDoWhileStmt(ViewPtr<const ast::DoWhileStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretForStmt(ViewPtr<const ast::ForStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretSwitchStmt(ViewPtr<const ast::SwitchStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretCaseStmt(ViewPtr<const ast::CaseStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretDefaultStmt(ViewPtr<const ast::DefaultStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretContinueStmt(ViewPtr<const ast::ContinueStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretBreakStmt(ViewPtr<const ast::BreakStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
}
/* ************************************************************************* */
void interpretReturnStmt(ViewPtr<const ast::ReturnStmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
// Evaluate return expr
auto ret = interpret(stmt->getResExpr(), ctx);
auto retSym = ctx.findSymbol("return");
SHARD_ASSERT(retSym);
retSym->setValue(moveValue(ret));
}
/* ************************************************************************* */
Value interpretNullLiteralExpr(ViewPtr<const ast::NullLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretBoolLiteralExpr(ViewPtr<const ast::BoolLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretIntLiteralExpr(ViewPtr<const ast::IntLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretFloatLiteralExpr(ViewPtr<const ast::FloatLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretCharLiteralExpr(ViewPtr<const ast::CharLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretStringLiteralExpr(ViewPtr<const ast::StringLiteralExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return Value(expr->getValue());
}
/* ************************************************************************* */
Value interpretBinaryExpr(ViewPtr<const ast::BinaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate operands
auto lhs = interpret(expr->getLhs(), ctx);
auto rhs = interpret(expr->getRhs(), ctx);
switch (expr->getOpKind())
{
// Equality operators
case ast::BinaryExpr::OpKind::EQ: return Value(lhs == rhs);
case ast::BinaryExpr::OpKind::NE: return Value(lhs != rhs);
// Relational operators
case ast::BinaryExpr::OpKind::LT: return Value(lhs < rhs);
case ast::BinaryExpr::OpKind::LE: return Value(lhs <= rhs);
case ast::BinaryExpr::OpKind::GT: return Value(lhs > rhs);
case ast::BinaryExpr::OpKind::GE: return Value(lhs >= rhs);
// Additive operators
case ast::BinaryExpr::OpKind::Add: return lhs + rhs;
case ast::BinaryExpr::OpKind::Sub: return lhs - rhs;
// Multiplicative operators
case ast::BinaryExpr::OpKind::Mul: return lhs * rhs;
case ast::BinaryExpr::OpKind::Div: return lhs / rhs;
case ast::BinaryExpr::OpKind::Rem: break;
// Assignment operators
case ast::BinaryExpr::OpKind::Assign: break;
case ast::BinaryExpr::OpKind::MulAssign: break;
case ast::BinaryExpr::OpKind::DivAssign: break;
case ast::BinaryExpr::OpKind::RemAssign: break;
case ast::BinaryExpr::OpKind::AddAssign: break;
case ast::BinaryExpr::OpKind::SubAssign: break;
}
return {};
}
/* ************************************************************************* */
Value interpretUnaryExpr(ViewPtr<const ast::UnaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate
auto res = interpret(expr->getExpr(), ctx);
switch (expr->getOpKind())
{
case ast::UnaryExpr::OpKind::PostInc: break;
case ast::UnaryExpr::OpKind::PostDec: break;
case ast::UnaryExpr::OpKind::PreInc: break;
case ast::UnaryExpr::OpKind::PreDec: break;
case ast::UnaryExpr::OpKind::Plus: break;
case ast::UnaryExpr::OpKind::Minus: break;
case ast::UnaryExpr::OpKind::Not: break;
}
return {};
}
/* ************************************************************************* */
Value interpretTernaryExpr(ViewPtr<const ast::TernaryExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretParenExpr(ViewPtr<const ast::ParenExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return interpret(expr->getExpr(), ctx);
}
/* ************************************************************************* */
Value interpretIdentifierExpr(ViewPtr<const ast::IdentifierExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Try to find required symbol
auto sym = ctx.findSymbol(expr->getName());
if (sym == nullptr)
throw Exception("Symbol '" + expr->getName() + "' not defined in within current scope");
return sym->getValue();
}
/* ************************************************************************* */
Value interpretFunctionCallExpr(ViewPtr<const ast::FunctionCallExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
// Evaluate expr before arguments
auto res = interpret(expr->getExpr(), ctx);
if (res.getKind() != ValueKind::Function)
throw Exception("Not a function");
// Get function info
auto fn = res.asFunction();
// Builtin function
if (fn.getName() == "print")
{
for (auto& arg : expr->getArguments())
{
// Evaluate argument
auto val = interpret(makeView(arg), ctx);
switch (val.getKind())
{
case ValueKind::Null: printf("null"); break;
case ValueKind::Bool: printf("%s", val.asBool() ? "true" : "false"); break;
case ValueKind::Int: printf("%d", val.asInt()); break;
case ValueKind::Float: printf("%f", val.asFloat()); break;
case ValueKind::Char: printf("%c", static_cast<char>(val.asChar())); break;
case ValueKind::String: printf("%s", val.asString().c_str()); break;
case ValueKind::Function: printf("<callable>"); break;
}
}
printf("\n");
return {};
}
if (fn.getDecl() == nullptr)
throw Exception("Missing function declaration");
// FIXME: Function context
// Arguments context
ctx.push();
// Return value
auto retSym = ctx.addSymbol("return", SymbolKind::Variable);
// Parameters & Arguments
const auto& params = fn.getDecl()->getParameters();
const auto& args = expr->getArguments();
if (args.size() != params.size())
throw Exception("Function call argument count mismatch");
// Register arguments
for (int i = 0; i < params.size(); ++i)
{
auto param = ctx.addSymbol(params[i]->getName(), SymbolKind::Variable);
SHARD_ASSERT(param);
param->setValue(interpret(makeView(args[i]), ctx));
}
// Intepret function body
interpretCompoundStmt(fn.getDecl()->getBodyStmt(), ctx);
// Get return value
auto ret = retSym->getValue();
ctx.pop();
return ret;
}
/* ************************************************************************* */
Value interpretMemberAccessExpr(ViewPtr<const ast::MemberAccessExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
Value interpretSubscriptExpr(ViewPtr<const ast::SubscriptExpr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
return {};
}
/* ************************************************************************* */
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Unit> unit, Context& ctx)
{
SHARD_ASSERT(unit);
PRINT_CALL;
// Register declarations
for (const auto& decl : unit->getDeclarations())
{
SHARD_ASSERT(decl);
// Is variable
if (decl->is<ast::VariableDecl>())
{
const auto varDecl = ast::VariableDecl::cast(decl);
SHARD_ASSERT(varDecl);
// Register symbol as variable
auto var = ctx.addSymbol(varDecl->getName(), SymbolKind::Variable);
SHARD_ASSERT(var);
// Define variable initial value
if (varDecl->getInitExpr())
var->setValue(interpret(varDecl->getInitExpr(), ctx));
}
else if (decl->is<ast::FunctionDecl>())
{
const auto fnDecl = ast::FunctionDecl::cast(decl);
SHARD_ASSERT(fnDecl);
// Register symbol as function
auto fn = ctx.addSymbol(fnDecl->getName(), SymbolKind::Function);
SHARD_ASSERT(fn);
// Store function definition
fn->setValue(Function(fnDecl->getName(), fnDecl));
}
}
// Find main function
auto main = ctx.findSymbol("main");
if (main == nullptr || main->getValue().getKind() != ValueKind::Function)
throw Exception("No 'main' function in the compilation unit");
// Parameters
ctx.push();
// Main function info
auto mainFn = main->getValue().asFunction();
SHARD_ASSERT(mainFn.getDecl());
// Call function
interpret(mainFn.getDecl()->getBodyStmt(), ctx);
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Unit> unit)
{
SHARD_ASSERT(unit);
PRINT_CALL;
Context ctx;
interpret(unit, ctx);
}
/* ************************************************************************* */
void interpret(ViewPtr<const ast::Stmt> stmt, Context& ctx)
{
SHARD_ASSERT(stmt);
PRINT_CALL;
#define CASE(name) \
case ast::StmtKind::name: interpret ## name ## Stmt(ast::name ## Stmt::cast(stmt), ctx); break;
switch (stmt->getKind())
{
CASE(Expr)
CASE(Decl)
CASE(Compound)
CASE(If)
CASE(While)
CASE(DoWhile)
CASE(For)
CASE(Switch)
CASE(Case)
CASE(Default)
CASE(Continue)
CASE(Break)
CASE(Return)
}
#undef CASE
}
/* ************************************************************************* */
Value interpret(ViewPtr<const ast::Expr> expr, Context& ctx)
{
SHARD_ASSERT(expr);
PRINT_CALL;
#define CASE(name) \
case ast::ExprKind::name: return interpret ## name ## Expr(ast::name ## Expr::cast(expr), ctx);
switch (expr->getKind())
{
CASE(NullLiteral)
CASE(BoolLiteral)
CASE(IntLiteral)
CASE(FloatLiteral)
CASE(CharLiteral)
CASE(StringLiteral)
CASE(Binary)
CASE(Unary)
CASE(Ternary)
CASE(Paren)
CASE(Identifier)
CASE(FunctionCall)
CASE(MemberAccess)
CASE(Subscript)
}
#undef CASE
return {};
}
/* ************************************************************************* */
}
}
}
/* ************************************************************************* */
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "player.h"
#include "playercontrols.h"
#include "playlistmodel.h"
#include <qabstractmediaservice.h>
#include <qmediaplaylist.h>
#include <qmediametadata.h>
#include <qmediawidgetendpoint.h>
#include <QtGui>
#define USE_VIDEOWIDGET
Player::Player(QWidget *parent)
: QWidget(parent)
, videoWidget(0)
, coverLabel(0)
, slider(0)
, colorDialog(0)
{
player = new QMediaPlayer;
metaData = new QMediaMetadata(player);
playlist = new QMediaPlaylist(player);
connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
connect(playlist, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));
connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));
connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
#ifdef USE_VIDEOWIDGET
videoWidget = new QVideoWidget(player);
connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),
this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));
#else
QWidget *videoWidget = player->service()->createEndpoint<QMediaWidgetEndpoint *>();
if (videoWidget) {
qDebug() << "service supports video widgets, nice";
player->service()->setVideoOutput(videoWidget);
} else {
coverLabel = new QLabel;
}
#endif
playlistModel = new PlaylistModel(this);
playlistModel->setPlaylist(playlist);
playlistView = new QTableView;
playlistView->setModel(playlistModel);
playlistView->setCurrentIndex(playlistModel->index(playlist->currentPosition(), 0));
connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));
slider = new QSlider(Qt::Horizontal);
slider->setRange(0, player->duration() / 1000);
connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
QPushButton *openButton = new QPushButton(tr("Open"));
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
PlayerControls *controls = new PlayerControls;
controls->setState(player->state());
controls->setVolume(player->volume());
controls->setMuted(controls->isMuted());
connect(controls, SIGNAL(play()), player, SLOT(play()));
connect(controls, SIGNAL(pause()), player, SLOT(pause()));
connect(controls, SIGNAL(stop()), player, SLOT(stop()));
connect(controls, SIGNAL(next()), playlist, SLOT(advance()));
connect(controls, SIGNAL(previous()), playlist, SLOT(back()));
connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
connect(controls, SIGNAL(changeRate(float)), player, SLOT(setPlaybackRate(float)));
connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
controls, SLOT(setState(QMediaPlayer::State)));
connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));
QPushButton *fullscreenButton = new QPushButton(tr("Fullscreen"));
fullscreenButton->setCheckable(true);
connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));
connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));
fullscreenButton->setEnabled(videoWidget != 0);
QPushButton *colorButton = new QPushButton(tr("Color Options..."));
if (videoWidget)
connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
else
colorButton->setEnabled(false);
QBoxLayout *controlLayout = new QHBoxLayout;
controlLayout->setMargin(0);
controlLayout->addWidget(openButton);
controlLayout->addStretch(1);
controlLayout->addWidget(controls);
controlLayout->addStretch(1);
controlLayout->addWidget(fullscreenButton);
controlLayout->addWidget(colorButton);
QBoxLayout *layout = new QVBoxLayout;
if (videoWidget) {
QSplitter *splitter = new QSplitter(Qt::Vertical);
splitter->addWidget(videoWidget);
splitter->addWidget(playlistView);
/*
connect(player, SIGNAL(videoAvailabilityChanged(bool)), videoWidget, SLOT(setVisible(bool)));
videoWidget->setMinimumSize(64,64);
videoWidget->setVisible(false);*/
layout->addWidget(splitter);
} else {
layout->addWidget(coverLabel, 0, Qt::AlignCenter);
layout->addWidget(playlistView);
}
layout->addWidget(slider);
layout->addLayout(controlLayout);
setLayout(layout);
metadataChanged();
}
Player::~Player()
{
delete player;
}
void Player::open()
{
QStringList fileNames = QFileDialog::getOpenFileNames();
foreach (QString const &fileName, fileNames) {
#ifndef Q_OS_WIN
playlist->appendItem(
QMediaResource(QUrl(QLatin1String("file://") + fileName)));
#else
playlist->appendItem(
QMediaResource(QUrl(QLatin1String("file:///") + fileName)));
#endif
}
}
void Player::durationChanged(qint64 duration)
{
slider->setMaximum(duration / 1000);
}
void Player::positionChanged(qint64 progress)
{
slider->setValue(progress / 1000);
}
void Player::metadataChanged()
{
qDebug() << "update metadata" << metaData->metadata(QLatin1String("title")).toString();
if (metaData->metadataAvailable()) {
setTrackInfo(QString("%1 - %2")
.arg(metaData->metadata(QLatin1String("Artist")).toString())
.arg(metaData->metadata(QLatin1String("Title")).toString()));
if (coverLabel) {
QMediaResource cover;
foreach (const QMediaResource &resource, metaData->resources()) {
if (resource.role() == QMediaResource::CoverArtRole
&& (cover.isNull()
|| resource.resolution().height() > cover.resolution().height())) {
cover = resource;
}
}
coverLabel->setPixmap(!cover.isNull()
? QPixmap(cover.uri().toString())
: QPixmap());
}
}
}
void Player::jump(const QModelIndex &index)
{
if (index.isValid()) {
playlist->setCurrentPosition(index.row());
}
}
void Player::playlistPositionChanged(int currentItem)
{
playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}
void Player::seek(int seconds)
{
player->setPosition(seconds * 1000);
}
void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
switch (status) {
case QMediaPlayer::UnknownMediaStatus:
case QMediaPlayer::NoMedia:
case QMediaPlayer::LoadedMedia:
case QMediaPlayer::BufferingMedia:
case QMediaPlayer::BufferedMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(QString());
break;
case QMediaPlayer::LoadingMedia:
#ifndef QT_NO_CURSOR
setCursor(QCursor(Qt::BusyCursor));
#endif
setStatusInfo(tr("Loading..."));
break;
case QMediaPlayer::StalledMedia:
#ifndef QT_NO_CURSOR
setCursor(QCursor(Qt::BusyCursor));
#endif
break;
case QMediaPlayer::EndOfMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(QString());
QApplication::alert(this);
break;
case QMediaPlayer::InvalidMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(player->errorString());
break;
}
}
void Player::bufferingProgress(int progress)
{
setStatusInfo(tr("Buffering %4%%").arg(progress));
}
void Player::setTrackInfo(const QString &info)
{
trackInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setStatusInfo(const QString &info)
{
statusInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setFullscreen(bool fullscreen)
{
videoWidget->setDisplayMode(
fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);
}
void Player::displayModeChanged(QVideoWidget::DisplayMode mode)
{
emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);
}
void Player::showColorDialog()
{
if (!colorDialog) {
QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
brightnessSlider->setRange(-100, 100);
brightnessSlider->setValue(videoWidget->brightness());
connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));
QSlider *contrastSlider = new QSlider(Qt::Horizontal);
contrastSlider->setRange(-100, 100);
contrastSlider->setValue(videoWidget->contrast());
connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));
QSlider *hueSlider = new QSlider(Qt::Horizontal);
hueSlider->setRange(-100, 100);
hueSlider->setValue(videoWidget->hue());
connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));
QSlider *saturationSlider = new QSlider(Qt::Horizontal);
saturationSlider->setRange(-100, 100);
saturationSlider->setValue(videoWidget->saturation());
connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));
QFormLayout *layout = new QFormLayout;
layout->addRow(tr("Brightness"), brightnessSlider);
layout->addRow(tr("Contrast"), contrastSlider);
layout->addRow(tr("Hue"), hueSlider);
layout->addRow(tr("Saturation"), saturationSlider);
colorDialog = new QDialog(this);
colorDialog->setWindowTitle(tr("Color Options"));
colorDialog->setLayout(layout);
}
colorDialog->show();
}
<commit_msg>Dropped deprecated use of video end points<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "player.h"
#include "playercontrols.h"
#include "playlistmodel.h"
#include <qabstractmediaservice.h>
#include <qmediaplaylist.h>
#include <qmediametadata.h>
#include <qmediawidgetendpoint.h>
#include <QtGui>
Player::Player(QWidget *parent)
: QWidget(parent)
, videoWidget(0)
, coverLabel(0)
, slider(0)
, colorDialog(0)
{
player = new QMediaPlayer;
metaData = new QMediaMetadata(player);
playlist = new QMediaPlaylist(player);
connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
connect(playlist, SIGNAL(playlistPositionChanged(int)), SLOT(playlistPositionChanged(int)));
connect(metaData, SIGNAL(metadataChanged()), SLOT(metadataChanged()));
connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
videoWidget = new QVideoWidget(player);
connect(videoWidget, SIGNAL(displayModeChanged(QVideoWidget::DisplayMode)),
this, SLOT(displayModeChanged(QVideoWidget::DisplayMode)));
playlistModel = new PlaylistModel(this);
playlistModel->setPlaylist(playlist);
playlistView = new QTableView;
playlistView->setModel(playlistModel);
playlistView->setCurrentIndex(playlistModel->index(playlist->currentPosition(), 0));
connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));
slider = new QSlider(Qt::Horizontal);
slider->setRange(0, player->duration() / 1000);
connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
QPushButton *openButton = new QPushButton(tr("Open"));
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
PlayerControls *controls = new PlayerControls;
controls->setState(player->state());
controls->setVolume(player->volume());
controls->setMuted(controls->isMuted());
connect(controls, SIGNAL(play()), player, SLOT(play()));
connect(controls, SIGNAL(pause()), player, SLOT(pause()));
connect(controls, SIGNAL(stop()), player, SLOT(stop()));
connect(controls, SIGNAL(next()), playlist, SLOT(advance()));
connect(controls, SIGNAL(previous()), playlist, SLOT(back()));
connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
connect(controls, SIGNAL(changeRate(float)), player, SLOT(setPlaybackRate(float)));
connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
controls, SLOT(setState(QMediaPlayer::State)));
connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
connect(player, SIGNAL(mutingChanged(bool)), controls, SLOT(setMuted(bool)));
QPushButton *fullscreenButton = new QPushButton(tr("Fullscreen"));
fullscreenButton->setCheckable(true);
connect(fullscreenButton, SIGNAL(clicked(bool)), this, SLOT(setFullscreen(bool)));
connect(this, SIGNAL(fullscreenChanged(bool)), fullscreenButton, SLOT(setChecked(bool)));
fullscreenButton->setEnabled(videoWidget != 0);
QPushButton *colorButton = new QPushButton(tr("Color Options..."));
if (videoWidget)
connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
else
colorButton->setEnabled(false);
QBoxLayout *controlLayout = new QHBoxLayout;
controlLayout->setMargin(0);
controlLayout->addWidget(openButton);
controlLayout->addStretch(1);
controlLayout->addWidget(controls);
controlLayout->addStretch(1);
controlLayout->addWidget(fullscreenButton);
controlLayout->addWidget(colorButton);
QBoxLayout *layout = new QVBoxLayout;
if (videoWidget) {
QSplitter *splitter = new QSplitter(Qt::Vertical);
splitter->addWidget(videoWidget);
splitter->addWidget(playlistView);
layout->addWidget(splitter);
} else {
layout->addWidget(coverLabel, 0, Qt::AlignCenter);
layout->addWidget(playlistView);
}
layout->addWidget(slider);
layout->addLayout(controlLayout);
setLayout(layout);
metadataChanged();
}
Player::~Player()
{
delete player;
}
void Player::open()
{
QStringList fileNames = QFileDialog::getOpenFileNames();
foreach (QString const &fileName, fileNames) {
#ifndef Q_OS_WIN
playlist->appendItem(
QMediaResource(QUrl(QLatin1String("file://") + fileName)));
#else
playlist->appendItem(
QMediaResource(QUrl(QLatin1String("file:///") + fileName)));
#endif
}
}
void Player::durationChanged(qint64 duration)
{
slider->setMaximum(duration / 1000);
}
void Player::positionChanged(qint64 progress)
{
slider->setValue(progress / 1000);
}
void Player::metadataChanged()
{
qDebug() << "update metadata" << metaData->metadata(QLatin1String("title")).toString();
if (metaData->metadataAvailable()) {
setTrackInfo(QString("%1 - %2")
.arg(metaData->metadata(QLatin1String("Artist")).toString())
.arg(metaData->metadata(QLatin1String("Title")).toString()));
if (coverLabel) {
QMediaResource cover;
foreach (const QMediaResource &resource, metaData->resources()) {
if (resource.role() == QMediaResource::CoverArtRole
&& (cover.isNull()
|| resource.resolution().height() > cover.resolution().height())) {
cover = resource;
}
}
coverLabel->setPixmap(!cover.isNull()
? QPixmap(cover.uri().toString())
: QPixmap());
}
}
}
void Player::jump(const QModelIndex &index)
{
if (index.isValid()) {
playlist->setCurrentPosition(index.row());
}
}
void Player::playlistPositionChanged(int currentItem)
{
playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}
void Player::seek(int seconds)
{
player->setPosition(seconds * 1000);
}
void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
switch (status) {
case QMediaPlayer::UnknownMediaStatus:
case QMediaPlayer::NoMedia:
case QMediaPlayer::LoadedMedia:
case QMediaPlayer::BufferingMedia:
case QMediaPlayer::BufferedMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(QString());
break;
case QMediaPlayer::LoadingMedia:
#ifndef QT_NO_CURSOR
setCursor(QCursor(Qt::BusyCursor));
#endif
setStatusInfo(tr("Loading..."));
break;
case QMediaPlayer::StalledMedia:
#ifndef QT_NO_CURSOR
setCursor(QCursor(Qt::BusyCursor));
#endif
break;
case QMediaPlayer::EndOfMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(QString());
QApplication::alert(this);
break;
case QMediaPlayer::InvalidMedia:
#ifndef QT_NO_CURSOR
unsetCursor();
#endif
setStatusInfo(player->errorString());
break;
}
}
void Player::bufferingProgress(int progress)
{
setStatusInfo(tr("Buffering %4%%").arg(progress));
}
void Player::setTrackInfo(const QString &info)
{
trackInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setStatusInfo(const QString &info)
{
statusInfo = info;
if (!statusInfo.isEmpty())
setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
else
setWindowTitle(trackInfo);
}
void Player::setFullscreen(bool fullscreen)
{
videoWidget->setDisplayMode(
fullscreen ? QVideoWidget::FullscreenDisplay : QVideoWidget::WindowedDisplay);
}
void Player::displayModeChanged(QVideoWidget::DisplayMode mode)
{
emit fullscreenChanged(mode == QVideoWidget::FullscreenDisplay);
}
void Player::showColorDialog()
{
if (!colorDialog) {
QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
brightnessSlider->setRange(-100, 100);
brightnessSlider->setValue(videoWidget->brightness());
connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));
QSlider *contrastSlider = new QSlider(Qt::Horizontal);
contrastSlider->setRange(-100, 100);
contrastSlider->setValue(videoWidget->contrast());
connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));
QSlider *hueSlider = new QSlider(Qt::Horizontal);
hueSlider->setRange(-100, 100);
hueSlider->setValue(videoWidget->hue());
connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));
QSlider *saturationSlider = new QSlider(Qt::Horizontal);
saturationSlider->setRange(-100, 100);
saturationSlider->setValue(videoWidget->saturation());
connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));
QFormLayout *layout = new QFormLayout;
layout->addRow(tr("Brightness"), brightnessSlider);
layout->addRow(tr("Contrast"), contrastSlider);
layout->addRow(tr("Hue"), hueSlider);
layout->addRow(tr("Saturation"), saturationSlider);
colorDialog = new QDialog(this);
colorDialog->setWindowTitle(tr("Color Options"));
colorDialog->setLayout(layout);
}
colorDialog->show();
}
<|endoftext|>
|
<commit_before><commit_msg>Fix session id for resume E++ account<commit_after><|endoftext|>
|
<commit_before><commit_msg>monclient: fix off-by-one buffer overrun<commit_after><|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
int main(int /*argc*/, char* /*argv*/ []) {
// Load the dataset
auto dataset = dll::make_mnist_dataset(0, dll::batch_size<100>{}, dll::scale_pre<255>{});
// Build the network
using network_t = dll::dyn_network_desc<
dll::network_layers<
dll::conv_layer<1, 28, 28, 8, 5, 5>,
dll::mp_2d_layer<8, 24, 24, 2, 2>,
dll::conv_layer<8, 12, 12, 8, 5, 5>,
dll::mp_2d_layer<8, 8, 8, 2, 2>,
dll::dense_layer<8 * 4 * 4, 150>,
dll::dense_layer<150, 10, dll::softmax>
>
, dll::updater<dll::updater_type::NADAM> // Momentum
, dll::batch_size<100> // The mini-batch size
, dll::shuffle // Shuffle the dataset before each epoch
>::network_t;
auto net = std::make_unique<network_t>();
// Display the network and dataset
net->display();
dataset.display();
// Train the network
net->fine_tune(dataset.train(), 25);
// Test the network on test set
net->evaluate(dataset.test());
return 0;
}
<commit_msg>Adapt one example<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
int main(int /*argc*/, char* /*argv*/ []) {
// Load the dataset
auto dataset = dll::make_mnist_dataset(dll::batch_size<100>{}, dll::scale_pre<255>{});
// Build the network
using network_t = dll::dyn_network_desc<
dll::network_layers<
dll::conv_layer<1, 28, 28, 8, 5, 5>,
dll::mp_2d_layer<8, 24, 24, 2, 2>,
dll::conv_layer<8, 12, 12, 8, 5, 5>,
dll::mp_2d_layer<8, 8, 8, 2, 2>,
dll::dense_layer<8 * 4 * 4, 150>,
dll::dense_layer<150, 10, dll::softmax>
>
, dll::updater<dll::updater_type::NADAM> // Momentum
, dll::batch_size<100> // The mini-batch size
, dll::shuffle // Shuffle the dataset before each epoch
>::network_t;
auto net = std::make_unique<network_t>();
// Display the network and dataset
net->display();
dataset.display();
// Train the network
net->fine_tune(dataset.train(), 25);
// Test the network on test set
net->evaluate(dataset.test());
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>fixed bug that prevented buffer optimization<commit_after><|endoftext|>
|
<commit_before><commit_msg>fixed unlimited settings check<commit_after><|endoftext|>
|
<commit_before>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "turtlesim/Pose.h"
#include <sstream>
using namespace std;
ros::Publisher velocity_publisher;
ros::Subscriber pose_subscriber;
turtlesim::Pose turtlesim_pose;
const double PI = 3.14159265359;
void move(double speed, double distance, bool isForward);
void rotate(double angular_speed, double angle, bool cloclwise);
void poseCallback(const turtlesim::Pose::ConstPtr & pose_message);
//void circle(double radius, double turn_angle, bool clockwise);
int main(int argc, char **argv)
{
// Initiate new ROS node named "robosys_turtle"
ros::init(argc, argv, "robosys_turtle");
ros::NodeHandle n;
double speed, angular_speed;
double distance, angle;
bool isForward, clockwise;
velocity_publisher = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 1000);
pose_subscriber = n.subscribe("/turtle1/pose", 10, poseCallback);
ros::Rate loop_rate(0.5);
move(2,3,1);
for(int i=0; i<4; i++){
rotate(2,4/PI,0);
move(2,2,1);
}
move(2,2,1);
ros::spin();
return 0;
}
void move(double speed, double distance, bool isForward)
{
geometry_msgs::Twist vel_msg;
//set a random linear velocity in the x-axis
if (isForward)
vel_msg.linear.x =abs(speed);
else
vel_msg.linear.x =-abs(speed);
vel_msg.linear.y =0;
vel_msg.linear.z =0;
//set a random angular velocity in the y-axis
vel_msg.angular.x = 0;
vel_msg.angular.y = 0;
vel_msg.angular.z =0;
double t0 = ros::Time::now().toSec();
double current_distance = 0.0;
ros::Rate loop_rate(100);
do{
velocity_publisher.publish(vel_msg);
double t1 = ros::Time::now().toSec();
current_distance = speed * (t1-t0);
ros::spinOnce();
loop_rate.sleep();
}while(current_distance<distance);
vel_msg.linear.x =0;
velocity_publisher.publish(vel_msg);
}
void rotate (double angular_speed, double relative_angle, bool clockwise)
{
geometry_msgs::Twist vel_msg;
//set a random linear velocity in the x-axis
vel_msg.linear.x =0;
vel_msg.linear.y =0;
vel_msg.linear.z =0;
//set a random angular velocity in the y-axis
vel_msg.angular.x = 0;
vel_msg.angular.y = 0;
if (clockwise)
vel_msg.angular.z =-abs(angular_speed);
else
vel_msg.angular.z =abs(angular_speed);
double t0 = ros::Time::now().toSec();
double current_angle = 0.0;
ros::Rate loop_rate(1000);
do{
velocity_publisher.publish(vel_msg);
double t1 = ros::Time::now().toSec();
current_angle = angular_speed * (t1-t0);
ros::spinOnce();
loop_rate.sleep();
//cout<<(t1-t0)<<", "<<current_angle <<", "<<relative_angle<<endl;
}while(current_angle<relative_angle);
vel_msg.angular.z =0;
velocity_publisher.publish(vel_msg);
}
void poseCallback(const turtlesim::Pose::ConstPtr & pose_message)
{
turtlesim_pose.x=pose_message->x;
turtlesim_pose.y=pose_message->y; turtlesim_pose.theta=pose_message->theta;
}
<commit_msg>Write the pentagon<commit_after>#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "turtlesim/Pose.h"
#include <sstream>
using namespace std;
ros::Publisher velocity_publisher;
ros::Subscriber pose_subscriber;
turtlesim::Pose turtlesim_pose;
const double PI = 3.14159265359;
void move(double speed, double distance, bool isForward);
void rotate(double angular_speed, double angle, bool cloclwise);
void poseCallback(const turtlesim::Pose::ConstPtr & pose_message);
//void circle(double radius, double turn_angle, bool clockwise);
int main(int argc, char **argv)
{
// Initiate new ROS node named "robosys_turtle"
ros::init(argc, argv, "robosys_turtle");
ros::NodeHandle n;
double speed, angular_speed;
double distance, angle;
bool isForward, clockwise;
velocity_publisher = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 1000);
pose_subscriber = n.subscribe("/turtle1/pose", 10, poseCallback);
ros::Rate loop_rate(0.5);
move(2,3,1);
for(int i=0; i<4; i++){
rotate(2,4/PI,0);
move(2,2,1);
}
rotate(2,4/PI,1);
move(2,3,1);
for(int i=0; i<4; i++){
rotate(2,4/PI,0);
move(2,2,1);
}
rotate(2,3/PI,1);
move(2,3,1);
for(int i=0; i<4; i++){
rotate(2,4/PI,0);
move(2,2,1);
}
ros::spin();
return 0;
}
void move(double speed, double distance, bool isForward)
{
geometry_msgs::Twist vel_msg;
//set a random linear velocity in the x-axis
if (isForward)
vel_msg.linear.x =abs(speed);
else
vel_msg.linear.x =-abs(speed);
vel_msg.linear.y =0;
vel_msg.linear.z =0;
//set a random angular velocity in the y-axis
vel_msg.angular.x = 0;
vel_msg.angular.y = 0;
vel_msg.angular.z =0;
double t0 = ros::Time::now().toSec();
double current_distance = 0.0;
ros::Rate loop_rate(100);
do{
velocity_publisher.publish(vel_msg);
double t1 = ros::Time::now().toSec();
current_distance = speed * (t1-t0);
ros::spinOnce();
loop_rate.sleep();
}while(current_distance<distance);
vel_msg.linear.x =0;
velocity_publisher.publish(vel_msg);
}
void rotate (double angular_speed, double relative_angle, bool clockwise)
{
geometry_msgs::Twist vel_msg;
//set a random linear velocity in the x-axis
vel_msg.linear.x =0;
vel_msg.linear.y =0;
vel_msg.linear.z =0;
//set a random angular velocity in the y-axis
vel_msg.angular.x = 0;
vel_msg.angular.y = 0;
if (clockwise)
vel_msg.angular.z =-abs(angular_speed);
else
vel_msg.angular.z =abs(angular_speed);
double t0 = ros::Time::now().toSec();
double current_angle = 0.0;
ros::Rate loop_rate(1000);
do{
velocity_publisher.publish(vel_msg);
double t1 = ros::Time::now().toSec();
current_angle = angular_speed * (t1-t0);
ros::spinOnce();
loop_rate.sleep();
//cout<<(t1-t0)<<", "<<current_angle <<", "<<relative_angle<<endl;
}while(current_angle<relative_angle);
vel_msg.angular.z =0;
velocity_publisher.publish(vel_msg);
}
void poseCallback(const turtlesim::Pose::ConstPtr & pose_message)
{
turtlesim_pose.x=pose_message->x;
turtlesim_pose.y=pose_message->y; turtlesim_pose.theta=pose_message->theta;
}
<|endoftext|>
|
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "graph.h"
#include "state.h"
#include "util.h"
bool DepsLog::OpenForWrite(const string& path, string* err) {
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
/* XXX
if (ftell(log_file_) == 0) {
if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
*err = strerror(errno);
return false;
}
}
*/
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
// Assign ids to all nodes that are missing one.
if (node->id() < 0)
RecordId(node);
for (vector<Node*>::const_iterator i = nodes.begin();
i != nodes.end(); ++i) {
if ((*i)->id() < 0)
RecordId(*i);
}
uint16_t size = 4 * (1 + 1 + nodes.size());
size |= 0x8000; // Deps record: set high bit.
fwrite(&size, 2, 1, file_);
int id = node->id();
fwrite(&id, 4, 1, file_);
int timestamp = node->mtime();
fwrite(×tamp, 4, 1, file_);
for (vector<Node*>::const_iterator i = nodes.begin();
i != nodes.end(); ++i) {
id = node->id();
fwrite(&id, 4, 1, file_);
}
return true;
}
void DepsLog::Close() {
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
char buf[32 << 10];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
*err = strerror(errno);
return false;
}
int id = 0;
for (;;) {
uint16_t size;
if (fread(&size, 2, 1, f) < 1)
break;
bool is_deps = (size >> 15) != 0;
size = size & 0x7FFF;
if (fread(buf, size, 1, f) < 1)
break;
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps;
deps->mtime = mtime;
deps->node_count = deps_count;
deps->nodes = new Node*[deps_count];
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
if (deps_[out_id])
delete deps_[out_id];
deps_[out_id] = deps;
} else {
StringPiece path(buf, size);
Node* node = state->GetNode(path);
assert(node->id() < 0);
node->set_id(id);
++id;
}
}
if (ferror(f)) {
*err = strerror(ferror(f));
return false;
}
fclose(f);
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
if (node->id() < 0)
return NULL;
return deps_[node->id()];
}
bool DepsLog::RecordId(Node* node) {
uint16_t size = node->path().size();
fwrite(&size, 2, 1, file_);
fwrite(node->path().data(), node->path().size(), 1, file_);
node->set_id(nodes_.size());
nodes_.push_back(node);
return true;
}
<commit_msg>no error if deps log doesn't exist<commit_after>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "graph.h"
#include "state.h"
#include "util.h"
bool DepsLog::OpenForWrite(const string& path, string* err) {
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
/* XXX
if (ftell(log_file_) == 0) {
if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
*err = strerror(errno);
return false;
}
}
*/
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
// Assign ids to all nodes that are missing one.
if (node->id() < 0)
RecordId(node);
for (vector<Node*>::const_iterator i = nodes.begin();
i != nodes.end(); ++i) {
if ((*i)->id() < 0)
RecordId(*i);
}
uint16_t size = 4 * (1 + 1 + nodes.size());
size |= 0x8000; // Deps record: set high bit.
fwrite(&size, 2, 1, file_);
int id = node->id();
fwrite(&id, 4, 1, file_);
int timestamp = node->mtime();
fwrite(×tamp, 4, 1, file_);
for (vector<Node*>::const_iterator i = nodes.begin();
i != nodes.end(); ++i) {
id = node->id();
fwrite(&id, 4, 1, file_);
}
return true;
}
void DepsLog::Close() {
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
char buf[32 << 10];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
int id = 0;
for (;;) {
uint16_t size;
if (fread(&size, 2, 1, f) < 1)
break;
bool is_deps = (size >> 15) != 0;
size = size & 0x7FFF;
if (fread(buf, size, 1, f) < 1)
break;
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps;
deps->mtime = mtime;
deps->node_count = deps_count;
deps->nodes = new Node*[deps_count];
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
if (deps_[out_id])
delete deps_[out_id];
deps_[out_id] = deps;
} else {
StringPiece path(buf, size);
Node* node = state->GetNode(path);
assert(node->id() < 0);
node->set_id(id);
++id;
}
}
if (ferror(f)) {
*err = strerror(ferror(f));
return false;
}
fclose(f);
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
if (node->id() < 0)
return NULL;
return deps_[node->id()];
}
bool DepsLog::RecordId(Node* node) {
uint16_t size = node->path().size();
fwrite(&size, 2, 1, file_);
fwrite(node->path().data(), node->path().size(), 1, file_);
node->set_id(nodes_.size());
nodes_.push_back(node);
return true;
}
<|endoftext|>
|
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/session.hpp>
using namespace boost::python;
using namespace libtorrent;
void bind_session_settings()
{
class_<session_settings>("session_settings")
.def_readwrite("user_agent", &session_settings::user_agent)
.def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
.def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
.def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
.def_readwrite("piece_timeout", &session_settings::piece_timeout)
.def_readwrite("request_queue_time", &session_settings::request_queue_time)
.def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
.def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
.def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
.def_readwrite("peer_timeout", &session_settings::peer_timeout)
.def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
.def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
.def_readwrite("file_pool_size", &session_settings::file_pool_size)
.def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
.def_readwrite("max_failcount", &session_settings::max_failcount)
.def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
.def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
.def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
.def_readwrite("connection_speed", &session_settings::connection_speed)
.def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
.def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
.def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
.def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
.def_readwrite("active_downloads", &session_settings::active_downloads)
.def_readwrite("active_seeds", &session_settings::active_seeds)
.def_readwrite("active_limit", &session_settings::active_limit)
.def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
.def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
.def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
.def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
.def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
.def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
.def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
.def_readwrite("peer_tos", &session_settings::peer_tos)
.def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
.def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
#ifndef TORRENT_DISABLE_DHT
.def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
;
enum_<proxy_settings::proxy_type>("proxy_type")
.value("none", proxy_settings::none)
.value("socks4", proxy_settings::socks4)
.value("socks5", proxy_settings::socks5)
.value("socks5_pw", proxy_settings::socks5_pw)
.value("http", proxy_settings::http)
.value("http_pw", proxy_settings::http_pw)
;
class_<proxy_settings>("proxy_settings")
.def_readwrite("hostname", &proxy_settings::hostname)
.def_readwrite("port", &proxy_settings::port)
.def_readwrite("password", &proxy_settings::password)
.def_readwrite("username", &proxy_settings::username)
.def_readwrite("type", &proxy_settings::type)
;
#ifndef TORRENT_DISABLE_ENCRYPTION
enum_<pe_settings::enc_policy>("enc_policy")
.value("forced", pe_settings::forced)
.value("enabled", pe_settings::enabled)
.value("disabled", pe_settings::disabled)
;
enum_<pe_settings::enc_level>("enc_level")
.value("rc4", pe_settings::rc4)
.value("plaintext", pe_settings::plaintext)
.value("both", pe_settings::both)
;
class_<pe_settings>("pe_settings")
.def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
.def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
.def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
.def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
;
#endif
}
<commit_msg>Add 'cache_size' and 'cache_expiry' session settings to the python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <libtorrent/session.hpp>
using namespace boost::python;
using namespace libtorrent;
void bind_session_settings()
{
class_<session_settings>("session_settings")
.def_readwrite("user_agent", &session_settings::user_agent)
.def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
.def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
.def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
.def_readwrite("piece_timeout", &session_settings::piece_timeout)
.def_readwrite("request_queue_time", &session_settings::request_queue_time)
.def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
.def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
.def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
.def_readwrite("peer_timeout", &session_settings::peer_timeout)
.def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
.def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
.def_readwrite("file_pool_size", &session_settings::file_pool_size)
.def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
.def_readwrite("max_failcount", &session_settings::max_failcount)
.def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
.def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
.def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
.def_readwrite("connection_speed", &session_settings::connection_speed)
.def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
.def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
.def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
.def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
.def_readwrite("active_downloads", &session_settings::active_downloads)
.def_readwrite("active_seeds", &session_settings::active_seeds)
.def_readwrite("active_limit", &session_settings::active_limit)
.def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
.def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
.def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
.def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
.def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
.def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
.def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
.def_readwrite("peer_tos", &session_settings::peer_tos)
.def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
.def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
.def_readwrite("cache_size", &session_settings::cache_size)
.def_readwrite("cache_expiry", &session_settings::cache_expiry)
#ifndef TORRENT_DISABLE_DHT
.def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
;
enum_<proxy_settings::proxy_type>("proxy_type")
.value("none", proxy_settings::none)
.value("socks4", proxy_settings::socks4)
.value("socks5", proxy_settings::socks5)
.value("socks5_pw", proxy_settings::socks5_pw)
.value("http", proxy_settings::http)
.value("http_pw", proxy_settings::http_pw)
;
class_<proxy_settings>("proxy_settings")
.def_readwrite("hostname", &proxy_settings::hostname)
.def_readwrite("port", &proxy_settings::port)
.def_readwrite("password", &proxy_settings::password)
.def_readwrite("username", &proxy_settings::username)
.def_readwrite("type", &proxy_settings::type)
;
#ifndef TORRENT_DISABLE_ENCRYPTION
enum_<pe_settings::enc_policy>("enc_policy")
.value("forced", pe_settings::forced)
.value("enabled", pe_settings::enabled)
.value("disabled", pe_settings::disabled)
;
enum_<pe_settings::enc_level>("enc_level")
.value("rc4", pe_settings::rc4)
.value("plaintext", pe_settings::plaintext)
.value("both", pe_settings::both)
;
class_<pe_settings>("pe_settings")
.def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
.def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
.def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
.def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
;
#endif
}
<|endoftext|>
|
<commit_before>// Virtual memory allocator for CPU/GPU
#if defined(CUDA_FOUND)
#include <cuda_runtime.h>
#endif
#include "util.h"
#include <taichi/unified_allocator.h>
#include <taichi/system/virtual_memory.h>
#include <string>
TLANG_NAMESPACE_BEGIN
UnifiedAllocator *allocator_instance = nullptr;
UnifiedAllocator *&allocator() {
return allocator_instance;
}
taichi::Tlang::UnifiedAllocator::UnifiedAllocator(std::size_t size, bool gpu)
: size(size), gpu(gpu) {
size += 4096;
if (!gpu) {
_data.resize(size + 4096);
data = _data.data();
} else {
#if defined(CUDA_FOUND)
cudaMallocManaged(&_cuda_data, size + 4096);
if (_cuda_data == nullptr) {
TC_ERROR("GPU memory allocation failed.");
}
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetPreferredLocation,
0);
// http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
/*
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetReadMostly,
cudaCpuDeviceId);
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetAccessedBy,
0);
*/
data = _cuda_data;
#else
cpu_vm = std::make_unique<VirtualMemoryAllocator>(size);
data = cpu_vm->ptr;
TC_ASSERT(data != nullptr);
#endif
}
auto p = reinterpret_cast<uint64>(data);
data = (void *)(p + (4096 - p % 4096));
// allocate head/tail ptrs on unified memory
head = (void **)data;
tail = (void **)((char *)data + sizeof(void *));
data = (char *)data + 4096;
*head = data;
*tail = (void *)(((char *)head) + size);
}
taichi::Tlang::UnifiedAllocator::~UnifiedAllocator() {
if (!initialized()) {
return;
}
if (gpu) {
#if defined(CUDA_FOUND)
cudaFree(_cuda_data);
#else
TC_ERROR("No CUDA support");
#endif
}
}
void taichi::Tlang::UnifiedAllocator::create() {
TC_ASSERT(allocator() == nullptr);
void *dst;
#if defined(CUDA_FOUND)
cudaMallocManaged(&dst, sizeof(UnifiedAllocator));
#else
dst = std::malloc(sizeof(UnifiedAllocator));
#endif
allocator() = new (dst) UnifiedAllocator(1LL << 40, true);
}
void taichi::Tlang::UnifiedAllocator::free() {
(*allocator()).~UnifiedAllocator();
#if defined(CUDA_FOUND)
cudaFree(allocator());
#else
std::free(allocator());
#endif
allocator() = nullptr;
}
void taichi::Tlang::UnifiedAllocator::memset(unsigned char val) {
std::memset(data, val, size);
}
UnifiedAllocator::UnifiedAllocator() {
data = nullptr;
gpu_error_code = 0;
}
TLANG_NAMESPACE_END
extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment) {
return taichi::Tlang::allocate(size, alignment);
}
<commit_msg>fixed non-gpu build<commit_after>// Virtual memory allocator for CPU/GPU
#if defined(CUDA_FOUND)
#include <cuda_runtime.h>
#endif
#include "util.h"
#include <taichi/unified_allocator.h>
#include <taichi/system/virtual_memory.h>
#include <string>
TLANG_NAMESPACE_BEGIN
UnifiedAllocator *allocator_instance = nullptr;
UnifiedAllocator *&allocator() {
return allocator_instance;
}
taichi::Tlang::UnifiedAllocator::UnifiedAllocator(std::size_t size, bool gpu)
: size(size), gpu(gpu) {
size += 4096;
if (!gpu) {
_data.resize(size + 4096);
data = _data.data();
} else {
#if defined(CUDA_FOUND)
cudaMallocManaged(&_cuda_data, size + 4096);
if (_cuda_data == nullptr) {
TC_ERROR("GPU memory allocation failed.");
}
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetPreferredLocation,
0);
// http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
/*
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetReadMostly,
cudaCpuDeviceId);
cudaMemAdvise(_cuda_data, size + 4096, cudaMemAdviseSetAccessedBy,
0);
*/
data = _cuda_data;
#else
cpu_vm = std::make_unique<VirtualMemoryAllocator>(size);
data = cpu_vm->ptr;
TC_ASSERT(data != nullptr);
#endif
}
auto p = reinterpret_cast<uint64>(data);
data = (void *)(p + (4096 - p % 4096));
// allocate head/tail ptrs on unified memory
head = (void **)data;
tail = (void **)((char *)data + sizeof(void *));
data = (char *)data + 4096;
*head = data;
*tail = (void *)(((char *)head) + size);
}
taichi::Tlang::UnifiedAllocator::~UnifiedAllocator() {
if (!initialized()) {
return;
}
if (gpu) {
#if defined(CUDA_FOUND)
cudaFree(_cuda_data);
#else
TC_ERROR("No CUDA support");
#endif
}
}
void taichi::Tlang::UnifiedAllocator::create() {
TC_ASSERT(allocator() == nullptr);
void *dst;
bool gpu = false;
#if defined(CUDA_FOUND)
gpu = true;
cudaMallocManaged(&dst, sizeof(UnifiedAllocator));
#else
dst = std::malloc(sizeof(UnifiedAllocator));
#endif
allocator() = new (dst) UnifiedAllocator(1LL << 40, gpu);
}
void taichi::Tlang::UnifiedAllocator::free() {
(*allocator()).~UnifiedAllocator();
#if defined(CUDA_FOUND)
cudaFree(allocator());
#else
std::free(allocator());
#endif
allocator() = nullptr;
}
void taichi::Tlang::UnifiedAllocator::memset(unsigned char val) {
std::memset(data, val, size);
}
UnifiedAllocator::UnifiedAllocator() {
data = nullptr;
gpu_error_code = 0;
}
TLANG_NAMESPACE_END
extern "C" void *taichi_allocate_aligned(std::size_t size, int alignment) {
return taichi::Tlang::allocate(size, alignment);
}
<|endoftext|>
|
<commit_before>
#include "display.h"
namespace ssnake
{
Display::Display(const coordType size_x, const coordType size_y)
{
initCurses();
setTextures();
initScreen(size_x * 2, size_y);
#ifdef _WIN32
system("title SlicerSnake");
#endif
}
Display::~Display()
{
if (snakeWin != nullptr)
{
delwin(snakeWin);
}
if (gameWin != nullptr)
{
delwin(gameWin);
}
if (messageWin != nullptr)
{
delwin(messageWin);
}
clear();
refresh();
endwin();
if (gameTextures != nullptr)
{
if (gameTextures[0] != nullptr)
{
delete gameTextures[0];
}
delete gameTextures;
}
}
void Display::clearGameMessage()
{
std::size_t lengthLabelSize = std::strlen(lengthLabel) + windowPadding + 3;
std::size_t maxLengthLabelSize = std::strlen(maxLengthLabel) + windowPadding + 3;
unsigned int endPos = ScreenSize.x - maxLengthLabelSize - 1;
wmove(gameWin, 0, lengthLabelSize);
for (unsigned int i = lengthLabelSize; i < endPos; ++i)
{
waddch(gameWin, ' ');
}
gameWinModified = true;
}
void Display::clearScreen()
{
wclear(snakeWin);
wclear(gameWin);
wclear(messageWin);
wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
box(snakeWin, 0, 0);
wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
snakeWinModified = true;
gameWinModified = true;
messageWinModified = true;
// Clear screen immediately
update();
}
void Display::drawTexture(Texture_t texture, const Vec2& pos)
{
mvwaddchnstr(snakeWin, pos.y, pos.x * 2, gameTextures[texture], 2);
snakeWinModified = true;
}
coordType Display::getSize_x() const
{
return getmaxx(snakeWin) / 2;
}
coordType Display::getSize_y() const
{
return getmaxy(snakeWin);
}
void Display::initCurses()
{
/*
if (curscr != NULL)
{
initscr();
refresh();
}
*/
initscr();
start_color();
leaveok(stdscr, TRUE);
refresh();
curs_set(0);
}
void Display::initScreen(coordType size_x, coordType size_y)
{
ScreenSize.x = size_x;
ScreenSize.y = size_y;
#ifdef _WIN32
// Ensure window is large enough for requested display size on windows
// Since window users generally want things to work more than to have control
if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr))
{
int err = resize_term(ScreenSize.y, ScreenSize.x);
assert(err == OK);
refresh();
}
#endif
if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr))
{
// probably warning or exit here, but for now do nothing
}
if (snakeWin != nullptr)
{
wclear(snakeWin);
}
else
{
snakeWin = newpad(ScreenSize.y - (gameTextLines + windowPadding * 2), ScreenSize.x - (windowPadding * 2));
}
if (gameWin != nullptr)
{
wclear(gameWin);
}
else
{
gameWin = newpad(gameTextLines, ScreenSize.x - (windowPadding * 2));
}
if (messageWin != nullptr)
{
wclear(messageWin);
}
else
{
messageWin = subpad(snakeWin, ScreenSize.y - (gameTextLines + windowPadding * 2), ScreenSize.x - (windowPadding * 2), 0, 0);
}
// gameWin and messageWin always uses the same color for now
wattron(gameWin, COLOR_PAIR(GAME_TEXT_TEXTURE));
wattron(messageWin, COLOR_PAIR(GAME_TEXT_TEXTURE));
wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
box(snakeWin, 0, 0);
wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
snakeWinModified = true;
gameWinModified = true;
messageWinModified = true;
update();
return;
}
void Display::moveSnakeHead(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
drawTexture(snakeTextures.body, oldPos);
drawTexture(snakeTextures.head, newPos);
}
void Display::moveSnakeBody(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
// unused in curses implementation
}
void Display::moveSnakeTail(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
drawTexture(snakeTextures.tail, newPos);
// Don't overwrite anything else when clearing old tail
chtype prevChar = mvwinch(snakeWin, oldPos.y, oldPos.x * 2);
if (prevChar == gameTextures[snakeTextures.tail][0])
{
drawTexture(BACKGROUND_TEXTURE, oldPos);
}
}
void Display::printTextLine(unsigned int lineNumber, const char* message)
{
std::size_t size = std::strlen(message);
std::size_t maxTextLength = ScreenSize.x - (windowPadding * 2) - 2;
mvwaddnstr(messageWin, lineNumber, (getmaxx(messageWin) / 2) - (size / 2), message, static_cast<int>(maxTextLength));
messageWinModified = true;
}
void Display::printGameMessage(const char* message)
{
clearGameMessage();
std::size_t size = std::strlen(message);
std::size_t maxGameTextLength = 2 * ((getmaxx(gameWin) / 2) - (std::strlen(maxLengthLabel) + windowPadding + 2) - 1);
if (size > maxGameTextLength)
{
size = maxGameTextLength;
}
mvwaddnstr(gameWin, 0, (getmaxx(gameWin) / 2) - (size / 2), message, static_cast<int>(maxGameTextLength));
gameWinModified = true;
// Game messages should be printed immediately
update();
}
void Display::setTextures()
{
init_pair(SNAKE_TEXTURE, COLOR_GREEN, COLOR_BLACK);
init_pair(SS_SNAKE_TEXTURE, COLOR_MAGENTA, COLOR_BLACK);
init_pair(FOOD_TEXTURE, COLOR_YELLOW, COLOR_BLACK);
init_pair(BORDER_TEXTURE, COLOR_CYAN, COLOR_BLACK);
init_pair(GAME_TEXT_TEXTURE, COLOR_RED, COLOR_BLACK);
init_pair(COLLISION_TEXTURE, COLOR_RED, COLOR_BLACK);
init_pair(BACKGROUND_TEXTURE, COLOR_BLACK, COLOR_BLACK);
if (can_change_color() && COLORS>=256)
{
init_color(9, 40, 1000, 90);
init_color(10, 900, 70, 1000);
init_pair(SNAKE_HEAD_TEXTURE, 9, COLOR_BLACK);
init_pair(SS_SNAKE_HEAD_TEXTURE, 10, COLOR_BLACK);
}
else
{
init_pair(SNAKE_HEAD_TEXTURE, COLOR_GREEN, COLOR_BLACK);
init_pair(SS_SNAKE_HEAD_TEXTURE, COLOR_MAGENTA, COLOR_BLACK);
}
const chtype missingTexture = '?';
gameTextures = new chtype*[TEXTURE_COUNT];
gameTextures[0] = new chtype[TEXTURE_COUNT*2];
for (int i=1; i < TEXTURE_COUNT; ++i)
{
gameTextures[i] = *gameTextures + (2*i);
gameTextures[i][1] = gameTextures[i][0] = missingTexture;
}
gameTextures[SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SNAKE_TEXTURE);
gameTextures[SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SNAKE_TEXTURE);
gameTextures[SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SNAKE_HEAD_TEXTURE);
gameTextures[SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SNAKE_HEAD_TEXTURE);
gameTextures[SS_SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SS_SNAKE_TEXTURE);
gameTextures[SS_SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SS_SNAKE_TEXTURE);
gameTextures[SS_SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE);
gameTextures[SS_SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE);
gameTextures[FOOD_TEXTURE][0] = '{' | COLOR_PAIR(FOOD_TEXTURE);
gameTextures[FOOD_TEXTURE][1] = '}' | COLOR_PAIR(FOOD_TEXTURE);
gameTextures[COLLISION_TEXTURE][0] = '*' | COLOR_PAIR(COLLISION_TEXTURE);
gameTextures[COLLISION_TEXTURE][1] = '*' | COLOR_PAIR(COLLISION_TEXTURE);
gameTextures[BACKGROUND_TEXTURE][0] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE);
gameTextures[BACKGROUND_TEXTURE][1] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE);
}
void Display::updateLengthCounter(std::size_t length)
{
mvwaddstr(gameWin, 0, windowPadding, lengthLabel);
std::size_t lengthLabelSize = std::strlen(lengthLabel);
mvwaddstr(gameWin, 0, lengthLabelSize + windowPadding, " ");
mvwprintw(gameWin, 0, lengthLabelSize + windowPadding, "%d", length);
gameWinModified = true;
}
void Display::updateMaxLengthCounter(std::size_t maxLength)
{
std::size_t lengthLabelSize = std::strlen(maxLengthLabel);
mvwaddstr(gameWin, 0, getmaxx(gameWin) - (lengthLabelSize + windowPadding + 2), maxLengthLabel);
mvwaddstr(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), " ");
mvwprintw(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), "%d", maxLength);
gameWinModified = true;
}
void Display::update()
{
if ( !(snakeWinModified || gameWinModified || messageWinModified) )
{
return;
}
if (snakeWinModified)
{
pnoutrefresh(snakeWin, 0, 0,
windowPadding, windowPadding,
ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding);
}
if (messageWinModified)
{
pnoutrefresh(messageWin, 0, 0,
windowPadding, windowPadding,
ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding);
}
if (gameWinModified)
{
pnoutrefresh(gameWin, 0, 0,
ScreenSize.y - (gameTextLines + windowPadding), windowPadding,
ScreenSize.y - windowPadding, ScreenSize.x - windowPadding);
}
doupdate();
snakeWinModified = false;
gameWinModified = false;
messageWinModified = false;
}
}<commit_msg>Fix message display with PDCurses<commit_after>
#include "display.h"
namespace ssnake
{
Display::Display(const coordType size_x, const coordType size_y)
{
initCurses();
setTextures();
initScreen(size_x * 2, size_y);
#ifdef _WIN32
system("title SlicerSnake");
#endif
}
Display::~Display()
{
if (snakeWin != nullptr)
{
delwin(snakeWin);
}
if (gameWin != nullptr)
{
delwin(gameWin);
}
if (messageWin != nullptr)
{
delwin(messageWin);
}
clear();
refresh();
endwin();
if (gameTextures != nullptr)
{
if (gameTextures[0] != nullptr)
{
delete gameTextures[0];
}
delete gameTextures;
}
}
void Display::clearGameMessage()
{
std::size_t lengthLabelSize = std::strlen(lengthLabel) + windowPadding + 3;
std::size_t maxLengthLabelSize = std::strlen(maxLengthLabel) + windowPadding + 3;
unsigned int endPos = ScreenSize.x - maxLengthLabelSize - 1;
wmove(gameWin, 0, lengthLabelSize);
for (unsigned int i = lengthLabelSize; i < endPos; ++i)
{
waddch(gameWin, ' ');
}
gameWinModified = true;
}
void Display::clearScreen()
{
wclear(snakeWin);
wclear(gameWin);
wclear(messageWin);
wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
box(snakeWin, 0, 0);
wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
snakeWinModified = true;
gameWinModified = true;
messageWinModified = true;
// Clear screen immediately
update();
}
void Display::drawTexture(Texture_t texture, const Vec2& pos)
{
mvwaddchnstr(snakeWin, pos.y, pos.x * 2, gameTextures[texture], 2);
snakeWinModified = true;
}
coordType Display::getSize_x() const
{
return getmaxx(snakeWin) / 2;
}
coordType Display::getSize_y() const
{
return getmaxy(snakeWin);
}
void Display::initCurses()
{
/*
if (curscr != NULL)
{
initscr();
refresh();
}
*/
initscr();
start_color();
leaveok(stdscr, TRUE);
refresh();
curs_set(0);
}
void Display::initScreen(coordType size_x, coordType size_y)
{
ScreenSize.x = size_x;
ScreenSize.y = size_y;
#ifdef _WIN32
// Ensure window is large enough for requested display size on windows
// Since window users generally want things to work more than to have control
if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr))
{
int err = resize_term(ScreenSize.y, ScreenSize.x);
assert(err == OK);
refresh();
}
#endif
if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr))
{
// probably warning or exit here, but for now do nothing
}
if (snakeWin != nullptr)
{
wclear(snakeWin);
}
else
{
snakeWin = newpad(ScreenSize.y - (gameTextLines + windowPadding * 2), ScreenSize.x - (windowPadding * 2));
}
if (gameWin != nullptr)
{
wclear(gameWin);
}
else
{
gameWin = newpad(gameTextLines, ScreenSize.x - (windowPadding * 2));
}
if (messageWin != nullptr)
{
wclear(messageWin);
}
else
{
// We have to make it slightly smaller here for Windows builds with pdcurses, because pdcurses doesn't allow it to be the same size
messageWin = subpad(snakeWin, ScreenSize.y - (gameTextLines + windowPadding * 2) - 1, ScreenSize.x - (windowPadding * 2) - 2, 0, 0);
}
// gameWin and messageWin always uses the same color for now
wattron(gameWin, COLOR_PAIR(GAME_TEXT_TEXTURE));
wattron(messageWin, COLOR_PAIR(GAME_TEXT_TEXTURE));
wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
box(snakeWin, 0, 0);
wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE));
snakeWinModified = true;
gameWinModified = true;
messageWinModified = true;
update();
return;
}
void Display::moveSnakeHead(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
drawTexture(snakeTextures.body, oldPos);
drawTexture(snakeTextures.head, newPos);
}
void Display::moveSnakeBody(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
// unused in curses implementation
}
void Display::moveSnakeTail(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures)
{
drawTexture(snakeTextures.tail, newPos);
// Don't overwrite anything else when clearing old tail
chtype prevChar = mvwinch(snakeWin, oldPos.y, oldPos.x * 2);
if (prevChar == gameTextures[snakeTextures.tail][0])
{
drawTexture(BACKGROUND_TEXTURE, oldPos);
}
}
void Display::printTextLine(unsigned int lineNumber, const char* message)
{
std::size_t size = std::strlen(message);
std::size_t maxTextLength = getmaxx(messageWin) - (windowPadding * 2) - 2;
mvwaddnstr(messageWin, lineNumber, (getmaxx(messageWin) / 2) - (size / 2) + 1, message, static_cast<int>(maxTextLength));
messageWinModified = true;
}
void Display::printGameMessage(const char* message)
{
clearGameMessage();
std::size_t size = std::strlen(message);
std::size_t maxGameTextLength = 2 * ((getmaxx(gameWin) / 2) - (std::strlen(maxLengthLabel) + windowPadding + 2) - 1);
if (size > maxGameTextLength)
{
size = maxGameTextLength;
}
mvwaddnstr(gameWin, 0, (getmaxx(gameWin) / 2) - (size / 2), message, static_cast<int>(maxGameTextLength));
gameWinModified = true;
// Game messages should be printed immediately
update();
}
void Display::setTextures()
{
init_pair(SNAKE_TEXTURE, COLOR_GREEN, COLOR_BLACK);
init_pair(SS_SNAKE_TEXTURE, COLOR_MAGENTA, COLOR_BLACK);
init_pair(FOOD_TEXTURE, COLOR_YELLOW, COLOR_BLACK);
init_pair(BORDER_TEXTURE, COLOR_CYAN, COLOR_BLACK);
init_pair(GAME_TEXT_TEXTURE, COLOR_RED, COLOR_BLACK);
init_pair(COLLISION_TEXTURE, COLOR_RED, COLOR_BLACK);
init_pair(BACKGROUND_TEXTURE, COLOR_BLACK, COLOR_BLACK);
if (can_change_color() && COLORS>=256)
{
init_color(9, 40, 1000, 90);
init_color(10, 900, 70, 1000);
init_pair(SNAKE_HEAD_TEXTURE, 9, COLOR_BLACK);
init_pair(SS_SNAKE_HEAD_TEXTURE, 10, COLOR_BLACK);
}
else
{
init_pair(SNAKE_HEAD_TEXTURE, COLOR_GREEN, COLOR_BLACK);
init_pair(SS_SNAKE_HEAD_TEXTURE, COLOR_MAGENTA, COLOR_BLACK);
}
const chtype missingTexture = '?';
gameTextures = new chtype*[TEXTURE_COUNT];
gameTextures[0] = new chtype[TEXTURE_COUNT*2];
for (int i=1; i < TEXTURE_COUNT; ++i)
{
gameTextures[i] = *gameTextures + (2*i);
gameTextures[i][1] = gameTextures[i][0] = missingTexture;
}
gameTextures[SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SNAKE_TEXTURE);
gameTextures[SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SNAKE_TEXTURE);
gameTextures[SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SNAKE_HEAD_TEXTURE);
gameTextures[SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SNAKE_HEAD_TEXTURE);
gameTextures[SS_SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SS_SNAKE_TEXTURE);
gameTextures[SS_SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SS_SNAKE_TEXTURE);
gameTextures[SS_SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE);
gameTextures[SS_SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE);
gameTextures[FOOD_TEXTURE][0] = '{' | COLOR_PAIR(FOOD_TEXTURE);
gameTextures[FOOD_TEXTURE][1] = '}' | COLOR_PAIR(FOOD_TEXTURE);
gameTextures[COLLISION_TEXTURE][0] = '*' | COLOR_PAIR(COLLISION_TEXTURE);
gameTextures[COLLISION_TEXTURE][1] = '*' | COLOR_PAIR(COLLISION_TEXTURE);
gameTextures[BACKGROUND_TEXTURE][0] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE);
gameTextures[BACKGROUND_TEXTURE][1] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE);
}
void Display::updateLengthCounter(std::size_t length)
{
mvwaddstr(gameWin, 0, windowPadding, lengthLabel);
std::size_t lengthLabelSize = std::strlen(lengthLabel);
mvwaddstr(gameWin, 0, lengthLabelSize + windowPadding, " ");
mvwprintw(gameWin, 0, lengthLabelSize + windowPadding, "%d", length);
gameWinModified = true;
}
void Display::updateMaxLengthCounter(std::size_t maxLength)
{
std::size_t lengthLabelSize = std::strlen(maxLengthLabel);
mvwaddstr(gameWin, 0, getmaxx(gameWin) - (lengthLabelSize + windowPadding + 2), maxLengthLabel);
mvwaddstr(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), " ");
mvwprintw(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), "%d", maxLength);
gameWinModified = true;
}
void Display::update()
{
if ( !(snakeWinModified || gameWinModified || messageWinModified) )
{
return;
}
if (snakeWinModified)
{
pnoutrefresh(snakeWin, 0, 0,
windowPadding, windowPadding,
ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding);
}
if (messageWinModified)
{
pnoutrefresh(messageWin, 0, 0,
windowPadding, windowPadding,
ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding);
}
if (gameWinModified)
{
pnoutrefresh(gameWin, 0, 0,
ScreenSize.y - (gameTextLines + windowPadding), windowPadding,
ScreenSize.y - windowPadding, ScreenSize.x - windowPadding);
}
doupdate();
snakeWinModified = false;
gameWinModified = false;
messageWinModified = false;
}
}<|endoftext|>
|
<commit_before>#include "openlr/openlr_match_quality/openlr_assessment_tool/mainwindow.hpp"
#include "openlr/openlr_match_quality/openlr_assessment_tool/traffic_panel.hpp"
#include "openlr/openlr_match_quality/openlr_assessment_tool/trafficmodeinitdlg.h"
#include "openlr/openlr_match_quality/openlr_assessment_tool/map_widget.hpp"
#include "map/framework.hpp"
#include "drape_frontend/drape_api.hpp"
#include "routing/features_road_graph.hpp"
#include "routing/road_graph.hpp"
#include "routing_common/car_model.hpp"
#include "geometry/mercator.hpp"
#include "geometry/point2d.hpp"
#include <QDockWidget>
#include <QFileDialog>
#include <QLayout>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QStandardPaths>
#include <cerrno>
#include <cstring>
#include <vector>
namespace
{
class TrafficDrawerDelegate : public TrafficDrawerDelegateBase
{
static constexpr char const * kEncodedLineId = "encodedPath";
static constexpr char const * kDecodedLineId = "decodedPath";
static constexpr char const * kGoldenLineId = "goldenPath";
public:
TrafficDrawerDelegate(Framework & framework)
: m_framework(framework)
, m_drapeApi(m_framework.GetDrapeApi())
, m_bm(framework.GetBookmarkManager())
{
}
void SetViewportCenter(m2::PointD const & center) override
{
m_framework.SetViewportCenter(center);
}
void DrawDecodedSegments(std::vector<m2::PointD> const & points) override
{
CHECK(!points.empty(), ("Points must not be empty."));
LOG(LINFO, ("Decoded segment", points));
m_drapeApi.AddLine(kDecodedLineId,
df::DrapeApiLineData(points, dp::Color(0, 0, 255, 255))
.Width(3.0f).ShowPoints(true /* markPoints */));
}
void DrawEncodedSegment(std::vector<m2::PointD> const & points) override
{
LOG(LINFO, ("Encoded segment", points));
m_drapeApi.AddLine(kEncodedLineId,
df::DrapeApiLineData(points, dp::Color(255, 0, 0, 255))
.Width(3.0f).ShowPoints(true /* markPoints */));
}
void DrawGoldenPath(std::vector<m2::PointD> const & points) override
{
m_drapeApi.AddLine(kGoldenLineId,
df::DrapeApiLineData(points, dp::Color(255, 127, 36, 255))
.Width(4.0f).ShowPoints(true /* markPoints */));
}
void ClearGoldenPath() override
{
m_drapeApi.RemoveLine(kGoldenLineId);
}
void ClearAllPaths() override
{
m_drapeApi.Clear();
}
void VisualizePoints(std::vector<m2::PointD> const & points) override
{
UserMarkNotificationGuard g(m_bm, UserMarkType::DEBUG_MARK);
g.m_controller.SetIsVisible(true);
g.m_controller.SetIsDrawable(true);
for (auto const & p : points)
g.m_controller.CreateUserMark(p);
}
void ClearAllVisualizedPoints() override
{
UserMarkNotificationGuard g(m_bm, UserMarkType::DEBUG_MARK);
g.m_controller.Clear();
}
private:
Framework & m_framework;
df::DrapeApi & m_drapeApi;
BookmarkManager & m_bm;
};
bool PointsMatch(m2::PointD const & a, m2::PointD const & b)
{
auto constexpr kToleranceDistanceM = 1.0;
return MercatorBounds::DistanceOnEarth(a, b) < kToleranceDistanceM;
}
class PointsControllerDelegate : public PointsControllerDelegateBase
{
public:
PointsControllerDelegate(Framework & framework)
: m_framework(framework)
, m_index(framework.GetIndex())
, m_roadGraph(m_index, routing::IRoadGraph::Mode::ObeyOnewayTag,
make_unique<routing::CarModelFactory>(routing::CountryParentNameGetterFn{}))
{
}
std::vector<m2::PointD> GetAllJunctionPointsInViewport() const override
{
std::vector<m2::PointD> points;
auto const & rect = m_framework.GetCurrentViewport();
auto const pushPoint = [&points, &rect](m2::PointD const & point) {
if (!rect.IsPointInside(point))
return;
for (auto const & p : points)
{
if (PointsMatch(point, p))
return;
}
points.push_back(point);
};
auto const pushFeaturePoints = [&pushPoint](FeatureType & ft) {
if (ft.GetFeatureType() != feature::GEOM_LINE)
return;
auto const roadClass = ftypes::GetHighwayClass(ft);
if (roadClass == ftypes::HighwayClass::Error ||
roadClass == ftypes::HighwayClass::Pedestrian)
{
return;
}
ft.ForEachPoint(pushPoint, scales::GetUpperScale());
};
m_index.ForEachInRect(pushFeaturePoints, rect, scales::GetUpperScale());
return points;
}
std::pair<std::vector<FeaturePoint>, m2::PointD> GetCandidatePoints(
m2::PointD const & p) const override
{
auto constexpr kInvalidIndex = std::numeric_limits<size_t>::max();
std::vector<FeaturePoint> points;
m2::PointD pointOnFt;
indexer::ForEachFeatureAtPoint(m_index, [&points, &p, &pointOnFt](FeatureType & ft) {
if (ft.GetFeatureType() != feature::GEOM_LINE)
return;
ft.ParseGeometry(FeatureType::BEST_GEOMETRY);
auto minDistance = std::numeric_limits<double>::max();
auto bestPointIndex = kInvalidIndex;
for (size_t i = 0; i < ft.GetPointsCount(); ++i)
{
auto const & fp = ft.GetPoint(i);
auto const distance = MercatorBounds::DistanceOnEarth(fp, p);
if (PointsMatch(fp, p) && distance < minDistance)
{
bestPointIndex = i;
minDistance = distance;
}
}
if (bestPointIndex != kInvalidIndex)
{
points.emplace_back(ft.GetID(), bestPointIndex);
pointOnFt = ft.GetPoint(bestPointIndex);
}
},
p);
return std::make_pair(points, pointOnFt);
}
std::vector<m2::PointD> GetReachablePoints(m2::PointD const & p) const override
{
routing::FeaturesRoadGraph::TEdgeVector edges;
m_roadGraph.GetOutgoingEdges(
routing::Junction(p, feature::kDefaultAltitudeMeters),
edges);
std::vector<m2::PointD> points;
for (auto const & e : edges)
points.push_back(e.GetEndJunction().GetPoint());
return points;
}
ClickType CheckClick(m2::PointD const & clickPoint,
m2::PointD const & lastClickedPoint,
std::vector<m2::PointD> const & reachablePoints) const override
{
// == Comparison is safe here since |clickPoint| is adjusted by GetFeaturesPointsByPoint
// so to be equal the closest feature's one.
if (clickPoint == lastClickedPoint)
return ClickType::Remove;
for (auto const & p : reachablePoints)
{
if (PointsMatch(clickPoint, p))
return ClickType::Add;
}
return ClickType::Miss;
}
private:
Framework & m_framework;
Index const & m_index;
routing::FeaturesRoadGraph m_roadGraph;
};
} // namespace
MainWindow::MainWindow(Framework & framework)
: m_framework(framework)
{
m_mapWidget = new MapWidget(
m_framework, false /* apiOpenGLES3 */, this /* parent */
);
setCentralWidget(m_mapWidget);
// setWindowTitle(tr("MAPS.ME"));
// setWindowIcon(QIcon(":/ui/logo.png"));
QMenu * fileMenu = new QMenu("File", this);
menuBar()->addMenu(fileMenu);
fileMenu->addAction("Open sample", this, &MainWindow::OnOpenTrafficSample);
m_closeTrafficSampleAction = fileMenu->addAction(
"Close sample", this, &MainWindow::OnCloseTrafficSample
);
m_saveTrafficSampleAction = fileMenu->addAction(
"Save sample", this, &MainWindow::OnSaveTrafficSample
);
m_startEditingAction = fileMenu->addAction("Start editing", [this] {
m_trafficMode->StartBuildingPath();
m_mapWidget->SetMode(MapWidget::Mode::TrafficMarkup);
m_commitPathAction->setEnabled(true /* enabled */);
m_cancelPathAction->setEnabled(true /* enabled */);
});
m_commitPathAction = fileMenu->addAction("Commit path", [this] {
m_trafficMode->CommitPath();
m_mapWidget->SetMode(MapWidget::Mode::Normal);
});
m_cancelPathAction = fileMenu->addAction("Cancel path", [this] {
m_trafficMode->RollBackPath();
m_mapWidget->SetMode(MapWidget::Mode::Normal);
});
m_closeTrafficSampleAction->setEnabled(false /* enabled */);
m_saveTrafficSampleAction->setEnabled(false /* enabled */);
m_startEditingAction->setEnabled(false /* enabled */);
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
}
void MainWindow::CreateTrafficPanel(string const & dataFilePath)
{
m_trafficMode = new TrafficMode(dataFilePath,
m_framework.GetIndex(),
make_unique<TrafficDrawerDelegate>(m_framework),
make_unique<PointsControllerDelegate>(m_framework));
connect(m_mapWidget, &MapWidget::TrafficMarkupClick,
m_trafficMode, &TrafficMode::OnClick);
connect(m_trafficMode, &TrafficMode::EditingStopped,
this, &MainWindow::OnPathEditingStop);
m_docWidget = new QDockWidget(tr("Routes"), this);
addDockWidget(Qt::DockWidgetArea::RightDockWidgetArea, m_docWidget);
m_docWidget->setWidget(new TrafficPanel(m_trafficMode, m_docWidget));
m_docWidget->adjustSize();
m_docWidget->show();
}
void MainWindow::DestroyTrafficPanel()
{
removeDockWidget(m_docWidget);
delete m_docWidget;
m_docWidget = nullptr;
delete m_trafficMode;
m_trafficMode = nullptr;
m_mapWidget->SetMode(MapWidget::Mode::Normal);
}
void MainWindow::OnOpenTrafficSample()
{
TrafficModeInitDlg dlg;
dlg.exec();
if (dlg.result() != QDialog::DialogCode::Accepted)
return;
try
{
CreateTrafficPanel(dlg.GetDataFilePath());
}
catch (TrafficModeError const & e)
{
QMessageBox::critical(this, "Data loading error", QString("Can't load data file."));
LOG(LERROR, (e.Msg()));
return;
}
m_closeTrafficSampleAction->setEnabled(true /* enabled */);
m_saveTrafficSampleAction->setEnabled(true /* enabled */);
m_startEditingAction->setEnabled(true /* enabled */);
}
void MainWindow::OnCloseTrafficSample()
{
// TODO(mgsergio):
// If not saved, ask a user if he/she wants to save.
// OnSaveTrafficSample()
m_saveTrafficSampleAction->setEnabled(false /* enabled */);
m_closeTrafficSampleAction->setEnabled(false /* enabled */);
m_startEditingAction->setEnabled(false /* enabled */);
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
DestroyTrafficPanel();
}
void MainWindow::OnSaveTrafficSample()
{
// TODO(mgsergio): Add default filename.
auto const & fileName = QFileDialog::getSaveFileName(this, "Save sample");
if (fileName.isEmpty())
return;
if (!m_trafficMode->SaveSampleAs(fileName.toStdString()))
{
QMessageBox::critical(
this, "Saving error",
QString("Can't save file: ") + strerror(errno));
}
}
void MainWindow::OnPathEditingStop()
{
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
}
<commit_msg>[openlr] Fix to OpenLR assessment tool CarModelFactory creation.<commit_after>#include "openlr/openlr_match_quality/openlr_assessment_tool/mainwindow.hpp"
#include "openlr/openlr_match_quality/openlr_assessment_tool/traffic_panel.hpp"
#include "openlr/openlr_match_quality/openlr_assessment_tool/trafficmodeinitdlg.h"
#include "openlr/openlr_match_quality/openlr_assessment_tool/map_widget.hpp"
#include "map/framework.hpp"
#include "drape_frontend/drape_api.hpp"
#include "routing/features_road_graph.hpp"
#include "routing/road_graph.hpp"
#include "routing_common/car_model.hpp"
#include "storage/country_parent_getter.hpp"
#include "geometry/mercator.hpp"
#include "geometry/point2d.hpp"
#include <QDockWidget>
#include <QFileDialog>
#include <QLayout>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QStandardPaths>
#include <cerrno>
#include <cstring>
#include <vector>
namespace
{
class TrafficDrawerDelegate : public TrafficDrawerDelegateBase
{
static constexpr char const * kEncodedLineId = "encodedPath";
static constexpr char const * kDecodedLineId = "decodedPath";
static constexpr char const * kGoldenLineId = "goldenPath";
public:
TrafficDrawerDelegate(Framework & framework)
: m_framework(framework)
, m_drapeApi(m_framework.GetDrapeApi())
, m_bm(framework.GetBookmarkManager())
{
}
void SetViewportCenter(m2::PointD const & center) override
{
m_framework.SetViewportCenter(center);
}
void DrawDecodedSegments(std::vector<m2::PointD> const & points) override
{
CHECK(!points.empty(), ("Points must not be empty."));
LOG(LINFO, ("Decoded segment", points));
m_drapeApi.AddLine(kDecodedLineId,
df::DrapeApiLineData(points, dp::Color(0, 0, 255, 255))
.Width(3.0f).ShowPoints(true /* markPoints */));
}
void DrawEncodedSegment(std::vector<m2::PointD> const & points) override
{
LOG(LINFO, ("Encoded segment", points));
m_drapeApi.AddLine(kEncodedLineId,
df::DrapeApiLineData(points, dp::Color(255, 0, 0, 255))
.Width(3.0f).ShowPoints(true /* markPoints */));
}
void DrawGoldenPath(std::vector<m2::PointD> const & points) override
{
m_drapeApi.AddLine(kGoldenLineId,
df::DrapeApiLineData(points, dp::Color(255, 127, 36, 255))
.Width(4.0f).ShowPoints(true /* markPoints */));
}
void ClearGoldenPath() override
{
m_drapeApi.RemoveLine(kGoldenLineId);
}
void ClearAllPaths() override
{
m_drapeApi.Clear();
}
void VisualizePoints(std::vector<m2::PointD> const & points) override
{
UserMarkNotificationGuard g(m_bm, UserMarkType::DEBUG_MARK);
g.m_controller.SetIsVisible(true);
g.m_controller.SetIsDrawable(true);
for (auto const & p : points)
g.m_controller.CreateUserMark(p);
}
void ClearAllVisualizedPoints() override
{
UserMarkNotificationGuard g(m_bm, UserMarkType::DEBUG_MARK);
g.m_controller.Clear();
}
private:
Framework & m_framework;
df::DrapeApi & m_drapeApi;
BookmarkManager & m_bm;
};
bool PointsMatch(m2::PointD const & a, m2::PointD const & b)
{
auto constexpr kToleranceDistanceM = 1.0;
return MercatorBounds::DistanceOnEarth(a, b) < kToleranceDistanceM;
}
class PointsControllerDelegate : public PointsControllerDelegateBase
{
public:
PointsControllerDelegate(Framework & framework)
: m_framework(framework)
, m_index(framework.GetIndex())
, m_roadGraph(m_index, routing::IRoadGraph::Mode::ObeyOnewayTag,
make_unique<routing::CarModelFactory>(storage::CountryParentGetter{}))
{
}
std::vector<m2::PointD> GetAllJunctionPointsInViewport() const override
{
std::vector<m2::PointD> points;
auto const & rect = m_framework.GetCurrentViewport();
auto const pushPoint = [&points, &rect](m2::PointD const & point) {
if (!rect.IsPointInside(point))
return;
for (auto const & p : points)
{
if (PointsMatch(point, p))
return;
}
points.push_back(point);
};
auto const pushFeaturePoints = [&pushPoint](FeatureType & ft) {
if (ft.GetFeatureType() != feature::GEOM_LINE)
return;
auto const roadClass = ftypes::GetHighwayClass(ft);
if (roadClass == ftypes::HighwayClass::Error ||
roadClass == ftypes::HighwayClass::Pedestrian)
{
return;
}
ft.ForEachPoint(pushPoint, scales::GetUpperScale());
};
m_index.ForEachInRect(pushFeaturePoints, rect, scales::GetUpperScale());
return points;
}
std::pair<std::vector<FeaturePoint>, m2::PointD> GetCandidatePoints(
m2::PointD const & p) const override
{
auto constexpr kInvalidIndex = std::numeric_limits<size_t>::max();
std::vector<FeaturePoint> points;
m2::PointD pointOnFt;
indexer::ForEachFeatureAtPoint(m_index, [&points, &p, &pointOnFt](FeatureType & ft) {
if (ft.GetFeatureType() != feature::GEOM_LINE)
return;
ft.ParseGeometry(FeatureType::BEST_GEOMETRY);
auto minDistance = std::numeric_limits<double>::max();
auto bestPointIndex = kInvalidIndex;
for (size_t i = 0; i < ft.GetPointsCount(); ++i)
{
auto const & fp = ft.GetPoint(i);
auto const distance = MercatorBounds::DistanceOnEarth(fp, p);
if (PointsMatch(fp, p) && distance < minDistance)
{
bestPointIndex = i;
minDistance = distance;
}
}
if (bestPointIndex != kInvalidIndex)
{
points.emplace_back(ft.GetID(), bestPointIndex);
pointOnFt = ft.GetPoint(bestPointIndex);
}
},
p);
return std::make_pair(points, pointOnFt);
}
std::vector<m2::PointD> GetReachablePoints(m2::PointD const & p) const override
{
routing::FeaturesRoadGraph::TEdgeVector edges;
m_roadGraph.GetOutgoingEdges(
routing::Junction(p, feature::kDefaultAltitudeMeters),
edges);
std::vector<m2::PointD> points;
for (auto const & e : edges)
points.push_back(e.GetEndJunction().GetPoint());
return points;
}
ClickType CheckClick(m2::PointD const & clickPoint,
m2::PointD const & lastClickedPoint,
std::vector<m2::PointD> const & reachablePoints) const override
{
// == Comparison is safe here since |clickPoint| is adjusted by GetFeaturesPointsByPoint
// so to be equal the closest feature's one.
if (clickPoint == lastClickedPoint)
return ClickType::Remove;
for (auto const & p : reachablePoints)
{
if (PointsMatch(clickPoint, p))
return ClickType::Add;
}
return ClickType::Miss;
}
private:
Framework & m_framework;
Index const & m_index;
routing::FeaturesRoadGraph m_roadGraph;
};
} // namespace
MainWindow::MainWindow(Framework & framework)
: m_framework(framework)
{
m_mapWidget = new MapWidget(
m_framework, false /* apiOpenGLES3 */, this /* parent */
);
setCentralWidget(m_mapWidget);
// setWindowTitle(tr("MAPS.ME"));
// setWindowIcon(QIcon(":/ui/logo.png"));
QMenu * fileMenu = new QMenu("File", this);
menuBar()->addMenu(fileMenu);
fileMenu->addAction("Open sample", this, &MainWindow::OnOpenTrafficSample);
m_closeTrafficSampleAction = fileMenu->addAction(
"Close sample", this, &MainWindow::OnCloseTrafficSample
);
m_saveTrafficSampleAction = fileMenu->addAction(
"Save sample", this, &MainWindow::OnSaveTrafficSample
);
m_startEditingAction = fileMenu->addAction("Start editing", [this] {
m_trafficMode->StartBuildingPath();
m_mapWidget->SetMode(MapWidget::Mode::TrafficMarkup);
m_commitPathAction->setEnabled(true /* enabled */);
m_cancelPathAction->setEnabled(true /* enabled */);
});
m_commitPathAction = fileMenu->addAction("Commit path", [this] {
m_trafficMode->CommitPath();
m_mapWidget->SetMode(MapWidget::Mode::Normal);
});
m_cancelPathAction = fileMenu->addAction("Cancel path", [this] {
m_trafficMode->RollBackPath();
m_mapWidget->SetMode(MapWidget::Mode::Normal);
});
m_closeTrafficSampleAction->setEnabled(false /* enabled */);
m_saveTrafficSampleAction->setEnabled(false /* enabled */);
m_startEditingAction->setEnabled(false /* enabled */);
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
}
void MainWindow::CreateTrafficPanel(string const & dataFilePath)
{
m_trafficMode = new TrafficMode(dataFilePath,
m_framework.GetIndex(),
make_unique<TrafficDrawerDelegate>(m_framework),
make_unique<PointsControllerDelegate>(m_framework));
connect(m_mapWidget, &MapWidget::TrafficMarkupClick,
m_trafficMode, &TrafficMode::OnClick);
connect(m_trafficMode, &TrafficMode::EditingStopped,
this, &MainWindow::OnPathEditingStop);
m_docWidget = new QDockWidget(tr("Routes"), this);
addDockWidget(Qt::DockWidgetArea::RightDockWidgetArea, m_docWidget);
m_docWidget->setWidget(new TrafficPanel(m_trafficMode, m_docWidget));
m_docWidget->adjustSize();
m_docWidget->show();
}
void MainWindow::DestroyTrafficPanel()
{
removeDockWidget(m_docWidget);
delete m_docWidget;
m_docWidget = nullptr;
delete m_trafficMode;
m_trafficMode = nullptr;
m_mapWidget->SetMode(MapWidget::Mode::Normal);
}
void MainWindow::OnOpenTrafficSample()
{
TrafficModeInitDlg dlg;
dlg.exec();
if (dlg.result() != QDialog::DialogCode::Accepted)
return;
try
{
CreateTrafficPanel(dlg.GetDataFilePath());
}
catch (TrafficModeError const & e)
{
QMessageBox::critical(this, "Data loading error", QString("Can't load data file."));
LOG(LERROR, (e.Msg()));
return;
}
m_closeTrafficSampleAction->setEnabled(true /* enabled */);
m_saveTrafficSampleAction->setEnabled(true /* enabled */);
m_startEditingAction->setEnabled(true /* enabled */);
}
void MainWindow::OnCloseTrafficSample()
{
// TODO(mgsergio):
// If not saved, ask a user if he/she wants to save.
// OnSaveTrafficSample()
m_saveTrafficSampleAction->setEnabled(false /* enabled */);
m_closeTrafficSampleAction->setEnabled(false /* enabled */);
m_startEditingAction->setEnabled(false /* enabled */);
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
DestroyTrafficPanel();
}
void MainWindow::OnSaveTrafficSample()
{
// TODO(mgsergio): Add default filename.
auto const & fileName = QFileDialog::getSaveFileName(this, "Save sample");
if (fileName.isEmpty())
return;
if (!m_trafficMode->SaveSampleAs(fileName.toStdString()))
{
QMessageBox::critical(
this, "Saving error",
QString("Can't save file: ") + strerror(errno));
}
}
void MainWindow::OnPathEditingStop()
{
m_commitPathAction->setEnabled(false /* enabled */);
m_cancelPathAction->setEnabled(false /* enabled */);
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "../includes/yz_ogre_vfs_DataStream.hpp"
yz::ogre::vfs::DataStream::DataStream(const yz::physfs::File* file) {
LOG_FUNCTION
vfsFile = file;
mSize = (size_t) this->vfsFile->getSize();
}
yz::ogre::vfs::DataStream::DataStream(const Ogre::String& name, const yz::physfs::File* file) : Ogre::DataStream(name) {
LOG_FUNCTION
vfsFile = file;
mSize = (size_t) this->vfsFile->getSize();
}
yz::ogre::vfs::DataStream::~DataStream() {
LOG_FUNCTION
close();
}
size_t yz::ogre::vfs::DataStream::read(void* buf, size_t count) {
LOG_FUNCTION
return this->vfsFile->readBytes(buf, count);
}
void yz::ogre::vfs::DataStream::seek(size_t pos) {
LOG_FUNCTION
this->vfsFile->seek(pos);
}
size_t yz::ogre::vfs::DataStream::tell() const {
LOG_FUNCTION
return (size_t) this->vfsFile->tell(file);
}
void yz::ogre::vfs::DataStream::skip(long count) {
LOG_FUNCTION
size_t pos = this->tell() + count;
this->seek(pos);
}
bool yz::ogre::vfs::DataStream::eof() const {
LOG_FUNCTION
return this->vfsFile->isEof();
}
void yz::ogre::vfs::DataStream::close() {
LOG_FUNCTION
this->vfsFile->close();
}
<commit_msg>Update yz_ogre_vfs_DataStream.cpp<commit_after>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "../includes/yz_ogre_vfs_DataStream.hpp"
yz::ogre::vfs::DataStream::DataStream(yz::physfs::File* file) {
LOG_FUNCTION
vfsFile = file;
mSize = (size_t) this->vfsFile->getSize();
}
yz::ogre::vfs::DataStream::DataStream(const Ogre::String& name, yz::physfs::File* file) : Ogre::DataStream(name) {
LOG_FUNCTION
vfsFile = file;
mSize = (size_t) this->vfsFile->getSize();
}
yz::ogre::vfs::DataStream::~DataStream() {
LOG_FUNCTION
close();
}
size_t yz::ogre::vfs::DataStream::read(void* buf, size_t count) {
LOG_FUNCTION
return this->vfsFile->readBytes(buf, count);
}
void yz::ogre::vfs::DataStream::seek(size_t pos) {
LOG_FUNCTION
this->vfsFile->seek(pos);
}
size_t yz::ogre::vfs::DataStream::tell() const {
LOG_FUNCTION
return (size_t) this->vfsFile->tell(file);
}
void yz::ogre::vfs::DataStream::skip(long count) {
LOG_FUNCTION
size_t pos = this->tell() + count;
this->seek(pos);
}
bool yz::ogre::vfs::DataStream::eof() const {
LOG_FUNCTION
return this->vfsFile->isEof();
}
void yz::ogre::vfs::DataStream::close() {
LOG_FUNCTION
this->vfsFile->close();
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Sanjiban Bairagya <[email protected]>
//
#include "TourPlayback.h"
#include <QTimer>
#include <QList>
#include <QSlider>
#include <qurl.h>
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "GeoDataTour.h"
#include "GeoDataTourPrimitive.h"
#include "GeoDataFlyTo.h"
#include "GeoDataLookAt.h"
#include "GeoDataCamera.h"
#include "GeoDataWait.h"
#include "GeoDataTourControl.h"
#include "GeoDataSoundCue.h"
#include "GeoDataAnimatedUpdate.h"
#include "GeoDataTypes.h"
#include "PlaybackFlyToItem.h"
#include "PlaybackAnimatedUpdateItem.h"
#include "PlaybackWaitItem.h"
#include "PlaybackTourControlItem.h"
#include "PlaybackSoundCueItem.h"
#include "PlaybackAnimatedUpdateItem.h"
namespace Marble
{
class TourPlaybackPrivate
{
public:
TourPlaybackPrivate(TourPlayback *q);
const GeoDataTour *m_tour;
bool m_pause;
SerialTrack *m_mainTrack;
QList<ParallelTrack*> m_parallelTracks;
GeoDataCoordinates m_coordinates;
GeoDataFlyTo m_mapCenter;
MarbleWidget *m_widget;
QSlider *m_slider;
protected:
TourPlayback *q_ptr;
private:
Q_DECLARE_PUBLIC(TourPlayback)
};
TourPlaybackPrivate::TourPlaybackPrivate(TourPlayback* q) :
m_tour( &GeoDataTour::null ),
m_pause( false ),
m_mainTrack( new SerialTrack),
q_ptr( q )
{
// do nothing
}
TourPlayback::TourPlayback(QObject *parent) :
QObject(parent),
d(new TourPlaybackPrivate(this))
{
connect( mainTrack(), SIGNAL( centerOn( GeoDataCoordinates ) ), this, SIGNAL( centerOn( GeoDataCoordinates ) ) );
connect( mainTrack(), SIGNAL( progressChanged( double ) ), this, SIGNAL( progressChanged( double ) ) );
connect( mainTrack(), SIGNAL( finished() ), this, SLOT( finishedSlot() ) );
}
TourPlayback::~TourPlayback()
{
delete d;
}
void TourPlayback::finishedSlot()
{
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->stop();
track->setPaused( false );
}
}
SerialTrack* TourPlayback::mainTrack()
{
return d->m_mainTrack;
}
bool TourPlayback::isPlaying() const
{
return !d->m_pause;
}
void TourPlayback::setMarbleWidget(MarbleWidget* widget)
{
d->m_widget = widget;
}
void TourPlayback::setupProgressBar( QSlider *slider )
{
slider->setMaximum( d->m_mainTrack->duration() * 100 );
d->m_slider = slider;
}
void TourPlayback::setTour(const GeoDataTour *tour)
{
d->m_mainTrack->clear();
d->m_parallelTracks.clear();
if (tour) {
d->m_tour = tour;
}
else {
d->m_tour = &GeoDataTour::null;
}
double delay = 0;
for( int i = 0; i < d->m_tour->playlist()->size(); i++){
const GeoDataTourPrimitive* primitive = d->m_tour->playlist()->primitive( i );
if( primitive->nodeType() == GeoDataTypes::GeoDataFlyToType ){
const GeoDataFlyTo *flyTo = dynamic_cast<const GeoDataFlyTo*>(primitive);
d->m_mainTrack->append( new PlaybackFlyToItem( flyTo ) );
delay += flyTo->duration();
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataWaitType ){
const GeoDataWait *wait = dynamic_cast<const GeoDataWait*>(primitive);
d->m_mainTrack->append( new PlaybackWaitItem( wait ) );
delay += wait->duration();
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataTourControlType ){
const GeoDataTourControl *tourControl = dynamic_cast<const GeoDataTourControl*>(primitive);
d->m_mainTrack->append( new PlaybackTourControlItem( tourControl ) );
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataSoundCueType ){
const GeoDataSoundCue *soundCue = dynamic_cast<const GeoDataSoundCue*>(primitive);
PlaybackSoundCueItem *item = new PlaybackSoundCueItem( soundCue );
ParallelTrack *track = new ParallelTrack( item );
track->setDelayBeforeTrackStarts( delay );
d->m_parallelTracks.append( track );
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataAnimatedUpdateType ){
const GeoDataAnimatedUpdate *animatedUpdate = dynamic_cast<const GeoDataAnimatedUpdate*>(primitive);
PlaybackAnimatedUpdateItem *item = new PlaybackAnimatedUpdateItem( animatedUpdate );
ParallelTrack *track = new ParallelTrack( item );
track->setDelayBeforeTrackStarts( delay );
d->m_parallelTracks.append( track );
}
}
Q_ASSERT( d->m_widget );
d->m_mapCenter.setView( new GeoDataLookAt( d->m_widget->lookAt() ) );
PlaybackFlyToItem* mapCenterItem = new PlaybackFlyToItem( &d->m_mapCenter );
PlaybackFlyToItem* before = mapCenterItem;
for ( int i=0; i<d->m_mainTrack->size(); ++i ) {
PlaybackFlyToItem* item = qobject_cast<PlaybackFlyToItem*>( d->m_mainTrack->at(i) );
if ( item ) {
item->setBefore( before );
before = item;
}
}
PlaybackFlyToItem* next = 0;
for ( int i=d->m_mainTrack->size()-1; i>=0; --i ) {
PlaybackFlyToItem* item = qobject_cast<PlaybackFlyToItem*>( d->m_mainTrack->at(i) );
if ( item ) {
item->setNext( next );
next = item;
}
}
}
void TourPlayback::play()
{
d->m_pause = false;
GeoDataCoordinates coords = d->m_widget->focusPoint();
d->m_mapCenter.setView( new GeoDataLookAt( d->m_widget->lookAt() ) );
mainTrack()->play();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->play();
}
}
void TourPlayback::pause()
{
d->m_pause = true;
mainTrack()->pause();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->pause();
}
}
void TourPlayback::stop()
{
d->m_pause = true;
d->m_mainTrack->stop();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->stop();
}
}
void TourPlayback::seek( double t )
{
Q_ASSERT( t >= 0.0 && t <= 1.0 );
double const offset = t * mainTrack()->duration();
mainTrack()->seek( offset );
foreach( ParallelTrack* track, d->m_parallelTracks ){
track->seek( offset );
}
}
} // namespace Marble
#include "TourPlayback.moc"
<commit_msg>Fix memory leak<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Sanjiban Bairagya <[email protected]>
//
#include "TourPlayback.h"
#include <QTimer>
#include <QList>
#include <QSlider>
#include <qurl.h>
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "GeoDataTour.h"
#include "GeoDataTourPrimitive.h"
#include "GeoDataFlyTo.h"
#include "GeoDataLookAt.h"
#include "GeoDataCamera.h"
#include "GeoDataWait.h"
#include "GeoDataTourControl.h"
#include "GeoDataSoundCue.h"
#include "GeoDataAnimatedUpdate.h"
#include "GeoDataTypes.h"
#include "PlaybackFlyToItem.h"
#include "PlaybackAnimatedUpdateItem.h"
#include "PlaybackWaitItem.h"
#include "PlaybackTourControlItem.h"
#include "PlaybackSoundCueItem.h"
#include "PlaybackAnimatedUpdateItem.h"
namespace Marble
{
class TourPlaybackPrivate
{
public:
TourPlaybackPrivate(TourPlayback *q);
const GeoDataTour *m_tour;
bool m_pause;
SerialTrack *m_mainTrack;
QList<ParallelTrack*> m_parallelTracks;
GeoDataCoordinates m_coordinates;
GeoDataFlyTo m_mapCenter;
MarbleWidget *m_widget;
QSlider *m_slider;
protected:
TourPlayback *q_ptr;
private:
Q_DECLARE_PUBLIC(TourPlayback)
};
TourPlaybackPrivate::TourPlaybackPrivate(TourPlayback* q) :
m_tour( &GeoDataTour::null ),
m_pause( false ),
m_mainTrack( new SerialTrack),
q_ptr( q )
{
// do nothing
}
TourPlayback::TourPlayback(QObject *parent) :
QObject(parent),
d(new TourPlaybackPrivate(this))
{
connect( mainTrack(), SIGNAL( centerOn( GeoDataCoordinates ) ), this, SIGNAL( centerOn( GeoDataCoordinates ) ) );
connect( mainTrack(), SIGNAL( progressChanged( double ) ), this, SIGNAL( progressChanged( double ) ) );
connect( mainTrack(), SIGNAL( finished() ), this, SLOT( finishedSlot() ) );
}
TourPlayback::~TourPlayback()
{
delete d;
}
void TourPlayback::finishedSlot()
{
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->stop();
track->setPaused( false );
}
}
SerialTrack* TourPlayback::mainTrack()
{
return d->m_mainTrack;
}
bool TourPlayback::isPlaying() const
{
return !d->m_pause;
}
void TourPlayback::setMarbleWidget(MarbleWidget* widget)
{
d->m_widget = widget;
}
void TourPlayback::setupProgressBar( QSlider *slider )
{
slider->setMaximum( d->m_mainTrack->duration() * 100 );
d->m_slider = slider;
}
void TourPlayback::setTour(const GeoDataTour *tour)
{
d->m_mainTrack->clear();
qDeleteAll( d->m_parallelTracks );
d->m_parallelTracks.clear();
if (tour) {
d->m_tour = tour;
}
else {
d->m_tour = &GeoDataTour::null;
}
double delay = 0;
for( int i = 0; i < d->m_tour->playlist()->size(); i++){
const GeoDataTourPrimitive* primitive = d->m_tour->playlist()->primitive( i );
if( primitive->nodeType() == GeoDataTypes::GeoDataFlyToType ){
const GeoDataFlyTo *flyTo = dynamic_cast<const GeoDataFlyTo*>(primitive);
d->m_mainTrack->append( new PlaybackFlyToItem( flyTo ) );
delay += flyTo->duration();
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataWaitType ){
const GeoDataWait *wait = dynamic_cast<const GeoDataWait*>(primitive);
d->m_mainTrack->append( new PlaybackWaitItem( wait ) );
delay += wait->duration();
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataTourControlType ){
const GeoDataTourControl *tourControl = dynamic_cast<const GeoDataTourControl*>(primitive);
d->m_mainTrack->append( new PlaybackTourControlItem( tourControl ) );
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataSoundCueType ){
const GeoDataSoundCue *soundCue = dynamic_cast<const GeoDataSoundCue*>(primitive);
PlaybackSoundCueItem *item = new PlaybackSoundCueItem( soundCue );
ParallelTrack *track = new ParallelTrack( item );
track->setDelayBeforeTrackStarts( delay );
d->m_parallelTracks.append( track );
}
else if( primitive->nodeType() == GeoDataTypes::GeoDataAnimatedUpdateType ){
const GeoDataAnimatedUpdate *animatedUpdate = dynamic_cast<const GeoDataAnimatedUpdate*>(primitive);
PlaybackAnimatedUpdateItem *item = new PlaybackAnimatedUpdateItem( animatedUpdate );
ParallelTrack *track = new ParallelTrack( item );
track->setDelayBeforeTrackStarts( delay );
d->m_parallelTracks.append( track );
}
}
Q_ASSERT( d->m_widget );
d->m_mapCenter.setView( new GeoDataLookAt( d->m_widget->lookAt() ) );
PlaybackFlyToItem* mapCenterItem = new PlaybackFlyToItem( &d->m_mapCenter );
PlaybackFlyToItem* before = mapCenterItem;
for ( int i=0; i<d->m_mainTrack->size(); ++i ) {
PlaybackFlyToItem* item = qobject_cast<PlaybackFlyToItem*>( d->m_mainTrack->at(i) );
if ( item ) {
item->setBefore( before );
before = item;
}
}
PlaybackFlyToItem* next = 0;
for ( int i=d->m_mainTrack->size()-1; i>=0; --i ) {
PlaybackFlyToItem* item = qobject_cast<PlaybackFlyToItem*>( d->m_mainTrack->at(i) );
if ( item ) {
item->setNext( next );
next = item;
}
}
}
void TourPlayback::play()
{
d->m_pause = false;
GeoDataCoordinates coords = d->m_widget->focusPoint();
d->m_mapCenter.setView( new GeoDataLookAt( d->m_widget->lookAt() ) );
mainTrack()->play();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->play();
}
}
void TourPlayback::pause()
{
d->m_pause = true;
mainTrack()->pause();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->pause();
}
}
void TourPlayback::stop()
{
d->m_pause = true;
d->m_mainTrack->stop();
foreach( ParallelTrack* track, d->m_parallelTracks) {
track->stop();
}
}
void TourPlayback::seek( double t )
{
Q_ASSERT( t >= 0.0 && t <= 1.0 );
double const offset = t * mainTrack()->duration();
mainTrack()->seek( offset );
foreach( ParallelTrack* track, d->m_parallelTracks ){
track->seek( offset );
}
}
} // namespace Marble
#include "TourPlayback.moc"
<|endoftext|>
|
<commit_before>/*
* Laser.cpp
*
* Created on: May 27, 2014
* Author: user
*/
#include "Laser.h"
double Laser::convertIndexToDegree(int index) const
{
return (index * LASER_RESOLUTION) - LASER_MESURING_AREA;
}
int Laser::convertDegreeToIndex(double degree) const
{
return (degree + LASER_MESURING_AREA) / LASER_RESOLUTION;
}
void Laser::getObstacles(double x, double y, double yaw, vector<Point>& obstacles) const
{
// Clear the data structure
obstacles.clear();
for (unsigned int index = 0; index < _laserProxy.GetCount(); index++)
{
double distance = _laserProxy[index];
// If the laser cannot seet an obstacle
if (distance >= LASER_MAXIMUM_RANGE)
{
// let's move to the next sample
continue;
}
double indexDegree = convertIndexToDegree(index);
double indexRadian = MathHelper::ConvertDegreeToRadian(indexDegree);
double obstacleRadian = indexRadian + yaw;
double obstacleX = distance * cos(obstacleRadian) + x;
double obstacleY = distance * sin(obstacleRadian) + y;
Point point(obstacleX, obstacleY);
obstacles.push_back(point);
}
}
void Laser::getObstacles(vector<Point>& obstacles) const
{
getObstacles(_robot.getX(), _robot.getY(), _robot.getYaw(), obstacles);
}
bool Laser::canRotate() const
{
double minRotationDistance = LASER_MIN_ROTATION_DISTANCE;
bool canRotate = true;
for (unsigned int index = 0; index < _laserProxy.GetCount(); index++)
{
double distance = _laserProxy[index];
if (distance < minRotationDistance)
{
canRotate = false;
break;
}
}
return canRotate;
}
bool Laser::canMoveForward() const
{
double minForwardDistance = LASER_MIN_FORWARD_DISTANCE;
bool canMoveForward = true;
for (unsigned int index = LASER_MIN_FORWARD_START_INDEX; index < LASER_MIN_FORWARD_END_INDEX; index++)
{
double distance = _laserProxy[index];
if (distance < minForwardDistance)
{
canMoveForward = false;
break;
}
}
return canMoveForward;
}
void Laser::updateMap(Map& map) const
{
}
<commit_msg>add funcion to calc rank for each side<commit_after>/*
* Laser.cpp
*
* Created on: May 27, 2014
* Author: user
*/
#include "Laser.h"
double Laser::convertIndexToDegree(int index) const
{
return (index * LASER_RESOLUTION) - LASER_MESURING_AREA;
}
int Laser::convertDegreeToIndex(double degree) const
{
return (degree + LASER_MESURING_AREA) / LASER_RESOLUTION;
}
void Laser::getObstacles(double x, double y, double yaw, vector<Point>& obstacles) const
{
// Clear the data structure
obstacles.clear();
for (unsigned int index = 0; index < _laserProxy.GetCount(); index++)
{
double distance = _laserProxy[index];
// If the laser cannot seet an obstacle
if (distance >= LASER_MAXIMUM_RANGE)
{
// let's move to the next sample
continue;
}
double indexDegree = convertIndexToDegree(index);
double indexRadian = MathHelper::ConvertDegreeToRadian(indexDegree);
double obstacleRadian = indexRadian + yaw;
double obstacleX = distance * cos(obstacleRadian) + x;
double obstacleY = distance * sin(obstacleRadian) + y;
Point point(obstacleX, obstacleY);
obstacles.push_back(point);
}
}
void Laser::getObstacles(vector<Point>& obstacles) const
{
getObstacles(_robot.getX(), _robot.getY(), _robot.getYaw(), obstacles);
}
bool Laser::canRotate() const
{
double minRotationDistance = LASER_MIN_ROTATION_DISTANCE;
bool canRotate = true;
for (unsigned int index = 0; index < _laserProxy.GetCount(); index++)
{
double distance = _laserProxy[index];
if (distance < minRotationDistance)
{
canRotate = false;
break;
}
}
return canRotate;
}
bool Laser::canMoveForward() const
{
double minForwardDistance = LASER_MIN_FORWARD_DISTANCE;
bool canMoveForward = true;
for (unsigned int index = LASER_MIN_FORWARD_START_INDEX; index < LASER_MIN_FORWARD_END_INDEX; index++)
{
double distance = _laserProxy[index];
if (distance < minForwardDistance)
{
canMoveForward = false;
break;
}
}
return canMoveForward;
}
double Laser::GetRightRank() const
{
double ret = 0;
for (unsigned int index = LASER_MIN_FORWARD_END_INDEX; index < LASER_ARRAY_SIZE; index += 10)
{
ret += _laserProxy[index];
}
return ret;
}
double Laser::GetLeftRank() const
{
double ret = 0;
for (unsigned int index = 0; index < LASER_MIN_FORWARD_START_INDEX; index += 10)
{
ret += _laserProxy[index];
}
return ret;
}
<|endoftext|>
|
<commit_before>/*
* ServerOptions.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SERVER_SERVER_OPTIONS_HPP
#define SERVER_SERVER_OPTIONS_HPP
#include <string>
#include <map>
#include <boost/utility.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramOptions.hpp>
#include <core/SafeConvert.hpp>
namespace core {
class ProgramStatus;
}
namespace server {
// singleton
class Options ;
Options& options();
class Options : boost::noncopyable
{
private:
Options() {}
friend Options& options();
// COPYING: boost::noncopyable
public:
virtual ~Options() {}
core::ProgramStatus read(int argc, char * const argv[]);
bool verifyInstallation() const
{
return verifyInstallation_;
}
std::string serverWorkingDir() const
{
return std::string(serverWorkingDir_.c_str());
}
bool serverOffline() const
{
return serverOffline_;
}
std::string serverUser() const
{
return std::string(serverUser_.c_str());
}
bool serverDaemonize() const { return serverDaemonize_; }
bool serverAppArmorEnabled() const { return serverAppArmorEnabled_; }
// www
std::string wwwAddress() const
{
return std::string(wwwAddress_.c_str()) ;
}
std::string wwwPort(bool secure = false) const
{
if (!wwwPort_.empty())
{
return std::string(wwwPort_.c_str());
}
else
{
if (secure)
return std::string("443");
else
return std::string("8787");
}
}
std::string wwwLocalPath() const
{
return std::string(wwwLocalPath_.c_str());
}
int wwwThreadPoolSize() const
{
return wwwThreadPoolSize_;
}
// auth
bool authValidateUsers()
{
return authValidateUsers_;
}
std::string authRequiredUserGroup()
{
return std::string(authRequiredUserGroup_.c_str());
}
std::string authPamHelperPath() const
{
return std::string(authPamHelperPath_.c_str());
}
// rsession
std::string rsessionWhichR() const
{
return std::string(rsessionWhichR_.c_str());
}
std::string rsessionPath() const
{
return std::string(rsessionPath_.c_str());
}
std::string rldpathPath() const
{
return std::string(rldpathPath_.c_str());
}
std::string rsessionLdLibraryPath() const
{
return std::string(rsessionLdLibraryPath_.c_str());
}
std::string rsessionConfigFile() const
{
return std::string(rsessionConfigFile_.c_str());
}
int rsessionMemoryLimitMb() const
{
return rsessionMemoryLimitMb_;
}
int rsessionStackLimitMb() const
{
return rsessionStackLimitMb_;
}
int rsessionUserProcessLimit() const
{
return rsessionUserProcessLimit_;
}
std::string getOverlayOption(const std::string& name)
{
return overlayOptions_[name];
}
private:
void resolvePath(std::string* pPath) const;
void addOverlayOptions(boost::program_options::options_description* pServer,
boost::program_options::options_description* pWWW,
boost::program_options::options_description* pRSession,
boost::program_options::options_description* pAuth);
bool validateOverlayOptions(std::string* pErrMsg);
void resolveOverlayOptions();
void setOverlayOption(const std::string& name, const std::string& value)
{
overlayOptions_[name] = value;
}
void setOverlayOption(const std::string& name, bool value)
{
setOverlayOption(name, value ? "1" : "0");
}
void setOverlayOption(const std::string& name, int value)
{
setOverlayOption(name, core::safe_convert::numberToString(value));
}
private:
core::FilePath installPath_;
bool verifyInstallation_;
std::string serverWorkingDir_;
std::string serverUser_;
bool serverDaemonize_;
bool serverAppArmorEnabled_;
bool serverOffline_;
std::string wwwAddress_ ;
std::string wwwPort_ ;
std::string wwwLocalPath_ ;
int wwwThreadPoolSize_;
bool authValidateUsers_;
std::string authRequiredUserGroup_;
std::string authPamHelperPath_;
std::string rsessionWhichR_;
std::string rsessionPath_;
std::string rldpathPath_;
std::string rsessionConfigFile_;
std::string rsessionLdLibraryPath_;
int rsessionMemoryLimitMb_;
int rsessionStackLimitMb_;
int rsessionUserProcessLimit_;
std::map<std::string,std::string> overlayOptions_;
};
} // namespace server
#endif // SERVER_SERVER_OPTIONS_HPP
<commit_msg>correct cast to string for bool overlay options<commit_after>/*
* ServerOptions.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SERVER_SERVER_OPTIONS_HPP
#define SERVER_SERVER_OPTIONS_HPP
#include <string>
#include <map>
#include <boost/utility.hpp>
#include <core/FilePath.hpp>
#include <core/ProgramOptions.hpp>
#include <core/SafeConvert.hpp>
namespace core {
class ProgramStatus;
}
namespace server {
// singleton
class Options ;
Options& options();
class Options : boost::noncopyable
{
private:
Options() {}
friend Options& options();
// COPYING: boost::noncopyable
public:
virtual ~Options() {}
core::ProgramStatus read(int argc, char * const argv[]);
bool verifyInstallation() const
{
return verifyInstallation_;
}
std::string serverWorkingDir() const
{
return std::string(serverWorkingDir_.c_str());
}
bool serverOffline() const
{
return serverOffline_;
}
std::string serverUser() const
{
return std::string(serverUser_.c_str());
}
bool serverDaemonize() const { return serverDaemonize_; }
bool serverAppArmorEnabled() const { return serverAppArmorEnabled_; }
// www
std::string wwwAddress() const
{
return std::string(wwwAddress_.c_str()) ;
}
std::string wwwPort(bool secure = false) const
{
if (!wwwPort_.empty())
{
return std::string(wwwPort_.c_str());
}
else
{
if (secure)
return std::string("443");
else
return std::string("8787");
}
}
std::string wwwLocalPath() const
{
return std::string(wwwLocalPath_.c_str());
}
int wwwThreadPoolSize() const
{
return wwwThreadPoolSize_;
}
// auth
bool authValidateUsers()
{
return authValidateUsers_;
}
std::string authRequiredUserGroup()
{
return std::string(authRequiredUserGroup_.c_str());
}
std::string authPamHelperPath() const
{
return std::string(authPamHelperPath_.c_str());
}
// rsession
std::string rsessionWhichR() const
{
return std::string(rsessionWhichR_.c_str());
}
std::string rsessionPath() const
{
return std::string(rsessionPath_.c_str());
}
std::string rldpathPath() const
{
return std::string(rldpathPath_.c_str());
}
std::string rsessionLdLibraryPath() const
{
return std::string(rsessionLdLibraryPath_.c_str());
}
std::string rsessionConfigFile() const
{
return std::string(rsessionConfigFile_.c_str());
}
int rsessionMemoryLimitMb() const
{
return rsessionMemoryLimitMb_;
}
int rsessionStackLimitMb() const
{
return rsessionStackLimitMb_;
}
int rsessionUserProcessLimit() const
{
return rsessionUserProcessLimit_;
}
std::string getOverlayOption(const std::string& name)
{
return overlayOptions_[name];
}
private:
void resolvePath(std::string* pPath) const;
void addOverlayOptions(boost::program_options::options_description* pServer,
boost::program_options::options_description* pWWW,
boost::program_options::options_description* pRSession,
boost::program_options::options_description* pAuth);
bool validateOverlayOptions(std::string* pErrMsg);
void resolveOverlayOptions();
void setOverlayOption(const std::string& name, const std::string& value)
{
overlayOptions_[name] = value;
}
void setOverlayOption(const std::string& name, bool value)
{
setOverlayOption(name, value ? std::string("1") : std::string("0"));
}
void setOverlayOption(const std::string& name, int value)
{
setOverlayOption(name, core::safe_convert::numberToString(value));
}
private:
core::FilePath installPath_;
bool verifyInstallation_;
std::string serverWorkingDir_;
std::string serverUser_;
bool serverDaemonize_;
bool serverAppArmorEnabled_;
bool serverOffline_;
std::string wwwAddress_ ;
std::string wwwPort_ ;
std::string wwwLocalPath_ ;
int wwwThreadPoolSize_;
bool authValidateUsers_;
std::string authRequiredUserGroup_;
std::string authPamHelperPath_;
std::string rsessionWhichR_;
std::string rsessionPath_;
std::string rldpathPath_;
std::string rsessionConfigFile_;
std::string rsessionLdLibraryPath_;
int rsessionMemoryLimitMb_;
int rsessionStackLimitMb_;
int rsessionUserProcessLimit_;
std::map<std::string,std::string> overlayOptions_;
};
} // namespace server
#endif // SERVER_SERVER_OPTIONS_HPP
<|endoftext|>
|
<commit_before>#ifndef _THREADPOOL_H
#define _THREADPOOL_H
#include <assert.h>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <memory>
#include <functional>
#include <condition_variable>
#include <atomic>
#include <type_traits>
static const unsigned int MaxTaskQueueSize = 100000;
static const unsigned int MaxNumOfThread = 30;
class ThreadPool
{
public:
using WorkerThreadPtr = std::shared_ptr<std::thread>;
using Task = std::function<void()>;
explicit ThreadPool() : m_isStopThreadPool(false) {}
~ThreadPool()
{
stop();
}
void initThreadNum(unsigned int num)
{
assert(num > 0 && num <= MaxNumOfThread);
for (unsigned int i = 0; i < num; ++i)
{
WorkerThreadPtr t = std::make_shared<std::thread>(std::bind(&ThreadPool::runTask, this));
m_threadVec.emplace_back(t);
}
}
template<typename Function, typename... Args>
void addTask(const Function& func, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, args...]{ return func(args...); };
addTaskImpl(task);
}
}
template<typename Function, typename... Args>
typename std::enable_if<std::is_class<Function>::value>::type addTask(Function& func, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, args...]{ return func(args...); };
addTaskImpl(task);
}
}
template<typename Function, typename Self, typename... Args>
void addTask(const Function& func, Self* self, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, &self, args...]{ return (*self.*func)(args...); };
addTaskImpl(task);
}
}
void stop()
{
std::call_once(m_callFlag, [this]{ terminateAll(); });
}
private:
void addTaskImpl(const Task& task)
{
{
std::unique_lock<std::mutex> locker(m_taskQueueMutex);
while (m_taskQueue.size() == MaxTaskQueueSize && !m_isStopThreadPool)
{
m_taskPut.wait(locker);
}
m_taskQueue.emplace(std::move(task));
}
m_taskGet.notify_one();
}
void terminateAll()
{
m_isStopThreadPool = true;
m_taskGet.notify_all();
for (auto& iter : m_threadVec)
{
if (iter->joinable())
{
iter->join();
}
}
m_threadVec.clear();
cleanTaskQueue();
}
void runTask()
{
while (true)
{
Task task = nullptr;
{
std::unique_lock<std::mutex> locker(m_taskQueueMutex);
while (m_taskQueue.empty() && !m_isStopThreadPool)
{
m_taskGet.wait(locker);
}
if (m_isStopThreadPool)
{
break;
}
if (!m_taskQueue.empty())
{
task = std::move(m_taskQueue.front());
m_taskQueue.pop();
}
}
if (task != nullptr)
{
task();
m_taskPut.notify_one();
}
}
}
void cleanTaskQueue()
{
std::lock_guard<std::mutex> locker(m_taskQueueMutex);
while (!m_taskQueue.empty())
{
m_taskQueue.pop();
}
}
private:
std::vector<WorkerThreadPtr> m_threadVec;
std::condition_variable m_taskPut;
std::condition_variable m_taskGet;
std::mutex m_taskQueueMutex;
std::queue<Task> m_taskQueue;
std::atomic<bool> m_isStopThreadPool;
std::once_flag m_callFlag;
};
#endif
<commit_msg>Update threadpool<commit_after>#ifndef _THREADPOOL_H
#define _THREADPOOL_H
#include <assert.h>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <memory>
#include <functional>
#include <condition_variable>
#include <atomic>
#include <type_traits>
static const unsigned int MaxTaskQueueSize = 100000;
static const unsigned int MaxNumOfThread = 30;
class ThreadPool
{
public:
using WorkerThreadPtr = std::shared_ptr<std::thread>;
using Task = std::function<void()>;
explicit ThreadPool() : m_isStopThreadPool(false) {}
~ThreadPool()
{
stop();
}
void initThreadNum(unsigned int num)
{
assert(num > 0 && num <= MaxNumOfThread);
for (unsigned int i = 0; i < num; ++i)
{
WorkerThreadPtr t = std::make_shared<std::thread>(std::bind(&ThreadPool::runTask, this));
m_threadVec.emplace_back(t);
}
}
template<typename Function, typename... Args>
void addTask(const Function& func, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, args...]{ return func(args...); };
addTaskImpl(task);
}
}
template<typename Function, typename... Args>
void addTask(Function& func, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, args...]{ return func(args...); };
addTaskImpl(task);
}
}
template<typename Function, typename Self, typename... Args>
void addTask(const Function& func, Self* self, Args... args)
{
if (!m_isStopThreadPool)
{
Task task = [&func, &self, args...]{ return (*self.*func)(args...); };
addTaskImpl(task);
}
}
void stop()
{
std::call_once(m_callFlag, [this]{ terminateAll(); });
}
private:
void addTaskImpl(const Task& task)
{
{
std::unique_lock<std::mutex> locker(m_taskQueueMutex);
while (m_taskQueue.size() == MaxTaskQueueSize && !m_isStopThreadPool)
{
m_taskPut.wait(locker);
}
m_taskQueue.emplace(std::move(task));
}
m_taskGet.notify_one();
}
void terminateAll()
{
m_isStopThreadPool = true;
m_taskGet.notify_all();
for (auto& iter : m_threadVec)
{
if (iter->joinable())
{
iter->join();
}
}
m_threadVec.clear();
cleanTaskQueue();
}
void runTask()
{
while (true)
{
Task task = nullptr;
{
std::unique_lock<std::mutex> locker(m_taskQueueMutex);
while (m_taskQueue.empty() && !m_isStopThreadPool)
{
m_taskGet.wait(locker);
}
if (m_isStopThreadPool)
{
break;
}
if (!m_taskQueue.empty())
{
task = std::move(m_taskQueue.front());
m_taskQueue.pop();
}
}
if (task != nullptr)
{
task();
m_taskPut.notify_one();
}
}
}
void cleanTaskQueue()
{
std::lock_guard<std::mutex> locker(m_taskQueueMutex);
while (!m_taskQueue.empty())
{
m_taskQueue.pop();
}
}
private:
std::vector<WorkerThreadPtr> m_threadVec;
std::condition_variable m_taskPut;
std::condition_variable m_taskGet;
std::mutex m_taskQueueMutex;
std::queue<Task> m_taskQueue;
std::atomic<bool> m_isStopThreadPool;
std::once_flag m_callFlag;
};
#endif
<|endoftext|>
|
<commit_before>#include "magellan/core/TestSuite.h"
#include "magellan/core/TestResult.h"
#include <l0-infra/std/Algorithm.h>
MAGELLAN_NS_BEGIN
TestSuite::TestSuite(const std::string& name)
: name(name)
{}
TestSuite::~TestSuite()
{
stdext::each(tests, [](Test* t){ delete t; });
}
void TestSuite::addTest(Test* test)
{
if (test != 0)
{
tests.push_back(test);
}
}
const std::string& TestSuite::getName() const
{
return name;
}
int TestSuite::countTestCases() const
{
return stdext::reduce(tests, 0, [](int& num, Test* test) {
num += test->countTestCases();
});
}
int TestSuite::countChildTests() const
{
return (int)tests.size();
}
void TestSuite::runBare(TestResult &result)
{
stdext::each(tests, [&](Test* test){ test->run(result); });
}
void TestSuite::run(TestResult& result)
{
result.run(*this);
}
bool TestSuite::hasChild() const
{
return countChildTests() != 0;
}
MAGELLAN_NS_END
<commit_msg>remove unused method for TestSuite<commit_after>#include "magellan/core/TestSuite.h"
#include "magellan/core/TestResult.h"
#include <l0-infra/std/Algorithm.h>
MAGELLAN_NS_BEGIN
TestSuite::TestSuite(const std::string& name)
: name(name)
{}
TestSuite::~TestSuite()
{
stdext::each(tests, [](Test* t){ delete t; });
}
void TestSuite::addTest(Test* test)
{
if (test != 0)
{
tests.push_back(test);
}
}
const std::string& TestSuite::getName() const
{
return name;
}
int TestSuite::countTestCases() const
{
return stdext::reduce(tests, 0, [](int& num, Test* test) {
num += test->countTestCases();
});
}
int TestSuite::countChildTests() const
{
return (int)tests.size();
}
void TestSuite::runBare(TestResult &result)
{
stdext::each(tests, [&](Test* test){ test->run(result); });
}
void TestSuite::run(TestResult& result)
{
result.run(*this);
}
MAGELLAN_NS_END
<|endoftext|>
|
<commit_before>/************************************************************
cvsurfpoint.cpp -
$Author: ser1zw $
Copyright (C) 2011 ser1zw
************************************************************/
#include "cvsurfpoint.h"
/*
* Document-class: OpenCV::CvSURFPoint
*
* C structure is here.
* typedef struct CvSURFPoint {
* CvPoint2D32f pt; // position of the feature within the image
* int laplacian; // -1, 0 or +1. sign of the laplacian at the point.
* // can be used to speedup feature comparison
* // (normally features with laplacians of different
* // signs can not match)
* int size; // size of the feature
* float dir; // orientation of the feature: 0..360 degrees
* float hessian; // value of the hessian (can be used to
* // approximately estimate the feature strengths)
* } CvSURFPoint;
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVSURFPOINT
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
VALUE
rb_allocate(VALUE klass)
{
CvSURFPoint *ptr;
return Data_Make_Struct(klass, CvSURFPoint, 0, -1, ptr);
}
/*
* Create a CvSURFPoint
*
* @overload new(pt, laplacian, size, dir, hessian)
* @param pt [CvPoint2D32f] Position of the feature within the image
* @param laplacian [Integer] -1, 0 or +1. sign of the laplacian at the point.
* Can be used to speedup feature comparison
* (normally features with laplacians of different signs can not match)
* @param size [Integer] Size of the feature
* @param dir [Number] Orientation of the feature: 0..360 degrees
* @param hessian [Number] Value of the hessian (can be used to
* approximately estimate the feature strengths)
* @return [CvSURFPoint] self
*/
VALUE
rb_initialize(VALUE self, VALUE pt, VALUE laplacian, VALUE size, VALUE dir, VALUE hessian)
{
CvSURFPoint *self_ptr = CVSURFPOINT(self);
self_ptr->pt = VALUE_TO_CVPOINT2D32F(pt);
self_ptr->laplacian = NUM2INT(laplacian);
self_ptr->size = NUM2INT(size);
self_ptr->dir = (float)NUM2DBL(dir);
self_ptr->hessian = (float)NUM2DBL(hessian);
return self;
}
/*
* Return position of the feature as CvPoint2D32f.
*
* @overload pt
* @return [CvPoint2D32f] Position of the feature.
*/
VALUE
rb_get_pt(VALUE self)
{
return REFER_OBJECT(cCvPoint2D32f::rb_class(), &CVSURFPOINT(self)->pt, self);
}
/*
* Set position of the feature.
*
* @overload pt=(value)
* @param value [CvPoint2D32f] Valuet to set.
*/
VALUE
rb_set_pt(VALUE self, VALUE value)
{
CVSURFPOINT(self)->pt = VALUE_TO_CVPOINT2D32F(value);
return self;
}
/*
* Return sign of the laplacian at the point (-1, 0 or +1)
*
* @overload laplacian
* @return [Integer] Sign of the laplacian at the point.
*/
VALUE
rb_get_laplacian(VALUE self)
{
return INT2NUM(CVSURFPOINT(self)->laplacian);
}
/*
* Set sign of the laplacian at the point
*
* @overload laplacian=(value)
* @param value [Integer] Value to set.
*/
VALUE
rb_set_laplacian(VALUE self, VALUE value)
{
int val = NUM2INT(value);
CVSURFPOINT(self)->laplacian = (val > 0) ? 1 : (val < 0) ? -1 : 0;
return self;
}
/*
* Returns size of feature.
*
* @overload size
* @return [Integer] Size of feature.
*/
VALUE
rb_get_size(VALUE self)
{
return INT2NUM(CVSURFPOINT(self)->size);
}
/*
* Return size of feature
*
* @overload size=(value)
* @param [Integer] Value to set.
*/
VALUE
rb_set_size(VALUE self, VALUE value)
{
CVSURFPOINT(self)->size = NUM2INT(value);
return self;
}
/*
* Return orientation of the feature: 0..360 degrees
*
* @overload dir
* @return [Number] Orientation of the feature.
*/
VALUE
rb_get_dir(VALUE self)
{
return DBL2NUM((double)(CVSURFPOINT(self)->dir));
}
/*
* Set orientation of the feature: 0..360 degrees.
*
* @overload dir=(value)
* @param [Number] Value to set.
*/
VALUE
rb_set_dir(VALUE self, VALUE value)
{
CVSURFPOINT(self)->dir = (float)NUM2DBL(value);
return self;
}
/*
* Return value of the hessian
*
* @overload hessian
* @return [Number] Hessian
*/
VALUE
rb_get_hessian(VALUE self)
{
return DBL2NUM((double)(CVSURFPOINT(self)->hessian));
}
/*
* Set value of the hessian
*
* @overload hessian=(value)
* @param [Number] Value to set.
*/
VALUE
rb_set_hessian(VALUE self, VALUE value)
{
CVSURFPOINT(self)->hessian = (float)NUM2DBL(value);
return self;
}
/*
* call-seq:
*
*
* From: https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/find_obj.cpp?rev=2065
*/
VALUE
rb_flann(VALUE klass, VALUE objectDesc, VALUE imageDesc)
{
const cv::Mat m_object(CVMAT(objectDesc));
const cv::Mat m_image(CVMAT(imageDesc));
cv::Mat m_indices(m_object.rows, 2, CV_32S);
cv::Mat m_dists(m_object.rows, 2, CV_32F);
cv::flann::Index flann_index(m_image, cv::flann::KDTreeIndexParams(4)); // using 4 randomized kdtrees
flann_index.knnSearch(m_object, m_indices, m_dists, 2, cv::flann::SearchParams(64)); // maximum number of leafs checked
VALUE ptpairs = rb_ary_new();
int* indices_ptr = m_indices.ptr<int>(0);
float* dists_ptr = m_dists.ptr<float>(0);
for (int i = 0; i < m_indices.rows; ++i) {
if (dists_ptr[2 * i] < 0.6 * dists_ptr[2 * i + 1]) {
rb_ary_push(ptpairs, rb_int_new(i));
rb_ary_push(ptpairs, rb_int_new(indices_ptr[2 * i]));
}
}
return ptpairs;
}
VALUE
new_object()
{
return rb_allocate(rb_klass);
}
VALUE
new_object(CvSURFPoint* cvsurfpoint)
{
VALUE object = rb_allocate(rb_klass);
CvSURFPoint *ptr = CVSURFPOINT(object);
ptr = cvsurfpoint;
return object;
}
void
init_ruby_class()
{
#if 0
// For documentation using YARD
VALUE opencv = rb_define_module("OpenCV");
#endif
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
*
* note: this comment is used by rdoc.
*/
VALUE opencv = rb_module_opencv();
rb_klass = rb_define_class_under(opencv, "CvSURFPoint", rb_cObject);
rb_define_alloc_func(rb_klass, rb_allocate);
rb_define_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), 5);
rb_define_method(rb_klass, "pt", RUBY_METHOD_FUNC(rb_get_pt), 0);
rb_define_method(rb_klass, "pt=", RUBY_METHOD_FUNC(rb_set_pt), 1);
rb_define_method(rb_klass, "laplacian", RUBY_METHOD_FUNC(rb_get_laplacian), 0);
rb_define_method(rb_klass, "laplacian=", RUBY_METHOD_FUNC(rb_set_laplacian), 1);
rb_define_method(rb_klass, "size", RUBY_METHOD_FUNC(rb_get_size), 0);
rb_define_method(rb_klass, "size=", RUBY_METHOD_FUNC(rb_set_size), 1);
rb_define_method(rb_klass, "dir", RUBY_METHOD_FUNC(rb_get_dir), 0);
rb_define_method(rb_klass, "dir=", RUBY_METHOD_FUNC(rb_set_dir), 1);
rb_define_method(rb_klass, "hessian", RUBY_METHOD_FUNC(rb_get_hessian), 0);
rb_define_method(rb_klass, "hessian=", RUBY_METHOD_FUNC(rb_set_hessian), 1);
}
__NAMESPACE_END_CVSURFPOINT
__NAMESPACE_END_OPENCV
<commit_msg>Add flann ruby method definition<commit_after>/************************************************************
cvsurfpoint.cpp -
$Author: ser1zw $
Copyright (C) 2011 ser1zw
************************************************************/
#include "cvsurfpoint.h"
/*
* Document-class: OpenCV::CvSURFPoint
*
* C structure is here.
* typedef struct CvSURFPoint {
* CvPoint2D32f pt; // position of the feature within the image
* int laplacian; // -1, 0 or +1. sign of the laplacian at the point.
* // can be used to speedup feature comparison
* // (normally features with laplacians of different
* // signs can not match)
* int size; // size of the feature
* float dir; // orientation of the feature: 0..360 degrees
* float hessian; // value of the hessian (can be used to
* // approximately estimate the feature strengths)
* } CvSURFPoint;
*/
__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVSURFPOINT
VALUE rb_klass;
VALUE
rb_class()
{
return rb_klass;
}
VALUE
rb_allocate(VALUE klass)
{
CvSURFPoint *ptr;
return Data_Make_Struct(klass, CvSURFPoint, 0, -1, ptr);
}
/*
* Create a CvSURFPoint
*
* @overload new(pt, laplacian, size, dir, hessian)
* @param pt [CvPoint2D32f] Position of the feature within the image
* @param laplacian [Integer] -1, 0 or +1. sign of the laplacian at the point.
* Can be used to speedup feature comparison
* (normally features with laplacians of different signs can not match)
* @param size [Integer] Size of the feature
* @param dir [Number] Orientation of the feature: 0..360 degrees
* @param hessian [Number] Value of the hessian (can be used to
* approximately estimate the feature strengths)
* @return [CvSURFPoint] self
*/
VALUE
rb_initialize(VALUE self, VALUE pt, VALUE laplacian, VALUE size, VALUE dir, VALUE hessian)
{
CvSURFPoint *self_ptr = CVSURFPOINT(self);
self_ptr->pt = VALUE_TO_CVPOINT2D32F(pt);
self_ptr->laplacian = NUM2INT(laplacian);
self_ptr->size = NUM2INT(size);
self_ptr->dir = (float)NUM2DBL(dir);
self_ptr->hessian = (float)NUM2DBL(hessian);
return self;
}
/*
* Return position of the feature as CvPoint2D32f.
*
* @overload pt
* @return [CvPoint2D32f] Position of the feature.
*/
VALUE
rb_get_pt(VALUE self)
{
return REFER_OBJECT(cCvPoint2D32f::rb_class(), &CVSURFPOINT(self)->pt, self);
}
/*
* Set position of the feature.
*
* @overload pt=(value)
* @param value [CvPoint2D32f] Valuet to set.
*/
VALUE
rb_set_pt(VALUE self, VALUE value)
{
CVSURFPOINT(self)->pt = VALUE_TO_CVPOINT2D32F(value);
return self;
}
/*
* Return sign of the laplacian at the point (-1, 0 or +1)
*
* @overload laplacian
* @return [Integer] Sign of the laplacian at the point.
*/
VALUE
rb_get_laplacian(VALUE self)
{
return INT2NUM(CVSURFPOINT(self)->laplacian);
}
/*
* Set sign of the laplacian at the point
*
* @overload laplacian=(value)
* @param value [Integer] Value to set.
*/
VALUE
rb_set_laplacian(VALUE self, VALUE value)
{
int val = NUM2INT(value);
CVSURFPOINT(self)->laplacian = (val > 0) ? 1 : (val < 0) ? -1 : 0;
return self;
}
/*
* Returns size of feature.
*
* @overload size
* @return [Integer] Size of feature.
*/
VALUE
rb_get_size(VALUE self)
{
return INT2NUM(CVSURFPOINT(self)->size);
}
/*
* Return size of feature
*
* @overload size=(value)
* @param [Integer] Value to set.
*/
VALUE
rb_set_size(VALUE self, VALUE value)
{
CVSURFPOINT(self)->size = NUM2INT(value);
return self;
}
/*
* Return orientation of the feature: 0..360 degrees
*
* @overload dir
* @return [Number] Orientation of the feature.
*/
VALUE
rb_get_dir(VALUE self)
{
return DBL2NUM((double)(CVSURFPOINT(self)->dir));
}
/*
* Set orientation of the feature: 0..360 degrees.
*
* @overload dir=(value)
* @param [Number] Value to set.
*/
VALUE
rb_set_dir(VALUE self, VALUE value)
{
CVSURFPOINT(self)->dir = (float)NUM2DBL(value);
return self;
}
/*
* Return value of the hessian
*
* @overload hessian
* @return [Number] Hessian
*/
VALUE
rb_get_hessian(VALUE self)
{
return DBL2NUM((double)(CVSURFPOINT(self)->hessian));
}
/*
* Set value of the hessian
*
* @overload hessian=(value)
* @param [Number] Value to set.
*/
VALUE
rb_set_hessian(VALUE self, VALUE value)
{
CVSURFPOINT(self)->hessian = (float)NUM2DBL(value);
return self;
}
/*
* call-seq:
*
*
* From: https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/find_obj.cpp?rev=2065
*/
VALUE
rb_flann(VALUE klass, VALUE objectDesc, VALUE imageDesc)
{
const cv::Mat m_object(CVMAT(objectDesc));
const cv::Mat m_image(CVMAT(imageDesc));
cv::Mat m_indices(m_object.rows, 2, CV_32S);
cv::Mat m_dists(m_object.rows, 2, CV_32F);
cv::flann::Index flann_index(m_image, cv::flann::KDTreeIndexParams(4)); // using 4 randomized kdtrees
flann_index.knnSearch(m_object, m_indices, m_dists, 2, cv::flann::SearchParams(64)); // maximum number of leafs checked
VALUE ptpairs = rb_ary_new();
int* indices_ptr = m_indices.ptr<int>(0);
float* dists_ptr = m_dists.ptr<float>(0);
for (int i = 0; i < m_indices.rows; ++i) {
if (dists_ptr[2 * i] < 0.6 * dists_ptr[2 * i + 1]) {
rb_ary_push(ptpairs, rb_int_new(i));
rb_ary_push(ptpairs, rb_int_new(indices_ptr[2 * i]));
}
}
return ptpairs;
}
VALUE
new_object()
{
return rb_allocate(rb_klass);
}
VALUE
new_object(CvSURFPoint* cvsurfpoint)
{
VALUE object = rb_allocate(rb_klass);
CvSURFPoint *ptr = CVSURFPOINT(object);
ptr = cvsurfpoint;
return object;
}
void
init_ruby_class()
{
#if 0
// For documentation using YARD
VALUE opencv = rb_define_module("OpenCV");
#endif
if (rb_klass)
return;
/*
* opencv = rb_define_module("OpenCV");
*
* note: this comment is used by rdoc.
*/
VALUE opencv = rb_module_opencv();
rb_klass = rb_define_class_under(opencv, "CvSURFPoint", rb_cObject);
rb_define_alloc_func(rb_klass, rb_allocate);
rb_define_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), 5);
rb_define_method(rb_klass, "pt", RUBY_METHOD_FUNC(rb_get_pt), 0);
rb_define_method(rb_klass, "pt=", RUBY_METHOD_FUNC(rb_set_pt), 1);
rb_define_method(rb_klass, "laplacian", RUBY_METHOD_FUNC(rb_get_laplacian), 0);
rb_define_method(rb_klass, "laplacian=", RUBY_METHOD_FUNC(rb_set_laplacian), 1);
rb_define_method(rb_klass, "size", RUBY_METHOD_FUNC(rb_get_size), 0);
rb_define_method(rb_klass, "size=", RUBY_METHOD_FUNC(rb_set_size), 1);
rb_define_method(rb_klass, "dir", RUBY_METHOD_FUNC(rb_get_dir), 0);
rb_define_method(rb_klass, "dir=", RUBY_METHOD_FUNC(rb_set_dir), 1);
rb_define_method(rb_klass, "hessian", RUBY_METHOD_FUNC(rb_get_hessian), 0);
rb_define_method(rb_klass, "hessian=", RUBY_METHOD_FUNC(rb_set_hessian), 1);
rb_define_method(rb_klass, "flann", RUBY_METHOD_FUNC(rb_flann), 2);
}
__NAMESPACE_END_CVSURFPOINT
__NAMESPACE_END_OPENCV
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
ViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);
}
ViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);
}
ViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);
}
DropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)
{
m_ulDropList = ulDropList;
m_lpuidDropList = lpuidDropList;
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
m_lpnaeDropList = lpnaeDropList;
m_bGUID = bGUID;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
SIZE sizeDrop = { 0 };
CString szDropString;
m_DropDown.GetLBText(iDropString, szDropString);
::GetTextExtentPoint32(hdc, szDropString, szDropString.GetLength(), &sizeDrop);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, dropHeight),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
DoInit(iControl, pParent, hdc);
if (m_lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = loadstring(m_lpuidDropList[iDropNum]);
InsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);
}
}
else if (m_lpnaeDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);
InsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);
}
}
// If this is a GUID list, load up our list of guids
if (m_bGUID)
{
for (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)
{
InsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue) const
{
COMBOBOXEXITEMW item = { 0 };
item.mask = CBEIF_TEXT | CBEIF_LPARAM;
item.iItem = iRow;
item.pszText = LPWSTR(szText.c_str());
item.cchTextMax = int(szText.length());
item.lParam = ulValue;
(void) ::SendMessage(m_DropDown.m_hWnd, CBEM_INSERTITEMW, WPARAM(0), LPARAM(&item));
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
CString szText;
m_DropDown.GetWindowText(szText);
return LPCTSTRToWstring(szText);
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const
{
if (!lpSelectedGUID) return NULL;
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
memcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));
return true;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
memcpy(lpSelectedGUID, lpGUID, sizeof(GUID));
delete[] lpGUID;
return true;
}
void DropDownPane::SetDropDownSelection(_In_ wstring szText)
{
auto hRes = S_OK;
auto text = wstringToCString(szText);
auto iSelect = m_DropDown.SelectString(0, text);
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<commit_msg>Fix crash in GetSelectedGUID<commit_after>#include "stdafx.h"
#include "DropDownPane.h"
#include "String.h"
#include "InterpretProp2.h"
#include <UIFunctions.h>
static wstring CLASS = L"DropDownPane";
ViewPane* CreateDropDownPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, lpuidDropList, nullptr, false);
}
ViewPane* CreateDropDownArrayPane(UINT uidLabel, ULONG ulDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, ulDropList, nullptr, lpnaeDropList, false);
}
ViewPane* CreateDropDownGuidPane(UINT uidLabel, bool bReadOnly)
{
return new DropDownPane(uidLabel, bReadOnly, 0, nullptr, nullptr, true);
}
DropDownPane::DropDownPane(UINT uidLabel, bool bReadOnly, ULONG ulDropList, _In_opt_count_(ulDropList) UINT* lpuidDropList, _In_opt_count_(ulDropList) LPNAME_ARRAY_ENTRY lpnaeDropList, bool bGUID) :ViewPane(uidLabel, bReadOnly)
{
m_ulDropList = ulDropList;
m_lpuidDropList = lpuidDropList;
m_iDropSelection = CB_ERR;
m_iDropSelectionValue = 0;
m_lpnaeDropList = lpnaeDropList;
m_bGUID = bGUID;
}
bool DropDownPane::IsType(__ViewTypes vType)
{
return CTRL_DROPDOWNPANE == vType;
}
ULONG DropDownPane::GetFlags()
{
ULONG ulFlags = vpNone;
if (m_bReadOnly) ulFlags |= vpReadonly;
return ulFlags;
}
int DropDownPane::GetMinWidth(_In_ HDC hdc)
{
auto cxDropDown = 0;
for (auto iDropString = 0; iDropString < m_DropDown.GetCount(); iDropString++)
{
SIZE sizeDrop = { 0 };
CString szDropString;
m_DropDown.GetLBText(iDropString, szDropString);
::GetTextExtentPoint32(hdc, szDropString, szDropString.GetLength(), &sizeDrop);
cxDropDown = max(cxDropDown, sizeDrop.cx);
}
// Add scroll bar and margins for our frame
cxDropDown += ::GetSystemMetrics(SM_CXVSCROLL) + 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
return max(ViewPane::GetMinWidth(hdc), cxDropDown);
}
int DropDownPane::GetFixedHeight()
{
auto iHeight = 0;
if (0 != m_iControl) iHeight += m_iSmallHeightMargin; // Top margin
if (m_bUseLabelControl)
{
iHeight += m_iLabelHeight;
}
iHeight += m_iEditHeight; // Height of the dropdown
// No bottom margin on the DropDown as it's usually tied to the following control
return iHeight;
}
int DropDownPane::GetLines()
{
return 0;
}
void DropDownPane::SetWindowPos(int x, int y, int width, int /*height*/)
{
auto hRes = S_OK;
if (0 != m_iControl)
{
y += m_iSmallHeightMargin;
// height -= m_iSmallHeightMargin;
}
if (m_bUseLabelControl)
{
EC_B(m_Label.SetWindowPos(
nullptr,
x,
y,
width,
m_iLabelHeight,
SWP_NOZORDER));
y += m_iLabelHeight;
// height -= m_iLabelHeight;
}
EC_B(m_DropDown.SetWindowPos(NULL, x, y, width, m_iEditHeight, SWP_NOZORDER));
}
void DropDownPane::DoInit(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
auto hRes = S_OK;
ViewPane::Initialize(iControl, pParent, hdc);
auto ulDrops = 1 + (m_ulDropList ? min(m_ulDropList, 4) : 4);
auto dropHeight = ulDrops * (pParent ? GetEditHeight(pParent->m_hWnd) : 0x1e);
// m_bReadOnly means you can't type...
DWORD dwDropStyle;
if (m_bReadOnly)
{
dwDropStyle = CBS_DROPDOWNLIST; // does not allow typing
}
else
{
dwDropStyle = CBS_DROPDOWN; // allows typing
}
EC_B(m_DropDown.Create(
WS_TABSTOP
| WS_CHILD
| WS_CLIPSIBLINGS
| WS_BORDER
| WS_VISIBLE
| WS_VSCROLL
| CBS_OWNERDRAWFIXED
| CBS_AUTOHSCROLL
| CBS_DISABLENOSCROLL
| dwDropStyle,
CRect(0, 0, 0, dropHeight),
pParent,
m_nID));
}
void DropDownPane::Initialize(int iControl, _In_ CWnd* pParent, _In_ HDC hdc)
{
DoInit(iControl, pParent, hdc);
if (m_lpuidDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = loadstring(m_lpuidDropList[iDropNum]);
InsertDropString(iDropNum, szDropString, m_lpuidDropList[iDropNum]);
}
}
else if (m_lpnaeDropList)
{
for (ULONG iDropNum = 0; iDropNum < m_ulDropList; iDropNum++)
{
auto szDropString = wstring(m_lpnaeDropList[iDropNum].lpszName);
InsertDropString(iDropNum, szDropString, m_lpnaeDropList[iDropNum].ulValue);
}
}
// If this is a GUID list, load up our list of guids
if (m_bGUID)
{
for (ULONG iDropNum = 0; iDropNum < ulPropGuidArray; iDropNum++)
{
InsertDropString(iDropNum, GUIDToStringAndName(PropGuidArray[iDropNum].lpGuid), iDropNum);
}
}
m_DropDown.SetCurSel(static_cast<int>(m_iDropSelectionValue));
m_bInitialized = true;
}
void DropDownPane::InsertDropString(int iRow, _In_ wstring szText, ULONG ulValue) const
{
COMBOBOXEXITEMW item = { 0 };
item.mask = CBEIF_TEXT | CBEIF_LPARAM;
item.iItem = iRow;
item.pszText = LPWSTR(szText.c_str());
item.cchTextMax = int(szText.length());
item.lParam = ulValue;
(void) ::SendMessage(m_DropDown.m_hWnd, CBEM_INSERTITEMW, WPARAM(0), LPARAM(&item));
}
void DropDownPane::CommitUIValues()
{
m_iDropSelection = GetDropDownSelection();
m_iDropSelectionValue = GetDropDownSelectionValue();
m_lpszSelectionString = GetDropStringUseControl();
m_bInitialized = false; // must be last
}
_Check_return_ wstring DropDownPane::GetDropStringUseControl() const
{
CString szText;
m_DropDown.GetWindowText(szText);
return LPCTSTRToWstring(szText);
}
// This should work whether the editor is active/displayed or not
_Check_return_ int DropDownPane::GetDropDownSelection() const
{
if (m_bInitialized) return m_DropDown.GetCurSel();
// In case we're being called after we're done displaying, use the stored value
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownSelectionValue() const
{
if (m_bInitialized)
{
auto iSel = m_DropDown.GetCurSel();
if (CB_ERR != iSel)
{
return m_DropDown.GetItemData(iSel);
}
}
else
{
return m_iDropSelectionValue;
}
return 0;
}
_Check_return_ int DropDownPane::GetDropDown() const
{
return m_iDropSelection;
}
_Check_return_ DWORD_PTR DropDownPane::GetDropDownValue() const
{
return m_iDropSelectionValue;
}
// This should work whether the editor is active/displayed or not
_Check_return_ bool DropDownPane::GetSelectedGUID(bool bByteSwapped, _In_ LPGUID lpSelectedGUID) const
{
if (!lpSelectedGUID) return NULL;
auto iCurSel = GetDropDownSelection();
if (iCurSel != CB_ERR)
{
memcpy(lpSelectedGUID, PropGuidArray[iCurSel].lpGuid, sizeof(GUID));
return true;
}
// no match - need to do a lookup
wstring szText;
if (m_bInitialized)
{
szText = GetDropStringUseControl();
}
if (szText.empty())
{
szText = m_lpszSelectionString;
}
auto lpGUID = GUIDNameToGUID(szText, bByteSwapped);
if (lpGUID)
{
memcpy(lpSelectedGUID, lpGUID, sizeof(GUID));
delete[] lpGUID;
return true;
}
return false;
}
void DropDownPane::SetDropDownSelection(_In_ wstring szText)
{
auto hRes = S_OK;
auto text = wstringToCString(szText);
auto iSelect = m_DropDown.SelectString(0, text);
// if we can't select, try pushing the text in there
// not all dropdowns will support this!
if (CB_ERR == iSelect)
{
EC_B(::SendMessage(
m_DropDown.m_hWnd,
WM_SETTEXT,
NULL,
reinterpret_cast<LPARAM>(static_cast<LPCTSTR>(text))));
}
}
void DropDownPane::SetSelection(DWORD_PTR iSelection)
{
if (!m_bInitialized)
{
m_iDropSelectionValue = iSelection;
}
else
{
m_DropDown.SetCurSel(static_cast<int>(iSelection));
}
}<|endoftext|>
|
<commit_before>
#include "potentialfunctioncbspl.h"
PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
const int ncutcoeff_, const double min_, const double max_) :
PotentialFunction(nlam_,min_,max_) {
/* Here nlam_ is the total number of coeff values that are to be optimized
* To ensure that potential and force go to zero smoothly near cut-off,
* as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
* cut-off and beyond take a value of zero.
*
* Since region less than rmin is not sampled sufficiently for stability
* first _nexcl coefficients are not optimized instead their values are
* extrapolated from first statistically significant knot values near rmin
*/
// number of break points = _lam.size() - 2
_nbreak = _lam.size() - 2;
double _dr = ( _cut_off )/( double (_nbreak - 1) );
// break point locations
// since ncoeff = nbreak +2 , r values for last two coefficients are also
// computed
_rbreak.resize(_lam.size(),false);
_rbreak.clear();
for( int i = 0; i < _lam.size(); i++)
_rbreak(i) = i*_dr;
_nexcl = min( int( ( _min )/_dr ), _nbreak - 2 );
_ncutcoeff = ncutcoeff_;
_M.resize(4,4,false);
_M.clear();
_M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0;
_M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0;
_M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0;
_M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
_M /= 6.0;
}
int PotentialFunctionCBSPL::getOptParamSize() const {
return _lam.size() - _nexcl - _ncutcoeff;
}
void PotentialFunctionCBSPL::setParam(string filename) {
Table param;
param.Load(filename);
if( param.size() != _lam.size()) {
throw std::runtime_error("Potential parameters size mismatch!\n"
"Check input parameter file \""
+ filename + "\" \nThere should be "
+ boost::lexical_cast<string>( _lam.size() ) + " parameters");
} else {
for( int i = 0; i < _lam.size(); i++){
_rbreak(i) = param.x(i);
_lam(i) = param.y(i);
}
}
}
void PotentialFunctionCBSPL::SaveParam(const string& filename){
Table param;
param.SetHasYErr(false);
param.resize(_lam.size(), false);
// extrapolate first _nexcl knot values using exponential extrapolation
// u(r) = a * exp( b * r)
// a = u0 * exp ( - m * r0/u0 )
// b = m/u0
// m = (u1-u0)/(r1-r0)
double u0 = _lam(_nexcl);
double r0 = _rbreak(_nexcl);
double m = ( _lam(_nexcl+1) - _lam(_nexcl) ) /
( _rbreak(_nexcl+1) - _rbreak(_nexcl) );
double a0 = u0 * exp ( - m * r0/u0 );
double b = m/u0;
for (int i = 0; i < _nexcl; i++){
double r = _rbreak(i);
double u = a * exp( b * r);
_lam(i) = u;
param.set(i, r, u, 'o');
}
for (int i = _nexcl; i < _lam.size(); i++){
param.set(i, _rbreak(i), _lam(i), 'i');
}
param.Save(filename);
}
double PotentialFunctionCBSPL::CalculateF (const double r) const {
if( r >= _min && r <= _cut_off){
ub::vector<double> R;
ub::vector<double> B;
int indx = min( int( r /_dr ) , _nbreak-2 );
double rk = indx*_dr;
double t = ( r - rk)/_dr;
R.resize(4,false); R.clear();
R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;
ub::vector<double> RM = ub::prod(R,_M);
B.resize(4,false); B.clear();
B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
B(3) = _lam(indx+3);
double u = ub::inner_prod(B,RM);
return u;
} else {
return 0.0;
}
}
// calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{
// since first _nexcl parameters are not optimized for stability reasons
//i = i + _nexcl;
if ( r >= _min && r <= _cut_off ) {
int indx = min( int( ( r )/_dr ), _nbreak-2 );
if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){
ub::vector<double> R;
double rk = indx*_dr;
double t = ( r - rk)/_dr;
R.resize(4,false); R.clear();
R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;
ub::vector<double> RM = ub::prod(R,_M);
return RM(i + _nexcl-indx);
}else{
return 0.0;
}
} else {
return 0;
}
}
// calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
const double r) const {
// for cubic B-SPlines D2F is zero for all lamdas
return 0.0;
}
<commit_msg>corrected compilation errors<commit_after>
#include "potentialfunctioncbspl.h"
PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
const int ncutcoeff_, const double min_, const double max_) :
PotentialFunction(nlam_,min_,max_) {
/* Here nlam_ is the total number of coeff values that are to be optimized
* To ensure that potential and force go to zero smoothly near cut-off,
* as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
* cut-off and beyond take a value of zero.
*
* Since region less than rmin is not sampled sufficiently for stability
* first _nexcl coefficients are not optimized instead their values are
* extrapolated from first statistically significant knot values near rmin
*/
// number of break points = _lam.size() - 2
_nbreak = _lam.size() - 2;
double _dr = ( _cut_off )/( double (_nbreak - 1) );
// break point locations
// since ncoeff = nbreak +2 , r values for last two coefficients are also
// computed
_rbreak.resize(_lam.size(),false);
_rbreak.clear();
for( int i = 0; i < _lam.size(); i++)
_rbreak(i) = i*_dr;
_nexcl = min( int( ( _min )/_dr ), _nbreak - 2 );
_ncutcoeff = ncutcoeff_;
_M.resize(4,4,false);
_M.clear();
_M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0;
_M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0;
_M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0;
_M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
_M /= 6.0;
}
int PotentialFunctionCBSPL::getOptParamSize() const {
return _lam.size() - _nexcl - _ncutcoeff;
}
void PotentialFunctionCBSPL::setParam(string filename) {
Table param;
param.Load(filename);
if( param.size() != _lam.size()) {
throw std::runtime_error("Potential parameters size mismatch!\n"
"Check input parameter file \""
+ filename + "\" \nThere should be "
+ boost::lexical_cast<string>( _lam.size() ) + " parameters");
} else {
for( int i = 0; i < _lam.size(); i++){
_rbreak(i) = param.x(i);
_lam(i) = param.y(i);
}
}
}
void PotentialFunctionCBSPL::SaveParam(const string& filename){
Table param;
param.SetHasYErr(false);
param.resize(_lam.size(), false);
// extrapolate first _nexcl knot values using exponential extrapolation
// u(r) = a * exp( b * r)
// a = u0 * exp ( - m * r0/u0 )
// b = m/u0
// m = (u1-u0)/(r1-r0)
double u0 = _lam(_nexcl);
double r0 = _rbreak(_nexcl);
double m = ( _lam(_nexcl+1) - _lam(_nexcl) ) /
( _rbreak(_nexcl+1) - _rbreak(_nexcl) );
double a = u0 * exp ( - m * r0/u0 );
double b = m/u0;
for (int i = 0; i < _nexcl; i++){
double r = _rbreak(i);
double u = a * exp( b * r);
_lam(i) = u;
param.set(i, r, u, 'o');
}
for (int i = _nexcl; i < _lam.size(); i++){
param.set(i, _rbreak(i), _lam(i), 'i');
}
param.Save(filename);
}
double PotentialFunctionCBSPL::CalculateF (const double r) const {
if( r >= _min && r <= _cut_off){
ub::vector<double> R;
ub::vector<double> B;
int indx = min( int( r /_dr ) , _nbreak-2 );
double rk = indx*_dr;
double t = ( r - rk)/_dr;
R.resize(4,false); R.clear();
R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;
ub::vector<double> RM = ub::prod(R,_M);
B.resize(4,false); B.clear();
B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
B(3) = _lam(indx+3);
double u = ub::inner_prod(B,RM);
return u;
} else {
return 0.0;
}
}
// calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{
// since first _nexcl parameters are not optimized for stability reasons
//i = i + _nexcl;
if ( r >= _min && r <= _cut_off ) {
int indx = min( int( ( r )/_dr ), _nbreak-2 );
if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){
ub::vector<double> R;
double rk = indx*_dr;
double t = ( r - rk)/_dr;
R.resize(4,false); R.clear();
R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;
ub::vector<double> RM = ub::prod(R,_M);
return RM(i + _nexcl-indx);
}else{
return 0.0;
}
} else {
return 0;
}
}
// calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
const double r) const {
// for cubic B-SPlines D2F is zero for all lamdas
return 0.0;
}
<|endoftext|>
|
<commit_before>#include <avr/io.h>
#include <avr/pgmspace.h>
#include "console.h"
#include "extdata.h"
#include "frequency.h"
namespace GpioInit
{
static uint16_t parseNumber(uint8_t* str, uint8_t len)
{
uint8_t* last = str + len - 1;
uint16_t number = 0;
while(str <= last)
{
number = (number * 10) + ((*str)-'0');
str++;
}
return number;
}
static void reportGpioError(const char* str)
{
console::print("GPIO init: ");
console::print(str);
}
static void reportGpioInvalidCommand()
{
reportGpioError("Invalid Port command");
}
/** The 3 character commands are of the form:
* D4+
* C7~
* F3^
*/
static bool processPortCommand(uint8_t* cmd, uint8_t len, bool errors_only)
{
if(len != 3)
{
reportGpioInvalidCommand();
return false;
}
volatile uint8_t* portData;
volatile uint8_t* portDir;
switch(cmd[0])
{
case 'B':
portData = &PORTB;
portDir = &DDRB;
break;
case 'C':
portData = &PORTC;
portDir = &DDRC;
break;
case 'D':
portData = &PORTD;
portDir = &DDRD;
break;
case 'E':
portData = &PORTE;
portDir = &DDRE;
break;
case 'F':
portData = &PORTF;
portDir = &DDRF;
break;
default:
reportGpioInvalidCommand();
return false;
}
uint8_t bitmask = (1 << (cmd[1]-'0'));
if(errors_only)
{
switch(cmd[2])
{
case '+': // drive high
case '-': // drive low
case '~': // input -- no pullup (floating)
case '^': // input -- with pullup (this will work only if PUD (in MCUCR) is 1)
return true;
default:
reportGpioInvalidCommand();
return false;
}
}
switch(cmd[2])
{
case '+': // drive high
*portData |= bitmask;
*portDir |= bitmask;
return true;
case '-': // drive low
*portData &= ~bitmask;
*portDir |= bitmask;
return true;
case '~': // input -- no pullup (floating)
*portData &= ~bitmask;
*portDir &= ~bitmask;
return true;
case '^': // input -- with pullup (this will work only if PUD (in MCUCR) is 1)
*portData |= bitmask;
*portDir &= ~bitmask;
return true;
default:
reportGpioInvalidCommand();
return false;
}
}
static bool processGpioCommand(uint8_t* cmd, uint8_t len, bool errors_only)
{
console::print("\nCmd(");
console::printNumber(len);
console::print(")='");
for(uint8_t i = 0; i<len; i++)
console::print(cmd[i]);
console::println("'");
switch(cmd[0])
{
case 'P':
{
if(len < 2)
{
reportGpioError("Invalid Pause command");
return false;
}
// pause for n milliseconds
if(!errors_only)
{
uint16_t n = parseNumber(cmd+1, len-1);
Frequency::delay_ms(n);
}
return true;
}
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return processPortCommand(cmd, len, errors_only);
default:
reportGpioError("Error parsing init string, bad character");
return false; // error, abort
}
return true;
}
bool customGpioInit(bool errors_only)
{
uint16_t gpioinit = extdata_getAddress(EXTDATA_GPIO_INIT);
uint8_t length = extdata_getLength8(EXTDATA_GPIO_INIT);
uint8_t command[8];
uint8_t cmdlen = 0;
for(uint8_t index = 0 ; index < length; index++)
{
uint8_t c = pgm_read_byte(gpioinit + index);
if(c == ',' || index+1 == length)
{
if(!processGpioCommand(command, cmdlen, errors_only))
{
console::print(" (pos = ");
console::printNumber(index);
console::println(")");
return false; // fatal error
}
cmdlen = 0;
continue;
}
command[cmdlen] = c;
cmdlen++;
if(cmdlen > 8)
{
reportGpioError("Error parsing init string, command too long (pos = ");
console::printNumber(index);
console::println(")");
return false;
}
}
return true;
}
}
<commit_msg>version 0.7f GPIO init parser bug<commit_after>#include <avr/io.h>
#include <avr/pgmspace.h>
#include "console.h"
#include "extdata.h"
#include "frequency.h"
namespace GpioInit
{
static uint16_t parseNumber(uint8_t* str, uint8_t len)
{
uint8_t* last = str + len - 1;
uint16_t number = 0;
while(str <= last)
{
number = (number * 10) + ((*str)-'0');
str++;
}
return number;
}
static void reportGpioError(const char* str)
{
console::print("GPIO init: ");
console::print(str);
}
static void reportGpioInvalidCommand()
{
reportGpioError("Invalid Port command");
}
/** The 3 character commands are of the form:
* D4+
* C7~
* F3^
*/
static bool processPortCommand(uint8_t* cmd, uint8_t len, bool errors_only)
{
if(len != 3)
{
reportGpioInvalidCommand();
return false;
}
volatile uint8_t* portData;
volatile uint8_t* portDir;
switch(cmd[0])
{
case 'B':
portData = &PORTB;
portDir = &DDRB;
break;
case 'C':
portData = &PORTC;
portDir = &DDRC;
break;
case 'D':
portData = &PORTD;
portDir = &DDRD;
break;
case 'E':
portData = &PORTE;
portDir = &DDRE;
break;
case 'F':
portData = &PORTF;
portDir = &DDRF;
break;
default:
reportGpioInvalidCommand();
return false;
}
uint8_t bitmask = (1 << (cmd[1]-'0'));
if(errors_only)
{
switch(cmd[2])
{
case '+': // drive high
case '-': // drive low
case '~': // input -- no pullup (floating)
case '^': // input -- with pullup (this will work only if PUD (in MCUCR) is 1)
return true;
default:
reportGpioInvalidCommand();
return false;
}
}
switch(cmd[2])
{
case '+': // drive high
*portData |= bitmask;
*portDir |= bitmask;
return true;
case '-': // drive low
*portData &= ~bitmask;
*portDir |= bitmask;
return true;
case '~': // input -- no pullup (floating)
*portData &= ~bitmask;
*portDir &= ~bitmask;
return true;
case '^': // input -- with pullup (this will work only if PUD (in MCUCR) is 1)
*portData |= bitmask;
*portDir &= ~bitmask;
return true;
default:
reportGpioInvalidCommand();
return false;
}
}
static bool processGpioCommand(uint8_t* cmd, uint8_t len, bool errors_only)
{
console::print("\nCmd(");
console::printNumber(len);
console::print(")='");
for(uint8_t i = 0; i<len; i++)
console::print(cmd[i]);
console::println("'");
switch(cmd[0])
{
case 'P':
{
if(len < 2)
{
reportGpioError("Invalid Pause command");
return false;
}
// pause for n milliseconds
if(!errors_only)
{
uint16_t n = parseNumber(cmd+1, len-1);
Frequency::delay_ms(n);
}
return true;
}
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return processPortCommand(cmd, len, errors_only);
default:
reportGpioError("Error parsing init string, bad character");
return false; // error, abort
}
return true;
}
bool customGpioInit(bool errors_only)
{
uint16_t gpioinit = extdata_getAddress(EXTDATA_GPIO_INIT);
uint8_t length = extdata_getLength8(EXTDATA_GPIO_INIT);
uint8_t command[8];
uint8_t cmdlen = 0;
for(uint8_t index = 0 ; index < length; index++)
{
uint8_t c = pgm_read_byte(gpioinit + index);
if(c != ',')
{
command[cmdlen] = c;
cmdlen++;
if(cmdlen > 8)
{
reportGpioError("Error parsing init string, command too long (pos = ");
console::printNumber(index);
console::println(")");
return false;
}
}
if(c == ',' || index+1 == length)
{
if(!processGpioCommand(command, cmdlen, errors_only))
{
console::print(" (pos = ");
console::printNumber(index);
console::println(")");
return false; // fatal error
}
cmdlen = 0;
continue;
}
}
return true;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include <ctime>
#include "unittest/gtest.hpp"
#include "http/http.hpp"
namespace unittest {
TEST(Http, FormatTime) {
std::string formatted_time = http_format_date(1356998463);
EXPECT_EQ("Tue, 01 Jan 2013 00:01:03 GMT", formatted_time);
}
// Helper functions to create dummy objects
http_req_t http_req_encoding(const std::string &encoding) {
http_req_t req;
header_line_t accept_encoding;
accept_encoding.key = "Accept-Encoding";
accept_encoding.val = encoding;
req.header_lines.push_back(accept_encoding);
return req;
}
void test_encoding(const std::string &encoding, bool expected) {
// Use at least 2k so compression has something to work with
static std::string body;
for (size_t i = 0; i < 2048; ++i) {
body += 'a' + (i % 26);
}
http_req_t req = http_req_encoding(encoding);
http_res_t res(HTTP_OK);
res.set_body("application/text", body);
EXPECT_EQ(expected, maybe_gzip_response(req, &res)) << "Incorrect handling of encoding '" + encoding + "'";
}
TEST(Http, Encodings) {
// These encodings are valid and should result in compression
test_encoding("gzip", true);
test_encoding("gzip", true);
test_encoding("gzip ;q=001", true);
test_encoding("gzip;q =0.1", true);
test_encoding("gzip ;q= 1000.11111 ", true);
test_encoding(" identity;q=1000.1111 , gzip;q=1000.11111", true);
test_encoding("compress, gzip", true);
test_encoding("*", true);
test_encoding("compress;q=0.5, gzip;q=1.0", true);
test_encoding("gzip;q=1.0, identity; q=0.5, *;q=0", true);
test_encoding("geewhiz;q=1.0,geezip;q=2.0,*;q=0.5", true);
test_encoding("geewhiz;q=0.0,geezip;q=2.2,*;q=3", true);
// These encodings are valid but should not result in compression
test_encoding("", false);
test_encoding("*;q=0.0", false);
test_encoding("gzip;q=0.1,identity;q=0.2", false);
test_encoding("gzip;q=1,*;q=1.84", false);
test_encoding("identity;q=1,*;q=0.5", false);
test_encoding("geewhiz", false);
test_encoding("geewhiz;q=1.0", false);
test_encoding("geewhiz;q=1.0,geezip;q=2.0", false);
// These encodings have bad syntax and should fail
test_encoding("gzip:q=0.1", false);
test_encoding("gzip;q=0 .1", false);
test_encoding("gzip;q=0. 1", false);
test_encoding("gzip:q=0x1", false);
test_encoding("gzip;q=", false);
test_encoding("gzip;q", false);
test_encoding("gzip;=0.5", false);
test_encoding("gzip=9.9", false);
test_encoding("gzip;", false);
test_encoding("gzip;s=0.6", false);
test_encoding("gzip;deflate", false);
test_encoding("gzip,deflate,*=0.0", false);
test_encoding("g^zip", false);
test_encoding("g_zip", false);
}
}
<commit_msg>adding http interruptor test<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include <ctime>
#include <boost/bind.hpp>
#include "unittest/unittest_utils.hpp"
#include "containers/object_buffer.hpp"
#include "concurrency/wait_any.hpp"
#include "arch/runtime/coroutines.hpp"
#include "arch/types.hpp"
#include "arch/timing.hpp"
#include "arch/io/network.hpp"
#include "unittest/gtest.hpp"
#include "http/http.hpp"
#include "http/routing_app.hpp"
namespace unittest {
TEST(Http, FormatTime) {
std::string formatted_time = http_format_date(1356998463);
EXPECT_EQ("Tue, 01 Jan 2013 00:01:03 GMT", formatted_time);
}
// Helper functions to create dummy objects
http_req_t http_req_encoding(const std::string &encoding) {
http_req_t req;
header_line_t accept_encoding;
accept_encoding.key = "Accept-Encoding";
accept_encoding.val = encoding;
req.header_lines.push_back(accept_encoding);
return req;
}
void test_encoding(const std::string &encoding, bool expected) {
// Use at least 2k so compression has something to work with
static std::string body;
for (size_t i = 0; i < 2048; ++i) {
body += 'a' + (i % 26);
}
http_req_t req = http_req_encoding(encoding);
http_res_t res(HTTP_OK);
res.set_body("application/text", body);
EXPECT_EQ(expected, maybe_gzip_response(req, &res)) << "Incorrect handling of encoding '" + encoding + "'";
}
TEST(Http, Encodings) {
// These encodings are valid and should result in compression
test_encoding("gzip", true);
test_encoding("gzip", true);
test_encoding("gzip ;q=001", true);
test_encoding("gzip;q =0.1", true);
test_encoding("gzip ;q= 1000.11111 ", true);
test_encoding(" identity;q=1000.1111 , gzip;q=1000.11111", true);
test_encoding("compress, gzip", true);
test_encoding("*", true);
test_encoding("compress;q=0.5, gzip;q=1.0", true);
test_encoding("gzip;q=1.0, identity; q=0.5, *;q=0", true);
test_encoding("geewhiz;q=1.0,geezip;q=2.0,*;q=0.5", true);
test_encoding("geewhiz;q=0.0,geezip;q=2.2,*;q=3", true);
// These encodings are valid but should not result in compression
test_encoding("", false);
test_encoding("*;q=0.0", false);
test_encoding("gzip;q=0.1,identity;q=0.2", false);
test_encoding("gzip;q=1,*;q=1.84", false);
test_encoding("identity;q=1,*;q=0.5", false);
test_encoding("geewhiz", false);
test_encoding("geewhiz;q=1.0", false);
test_encoding("geewhiz;q=1.0,geezip;q=2.0", false);
// These encodings have bad syntax and should fail
test_encoding("gzip:q=0.1", false);
test_encoding("gzip;q=0 .1", false);
test_encoding("gzip;q=0. 1", false);
test_encoding("gzip:q=0x1", false);
test_encoding("gzip;q=", false);
test_encoding("gzip;q", false);
test_encoding("gzip;=0.5", false);
test_encoding("gzip=9.9", false);
test_encoding("gzip;", false);
test_encoding("gzip;s=0.6", false);
test_encoding("gzip;deflate", false);
test_encoding("gzip,deflate,*=0.0", false);
test_encoding("g^zip", false);
test_encoding("g_zip", false);
}
class dummy_http_app_t : public http_app_t {
public:
signal_t *get_handle_signal() {
return &request_received;
}
http_res_t handle(const http_req_t &, signal_t *interruptor) {
request_received.pulse();
interruptor->wait();
throw interrupted_exc_t();
}
private:
// Signal used to synchronize between test and app_t
cond_t request_received;
};
class http_interrupt_test_t {
public:
http_interrupt_test_t(const std::string &_http_get_path,
const std::string &_http_get_body) :
http_get_path(_http_get_path), http_get_body(_http_get_body) { }
virtual ~http_interrupt_test_t() { }
bool run() {
http_app_t *app = create_app();
ip_address_t loopback("127.0.0.1");
std::set<ip_address_t> ip_addresses;
ip_addresses.insert(loopback);
server.create(ip_addresses, 0, app);
// Start an http request
coro_t::spawn_sometime(boost::bind(&http_interrupt_test_t::http_get, this));
wait_for_connect();
// Interrupt the request by destroying the server
coro_t::spawn_sometime(boost::bind(&http_interrupt_test_t::destruct_server, this));
// Make sure the get had no reply
wait_any_t success_fail(&http_get_timed_out, &http_get_succeeded);
success_fail.wait();
return http_get_timed_out.is_pulsed();
}
protected:
virtual http_app_t *create_app() = 0;
virtual void wait_for_connect() = 0;
private:
void destruct_server() {
server.reset();
}
void http_get() {
cond_t non_interruptor;
ip_address_t loopback("127.0.0.1");
tcp_conn_t http_conn(loopback, server->get_port(), &non_interruptor);
// Send the get request
std::string buffer = strprintf("GET %s HTTP/1.1\r\n\r\n%s\r\n",
http_get_path.c_str(), http_get_body.c_str());
http_conn.write(buffer.c_str(), buffer.length(), &non_interruptor);
// Verify that we do not get a response - allow 0.5s
signal_timer_t timeout;
timeout.start(500);
try {
char dummy_buffer[1];
http_conn.read(&dummy_buffer, sizeof(dummy_buffer), &timeout);
http_get_succeeded.pulse();
return;
} catch (const tcp_conn_read_closed_exc_t &ex) {
// This is expected, the server should not send a reply when shutting down
}
http_get_timed_out.pulse();
}
object_buffer_t<http_server_t> server;
const std::string http_get_path;
const std::string http_get_body;
cond_t http_get_timed_out;
cond_t http_get_succeeded;
};
class routing_app_interrupt_test_t : public http_interrupt_test_t {
public:
routing_app_interrupt_test_t(const std::string& http_get_path) :
http_interrupt_test_t(http_get_path, "") { }
virtual ~routing_app_interrupt_test_t() { }
private:
dummy_http_app_t dummy_default;
dummy_http_app_t dummy_b;
object_buffer_t<routing_http_app_t> router;
http_app_t *create_app() {
std::map<std::string, http_app_t *> subroutes;
subroutes.insert(std::make_pair("b", &dummy_b));
router.create(&dummy_default, subroutes);
return router.get();
}
void wait_for_connect() {
wait_any_t waiter(dummy_default.get_handle_signal(), dummy_b.get_handle_signal());
waiter.wait();
}
};
void run_routing_app_test() {
{
routing_app_interrupt_test_t router_test("/");
EXPECT_TRUE(router_test.run());
}
{
routing_app_interrupt_test_t router_test("/b");
EXPECT_TRUE(router_test.run());
}
}
TEST(Http, InterruptRoutingApp) {
run_in_thread_pool(boost::bind(&run_routing_app_test));
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the ef.gy project.
* See the appropriate repository at http://ef.gy/.git for exact file
* modification records.
*/
/*
* Copyright (c) 2012, ef.gy Project Members
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <ef.gy/http.h>
#include <cstdlib>
#include <iostream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
using namespace boost::iostreams;
using namespace boost::asio;
using namespace boost;
using namespace std;
map<string, mapped_file_source> fortuneData;
class cookie
{
public:
enum encoding { ePlain, eROT13 } encoding;
string file;
size_t offset;
size_t length;
cookie (enum encoding pE, const string &pFile, size_t pOffset, size_t pLength)
: encoding(pE), file(pFile), offset(pOffset), length(pLength)
{}
operator string (void) const
{
string r(fortuneData[file].data() + offset, length);
if (encoding == eROT13)
{
for (size_t i = 0; i < r.size(); i++)
{
char c = r[i];
switch (c)
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
r[i] = c + 13;
break;
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
r[i] = c - 13;
break;
default:
break;
}
}
}
return r;
}
};
vector<cookie> cookies;
bool prepareFortunes
(const string &pInoffensive = "/usr/share/games/fortunes/",
const string &pOffensive = "/usr/share/games/fortunes/off/")
{
static const regex dataFile(".*/[a-zA-Z-]+");
smatch matches;
for (unsigned int q = 0; q < 2; q++)
{
string dir = (q == 0) ? pInoffensive : pOffensive;
bool doROT13 = (q == 1);
if (exists (dir))
{
directory_iterator end;
for (directory_iterator iter(dir); iter != end; ++iter)
{
if (is_regular(*iter))
{
string e = iter->path().string();
if (regex_match(e, matches, dataFile))
{
fortuneData[e] = mapped_file_source(e);
const mapped_file_source &p = fortuneData[e];
const char *data = p.data();
size_t start = 0;
enum { stN, stNL, stNLP } state = stN;
for (size_t c = 0; c < p.size(); c++)
{
switch (data[c])
{
case '\n':
switch (state)
{
case stN:
state = stNL;
break;
case stNLP:
cookies.push_back
(cookie((doROT13 ? cookie::eROT13 : cookie::ePlain),
e, start, c - start - 1));
start = c+1;
default:
state = stN;
break;
}
break;
case '%':
switch (state)
{
case stNL:
state = stNLP;
break;
default:
state = stN;
break;
}
break;
case '\r':
break;
default:
state = stN;
break;
}
}
}
}
}
}
}
return true;
}
class processFortune
{
public:
bool operator () (efgy::net::http::session<processFortune> &a)
{
const int id = rand() % cookies.size();
const cookie &c = cookies[id];
char nbuf[20];
snprintf (nbuf, 20, "%i", id);
string sc = string(c);
sc = "<![CDATA[" + sc + "]]>";
a.reply (200,
"Content-Type: text/xml; charset=utf-8\r\n",
string("<?xml version='1.0' encoding='utf-8'?>"
"<fortune xmlns='http://ef.gy/2012/fortune' quoteID='")
+ nbuf + "' sourceFile='"
+ c.file + "'>"
+ sc
+ "</fortune>");
return true;
}
};
int main (int argc, char* argv[])
{
prepareFortunes();
cerr << cookies.size() << " cookie(s) loaded\n";
srand(time(0));
cerr << string(cookies[(rand() % cookies.size())]);
try
{
if (argc != 2)
{
std::cerr << "Usage: fortune <socket>\n";
return 1;
}
boost::asio::io_service io_service;
efgy::net::http::server<processFortune> s(io_service, argv[1]);
io_service.run();
}
catch (std::exception &e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<commit_msg>stray ^H and ^G characters were causing trouble for libxmls parser<commit_after>/*
* This file is part of the ef.gy project.
* See the appropriate repository at http://ef.gy/.git for exact file
* modification records.
*/
/*
* Copyright (c) 2012, ef.gy Project Members
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <ef.gy/http.h>
#include <cstdlib>
#include <iostream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
using namespace boost::iostreams;
using namespace boost::asio;
using namespace boost;
using namespace std;
map<string, mapped_file_source> fortuneData;
class cookie
{
public:
enum encoding { ePlain, eROT13 } encoding;
string file;
size_t offset;
size_t length;
cookie (enum encoding pE, const string &pFile, size_t pOffset, size_t pLength)
: encoding(pE), file(pFile), offset(pOffset), length(pLength)
{}
operator string (void) const
{
string r(fortuneData[file].data() + offset, length);
if (encoding == eROT13)
{
for (size_t i = 0; i < r.size(); i++)
{
char c = r[i];
switch (c)
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
r[i] = c + 13;
break;
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
r[i] = c - 13;
break;
default:
break;
}
}
}
return r;
}
};
vector<cookie> cookies;
bool prepareFortunes
(const string &pInoffensive = "/usr/share/games/fortunes/",
const string &pOffensive = "/usr/share/games/fortunes/off/")
{
static const regex dataFile(".*/[a-zA-Z-]+");
smatch matches;
for (unsigned int q = 0; q < 2; q++)
{
string dir = (q == 0) ? pInoffensive : pOffensive;
bool doROT13 = (q == 1);
if (exists (dir))
{
directory_iterator end;
for (directory_iterator iter(dir); iter != end; ++iter)
{
if (is_regular(*iter))
{
string e = iter->path().string();
if (regex_match(e, matches, dataFile))
{
fortuneData[e] = mapped_file_source(e);
const mapped_file_source &p = fortuneData[e];
const char *data = p.data();
size_t start = 0;
enum { stN, stNL, stNLP } state = stN;
for (size_t c = 0; c < p.size(); c++)
{
switch (data[c])
{
case '\n':
switch (state)
{
case stN:
state = stNL;
break;
case stNLP:
cookies.push_back
(cookie((doROT13 ? cookie::eROT13 : cookie::ePlain),
e, start, c - start - 1));
start = c+1;
default:
state = stN;
break;
}
break;
case '%':
switch (state)
{
case stNL:
state = stNLP;
break;
default:
state = stN;
break;
}
break;
case '\r':
break;
default:
state = stN;
break;
}
}
}
}
}
}
}
return true;
}
class processFortune
{
public:
bool operator () (efgy::net::http::session<processFortune> &a)
{
const int id = rand() % cookies.size();
const cookie &c = cookies[id];
char nbuf[20];
snprintf (nbuf, 20, "%i", id);
string sc = string(c);
/* note: this escaping is not exactly efficient, but it's fairly simple
and the strings are fairly short, so it shouldn't be much of an issue. */
for (char i = 0; i < 0x20; i++)
{
if ((i == '\n') || (i == '\t'))
{
continue;
}
const char org [2] = { i, 0 };
const char rep [3] = { '^', (('A'-1) + i), 0 };
replace_all (sc, org, rep);
}
sc = "<![CDATA[" + sc + "]]>";
a.reply (200,
"Content-Type: text/xml; charset=utf-8\r\n",
string("<?xml version='1.0' encoding='utf-8'?>"
"<fortune xmlns='http://ef.gy/2012/fortune' quoteID='")
+ nbuf + "' sourceFile='"
+ c.file + "'>"
+ sc
+ "</fortune>");
return true;
}
};
int main (int argc, char* argv[])
{
prepareFortunes();
cerr << cookies.size() << " cookie(s) loaded\n";
srand(time(0));
cerr << string(cookies[(rand() % cookies.size())]);
try
{
if (argc != 2)
{
std::cerr << "Usage: fortune <socket>\n";
return 1;
}
boost::asio::io_service io_service;
efgy::net::http::server<processFortune> s(io_service, argv[1]);
io_service.run();
}
catch (std::exception &e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "value.h"
#include "gobject.h"
#include "gi.h"
#include <girffi.h>
using namespace v8;
using Nan::New;
using Nan::WeakCallbackType;
namespace GNodeJS {
static void FillArgument(GIArgInfo *arg_info,
GIArgument *argument,
Local<Value> value) {
bool may_be_null = g_arg_info_may_be_null (arg_info);
GITypeInfo type_info;
g_arg_info_load_type (arg_info, &type_info);
V8ToGIArgument(&type_info, argument, value, may_be_null);
}
static void AllocateArgument (GIBaseInfo *arg_info, GIArgument *argument) {
gsize size;
GITypeInfo arg_type;
g_arg_info_load_type(arg_info, &arg_type);
GITypeTag a_tag = g_type_info_get_tag(&arg_type);
if (a_tag == GI_TYPE_TAG_INTERFACE) {
GIInfoType i_type;
GIBaseInfo *i_info;
i_info = g_type_info_get_interface(&arg_type);
i_type = g_base_info_get_type(i_info);
if (i_type == GI_INFO_TYPE_STRUCT) {
size = g_struct_info_get_size((GIStructInfo*)i_info);
} else if (i_type == GI_INFO_TYPE_UNION) {
size = g_union_info_get_size((GIUnionInfo*)i_info);
} else if (i_type == GI_INFO_TYPE_INTERFACE) {
g_warning("Allocate: arg %s \t interface %s",
g_base_info_get_name(arg_info),
g_base_info_get_name(i_info));
size = g_struct_info_get_size(
g_interface_info_get_iface_struct(i_info));
} else {
DEBUG("arg OUT && caller-allocates && not supported: %s",
g_type_tag_to_string(a_tag));
g_assert_not_reached();
}
argument->v_pointer = g_slice_alloc0(size);
g_base_info_unref(i_info);
} else {
DEBUG("arg OUT && NOT INTERFACE: %s", g_type_tag_to_string(a_tag));
g_assert_not_reached();
}
}
/* see: /home/romgrk/src/gjs/gi/function.cpp */
void FunctionInvoker(const Nan::FunctionCallbackInfo<Value> &args) {
//Isolate *isolate = args.GetIsolate();
FunctionInfo *func = (FunctionInfo *) External::Cast (*args.Data ())->Value ();
GIBaseInfo *info = func->info;
GError *error = NULL;
int n_callable_args = g_callable_info_get_n_args ((GICallableInfo *) info);
int n_total_args = n_callable_args;
int n_out_args = 0;
int n_in_args = 0;
Parameter call_parameters[n_callable_args];
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
GITypeInfo type_info;
g_arg_info_load_type(&arg_info, &type_info);
int array_length_idx = g_type_info_get_array_length (&type_info);
if (array_length_idx >= 0) {
call_parameters[i].type = Parameter::ARRAY;
call_parameters[array_length_idx].type = Parameter::SKIP;
}
}
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info;
if (call_parameters[i].type == Parameter::SKIP)
continue;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
if (g_arg_info_get_direction (&arg_info) == GI_DIRECTION_IN ||
g_arg_info_get_direction (&arg_info) == GI_DIRECTION_INOUT)
n_in_args++;
}
if (args.Length() < n_in_args) {
Nan::ThrowTypeError(g_strdup_printf(
"Not enough arguments; expected %i, have %i",
n_in_args, args.Length()));
return;
}
GIFunctionInfoFlags flags = g_function_info_get_flags (info);
gboolean is_method = ((flags & GI_FUNCTION_IS_METHOD) != 0 &&
(flags & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
if (is_method)
n_total_args++;
gboolean can_throw = g_callable_info_can_throw_gerror (info);
if (can_throw)
n_total_args++;
GIArgument total_arg_values[n_total_args];
GIArgument *callable_arg_values;
if (is_method) {
GIBaseInfo *container = g_base_info_get_container (func->info);
V8ToGIArgument(container, &total_arg_values[0], args.This() );
callable_arg_values = &total_arg_values[1];
} else {
callable_arg_values = &total_arg_values[0];
}
int in_arg = 0, i = 0;
for (; i < n_callable_args; i++) {
if (call_parameters[i].type == Parameter::SKIP)
continue;
GIArgInfo arg_info = {};
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
GIDirection direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) {
n_out_args++;
if (g_arg_info_is_caller_allocates (&arg_info)) {
AllocateArgument(&arg_info, &callable_arg_values[i]);
} else /* is_callee_allocates */ {
callable_arg_values[i].v_pointer = NULL;
}
}
if (direction == GI_DIRECTION_IN || direction == GI_DIRECTION_INOUT) {
/* Fill the in-argument if it is null and nullable */
FillArgument(&arg_info, &callable_arg_values[i], args[in_arg]);
if (call_parameters[i].type == Parameter::ARRAY) {
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
int array_length_pos = g_type_info_get_array_length (&type_info);
GIArgInfo array_length_arg;
g_callable_info_load_arg(info, array_length_pos, &array_length_arg);
int array_length;
//array_length = GetArrayLength (args[in_arg]);
if (args[in_arg]->IsArray())
array_length = Local<Array>::Cast (args[in_arg]->ToObject ())->Length();
else if (args[in_arg]->IsString())
array_length = Local<String>::Cast (args[in_arg]->ToObject ())->Length();
else if (args[in_arg]->IsNull())
array_length = 0;
else
g_assert_not_reached();
Local<Value> array_length_value = New(array_length);
FillArgument(
&array_length_arg,
&callable_arg_values[array_length_pos],
array_length_value);
}
in_arg++;
}
if (direction == GI_DIRECTION_INOUT) {
WARN("FunctionInvoker: arg INOUT: %s ", g_base_info_get_name(&arg_info));
WARN("Value: %s", *String::Utf8Value(args[in_arg]->ToString()) );
}
}
if (can_throw)
callable_arg_values[i].v_pointer = &error;
void *ffi_arg_pointers[n_total_args];
for (int i = 0; i < n_total_args; i++)
ffi_arg_pointers[i] = &total_arg_values[i];
GIArgument return_value;
ffi_call (&func->invoker.cif, FFI_FN (func->invoker.native_address),
&return_value, ffi_arg_pointers);
GITypeInfo return_type;
g_callable_info_load_return_type(info, &return_type);
GITypeTag return_tag = g_type_info_get_tag(&return_type);
GITransfer return_transfer = g_callable_info_get_caller_owns(info);
//bool retValueLoaded = false;
//FreeGIArgument(&return_type, &return_value);
gboolean skip_return = g_callable_info_skip_return(info);
//gboolean may_return_null = g_callable_info_may_return_null(info);
if (return_transfer == GI_TRANSFER_NOTHING) {
//if (skip_return == FALSE)
//g_warning("Return: (transfer none) (no-skip!) %s ",
//(may_return_null ? "(allow-none)" : ""));
} else if (return_transfer == GI_TRANSFER_CONTAINER) {
//g_warning("Return: (transfer container) %s ",
//(may_return_null ? "(allow-none)" : ""));
} else if (return_transfer == GI_TRANSFER_EVERYTHING) {
//g_warning("Return: (transfer full) %s ",
//(may_return_null ? "(allow-none)" : ""));
//if (!may_return_null)
}
if (return_tag != GI_TYPE_TAG_VOID && (skip_return == FALSE))
n_out_args++;
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info = {};
GITypeInfo arg_type;
GIDirection direction;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
g_arg_info_load_type (&arg_info, &arg_type);
direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) { //|| direction == GI_DIRECTION_INOUT)
args.GetReturnValue().Set(
GIArgumentToV8(&arg_type, &callable_arg_values[i]) );
//retValueLoaded = true;
} else if (direction == GI_DIRECTION_INOUT) {
// XXX is there something to do here?
g_warning("INOUT: %s", g_base_info_get_name(&arg_info));
} else {
FreeGIArgument (&arg_type, &callable_arg_values[i]);
}
}
if (error) {
Nan::ThrowError(error->message);
g_error_free(error);
return;
}
if (return_tag != GI_TYPE_TAG_VOID)
args.GetReturnValue().Set(
GIArgumentToV8(&return_type, &return_value));
//if (return_transfer == GI_TRANSFER_CONTAINER)
//FreeGIArgument(&return_type, &return_value);
}
void FunctionDestroyed(const v8::WeakCallbackInfo<FunctionInfo> &data) {
FunctionInfo *func = data.GetParameter ();
g_base_info_unref (func->info);
g_function_invoker_destroy (&func->invoker);
g_free (func);
}
NAN_METHOD(FunctionInfoToString) {
//Isolate *isolate = info.GetIsolate();
FunctionInfo *func = (FunctionInfo *) External::Cast(*info.Holder());
GIFunctionInfo *fn = func->info;
GString *args_string = g_string_new("");
int n_args = g_callable_info_get_n_args(fn);
for (int i = 0; i < n_args; i++) {
if (i != 0)
g_string_append(args_string, ", ");
GIArgInfo *arg_info = nullptr;
arg_info = g_callable_info_get_arg(fn, i);
g_string_append(args_string, g_base_info_get_name(arg_info));
g_base_info_unref(arg_info);
}
gchar *args = g_string_free(args_string, FALSE);
gchar *string = g_strdup_printf("function %s (%s) {}",
g_function_info_get_symbol(fn),
args);
Local<String> result = UTF8(string);
g_free(args);
g_free(string);
info.GetReturnValue().Set(result);
}
Local<Function> MakeFunction(GIBaseInfo *info) {
FunctionInfo *func = g_new0 (FunctionInfo, 1);
func->info = g_base_info_ref (info);
g_function_info_prep_invoker (func->info, &func->invoker, NULL);
auto tpl = New<FunctionTemplate>(FunctionInvoker, New<External>(func));
Local<Function> fn = tpl->GetFunction();
fn->SetName(
New(g_function_info_get_symbol(info)).ToLocalChecked());
Isolate *isolate = Isolate::GetCurrent();
v8::Persistent<v8::FunctionTemplate> persistent(isolate, tpl);
persistent.SetWeak(func, FunctionDestroyed, WeakCallbackType::kParameter);
return fn;
}
#if 0
class TrampolineInfo {
ffi_cif cif;
ffi_closure *closure;
Persistent<Function> persistent;
GICallableInfo *info;
GIScopeType scope_type;
TrampolineInfo(Handle<Function> function,
GICallableInfo *info,
GIScopeType scope_type);
void Dispose();
static void Call(ffi_cif *cif, void *result, void **args, void *data);
void *GetClosure();
};
void TrampolineInfo::Dispose() {
persistent = nullptr;
g_base_info_unref (info);
g_callable_info_free_closure (info, closure);
};
void TrampolineInfo::Call(ffi_cif *cif,
void *result,
void **args,
void *data) {
TrampolineInfo *trampoline = (TrampolineInfo *) data;
int argc = g_callable_info_get_n_args (trampoline->info);
Handle<Value> argv[argc];
for (int i = 0; i < argc; i++) {
GIArgInfo arg_info;
g_callable_info_load_arg (trampoline->info, i, &arg_info);
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
argv[i] = GIArgumentToV8 (&type_info, (GIArgument *) &args[i]);
}
Handle<Function> func = trampoline->func;
/* Provide a bogus "this" function. Any interested callers should
* bind their callbacks to what they're intersted in... */
Handle<Object> this_obj = func;
Handle<Value> return_value = func->Call (this_obj, argc, argv);
GITypeInfo type_info;
g_callable_info_load_return_type (trampoline->info, &type_info);
V8ToGIArgument (&type_info, (GIArgument *) &result, return_value,
g_callable_info_may_return_null (trampoline->info));
}
TrampolineInfo::TrampolineInfo(Handle<Function> function,
GICallableInfo *info,
GIScopeType scope_type) {
this->closure = g_callable_info_prepare_closure (info, &cif, Call, this);
this->func = Persistent<Function>::New (function);
this->info = g_base_info_ref (info);
this->scope_type = scope_type;
}
#endif
};
<commit_msg>remove duplicate loop<commit_after>
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "value.h"
#include "gobject.h"
#include "gi.h"
#include <girffi.h>
using namespace v8;
using Nan::New;
using Nan::WeakCallbackType;
namespace GNodeJS {
static void FillArgument(GIArgInfo *arg_info,
GIArgument *argument,
Local<Value> value) {
bool may_be_null = g_arg_info_may_be_null (arg_info);
GITypeInfo type_info;
g_arg_info_load_type (arg_info, &type_info);
V8ToGIArgument(&type_info, argument, value, may_be_null);
}
static void AllocateArgument (GIBaseInfo *arg_info, GIArgument *argument) {
gsize size;
GITypeInfo arg_type;
g_arg_info_load_type(arg_info, &arg_type);
GITypeTag a_tag = g_type_info_get_tag(&arg_type);
if (a_tag == GI_TYPE_TAG_INTERFACE) {
GIInfoType i_type;
GIBaseInfo *i_info;
i_info = g_type_info_get_interface(&arg_type);
i_type = g_base_info_get_type(i_info);
if (i_type == GI_INFO_TYPE_STRUCT) {
size = g_struct_info_get_size((GIStructInfo*)i_info);
} else if (i_type == GI_INFO_TYPE_UNION) {
size = g_union_info_get_size((GIUnionInfo*)i_info);
} else if (i_type == GI_INFO_TYPE_INTERFACE) {
g_warning("Allocate: arg %s \t interface %s",
g_base_info_get_name(arg_info),
g_base_info_get_name(i_info));
size = g_struct_info_get_size(
g_interface_info_get_iface_struct(i_info));
} else {
DEBUG("arg OUT && caller-allocates && not supported: %s",
g_type_tag_to_string(a_tag));
g_assert_not_reached();
}
argument->v_pointer = g_slice_alloc0(size);
g_base_info_unref(i_info);
} else {
DEBUG("arg OUT && NOT INTERFACE: %s", g_type_tag_to_string(a_tag));
g_assert_not_reached();
}
}
/* see: /home/romgrk/src/gjs/gi/function.cpp */
void FunctionInvoker(const Nan::FunctionCallbackInfo<Value> &args) {
//Isolate *isolate = args.GetIsolate();
FunctionInfo *func = (FunctionInfo *) External::Cast (*args.Data ())->Value ();
GIBaseInfo *info = func->info;
GError *error = NULL;
int n_callable_args = g_callable_info_get_n_args ((GICallableInfo *) info);
int n_total_args = n_callable_args;
int n_out_args = 0;
int n_in_args = 0;
Parameter call_parameters[n_callable_args];
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info;
GITypeInfo type_info;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
g_arg_info_load_type (&arg_info, &type_info);
int array_length_idx = g_type_info_get_array_length (&type_info);
if (array_length_idx >= 0) {
call_parameters[i].type = Parameter::ARRAY;
call_parameters[array_length_idx].type = Parameter::SKIP;
}
if (call_parameters[i].type == Parameter::SKIP)
continue;
if (g_arg_info_get_direction (&arg_info) == GI_DIRECTION_IN ||
g_arg_info_get_direction (&arg_info) == GI_DIRECTION_INOUT)
n_in_args++;
}
if (args.Length() < n_in_args) {
Nan::ThrowTypeError(g_strdup_printf(
"Not enough arguments; expected %i, have %i",
n_in_args, args.Length()));
return;
}
GIFunctionInfoFlags flags = g_function_info_get_flags (info);
gboolean is_method = ((flags & GI_FUNCTION_IS_METHOD) != 0 &&
(flags & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
if (is_method)
n_total_args++;
gboolean can_throw = g_callable_info_can_throw_gerror (info);
if (can_throw)
n_total_args++;
GIArgument total_arg_values[n_total_args];
GIArgument *callable_arg_values;
if (is_method) {
GIBaseInfo *container = g_base_info_get_container (func->info);
V8ToGIArgument(container, &total_arg_values[0], args.This() );
callable_arg_values = &total_arg_values[1];
} else {
callable_arg_values = &total_arg_values[0];
}
int in_arg = 0, i = 0;
for (; i < n_callable_args; i++) {
if (call_parameters[i].type == Parameter::SKIP)
continue;
GIArgInfo arg_info = {};
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
GIDirection direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) {
n_out_args++;
if (g_arg_info_is_caller_allocates (&arg_info)) {
AllocateArgument(&arg_info, &callable_arg_values[i]);
} else /* is_callee_allocates */ {
callable_arg_values[i].v_pointer = NULL;
}
}
if (direction == GI_DIRECTION_IN || direction == GI_DIRECTION_INOUT) {
/* Fill the in-argument if it is null and nullable */
FillArgument(&arg_info, &callable_arg_values[i], args[in_arg]);
if (call_parameters[i].type == Parameter::ARRAY) {
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
int array_length_pos = g_type_info_get_array_length (&type_info);
GIArgInfo array_length_arg;
g_callable_info_load_arg(info, array_length_pos, &array_length_arg);
int array_length;
//array_length = GetArrayLength (args[in_arg]);
if (args[in_arg]->IsArray())
array_length = Local<Array>::Cast (args[in_arg]->ToObject ())->Length();
else if (args[in_arg]->IsString())
array_length = Local<String>::Cast (args[in_arg]->ToObject ())->Length();
else if (args[in_arg]->IsNull())
array_length = 0;
else
g_assert_not_reached();
Local<Value> array_length_value = New(array_length);
FillArgument(
&array_length_arg,
&callable_arg_values[array_length_pos],
array_length_value);
}
in_arg++;
}
if (direction == GI_DIRECTION_INOUT) {
WARN("FunctionInvoker: arg INOUT: %s ", g_base_info_get_name(&arg_info));
WARN("Value: %s", *String::Utf8Value(args[in_arg]->ToString()) );
}
}
if (can_throw)
callable_arg_values[i].v_pointer = &error;
void *ffi_arg_pointers[n_total_args];
for (int i = 0; i < n_total_args; i++)
ffi_arg_pointers[i] = &total_arg_values[i];
GIArgument return_value;
ffi_call (&func->invoker.cif, FFI_FN (func->invoker.native_address),
&return_value, ffi_arg_pointers);
GITypeInfo return_type;
g_callable_info_load_return_type(info, &return_type);
GITypeTag return_tag = g_type_info_get_tag(&return_type);
GITransfer return_transfer = g_callable_info_get_caller_owns(info);
//bool retValueLoaded = false;
//FreeGIArgument(&return_type, &return_value);
gboolean skip_return = g_callable_info_skip_return(info);
//gboolean may_return_null = g_callable_info_may_return_null(info);
if (return_transfer == GI_TRANSFER_NOTHING) {
//if (skip_return == FALSE)
//g_warning("Return: (transfer none) (no-skip!) %s ",
//(may_return_null ? "(allow-none)" : ""));
} else if (return_transfer == GI_TRANSFER_CONTAINER) {
//g_warning("Return: (transfer container) %s ",
//(may_return_null ? "(allow-none)" : ""));
} else if (return_transfer == GI_TRANSFER_EVERYTHING) {
//g_warning("Return: (transfer full) %s ",
//(may_return_null ? "(allow-none)" : ""));
//if (!may_return_null)
}
if (return_tag != GI_TYPE_TAG_VOID && (skip_return == FALSE))
n_out_args++;
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info = {};
GITypeInfo arg_type;
GIDirection direction;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
g_arg_info_load_type (&arg_info, &arg_type);
direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) { //|| direction == GI_DIRECTION_INOUT)
args.GetReturnValue().Set(
GIArgumentToV8(&arg_type, &callable_arg_values[i]) );
//retValueLoaded = true;
} else if (direction == GI_DIRECTION_INOUT) {
// XXX is there something to do here?
g_warning("INOUT: %s", g_base_info_get_name(&arg_info));
} else {
FreeGIArgument (&arg_type, &callable_arg_values[i]);
}
}
if (error) {
Nan::ThrowError(error->message);
g_error_free(error);
return;
}
if (return_tag != GI_TYPE_TAG_VOID)
args.GetReturnValue().Set(
GIArgumentToV8(&return_type, &return_value));
//if (return_transfer == GI_TRANSFER_CONTAINER)
//FreeGIArgument(&return_type, &return_value);
}
void FunctionDestroyed(const v8::WeakCallbackInfo<FunctionInfo> &data) {
FunctionInfo *func = data.GetParameter ();
g_base_info_unref (func->info);
g_function_invoker_destroy (&func->invoker);
g_free (func);
}
NAN_METHOD(FunctionInfoToString) {
//Isolate *isolate = info.GetIsolate();
FunctionInfo *func = (FunctionInfo *) External::Cast(*info.Holder());
GIFunctionInfo *fn = func->info;
GString *args_string = g_string_new("");
int n_args = g_callable_info_get_n_args(fn);
for (int i = 0; i < n_args; i++) {
if (i != 0)
g_string_append(args_string, ", ");
GIArgInfo *arg_info = nullptr;
arg_info = g_callable_info_get_arg(fn, i);
g_string_append(args_string, g_base_info_get_name(arg_info));
g_base_info_unref(arg_info);
}
gchar *args = g_string_free(args_string, FALSE);
gchar *string = g_strdup_printf("function %s (%s) {}",
g_function_info_get_symbol(fn),
args);
Local<String> result = UTF8(string);
g_free(args);
g_free(string);
info.GetReturnValue().Set(result);
}
Local<Function> MakeFunction(GIBaseInfo *info) {
FunctionInfo *func = g_new0 (FunctionInfo, 1);
func->info = g_base_info_ref (info);
g_function_info_prep_invoker (func->info, &func->invoker, NULL);
auto tpl = New<FunctionTemplate>(FunctionInvoker, New<External>(func));
Local<Function> fn = tpl->GetFunction();
fn->SetName(
New(g_function_info_get_symbol(info)).ToLocalChecked());
Isolate *isolate = Isolate::GetCurrent();
v8::Persistent<v8::FunctionTemplate> persistent(isolate, tpl);
persistent.SetWeak(func, FunctionDestroyed, WeakCallbackType::kParameter);
return fn;
}
#if 0
class TrampolineInfo {
ffi_cif cif;
ffi_closure *closure;
Persistent<Function> persistent;
GICallableInfo *info;
GIScopeType scope_type;
TrampolineInfo(Handle<Function> function,
GICallableInfo *info,
GIScopeType scope_type);
void Dispose();
static void Call(ffi_cif *cif, void *result, void **args, void *data);
void *GetClosure();
};
void TrampolineInfo::Dispose() {
persistent = nullptr;
g_base_info_unref (info);
g_callable_info_free_closure (info, closure);
};
void TrampolineInfo::Call(ffi_cif *cif,
void *result,
void **args,
void *data) {
TrampolineInfo *trampoline = (TrampolineInfo *) data;
int argc = g_callable_info_get_n_args (trampoline->info);
Handle<Value> argv[argc];
for (int i = 0; i < argc; i++) {
GIArgInfo arg_info;
g_callable_info_load_arg (trampoline->info, i, &arg_info);
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
argv[i] = GIArgumentToV8 (&type_info, (GIArgument *) &args[i]);
}
Handle<Function> func = trampoline->func;
/* Provide a bogus "this" function. Any interested callers should
* bind their callbacks to what they're intersted in... */
Handle<Object> this_obj = func;
Handle<Value> return_value = func->Call (this_obj, argc, argv);
GITypeInfo type_info;
g_callable_info_load_return_type (trampoline->info, &type_info);
V8ToGIArgument (&type_info, (GIArgument *) &result, return_value,
g_callable_info_may_return_null (trampoline->info));
}
TrampolineInfo::TrampolineInfo(Handle<Function> function,
GICallableInfo *info,
GIScopeType scope_type) {
this->closure = g_callable_info_prepare_closure (info, &cif, Call, this);
this->func = Persistent<Function>::New (function);
this->info = g_base_info_ref (info);
this->scope_type = scope_type;
}
#endif
};
<|endoftext|>
|
<commit_before>/*
Copyright libCellML Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "xmlattribute.h"
#include <libxml/tree.h>
#include <string>
#include <vector>
#include "namespaces.h"
namespace libcellml {
/**
* @brief The XmlAttribute::XmlAttributeImpl struct.
*
* This struct is the private implementation struct for the XmlAttribute class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct XmlAttribute::XmlAttributeImpl
{
xmlAttrPtr mXmlAttributePtr;
};
XmlAttribute::XmlAttribute()
: mPimpl(new XmlAttributeImpl())
{
}
XmlAttribute::~XmlAttribute()
{
delete mPimpl;
}
void XmlAttribute::setXmlAttribute(const xmlAttrPtr &attribute)
{
mPimpl->mXmlAttributePtr = attribute;
}
std::string XmlAttribute::namespaceUri() const
{
if (mPimpl->mXmlAttributePtr->ns == nullptr) {
return {};
}
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->href);
}
std::string XmlAttribute::namespacePrefix() const
{
if (mPimpl->mXmlAttributePtr->ns == nullptr || mPimpl->mXmlAttributePtr->ns->prefix == nullptr) {
return {};
}
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->prefix);
}
bool XmlAttribute::inNamespaceUri(const char *ns) const
{
return xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0;
}
bool XmlAttribute::isType(const char *name, const char *ns) const
{
return (xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0)
&& (xmlStrcmp(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(name)) == 0);
}
bool XmlAttribute::isCellmlType(const char *name) const
{
return isType(name, CELLML_2_0_NS);
}
std::string XmlAttribute::name() const
{
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->name);
}
std::string XmlAttribute::value() const
{
std::string valueString;
if ((mPimpl->mXmlAttributePtr->name != nullptr) && (mPimpl->mXmlAttributePtr->parent != nullptr)) {
xmlChar *value = xmlGetProp(mPimpl->mXmlAttributePtr->parent, mPimpl->mXmlAttributePtr->name);
valueString = std::string(reinterpret_cast<const char *>(value));
xmlFree(value);
}
return valueString;
}
XmlAttributePtr XmlAttribute::next() const
{
xmlAttrPtr next = mPimpl->mXmlAttributePtr->next;
XmlAttributePtr nextHandle = nullptr;
if (next != nullptr) {
nextHandle = std::make_shared<XmlAttribute>();
nextHandle->setXmlAttribute(next);
}
return nextHandle;
}
void XmlAttribute::removeAttribute()
{
xmlRemoveProp(mPimpl->mXmlAttributePtr);
}
void XmlAttribute::setNamespacePrefix(const std::string &prefix)
{
std::vector<xmlChar> buffer;
xmlNodePtr parent = mPimpl->mXmlAttributePtr->parent;
buffer.reserve(prefix.length() + 1);
xmlChar *fullElemName = xmlBuildQName(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(prefix.c_str()), buffer.data(), static_cast<int>(buffer.size()));
auto oldAttribute = mPimpl->mXmlAttributePtr;
mPimpl->mXmlAttributePtr = xmlSetProp(parent, fullElemName, reinterpret_cast<const xmlChar *>(value().c_str()));
xmlRemoveProp(oldAttribute);
}
} // namespace libcellml
<commit_msg>Fix memory leak in setNamespacePrefix.<commit_after>/*
Copyright libCellML Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "xmlattribute.h"
#include <libxml/tree.h>
#include <string>
#include <vector>
#include "namespaces.h"
namespace libcellml {
/**
* @brief The XmlAttribute::XmlAttributeImpl struct.
*
* This struct is the private implementation struct for the XmlAttribute class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct XmlAttribute::XmlAttributeImpl
{
xmlAttrPtr mXmlAttributePtr;
};
XmlAttribute::XmlAttribute()
: mPimpl(new XmlAttributeImpl())
{
}
XmlAttribute::~XmlAttribute()
{
delete mPimpl;
}
void XmlAttribute::setXmlAttribute(const xmlAttrPtr &attribute)
{
mPimpl->mXmlAttributePtr = attribute;
}
std::string XmlAttribute::namespaceUri() const
{
if (mPimpl->mXmlAttributePtr->ns == nullptr) {
return {};
}
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->href);
}
std::string XmlAttribute::namespacePrefix() const
{
if (mPimpl->mXmlAttributePtr->ns == nullptr || mPimpl->mXmlAttributePtr->ns->prefix == nullptr) {
return {};
}
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->prefix);
}
bool XmlAttribute::inNamespaceUri(const char *ns) const
{
return xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0;
}
bool XmlAttribute::isType(const char *name, const char *ns) const
{
return (xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0)
&& (xmlStrcmp(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(name)) == 0);
}
bool XmlAttribute::isCellmlType(const char *name) const
{
return isType(name, CELLML_2_0_NS);
}
std::string XmlAttribute::name() const
{
return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->name);
}
std::string XmlAttribute::value() const
{
std::string valueString;
if ((mPimpl->mXmlAttributePtr->name != nullptr) && (mPimpl->mXmlAttributePtr->parent != nullptr)) {
xmlChar *value = xmlGetProp(mPimpl->mXmlAttributePtr->parent, mPimpl->mXmlAttributePtr->name);
valueString = std::string(reinterpret_cast<const char *>(value));
xmlFree(value);
}
return valueString;
}
XmlAttributePtr XmlAttribute::next() const
{
xmlAttrPtr next = mPimpl->mXmlAttributePtr->next;
XmlAttributePtr nextHandle = nullptr;
if (next != nullptr) {
nextHandle = std::make_shared<XmlAttribute>();
nextHandle->setXmlAttribute(next);
}
return nextHandle;
}
void XmlAttribute::removeAttribute()
{
xmlRemoveProp(mPimpl->mXmlAttributePtr);
}
void XmlAttribute::setNamespacePrefix(const std::string &prefix)
{
std::vector<xmlChar> buffer;
xmlNodePtr parent = mPimpl->mXmlAttributePtr->parent;
buffer.resize(prefix.length() + 1);
xmlChar *fullElemName = xmlBuildQName(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(prefix.c_str()), buffer.data(), static_cast<int>(buffer.size()));
auto oldAttribute = mPimpl->mXmlAttributePtr;
mPimpl->mXmlAttributePtr = xmlSetProp(parent, fullElemName, reinterpret_cast<const xmlChar *>(value().c_str()));
xmlRemoveProp(oldAttribute);
xmlFree(fullElemName);
}
} // namespace libcellml
<|endoftext|>
|
<commit_before>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "const.h" /* for XSD_INTEGER_CAPTURES */
#include "integer.h"
#include "regex.h" /* for std::regex, std::regex_match() */
#include <algorithm> /* for std::copy() */
#include <cassert> /* for assert() */
#include <cerrno> /* for errno */
#include <cinttypes> /* for std::strtoimax() */
using namespace std::regex_constants;
using namespace xsd;
////////////////////////////////////////////////////////////////////////////////
constexpr char integer::name[];
constexpr char integer::pattern[];
static const std::regex integer_regex{integer::pattern};
////////////////////////////////////////////////////////////////////////////////
static bool
parse_literal(const char* literal,
bool& sign,
std::string& integer) {
std::cmatch matches;
if (!std::regex_match(literal, matches, integer_regex, match_not_null)) {
return false; /* invalid literal */
}
assert(matches.size() == XSD_INTEGER_CAPTURES);
/* 3.3.13.2 'The preceding optional "+" sign is prohibited' */
if (matches[1].length()) {
switch (*matches[1].first) {
case '-': sign = false; break;
case '+': sign = true; break;
}
}
/* 3.3.13.2 'Leading zeroes are prohibited' */
integer.append(matches[2].first, matches[2].second);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool
integer::validate(const char* literal) noexcept {
return integer::match(literal);
}
bool
integer::match(const char* literal) noexcept {
return std::regex_match(literal, integer_regex, match_not_null);
}
bool
integer::canonicalize(std::string& literal) {
bool sign{true};
std::string integer;
if (!parse_literal(literal.c_str(), sign, integer)) {
throw std::invalid_argument{literal}; /* invalid literal */
}
char buffer[256] = "";
char* output = buffer;
/* 3.3.13.2 'The preceding optional "+" sign is prohibited' */
if (sign == false) *output++ = '-';
/* 3.3.13.2 'Leading zeroes are prohibited' */
output = std::copy(integer.cbegin(), integer.cend(), output);
*output++ = '\0';
if (literal.compare(buffer) != 0) {
literal.assign(buffer);
return true; /* now in canonical form */
}
return false; /* already in canonical form */
}
integer
integer::parse(const char* literal) {
std::error_condition error;
const auto result = parse(literal, error);
if (error) {
if (error == std::errc::invalid_argument) {
throw std::invalid_argument{literal};
}
if (error == std::errc::result_out_of_range) {
if (result.value() == INTMAX_MIN) {
throw std::underflow_error{literal};
}
else {
throw std::overflow_error{literal};
}
}
}
return result;
}
integer
integer::parse(const char* literal,
std::error_condition& error) noexcept {
return parse(literal, INTMAX_MIN, INTMAX_MAX, error);
}
integer
integer::parse(const char* literal,
const integer::value_type min_value,
const integer::value_type max_value,
std::error_condition& error) noexcept {
bool sign{true};
std::string integer;
if (!parse_literal(literal, sign, integer)) {
error = std::errc::invalid_argument;
return {};
}
errno = 0;
auto value = std::strtoimax(integer.c_str(), nullptr, 10);
if (sign == false) {
value = -value;
}
if (errno) {
error.assign(errno, std::generic_category());
}
else if (value < min_value) {
error = std::errc::result_out_of_range;
value = INTMAX_MIN;
}
else if (value > max_value) {
error = std::errc::result_out_of_range;
value = INTMAX_MAX;
}
return value;
}
////////////////////////////////////////////////////////////////////////////////
bool
integer::normalize() noexcept {
return false; /* already in normal form */
}
std::string
integer::literal() const {
return std::to_string(value());
}
<commit_msg>Fixed a bug in xsd::integer::parse() error handling.<commit_after>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "const.h" /* for XSD_INTEGER_CAPTURES */
#include "integer.h"
#include "regex.h" /* for std::regex, std::regex_match() */
#include <algorithm> /* for std::copy() */
#include <cassert> /* for assert() */
#include <cerrno> /* for errno */
#include <cinttypes> /* for std::strtoimax() */
using namespace std::regex_constants;
using namespace xsd;
////////////////////////////////////////////////////////////////////////////////
constexpr char integer::name[];
constexpr char integer::pattern[];
static const std::regex integer_regex{integer::pattern};
////////////////////////////////////////////////////////////////////////////////
static bool
parse_literal(const char* literal,
bool& sign,
std::string& integer) {
std::cmatch matches;
if (!std::regex_match(literal, matches, integer_regex, match_not_null)) {
return false; /* invalid literal */
}
assert(matches.size() == XSD_INTEGER_CAPTURES);
/* 3.3.13.2 'The preceding optional "+" sign is prohibited' */
if (matches[1].length()) {
switch (*matches[1].first) {
case '-': sign = false; break;
case '+': sign = true; break;
}
}
/* 3.3.13.2 'Leading zeroes are prohibited' */
integer.append(matches[2].first, matches[2].second);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool
integer::validate(const char* literal) noexcept {
return integer::match(literal);
}
bool
integer::match(const char* literal) noexcept {
return std::regex_match(literal, integer_regex, match_not_null);
}
bool
integer::canonicalize(std::string& literal) {
bool sign{true};
std::string integer;
if (!parse_literal(literal.c_str(), sign, integer)) {
throw std::invalid_argument{literal}; /* invalid literal */
}
char buffer[256] = "";
char* output = buffer;
/* 3.3.13.2 'The preceding optional "+" sign is prohibited' */
if (sign == false) *output++ = '-';
/* 3.3.13.2 'Leading zeroes are prohibited' */
output = std::copy(integer.cbegin(), integer.cend(), output);
*output++ = '\0';
if (literal.compare(buffer) != 0) {
literal.assign(buffer);
return true; /* now in canonical form */
}
return false; /* already in canonical form */
}
integer
integer::parse(const char* literal) {
std::error_condition error;
const auto result = parse(literal, INTMAX_MIN, INTMAX_MAX, error);
if (error) {
if (error == std::errc::invalid_argument) {
throw std::invalid_argument{literal};
}
if (error == std::errc::result_out_of_range) {
if (result.value() == INTMAX_MIN) {
throw std::underflow_error{literal};
}
else {
throw std::overflow_error{literal};
}
}
}
return result;
}
integer
integer::parse(const char* literal,
std::error_condition& error) noexcept {
return parse(literal, INTMAX_MIN, INTMAX_MAX, error);
}
integer
integer::parse(const char* literal,
const integer::value_type min_value,
const integer::value_type max_value,
std::error_condition& error) noexcept {
bool sign{true};
std::string integer;
if (!parse_literal(literal, sign, integer)) {
error = std::errc::invalid_argument;
return {};
}
errno = 0;
auto value = std::strtoimax(integer.c_str(), nullptr, 10);
if (sign == false) {
value = -value;
}
if (errno) {
error.assign(errno, std::generic_category());
}
else if (value < min_value) {
error = std::errc::result_out_of_range;
value = min_value;
}
else if (value > max_value) {
error = std::errc::result_out_of_range;
value = max_value;
}
return value;
}
////////////////////////////////////////////////////////////////////////////////
bool
integer::normalize() noexcept {
return false; /* already in normal form */
}
std::string
integer::literal() const {
return std::to_string(value());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/child_process_launcher.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/thread.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_descriptors.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#if defined(OS_WIN)
#include "chrome/common/sandbox_policy.h"
#elif defined(OS_LINUX)
#include "base/singleton.h"
#include "chrome/browser/crash_handler_host_linux.h"
#include "chrome/browser/zygote_host_linux.h"
#include "chrome/browser/renderer_host/render_sandbox_host_linux.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/mach_broker_mac.h"
#endif
#if defined(OS_POSIX)
#include "base/global_descriptors_posix.h"
#endif
// TODO(eroman): Debugging helper to make strings show up in mini-dumps.
// Remove after done investigating 40447.
class StackString {
public:
explicit StackString(const std::wstring& str) {
length_ = str.size();
memcpy(&buffer_[0], str.data(),
std::min(sizeof(wchar_t) * str.length(),
sizeof(buffer_)));
}
std::wstring ToString() {
return std::wstring(buffer_, length_);
}
~StackString() {
// Hack to make sure compiler doesn't optimize us away.
if (ToString() != ToString())
LOG(INFO) << ToString();
}
private:
wchar_t buffer_[128];
size_t length_;
};
// Having the functionality of ChildProcessLauncher be in an internal
// ref counted object allows us to automatically terminate the process when the
// parent class destructs, while still holding on to state that we need.
class ChildProcessLauncher::Context
: public base::RefCountedThreadSafe<ChildProcessLauncher::Context> {
public:
Context()
: starting_(true)
#if defined(OS_LINUX)
, zygote_(false)
#endif
{
}
void Launch(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
int ipcfd,
#endif
CommandLine* cmd_line,
Client* client) {
client_ = client;
CHECK(ChromeThread::GetCurrentThreadIdentifier(&client_thread_id_));
ChromeThread::PostTask(
ChromeThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableMethod(
this,
&Context::LaunchInternal,
#if defined(OS_WIN)
exposed_dir,
#elif defined(POSIX)
use_zygote,
environ,
ipcfd,
#endif
cmd_line));
}
void ResetClient() {
// No need for locking as this function gets called on the same thread that
// client_ would be used.
CHECK(ChromeThread::CurrentlyOn(client_thread_id_));
client_ = NULL;
}
private:
friend class base::RefCountedThreadSafe<ChildProcessLauncher::Context>;
friend class ChildProcessLauncher;
~Context() {
Terminate();
}
void LaunchInternal(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& env,
int ipcfd,
#endif
CommandLine* cmd_line) {
scoped_ptr<CommandLine> cmd_line_deleter(cmd_line);
base::ProcessHandle handle = base::kNullProcessHandle;
#if defined(OS_WIN)
// TODO(eroman): Remove after done investigating 40447.
StackString stack_command_line(cmd_line->command_line_string());
// This line might crash, since it calls the string copy-constructor:
StackString stack_program(cmd_line->program());
handle = sandbox::StartProcessWithAccess(cmd_line, exposed_dir);
#elif defined(OS_POSIX)
#if defined(OS_LINUX)
if (use_zygote) {
base::GlobalDescriptors::Mapping mapping;
mapping.push_back(std::pair<uint32_t, int>(kPrimaryIPCChannel, ipcfd));
const int crash_signal_fd =
Singleton<RendererCrashHandlerHostLinux>()->GetDeathSignalSocket();
if (crash_signal_fd >= 0) {
mapping.push_back(std::pair<uint32_t, int>(kCrashDumpSignal,
crash_signal_fd));
}
handle = Singleton<ZygoteHost>()->ForkRenderer(cmd_line->argv(), mapping);
} else
// Fall through to the normal posix case below when we're not zygoting.
#endif
{
base::file_handle_mapping_vector fds_to_map;
fds_to_map.push_back(std::make_pair(
ipcfd,
kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
#if defined(OS_LINUX)
// On Linux, we need to add some extra file descriptors for crash handling
// and the sandbox.
bool is_renderer =
cmd_line->GetSwitchValueASCII(switches::kProcessType) ==
switches::kRendererProcess;
bool is_plugin =
cmd_line->GetSwitchValueASCII(switches::kProcessType) ==
switches::kPluginProcess;
if (is_renderer || is_plugin) {
int crash_signal_fd;
if (is_renderer) {
crash_signal_fd = Singleton<RendererCrashHandlerHostLinux>()->
GetDeathSignalSocket();
} else {
crash_signal_fd = Singleton<PluginCrashHandlerHostLinux>()->
GetDeathSignalSocket();
}
if (crash_signal_fd >= 0) {
fds_to_map.push_back(std::make_pair(
crash_signal_fd,
kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor));
}
}
if (is_renderer) {
const int sandbox_fd =
Singleton<RenderSandboxHostLinux>()->GetRendererSocket();
fds_to_map.push_back(std::make_pair(
sandbox_fd,
kSandboxIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
}
#endif // defined(OS_LINUX)
// Actually launch the app.
bool launched;
#if defined(OS_MACOSX)
task_t child_task;
launched = base::LaunchAppAndGetTask(
cmd_line->argv(), env, fds_to_map, false, &child_task, &handle);
if (launched && child_task != MACH_PORT_NULL) {
MachBroker::instance()->RegisterPid(
handle,
MachBroker::MachInfo().SetTask(child_task));
}
#else
launched = base::LaunchApp(cmd_line->argv(), env, fds_to_map,
/* wait= */false, &handle);
#endif
if (!launched)
handle = base::kNullProcessHandle;
}
#endif // else defined(OS_POSIX)
ChromeThread::PostTask(
client_thread_id_, FROM_HERE,
NewRunnableMethod(
this,
&ChildProcessLauncher::Context::Notify,
#if defined(OS_LINUX)
use_zygote,
#endif
handle));
}
void Notify(
#if defined(OS_LINUX)
bool zygote,
#endif
base::ProcessHandle handle) {
starting_ = false;
process_.set_handle(handle);
#if defined(OS_LINUX)
zygote_ = zygote;
#endif
if (client_) {
client_->OnProcessLaunched();
} else {
Terminate();
}
}
void Terminate() {
if (!process_.handle())
return;
// On Posix, EnsureProcessTerminated can lead to 2 seconds of sleep! So
// don't this on the UI/IO threads.
ChromeThread::PostTask(
ChromeThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableFunction(
&ChildProcessLauncher::Context::TerminateInternal,
#if defined(OS_LINUX)
zygote_,
#endif
process_.handle()));
process_.set_handle(base::kNullProcessHandle);
}
static void TerminateInternal(
#if defined(OS_LINUX)
bool zygote,
#endif
base::ProcessHandle handle) {
base::Process process(handle);
// Client has gone away, so just kill the process. Using exit code 0
// means that UMA won't treat this as a crash.
process.Terminate(ResultCodes::NORMAL_EXIT);
// On POSIX, we must additionally reap the child.
#if defined(OS_POSIX)
#if defined(OS_LINUX)
if (zygote) {
// If the renderer was created via a zygote, we have to proxy the reaping
// through the zygote process.
Singleton<ZygoteHost>()->EnsureProcessTerminated(handle);
} else
#endif // OS_LINUX
{
ProcessWatcher::EnsureProcessTerminated(handle);
}
#endif // OS_POSIX
process.Close();
}
Client* client_;
ChromeThread::ID client_thread_id_;
base::Process process_;
bool starting_;
#if defined(OS_LINUX)
bool zygote_;
#endif
};
ChildProcessLauncher::ChildProcessLauncher(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
int ipcfd,
#endif
CommandLine* cmd_line,
Client* client) {
context_ = new Context();
context_->Launch(
#if defined(OS_WIN)
exposed_dir,
#elif defined(OS_POSIX)
use_zygote,
environ,
ipcfd,
#endif
cmd_line,
client);
}
ChildProcessLauncher::~ChildProcessLauncher() {
context_->ResetClient();
}
bool ChildProcessLauncher::IsStarting() {
return context_->starting_;
}
base::ProcessHandle ChildProcessLauncher::GetHandle() {
DCHECK(!context_->starting_);
return context_->process_.handle();
}
bool ChildProcessLauncher::DidProcessCrash() {
bool did_crash, child_exited;
base::ProcessHandle handle = context_->process_.handle();
#if defined(OS_LINUX)
if (context_->zygote_) {
did_crash = Singleton<ZygoteHost>()->DidProcessCrash(handle, &child_exited);
} else
#endif
{
did_crash = base::DidProcessCrash(&child_exited, handle);
}
// POSIX: If the process crashed, then the kernel closed the socket for it
// and so the child has already died by the time we get here. Since
// DidProcessCrash called waitpid with WNOHANG, it'll reap the process.
// However, if DidProcessCrash didn't reap the child, we'll need to in
// Terminate via ProcessWatcher. So we can't close the handle here.
if (child_exited)
context_->process_.Close();
return did_crash;
}
void ChildProcessLauncher::SetProcessBackgrounded(bool background) {
DCHECK(!context_->starting_);
context_->process_.SetProcessBackgrounded(background);
}
<commit_msg>Revert 43821 - Add some temporary instrumentation to help track down a crasher.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/child_process_launcher.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/thread.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/chrome_descriptors.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/result_codes.h"
#if defined(OS_WIN)
#include "chrome/common/sandbox_policy.h"
#elif defined(OS_LINUX)
#include "base/singleton.h"
#include "chrome/browser/crash_handler_host_linux.h"
#include "chrome/browser/zygote_host_linux.h"
#include "chrome/browser/renderer_host/render_sandbox_host_linux.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/mach_broker_mac.h"
#endif
#if defined(OS_POSIX)
#include "base/global_descriptors_posix.h"
#endif
// Having the functionality of ChildProcessLauncher be in an internal
// ref counted object allows us to automatically terminate the process when the
// parent class destructs, while still holding on to state that we need.
class ChildProcessLauncher::Context
: public base::RefCountedThreadSafe<ChildProcessLauncher::Context> {
public:
Context()
: starting_(true)
#if defined(OS_LINUX)
, zygote_(false)
#endif
{
}
void Launch(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
int ipcfd,
#endif
CommandLine* cmd_line,
Client* client) {
client_ = client;
CHECK(ChromeThread::GetCurrentThreadIdentifier(&client_thread_id_));
ChromeThread::PostTask(
ChromeThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableMethod(
this,
&Context::LaunchInternal,
#if defined(OS_WIN)
exposed_dir,
#elif defined(POSIX)
use_zygote,
environ,
ipcfd,
#endif
cmd_line));
}
void ResetClient() {
// No need for locking as this function gets called on the same thread that
// client_ would be used.
CHECK(ChromeThread::CurrentlyOn(client_thread_id_));
client_ = NULL;
}
private:
friend class base::RefCountedThreadSafe<ChildProcessLauncher::Context>;
friend class ChildProcessLauncher;
~Context() {
Terminate();
}
void LaunchInternal(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& env,
int ipcfd,
#endif
CommandLine* cmd_line) {
scoped_ptr<CommandLine> cmd_line_deleter(cmd_line);
base::ProcessHandle handle = base::kNullProcessHandle;
#if defined(OS_WIN)
handle = sandbox::StartProcessWithAccess(cmd_line, exposed_dir);
#elif defined(OS_POSIX)
#if defined(OS_LINUX)
if (use_zygote) {
base::GlobalDescriptors::Mapping mapping;
mapping.push_back(std::pair<uint32_t, int>(kPrimaryIPCChannel, ipcfd));
const int crash_signal_fd =
Singleton<RendererCrashHandlerHostLinux>()->GetDeathSignalSocket();
if (crash_signal_fd >= 0) {
mapping.push_back(std::pair<uint32_t, int>(kCrashDumpSignal,
crash_signal_fd));
}
handle = Singleton<ZygoteHost>()->ForkRenderer(cmd_line->argv(), mapping);
} else
// Fall through to the normal posix case below when we're not zygoting.
#endif
{
base::file_handle_mapping_vector fds_to_map;
fds_to_map.push_back(std::make_pair(
ipcfd,
kPrimaryIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
#if defined(OS_LINUX)
// On Linux, we need to add some extra file descriptors for crash handling
// and the sandbox.
bool is_renderer =
cmd_line->GetSwitchValueASCII(switches::kProcessType) ==
switches::kRendererProcess;
bool is_plugin =
cmd_line->GetSwitchValueASCII(switches::kProcessType) ==
switches::kPluginProcess;
if (is_renderer || is_plugin) {
int crash_signal_fd;
if (is_renderer) {
crash_signal_fd = Singleton<RendererCrashHandlerHostLinux>()->
GetDeathSignalSocket();
} else {
crash_signal_fd = Singleton<PluginCrashHandlerHostLinux>()->
GetDeathSignalSocket();
}
if (crash_signal_fd >= 0) {
fds_to_map.push_back(std::make_pair(
crash_signal_fd,
kCrashDumpSignal + base::GlobalDescriptors::kBaseDescriptor));
}
}
if (is_renderer) {
const int sandbox_fd =
Singleton<RenderSandboxHostLinux>()->GetRendererSocket();
fds_to_map.push_back(std::make_pair(
sandbox_fd,
kSandboxIPCChannel + base::GlobalDescriptors::kBaseDescriptor));
}
#endif // defined(OS_LINUX)
// Actually launch the app.
bool launched;
#if defined(OS_MACOSX)
task_t child_task;
launched = base::LaunchAppAndGetTask(
cmd_line->argv(), env, fds_to_map, false, &child_task, &handle);
if (launched && child_task != MACH_PORT_NULL) {
MachBroker::instance()->RegisterPid(
handle,
MachBroker::MachInfo().SetTask(child_task));
}
#else
launched = base::LaunchApp(cmd_line->argv(), env, fds_to_map,
/* wait= */false, &handle);
#endif
if (!launched)
handle = base::kNullProcessHandle;
}
#endif // else defined(OS_POSIX)
ChromeThread::PostTask(
client_thread_id_, FROM_HERE,
NewRunnableMethod(
this,
&ChildProcessLauncher::Context::Notify,
#if defined(OS_LINUX)
use_zygote,
#endif
handle));
}
void Notify(
#if defined(OS_LINUX)
bool zygote,
#endif
base::ProcessHandle handle) {
starting_ = false;
process_.set_handle(handle);
#if defined(OS_LINUX)
zygote_ = zygote;
#endif
if (client_) {
client_->OnProcessLaunched();
} else {
Terminate();
}
}
void Terminate() {
if (!process_.handle())
return;
// On Posix, EnsureProcessTerminated can lead to 2 seconds of sleep! So
// don't this on the UI/IO threads.
ChromeThread::PostTask(
ChromeThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableFunction(
&ChildProcessLauncher::Context::TerminateInternal,
#if defined(OS_LINUX)
zygote_,
#endif
process_.handle()));
process_.set_handle(base::kNullProcessHandle);
}
static void TerminateInternal(
#if defined(OS_LINUX)
bool zygote,
#endif
base::ProcessHandle handle) {
base::Process process(handle);
// Client has gone away, so just kill the process. Using exit code 0
// means that UMA won't treat this as a crash.
process.Terminate(ResultCodes::NORMAL_EXIT);
// On POSIX, we must additionally reap the child.
#if defined(OS_POSIX)
#if defined(OS_LINUX)
if (zygote) {
// If the renderer was created via a zygote, we have to proxy the reaping
// through the zygote process.
Singleton<ZygoteHost>()->EnsureProcessTerminated(handle);
} else
#endif // OS_LINUX
{
ProcessWatcher::EnsureProcessTerminated(handle);
}
#endif // OS_POSIX
process.Close();
}
Client* client_;
ChromeThread::ID client_thread_id_;
base::Process process_;
bool starting_;
#if defined(OS_LINUX)
bool zygote_;
#endif
};
ChildProcessLauncher::ChildProcessLauncher(
#if defined(OS_WIN)
const FilePath& exposed_dir,
#elif defined(OS_POSIX)
bool use_zygote,
const base::environment_vector& environ,
int ipcfd,
#endif
CommandLine* cmd_line,
Client* client) {
context_ = new Context();
context_->Launch(
#if defined(OS_WIN)
exposed_dir,
#elif defined(OS_POSIX)
use_zygote,
environ,
ipcfd,
#endif
cmd_line,
client);
}
ChildProcessLauncher::~ChildProcessLauncher() {
context_->ResetClient();
}
bool ChildProcessLauncher::IsStarting() {
return context_->starting_;
}
base::ProcessHandle ChildProcessLauncher::GetHandle() {
DCHECK(!context_->starting_);
return context_->process_.handle();
}
bool ChildProcessLauncher::DidProcessCrash() {
bool did_crash, child_exited;
base::ProcessHandle handle = context_->process_.handle();
#if defined(OS_LINUX)
if (context_->zygote_) {
did_crash = Singleton<ZygoteHost>()->DidProcessCrash(handle, &child_exited);
} else
#endif
{
did_crash = base::DidProcessCrash(&child_exited, handle);
}
// POSIX: If the process crashed, then the kernel closed the socket for it
// and so the child has already died by the time we get here. Since
// DidProcessCrash called waitpid with WNOHANG, it'll reap the process.
// However, if DidProcessCrash didn't reap the child, we'll need to in
// Terminate via ProcessWatcher. So we can't close the handle here.
if (child_exited)
context_->process_.Close();
return did_crash;
}
void ChildProcessLauncher::SetProcessBackgrounded(bool background) {
DCHECK(!context_->starting_);
context_->process_.SetProcessBackgrounded(background);
}
<|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/dom_ui/dom_ui_contents.h"
#include "chrome/browser/debugger/debugger_contents.h"
#include "chrome/browser/dom_ui/dev_tools_ui.h"
#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/web_contents_view.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";
// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";
///////////////////////////////////////////////////////////////////////////////
// FavIconSource
FavIconSource::FavIconSource(Profile* profile)
: DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}
void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = hs->GetFavIcon(
GURL(path.substr(8)),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
} else {
handle = hs->GetFavIconForURL(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
}
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
void FavIconSource::OnFavIconDataAvailable(
HistoryService::Handle request_handle,
bool know_favicon,
scoped_refptr<RefCountedBytes> data,
bool expired,
GURL icon_url) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
if (know_favicon && data.get() && !data->data.empty()) {
// Forward the data along to the networking system.
SendResponse(request_id, data);
} else {
if (!default_favicon_.get()) {
default_favicon_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_FAVICON, &default_favicon_->data);
}
SendResponse(request_id, default_favicon_);
}
}
///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource
ThumbnailSource::ThumbnailSource(Profile* profile)
: DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}
void ThumbnailSource::StartDataRequest(const std::string& path,
int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle = hs->GetPageThumbnail(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
// Tell the caller that no thumbnail is available.
SendResponse(request_id, NULL);
}
}
void ThumbnailSource::OnThumbnailDataAvailable(
HistoryService::Handle request_handle,
scoped_refptr<RefCountedBytes> data) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
// Forward the data along to the networking system.
if (data.get() && !data->data.empty()) {
SendResponse(request_id, data);
} else {
if (!default_thumbnail_.get()) {
default_thumbnail_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
}
SendResponse(request_id, default_thumbnail_);
}
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIContents
// This is the top-level URL handler for chrome-ui: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome-ui:// HTML source
// at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
TabContentsType* result_type) {
// chrome-internal is a scheme we used to use for the new tab page.
if (!url->SchemeIs(chrome::kChromeUIScheme) &&
!url->SchemeIs(chrome::kChromeInternalScheme))
return false;
*result_type = TAB_CONTENTS_DOM_UI;
return true;
}
DOMUIContents::DOMUIContents(Profile* profile,
SiteInstance* instance,
RenderViewHostFactory* render_view_factory)
: WebContents(profile,
instance,
render_view_factory,
MSG_ROUTING_NONE,
NULL),
current_ui_(NULL),
current_url_(GURL()) {
set_type(TAB_CONTENTS_DOM_UI);
}
DOMUIContents::~DOMUIContents() {
if (current_ui_)
delete current_ui_;
}
bool DOMUIContents::CreateRenderViewForRenderManager(
RenderViewHost* render_view_host) {
// Be sure to enable DOM UI bindings on the RenderViewHost before
// CreateRenderView is called. Since a cross-site transition may be
// involved, this may or may not be the same RenderViewHost that we had when
// we were created.
render_view_host->AllowDOMUIBindings();
return WebContents::CreateRenderViewForRenderManager(render_view_host);
}
WebPreferences DOMUIContents::GetWebkitPrefs() {
// Get the users preferences then force image loading to always be on.
WebPreferences web_prefs = WebContents::GetWebkitPrefs();
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
return web_prefs;
}
void DOMUIContents::RenderViewCreated(RenderViewHost* render_view_host) {
if (current_ui_)
current_ui_->RenderViewCreated(render_view_host);
}
bool DOMUIContents::ShouldDisplayFavIcon() {
if (InitCurrentUI(false))
return current_ui_->ShouldDisplayFavIcon();
return true;
}
bool DOMUIContents::IsBookmarkBarAlwaysVisible() {
if (InitCurrentUI(false))
return current_ui_->IsBookmarkBarAlwaysVisible();
return false;
}
void DOMUIContents::SetInitialFocus() {
if (InitCurrentUI(false))
current_ui_->SetInitialFocus();
else
current_ui_->get_contents()->view()->SetInitialFocus();
}
const string16& DOMUIContents::GetTitle() const {
// Workaround for new tab page - we may be asked for a title before
// the content is ready, and we don't even want to display a 'loading...'
// message, so we force it here.
if (controller()->GetActiveEntry() &&
controller()->GetActiveEntry()->url().host() ==
NewTabUI::GetBaseURL().host()) {
static string16* newtab_title = new string16(WideToUTF16Hack(
l10n_util::GetString(IDS_NEW_TAB_TITLE)));
return *newtab_title;
}
return WebContents::GetTitle();
}
bool DOMUIContents::ShouldDisplayURL() {
if (InitCurrentUI(false))
return current_ui_->ShouldDisplayURL();
return TabContents::ShouldDisplayURL();
}
void DOMUIContents::RequestOpenURL(const GURL& url, const GURL& referrer,
WindowOpenDisposition disposition) {
if (InitCurrentUI(false))
current_ui_->RequestOpenURL(url, referrer, disposition);
else
WebContents::RequestOpenURL(url, referrer, disposition);
}
bool DOMUIContents::NavigateToPendingEntry(bool reload) {
InitCurrentUI(reload);
// Let WebContents do whatever it's meant to do.
return WebContents::NavigateToPendingEntry(reload);
}
void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
const std::string& content) {
DCHECK(current_ui_);
current_ui_->ProcessDOMUIMessage(message, content);
}
bool DOMUIContents::InitCurrentUI(bool reload) {
if (!controller()->GetActiveEntry())
return false;
GURL url = controller()->GetActiveEntry()->url();
if (url.is_empty() || !url.is_valid())
return false;
if (reload || url.host() != current_url_.host()) {
// Shut down our existing DOMUI.
delete current_ui_;
current_ui_ = NULL;
// Set up a new DOMUI.
current_ui_ = GetDOMUIForURL(url);
if (current_ui_) {
current_ui_->Init();
current_url_ = url;
return true;
}
} else if (current_ui_) {
return true;
}
return false;
}
// static
const std::string DOMUIContents::GetScheme() {
return chrome::kChromeUIScheme;
}
DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
if (url.host() == NewTabUI::GetBaseURL().host() ||
url.SchemeIs(chrome::kChromeInternalScheme)) {
return new NewTabUI(this);
}
if (url.host() == HistoryUI::GetBaseURL().host()) {
return new HistoryUI(this);
}
if (url.host() == DownloadsUI::GetBaseURL().host()) {
return new DownloadsUI(this);
}
#if defined(OS_WIN)
// TODO(port): include this once these are converted to HTML
if (url.host() == ExtensionsUI::GetBaseURL().host()) {
return new ExtensionsUI(this);
}
if (url.host() == DebuggerContents::GetBaseURL().host()) {
return new DebuggerContents(this);
}
if (url.host() == DevToolsUI::GetBaseURL().host()) {
return new DevToolsUI(this);
}
#else
NOTIMPLEMENTED();
#endif
return NULL;
}
<commit_msg>Fix a crash when with chrome-ui://about/" or anything invalid<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/dom_ui/dom_ui_contents.h"
#include "chrome/browser/debugger/debugger_contents.h"
#include "chrome/browser/dom_ui/dev_tools_ui.h"
#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/web_contents_view.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";
// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";
///////////////////////////////////////////////////////////////////////////////
// FavIconSource
FavIconSource::FavIconSource(Profile* profile)
: DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}
void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = hs->GetFavIcon(
GURL(path.substr(8)),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
} else {
handle = hs->GetFavIconForURL(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
}
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
void FavIconSource::OnFavIconDataAvailable(
HistoryService::Handle request_handle,
bool know_favicon,
scoped_refptr<RefCountedBytes> data,
bool expired,
GURL icon_url) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
if (know_favicon && data.get() && !data->data.empty()) {
// Forward the data along to the networking system.
SendResponse(request_id, data);
} else {
if (!default_favicon_.get()) {
default_favicon_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_FAVICON, &default_favicon_->data);
}
SendResponse(request_id, default_favicon_);
}
}
///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource
ThumbnailSource::ThumbnailSource(Profile* profile)
: DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}
void ThumbnailSource::StartDataRequest(const std::string& path,
int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle = hs->GetPageThumbnail(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
// Tell the caller that no thumbnail is available.
SendResponse(request_id, NULL);
}
}
void ThumbnailSource::OnThumbnailDataAvailable(
HistoryService::Handle request_handle,
scoped_refptr<RefCountedBytes> data) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
// Forward the data along to the networking system.
if (data.get() && !data->data.empty()) {
SendResponse(request_id, data);
} else {
if (!default_thumbnail_.get()) {
default_thumbnail_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
}
SendResponse(request_id, default_thumbnail_);
}
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIContents
// This is the top-level URL handler for chrome-ui: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome-ui:// HTML source
// at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
TabContentsType* result_type) {
// chrome-internal is a scheme we used to use for the new tab page.
if (!url->SchemeIs(chrome::kChromeUIScheme) &&
!url->SchemeIs(chrome::kChromeInternalScheme))
return false;
*result_type = TAB_CONTENTS_DOM_UI;
return true;
}
DOMUIContents::DOMUIContents(Profile* profile,
SiteInstance* instance,
RenderViewHostFactory* render_view_factory)
: WebContents(profile,
instance,
render_view_factory,
MSG_ROUTING_NONE,
NULL),
current_ui_(NULL),
current_url_(GURL()) {
set_type(TAB_CONTENTS_DOM_UI);
}
DOMUIContents::~DOMUIContents() {
if (current_ui_)
delete current_ui_;
}
bool DOMUIContents::CreateRenderViewForRenderManager(
RenderViewHost* render_view_host) {
// Be sure to enable DOM UI bindings on the RenderViewHost before
// CreateRenderView is called. Since a cross-site transition may be
// involved, this may or may not be the same RenderViewHost that we had when
// we were created.
render_view_host->AllowDOMUIBindings();
return WebContents::CreateRenderViewForRenderManager(render_view_host);
}
WebPreferences DOMUIContents::GetWebkitPrefs() {
// Get the users preferences then force image loading to always be on.
WebPreferences web_prefs = WebContents::GetWebkitPrefs();
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
return web_prefs;
}
void DOMUIContents::RenderViewCreated(RenderViewHost* render_view_host) {
if (current_ui_)
current_ui_->RenderViewCreated(render_view_host);
}
bool DOMUIContents::ShouldDisplayFavIcon() {
if (InitCurrentUI(false))
return current_ui_->ShouldDisplayFavIcon();
return true;
}
bool DOMUIContents::IsBookmarkBarAlwaysVisible() {
if (InitCurrentUI(false))
return current_ui_->IsBookmarkBarAlwaysVisible();
return false;
}
void DOMUIContents::SetInitialFocus() {
if (InitCurrentUI(false))
current_ui_->SetInitialFocus();
else if (current_ui_)
current_ui_->get_contents()->view()->SetInitialFocus();
}
const string16& DOMUIContents::GetTitle() const {
// Workaround for new tab page - we may be asked for a title before
// the content is ready, and we don't even want to display a 'loading...'
// message, so we force it here.
if (controller()->GetActiveEntry() &&
controller()->GetActiveEntry()->url().host() ==
NewTabUI::GetBaseURL().host()) {
static string16* newtab_title = new string16(WideToUTF16Hack(
l10n_util::GetString(IDS_NEW_TAB_TITLE)));
return *newtab_title;
}
return WebContents::GetTitle();
}
bool DOMUIContents::ShouldDisplayURL() {
if (InitCurrentUI(false))
return current_ui_->ShouldDisplayURL();
return TabContents::ShouldDisplayURL();
}
void DOMUIContents::RequestOpenURL(const GURL& url, const GURL& referrer,
WindowOpenDisposition disposition) {
if (InitCurrentUI(false))
current_ui_->RequestOpenURL(url, referrer, disposition);
else
WebContents::RequestOpenURL(url, referrer, disposition);
}
bool DOMUIContents::NavigateToPendingEntry(bool reload) {
InitCurrentUI(reload);
// Let WebContents do whatever it's meant to do.
return WebContents::NavigateToPendingEntry(reload);
}
void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
const std::string& content) {
DCHECK(current_ui_);
current_ui_->ProcessDOMUIMessage(message, content);
}
bool DOMUIContents::InitCurrentUI(bool reload) {
if (!controller()->GetActiveEntry())
return false;
GURL url = controller()->GetActiveEntry()->url();
if (url.is_empty() || !url.is_valid())
return false;
if (reload || url.host() != current_url_.host()) {
// Shut down our existing DOMUI.
delete current_ui_;
current_ui_ = NULL;
// Set up a new DOMUI.
current_ui_ = GetDOMUIForURL(url);
if (current_ui_) {
current_ui_->Init();
current_url_ = url;
}
}
if (current_ui_)
return true;
return false;
}
// static
const std::string DOMUIContents::GetScheme() {
return chrome::kChromeUIScheme;
}
DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
if (url.host() == NewTabUI::GetBaseURL().host() ||
url.SchemeIs(chrome::kChromeInternalScheme)) {
return new NewTabUI(this);
}
if (url.host() == HistoryUI::GetBaseURL().host()) {
return new HistoryUI(this);
}
if (url.host() == DownloadsUI::GetBaseURL().host()) {
return new DownloadsUI(this);
}
#if defined(OS_WIN)
// TODO(port): include this once these are converted to HTML
if (url.host() == ExtensionsUI::GetBaseURL().host()) {
return new ExtensionsUI(this);
}
if (url.host() == DebuggerContents::GetBaseURL().host()) {
return new DebuggerContents(this);
}
if (url.host() == DevToolsUI::GetBaseURL().host()) {
return new DevToolsUI(this);
}
#else
NOTIMPLEMENTED();
#endif
return NULL;
}
<|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/gtk/download_item_drag.h"
#include "app/gfx/gtk_util.h"
#include "app/gtk_dnd_util.h"
#include "base/string_util.h"
#include "chrome/browser/download/download_manager.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace {
const int kCodeMask = GtkDndUtil::TEXT_URI_LIST |
GtkDndUtil::CHROME_NAMED_URL;
const GdkDragAction kDragAction = GDK_ACTION_COPY;
void OnDragDataGet(GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data,
guint target_type, guint time,
DownloadItem* download_item) {
GURL url = net::FilePathToFileURL(download_item->full_path());
GtkDndUtil::WriteURLWithName(selection_data, url,
UTF8ToUTF16(download_item->GetFileName().value()), target_type);
}
} // namespace
// static
void DownloadItemDrag::SetSource(GtkWidget* widget, DownloadItem* item) {
gtk_drag_source_set(widget, GDK_BUTTON1_MASK, NULL, 0,
kDragAction);
GtkDndUtil::SetSourceTargetListFromCodeMask(widget, kCodeMask);
g_signal_connect(widget, "drag-data-get",
G_CALLBACK(OnDragDataGet), item);
}
// static
void DownloadItemDrag::BeginDrag(const DownloadItem* item, SkBitmap* icon) {
new DownloadItemDrag(item, icon);
}
DownloadItemDrag::DownloadItemDrag(const DownloadItem* item,
SkBitmap* icon)
: drag_widget_(gtk_invisible_new()),
pixbuf_(gfx::GdkPixbufFromSkBitmap(icon)) {
g_object_ref_sink(drag_widget_);
g_signal_connect(drag_widget_, "drag-data-get",
G_CALLBACK(OnDragDataGet), const_cast<DownloadItem*>(item));
g_signal_connect(drag_widget_, "drag-begin",
G_CALLBACK(OnDragBegin), this);
g_signal_connect(drag_widget_, "drag-end",
G_CALLBACK(OnDragEnd), this);
GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(kCodeMask);
gtk_drag_begin(drag_widget_, list, kDragAction, 1, gtk_get_current_event());
gtk_target_list_unref(list);
}
DownloadItemDrag::~DownloadItemDrag() {
g_object_unref(pixbuf_);
g_object_unref(drag_widget_);
}
// static
void DownloadItemDrag::OnDragBegin(GtkWidget* widget,
GdkDragContext* drag_context,
DownloadItemDrag* drag) {
gtk_drag_set_icon_pixbuf(drag_context, drag->pixbuf_, 0, 0);
}
// static
void DownloadItemDrag::OnDragEnd(GtkWidget* widget,
GdkDragContext* drag_context,
DownloadItemDrag* drag) {
delete drag;
}
<commit_msg>GTK: fix hypothetical leak.<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/gtk/download_item_drag.h"
#include "app/gfx/gtk_util.h"
#include "app/gtk_dnd_util.h"
#include "base/string_util.h"
#include "chrome/browser/download/download_manager.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace {
const int kCodeMask = GtkDndUtil::TEXT_URI_LIST |
GtkDndUtil::CHROME_NAMED_URL;
const GdkDragAction kDragAction = GDK_ACTION_COPY;
void OnDragDataGet(GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data,
guint target_type, guint time,
DownloadItem* download_item) {
GURL url = net::FilePathToFileURL(download_item->full_path());
GtkDndUtil::WriteURLWithName(selection_data, url,
UTF8ToUTF16(download_item->GetFileName().value()), target_type);
}
} // namespace
// static
void DownloadItemDrag::SetSource(GtkWidget* widget, DownloadItem* item) {
gtk_drag_source_set(widget, GDK_BUTTON1_MASK, NULL, 0,
kDragAction);
GtkDndUtil::SetSourceTargetListFromCodeMask(widget, kCodeMask);
g_signal_connect(widget, "drag-data-get",
G_CALLBACK(OnDragDataGet), item);
}
// static
void DownloadItemDrag::BeginDrag(const DownloadItem* item, SkBitmap* icon) {
new DownloadItemDrag(item, icon);
}
DownloadItemDrag::DownloadItemDrag(const DownloadItem* item,
SkBitmap* icon)
: drag_widget_(gtk_invisible_new()),
pixbuf_(gfx::GdkPixbufFromSkBitmap(icon)) {
g_object_ref_sink(drag_widget_);
g_signal_connect(drag_widget_, "drag-data-get",
G_CALLBACK(OnDragDataGet), const_cast<DownloadItem*>(item));
g_signal_connect(drag_widget_, "drag-begin",
G_CALLBACK(OnDragBegin), this);
g_signal_connect(drag_widget_, "drag-end",
G_CALLBACK(OnDragEnd), this);
GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(kCodeMask);
GdkEvent* event = gtk_get_current_event();
gtk_drag_begin(drag_widget_, list, kDragAction, 1, event);
if (event)
gdk_event_free(event);
gtk_target_list_unref(list);
}
DownloadItemDrag::~DownloadItemDrag() {
g_object_unref(pixbuf_);
g_object_unref(drag_widget_);
}
// static
void DownloadItemDrag::OnDragBegin(GtkWidget* widget,
GdkDragContext* drag_context,
DownloadItemDrag* drag) {
gtk_drag_set_icon_pixbuf(drag_context, drag->pixbuf_, 0, 0);
}
// static
void DownloadItemDrag::OnDragEnd(GtkWidget* widget,
GdkDragContext* drag_context,
DownloadItemDrag* drag) {
delete drag;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/adjacent_difference.h>
#include <thrust/gather.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/system/detail/internal/decompose.h>
#include <thrust/system/cuda/detail/default_decomposition.h>
#include <thrust/system/cuda/detail/detail/launch_closure.h>
#include <thrust/system/cuda/detail/detail/launch_calculator.h>
#include <thrust/system/cuda/detail/execution_policy.h>
#include <thrust/detail/seq.h>
namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace adjacent_difference_detail
{
template<typename Decomposition>
struct last_index_in_each_interval : public thrust::unary_function<typename Decomposition::index_type, typename Decomposition::index_type>
{
typedef typename Decomposition::index_type index_type;
Decomposition decomp;
__host__ __device__
last_index_in_each_interval(Decomposition decomp) : decomp(decomp) {}
__host__ __device__
index_type operator()(index_type interval)
{
return decomp[interval].end() - 1;
}
};
template <typename InputIterator1,
typename InputIterator2,
typename OutputIterator,
typename BinaryFunction,
typename Decomposition,
typename Context>
struct adjacent_difference_closure
{
InputIterator1 input;
InputIterator2 input_copy;
OutputIterator output;
BinaryFunction binary_op;
Decomposition decomp;
Context context;
typedef Context context_type;
__host__ __device__
adjacent_difference_closure(InputIterator1 input,
InputIterator2 input_copy,
OutputIterator output,
BinaryFunction binary_op,
Decomposition decomp,
Context context = Context())
: input(input), input_copy(input_copy), output(output), binary_op(binary_op), decomp(decomp), context(context) {}
__device__ __thrust_forceinline__
void operator()(void)
{
typedef typename thrust::iterator_value<InputIterator1>::type InputType;
typedef typename Decomposition::index_type index_type;
// this block processes results in [range.begin(), range.end())
thrust::system::detail::internal::index_range<index_type> range = decomp[context.block_index()];
input_copy += context.block_index() - 1;
// prime the temp values for all threads so we don't need to launch a default constructor
InputType next_left = (context.block_index() == 0) ? *input : *input_copy;
index_type base = range.begin();
index_type i = range.begin() + context.thread_index();
if(i < range.end())
{
if(context.thread_index() > 0)
{
InputIterator1 temp = input + (i - 1);
next_left = *temp;
}
}
input += i;
output += i;
while(base < range.end())
{
InputType curr_left = next_left;
if(i + context.block_dimension() < range.end())
{
InputIterator1 temp = input + (context.block_dimension() - 1);
next_left = *temp;
}
context.barrier();
if(i < range.end())
{
if(i == 0)
{
*output = *input;
}
else
{
InputType x = *input;
*output = binary_op(x, curr_left);
}
}
i += context.block_dimension();
base += context.block_dimension();
input += context.block_dimension();
output += context.block_dimension();
}
}
};
template<typename DerivedPolicy,
typename InputIterator,
typename OutputIterator,
typename BinaryFunction>
__host__ __device__
OutputIterator adjacent_difference(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
typedef typename thrust::iterator_value<InputIterator>::type InputType;
typedef typename thrust::iterator_difference<InputIterator>::type IndexType;
typedef thrust::system::detail::internal::uniform_decomposition<IndexType> Decomposition;
IndexType n = last - first;
if(n == 0)
{
return result;
}
Decomposition decomp = default_decomposition(last - first);
// allocate temporary storage
thrust::detail::temporary_array<InputType,DerivedPolicy> temp(exec, decomp.size() - 1);
// gather last value in each interval
last_index_in_each_interval<Decomposition> unary_op(decomp);
thrust::gather(exec,
thrust::make_transform_iterator(thrust::counting_iterator<IndexType>(0), unary_op),
thrust::make_transform_iterator(thrust::counting_iterator<IndexType>(0), unary_op) + (decomp.size() - 1),
first,
temp.begin());
typedef typename thrust::detail::temporary_array<InputType,DerivedPolicy>::iterator InputIterator2;
typedef detail::blocked_thread_array Context;
typedef adjacent_difference_closure<InputIterator,InputIterator2,OutputIterator,BinaryFunction,Decomposition,Context> Closure;
Closure closure(first, temp.begin(), result, binary_op, decomp);
detail::launch_closure(exec, closure, decomp.size());
return result + n;
} // end adjacent_difference()
} // end namespace adjacent_difference_detail
__THRUST_DISABLE_MSVC_POSSIBLE_LOSS_OF_DATA_WARNING_BEGIN
template<typename DerivedPolicy,
typename InputIterator,
typename OutputIterator,
typename BinaryFunction>
__host__ __device__
OutputIterator adjacent_difference(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
struct workaround
{
__host__ __device__
static OutputIterator parallel_path(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
return thrust::system::cuda::detail::adjacent_difference_detail::adjacent_difference(exec, first, last, result, binary_op);
}
__host__ __device__
static OutputIterator sequential_path(execution_policy<DerivedPolicy> &,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
return thrust::adjacent_difference(thrust::seq, first, last, result, binary_op);
}
};
#if __BULK_HAS_CUDART__
return workaround::parallel_path(exec, first, last, result, binary_op);
#else
return workaround::sequential_path(exec, first, last, result, binary_op);
#endif
}
__THRUST_DISABLE_MSVC_POSSIBLE_LOSS_OF_DATA_WARNING_END
} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust
<commit_msg>my-iss-574-fix<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/detail/config.h>
#include <thrust/adjacent_difference.h>
#include <thrust/gather.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/system/detail/internal/decompose.h>
#include <thrust/system/cuda/detail/default_decomposition.h>
#include <thrust/system/cuda/detail/detail/launch_closure.h>
#include <thrust/system/cuda/detail/detail/launch_calculator.h>
#include <thrust/system/cuda/detail/execution_policy.h>
#include <thrust/detail/seq.h>
namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace adjacent_difference_detail
{
template<typename Decomposition>
struct last_index_in_each_interval : public thrust::unary_function<typename Decomposition::index_type, typename Decomposition::index_type>
{
typedef typename Decomposition::index_type index_type;
Decomposition decomp;
__host__ __device__
last_index_in_each_interval(Decomposition decomp) : decomp(decomp) {}
__host__ __device__
index_type operator()(index_type interval)
{
return decomp[interval].end() - 1;
}
};
template <typename InputIterator1,
typename InputIterator2,
typename OutputIterator,
typename BinaryFunction,
typename Decomposition,
typename Context>
struct adjacent_difference_closure
{
InputIterator1 input;
InputIterator2 input_copy;
OutputIterator output;
BinaryFunction binary_op;
Decomposition decomp;
Context context;
typedef Context context_type;
__host__ __device__
adjacent_difference_closure(InputIterator1 input,
InputIterator2 input_copy,
OutputIterator output,
BinaryFunction binary_op,
Decomposition decomp,
Context context = Context())
: input(input), input_copy(input_copy), output(output), binary_op(binary_op), decomp(decomp), context(context) {}
__device__ __thrust_forceinline__
void operator()(void)
{
typedef typename thrust::iterator_value<InputIterator1>::type InputType;
typedef typename Decomposition::index_type index_type;
// this block processes results in [range.begin(), range.end())
thrust::system::detail::internal::index_range<index_type> range = decomp[context.block_index()];
input_copy += context.block_index() - 1;
// prime the temp values for all threads so we don't need to launch a default constructor
InputType next_left = (context.block_index() == 0) ? thrust::raw_reference_cast(*input) : thrust::raw_reference_cast(*input_copy);
index_type base = range.begin();
index_type i = range.begin() + context.thread_index();
if(i < range.end())
{
if(context.thread_index() > 0)
{
InputIterator1 temp = input + (i - 1);
next_left = *temp;
}
}
input += i;
output += i;
while(base < range.end())
{
InputType curr_left = next_left;
if(i + context.block_dimension() < range.end())
{
InputIterator1 temp = input + (context.block_dimension() - 1);
next_left = *temp;
}
context.barrier();
if(i < range.end())
{
if(i == 0)
{
*output = *input;
}
else
{
InputType x = *input;
*output = binary_op(x, curr_left);
}
}
i += context.block_dimension();
base += context.block_dimension();
input += context.block_dimension();
output += context.block_dimension();
}
}
};
template<typename DerivedPolicy,
typename InputIterator,
typename OutputIterator,
typename BinaryFunction>
__host__ __device__
OutputIterator adjacent_difference(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
typedef typename thrust::iterator_value<InputIterator>::type InputType;
typedef typename thrust::iterator_difference<InputIterator>::type IndexType;
typedef thrust::system::detail::internal::uniform_decomposition<IndexType> Decomposition;
IndexType n = last - first;
if(n == 0)
{
return result;
}
Decomposition decomp = default_decomposition(last - first);
// allocate temporary storage
thrust::detail::temporary_array<InputType,DerivedPolicy> temp(exec, decomp.size() - 1);
// gather last value in each interval
last_index_in_each_interval<Decomposition> unary_op(decomp);
thrust::gather(exec,
thrust::make_transform_iterator(thrust::counting_iterator<IndexType>(0), unary_op),
thrust::make_transform_iterator(thrust::counting_iterator<IndexType>(0), unary_op) + (decomp.size() - 1),
first,
temp.begin());
typedef typename thrust::detail::temporary_array<InputType,DerivedPolicy>::iterator InputIterator2;
typedef detail::blocked_thread_array Context;
typedef adjacent_difference_closure<InputIterator,InputIterator2,OutputIterator,BinaryFunction,Decomposition,Context> Closure;
Closure closure(first, temp.begin(), result, binary_op, decomp);
detail::launch_closure(exec, closure, decomp.size());
return result + n;
} // end adjacent_difference()
} // end namespace adjacent_difference_detail
__THRUST_DISABLE_MSVC_POSSIBLE_LOSS_OF_DATA_WARNING_BEGIN
template<typename DerivedPolicy,
typename InputIterator,
typename OutputIterator,
typename BinaryFunction>
__host__ __device__
OutputIterator adjacent_difference(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
struct workaround
{
__host__ __device__
static OutputIterator parallel_path(execution_policy<DerivedPolicy> &exec,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
return thrust::system::cuda::detail::adjacent_difference_detail::adjacent_difference(exec, first, last, result, binary_op);
}
__host__ __device__
static OutputIterator sequential_path(execution_policy<DerivedPolicy> &,
InputIterator first, InputIterator last,
OutputIterator result,
BinaryFunction binary_op)
{
return thrust::adjacent_difference(thrust::seq, first, last, result, binary_op);
}
};
#if __BULK_HAS_CUDART__
return workaround::parallel_path(exec, first, last, result, binary_op);
#else
return workaround::sequential_path(exec, first, last, result, binary_op);
#endif
}
__THRUST_DISABLE_MSVC_POSSIBLE_LOSS_OF_DATA_WARNING_END
} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust
<|endoftext|>
|
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2014
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#include <array>
#include <vector>
template<typename DomainType, typename MappedType>
class interval_tree {
public:
typedef std::pair<interval, MappedType> value_type;
struct interval {
std::array<DomainType, 2> bounds;
};
private:
struct node {
bool splits_based_on_which_bound;
size_t num_descendant_intervals;
// only for non leaves
DomainType child_separator;
std::array<std::unique_ptr<node>, 2> children; // the first has the lower values, the second the higher values
// only for leaves
std::unordered_map<interval, MappedType> intervals_here;
};
std::unique_ptr<node> root;
public:
template<typename Ordering>
class iterator {
public:
iterator():bound_minima_exist({{false,false}}),bound_maxima_exist({{false,false}}),min_length_exists(false){}
value_type& operator*() const {
caller_error_if(queue_.empty(), "can't dereference an empty iterator");
return *queue.front().value;
}
value_type* operator->() const {
caller_error_if(queue_.empty(), "can't dereference an empty iterator");
return queue.front().value;
}
value_type* operator++(int) {
value_type* result = queue.front().value;
++*this;
return result;
}
iterator& operator++() {
queue.pop();
advance_to_a_returnable();
return *this;
}
bool operator==(iterator const& other) const {
if (queue.empty()) { return other.queue.empty(); }
if (other.queue.empty()) { return false; }
return queue.front() == other.queue.front();
}
bool operator!=(iterator const& other) const { return !(*this == other); }
private:
std::array<bool, 2> bound_minima_exist;
std::array<bool, 2> bound_maxima_exist;
bool min_length_exists;
struct queue_entry {
node* n;
value_type* value;
std::array<interval, 2> possible_bounds;
};
std::priority_queue<queue_value_type_, std::vector<queue_value_type_>, reverse_first_ordering<CostOrdering, queue_value_type_> > queue_type_;
void queue_root(node* root) {
queue_entry e;
e.n = root;
if (!e.n) return;
e.possible_bounds[0][0] = neginf;
e.possible_bounds[0][1] = inf;
e.possible_bounds[1][0] = neginf;
e.possible_bounds[1][1] = inf;
queue.push(e);
}
void queue_node(queue_entry const& parent, bool use_second_child) {
queue_entry e = parent;
e.n = parent.n->children[use_second_child].get();
if (!e.n) return;
if (bound_minima_exist[parent.n->splits_based_on_which_bound] && use_second_child && (parent.n->child_separator < bound_minima[parent.n->splits_based_on_which_bound])) return;
if (bound_maxima_exist[parent.n->splits_based_on_which_bound] && !use_second_child && (parent.n->child_separator > bound_maxima[parent.n->splits_based_on_which_bound])) return;
e.possible_bounds[parent.n->splits_based_on_which_bound].bounds[!use_second_child] = parent.n->child_separator;
if (min_length_exists && interval(e.possible_bounds[0].bounds[0], e.possible_bounds[1].bounds[1]).length_less_than(min_length)) return;
queue.push(e);
}
void queue_value(node* n, value_type* value) {
queue_entry e;
e.n = n;
e.value = value;
std::array<DomainType, 2> const& bounds = value->second.bounds;
if (bound_minima_exist[0] && (bounds[0] < bound_minima[0])) return;
if (bound_maxima_exist[0] && (bounds[0] > bound_maxima[0])) return;
if (bound_minima_exist[1] && (bounds[1] < bound_minima[1])) return;
if (bound_maxima_exist[1] && (bounds[1] > bound_maxima[1])) return;
if (min_length_exists && value->second.length_less_than(min_length)) return;
queue.push(e);
}
void advance_to_a_returnable() {
while (!queue.front().value) {
queue_node(queue.front(), 0);
queue_node(queue.front(), 1);
for (value_type& v : queue.front().n->intervals_here) {
queue_value(queue.front().n, &v);
}
queue.pop();
if (queue.empty()) { return; }
}
}
friend interval_tree;
};
iterator find_containing(KeyType const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k;
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k;
result.queue_root(root.get());
return result;
}
iterator find_overlapping(interval const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[1];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[0];
result.queue_root(root.get());
return result;
}
iterator find_subsuming(interval const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[0];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator find_subsumed(interval const& k) {
iterator result;
result.bound_minima_exist[0] = true;
result.bound_minima[0] = k.bounds[0];
result.bound_maxima_exist[1] = true;
result.bound_maxima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator find_exact(interval const& k) {
iterator result;
result.bound_minima_exist[0] = true;
result.bound_minima[0] = k.bounds[0];
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[0];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[1];
result.bound_maxima_exist[1] = true;
result.bound_maxima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator end()const {
return iterator();
}
void erase(iterator i) {
i.queue.front().n
}
};
<commit_msg>Continued throwing together an interval tree type<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2014
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#include <array>
#include <vector>
template<typename DomainType, typename MappedType>
class interval_tree {
public:
typedef std::pair<interval, MappedType> value_type;
struct interval {
std::array<DomainType, 2> bounds;
};
private:
struct node {
node(bool splits_based_on_which_bound):
splits_based_on_which_bound(splits_based_on_which_bound),
num_descendant_intervals(0),
children({{nullptr,nullptr}}),
values_here(){}
bool splits_based_on_which_bound;
size_t num_descendant_intervals;
// only for non leaves
DomainType child_separator;
std::array<std::unique_ptr<node>, 2> children; // the first has the lower values, the second the higher values
// only for leaves
std::unordered_map<interval, MappedType> values_here;
};
std::unique_ptr<node> root;
public:
template<typename Ordering>
class iterator {
public:
iterator():bound_minima_exist({{false,false}}),bound_maxima_exist({{false,false}}),min_length_exists(false){}
value_type& operator*() const {
caller_error_if(queue_.empty(), "can't dereference an empty iterator");
return *queue.front().value;
}
value_type* operator->() const {
caller_error_if(queue_.empty(), "can't dereference an empty iterator");
return queue.front().value;
}
value_type* operator++(int) {
value_type* result = queue.front().value;
++*this;
return result;
}
iterator& operator++() {
queue.pop();
advance_to_a_returnable();
return *this;
}
bool operator==(iterator const& other) const {
if (queue.empty()) { return other.queue.empty(); }
if (other.queue.empty()) { return false; }
return queue.front() == other.queue.front();
}
bool operator!=(iterator const& other) const { return !(*this == other); }
private:
std::array<bool, 2> bound_minima_exist;
std::array<bool, 2> bound_maxima_exist;
bool min_length_exists;
struct queue_entry {
node* n;
value_type* value;
std::array<interval, 2> possible_bounds;
};
std::priority_queue<queue_value_type_, std::vector<queue_value_type_>, reverse_first_ordering<CostOrdering, queue_value_type_> > queue_type_;
void queue_root(node* root) {
queue_entry e;
e.n = root;
if (!e.n) return;
e.possible_bounds[0][0] = neginf;
e.possible_bounds[0][1] = inf;
e.possible_bounds[1][0] = neginf;
e.possible_bounds[1][1] = inf;
queue.push(e);
}
void queue_node(queue_entry const& parent, bool use_second_child) {
queue_entry e = parent;
e.n = parent.n->children[use_second_child].get();
if (!e.n) return;
if (bound_minima_exist[parent.n->splits_based_on_which_bound] && use_second_child && (parent.n->child_separator < bound_minima[parent.n->splits_based_on_which_bound])) return;
if (bound_maxima_exist[parent.n->splits_based_on_which_bound] && !use_second_child && (parent.n->child_separator > bound_maxima[parent.n->splits_based_on_which_bound])) return;
e.possible_bounds[parent.n->splits_based_on_which_bound].bounds[!use_second_child] = parent.n->child_separator;
if (min_length_exists && interval(e.possible_bounds[0].bounds[0], e.possible_bounds[1].bounds[1]).length_less_than(min_length)) return;
queue.push(e);
}
void queue_value(node* n, value_type* value) {
queue_entry e;
e.n = n;
e.value = value;
std::array<DomainType, 2> const& bounds = value->second.bounds;
if (bound_minima_exist[0] && (bounds[0] < bound_minima[0])) return;
if (bound_maxima_exist[0] && (bounds[0] > bound_maxima[0])) return;
if (bound_minima_exist[1] && (bounds[1] < bound_minima[1])) return;
if (bound_maxima_exist[1] && (bounds[1] > bound_maxima[1])) return;
if (min_length_exists && value->second.length_less_than(min_length)) return;
queue.push(e);
}
void advance_to_a_returnable() {
while (!queue.front().value) {
queue_node(queue.front(), 0);
queue_node(queue.front(), 1);
for (value_type& v : queue.front().n->values_here) {
queue_value(queue.front().n, &v);
}
queue.pop();
if (queue.empty()) { return; }
}
}
friend interval_tree;
};
iterator find_containing(KeyType const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k;
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k;
result.queue_root(root.get());
return result;
}
iterator find_overlapping(interval const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[1];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[0];
result.queue_root(root.get());
return result;
}
iterator find_subsuming(interval const& k) {
iterator result;
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[0];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator find_subsumed(interval const& k) {
iterator result;
result.bound_minima_exist[0] = true;
result.bound_minima[0] = k.bounds[0];
result.bound_maxima_exist[1] = true;
result.bound_maxima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator find_exact(interval const& k) {
iterator result;
result.bound_minima_exist[0] = true;
result.bound_minima[0] = k.bounds[0];
result.bound_maxima_exist[0] = true;
result.bound_maxima[0] = k.bounds[0];
result.bound_minima_exist[1] = true;
result.bound_minima[1] = k.bounds[1];
result.bound_maxima_exist[1] = true;
result.bound_maxima[1] = k.bounds[1];
result.queue_root(root.get());
return result;
}
iterator end()const {
return iterator();
}
// The tree maintains these invariants:
// Nodes always alternate splits_based_on_which_bound.
// No non-leaf directly contains any intervals.
// 1) No leaf contains more than max_leaf_size intervals.
// 2) No leaf contains less than min_leaf_size intervals (except for when the root is just a leaf).
// 3) No non-leaf has more than twice as many descendants on one side as on the other.
// (2) and (3) together bound the tree height at log_3(N).
static const min_leaf_size = 2;
static const max_leaf_size = 6;
static_assert (max_leaf_size+1 >= min_leaf_size * 2, "must be able to split a node that exceeds max size");
static void collapse_node(node& n, std::unique_ptr<node>& descendant) {
for (value_type& v : descendant.values_here) {
n.values_here.insert(v);
}
if (descendant->children[0]) {
collapse_node(n, descendant->children[0]);
collapse_node(n, descendant->children[1]);
}
descendant = nullptr;
}
static void insert_and_or_erase_impl(bool is_root, std::unique_ptr<node>& n, std::vector<value_type_ref> const& values_to_insert, std::vector<value_type_ref> const& values_to_erase) {
if (!n) {
assert(is_root);
n.reset(new node(false));
}
n->num_descendant_intervals += values_to_insert.size();
n->num_descendant_intervals -= values_to_erase .size();
assert(is_root || (n->num_descendant_intervals >= min_leaf_size));
if (n->children[0]) { // i.e. "if non leaf"
if (n->num_descendant_intervals <= max_leaf_size) {
collapse_node(*n, n->children[0]);
collapse_node(*n, n->children[1]);
}
else {
std::array<std::vector<value_type_ref>, 2> values_to_insert_by_child;
std::array<std::vector<value_type_ref>, 2> values_to_erase_by_child;
for (auto& v : values_to_insert_by_child) { v.reserve(values_to_insert.size()); }
for (auto& v : values_to_erase_by_child ) { v.reserve(values_to_erase .size()); }
for (value_type_ref v : values_to_insert) {
values_to_insert_by_child[v.first.bounds[n->splits_based_on_which_bound] > n->child_separator].push_back(v);
}
for (value_type_ref v : values_to_erase ) {
values_to_erase_by_child [v.first.bounds[n->splits_based_on_which_bound] > n->child_separator].push_back(v);
}
#define NEW_NUM_DESCENDANTS(which_child) (n->children[which_child]->num_descendant_intervals \
+ values_to_insert_by_child[which_child].size() \
- values_to_erase_by_child[which_child].size())
for (which_child : true, false) {
if (NEW_NUM_DESCENDANTS(which_child) > 2*NEW_NUM_DESCENDANTS(!which_child)) {
iterator<> thief;
if (which_child) {
result.bound_minima_exist[0] = true;
result.bound_minima[0] = n->child_separator;
}
else {
result.bound_maxima_exist[1] = true;
result.bound_maxima[1] = n->child_separator;
}
iterator.queue_root(n->children[which_child].get());
while (NEW_NUM_DESCENDANTS(which_child) > NEW_NUM_DESCENDANTS(!which_child) + 1) {
values_to_erase_by_child [ which_child].push_back(*iterator);
values_to_insert_by_child[!which_child].push_back(*iterator);
n->child_separator = iterator->first.bounds[!which_child]; // TODO worry about < vs <=
}
}
}
for (which_child : true, false) {
insert_and_or_erase_impl(false, n->children[which_child], values_to_insert_by_child[which_child], values_to_erase_by_child);
}
}
}
else {
for (value_type& v : values_to_erase) {
n->values_here.erase(v);
}
for (value_type& v : values_to_insert) {
n->values_here.insert(v);
}
if (n->num_descendant_intervals > max_leaf_size) {
n->children[0].reset(new node(!n->splits_based_on_which_bound));
n->children[1].reset(new node(!n->splits_based_on_which_bound));
n->child_separator = median(n->values_here)
std::array<std::vector<value_type_ref>, 2> values_to_insert_by_child;
for (value_type_ref v : n->values_here) {
values_to_insert_by_child[v > n->child_separator].push_back(v);
}
for (which_child : true, false) {
insert_and_or_erase_impl(false, n->children[which_child], values_to_insert_by_child[which_child], values_to_erase_by_child);
}
}
}
}
void erase(iterator i) {
i.queue.front().n
}
};
<|endoftext|>
|
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/graphics.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/image.hpp"
namespace gcn
{
Graphics::Graphics()
{
mFont = NULL;
}
bool Graphics::pushClipArea(Rectangle area)
{
// Ignore area with a negate width or height
if (area.width < 0 || area.height < 0)
return false;
if (mClipStack.empty())
{
ClipRectangle carea;
carea.x = area.x;
carea.y = area.y;
carea.width = area.width;
carea.height = area.height;
carea.xOffset = area.x;
carea.yOffset = area.y;
mClipStack.push(carea);
return true;
}
const ClipRectangle &top = mClipStack.top();
ClipRectangle carea;
carea = area;
carea.xOffset = top.xOffset + carea.x;
carea.yOffset = top.yOffset + carea.y;
carea.x += top.xOffset;
carea.y += top.yOffset;
// Clamp the pushed clip rectangle.
if (carea.x < top.x)
{
carea.x = top.x;
}
if (carea.y < top.y)
{
carea.y = top.y;
}
if (carea.x + carea.width > top.x + top.width)
{
carea.width = top.x + top.width - carea.x;
if (carea.width < 0)
{
carea.width = 0;
}
}
if (carea.y + carea.height > top.y + top.height)
{
carea.height = top.y + top.height - carea.y;
if (carea.height < 0)
{
carea.height = 0;
}
}
bool result = carea.isIntersecting(top);
mClipStack.push(carea);
return result;
}
void Graphics::popClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("Tried to pop clip area from empty stack.");
}
mClipStack.pop();
}
const ClipRectangle& Graphics::getCurrentClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("The clip area stack is empty.");
}
return mClipStack.top();
}
void Graphics::drawImage(const Image* image, int dstX, int dstY)
{
drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight());
}
void Graphics::setFont(Font* font)
{
mFont = font;
}
void Graphics::drawText(const std::string& text, int x, int y,
Alignment alignment)
{
if (mFont == NULL)
{
throw GCN_EXCEPTION("No font set.");
}
switch (alignment)
{
case LEFT:
mFont->drawString(this, text, x, y);
break;
case CENTER:
mFont->drawString(this, text, x - mFont->getWidth(text) / 2, y);
break;
case RIGHT:
mFont->drawString(this, text, x - mFont->getWidth(text), y);
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
}
}
<commit_msg>http://code.google.com/p/guichan/issues/detail?id=48<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/graphics.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/image.hpp"
namespace gcn
{
Graphics::Graphics()
{
mFont = NULL;
}
bool Graphics::pushClipArea(Rectangle area)
{
// Ignore area with a negate width or height
// by simple pushing an empty clip area
// to the stack.
if (area.width < 0 || area.height < 0)
{
ClipRectangle carea;
mClipStack.push(carea);
return true;
}
if (mClipStack.empty())
{
ClipRectangle carea;
carea.x = area.x;
carea.y = area.y;
carea.width = area.width;
carea.height = area.height;
carea.xOffset = area.x;
carea.yOffset = area.y;
mClipStack.push(carea);
return true;
}
const ClipRectangle &top = mClipStack.top();
ClipRectangle carea;
carea = area;
carea.xOffset = top.xOffset + carea.x;
carea.yOffset = top.yOffset + carea.y;
carea.x += top.xOffset;
carea.y += top.yOffset;
// Clamp the pushed clip rectangle.
if (carea.x < top.x)
{
carea.x = top.x;
}
if (carea.y < top.y)
{
carea.y = top.y;
}
if (carea.x + carea.width > top.x + top.width)
{
carea.width = top.x + top.width - carea.x;
if (carea.width < 0)
{
carea.width = 0;
}
}
if (carea.y + carea.height > top.y + top.height)
{
carea.height = top.y + top.height - carea.y;
if (carea.height < 0)
{
carea.height = 0;
}
}
bool result = carea.isIntersecting(top);
mClipStack.push(carea);
return result;
}
void Graphics::popClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("Tried to pop clip area from empty stack.");
}
mClipStack.pop();
}
const ClipRectangle& Graphics::getCurrentClipArea()
{
if (mClipStack.empty())
{
throw GCN_EXCEPTION("The clip area stack is empty.");
}
return mClipStack.top();
}
void Graphics::drawImage(const Image* image, int dstX, int dstY)
{
drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight());
}
void Graphics::setFont(Font* font)
{
mFont = font;
}
void Graphics::drawText(const std::string& text, int x, int y,
Alignment alignment)
{
if (mFont == NULL)
{
throw GCN_EXCEPTION("No font set.");
}
switch (alignment)
{
case LEFT:
mFont->drawString(this, text, x, y);
break;
case CENTER:
mFont->drawString(this, text, x - mFont->getWidth(text) / 2, y);
break;
case RIGHT:
mFont->drawString(this, text, x - mFont->getWidth(text), y);
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
}
}
<|endoftext|>
|
<commit_before>#include "simplestack.h"
#include <iostream>
using namespace std;
struct StackElement
{
ElementType value;
StackElement *next;
};
struct Stack
{
StackElement *head;
};
Stack* createStack()
{
return new Stack{ nullptr };
}
StackElement* next(StackElement *element)
{
return (element) ? element->next : nullptr;
}
StackElement* getHead(Stack *stack)
{
return stack->head;
}
ElementType getValue(StackElement *element)
{
return element->value;
}
void deleteFromHead(Stack *stack)
{
if (stack->head)
{
auto oldHead = stack->head;
stack->head = stack->head->next;
delete oldHead;
}
}
void deleteStack(Stack *&stack)
{
while (stack->head)
{
deleteFromHead(stack);
}
delete stack;
}
void pushback(Stack *stack, ElementType value)
{
auto newElement = new StackElement{ value, stack->head };
stack->head = newElement;
}
void insert(StackElement *position, ElementType value)
{
auto newElement = new StackElement{ value, position };
position->next = newElement;
}
ElementType pop(Stack *stack)
{
if (!stack->head)
{
auto oldElement = stack->head;
auto oldValue = oldElement->value;
stack->head = stack->head->next;
delete oldElement;
return oldValue;
}
return ' ';
}
ElementType remove(StackElement *position)
{
if ((!position) || (!position->next))
{
return ' ';
}
auto oldElement = position->next;
auto oldValue = oldElement->value;
position->next = position->next->next;
delete oldElement;
return oldValue;
}
void print(Stack *stack)
{
auto iterator = stack->head;
while (iterator)
{
cout << iterator->value << endl;
iterator = iterator->next;
}
cout << "===" << endl;
}
void printReversed(Stack *stack)
{
auto temporaryStack = createStack();
auto iterator = stack->head;
while (iterator)
{
pushback(temporaryStack, iterator->value);
iterator = iterator->next;
}
print(temporaryStack);
deleteStack(temporaryStack);
}
void print_r(Stack *stack)
{
auto iterator = stack->head;
while (iterator)
{
cout << iterator->value;
iterator = iterator->next;
}
cout << endl << "===" << endl;
}
void printReversed_r(Stack *stack)
{
auto temporaryStack = createStack();
auto iterator = stack->head;
while (iterator)
{
pushback(temporaryStack, iterator->value);
iterator = iterator->next;
}
print_r(temporaryStack);
deleteStack(temporaryStack);
}
<commit_msg>исправлена ошибка в поп<commit_after>#include "simplestack.h"
#include <iostream>
using namespace std;
struct StackElement
{
ElementType value;
StackElement *next;
};
struct Stack
{
StackElement *head;
};
Stack* createStack()
{
return new Stack{ nullptr };
}
StackElement* next(StackElement *element)
{
return (element) ? element->next : nullptr;
}
StackElement* getHead(Stack *stack)
{
return stack->head;
}
ElementType getValue(StackElement *element)
{
return element->value;
}
void deleteFromHead(Stack *stack)
{
if (stack->head)
{
auto oldHead = stack->head;
stack->head = stack->head->next;
delete oldHead;
}
}
void deleteStack(Stack *&stack)
{
while (stack->head)
{
deleteFromHead(stack);
}
delete stack;
}
void pushback(Stack *stack, ElementType value)
{
auto newElement = new StackElement{ value, stack->head };
stack->head = newElement;
}
void insert(StackElement *position, ElementType value)
{
auto newElement = new StackElement{ value, position };
position->next = newElement;
}
ElementType pop(Stack *stack)
{
if (stack->head)
{
auto oldElement = stack->head;
auto oldValue = oldElement->value;
stack->head = stack->head->next;
delete oldElement;
return oldValue;
}
return ' ';
}
ElementType remove(StackElement *position)
{
if ((!position) || (!position->next))
{
return ' ';
}
auto oldElement = position->next;
auto oldValue = oldElement->value;
position->next = position->next->next;
delete oldElement;
return oldValue;
}
void print(Stack *stack)
{
auto iterator = stack->head;
while (iterator)
{
cout << iterator->value << endl;
iterator = iterator->next;
}
cout << "===" << endl;
}
void printReversed(Stack *stack)
{
auto temporaryStack = createStack();
auto iterator = stack->head;
while (iterator)
{
pushback(temporaryStack, iterator->value);
iterator = iterator->next;
}
print(temporaryStack);
deleteStack(temporaryStack);
}
void print_r(Stack *stack)
{
auto iterator = stack->head;
while (iterator)
{
cout << iterator->value;
iterator = iterator->next;
}
cout << endl << "===" << endl;
}
void printReversed_r(Stack *stack)
{
auto temporaryStack = createStack();
auto iterator = stack->head;
while (iterator)
{
pushback(temporaryStack, iterator->value);
iterator = iterator->next;
}
print_r(temporaryStack);
deleteStack(temporaryStack);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/common/clock_tracker.h"
#include <inttypes.h>
#include <algorithm>
#include <queue>
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/hash.h"
#include "src/trace_processor/storage/trace_storage.h"
#include "src/trace_processor/types/trace_processor_context.h"
#include "protos/perfetto/common/builtin_clock.pbzero.h"
#include "protos/perfetto/trace/clock_snapshot.pbzero.h"
namespace perfetto {
namespace trace_processor {
using Clock = protos::pbzero::ClockSnapshot::Clock;
ClockTracker::ClockTracker(TraceProcessorContext* ctx)
: context_(ctx),
trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}
ClockTracker::~ClockTracker() = default;
void ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {
const auto snapshot_id = cur_snapshot_id_++;
// Clear the cache
static_assert(std::is_trivial<decltype(cache_)>::value, "must be trivial");
memset(&cache_[0], 0, sizeof(cache_));
// Compute the fingerprint of the snapshot by hashing all clock ids. This is
// used by the clock pathfinding logic.
base::Hash hasher;
for (const auto& clock : clocks)
hasher.Update(clock.clock_id);
const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());
// Add a new entry in each clock's snapshot vector.
for (const auto& clock : clocks) {
ClockId clock_id = clock.clock_id;
ClockDomain& domain = clocks_[clock_id];
if (domain.snapshots.empty()) {
if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {
PERFETTO_ELOG("Clock sync error: the global clock with id=%" PRIu64
" cannot use incremental encoding; this is only "
"supported for sequence-scoped clocks.",
clock_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
domain.unit_multiplier_ns = clock.unit_multiplier_ns;
domain.is_incremental = clock.is_incremental;
} else if (PERFETTO_UNLIKELY(
domain.unit_multiplier_ns != clock.unit_multiplier_ns ||
domain.is_incremental != clock.is_incremental)) {
PERFETTO_ELOG("Clock sync error: the clock domain with id=%" PRIu64
" (unit=%" PRIu64
", incremental=%d), was previously registered with "
"different properties (unit=%" PRIu64 ", incremental=%d).",
clock_id, clock.unit_multiplier_ns, clock.is_incremental,
domain.unit_multiplier_ns, domain.is_incremental);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
const int64_t timestamp_ns =
clock.absolute_timestamp * domain.unit_multiplier_ns;
domain.last_timestamp_ns = timestamp_ns;
ClockSnapshots& vect = domain.snapshots[snapshot_hash];
if (!vect.snapshot_ids.empty() &&
PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {
PERFETTO_ELOG("Clock sync error: duplicate clock domain with id=%" PRIu64
" at snapshot %" PRIu32 ".",
clock_id, snapshot_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
// Clock ids in the range [64, 128) are sequence-scoped and must be
// translated to global ids via SeqScopedClockIdToGlobal() before calling
// this function.
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));
// Snapshot IDs must be always monotonic.
PERFETTO_DCHECK(vect.snapshot_ids.empty() ||
vect.snapshot_ids.back() < snapshot_id);
if (!vect.timestamps_ns.empty() &&
timestamp_ns < vect.timestamps_ns.back()) {
// Clock is not monotonic.
if (clock_id == trace_time_clock_id_) {
// The trace clock cannot be non-monotonic.
PERFETTO_ELOG("Clock sync error: the trace clock (id=%" PRIu64
") is not monotonic at snapshot %" PRIu32 ". %" PRId64
" not >= %" PRId64 ".",
clock_id, snapshot_id, timestamp_ns,
vect.timestamps_ns.back());
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
PERFETTO_DLOG("Detected non-monotonic clock with ID %" PRIu64, clock_id);
// For the other clocks the best thing we can do is mark it as
// non-monotonic and refuse to use it as a source clock in the resolution
// graph. We can still use it as a target clock, but not viceversa.
// The concrete example is the CLOCK_REALTIME going 1h backwards during
// daylight saving. We can still answer the question "what was the
// REALTIME timestamp when BOOTTIME was X?" but we can't answer the
// opposite question because there can be two valid BOOTTIME(s) for the
// same REALTIME instant because of the 1:many relationship.
non_monotonic_clocks_.insert(clock_id);
// Erase all edges from the graph that start from this clock (but keep the
// ones that end on this clock).
auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});
auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});
graph_.erase(begin, end);
}
vect.snapshot_ids.emplace_back(snapshot_id);
vect.timestamps_ns.emplace_back(timestamp_ns);
}
// Create graph edges for all the possible tuples of clocks in this snapshot.
// If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,
// cd] and the symmetrical ones [ba, ca, da, bc, db, dc].
// This is to store the information: Clock A is syncable to Clock B via the
// snapshots of type (hash).
// Clocks that were previously marked as non-monotonic won't be added as
// valid sources.
for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {
auto it2 = it1;
++it2;
for (; it2 != clocks.end(); ++it2) {
if (!non_monotonic_clocks_.count(it1->clock_id))
graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);
if (!non_monotonic_clocks_.count(it2->clock_id))
graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);
}
}
}
// Finds the shortest clock resolution path in the graph that allows to
// translate a timestamp from |src| to |target| clocks.
// The return value looks like the following: "If you want to convert a
// timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the
// snapshot hash A, then convert C3 -> C2 via snapshot hash B".
ClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {
// This is a classic breadth-first search. Each node in the queue holds also
// the full path to reach that node.
// We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will
// stop the search anyways.
PERFETTO_CHECK(src != target);
std::queue<ClockPath> queue;
queue.emplace(src);
while (!queue.empty()) {
ClockPath cur_path = queue.front();
queue.pop();
const ClockId cur_clock_id = cur_path.last;
if (cur_clock_id == target)
return cur_path;
if (cur_path.len >= ClockPath::kMaxLen)
continue;
// Expore all the adjacent clocks.
// The lower_bound() below returns an iterator to the first edge that starts
// on |cur_clock_id|. The edges are sorted by (src, target, hash).
for (auto it = std::lower_bound(graph_.begin(), graph_.end(),
ClockGraphEdge(cur_clock_id, 0, 0));
it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {
ClockId next_clock_id = std::get<1>(*it);
SnapshotHash hash = std::get<2>(*it);
queue.push(ClockPath(cur_path, next_clock_id, hash));
}
}
return ClockPath(); // invalid path.
}
base::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,
int64_t src_timestamp,
ClockId target_clock_id) {
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));
context_->storage->IncrementStats(stats::clock_sync_cache_miss);
ClockPath path = FindPath(src_clock_id, target_clock_id);
if (!path.valid()) {
PERFETTO_DLOG("No path from clock %" PRIu64 " to %" PRIu64
" at timestamp %" PRId64,
src_clock_id, target_clock_id, src_timestamp);
context_->storage->IncrementStats(stats::clock_sync_failure);
return base::nullopt;
}
// We can cache only single-path resolutions between two clocks.
// Caching multi-path resolutions is harder because the (src,target) tuple
// is not enough as a cache key: at any step the |ns| value can yield to a
// different choice of the next snapshot. Multi-path resolutions don't seem
// too frequent these days, so we focus only on caching the more frequent
// one-step resolutions (typically from any clock to the trace clock).
const bool cacheable = path.len == 1;
CachedClockPath cache_entry{};
// Iterate trough the path found and translate timestamps onto the new clock
// domain on each step, until the target domain is reached.
ClockDomain* src_domain = GetClock(src_clock_id);
int64_t ns = src_domain->ToNs(src_timestamp);
for (uint32_t i = 0; i < path.len; ++i) {
const ClockGraphEdge edge = path.at(i);
ClockDomain* cur_clock = GetClock(std::get<0>(edge));
ClockDomain* next_clock = GetClock(std::get<1>(edge));
const SnapshotHash hash = std::get<2>(edge);
// Find the closest timestamp within the snapshots of the source clock.
const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);
const auto& ts_vec = cur_snap.timestamps_ns;
auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);
if (it != ts_vec.begin())
--it;
// Now lookup the snapshot id that matches the closest timestamp.
size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));
PERFETTO_DCHECK(index < ts_vec.size());
PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());
uint32_t snapshot_id = cur_snap.snapshot_ids[index];
// And use that to retrieve the corresponding time in the next clock domain.
// The snapshot id must exist in the target clock domain. If it doesn't
// either the hash logic or the pathfinding logic are bugged.
const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);
auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),
next_snap.snapshot_ids.end(), snapshot_id);
PERFETTO_DCHECK(next_it != next_snap.snapshot_ids.end() &&
*next_it == snapshot_id);
size_t next_index = static_cast<size_t>(
std::distance(next_snap.snapshot_ids.begin(), next_it));
PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());
int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];
// The translated timestamp is the relative delta of the source timestamp
// from the closest snapshot found (ns - *it), plus the timestamp in
// the new clock domain for the same snapshot id.
const int64_t adj = next_timestamp_ns - *it;
ns += adj;
// On the first iteration, keep track of the bounds for the cache entry.
// This will allow future Convert() calls to skip the pathfinder logic
// as long as the query stays within the bound.
if (cacheable) {
PERFETTO_DCHECK(i == 0);
const int64_t kInt64Min = std::numeric_limits<int64_t>::min();
const int64_t kInt64Max = std::numeric_limits<int64_t>::max();
cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;
auto ubound = it + 1;
cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;
cache_entry.translation_ns = adj;
}
// The last clock in the path must be the target clock.
PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);
}
if (cacheable) {
cache_entry.src = src_clock_id;
cache_entry.src_domain = src_domain;
cache_entry.target = target_clock_id;
cache_[rnd_() % cache_.size()] = cache_entry;
}
return ns;
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>Remove unnecessarily standard-incompliant code. am: 1142652106 am: 666c4e0ea4 am: 141c988022 am: 44072240d8<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/common/clock_tracker.h"
#include <inttypes.h>
#include <algorithm>
#include <queue>
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/hash.h"
#include "src/trace_processor/storage/trace_storage.h"
#include "src/trace_processor/types/trace_processor_context.h"
#include "protos/perfetto/common/builtin_clock.pbzero.h"
#include "protos/perfetto/trace/clock_snapshot.pbzero.h"
namespace perfetto {
namespace trace_processor {
using Clock = protos::pbzero::ClockSnapshot::Clock;
ClockTracker::ClockTracker(TraceProcessorContext* ctx)
: context_(ctx),
trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}
ClockTracker::~ClockTracker() = default;
void ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {
const auto snapshot_id = cur_snapshot_id_++;
// Clear the cache
cache_.fill({});
// Compute the fingerprint of the snapshot by hashing all clock ids. This is
// used by the clock pathfinding logic.
base::Hash hasher;
for (const auto& clock : clocks)
hasher.Update(clock.clock_id);
const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());
// Add a new entry in each clock's snapshot vector.
for (const auto& clock : clocks) {
ClockId clock_id = clock.clock_id;
ClockDomain& domain = clocks_[clock_id];
if (domain.snapshots.empty()) {
if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {
PERFETTO_ELOG("Clock sync error: the global clock with id=%" PRIu64
" cannot use incremental encoding; this is only "
"supported for sequence-scoped clocks.",
clock_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
domain.unit_multiplier_ns = clock.unit_multiplier_ns;
domain.is_incremental = clock.is_incremental;
} else if (PERFETTO_UNLIKELY(
domain.unit_multiplier_ns != clock.unit_multiplier_ns ||
domain.is_incremental != clock.is_incremental)) {
PERFETTO_ELOG("Clock sync error: the clock domain with id=%" PRIu64
" (unit=%" PRIu64
", incremental=%d), was previously registered with "
"different properties (unit=%" PRIu64 ", incremental=%d).",
clock_id, clock.unit_multiplier_ns, clock.is_incremental,
domain.unit_multiplier_ns, domain.is_incremental);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
const int64_t timestamp_ns =
clock.absolute_timestamp * domain.unit_multiplier_ns;
domain.last_timestamp_ns = timestamp_ns;
ClockSnapshots& vect = domain.snapshots[snapshot_hash];
if (!vect.snapshot_ids.empty() &&
PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {
PERFETTO_ELOG("Clock sync error: duplicate clock domain with id=%" PRIu64
" at snapshot %" PRIu32 ".",
clock_id, snapshot_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
// Clock ids in the range [64, 128) are sequence-scoped and must be
// translated to global ids via SeqScopedClockIdToGlobal() before calling
// this function.
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));
// Snapshot IDs must be always monotonic.
PERFETTO_DCHECK(vect.snapshot_ids.empty() ||
vect.snapshot_ids.back() < snapshot_id);
if (!vect.timestamps_ns.empty() &&
timestamp_ns < vect.timestamps_ns.back()) {
// Clock is not monotonic.
if (clock_id == trace_time_clock_id_) {
// The trace clock cannot be non-monotonic.
PERFETTO_ELOG("Clock sync error: the trace clock (id=%" PRIu64
") is not monotonic at snapshot %" PRIu32 ". %" PRId64
" not >= %" PRId64 ".",
clock_id, snapshot_id, timestamp_ns,
vect.timestamps_ns.back());
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
PERFETTO_DLOG("Detected non-monotonic clock with ID %" PRIu64, clock_id);
// For the other clocks the best thing we can do is mark it as
// non-monotonic and refuse to use it as a source clock in the resolution
// graph. We can still use it as a target clock, but not viceversa.
// The concrete example is the CLOCK_REALTIME going 1h backwards during
// daylight saving. We can still answer the question "what was the
// REALTIME timestamp when BOOTTIME was X?" but we can't answer the
// opposite question because there can be two valid BOOTTIME(s) for the
// same REALTIME instant because of the 1:many relationship.
non_monotonic_clocks_.insert(clock_id);
// Erase all edges from the graph that start from this clock (but keep the
// ones that end on this clock).
auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});
auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});
graph_.erase(begin, end);
}
vect.snapshot_ids.emplace_back(snapshot_id);
vect.timestamps_ns.emplace_back(timestamp_ns);
}
// Create graph edges for all the possible tuples of clocks in this snapshot.
// If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,
// cd] and the symmetrical ones [ba, ca, da, bc, db, dc].
// This is to store the information: Clock A is syncable to Clock B via the
// snapshots of type (hash).
// Clocks that were previously marked as non-monotonic won't be added as
// valid sources.
for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {
auto it2 = it1;
++it2;
for (; it2 != clocks.end(); ++it2) {
if (!non_monotonic_clocks_.count(it1->clock_id))
graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);
if (!non_monotonic_clocks_.count(it2->clock_id))
graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);
}
}
}
// Finds the shortest clock resolution path in the graph that allows to
// translate a timestamp from |src| to |target| clocks.
// The return value looks like the following: "If you want to convert a
// timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the
// snapshot hash A, then convert C3 -> C2 via snapshot hash B".
ClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {
// This is a classic breadth-first search. Each node in the queue holds also
// the full path to reach that node.
// We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will
// stop the search anyways.
PERFETTO_CHECK(src != target);
std::queue<ClockPath> queue;
queue.emplace(src);
while (!queue.empty()) {
ClockPath cur_path = queue.front();
queue.pop();
const ClockId cur_clock_id = cur_path.last;
if (cur_clock_id == target)
return cur_path;
if (cur_path.len >= ClockPath::kMaxLen)
continue;
// Expore all the adjacent clocks.
// The lower_bound() below returns an iterator to the first edge that starts
// on |cur_clock_id|. The edges are sorted by (src, target, hash).
for (auto it = std::lower_bound(graph_.begin(), graph_.end(),
ClockGraphEdge(cur_clock_id, 0, 0));
it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {
ClockId next_clock_id = std::get<1>(*it);
SnapshotHash hash = std::get<2>(*it);
queue.push(ClockPath(cur_path, next_clock_id, hash));
}
}
return ClockPath(); // invalid path.
}
base::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,
int64_t src_timestamp,
ClockId target_clock_id) {
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));
context_->storage->IncrementStats(stats::clock_sync_cache_miss);
ClockPath path = FindPath(src_clock_id, target_clock_id);
if (!path.valid()) {
PERFETTO_DLOG("No path from clock %" PRIu64 " to %" PRIu64
" at timestamp %" PRId64,
src_clock_id, target_clock_id, src_timestamp);
context_->storage->IncrementStats(stats::clock_sync_failure);
return base::nullopt;
}
// We can cache only single-path resolutions between two clocks.
// Caching multi-path resolutions is harder because the (src,target) tuple
// is not enough as a cache key: at any step the |ns| value can yield to a
// different choice of the next snapshot. Multi-path resolutions don't seem
// too frequent these days, so we focus only on caching the more frequent
// one-step resolutions (typically from any clock to the trace clock).
const bool cacheable = path.len == 1;
CachedClockPath cache_entry{};
// Iterate trough the path found and translate timestamps onto the new clock
// domain on each step, until the target domain is reached.
ClockDomain* src_domain = GetClock(src_clock_id);
int64_t ns = src_domain->ToNs(src_timestamp);
for (uint32_t i = 0; i < path.len; ++i) {
const ClockGraphEdge edge = path.at(i);
ClockDomain* cur_clock = GetClock(std::get<0>(edge));
ClockDomain* next_clock = GetClock(std::get<1>(edge));
const SnapshotHash hash = std::get<2>(edge);
// Find the closest timestamp within the snapshots of the source clock.
const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);
const auto& ts_vec = cur_snap.timestamps_ns;
auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);
if (it != ts_vec.begin())
--it;
// Now lookup the snapshot id that matches the closest timestamp.
size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));
PERFETTO_DCHECK(index < ts_vec.size());
PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());
uint32_t snapshot_id = cur_snap.snapshot_ids[index];
// And use that to retrieve the corresponding time in the next clock domain.
// The snapshot id must exist in the target clock domain. If it doesn't
// either the hash logic or the pathfinding logic are bugged.
const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);
auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),
next_snap.snapshot_ids.end(), snapshot_id);
PERFETTO_DCHECK(next_it != next_snap.snapshot_ids.end() &&
*next_it == snapshot_id);
size_t next_index = static_cast<size_t>(
std::distance(next_snap.snapshot_ids.begin(), next_it));
PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());
int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];
// The translated timestamp is the relative delta of the source timestamp
// from the closest snapshot found (ns - *it), plus the timestamp in
// the new clock domain for the same snapshot id.
const int64_t adj = next_timestamp_ns - *it;
ns += adj;
// On the first iteration, keep track of the bounds for the cache entry.
// This will allow future Convert() calls to skip the pathfinder logic
// as long as the query stays within the bound.
if (cacheable) {
PERFETTO_DCHECK(i == 0);
const int64_t kInt64Min = std::numeric_limits<int64_t>::min();
const int64_t kInt64Max = std::numeric_limits<int64_t>::max();
cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;
auto ubound = it + 1;
cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;
cache_entry.translation_ns = adj;
}
// The last clock in the path must be the target clock.
PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);
}
if (cacheable) {
cache_entry.src = src_clock_id;
cache_entry.src_domain = src_domain;
cache_entry.target = target_clock_id;
cache_[rnd_() % cache_.size()] = cache_entry;
}
return ns;
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|>
|
<commit_before>#include <sparsehash/dense_hash_map>
#include <unordered_map>
#include "fixture_unittests.h"
#include "hashtable_test_interface.h"
#include "gtest/gtest.h"
#include <unordered_map>
#include <unordered_set>
#include <chrono>
using google::dense_hash_map;
using google::dense_hash_set;
namespace sparsehash_internal = google::sparsehash_internal;
TYPED_TEST(HashtableAllTest, NormalIterators222) {
EXPECT_TRUE(this->ht_.begin() == this->ht_.end());
this->ht_.insert(this->UniqueObject(1));
{
typename TypeParam::iterator it = this->ht_.begin();
EXPECT_TRUE(it != this->ht_.end());
++it;
EXPECT_TRUE(it == this->ht_.end());
}
}
TEST(HashtableMoveTest, Insert_RValue)
{
dense_hash_map<int, std::unique_ptr<int>> h;
h.set_empty_key(0);
auto p1 = std::make_pair(5, std::unique_ptr<int>(new int(1234)));
auto p = h.insert(std::move(p1));
ASSERT_EQ(true, p.second);
ASSERT_EQ(5, p.first->first);
ASSERT_EQ(1234, *p.first->second);
p = h.insert(std::make_pair(10, std::unique_ptr<int>(new int(5678))));
ASSERT_EQ(true, p.second);
ASSERT_EQ(10, p.first->first);
ASSERT_EQ(5678, *p.first->second);
ASSERT_EQ(2, (int)h.size());
}
TEST(HashtableMoveTest, Emplace)
{
dense_hash_map<int, std::unique_ptr<int>> h;
h.set_empty_key(0);
auto p = h.emplace(5, new int(1234));
ASSERT_EQ(true, p.second);
ASSERT_EQ(5, p.first->first);
ASSERT_EQ(1234, *p.first->second);
p = h.emplace(10, new int(5678));
ASSERT_EQ(true, p.second);
ASSERT_EQ(10, p.first->first);
ASSERT_EQ(5678, *p.first->second);
ASSERT_EQ(2, (int)h.size());
ASSERT_TRUE(h.emplace(11, new int(1)).second);
ASSERT_FALSE(h.emplace(11, new int(1)).second);
ASSERT_TRUE(h.emplace(12, new int(1)).second);
ASSERT_FALSE(h.emplace(12, new int(1)).second);
}
TEST(HashtableMoveTest, EmplaceHint)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h[1] = 1;
h[3] = 3;
h[5] = 5;
ASSERT_FALSE(h.emplace_hint(h.find(1), 1, 0).second);
ASSERT_FALSE(h.emplace_hint(h.find(3), 1, 0).second);
ASSERT_FALSE(h.emplace_hint(h.end(), 1, 0).second);
ASSERT_EQ(3, (int)h.size());
ASSERT_TRUE(h.emplace_hint(h.find(1), 2, 0).second);
ASSERT_TRUE(h.emplace_hint(h.find(3), 4, 0).second);
ASSERT_TRUE(h.emplace_hint(h.end(), 6, 0).second);
ASSERT_EQ(6, (int)h.size());
}
TEST(HashtableMoveTest, EmplaceHint_SpeedComparison)
{
static const int Elements = 1e6;
static const int Duplicates = 5;
std::vector<int> v(Elements * Duplicates);
for (int i = 0; i < Elements * Duplicates; i += Duplicates)
{
auto r = std::rand();
for (int j = 0; j < Duplicates; ++j)
v[i + j] = r;
}
std::sort(std::begin(v), std::end(v));
auto start = std::chrono::system_clock::now();
{
dense_hash_map<int, int> h;
h.set_empty_key(-1);
for (int i = 0; i < Elements; ++i)
h.emplace(v[i], 0);
}
auto end = std::chrono::system_clock::now();
auto emplace_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
start = std::chrono::system_clock::now();
{
dense_hash_map<int, int> h;
h.set_empty_key(-1);
auto hint = h.begin();
for (int i = 0; i < Elements; ++i)
hint = h.emplace_hint(hint, v[i], 0).first;
}
end = std::chrono::system_clock::now();
auto emplace_hint_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
ASSERT_LE(emplace_hint_time, emplace_time);
}
struct A
{
A() =default;
A(int i) noexcept : _i(i) {}
A(const A& a) { _i = a._i; ++copy_ctor;; }
A& operator=(const A& a) { _i = a._i; ++copy_assign; return *this; }
A(A&& a) { _i = a._i; ++move_ctor; }
A& operator=(A&& a) { _i = a._i; ++move_assign; return *this; }
static void reset()
{
copy_ctor = 0;
copy_assign = 0;
move_ctor = 0;
move_assign = 0;
}
int _i = 0;
static int copy_ctor;
static int copy_assign;
static int move_ctor;
static int move_assign;
};
int A::copy_ctor = 0;
int A::copy_assign = 0;
int A::move_ctor = 0;
int A::move_assign = 0;
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a._i << " copy_ctor=" << a.copy_ctor << " copy_assign=" << a.copy_assign <<
" move_ctor=" << a.move_ctor << " move_assign=" << a.move_assign;
}
bool operator==(const A& a1, const A& a2) { return a1._i == a2._i; }
struct HashA
{
std::size_t operator()(const A& a) const { return std::hash<int>()(a._i); }
};
TEST(HashtableMoveTest, InsertRValue_ValueMoveCount)
{
dense_hash_map<int, A> h(10);
h.set_empty_key(0);
A::reset();
h.insert(std::make_pair(5, A()));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(2, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, InsertMoved_ValueMoveCount)
{
dense_hash_map<int, A> h(10);
h.set_empty_key(0);
auto p = std::make_pair(5, A());
A::reset();
h.insert(std::move(p));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, Emplace_ValueMoveCount)
{
dense_hash_map<int, A> h;
h.set_empty_key(0);
A::reset();
h.emplace(1, 2);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(0, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, InsertRValue_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h.insert(std::make_pair(A(2), 2));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(2, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, InsertMoved_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
auto m = std::make_pair(A(2), 2);
A::reset();
h.insert(std::move(m));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, Emplace_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h.emplace(1, 2);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(0, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, OperatorSqBck_InsertRValue_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h[A(1)] = 1;
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(HashtableMoveTest, OperatorSqBck_InsertMoved_ValueMoveCount)
{
dense_hash_map<int, A> h;
h.set_empty_key(0);
A::reset();
h[1] = A(1);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(1, A::move_assign);
}
TEST(HashtableMoveTest, EraseConstIterator)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
const auto it = h.begin();
ASSERT_TRUE(h.end() == h.erase(it));
ASSERT_EQ(0, (int)h.size());
}
TEST(HashtableMoveTest, EraseRange)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
for (int i = 0; i < 10; ++i)
h[i + 1] = i;
auto it = h.begin();
std::advance(it, 2);
auto it2 = h.begin();
std::advance(it2, 8);
auto nextit = h.erase(it, it2);
ASSERT_FALSE(h.end() == nextit);
nextit = h.erase(nextit);
ASSERT_FALSE(h.end() == nextit);
ASSERT_TRUE(h.end() == h.erase(nextit));
ASSERT_FALSE(h.end() == h.erase(h.begin()));
ASSERT_TRUE(h.end() == h.erase(h.begin()));
ASSERT_TRUE(h.empty());
}
TEST(HashtableMoveTest, EraseRangeEntireMap)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
for (int i = 0; i < 10; ++i)
h[i + 1] = i;
ASSERT_TRUE(h.end() == h.erase(h.begin(), h.end()));
ASSERT_TRUE(h.empty());
}
TEST(HashtableMoveTest, EraseNextElementReturned)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
h[2] = 2;
int first = h.begin()->first;
int second = first == 1 ? 2 : 1;
ASSERT_EQ(second, h.erase(h.begin())->first); // second element is returned when erasing the first one
ASSERT_TRUE(h.end() == h.erase(h.begin())); // end() is returned when erasing the second and last element
}
TEST(HashtableMoveTest, EraseNumberOfElementsDeleted)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
h[2] = 2;
ASSERT_EQ(0, (int)h.erase(3));
ASSERT_EQ(1, (int)h.erase(1));
ASSERT_EQ(1, (int)h.erase(2));
ASSERT_EQ(0, (int)h.erase(4));
ASSERT_TRUE(h.empty());
}
TEST(HashtableMoveTest, CBeginCEnd)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
auto it = h.cbegin();
ASSERT_EQ(1, it->first);
std::advance(it, 1);
ASSERT_TRUE(it == h.cend());
using cit = dense_hash_map<int, int>::const_iterator;
cit begin = h.begin();
cit end = h.end();
ASSERT_TRUE(begin == h.cbegin());
ASSERT_TRUE(end == h.cend());
}
<commit_msg>unit tests: renaming cases for dense hash map<commit_after>#include <sparsehash/dense_hash_map>
#include <unordered_map>
#include "fixture_unittests.h"
#include "hashtable_test_interface.h"
#include "gtest/gtest.h"
#include <unordered_map>
#include <unordered_set>
#include <chrono>
using google::dense_hash_map;
using google::dense_hash_set;
namespace sparsehash_internal = google::sparsehash_internal;
TEST(DenseHashMapMoveTest, Insert_RValue)
{
dense_hash_map<int, std::unique_ptr<int>> h;
h.set_empty_key(0);
auto p1 = std::make_pair(5, std::unique_ptr<int>(new int(1234)));
auto p = h.insert(std::move(p1));
ASSERT_EQ(true, p.second);
ASSERT_EQ(5, p.first->first);
ASSERT_EQ(1234, *p.first->second);
p = h.insert(std::make_pair(10, std::unique_ptr<int>(new int(5678))));
ASSERT_EQ(true, p.second);
ASSERT_EQ(10, p.first->first);
ASSERT_EQ(5678, *p.first->second);
ASSERT_EQ(2, (int)h.size());
}
TEST(DenseHashMapMoveTest, Emplace)
{
dense_hash_map<int, std::unique_ptr<int>> h;
h.set_empty_key(0);
auto p = h.emplace(5, new int(1234));
ASSERT_EQ(true, p.second);
ASSERT_EQ(5, p.first->first);
ASSERT_EQ(1234, *p.first->second);
p = h.emplace(10, new int(5678));
ASSERT_EQ(true, p.second);
ASSERT_EQ(10, p.first->first);
ASSERT_EQ(5678, *p.first->second);
ASSERT_EQ(2, (int)h.size());
ASSERT_TRUE(h.emplace(11, new int(1)).second);
ASSERT_FALSE(h.emplace(11, new int(1)).second);
ASSERT_TRUE(h.emplace(12, new int(1)).second);
ASSERT_FALSE(h.emplace(12, new int(1)).second);
}
TEST(DenseHashMapMoveTest, EmplaceHint)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h[1] = 1;
h[3] = 3;
h[5] = 5;
ASSERT_FALSE(h.emplace_hint(h.find(1), 1, 0).second);
ASSERT_FALSE(h.emplace_hint(h.find(3), 1, 0).second);
ASSERT_FALSE(h.emplace_hint(h.end(), 1, 0).second);
ASSERT_EQ(3, (int)h.size());
ASSERT_TRUE(h.emplace_hint(h.find(1), 2, 0).second);
ASSERT_TRUE(h.emplace_hint(h.find(3), 4, 0).second);
ASSERT_TRUE(h.emplace_hint(h.end(), 6, 0).second);
ASSERT_EQ(6, (int)h.size());
}
TEST(DenseHashMapMoveTest, EmplaceHint_SpeedComparison)
{
static const int Elements = 1e6;
static const int Duplicates = 5;
std::vector<int> v(Elements * Duplicates);
for (int i = 0; i < Elements * Duplicates; i += Duplicates)
{
auto r = std::rand();
for (int j = 0; j < Duplicates; ++j)
v[i + j] = r;
}
std::sort(std::begin(v), std::end(v));
auto start = std::chrono::system_clock::now();
{
dense_hash_map<int, int> h;
h.set_empty_key(-1);
for (int i = 0; i < Elements; ++i)
h.emplace(v[i], 0);
}
auto end = std::chrono::system_clock::now();
auto emplace_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
start = std::chrono::system_clock::now();
{
dense_hash_map<int, int> h;
h.set_empty_key(-1);
auto hint = h.begin();
for (int i = 0; i < Elements; ++i)
hint = h.emplace_hint(hint, v[i], 0).first;
}
end = std::chrono::system_clock::now();
auto emplace_hint_time = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
ASSERT_LE(emplace_hint_time, emplace_time);
}
struct A
{
A() =default;
A(int i) noexcept : _i(i) {}
A(const A& a) { _i = a._i; ++copy_ctor;; }
A& operator=(const A& a) { _i = a._i; ++copy_assign; return *this; }
A(A&& a) { _i = a._i; ++move_ctor; }
A& operator=(A&& a) { _i = a._i; ++move_assign; return *this; }
static void reset()
{
copy_ctor = 0;
copy_assign = 0;
move_ctor = 0;
move_assign = 0;
}
int _i = 0;
static int copy_ctor;
static int copy_assign;
static int move_ctor;
static int move_assign;
};
int A::copy_ctor = 0;
int A::copy_assign = 0;
int A::move_ctor = 0;
int A::move_assign = 0;
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a._i << " copy_ctor=" << a.copy_ctor << " copy_assign=" << a.copy_assign <<
" move_ctor=" << a.move_ctor << " move_assign=" << a.move_assign;
}
bool operator==(const A& a1, const A& a2) { return a1._i == a2._i; }
struct HashA
{
std::size_t operator()(const A& a) const { return std::hash<int>()(a._i); }
};
TEST(DenseHashMapMoveTest, InsertRValue_ValueMoveCount)
{
dense_hash_map<int, A> h(10);
h.set_empty_key(0);
A::reset();
h.insert(std::make_pair(5, A()));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(2, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, InsertMoved_ValueMoveCount)
{
dense_hash_map<int, A> h(10);
h.set_empty_key(0);
auto p = std::make_pair(5, A());
A::reset();
h.insert(std::move(p));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, Emplace_ValueMoveCount)
{
dense_hash_map<int, A> h;
h.set_empty_key(0);
A::reset();
h.emplace(1, 2);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(0, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, InsertRValue_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h.insert(std::make_pair(A(2), 2));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(2, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, InsertMoved_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
auto m = std::make_pair(A(2), 2);
A::reset();
h.insert(std::move(m));
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, Emplace_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h.emplace(1, 2);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(0, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, OperatorSqBck_InsertRValue_KeyMoveCount)
{
dense_hash_map<A, int, HashA> h;
h.set_empty_key(A(0));
A::reset();
h[A(1)] = 1;
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(0, A::move_assign);
}
TEST(DenseHashMapMoveTest, OperatorSqBck_InsertMoved_ValueMoveCount)
{
dense_hash_map<int, A> h;
h.set_empty_key(0);
A::reset();
h[1] = A(1);
ASSERT_EQ(0, A::copy_ctor);
ASSERT_EQ(0, A::copy_assign);
ASSERT_EQ(1, A::move_ctor);
ASSERT_EQ(1, A::move_assign);
}
TEST(DenseHashMapMoveTest, EraseConstIterator)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
const auto it = h.begin();
ASSERT_TRUE(h.end() == h.erase(it));
ASSERT_EQ(0, (int)h.size());
}
TEST(DenseHashMapMoveTest, EraseRange)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
for (int i = 0; i < 10; ++i)
h[i + 1] = i;
auto it = h.begin();
std::advance(it, 2);
auto it2 = h.begin();
std::advance(it2, 8);
auto nextit = h.erase(it, it2);
ASSERT_FALSE(h.end() == nextit);
nextit = h.erase(nextit);
ASSERT_FALSE(h.end() == nextit);
ASSERT_TRUE(h.end() == h.erase(nextit));
ASSERT_FALSE(h.end() == h.erase(h.begin()));
ASSERT_TRUE(h.end() == h.erase(h.begin()));
ASSERT_TRUE(h.empty());
}
TEST(DenseHashMapMoveTest, EraseRangeEntireMap)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
for (int i = 0; i < 10; ++i)
h[i + 1] = i;
ASSERT_TRUE(h.end() == h.erase(h.begin(), h.end()));
ASSERT_TRUE(h.empty());
}
TEST(DenseHashMapMoveTest, EraseNextElementReturned)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
h[2] = 2;
int first = h.begin()->first;
int second = first == 1 ? 2 : 1;
ASSERT_EQ(second, h.erase(h.begin())->first); // second element is returned when erasing the first one
ASSERT_TRUE(h.end() == h.erase(h.begin())); // end() is returned when erasing the second and last element
}
TEST(DenseHashMapMoveTest, EraseNumberOfElementsDeleted)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
h[2] = 2;
ASSERT_EQ(0, (int)h.erase(3));
ASSERT_EQ(1, (int)h.erase(1));
ASSERT_EQ(1, (int)h.erase(2));
ASSERT_EQ(0, (int)h.erase(4));
ASSERT_TRUE(h.empty());
}
TEST(DenseHashMapMoveTest, CBeginCEnd)
{
dense_hash_map<int, int> h;
h.set_empty_key(0);
h.set_deleted_key(-1);
h[1] = 1;
auto it = h.cbegin();
ASSERT_EQ(1, it->first);
std::advance(it, 1);
ASSERT_TRUE(it == h.cend());
using cit = dense_hash_map<int, int>::const_iterator;
cit begin = h.begin();
cit end = h.end();
ASSERT_TRUE(begin == h.cbegin());
ASSERT_TRUE(end == h.cend());
}
<|endoftext|>
|
<commit_before>#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <gtest/gtest.h>
#include <stan/math/fwd/scal/fun/value_of.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/fabs.hpp>
#include <stan/math/fwd/scal/fun/sqrt.hpp>
#include <cmath>
template <typename T>
void deriv_chol_fwd(const Eigen::Matrix<T, -1, -1>& parent_mat,
Eigen::Matrix<double,-1, -1>& vals,
Eigen::Matrix<double, -1, -1>& gradients) {
using stan::math::value_of_rec;
Eigen::Matrix<double,2,2> parent_mat_d = value_of_rec(parent_mat);
vals(0,0) = sqrt(parent_mat_d(0,0));
vals(1,0) = parent_mat_d(1,0) / sqrt(parent_mat_d(0,0));
vals(0,1) = 0.0;
vals(1,1) = sqrt(parent_mat_d(1,1) - pow(vals(1,0), 2));
double pow_neg_half_00 = pow(parent_mat_d(0,0), -0.5);
double pow_neg_half_comb = pow(parent_mat_d(1,1)
- pow(parent_mat_d(1,0),2.0)
/ parent_mat_d(0,0), -0.5);
gradients(0,0) = pow_neg_half_00 / 2 * value_of_rec(parent_mat(0,0).d_);
gradients(1,0) = -0.5 * value_of_rec(parent_mat(0,0).d_)
* pow(parent_mat_d(0,0), -1.5)
+ value_of_rec(parent_mat(1,0).d_) * pow_neg_half_00
* parent_mat_d(1,0);
gradients(0,1) = 0.0;
gradients(1,1) = 0.5 * pow_neg_half_comb
* (value_of_rec(parent_mat(1,1).d_)
* - 2 * parent_mat_d(1,0) / parent_mat_d(0,0)
* value_of_rec(parent_mat(1,0).d_)
+ pow(parent_mat_d(1,0),2.0) / pow(parent_mat_d(0,0),2.0)
* value_of_rec(parent_mat(0,0).d_));
}
TEST(AgradFwdMatrixCholeskyDecompose, exception_mat_fd) {
stan::math::matrix_fd m;
m.resize(2,2);
m << 1.0, 2.0,
2.0, 3.0;
EXPECT_THROW(stan::math::cholesky_decompose(m),std::domain_error);
m.resize(0, 0);
EXPECT_NO_THROW(stan::math::cholesky_decompose(m));
m.resize(2, 3);
EXPECT_THROW(stan::math::cholesky_decompose(m), std::invalid_argument);
// not symmetric
m.resize(2,2);
m << 1.0, 2.0,
3.0, 4.0;
EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);
}
TEST(AgradFwdMatrixCholeskyDecompose, exception_mat_ffd) {
stan::math::matrix_ffd m;
m.resize(2,2);
m << 1.0, 2.0,
2.0, 3.0;
EXPECT_THROW(stan::math::cholesky_decompose(m),std::domain_error);
m.resize(0, 0);
EXPECT_NO_THROW(stan::math::cholesky_decompose(m));
m.resize(2, 3);
EXPECT_THROW(stan::math::cholesky_decompose(m), std::invalid_argument);
// not symmetric
m.resize(2,2);
m << 1.0, 2.0,
3.0, 4.0;
EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);
}
TEST(AgradFwdMatrixCholeskyDecompose, mat_fd) {
stan::agrad::matrix_fd m0(2,2);
m0 << 2, 1, 1, 2;
m0(0,0).d_ = 1.0;
m0(0,1).d_ = 1.0;
m0(1,0).d_ = 1.0;
m0(1,1).d_ = 1.0;
using stan::math::cholesky_decompose;
stan::agrad::matrix_fd res = cholesky_decompose(m0);
Eigen::Matrix<double,-1,-1> res_mat(2,2);
Eigen::Matrix<double,-1,-1> d_mat(2,2);
deriv_chol_fwd(m0, res_mat, d_mat);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < i; ++j) {
EXPECT_FLOAT_EQ(res_mat(i,j), res(i,j).val_);
EXPECT_FLOAT_EQ(d_mat(i,j),res(i,j).d_) << "Row: " << i
<< "Col: " << j;
}
}
TEST(AgradFwdMatrixCholeskyDecompose, mat_ffd) {
stan::agrad::matrix_ffd m0(2,2);
m0 << 4, 1, 1, 4;
m0(0,0).d_ = 1.0;
m0(0,1).d_ = 1.0;
m0(1,0).d_ = 1.0;
m0(1,1).d_ = 1.0;
using stan::math::cholesky_decompose;
stan::agrad::matrix_ffd res = cholesky_decompose(m0);
Eigen::Matrix<double,-1,-1> res_mat(2,2);
Eigen::Matrix<double,-1,-1> d_mat(2,2);
deriv_chol_fwd(m0, res_mat, d_mat);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < i; ++j) {
EXPECT_FLOAT_EQ(res_mat(i,j), res(i,j).val_.val_);
EXPECT_FLOAT_EQ(d_mat(i,j),res(i,j).d_.val_) << "Row: " << i
<< " Col: " << j;
}
}
<commit_msg>b f/i-48 namespace changes agrad -> math<commit_after>#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <gtest/gtest.h>
#include <stan/math/fwd/scal/fun/value_of.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/fabs.hpp>
#include <stan/math/fwd/scal/fun/sqrt.hpp>
#include <cmath>
template <typename T>
void deriv_chol_fwd(const Eigen::Matrix<T, -1, -1>& parent_mat,
Eigen::Matrix<double,-1, -1>& vals,
Eigen::Matrix<double, -1, -1>& gradients) {
using stan::math::value_of_rec;
Eigen::Matrix<double,2,2> parent_mat_d = value_of_rec(parent_mat);
vals(0,0) = sqrt(parent_mat_d(0,0));
vals(1,0) = parent_mat_d(1,0) / sqrt(parent_mat_d(0,0));
vals(0,1) = 0.0;
vals(1,1) = sqrt(parent_mat_d(1,1) - pow(vals(1,0), 2));
double pow_neg_half_00 = pow(parent_mat_d(0,0), -0.5);
double pow_neg_half_comb = pow(parent_mat_d(1,1)
- pow(parent_mat_d(1,0),2.0)
/ parent_mat_d(0,0), -0.5);
gradients(0,0) = pow_neg_half_00 / 2 * value_of_rec(parent_mat(0,0).d_);
gradients(1,0) = -0.5 * value_of_rec(parent_mat(0,0).d_)
* pow(parent_mat_d(0,0), -1.5)
+ value_of_rec(parent_mat(1,0).d_) * pow_neg_half_00
* parent_mat_d(1,0);
gradients(0,1) = 0.0;
gradients(1,1) = 0.5 * pow_neg_half_comb
* (value_of_rec(parent_mat(1,1).d_)
* - 2 * parent_mat_d(1,0) / parent_mat_d(0,0)
* value_of_rec(parent_mat(1,0).d_)
+ pow(parent_mat_d(1,0),2.0) / pow(parent_mat_d(0,0),2.0)
* value_of_rec(parent_mat(0,0).d_));
}
TEST(AgradFwdMatrixCholeskyDecompose, exception_mat_fd) {
stan::math::matrix_fd m;
m.resize(2,2);
m << 1.0, 2.0,
2.0, 3.0;
EXPECT_THROW(stan::math::cholesky_decompose(m),std::domain_error);
m.resize(0, 0);
EXPECT_NO_THROW(stan::math::cholesky_decompose(m));
m.resize(2, 3);
EXPECT_THROW(stan::math::cholesky_decompose(m), std::invalid_argument);
// not symmetric
m.resize(2,2);
m << 1.0, 2.0,
3.0, 4.0;
EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);
}
TEST(AgradFwdMatrixCholeskyDecompose, exception_mat_ffd) {
stan::math::matrix_ffd m;
m.resize(2,2);
m << 1.0, 2.0,
2.0, 3.0;
EXPECT_THROW(stan::math::cholesky_decompose(m),std::domain_error);
m.resize(0, 0);
EXPECT_NO_THROW(stan::math::cholesky_decompose(m));
m.resize(2, 3);
EXPECT_THROW(stan::math::cholesky_decompose(m), std::invalid_argument);
// not symmetric
m.resize(2,2);
m << 1.0, 2.0,
3.0, 4.0;
EXPECT_THROW(stan::math::cholesky_decompose(m), std::domain_error);
}
TEST(AgradFwdMatrixCholeskyDecompose, mat_fd) {
stan::math::matrix_fd m0(2,2);
m0 << 2, 1, 1, 2;
m0(0,0).d_ = 1.0;
m0(0,1).d_ = 1.0;
m0(1,0).d_ = 1.0;
m0(1,1).d_ = 1.0;
using stan::math::cholesky_decompose;
stan::math::matrix_fd res = cholesky_decompose(m0);
Eigen::Matrix<double,-1,-1> res_mat(2,2);
Eigen::Matrix<double,-1,-1> d_mat(2,2);
deriv_chol_fwd(m0, res_mat, d_mat);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < i; ++j) {
EXPECT_FLOAT_EQ(res_mat(i,j), res(i,j).val_);
EXPECT_FLOAT_EQ(d_mat(i,j),res(i,j).d_) << "Row: " << i
<< "Col: " << j;
}
}
TEST(AgradFwdMatrixCholeskyDecompose, mat_ffd) {
stan::math::matrix_ffd m0(2,2);
m0 << 4, 1, 1, 4;
m0(0,0).d_ = 1.0;
m0(0,1).d_ = 1.0;
m0(1,0).d_ = 1.0;
m0(1,1).d_ = 1.0;
using stan::math::cholesky_decompose;
stan::math::matrix_ffd res = cholesky_decompose(m0);
Eigen::Matrix<double,-1,-1> res_mat(2,2);
Eigen::Matrix<double,-1,-1> d_mat(2,2);
deriv_chol_fwd(m0, res_mat, d_mat);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < i; ++j) {
EXPECT_FLOAT_EQ(res_mat(i,j), res(i,j).val_.val_);
EXPECT_FLOAT_EQ(d_mat(i,j),res(i,j).d_.val_) << "Row: " << i
<< " Col: " << j;
}
}
<|endoftext|>
|
<commit_before>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include <cassert>
#include <algorithm>
#include <string>
#include <set>
namespace argparse {
ParserError::ParserError(const std::string& error)
: runtime_error("error: " + error), has_displayed_usage(false)
{
}
void OnParserError(Running& running, const Parser* parser, ParserError& p) {
if( p.has_displayed_usage == false ) {
running.o << "Usage:";
parser->WriteUsage(running);
p.has_displayed_usage = true;
}
}
Arguments::Arguments(int argc, char* argv[]) : name_(argv[0])
{
for (int i = 1; i < argc; ++i)
{
args_.push_back(argv[i]);
}
}
Arguments::Arguments(const std::string& name, const std::vector<std::string>& args) : name_(name), args_(args) {
}
const std::string Arguments::operator[](int index) const
{
return args_[index];
}
const bool Arguments::is_empty() const
{
return args_.empty();
}
const std::string Arguments::name() const
{
return name_;
}
const size_t Arguments::size() const
{
return args_.size();
}
const std::string Arguments::ConsumeOne(const std::string& error)
{
if (is_empty()) throw ParserError(error);
const std::string r = args_[0];
args_.erase(args_.begin());
return r;
}
Count::Count(size_t c)
: count_(c)
, type_(Const)
{
}
Count::Count(Count::Type t)
: count_(0)
, type_(t)
{
assert(t != Const);
}
Count::Type Count::type() const
{
return type_;
}
size_t Count::count() const
{
return count_;
}
Running::Running(const std::string& aapp, std::ostream& ao, std::ostream& ae)
: app(aapp)
, o(ao)
, e(ae)
, quit(false)
{
}
Argument::~Argument()
{
}
Argument::Argument(const Count& co)
: count_(co)
, has_been_parsed_(false)
, has_several_(false)
{
}
bool Argument::has_been_parsed() const {
return has_been_parsed_;
}
void Argument::set_has_been_parsed(bool v) {
if (has_several_) return;
has_been_parsed_ = v;
}
void Argument::ConsumeArguments(Running& r, Arguments& args, const std::string& argname) {
switch (count_.type())
{
case Count::Const:
for (size_t i = 0; i < count_.count(); ++i)
{
std::stringstream ss;
ss << "argument " << argname << ": expected ";
if (count_.count() == 1)
{
ss << "one argument";
}
else
{
ss << count_.count() << " argument(s), " << i << " already given";
}
OnArgument(r, args.ConsumeOne(ss.str()));
// abort on optional?
}
return;
case Count::MoreThanOne:
OnArgument(r, args.ConsumeOne("argument " + argname + ": expected atleast one argument"));
// fall through
case Count::ZeroOrMore:
while (args.is_empty() == false)
{
OnArgument(r, args.ConsumeOne("internal error"));
}
return;
case Count::Optional:
if (args.is_empty()) {
OnArgument(r, "");
return;
}
if (IsOptional(args[0])) {
OnArgument(r, "");
return;
}
OnArgument(r, args.ConsumeOne("internal error"));
return;
case Count::None:
OnArgument(r, "");
return;
default:
assert(0 && "internal error, ArgumentT::parse invalid Count");
throw "internal error, ArgumentT::parse invalid Count";
}
}
void Argument::set_has_several() {
has_several_ = true;
}
bool IsOptional(const std::string& arg)
{
if (arg.empty()) return false; // todo: assert this?
return arg[0] == '-';
}
Extra::Extra()
: count_(1)
, has_several_(false)
{
}
Extra& Extra::help(const std::string& h)
{
help_ = h;
return *this;
}
const std::string& Extra::help() const
{
return help_;
}
Extra& Extra::count(const Count c)
{
count_ = c;
return *this;
}
const Count& Extra::count() const
{
return count_;
}
Extra& Extra::metavar(const std::string& metavar)
{
metaVar_ = metavar;
return *this;
}
const std::string& Extra::metavar() const
{
return metaVar_;
}
Extra& Extra::several() {
has_several_ = true;
return *this;
}
bool Extra::has_several() const {
return has_several_;
}
std::string ToUpper(const std::string& s)
{
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), toupper);
return str;
}
Help::Help(const std::string& name, const Extra& e)
: name_(name)
, help_(e.help())
, metavar_(e.metavar())
, count_(e.count().type())
, countcount_(e.count().count())
{
}
const std::string Help::GetUsage() const
{
if (IsOptional(name_))
{
const auto rep = GetMetavarReprestentation();
if( rep.empty()) return "[" + name_ + "]";
return "[" + name_ + " " + rep + "]";
}
else
{
return GetMetavarReprestentation();
}
}
const std::string Help::GetMetavarReprestentation() const
{
switch (count_)
{
case Count::None:
return "";
case Count::MoreThanOne:
return GetMetavarName() + " [" + GetMetavarName() + " ...]";
case Count::Optional:
return "[" + GetMetavarName() + "]";
case Count::ZeroOrMore:
return "[" + GetMetavarName() + " [" + GetMetavarName() + " ...]]";
case Count::Const:
{
std::ostringstream ss;
for (size_t i = 0; i < countcount_; ++i)
{
if (i != 0)
{
ss << " ";
}
ss << GetMetavarName();
}
return ss.str();
}
default:
assert(false && "missing case");
throw "invalid count type in " __FUNCTION__;
}
}
const std::string Help::GetMetavarName() const
{
if (metavar_.empty() == false)
{
return metavar_;
}
else
{
if (IsOptional(name_))
{
return ToUpper(name_.substr(1));
}
else
{
return name_;
}
}
}
const std::string Help::GetHelpCommand() const
{
if (IsOptional(name_))
{
const auto meta = GetMetavarReprestentation();
if (meta.empty()) {
return name_;
}
else {
return name_ + " " + meta;
}
}
else
{
return GetMetavarName();
}
}
const std::string& Help::help() const
{
return help_;
}
struct CallHelp : public Argument
{
CallHelp(Parser* on)
: Argument( Count(Count::Optional) )
, parser(on)
{
}
void OnArgument(Running& r, const std::string& argname) override
{
parser->WriteHelp(r);
r.quit = true;
}
Parser* parser;
};
class ParserChild : public Parser {
public:
ParserChild(const std::string& desc, const Parser* parent) : Parser(desc), parent_(parent) {}
void WriteUsage(Running& r) const override {
parent_->WriteUsage(r);
Parser::WriteUsage(r);
}
private:
const Parser* parent_;
};
Parser::Parser(const std::string& d, const std::string aappname)
: positionalIndex_(0)
, description_(d)
, appname_(aappname)
, sub_parsers_("subparser")
{
std::shared_ptr<Argument> arg(new CallHelp(this));
AddArgument("-h", arg, Extra().count(Count(Count::None)).help("Show this help message and exit."));
}
Parser::ParseStatus Parser::ParseArgs(int argc, char* argv[], std::ostream& out, std::ostream& error) const
{
Arguments args(argc, argv);
return ParseArgs(args, out, error);
}
void Parser::AddSubParser(const std::string& name, SubParser* parser) {
sub_parsers_(name, parser);
}
Parser::ParseStatus Parser::ParseArgs(const Arguments& arguments, std::ostream& out, std::ostream& error) const {
Arguments args = arguments;
Running running(arguments.name(), out, error);
try {
return DoParseArgs(args, running);
}
catch (ParserError& p) {
OnParserError(running, this, p);
running.e << p.what() << "\n";
running.o << "\n";
return Parser::ParseStatus::ParseFailed;
}
}
Parser::ParseStatus Parser::DoParseArgs(Arguments& args, Running& running) const {
try
{
while (false == args.is_empty())
{
bool isParsed = false;
const bool isParsingPositionals = positionalIndex_ < positionals_.size();
if (IsOptional(args[0]))
{
// optional
const std::string arg = args[0];
Optionals::const_iterator r = optionals_.find(arg);
if (r == optionals_.end())
{
if (isParsingPositionals == false) {
throw ParserError("Unknown optional argument: " + arg); // todo: implement partial matching of arguments?
}
}
else {
if (false == r->second->has_been_parsed()) {
isParsed = true;
args.ConsumeOne(); // the optional command = arg[0}
r->second->ConsumeArguments(running, args, arg);
r->second->set_has_been_parsed(true);
if (running.quit) return ParseStatus::ParseQuit;
}
}
}
bool consumed = false;
if (isParsed == false) {
if (positionalIndex_ >= positionals_.size())
{
if (sub_parsers_.empty()) {
throw ParserError("All positional arguments have been consumed: " + args[0]);
}
else {
std::string subname;
SubParser* sub = sub_parsers_.Convert(args[0], &subname);
sub_parser_used_ = subname;
ParserChild parser(args[0], this);
sub->AddParser(parser);
consumed = true;
args.ConsumeOne("SUBCOMMAND");
try {
return parser.DoParseArgs(args, running);
}
catch (ParserError& p) {
OnParserError(running, &parser, p);
running.e << "error: Failed to parse " << subname << ":\n";
throw;
}
}
}
if (consumed == false) {
ArgumentPtr p = positionals_[positionalIndex_];
++positionalIndex_;
p->ConsumeArguments(running, args, "POSITIONAL"); // todo: give better name or something
}
}
}
if (positionalIndex_ != positionals_.size())
{
throw ParserError("too few arguments."); // todo: list a few missing arguments...
}
return ParseComplete;
}
catch (ParserError& p)
{
OnParserError(running, this, p);
throw;
}
}
void Parser::WriteHelp(Running& r) const
{
r.o << "Usage:";
r.o << " " << (appname_.empty() ? r.app : appname_);
WriteUsage(r);
r.o << std::endl << description_ << std::endl << std::endl;
const std::string sep = "\t";
const std::string ins = " ";
if (helpPositional_.empty() == false)
{
r.o << "Positional arguments:" << std::endl;
for (const Help& positional : helpPositional_)
{
r.o << ins << positional.GetHelpCommand();
const auto h = positional.help();
if (h.empty() == false) {
r.o << sep << h;
}
r.o << std::endl;
}
r.o << std::endl;
}
if (helpOptional_.empty() == false)
{
r.o << "Optional arguments:" << std::endl;
std::set<std::string> opts;
for (const Help& optional : helpOptional_)
{
std::ostringstream ss;
ss << ins << optional.GetHelpCommand();
const auto h = optional.help();
if( h.empty() == false) {
ss << sep << h;
}
opts.insert(ss.str());
}
for (const auto& s : opts) {
r.o << s << "\n";
}
}
r.o << std::endl;
}
void Parser::WriteUsage(Running& r) const
{
for (const Help& optional : helpOptional_)
{
r.o << " " << optional.GetUsage();
}
if (false == sub_parsers_.empty()) {
// if the sub-parser is set, use it instead of the array
if (false == sub_parser_used_.empty()) {
r.o << " " << sub_parser_used_;
}
else {
const auto sp = sub_parsers_.names();
r.o << " {";
bool first = true;
for (const auto& p : sp) {
if (first == false) {
r.o << "|";
}
first = false;
r.o << p;
}
r.o << "}";
}
}
for (const Help& positional : helpPositional_)
{
r.o << " " << positional.GetUsage();
}
}
Parser& Parser::AddArgument(const std::string& commands, ArgumentPtr arg, const Extra& extra)
{
if( extra.has_several() ) {
arg->set_has_several();
}
const auto names = Tokenize(commands, ",", true);
std::string thename = "";
for(const auto name: names) {
if (IsOptional(name))
{
optionals_.insert(Optionals::value_type(name, arg));
if (thename.empty()) thename = name.substr(1);
}
else
{
positionals_.push_back(arg);
if( thename.empty() ) thename = name;
}
}
Extra e = extra;
if (e.metavar().empty()) {
e.metavar(thename);
}
helpOptional_.push_back(Help(commands, e));
return *this;
}
}
<commit_msg>fixed positional help<commit_after>// Copyright (2015) Gustav
#include "finans/core/commandline.h"
#include <cassert>
#include <algorithm>
#include <string>
#include <set>
namespace argparse {
ParserError::ParserError(const std::string& error)
: runtime_error("error: " + error), has_displayed_usage(false)
{
}
void OnParserError(Running& running, const Parser* parser, ParserError& p) {
if( p.has_displayed_usage == false ) {
running.o << "Usage:";
parser->WriteUsage(running);
p.has_displayed_usage = true;
}
}
Arguments::Arguments(int argc, char* argv[]) : name_(argv[0])
{
for (int i = 1; i < argc; ++i)
{
args_.push_back(argv[i]);
}
}
Arguments::Arguments(const std::string& name, const std::vector<std::string>& args) : name_(name), args_(args) {
}
const std::string Arguments::operator[](int index) const
{
return args_[index];
}
const bool Arguments::is_empty() const
{
return args_.empty();
}
const std::string Arguments::name() const
{
return name_;
}
const size_t Arguments::size() const
{
return args_.size();
}
const std::string Arguments::ConsumeOne(const std::string& error)
{
if (is_empty()) throw ParserError(error);
const std::string r = args_[0];
args_.erase(args_.begin());
return r;
}
Count::Count(size_t c)
: count_(c)
, type_(Const)
{
}
Count::Count(Count::Type t)
: count_(0)
, type_(t)
{
assert(t != Const);
}
Count::Type Count::type() const
{
return type_;
}
size_t Count::count() const
{
return count_;
}
Running::Running(const std::string& aapp, std::ostream& ao, std::ostream& ae)
: app(aapp)
, o(ao)
, e(ae)
, quit(false)
{
}
Argument::~Argument()
{
}
Argument::Argument(const Count& co)
: count_(co)
, has_been_parsed_(false)
, has_several_(false)
{
}
bool Argument::has_been_parsed() const {
return has_been_parsed_;
}
void Argument::set_has_been_parsed(bool v) {
if (has_several_) return;
has_been_parsed_ = v;
}
void Argument::ConsumeArguments(Running& r, Arguments& args, const std::string& argname) {
switch (count_.type())
{
case Count::Const:
for (size_t i = 0; i < count_.count(); ++i)
{
std::stringstream ss;
ss << "argument " << argname << ": expected ";
if (count_.count() == 1)
{
ss << "one argument";
}
else
{
ss << count_.count() << " argument(s), " << i << " already given";
}
OnArgument(r, args.ConsumeOne(ss.str()));
// abort on optional?
}
return;
case Count::MoreThanOne:
OnArgument(r, args.ConsumeOne("argument " + argname + ": expected atleast one argument"));
// fall through
case Count::ZeroOrMore:
while (args.is_empty() == false)
{
OnArgument(r, args.ConsumeOne("internal error"));
}
return;
case Count::Optional:
if (args.is_empty()) {
OnArgument(r, "");
return;
}
if (IsOptional(args[0])) {
OnArgument(r, "");
return;
}
OnArgument(r, args.ConsumeOne("internal error"));
return;
case Count::None:
OnArgument(r, "");
return;
default:
assert(0 && "internal error, ArgumentT::parse invalid Count");
throw "internal error, ArgumentT::parse invalid Count";
}
}
void Argument::set_has_several() {
has_several_ = true;
}
bool IsOptional(const std::string& arg)
{
if (arg.empty()) return false; // todo: assert this?
return arg[0] == '-';
}
Extra::Extra()
: count_(1)
, has_several_(false)
{
}
Extra& Extra::help(const std::string& h)
{
help_ = h;
return *this;
}
const std::string& Extra::help() const
{
return help_;
}
Extra& Extra::count(const Count c)
{
count_ = c;
return *this;
}
const Count& Extra::count() const
{
return count_;
}
Extra& Extra::metavar(const std::string& metavar)
{
metaVar_ = metavar;
return *this;
}
const std::string& Extra::metavar() const
{
return metaVar_;
}
Extra& Extra::several() {
has_several_ = true;
return *this;
}
bool Extra::has_several() const {
return has_several_;
}
std::string ToUpper(const std::string& s)
{
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), toupper);
return str;
}
Help::Help(const std::string& name, const Extra& e)
: name_(name)
, help_(e.help())
, metavar_(e.metavar())
, count_(e.count().type())
, countcount_(e.count().count())
{
}
const std::string Help::GetUsage() const
{
if (IsOptional(name_))
{
const auto rep = GetMetavarReprestentation();
if( rep.empty()) return "[" + name_ + "]";
return "[" + name_ + " " + rep + "]";
}
else
{
return GetMetavarReprestentation();
}
}
const std::string Help::GetMetavarReprestentation() const
{
switch (count_)
{
case Count::None:
return "";
case Count::MoreThanOne:
return GetMetavarName() + " [" + GetMetavarName() + " ...]";
case Count::Optional:
return "[" + GetMetavarName() + "]";
case Count::ZeroOrMore:
return "[" + GetMetavarName() + " [" + GetMetavarName() + " ...]]";
case Count::Const:
{
std::ostringstream ss;
for (size_t i = 0; i < countcount_; ++i)
{
if (i != 0)
{
ss << " ";
}
ss << GetMetavarName();
}
return ss.str();
}
default:
assert(false && "missing case");
throw "invalid count type in " __FUNCTION__;
}
}
const std::string Help::GetMetavarName() const
{
if (metavar_.empty() == false)
{
return metavar_;
}
else
{
if (IsOptional(name_))
{
return ToUpper(name_.substr(1));
}
else
{
return name_;
}
}
}
const std::string Help::GetHelpCommand() const
{
if (IsOptional(name_))
{
const auto meta = GetMetavarReprestentation();
if (meta.empty()) {
return name_;
}
else {
return name_ + " " + meta;
}
}
else
{
return GetMetavarName();
}
}
const std::string& Help::help() const
{
return help_;
}
struct CallHelp : public Argument
{
CallHelp(Parser* on)
: Argument( Count(Count::Optional) )
, parser(on)
{
}
void OnArgument(Running& r, const std::string& argname) override
{
parser->WriteHelp(r);
r.quit = true;
}
Parser* parser;
};
class ParserChild : public Parser {
public:
ParserChild(const std::string& desc, const Parser* parent) : Parser(desc), parent_(parent) {}
void WriteUsage(Running& r) const override {
parent_->WriteUsage(r);
Parser::WriteUsage(r);
}
private:
const Parser* parent_;
};
Parser::Parser(const std::string& d, const std::string aappname)
: positionalIndex_(0)
, description_(d)
, appname_(aappname)
, sub_parsers_("subparser")
{
std::shared_ptr<Argument> arg(new CallHelp(this));
AddArgument("-h", arg, Extra().count(Count(Count::None)).help("Show this help message and exit."));
}
Parser::ParseStatus Parser::ParseArgs(int argc, char* argv[], std::ostream& out, std::ostream& error) const
{
Arguments args(argc, argv);
return ParseArgs(args, out, error);
}
void Parser::AddSubParser(const std::string& name, SubParser* parser) {
sub_parsers_(name, parser);
}
Parser::ParseStatus Parser::ParseArgs(const Arguments& arguments, std::ostream& out, std::ostream& error) const {
Arguments args = arguments;
Running running(arguments.name(), out, error);
try {
return DoParseArgs(args, running);
}
catch (ParserError& p) {
OnParserError(running, this, p);
running.e << p.what() << "\n";
running.o << "\n";
return Parser::ParseStatus::ParseFailed;
}
}
Parser::ParseStatus Parser::DoParseArgs(Arguments& args, Running& running) const {
try
{
while (false == args.is_empty())
{
bool isParsed = false;
const bool isParsingPositionals = positionalIndex_ < positionals_.size();
if (IsOptional(args[0]))
{
// optional
const std::string arg = args[0];
Optionals::const_iterator r = optionals_.find(arg);
if (r == optionals_.end())
{
if (isParsingPositionals == false) {
throw ParserError("Unknown optional argument: " + arg); // todo: implement partial matching of arguments?
}
}
else {
if (false == r->second->has_been_parsed()) {
isParsed = true;
args.ConsumeOne(); // the optional command = arg[0}
r->second->ConsumeArguments(running, args, arg);
r->second->set_has_been_parsed(true);
if (running.quit) return ParseStatus::ParseQuit;
}
}
}
bool consumed = false;
if (isParsed == false) {
if (positionalIndex_ >= positionals_.size())
{
if (sub_parsers_.empty()) {
throw ParserError("All positional arguments have been consumed: " + args[0]);
}
else {
std::string subname;
SubParser* sub = sub_parsers_.Convert(args[0], &subname);
sub_parser_used_ = subname;
ParserChild parser(args[0], this);
sub->AddParser(parser);
consumed = true;
args.ConsumeOne("SUBCOMMAND");
try {
return parser.DoParseArgs(args, running);
}
catch (ParserError& p) {
OnParserError(running, &parser, p);
running.e << "error: Failed to parse " << subname << ":\n";
throw;
}
}
}
if (consumed == false) {
ArgumentPtr p = positionals_[positionalIndex_];
++positionalIndex_;
p->ConsumeArguments(running, args, "POSITIONAL"); // todo: give better name or something
}
}
}
if (positionalIndex_ != positionals_.size())
{
throw ParserError("too few arguments."); // todo: list a few missing arguments...
}
return ParseComplete;
}
catch (ParserError& p)
{
OnParserError(running, this, p);
throw;
}
}
void Parser::WriteHelp(Running& r) const
{
r.o << "Usage:";
r.o << " " << (appname_.empty() ? r.app : appname_);
WriteUsage(r);
r.o << std::endl << description_ << std::endl << std::endl;
const std::string sep = "\t";
const std::string ins = " ";
if (helpPositional_.empty() == false)
{
r.o << "Positional arguments:" << std::endl;
for (const Help& positional : helpPositional_)
{
r.o << ins << positional.GetHelpCommand();
const auto h = positional.help();
if (h.empty() == false) {
r.o << sep << h;
}
r.o << std::endl;
}
r.o << std::endl;
}
if (helpOptional_.empty() == false)
{
r.o << "Optional arguments:" << std::endl;
std::set<std::string> opts;
for (const Help& optional : helpOptional_)
{
std::ostringstream ss;
ss << ins << optional.GetHelpCommand();
const auto h = optional.help();
if( h.empty() == false) {
ss << sep << h;
}
opts.insert(ss.str());
}
for (const auto& s : opts) {
r.o << s << "\n";
}
}
r.o << std::endl;
}
void Parser::WriteUsage(Running& r) const
{
for (const Help& optional : helpOptional_)
{
r.o << " " << optional.GetUsage();
}
if (false == sub_parsers_.empty()) {
// if the sub-parser is set, use it instead of the array
if (false == sub_parser_used_.empty()) {
r.o << " " << sub_parser_used_;
}
else {
const auto sp = sub_parsers_.names();
r.o << " {";
bool first = true;
for (const auto& p : sp) {
if (first == false) {
r.o << "|";
}
first = false;
r.o << p;
}
r.o << "}";
}
}
for (const Help& positional : helpPositional_)
{
r.o << " " << positional.GetUsage();
}
}
Parser& Parser::AddArgument(const std::string& commands, ArgumentPtr arg, const Extra& extra)
{
if( extra.has_several() ) {
arg->set_has_several();
}
const auto names = Tokenize(commands, ",", true);
std::string thename = "";
int optionalcount = 0;
int positionalcount = 0;
for(const auto name: names) {
if (IsOptional(name))
{
optionals_.insert(Optionals::value_type(name, arg));
if (thename.empty()) thename = name.substr(1);
++optionalcount;
}
else
{
positionals_.push_back(arg);
if( thename.empty() ) thename = name;
++positionalcount;
}
}
Extra e = extra;
if (e.metavar().empty()) {
e.metavar(thename);
}
if (positionalcount > 0 && optionalcount > 0) {
assert(false && "Optional and positional in argumentlist is not supported.");
}
if( positionalcount > 0 ) {
helpPositional_.push_back(Help(commands, e));
}
else {
assert(optionalcount > 0);
helpOptional_.push_back(Help(commands, e));
}
return *this;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtNetwork/QNetworkCookieJar>
class tst_QNetworkCookieJar: public QObject
{
Q_OBJECT
private slots:
void getterSetter();
void setCookiesFromUrl_data();
void setCookiesFromUrl();
void cookiesForUrl_data();
void cookiesForUrl();
};
QT_BEGIN_NAMESPACE
namespace QTest {
template<>
char *toString(const QNetworkCookie &cookie)
{
return qstrdup(cookie.toRawForm());
}
template<>
char *toString(const QList<QNetworkCookie> &list)
{
QString result = "QList(";
bool first = true;
foreach (QNetworkCookie cookie, list) {
if (!first)
result += ", ";
first = false;
result += QString::fromLatin1("QNetworkCookie(%1)").arg(QLatin1String(cookie.toRawForm()));
}
return qstrdup(result.append(')').toLocal8Bit());
}
}
QT_END_NAMESPACE
class MyCookieJar: public QNetworkCookieJar
{
public:
inline QList<QNetworkCookie> allCookies() const
{ return QNetworkCookieJar::allCookies(); }
inline void setAllCookies(const QList<QNetworkCookie> &cookieList)
{ QNetworkCookieJar::setAllCookies(cookieList); }
};
void tst_QNetworkCookieJar::getterSetter()
{
MyCookieJar jar;
QVERIFY(jar.allCookies().isEmpty());
QList<QNetworkCookie> list;
QNetworkCookie cookie;
cookie.setName("a");
list << cookie;
jar.setAllCookies(list);
QCOMPARE(jar.allCookies(), list);
}
void tst_QNetworkCookieJar::setCookiesFromUrl_data()
{
QTest::addColumn<QList<QNetworkCookie> >("preset");
QTest::addColumn<QNetworkCookie>("newCookie");
QTest::addColumn<QString>("referenceUrl");
QTest::addColumn<QList<QNetworkCookie> >("expectedResult");
QTest::addColumn<bool>("setCookies");
QList<QNetworkCookie> preset;
QList<QNetworkCookie> result;
QNetworkCookie cookie;
cookie.setName("a");
cookie.setPath("/");
cookie.setDomain("www.foo.tld");
result += cookie;
QTest::newRow("just-add") << preset << cookie << "http://www.foo.tld" << result << true;
preset = result;
QTest::newRow("replace-1") << preset << cookie << "http://www.foo.tld" << result << true;
cookie.setValue("bc");
result.clear();
result += cookie;
QTest::newRow("replace-2") << preset << cookie << "http://www.foo.tld" << result << true;
preset = result;
cookie.setName("d");
result += cookie;
QTest::newRow("append") << preset << cookie << "http://www.foo.tld" << result << true;
cookie = preset.at(0);
result = preset;
cookie.setPath("/something");
result += cookie;
QTest::newRow("diff-path") << preset << cookie << "http://www.foo.tld/something" << result << true;
preset.clear();
preset += cookie;
cookie.setPath("/");
QTest::newRow("diff-path-order") << preset << cookie << "http://www.foo.tld" << result << true;
// security test:
result.clear();
preset.clear();
cookie.setDomain("something.completely.different");
QTest::newRow("security-domain-1") << preset << cookie << "http://www.foo.tld" << result << false;
cookie.setDomain("www.foo.tld");
cookie.setPath("/something");
QTest::newRow("security-path-1") << preset << cookie << "http://www.foo.tld" << result << false;
// setting the defaults:
QNetworkCookie finalCookie = cookie;
finalCookie.setPath("/something/");
cookie.setPath("");
cookie.setDomain("");
result.clear();
result += finalCookie;
QTest::newRow("defaults-1") << preset << cookie << "http://www.foo.tld/something/" << result << true;
finalCookie.setPath("/");
result.clear();
result += finalCookie;
QTest::newRow("defaults-2") << preset << cookie << "http://www.foo.tld" << result << true;
// security test: do not accept cookie domains like ".com" nor ".com." (see RFC 2109 section 4.3.2)
result.clear();
preset.clear();
cookie.setDomain(".com");
QTest::newRow("rfc2109-4.3.2-ex3") << preset << cookie << "http://x.foo.com" << result << false;
result.clear();
preset.clear();
cookie.setDomain(".com.");
QTest::newRow("rfc2109-4.3.2-ex3-2") << preset << cookie << "http://x.foo.com" << result << false;
}
void tst_QNetworkCookieJar::setCookiesFromUrl()
{
QFETCH(QList<QNetworkCookie>, preset);
QFETCH(QNetworkCookie, newCookie);
QFETCH(QString, referenceUrl);
QFETCH(QList<QNetworkCookie>, expectedResult);
QFETCH(bool, setCookies);
QList<QNetworkCookie> cookieList;
cookieList += newCookie;
MyCookieJar jar;
jar.setAllCookies(preset);
QCOMPARE(jar.setCookiesFromUrl(cookieList, referenceUrl), setCookies);
QList<QNetworkCookie> result = jar.allCookies();
foreach (QNetworkCookie cookie, expectedResult) {
QVERIFY2(result.contains(cookie), cookie.toRawForm());
result.removeAll(cookie);
}
QVERIFY2(result.isEmpty(), QTest::toString(result));
}
void tst_QNetworkCookieJar::cookiesForUrl_data()
{
QTest::addColumn<QList<QNetworkCookie> >("allCookies");
QTest::addColumn<QString>("url");
QTest::addColumn<QList<QNetworkCookie> >("expectedResult");
QList<QNetworkCookie> allCookies;
QList<QNetworkCookie> result;
QTest::newRow("no-cookies") << allCookies << "http://foo.bar/" << result;
QNetworkCookie cookie;
cookie.setName("a");
cookie.setPath("/web");
cookie.setDomain(".trolltech.com");
allCookies += cookie;
QTest::newRow("no-match-1") << allCookies << "http://foo.bar/" << result;
QTest::newRow("no-match-2") << allCookies << "http://foo.bar/web" << result;
QTest::newRow("no-match-3") << allCookies << "http://foo.bar/web/wiki" << result;
QTest::newRow("no-match-4") << allCookies << "http://trolltech.com" << result;
QTest::newRow("no-match-5") << allCookies << "http://qt.nokia.com" << result;
QTest::newRow("no-match-6") << allCookies << "http://trolltech.com/webinar" << result;
QTest::newRow("no-match-7") << allCookies << "http://qt.nokia.com/webinar" << result;
result = allCookies;
QTest::newRow("match-1") << allCookies << "http://trolltech.com/web" << result;
QTest::newRow("match-2") << allCookies << "http://trolltech.com/web/" << result;
QTest::newRow("match-3") << allCookies << "http://trolltech.com/web/content" << result;
QTest::newRow("match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
cookie.setPath("/web/wiki");
allCookies += cookie;
// exact same results as before:
QTest::newRow("one-match-1") << allCookies << "http://trolltech.com/web" << result;
QTest::newRow("one-match-2") << allCookies << "http://trolltech.com/web/" << result;
QTest::newRow("one-match-3") << allCookies << "http://trolltech.com/web/content" << result;
QTest::newRow("one-match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("one-match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("one-match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
result.prepend(cookie); // longer path, it must match first
QTest::newRow("two-matches-1") << allCookies << "http://trolltech.com/web/wiki" << result;
QTest::newRow("two-matches-2") << allCookies << "http://qt.nokia.com/web/wiki" << result;
// invert the order;
allCookies.clear();
allCookies << result.at(1) << result.at(0);
QTest::newRow("two-matches-3") << allCookies << "http://trolltech.com/web/wiki" << result;
QTest::newRow("two-matches-4") << allCookies << "http://qt.nokia.com/web/wiki" << result;
// expired cookie
allCookies.clear();
cookie.setExpirationDate(QDateTime::fromString("09-Nov-1999", "dd-MMM-yyyy"));
allCookies += cookie;
result.clear();
QTest::newRow("exp-match-1") << allCookies << "http://trolltech.com/web" << result;
QTest::newRow("exp-match-2") << allCookies << "http://trolltech.com/web/" << result;
QTest::newRow("exp-match-3") << allCookies << "http://trolltech.com/web/content" << result;
QTest::newRow("exp-match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("exp-match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("exp-match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
}
void tst_QNetworkCookieJar::cookiesForUrl()
{
QFETCH(QList<QNetworkCookie>, allCookies);
QFETCH(QString, url);
QFETCH(QList<QNetworkCookie>, expectedResult);
MyCookieJar jar;
jar.setAllCookies(allCookies);
QList<QNetworkCookie> result = jar.cookiesForUrl(url);
QCOMPARE(result, expectedResult);
}
QTEST_MAIN(tst_QNetworkCookieJar)
#include "tst_qnetworkcookiejar.moc"
<commit_msg>tst_qnetworkcookiejar: Backported 4.6 changes<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtNetwork/QNetworkCookieJar>
class tst_QNetworkCookieJar: public QObject
{
Q_OBJECT
private slots:
void getterSetter();
void setCookiesFromUrl_data();
void setCookiesFromUrl();
void cookiesForUrl_data();
void cookiesForUrl();
};
QT_BEGIN_NAMESPACE
namespace QTest {
template<>
char *toString(const QNetworkCookie &cookie)
{
return qstrdup(cookie.toRawForm());
}
template<>
char *toString(const QList<QNetworkCookie> &list)
{
QString result = "QList(";
bool first = true;
foreach (QNetworkCookie cookie, list) {
if (!first)
result += ", ";
first = false;
result += QString::fromLatin1("QNetworkCookie(%1)").arg(QLatin1String(cookie.toRawForm()));
}
return qstrdup(result.append(')').toLocal8Bit());
}
}
QT_END_NAMESPACE
class MyCookieJar: public QNetworkCookieJar
{
public:
inline QList<QNetworkCookie> allCookies() const
{ return QNetworkCookieJar::allCookies(); }
inline void setAllCookies(const QList<QNetworkCookie> &cookieList)
{ QNetworkCookieJar::setAllCookies(cookieList); }
};
void tst_QNetworkCookieJar::getterSetter()
{
MyCookieJar jar;
QVERIFY(jar.allCookies().isEmpty());
QList<QNetworkCookie> list;
QNetworkCookie cookie;
cookie.setName("a");
list << cookie;
jar.setAllCookies(list);
QCOMPARE(jar.allCookies(), list);
}
void tst_QNetworkCookieJar::setCookiesFromUrl_data()
{
QTest::addColumn<QList<QNetworkCookie> >("preset");
QTest::addColumn<QNetworkCookie>("newCookie");
QTest::addColumn<QString>("referenceUrl");
QTest::addColumn<QList<QNetworkCookie> >("expectedResult");
QTest::addColumn<bool>("setCookies");
QList<QNetworkCookie> preset;
QList<QNetworkCookie> result;
QNetworkCookie cookie;
cookie.setName("a");
cookie.setPath("/");
cookie.setDomain("www.foo.tld");
result += cookie;
QTest::newRow("just-add") << preset << cookie << "http://www.foo.tld" << result << true;
preset = result;
QTest::newRow("replace-1") << preset << cookie << "http://www.foo.tld" << result << true;
cookie.setValue("bc");
result.clear();
result += cookie;
QTest::newRow("replace-2") << preset << cookie << "http://www.foo.tld" << result << true;
preset = result;
cookie.setName("d");
result += cookie;
QTest::newRow("append") << preset << cookie << "http://www.foo.tld" << result << true;
cookie = preset.at(0);
result = preset;
cookie.setPath("/something");
result += cookie;
QTest::newRow("diff-path") << preset << cookie << "http://www.foo.tld/something" << result << true;
preset.clear();
preset += cookie;
cookie.setPath("/");
QTest::newRow("diff-path-order") << preset << cookie << "http://www.foo.tld" << result << true;
// security test:
result.clear();
preset.clear();
cookie.setDomain("something.completely.different");
QTest::newRow("security-domain-1") << preset << cookie << "http://www.foo.tld" << result << false;
cookie.setDomain("www.foo.tld");
cookie.setPath("/something");
QTest::newRow("security-path-1") << preset << cookie << "http://www.foo.tld" << result << false;
// setting the defaults:
QNetworkCookie finalCookie = cookie;
finalCookie.setPath("/something/");
cookie.setPath("");
cookie.setDomain("");
result.clear();
result += finalCookie;
QTest::newRow("defaults-1") << preset << cookie << "http://www.foo.tld/something/" << result << true;
finalCookie.setPath("/");
result.clear();
result += finalCookie;
QTest::newRow("defaults-2") << preset << cookie << "http://www.foo.tld" << result << true;
// security test: do not accept cookie domains like ".com" nor ".com." (see RFC 2109 section 4.3.2)
result.clear();
preset.clear();
cookie.setDomain(".com");
QTest::newRow("rfc2109-4.3.2-ex3") << preset << cookie << "http://x.foo.com" << result << false;
result.clear();
preset.clear();
cookie.setDomain(".com.");
QTest::newRow("rfc2109-4.3.2-ex3-2") << preset << cookie << "http://x.foo.com" << result << false;
}
void tst_QNetworkCookieJar::setCookiesFromUrl()
{
QFETCH(QList<QNetworkCookie>, preset);
QFETCH(QNetworkCookie, newCookie);
QFETCH(QString, referenceUrl);
QFETCH(QList<QNetworkCookie>, expectedResult);
QFETCH(bool, setCookies);
QList<QNetworkCookie> cookieList;
cookieList += newCookie;
MyCookieJar jar;
jar.setAllCookies(preset);
QCOMPARE(jar.setCookiesFromUrl(cookieList, referenceUrl), setCookies);
QList<QNetworkCookie> result = jar.allCookies();
foreach (QNetworkCookie cookie, expectedResult) {
QVERIFY2(result.contains(cookie), cookie.toRawForm());
result.removeAll(cookie);
}
QVERIFY2(result.isEmpty(), QTest::toString(result));
}
void tst_QNetworkCookieJar::cookiesForUrl_data()
{
QTest::addColumn<QList<QNetworkCookie> >("allCookies");
QTest::addColumn<QString>("url");
QTest::addColumn<QList<QNetworkCookie> >("expectedResult");
QList<QNetworkCookie> allCookies;
QList<QNetworkCookie> result;
QTest::newRow("no-cookies") << allCookies << "http://foo.bar/" << result;
QNetworkCookie cookie;
cookie.setName("a");
cookie.setPath("/web");
cookie.setDomain(".nokia.com");
allCookies += cookie;
QTest::newRow("no-match-1") << allCookies << "http://foo.bar/" << result;
QTest::newRow("no-match-2") << allCookies << "http://foo.bar/web" << result;
QTest::newRow("no-match-3") << allCookies << "http://foo.bar/web/wiki" << result;
QTest::newRow("no-match-4") << allCookies << "http://nokia.com" << result;
QTest::newRow("no-match-5") << allCookies << "http://qt.nokia.com" << result;
QTest::newRow("no-match-6") << allCookies << "http://nokia.com/webinar" << result;
QTest::newRow("no-match-7") << allCookies << "http://qt.nokia.com/webinar" << result;
result = allCookies;
QTest::newRow("match-1") << allCookies << "http://nokia.com/web" << result;
QTest::newRow("match-2") << allCookies << "http://nokia.com/web/" << result;
QTest::newRow("match-3") << allCookies << "http://nokia.com/web/content" << result;
QTest::newRow("match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
cookie.setPath("/web/wiki");
allCookies += cookie;
// exact same results as before:
QTest::newRow("one-match-1") << allCookies << "http://nokia.com/web" << result;
QTest::newRow("one-match-2") << allCookies << "http://nokia.com/web/" << result;
QTest::newRow("one-match-3") << allCookies << "http://nokia.com/web/content" << result;
QTest::newRow("one-match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("one-match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("one-match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
result.prepend(cookie); // longer path, it must match first
QTest::newRow("two-matches-1") << allCookies << "http://nokia.com/web/wiki" << result;
QTest::newRow("two-matches-2") << allCookies << "http://qt.nokia.com/web/wiki" << result;
// invert the order;
allCookies.clear();
allCookies << result.at(1) << result.at(0);
QTest::newRow("two-matches-3") << allCookies << "http://nokia.com/web/wiki" << result;
QTest::newRow("two-matches-4") << allCookies << "http://qt.nokia.com/web/wiki" << result;
// expired cookie
allCookies.clear();
cookie.setExpirationDate(QDateTime::fromString("09-Nov-1999", "dd-MMM-yyyy"));
allCookies += cookie;
result.clear();
QTest::newRow("exp-match-1") << allCookies << "http://nokia.com/web" << result;
QTest::newRow("exp-match-2") << allCookies << "http://nokia.com/web/" << result;
QTest::newRow("exp-match-3") << allCookies << "http://nokia.com/web/content" << result;
QTest::newRow("exp-match-4") << allCookies << "http://qt.nokia.com/web" << result;
QTest::newRow("exp-match-4") << allCookies << "http://qt.nokia.com/web/" << result;
QTest::newRow("exp-match-6") << allCookies << "http://qt.nokia.com/web/content" << result;
}
void tst_QNetworkCookieJar::cookiesForUrl()
{
QFETCH(QList<QNetworkCookie>, allCookies);
QFETCH(QString, url);
QFETCH(QList<QNetworkCookie>, expectedResult);
MyCookieJar jar;
jar.setAllCookies(allCookies);
QList<QNetworkCookie> result = jar.cookiesForUrl(url);
QCOMPARE(result, expectedResult);
}
QTEST_MAIN(tst_QNetworkCookieJar)
#include "tst_qnetworkcookiejar.moc"
<|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 "ui/aura_shell/default_container_layout_manager.h"
#include "base/auto_reset.h"
#include "ui/aura/desktop.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "ui/aura/screen_aura.h"
#include "ui/aura/window_types.h"
#include "ui/aura_shell/workspace/workspace.h"
#include "ui/aura_shell/workspace/workspace_manager.h"
#include "ui/base/view_prop.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_aura.h"
namespace aura_shell {
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// DefaultContainerLayoutManager, public:
DefaultContainerLayoutManager::DefaultContainerLayoutManager(
aura::Window* owner,
WorkspaceManager* workspace_manager)
: owner_(owner),
workspace_manager_(workspace_manager),
drag_window_(NULL),
ignore_calculate_bounds_(false) {
}
DefaultContainerLayoutManager::~DefaultContainerLayoutManager() {}
void DefaultContainerLayoutManager::PrepareForMoveOrResize(
aura::Window* drag,
aura::MouseEvent* event) {
drag_window_ = drag;
}
void DefaultContainerLayoutManager::CancelMoveOrResize(
aura::Window* drag,
aura::MouseEvent* event) {
drag_window_ = NULL;
}
void DefaultContainerLayoutManager::ProcessMove(
aura::Window* drag,
aura::MouseEvent* event) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
// TODO(oshima): Just zooming out may (and will) move/swap window without
// a users's intent. We probably should scroll viewport, but that may not
// be enough. See crbug.com/101826 for more discussion.
workspace_manager_->SetOverview(true);
gfx::Point point_in_owner = event->location();
aura::Window::ConvertPointToWindow(
drag,
owner_,
&point_in_owner);
// TODO(oshima): We should support simply moving to another
// workspace when the destination workspace has enough room to accomodate.
aura::Window* rotate_target =
workspace_manager_->FindRotateWindowForLocation(point_in_owner);
if (rotate_target)
workspace_manager_->RotateWindows(drag, rotate_target);
}
void DefaultContainerLayoutManager::EndMove(
aura::Window* drag,
aura::MouseEvent* evnet) {
// TODO(oshima): finish moving window between workspaces.
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
drag_window_ = NULL;
Workspace* workspace = workspace_manager_->GetActiveWorkspace();
if (workspace)
workspace->Layout(NULL, NULL);
workspace_manager_->SetOverview(false);
}
void DefaultContainerLayoutManager::EndResize(
aura::Window* drag,
aura::MouseEvent* evnet) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
drag_window_ = NULL;
Workspace* workspace = workspace_manager_->GetActiveWorkspace();
if (workspace)
workspace->Layout(NULL, NULL);
workspace_manager_->SetOverview(false);
}
////////////////////////////////////////////////////////////////////////////////
// DefaultContainerLayoutManager, aura::LayoutManager implementation:
void DefaultContainerLayoutManager::OnWindowResized() {
// Workspace is updated via DesktopObserver::OnDesktopResized.
}
void DefaultContainerLayoutManager::OnWindowAdded(aura::Window* child) {
intptr_t type = reinterpret_cast<intptr_t>(
ui::ViewProp::GetValue(child, views::NativeWidgetAura::kWindowTypeKey));
if (type != views::Widget::InitParams::TYPE_WINDOW)
return;
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
Workspace* workspace = workspace_manager_->GetActiveWorkspace();
if (workspace) {
aura::Window* active = aura::Desktop::GetInstance()->active_window();
// Active window may not be in the default container layer.
if (!workspace->Contains(active))
active = NULL;
if (workspace->AddWindowAfter(child, active))
return;
}
// Create new workspace if new |child| doesn't fit to current workspace.
Workspace* new_workspace = workspace_manager_->CreateWorkspace();
new_workspace->AddWindowAfter(child, NULL);
new_workspace->Activate();
}
void DefaultContainerLayoutManager::OnWillRemoveWindow(aura::Window* child) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
Workspace* workspace = workspace_manager_->FindBy(child);
if (!workspace)
return;
workspace->RemoveWindow(child);
if (workspace->is_empty())
delete workspace;
}
void DefaultContainerLayoutManager::OnChildWindowVisibilityChanged(
aura::Window* child,
bool visible) {
NOTIMPLEMENTED();
}
void DefaultContainerLayoutManager::CalculateBoundsForChild(
aura::Window* child,
gfx::Rect* requested_bounds) {
intptr_t type = reinterpret_cast<intptr_t>(
ui::ViewProp::GetValue(child, views::NativeWidgetAura::kWindowTypeKey));
if (type != views::Widget::InitParams::TYPE_WINDOW ||
ignore_calculate_bounds_)
return;
// If a drag window is requesting bounds, make sure its attached to
// the workarea's top and fits within the total drag area.
if (drag_window_) {
gfx::Rect drag_area = workspace_manager_->GetDragAreaBounds();
requested_bounds->set_y(drag_area.y());
*requested_bounds = requested_bounds->AdjustToFit(drag_area);
return;
}
Workspace* workspace = workspace_manager_->FindBy(child);
gfx::Rect work_area = workspace->GetWorkAreaBounds();
requested_bounds->set_origin(
gfx::Point(child->GetTargetBounds().x(), work_area.y()));
*requested_bounds = requested_bounds->AdjustToFit(work_area);
}
} // namespace internal
} // namespace aura_shell
<commit_msg>Activate the workspace that dragged window has landed.<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 "ui/aura_shell/default_container_layout_manager.h"
#include "base/auto_reset.h"
#include "ui/aura/desktop.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "ui/aura/screen_aura.h"
#include "ui/aura/window_types.h"
#include "ui/aura_shell/workspace/workspace.h"
#include "ui/aura_shell/workspace/workspace_manager.h"
#include "ui/base/view_prop.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_aura.h"
namespace aura_shell {
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// DefaultContainerLayoutManager, public:
DefaultContainerLayoutManager::DefaultContainerLayoutManager(
aura::Window* owner,
WorkspaceManager* workspace_manager)
: owner_(owner),
workspace_manager_(workspace_manager),
drag_window_(NULL),
ignore_calculate_bounds_(false) {
}
DefaultContainerLayoutManager::~DefaultContainerLayoutManager() {}
void DefaultContainerLayoutManager::PrepareForMoveOrResize(
aura::Window* drag,
aura::MouseEvent* event) {
drag_window_ = drag;
}
void DefaultContainerLayoutManager::CancelMoveOrResize(
aura::Window* drag,
aura::MouseEvent* event) {
drag_window_ = NULL;
}
void DefaultContainerLayoutManager::ProcessMove(
aura::Window* drag,
aura::MouseEvent* event) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
// TODO(oshima): Just zooming out may (and will) move/swap window without
// a users's intent. We probably should scroll viewport, but that may not
// be enough. See crbug.com/101826 for more discussion.
workspace_manager_->SetOverview(true);
gfx::Point point_in_owner = event->location();
aura::Window::ConvertPointToWindow(
drag,
owner_,
&point_in_owner);
// TODO(oshima): We should support simply moving to another
// workspace when the destination workspace has enough room to accomodate.
aura::Window* rotate_target =
workspace_manager_->FindRotateWindowForLocation(point_in_owner);
if (rotate_target)
workspace_manager_->RotateWindows(drag, rotate_target);
}
void DefaultContainerLayoutManager::EndMove(
aura::Window* drag,
aura::MouseEvent* evnet) {
// TODO(oshima): finish moving window between workspaces.
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
drag_window_ = NULL;
Workspace* workspace = workspace_manager_->FindBy(drag);
workspace->Layout(NULL, NULL);
workspace->Activate();
workspace_manager_->SetOverview(false);
}
void DefaultContainerLayoutManager::EndResize(
aura::Window* drag,
aura::MouseEvent* evnet) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
drag_window_ = NULL;
Workspace* workspace = workspace_manager_->GetActiveWorkspace();
if (workspace)
workspace->Layout(NULL, NULL);
workspace_manager_->SetOverview(false);
}
////////////////////////////////////////////////////////////////////////////////
// DefaultContainerLayoutManager, aura::LayoutManager implementation:
void DefaultContainerLayoutManager::OnWindowResized() {
// Workspace is updated via DesktopObserver::OnDesktopResized.
}
void DefaultContainerLayoutManager::OnWindowAdded(aura::Window* child) {
intptr_t type = reinterpret_cast<intptr_t>(
ui::ViewProp::GetValue(child, views::NativeWidgetAura::kWindowTypeKey));
if (type != views::Widget::InitParams::TYPE_WINDOW)
return;
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
Workspace* workspace = workspace_manager_->GetActiveWorkspace();
if (workspace) {
aura::Window* active = aura::Desktop::GetInstance()->active_window();
// Active window may not be in the default container layer.
if (!workspace->Contains(active))
active = NULL;
if (workspace->AddWindowAfter(child, active))
return;
}
// Create new workspace if new |child| doesn't fit to current workspace.
Workspace* new_workspace = workspace_manager_->CreateWorkspace();
new_workspace->AddWindowAfter(child, NULL);
new_workspace->Activate();
}
void DefaultContainerLayoutManager::OnWillRemoveWindow(aura::Window* child) {
AutoReset<bool> reset(&ignore_calculate_bounds_, true);
Workspace* workspace = workspace_manager_->FindBy(child);
if (!workspace)
return;
workspace->RemoveWindow(child);
if (workspace->is_empty())
delete workspace;
}
void DefaultContainerLayoutManager::OnChildWindowVisibilityChanged(
aura::Window* child,
bool visible) {
NOTIMPLEMENTED();
}
void DefaultContainerLayoutManager::CalculateBoundsForChild(
aura::Window* child,
gfx::Rect* requested_bounds) {
intptr_t type = reinterpret_cast<intptr_t>(
ui::ViewProp::GetValue(child, views::NativeWidgetAura::kWindowTypeKey));
if (type != views::Widget::InitParams::TYPE_WINDOW ||
ignore_calculate_bounds_)
return;
// If a drag window is requesting bounds, make sure its attached to
// the workarea's top and fits within the total drag area.
if (drag_window_) {
gfx::Rect drag_area = workspace_manager_->GetDragAreaBounds();
requested_bounds->set_y(drag_area.y());
*requested_bounds = requested_bounds->AdjustToFit(drag_area);
return;
}
Workspace* workspace = workspace_manager_->FindBy(child);
gfx::Rect work_area = workspace->GetWorkAreaBounds();
requested_bounds->set_origin(
gfx::Point(child->GetTargetBounds().x(), work_area.y()));
*requested_bounds = requested_bounds->AdjustToFit(work_area);
}
} // namespace internal
} // namespace aura_shell
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2009 by Tobias Koenig <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "search.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "fetchhelper.h"
#include "handlerhelper.h"
#include "imapstreamparser.h"
#include "nepomuksearch.h"
#include "response.h"
#include "storage/selectquerybuilder.h"
#include "search/agentsearchrequest.h"
#include "search/searchmanager.h"
#include "libs/protocol_p.h"
#include <QtCore/QStringList>
using namespace Akonadi;
Search::Search()
: Handler()
{
}
Search::~Search()
{
}
bool Search::parseStream()
{
QStringList mimeTypes;
QVector<qint64> collectionIds;
bool recursive = false;
QString queryString;
// Backward compatibility
if ( !connection()->capabilities().serverSideSearch() ) {
searchNepomuk();
} else {
while (m_streamParser->hasString()) {
const QByteArray param = m_streamParser->readString();
if ( param == AKONADI_PARAM_MIMETYPE ) {
const QList<QByteArray> mt = m_streamParser->readParenthesizedList();
mimeTypes.reserve( mt.size() );
Q_FOREACH ( const QByteArray &ba, mt ) {
mimeTypes.append( QString::fromLatin1( ba ) );
}
} else if ( param == AKONADI_PARAM_COLLECTIONS ) {
QList<QByteArray> list = m_streamParser->readParenthesizedList();
Q_FOREACH ( const QByteArray &col, list ) {
collectionIds << col.toLongLong();
}
} else if ( param == AKONADI_PARAM_RECURSIVE ) {
recursive = true;
} else if ( param == AKONADI_PARAM_QUERY ) {
queryString = m_streamParser->readUtf8String();
} else {
return failureResponse( "Invalid parameter" );
}
}
if ( queryString.isEmpty() ) {
return failureResponse( "No query specified" );
}
QVector<qint64> collections;
if ( recursive ) {
Q_FOREACH ( qint64 collection, collectionIds ) {
collections << listCollectionsRecursive( QVector<qint64>() << collection, mimeTypes );
}
} else {
collections = collectionIds;
}
akDebug() << "SEARCH:";
akDebug() << "\tQuery:" << queryString;
akDebug() << "\tMimeTypes:" << mimeTypes;
akDebug() << "\tCollections:" << collections;
// Read the fetch scope
mFetchScope = FetchScope( m_streamParser );
AgentSearchRequest request( connection() );
request.setCollections( collections );
request.setMimeTypes( mimeTypes );
request.setQuery( queryString );
connect( &request, SIGNAL(resultsAvailable(QSet<qint64>)),
this, SLOT(slotResultsAvailable(QSet<qint64>)) );
request.exec();
}
//akDebug() << "\tResult:" << uids;
akDebug() << "\tResult:" << mAllResults.count() << "matches";
return successResponse( "Search done" );
}
void Search::searchNepomuk()
{
const QString queryString = m_streamParser->readUtf8String();
mFetchScope = FetchScope( m_streamParser );
NepomukSearch *service = new NepomukSearch;
const QStringList uids = service->search( queryString );
delete service;
if ( uids.isEmpty() ) {
return;
}
QSet<qint64> results;
Q_FOREACH ( const QString &uid, uids ) {
results.insert( uid.toLongLong() );
}
slotResultsAvailable( results );
}
QVector<qint64> Search::listCollectionsRecursive( const QVector<qint64> &ancestors, const QStringList &mimeTypes )
{
QVector<qint64> recursiveChildren;
Q_FOREACH ( qint64 ancestor, ancestors ) {
Query::Condition mimeTypeCondition;
mimeTypeCondition.addColumnCondition( CollectionMimeTypeRelation::rightFullColumnName(), Query::Equals, MimeType::idFullColumnName() );
// Exclude top-level collections and collections that cannot have items!
mimeTypeCondition.addValueCondition( MimeType::nameFullColumnName(), Query::NotEquals, QLatin1String( "inode/directory" ) );
if ( !mimeTypes.isEmpty() ) {
mimeTypeCondition.addValueCondition( MimeType::nameFullColumnName(), Query::In, mimeTypes );
}
QueryBuilder qb( Collection::tableName() );
qb.addColumn( Collection::idFullColumnName() );
qb.addColumn( MimeType::nameFullColumnName() );
qb.addJoin( QueryBuilder::InnerJoin, Resource::tableName(), Resource::idFullColumnName(), Collection::resourceIdFullColumnName() );
qb.addJoin( QueryBuilder::LeftJoin, CollectionMimeTypeRelation::tableName(), CollectionMimeTypeRelation::leftFullColumnName(), Collection::idFullColumnName() );
qb.addJoin( QueryBuilder::LeftJoin, MimeType::tableName(), mimeTypeCondition );
if ( ancestor == 0 ) {
qb.addValueCondition( Collection::parentIdFullColumnName(), Query::Is, QVariant() );
} else {
qb.addValueCondition( Collection::parentIdFullColumnName(), Query::Equals, ancestor );
}
qb.addGroupColumn( Collection::idFullColumnName() );
qb.exec();
QSqlQuery query = qb.query();
QVector<qint64> searchChildren;
while ( query.next() ) {
const qint64 id = query.value( 0 ).toLongLong();
searchChildren << id;
if ( !query.value( 1 ).isNull() ) {
recursiveChildren << id;
}
}
if ( !searchChildren.isEmpty() ) {
recursiveChildren << listCollectionsRecursive( searchChildren, mimeTypes );
}
}
return recursiveChildren;
}
void Search::slotResultsAvailable( const QSet<qint64> &results )
{
QSet<qint64> newResults = results;
newResults.subtract( mAllResults );
mAllResults.unite( newResults );
if ( newResults.isEmpty() ) {
return;
}
// create imap query
ImapSet itemSet;
itemSet.add( newResults );
Scope scope( Scope::Uid );
scope.setUidSet( itemSet );
FetchHelper fetchHelper( connection(), scope, mFetchScope );
connect( &fetchHelper, SIGNAL(responseAvailable(Akonadi::Response)),
this, SIGNAL(responseAvailable(Akonadi::Response)) );
fetchHelper.fetchItems( AKONADI_CMD_SEARCH );
}
<commit_msg>Fast path exit in case no search collection is specified<commit_after>/***************************************************************************
* Copyright (C) 2009 by Tobias Koenig <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "search.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "fetchhelper.h"
#include "handlerhelper.h"
#include "imapstreamparser.h"
#include "nepomuksearch.h"
#include "response.h"
#include "storage/selectquerybuilder.h"
#include "search/agentsearchrequest.h"
#include "search/searchmanager.h"
#include "libs/protocol_p.h"
#include <QtCore/QStringList>
using namespace Akonadi;
Search::Search()
: Handler()
{
}
Search::~Search()
{
}
bool Search::parseStream()
{
QStringList mimeTypes;
QVector<qint64> collectionIds;
bool recursive = false;
QString queryString;
// Backward compatibility
if ( !connection()->capabilities().serverSideSearch() ) {
searchNepomuk();
} else {
while (m_streamParser->hasString()) {
const QByteArray param = m_streamParser->readString();
if ( param == AKONADI_PARAM_MIMETYPE ) {
const QList<QByteArray> mt = m_streamParser->readParenthesizedList();
mimeTypes.reserve( mt.size() );
Q_FOREACH ( const QByteArray &ba, mt ) {
mimeTypes.append( QString::fromLatin1( ba ) );
}
} else if ( param == AKONADI_PARAM_COLLECTIONS ) {
QList<QByteArray> list = m_streamParser->readParenthesizedList();
Q_FOREACH ( const QByteArray &col, list ) {
collectionIds << col.toLongLong();
}
} else if ( param == AKONADI_PARAM_RECURSIVE ) {
recursive = true;
} else if ( param == AKONADI_PARAM_QUERY ) {
queryString = m_streamParser->readUtf8String();
} else {
return failureResponse( "Invalid parameter" );
}
}
if ( queryString.isEmpty() ) {
return failureResponse( "No query specified" );
}
QVector<qint64> collections;
if ( recursive ) {
Q_FOREACH ( qint64 collection, collectionIds ) {
collections << listCollectionsRecursive( QVector<qint64>() << collection, mimeTypes );
}
} else {
collections = collectionIds;
}
akDebug() << "SEARCH:";
akDebug() << "\tQuery:" << queryString;
akDebug() << "\tMimeTypes:" << mimeTypes;
akDebug() << "\tCollections:" << collections;
if ( collections.isEmpty() ) {
m_streamParser->readUntilCommandEnd();
return successResponse( "Search done" );
}
// Read the fetch scope
mFetchScope = FetchScope( m_streamParser );
AgentSearchRequest request( connection() );
request.setCollections( collections );
request.setMimeTypes( mimeTypes );
request.setQuery( queryString );
connect( &request, SIGNAL(resultsAvailable(QSet<qint64>)),
this, SLOT(slotResultsAvailable(QSet<qint64>)) );
request.exec();
}
//akDebug() << "\tResult:" << uids;
akDebug() << "\tResult:" << mAllResults.count() << "matches";
return successResponse( "Search done" );
}
void Search::searchNepomuk()
{
const QString queryString = m_streamParser->readUtf8String();
mFetchScope = FetchScope( m_streamParser );
NepomukSearch *service = new NepomukSearch;
const QStringList uids = service->search( queryString );
delete service;
if ( uids.isEmpty() ) {
return;
}
QSet<qint64> results;
Q_FOREACH ( const QString &uid, uids ) {
results.insert( uid.toLongLong() );
}
slotResultsAvailable( results );
}
QVector<qint64> Search::listCollectionsRecursive( const QVector<qint64> &ancestors, const QStringList &mimeTypes )
{
QVector<qint64> recursiveChildren;
Q_FOREACH ( qint64 ancestor, ancestors ) {
Query::Condition mimeTypeCondition;
mimeTypeCondition.addColumnCondition( CollectionMimeTypeRelation::rightFullColumnName(), Query::Equals, MimeType::idFullColumnName() );
// Exclude top-level collections and collections that cannot have items!
mimeTypeCondition.addValueCondition( MimeType::nameFullColumnName(), Query::NotEquals, QLatin1String( "inode/directory" ) );
if ( !mimeTypes.isEmpty() ) {
mimeTypeCondition.addValueCondition( MimeType::nameFullColumnName(), Query::In, mimeTypes );
}
QueryBuilder qb( Collection::tableName() );
qb.addColumn( Collection::idFullColumnName() );
qb.addColumn( MimeType::nameFullColumnName() );
qb.addJoin( QueryBuilder::InnerJoin, Resource::tableName(), Resource::idFullColumnName(), Collection::resourceIdFullColumnName() );
qb.addJoin( QueryBuilder::LeftJoin, CollectionMimeTypeRelation::tableName(), CollectionMimeTypeRelation::leftFullColumnName(), Collection::idFullColumnName() );
qb.addJoin( QueryBuilder::LeftJoin, MimeType::tableName(), mimeTypeCondition );
if ( ancestor == 0 ) {
qb.addValueCondition( Collection::parentIdFullColumnName(), Query::Is, QVariant() );
} else {
qb.addValueCondition( Collection::parentIdFullColumnName(), Query::Equals, ancestor );
}
qb.addGroupColumn( Collection::idFullColumnName() );
qb.exec();
QSqlQuery query = qb.query();
QVector<qint64> searchChildren;
while ( query.next() ) {
const qint64 id = query.value( 0 ).toLongLong();
searchChildren << id;
if ( !query.value( 1 ).isNull() ) {
recursiveChildren << id;
}
}
if ( !searchChildren.isEmpty() ) {
recursiveChildren << listCollectionsRecursive( searchChildren, mimeTypes );
}
}
return recursiveChildren;
}
void Search::slotResultsAvailable( const QSet<qint64> &results )
{
QSet<qint64> newResults = results;
newResults.subtract( mAllResults );
mAllResults.unite( newResults );
if ( newResults.isEmpty() ) {
return;
}
// create imap query
ImapSet itemSet;
itemSet.add( newResults );
Scope scope( Scope::Uid );
scope.setUidSet( itemSet );
FetchHelper fetchHelper( connection(), scope, mFetchScope );
connect( &fetchHelper, SIGNAL(responseAvailable(Akonadi::Response)),
this, SIGNAL(responseAvailable(Akonadi::Response)) );
fetchHelper.fetchItems( AKONADI_CMD_SEARCH );
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 [email protected].
*
* 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 "XercesNamedNodeListCache.hpp"
#include <algorithm>
#include <cassert>
#include <PlatformSupport/STLHelper.hpp>
#include <dom/DOM_Node.hpp>
#include "XercesNodeListBridge.hpp"
XercesNamedNodeListCache::XercesNamedNodeListCache(const XercesBridgeNavigator& theNavigator) :
m_navigator(theNavigator),
m_cachedNodeLists(),
m_cachedNodeListsNS()
{
}
XercesNamedNodeListCache::~XercesNamedNodeListCache()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_cachedNodeLists.begin(),
m_cachedNodeLists.end(),
makeMapValueDeleteFunctor(m_cachedNodeLists));
for_each(m_cachedNodeListsNS.begin(),
m_cachedNodeListsNS.end(),
makeMapValueDeleteFunctor(m_cachedNodeListsNS));
}
XercesNodeListBridge*
XercesNamedNodeListCache::getElementsByTagName(const XalanDOMString& tagname) const
{
const NodeListCacheType::const_iterator i =
m_cachedNodeLists.find(tagname);
if (i != m_cachedNodeLists.end())
{
return i->second;
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::make_pair;
#endif
XercesNodeListBridge* const theNewBridge =
new XercesNodeListBridge(getXercesNodeList(tagname),
m_navigator);
#if defined(XALAN_NO_MUTABLE)
return ((NodeListCacheType&)m_cachedNodeLists).insert(make_pair(tagname,
theNewBridge)).first->second;
#else
return m_cachedNodeLists.insert(make_pair(tagname,
theNewBridge)).first->second;
#endif
}
}
XercesNodeListBridge*
XercesNamedNodeListCache::getElementsByTagNameNS(
const XalanDOMString& namespaceURI,
const XalanDOMString& localName) const
{
XalanDOMString theSearchString(namespaceURI + localName);
const NodeListCacheType::const_iterator i =
m_cachedNodeListsNS.find(theSearchString);
if (i != m_cachedNodeLists.end())
{
return i->second;
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::make_pair;
#endif
XercesNodeListBridge* const theNewBridge =
new XercesNodeListBridge(getXercesNodeList(namespaceURI, localName),
m_navigator);
#if defined(XALAN_NO_MUTABLE)
return ((NodeListCacheType&)m_cachedNodeLists).insert(make_pair(theSearchString,
theNewBridge)).first->second;
#else
return m_cachedNodeLists.insert(make_pair(theSearchString,
theNewBridge)).first->second;
#endif
}
}
<commit_msg>Fixes for AIX compiler.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 [email protected].
*
* 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 "XercesNamedNodeListCache.hpp"
#include <algorithm>
#include <cassert>
#include <PlatformSupport/STLHelper.hpp>
#include <dom/DOM_Node.hpp>
#include "XercesNodeListBridge.hpp"
XercesNamedNodeListCache::XercesNamedNodeListCache(const XercesBridgeNavigator& theNavigator) :
m_navigator(theNavigator),
m_cachedNodeLists(),
m_cachedNodeListsNS()
{
}
XercesNamedNodeListCache::~XercesNamedNodeListCache()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_cachedNodeLists.begin(),
m_cachedNodeLists.end(),
makeMapValueDeleteFunctor(m_cachedNodeLists));
for_each(m_cachedNodeListsNS.begin(),
m_cachedNodeListsNS.end(),
makeMapValueDeleteFunctor(m_cachedNodeListsNS));
}
XercesNodeListBridge*
XercesNamedNodeListCache::getElementsByTagName(const XalanDOMString& tagname) const
{
const NodeListCacheType::const_iterator i =
m_cachedNodeLists.find(tagname);
if (i != m_cachedNodeLists.end())
{
return (*i).second;
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::make_pair;
#endif
XercesNodeListBridge* const theNewBridge =
new XercesNodeListBridge(getXercesNodeList(tagname),
m_navigator);
#if defined(XALAN_NO_MUTABLE)
return ((NodeListCacheType&)m_cachedNodeLists).insert(make_pair(tagname,
theNewBridge)).first->second;
#else
return m_cachedNodeLists.insert(make_pair(tagname,
theNewBridge)).first->second;
#endif
}
}
XercesNodeListBridge*
XercesNamedNodeListCache::getElementsByTagNameNS(
const XalanDOMString& namespaceURI,
const XalanDOMString& localName) const
{
XalanDOMString theSearchString(namespaceURI + localName);
const NodeListCacheType::const_iterator i =
m_cachedNodeListsNS.find(theSearchString);
if (i != m_cachedNodeLists.end())
{
return (*i).second;
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::make_pair;
#endif
XercesNodeListBridge* const theNewBridge =
new XercesNodeListBridge(getXercesNodeList(namespaceURI, localName),
m_navigator);
#if defined(XALAN_NO_MUTABLE)
return ((NodeListCacheType&)m_cachedNodeLists).insert(make_pair(theSearchString,
theNewBridge)).first->second;
#else
return m_cachedNodeLists.insert(make_pair(theSearchString,
theNewBridge)).first->second;
#endif
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <pcl/PCLPointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/common/common_headers.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/marching_cubes_hoppe.h>
#include <pcl/surface/marching_cubes_rbf.h>
#include <pcl/console/time.h>
#include <pcl/console/parse.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_mean_k = 200;
float default_stdev = 0.3f;
float default_leaf_size = 0.01f;
int default_norm_k = 100;
float default_off_surface_eps = 0.1f;
int default_grid_res = 50;
int default_algorithm = 1;
void print_help(char **argv) {
print_error("Syntax is: %s in.txt out.vtk <options>\n", argv[0]);
print_info(" -mean_k X = # of neighbors to analyze (StatisticalOutlierRemoval) (default: ");
print_value("%d", default_mean_k);
print_info(")\n");
print_info(" -stdev X = standard deviation threshold (StatisticalOutlierRemoval) (default: ");
print_value("%.5f", default_stdev);
print_info(")\n");
print_info(" -leaf_size X = resolution of the cubic grid (VoxelGridFilter) (default: ");
print_value("%.5f", default_leaf_size);
print_info(")\n");
print_info(" -norm_k X = # of neighbors for normal estimation (default: ");
print_value("%d", default_norm_k);
print_info(")\n");
print_info(" -algorithm X = ID of the algorithm to run (default: ");
print_value("%d", default_algorithm);
print_info(")\n");
print_info(" 1 : GreedyTriangulation\n");
print_info(" 2 : MarchingCubesHoppe\n");
print_info(" 3 : MarchingCubesRBF\n");
}
int main(int argc, char *argv[]) {
if (argc < 3) {
print_help(argv);
return -1;
}
// Parse the command line arguments for .pcd files
std::vector<int> txt_file_indices;
txt_file_indices = parse_file_extension_argument(argc, argv, ".txt");
if (txt_file_indices.size() != 1) {
print_error("Need one input text file and one output VTK file to continue.\n");
return -1;
}
std::vector<int> vtk_file_indices = parse_file_extension_argument(argc, argv, ".vtk");
if (vtk_file_indices.size() != 1) {
print_error("Need one output VTK file to continue.\n");
return -1;
}
int mean_k = default_mean_k;
parse_argument(argc, argv, "-mean_k", mean_k);
if (mean_k < 1) mean_k = default_mean_k;
print_info("Setting a mean k of: ");
print_value("%d\n", mean_k);
float stdev = default_stdev;
parse_argument(argc, argv, "-stdev", stdev);
if (stdev < 0) stdev = default_stdev;
print_info("Setting a standard deviation of: ");
print_value("%f\n", stdev);
float leaf_size = default_leaf_size;
parse_argument(argc, argv, "-leaf_size", leaf_size);
if (leaf_size <= 0) leaf_size = default_leaf_size;
print_info("Setting a leaf size of: ");
print_value("%f\n", leaf_size);
int norm_k = default_norm_k;
parse_argument(argc, argv, "-norm_k", norm_k);
if (norm_k < 1) norm_k = default_norm_k;
print_info("Setting a norm k of: ");
print_value("%d\n", norm_k);
int algorithm = default_algorithm;
parse_argument(argc, argv, "-algorithm", algorithm);
if (algorithm <= 1 || algorithm > 3) {
print_info("Selected algorithm: GreedyTriangulation\n");
}
else if (algorithm == 2) {
print_info("Selected algorithm: MarchingCubesHoppe\n");
}
else if (algorithm == 3) {
print_info("Selected algorithm: MarchingCubesRBF\n");
}
std::ifstream fin(argv[txt_file_indices[0]]);
uint32_t num_data_pts = 0;
std::string line;
while (std::getline(fin, line)) ++num_data_pts;
print_info("Num of data points: ");
print_value("%d\n", num_data_pts);
fin.clear();
fin.seekg(0, std::ios::beg);
PointCloud<PointXYZ>::Ptr cloud(new PointCloud<PointXYZ>());
cloud->width = num_data_pts;
cloud->height = 1;
cloud->points.resize(cloud->width * cloud->height);
for (int i = 0; i < cloud->width; ++i) {
float x, y, z;
fin >> x >> y >> z;
cloud->points[i].x = x;
cloud->points[i].y = y;
cloud->points[i].z = z;
}
fin.close();
savePCDFileASCII("out/pre-processed.pcd", *cloud);
print_highlight("Saving ");
print_value("%s\n", "pre-processed.pcd");
/******************************************************************************************************************
* STATISTICAL OUTLIER REMOVAL
******************************************************************************************************************/
// New cloud to hold filtered data
PointCloud<PointXYZ>::Ptr cloudSORFiltered(new PointCloud<PointXYZ>());
StatisticalOutlierRemoval<PointXYZ> sor;
sor.setInputCloud(cloud);
sor.setMeanK(mean_k);
sor.setStddevMulThresh(stdev);
TicToc tt1;
tt1.tic();
print_highlight("Computing StatisticalOutlierRemoval ");
sor.filter(*cloudSORFiltered);
print_info("[done, ");
print_value("%g", tt1.toc());
print_info(" ms]\n");
print_info("Stats filtered cloud is now ");
print_value("%d\n", cloudSORFiltered->points.size());
/******************************************************************************************************************
* VOXEL GRID FILTER
******************************************************************************************************************/
PointCloud<PointXYZ>::Ptr cloudVGFFiltered(new PointCloud<PointXYZ>());
VoxelGrid<PointXYZ> voxelFilter;
voxelFilter.setInputCloud(cloudSORFiltered);
voxelFilter.setLeafSize(leaf_size, leaf_size, leaf_size);
TicToc tt2;
tt2.tic();
print_highlight("Computing VoxelGridFilter ");
voxelFilter.filter(*cloudVGFFiltered);
print_info("[done, ");
print_value("%g", tt2.toc());
print_info(" ms]\n");
print_info("Voxel filtered cloud is now ");
print_value("%d\n", cloudVGFFiltered->points.size());
savePCDFileASCII("out/post-processed.pcd", *cloudVGFFiltered);
print_highlight("Saving ");
print_value("%s\n", "post-processed.pcd");
/******************************************************************************************************************
* NORMAL ESTIMATION
******************************************************************************************************************/
PointCloud<Normal>::Ptr cloudNormals(new PointCloud<Normal>());
NormalEstimationOMP<PointXYZ, Normal> ne;
search::KdTree<PointXYZ>::Ptr pointTree(new search::KdTree<PointXYZ>);
pointTree->setInputCloud(cloudVGFFiltered);
unsigned int nthreads = 2;
print_info("Running normal estimation on ");
print_value("%d", nthreads);
print_info(" threads\n");
ne.setNumberOfThreads(nthreads);
ne.setInputCloud(cloudVGFFiltered);
ne.setSearchMethod(pointTree);
ne.setKSearch(norm_k);
TicToc tt3;
tt3.tic();
print_highlight("Computing normals ");
ne.compute(*cloudNormals);
print_info("[done, ");
print_value("%g", tt3.toc());
print_info(" ms]\n");
// Concatenate the XYZ and normal fields
PointCloud<PointNormal>::Ptr cloudWithNormals(new PointCloud<PointNormal>());
concatenateFields(*cloudVGFFiltered, *cloudNormals, *cloudWithNormals);
savePCDFileASCII("out/post-processed_normals.pcd", *cloudWithNormals);
print_highlight("Saving ");
print_value("%s\n", "post-processed_normals.pcd");
// Create k-d search tree that has the points and point normals
search::KdTree<PointNormal>::Ptr normalTree(new search::KdTree<PointNormal>);
normalTree->setInputCloud(cloudWithNormals);
/******************************************************************************************************************
* SURFACE RECONSTRUCTION
******************************************************************************************************************/
PolygonMesh triangles;
// Using OOP principle of polymorphism!
PCLSurfaceBase<PointNormal> *reconstruction;
switch (algorithm) {
case 1: {
reconstruction = new GreedyProjectionTriangulation<PointNormal>();
GreedyProjectionTriangulation<PointNormal> *greedy = reinterpret_cast<GreedyProjectionTriangulation<PointNormal> *>(reconstruction);
greedy->setSearchRadius(0.025);
greedy->setMu(2.5);
greedy->setMaximumNearestNeighbors(500);
greedy->setMaximumSurfaceAngle(M_PI / 4);
greedy->setMinimumAngle(M_PI / 18);
greedy->setMaximumAngle(2 * M_PI / 3);
greedy->setNormalConsistency(false);
break;
}
case 2: {
reconstruction = new MarchingCubesHoppe<PointNormal>();
MarchingCubesHoppe<PointNormal> *hoppe = reinterpret_cast<MarchingCubesHoppe<PointNormal> *>(reconstruction);
hoppe->setGridResolution(default_grid_res, default_grid_res, default_grid_res);
hoppe->setIsoLevel(0);
hoppe->setPercentageExtendGrid(0);
break;
}
case 3: {
reconstruction = new MarchingCubesRBF<PointNormal>();
MarchingCubesRBF<PointNormal> *rbf = reinterpret_cast<MarchingCubesRBF<PointNormal> *>(reconstruction);
rbf->setOffSurfaceDisplacement(default_off_surface_eps);
rbf->setGridResolution(default_grid_res, default_grid_res, default_grid_res);
rbf->setIsoLevel(0);
rbf->setPercentageExtendGrid(0);
break;
}
default:
print_error("Unrecognized algorithm selection: %d", algorithm);
return -1;
}
reconstruction->setInputCloud(cloudWithNormals);
reconstruction->setSearchMethod(normalTree);
TicToc tt4;
tt4.tic();
print_highlight("Computing surface ");
reconstruction->reconstruct(triangles);
print_info("[done, ");
print_value("%g", tt4.toc());
print_info(" ms]\n");
std::string file(argv[vtk_file_indices[0]]);
saveVTKFile(std::string("out/") + file, triangles);
print_highlight("Saving ");
print_value("%s\n", argv[vtk_file_indices[0]]);
return 0;
}
<commit_msg>Deleted memory references<commit_after>#include <iostream>
#include <fstream>
#include <pcl/PCLPointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/common/common_headers.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/marching_cubes_hoppe.h>
#include <pcl/surface/marching_cubes_rbf.h>
#include <pcl/console/time.h>
#include <pcl/console/parse.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
int default_mean_k = 200;
float default_stdev = 0.3f;
float default_leaf_size = 0.01f;
int default_norm_k = 100;
float default_off_surface_eps = 0.1f;
int default_grid_res = 50;
int default_algorithm = 1;
void print_help(char **argv) {
print_error("Syntax is: %s in.txt out.vtk <options>\n", argv[0]);
print_info(" -mean_k X = # of neighbors to analyze (StatisticalOutlierRemoval) (default: ");
print_value("%d", default_mean_k);
print_info(")\n");
print_info(" -stdev X = standard deviation threshold (StatisticalOutlierRemoval) (default: ");
print_value("%.5f", default_stdev);
print_info(")\n");
print_info(" -leaf_size X = resolution of the cubic grid (VoxelGridFilter) (default: ");
print_value("%.5f", default_leaf_size);
print_info(")\n");
print_info(" -norm_k X = # of neighbors for normal estimation (default: ");
print_value("%d", default_norm_k);
print_info(")\n");
print_info(" -algorithm X = ID of the algorithm to run (default: ");
print_value("%d", default_algorithm);
print_info(")\n");
print_info(" 1 : GreedyTriangulation\n");
print_info(" 2 : MarchingCubesHoppe\n");
print_info(" 3 : MarchingCubesRBF\n");
}
int main(int argc, char *argv[]) {
if (argc < 3) {
print_help(argv);
return -1;
}
// Parse the command line arguments for .pcd files
std::vector<int> txt_file_indices;
txt_file_indices = parse_file_extension_argument(argc, argv, ".txt");
if (txt_file_indices.size() != 1) {
print_error("Need one input text file and one output VTK file to continue.\n");
return -1;
}
std::vector<int> vtk_file_indices = parse_file_extension_argument(argc, argv, ".vtk");
if (vtk_file_indices.size() != 1) {
print_error("Need one output VTK file to continue.\n");
return -1;
}
int mean_k = default_mean_k;
parse_argument(argc, argv, "-mean_k", mean_k);
if (mean_k < 1) mean_k = default_mean_k;
print_info("Setting a mean k of: ");
print_value("%d\n", mean_k);
float stdev = default_stdev;
parse_argument(argc, argv, "-stdev", stdev);
if (stdev < 0) stdev = default_stdev;
print_info("Setting a standard deviation of: ");
print_value("%f\n", stdev);
float leaf_size = default_leaf_size;
parse_argument(argc, argv, "-leaf_size", leaf_size);
if (leaf_size <= 0) leaf_size = default_leaf_size;
print_info("Setting a leaf size of: ");
print_value("%f\n", leaf_size);
int norm_k = default_norm_k;
parse_argument(argc, argv, "-norm_k", norm_k);
if (norm_k < 1) norm_k = default_norm_k;
print_info("Setting a norm k of: ");
print_value("%d\n", norm_k);
int algorithm = default_algorithm;
parse_argument(argc, argv, "-algorithm", algorithm);
if (algorithm <= 1 || algorithm > 3) {
print_info("Selected algorithm: GreedyTriangulation\n");
}
else if (algorithm == 2) {
print_info("Selected algorithm: MarchingCubesHoppe\n");
}
else if (algorithm == 3) {
print_info("Selected algorithm: MarchingCubesRBF\n");
}
std::ifstream fin(argv[txt_file_indices[0]]);
uint32_t num_data_pts = 0;
std::string line;
while (std::getline(fin, line)) ++num_data_pts;
print_info("Num of data points: ");
print_value("%d\n", num_data_pts);
fin.clear();
fin.seekg(0, std::ios::beg);
PointCloud<PointXYZ>::Ptr cloud(new PointCloud<PointXYZ>());
cloud->width = num_data_pts;
cloud->height = 1;
cloud->points.resize(cloud->width * cloud->height);
for (int i = 0; i < cloud->width; ++i) {
float x, y, z;
fin >> x >> y >> z;
cloud->points[i].x = x;
cloud->points[i].y = y;
cloud->points[i].z = z;
}
fin.close();
savePCDFileASCII("out/pre-processed.pcd", *cloud);
print_highlight("Saving ");
print_value("%s\n", "pre-processed.pcd");
/******************************************************************************************************************
* STATISTICAL OUTLIER REMOVAL
******************************************************************************************************************/
// New cloud to hold filtered data
PointCloud<PointXYZ>::Ptr cloudSORFiltered(new PointCloud<PointXYZ>());
StatisticalOutlierRemoval<PointXYZ> sor;
sor.setInputCloud(cloud);
sor.setMeanK(mean_k);
sor.setStddevMulThresh(stdev);
TicToc tt1;
tt1.tic();
print_highlight("Computing StatisticalOutlierRemoval ");
sor.filter(*cloudSORFiltered);
print_info("[done, ");
print_value("%g", tt1.toc());
print_info(" ms]\n");
print_info("Stats filtered cloud is now ");
print_value("%d\n", cloudSORFiltered->points.size());
/******************************************************************************************************************
* VOXEL GRID FILTER
******************************************************************************************************************/
PointCloud<PointXYZ>::Ptr cloudVGFFiltered(new PointCloud<PointXYZ>());
VoxelGrid<PointXYZ> voxelFilter;
voxelFilter.setInputCloud(cloudSORFiltered);
voxelFilter.setLeafSize(leaf_size, leaf_size, leaf_size);
TicToc tt2;
tt2.tic();
print_highlight("Computing VoxelGridFilter ");
voxelFilter.filter(*cloudVGFFiltered);
print_info("[done, ");
print_value("%g", tt2.toc());
print_info(" ms]\n");
print_info("Voxel filtered cloud is now ");
print_value("%d\n", cloudVGFFiltered->points.size());
savePCDFileASCII("out/post-processed.pcd", *cloudVGFFiltered);
print_highlight("Saving ");
print_value("%s\n", "post-processed.pcd");
/******************************************************************************************************************
* NORMAL ESTIMATION
******************************************************************************************************************/
PointCloud<Normal>::Ptr cloudNormals(new PointCloud<Normal>());
NormalEstimationOMP<PointXYZ, Normal> ne;
search::KdTree<PointXYZ>::Ptr pointTree(new search::KdTree<PointXYZ>);
pointTree->setInputCloud(cloudVGFFiltered);
unsigned int nthreads = 2;
print_info("Running normal estimation on ");
print_value("%d", nthreads);
print_info(" threads\n");
ne.setNumberOfThreads(nthreads);
ne.setInputCloud(cloudVGFFiltered);
ne.setSearchMethod(pointTree);
ne.setKSearch(norm_k);
TicToc tt3;
tt3.tic();
print_highlight("Computing normals ");
ne.compute(*cloudNormals);
print_info("[done, ");
print_value("%g", tt3.toc());
print_info(" ms]\n");
// Concatenate the XYZ and normal fields
PointCloud<PointNormal>::Ptr cloudWithNormals(new PointCloud<PointNormal>());
concatenateFields(*cloudVGFFiltered, *cloudNormals, *cloudWithNormals);
savePCDFileASCII("out/post-processed_normals.pcd", *cloudWithNormals);
print_highlight("Saving ");
print_value("%s\n", "post-processed_normals.pcd");
// Create k-d search tree that has the points and point normals
search::KdTree<PointNormal>::Ptr normalTree(new search::KdTree<PointNormal>);
normalTree->setInputCloud(cloudWithNormals);
/******************************************************************************************************************
* SURFACE RECONSTRUCTION
******************************************************************************************************************/
PolygonMesh triangles;
// Using OOP principle of polymorphism!
PCLSurfaceBase<PointNormal> *reconstruction;
switch (algorithm) {
case 1: {
reconstruction = new GreedyProjectionTriangulation<PointNormal>();
GreedyProjectionTriangulation<PointNormal> *greedy = reinterpret_cast<GreedyProjectionTriangulation<PointNormal> *>(reconstruction);
greedy->setSearchRadius(0.025);
greedy->setMu(2.5);
greedy->setMaximumNearestNeighbors(500);
greedy->setMaximumSurfaceAngle(M_PI / 4);
greedy->setMinimumAngle(M_PI / 18);
greedy->setMaximumAngle(2 * M_PI / 3);
greedy->setNormalConsistency(false);
break;
}
case 2: {
reconstruction = new MarchingCubesHoppe<PointNormal>();
MarchingCubesHoppe<PointNormal> *hoppe = reinterpret_cast<MarchingCubesHoppe<PointNormal> *>(reconstruction);
hoppe->setGridResolution(default_grid_res, default_grid_res, default_grid_res);
hoppe->setIsoLevel(0);
hoppe->setPercentageExtendGrid(0);
break;
}
case 3: {
reconstruction = new MarchingCubesRBF<PointNormal>();
MarchingCubesRBF<PointNormal> *rbf = reinterpret_cast<MarchingCubesRBF<PointNormal> *>(reconstruction);
rbf->setOffSurfaceDisplacement(default_off_surface_eps);
rbf->setGridResolution(default_grid_res, default_grid_res, default_grid_res);
rbf->setIsoLevel(0);
rbf->setPercentageExtendGrid(0);
break;
}
default:
print_error("Unrecognized algorithm selection: %d", algorithm);
return -1;
}
reconstruction->setInputCloud(cloudWithNormals);
reconstruction->setSearchMethod(normalTree);
TicToc tt4;
tt4.tic();
print_highlight("Computing surface ");
reconstruction->reconstruct(triangles);
print_info("[done, ");
print_value("%g", tt4.toc());
print_info(" ms]\n");
delete reconstruction;
std::string file(argv[vtk_file_indices[0]]);
saveVTKFile(std::string("out/") + file, triangles);
print_highlight("Saving ");
print_value("%s\n", argv[vtk_file_indices[0]]);
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "keystore.h"
#include "script.h"
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
bool fCompressed = false;
CSecret secret = key.GetSecret(fCompressed);
{
LOCK(cs_KeyStore);
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
}
return true;
}
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
{
LOCK(cs_KeyStore);
mapScripts[redeemScript.GetID()] = redeemScript;
}
return true;
}
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapScripts.count(hash) > 0);
}
return result;
}
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
{
LOCK(cs_KeyStore);
ScriptMap::const_iterator mi = mapScripts.find(hash);
if (mi != mapScripts.end())
{
redeemScriptOut = (*mi).second;
return true;
}
}
return false;
}
bool CCryptoKeyStore::SetCrypted()
{
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
}
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.SetPubKey(vchPubKey);
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CPubKey vchPubKey = key.GetPubKey();
bool fCompressed;
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.SetPubKey(vchPubKey);
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
CKey key;
if (!key.SetSecret(mKey.second.first, mKey.second.second))
return false;
const CPubKey vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
bool fCompressed;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<commit_msg>Check redeemScript size does not exceed 520 byte limit 1/2<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "keystore.h"
#include "script.h"
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
bool fCompressed = false;
CSecret secret = key.GetSecret(fCompressed);
{
LOCK(cs_KeyStore);
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
}
return true;
}
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
{
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
return error("CBasicKeyStore::AddCScript() : redeemScripts > %i bytes are invalid", MAX_SCRIPT_ELEMENT_SIZE);
{
LOCK(cs_KeyStore);
mapScripts[redeemScript.GetID()] = redeemScript;
}
return true;
}
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
{
bool result;
{
LOCK(cs_KeyStore);
result = (mapScripts.count(hash) > 0);
}
return result;
}
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
{
{
LOCK(cs_KeyStore);
ScriptMap::const_iterator mi = mapScripts.find(hash);
if (mi != mapScripts.end())
{
redeemScriptOut = (*mi).second;
return true;
}
}
return false;
}
bool CCryptoKeyStore::SetCrypted()
{
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
}
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
CKey key;
key.SetPubKey(vchPubKey);
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CPubKey vchPubKey = key.GetPubKey();
bool fCompressed;
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.SetPubKey(vchPubKey);
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
CKey key;
if (!key.SetSecret(mKey.second.first, mKey.second.second))
return false;
const CPubKey vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
bool fCompressed;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 "RuntimeParameterFileReader.h"
#include <cctype>
#include <cstring>
#include <vector>
namespace madai {
RuntimeParameterFileReader
::RuntimeParameterFileReader() :
m_NumberOfArguments( 0 ),
m_Arguments( NULL )
{
}
RuntimeParameterFileReader
::~RuntimeParameterFileReader()
{
this->FreeMemory();
}
bool
RuntimeParameterFileReader
::ParseFile( const std::string fileName )
{
this->FreeMemory();
std::ifstream inFile( fileName.c_str() );
if ( inFile.is_open() ) {
std::string line;
std::string element;
std::vector< std::string > arg_list;
m_NumberOfArguments = 0;
while ( inFile.good() ) {
std::getline( inFile, line );
line = this->RegularizeLine( line );
// Split the regularized string by the first space
size_t firstSpace = line.find_first_of( ' ' );
std::string name = line.substr( 0, firstSpace );
if ( name.size() > 0 ) {
if ( firstSpace != std::string::npos ) {
std::string value = line.substr( firstSpace+1 );
m_Options[ name ] = value;
} else {
m_Options[ name ] = std::string();
}
arg_list.push_back( name );
// Push rest of tokens onto the arg_list
while ( firstSpace != std::string::npos ) {
size_t nextSpace = line.find_first_of( ' ', firstSpace+1 );
std::string token = line.substr( firstSpace+1,
(nextSpace - firstSpace - 1) );
arg_list.push_back( token );
firstSpace = nextSpace;
}
}
}
m_NumberOfArguments = arg_list.size();
m_Arguments = new char*[m_NumberOfArguments]();
for ( int i = 0; i < m_NumberOfArguments; i++ ) {
m_Arguments[i] = new char[arg_list[i].size()+1];
std::strcpy( m_Arguments[i], arg_list[i].c_str() );
}
} else {
std::cerr << "RuntimeParameterFileReader couldn't find input file'" << fileName << "'\n";
return false;
}
return true;
}
bool
RuntimeParameterFileReader
::HasOption(const std::string & key) const
{
return (m_Options.count(key) > 0);
}
const std::string &
RuntimeParameterFileReader
::GetOption(const std::string & key) const
{
static const std::string empty("");
if (this->HasOption(key)) {
//return m_Options[key]; doesn't work because operator [] isn't const
return m_Options.find( key )->second;
} else {
return empty;
}
}
double
RuntimeParameterFileReader
::GetOptionAsDouble(const std::string & key) const
{
return std::atof(this->GetOption(key).c_str());
}
long
RuntimeParameterFileReader
::GetOptionAsInt(const std::string & key) const
{
return std::atol(this->GetOption(key).c_str());
}
void
RuntimeParameterFileReader
::PrintAllOptions(std::ostream & out) const
{
for (std::map<std::string, std::string>::const_iterator it =
m_Options.begin(); it != m_Options.end(); ++it)
out << "Options[\"" << it->first << "\"] = \"" << it->second << "\"\n";
}
const std::map<std::string, std::string>
RuntimeParameterFileReader
::GetAllOptions() const
{
return m_Options; // implicit cast to const
}
int
RuntimeParameterFileReader
::GetNumberOfArguments() const
{
return m_NumberOfArguments;
}
char **
RuntimeParameterFileReader
::GetArguments() const
{
return m_Arguments;
}
void
RuntimeParameterFileReader
::FreeMemory()
{
for ( int i = 0; i < m_NumberOfArguments; i++ ) {
delete[] m_Arguments[i];
}
delete[] m_Arguments;
m_Arguments = NULL;
}
std::string
RuntimeParameterFileReader
::RegularizeLine( std::string line )
{
// Chop off anything after comment character
size_t commentPosition = line.find_first_of( '#' );
line = line.substr( 0, commentPosition );
// Trim left whitespace
size_t left;
for ( left = 0; left < line.size(); ++left ) {
if ( line[left] != ' ' || line[left] != '\t' ) {
break;
}
}
// Trim right whitespace
size_t right;
for ( right = line.size()-1; right > 0; --right ) {
if ( line[right] != ' ' || line[right] != '\t' ) {
break;
}
}
line = line.substr( left, (right - left + 1) );
// Convert contiguous white space in line to a single space
bool inWhiteSpace = std::isspace( line[0] );
std::string newLine;
for ( size_t i = 0; i < line.size(); ++i ) {
char character = line[i];
if ( inWhiteSpace ) {
if ( std::isspace( character ) ) {
// Skip
} else {
inWhiteSpace = false;
newLine.push_back( character );
}
} else {
if ( std::isspace( character ) ) {
inWhiteSpace = true;
newLine.push_back( ' ' );
} else {
newLine.push_back( character );
}
}
}
if ( *(newLine.end()-1) == ' ' ) {
newLine.erase( newLine.end() - 1 );
}
return newLine;
}
} // end namespace madai
<commit_msg>Greatly simplified RuntimeParameterFileReader::RegularizeLine()<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 "RuntimeParameterFileReader.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <vector>
namespace madai {
RuntimeParameterFileReader
::RuntimeParameterFileReader() :
m_NumberOfArguments( 0 ),
m_Arguments( NULL )
{
}
RuntimeParameterFileReader
::~RuntimeParameterFileReader()
{
this->FreeMemory();
}
bool
RuntimeParameterFileReader
::ParseFile( const std::string fileName )
{
this->FreeMemory();
std::ifstream inFile( fileName.c_str() );
if ( inFile.is_open() ) {
std::string line;
std::string element;
std::vector< std::string > arg_list;
m_NumberOfArguments = 0;
while ( inFile.good() ) {
std::getline( inFile, line );
line = this->RegularizeLine( line );
// Split the regularized string by the first space
size_t firstSpace = line.find_first_of( ' ' );
std::string name = line.substr( 0, firstSpace );
if ( name.size() > 0 ) {
if ( firstSpace != std::string::npos ) {
std::string value = line.substr( firstSpace+1 );
m_Options[ name ] = value;
} else {
m_Options[ name ] = std::string();
}
arg_list.push_back( name );
// Push rest of tokens onto the arg_list
while ( firstSpace != std::string::npos ) {
size_t nextSpace = line.find_first_of( ' ', firstSpace+1 );
std::string token = line.substr( firstSpace+1,
(nextSpace - firstSpace - 1) );
arg_list.push_back( token );
firstSpace = nextSpace;
}
}
}
m_NumberOfArguments = arg_list.size();
m_Arguments = new char*[m_NumberOfArguments]();
for ( int i = 0; i < m_NumberOfArguments; i++ ) {
m_Arguments[i] = new char[arg_list[i].size()+1];
std::strcpy( m_Arguments[i], arg_list[i].c_str() );
}
} else {
std::cerr << "RuntimeParameterFileReader couldn't find input file'" << fileName << "'\n";
return false;
}
return true;
}
bool
RuntimeParameterFileReader
::HasOption(const std::string & key) const
{
return (m_Options.count(key) > 0);
}
const std::string &
RuntimeParameterFileReader
::GetOption(const std::string & key) const
{
static const std::string empty("");
if (this->HasOption(key)) {
//return m_Options[key]; doesn't work because operator [] isn't const
return m_Options.find( key )->second;
} else {
return empty;
}
}
double
RuntimeParameterFileReader
::GetOptionAsDouble(const std::string & key) const
{
return std::atof(this->GetOption(key).c_str());
}
long
RuntimeParameterFileReader
::GetOptionAsInt(const std::string & key) const
{
return std::atol(this->GetOption(key).c_str());
}
void
RuntimeParameterFileReader
::PrintAllOptions(std::ostream & out) const
{
for (std::map<std::string, std::string>::const_iterator it =
m_Options.begin(); it != m_Options.end(); ++it)
out << "Options[\"" << it->first << "\"] = \"" << it->second << "\"\n";
}
const std::map<std::string, std::string>
RuntimeParameterFileReader
::GetAllOptions() const
{
return m_Options; // implicit cast to const
}
int
RuntimeParameterFileReader
::GetNumberOfArguments() const
{
return m_NumberOfArguments;
}
char **
RuntimeParameterFileReader
::GetArguments() const
{
return m_Arguments;
}
void
RuntimeParameterFileReader
::FreeMemory()
{
for ( int i = 0; i < m_NumberOfArguments; i++ ) {
delete[] m_Arguments[i];
}
delete[] m_Arguments;
m_Arguments = NULL;
}
bool IsSameWhitespace( char c1, char c2 )
{
return ( ::isspace( c1 ) && ::isspace( c2 ) );
}
char TabToSpace( char input )
{
if ( input == '\t' ) {
return ' ';
}
return input;
}
std::string
RuntimeParameterFileReader
::RegularizeLine( std::string line )
{
// Chop off anything after comment character
size_t commentPosition = line.find_first_of( '#' );
line = line.substr( 0, commentPosition );
// Convert any tabs to spaces
std::transform( line.begin(), line.end(), line.begin(), TabToSpace );
// Convert contiguous white space in line to a single space
std::string::iterator newEnd = std::unique( line.begin(), line.end(), IsSameWhitespace );
line.resize( std::distance( line.begin(), newEnd ) );
// Trim whitespace left
if ( *(line.begin()) == ' ' ) {
line.erase( line.begin() );
}
// Trim whitespace right
if ( *(line.end() - 1) == ' ' ) {
line.erase( (line.end() - 1) );
}
return line;
}
} // end namespace madai
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*
*/
#pragma once
#include "core/file.hh"
#include "core/fstream.hh"
#include "core/future.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
#include "core/shared_ptr.hh"
#include "core/distributed.hh"
#include <unordered_set>
#include <unordered_map>
#include "types.hh"
#include "core/enum.hh"
#include "compress.hh"
#include "row.hh"
#include "database.hh"
#include "dht/i_partitioner.hh"
#include "schema.hh"
#include "mutation.hh"
#include "utils/i_filter.hh"
#include "core/stream.hh"
#include "writer.hh"
#include "metadata_collector.hh"
#include "filter.hh"
namespace sstables {
// data_consume_context is an object returned by sstable::data_consume_rows()
// which allows knowing when the consumer stops reading, and starting it again
// (e.g., when the consumer wants to stop after every sstable row).
//
// The read() method initiates reading into the consumer, and continues to
// read and feed data into the consumer until one of the consumer's callbacks
// requests to stop, or until we reach the end of the data range originally
// requested. read() returns a future which completes when reading stopped.
// If we're at the end-of-file, the read may complete without reading anything
// so it's the consumer class's task to check if anything was consumed.
// Note:
// The caller MUST ensure that between calling read() on this object,
// and the time the returned future is completed, the object lives on.
// Moreover, the sstable object used for the sstable::data_consume_rows()
// call which created this data_consume_context, must also be kept alive.
class data_consume_context {
class impl;
std::unique_ptr<impl> _pimpl;
// This object can only be constructed by sstable::data_consume_rows()
data_consume_context(std::unique_ptr<impl>);
friend class sstable;
public:
future<> read();
// Define (as defaults) the destructor and move operations in the source
// file, so here we don't need to know the incomplete impl type.
~data_consume_context();
data_consume_context(data_consume_context&&);
data_consume_context& operator=(data_consume_context&&);
};
// mutation_reader is an object returned by sstable::read_rows() et al. which
// allows getting each sstable row in sequence, in mutation format.
//
// The read() method reads the next mutation, returning a disengaged optional
// on EOF. As usual for future-returning functions, a caller which starts a
// read() MUST ensure that the mutation_reader object continues to live until
// the returned future is fulfilled. Moreover, the sstable whose read_rows()
// method was used to open this mutation_reader must also live between the
// time read() is called and its future ends.
// As soon as the future returned by read() completes, the object may safely
// be deleted. In other words, when the read() future is fulfilled, we can
// be sure there are no background tasks still scheduled.
class mutation_reader {
class impl;
std::unique_ptr<impl> _pimpl;
// This object can only be constructed by sstable::read_rows() et al.
mutation_reader(std::unique_ptr<impl>);
friend class sstable;
public:
future<mutation_opt> read();
// Define (as defaults) the destructor and move operations in the source
// file, so here we don't need to know the incomplete impl type.
~mutation_reader();
mutation_reader(mutation_reader&&);
mutation_reader& operator=(mutation_reader&&);
};
class key;
class malformed_sstable_exception : public std::exception {
sstring _msg;
public:
malformed_sstable_exception(sstring s) : _msg(s) {}
const char *what() const noexcept {
return _msg.c_str();
}
};
using index_list = std::vector<index_entry>;
class sstable {
public:
enum class component_type {
Index,
CompressionInfo,
Data,
TOC,
Summary,
Digest,
CRC,
Filter,
Statistics,
};
enum class version_types { la };
enum class format_types { big };
public:
sstable(sstring dir, unsigned long generation, version_types v, format_types f)
: _dir(dir)
, _generation(generation)
, _version(v)
, _format(f)
, _filter_tracker(make_lw_shared<distributed<filter_tracker>>())
{ }
sstable& operator=(const sstable&) = delete;
sstable(const sstable&) = delete;
sstable(sstable&&) = default;
~sstable();
// Read one or few rows at the given byte range from the data file,
// feeding them into the consumer. This function reads the entire given
// byte range at once into memory, so it should not be used for iterating
// over all the rows in the data file (see the next function for that.
// The function returns a future which completes after all the data has
// been fed into the consumer. The caller needs to ensure the "consumer"
// object lives until then (e.g., using the do_with() idiom).
future<> data_consume_rows_at_once(row_consumer& consumer, uint64_t pos, uint64_t end);
// data_consume_rows() iterates over all rows in the data file (or rows in
// a particular range), feeding them into the consumer. The iteration is
// done as efficiently as possible - reading only the data file (not the
// summary or index files) and reading data in batches.
//
// The consumer object may request the iteration to stop before reaching
// the end of the requested data range (e.g. stop after each sstable row).
// A context object is returned which allows to resume this consumption:
// This context's read() method requests that consumption begins, and
// returns a future which will be resolved when it ends (because the
// consumer asked to stop, or the data range ended). Only after the
// returned future is resolved, may read() be called again to consume
// more.
// The caller must ensure (e.g., using do_with()) that the context object,
// as well as the sstable, remains alive as long as a read() is in
// progress (i.e., returned a future which hasn't completed yet).
data_consume_context data_consume_rows(row_consumer& consumer,
uint64_t start = 0, uint64_t end = 0);
static version_types version_from_sstring(sstring& s);
static format_types format_from_sstring(sstring& s);
static const sstring filename(sstring dir, version_types version, unsigned long generation,
format_types format, component_type component);
future<> load();
// Used to serialize sstable components, but so far only for the purpose
// of testing.
future<> store();
void set_generation(unsigned long generation) {
_generation = generation;
}
unsigned long generation() const {
return _generation;
}
future<mutation_opt> read_row(schema_ptr schema, const key& k);
/**
* @param schema a schema_ptr object describing this table
* @param min the minimum token we want to search for (inclusive)
* @param max the maximum token we want to search for (inclusive)
* @return a mutation_reader object that can be used to iterate over
* mutations.
*/
mutation_reader read_range_rows(schema_ptr schema,
const dht::token& min, const dht::token& max);
// read_rows() returns each of the rows in the sstable, in sequence,
// converted to a "mutation" data structure.
// This function is implemented efficiently - doing buffered, sequential
// read of the data file (no need to access the index file).
// A "mutation_reader" object is returned with which the caller can
// fetch mutations in sequence, and allows stop iteration any time
// after getting each row.
//
// The caller must ensure (e.g., using do_with()) that the context object,
// as well as the sstable, remains alive as long as a read() is in
// progress (i.e., returned a future which hasn't completed yet).
mutation_reader read_rows(schema_ptr schema);
// Write sstable components from a memtable.
future<> write_components(const memtable& mt);
future<> write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema);
uint64_t get_estimated_key_count() const {
return ((uint64_t)_summary.header.size_at_full_sampling + 1) *
_summary.header.min_index_interval;
}
// mark_for_deletion() specifies that the on-disk files for this sstable
// should be deleted as soon as the in-memory object is destructed.
void mark_for_deletion() {
_marked_for_deletion = true;
}
void add_ancestor(int generation) {
_collector.add_ancestor(generation);
}
private:
void do_write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema, file_writer& out);
void prepare_write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema);
static std::unordered_map<version_types, sstring, enum_hash<version_types>> _version_string;
static std::unordered_map<format_types, sstring, enum_hash<format_types>> _format_string;
static std::unordered_map<component_type, sstring, enum_hash<component_type>> _component_map;
std::unordered_set<component_type, enum_hash<component_type>> _components;
compression _compression;
utils::filter_ptr _filter;
summary _summary;
statistics _statistics;
metadata_collector _collector;
column_stats _c_stats;
lw_shared_ptr<file> _index_file;
lw_shared_ptr<file> _data_file;
uint64_t _data_file_size;
sstring _dir;
unsigned long _generation = 0;
version_types _version;
format_types _format;
lw_shared_ptr<distributed<filter_tracker>> _filter_tracker;
bool _marked_for_deletion = false;
const bool has_component(component_type f);
const sstring filename(component_type f);
template <sstable::component_type Type, typename T>
future<> read_simple(T& comp);
template <sstable::component_type Type, typename T>
future<> write_simple(T& comp);
uint64_t data_size();
future<> read_toc();
future<> write_toc();
future<> read_compression();
future<> write_compression();
future<> read_filter();
future<> write_filter();
future<> read_summary() {
return read_simple<component_type::Summary>(_summary);
}
future<> write_summary() {
return write_simple<component_type::Summary>(_summary);
}
future<> read_statistics();
future<> write_statistics();
future<> open_data();
future<> create_data();
future<index_list> read_indexes(uint64_t position, uint64_t quantity);
future<index_list> read_indexes(uint64_t position) {
return read_indexes(position, _summary.header.sampling_level);
}
input_stream<char> data_stream_at(uint64_t pos);
// Read exactly the specific byte range from the data file (after
// uncompression, if the file is compressed). This can be used to read
// a specific row from the data file (its position and length can be
// determined using the index file).
// This function is intended (and optimized for) random access, not
// for iteration through all the rows.
future<temporary_buffer<char>> data_read(uint64_t pos, size_t len);
future<uint64_t> data_end_position(int summary_idx, int index_idx, const index_list& il);
template <typename T>
int binary_search(const T& entries, const key& sk, const dht::token& token);
template <typename T>
int binary_search(const T& entries, const key& sk) {
return binary_search(entries, sk, dht::global_partitioner().get_token(key_view(sk)));
}
future<summary_entry&> read_summary_entry(size_t i);
// FIXME: pending on Bloom filter implementation
bool filter_has_key(const key& key) { return _filter->is_present(bytes_view(key)); }
bool filter_has_key(const schema& s, const dht::decorated_key& dk) { return filter_has_key(key::from_partition_key(s, dk._key)); }
// NOTE: functions used to generate sstable components.
void write_row_marker(file_writer& out, const rows_entry& clustered_row, const composite& clustering_key);
void write_clustered_row(file_writer& out, const schema& schema, const rows_entry& clustered_row);
void write_static_row(file_writer& out, const schema& schema, const row& static_row);
void write_cell(file_writer& out, atomic_cell_view cell);
void write_column_name(file_writer& out, const composite& clustering_key, const std::vector<bytes_view>& column_names, composite_marker m = composite_marker::none);
void write_range_tombstone(file_writer& out, const composite& clustering_prefix, std::vector<bytes_view> suffix, const tombstone t);
void write_collection(file_writer& out, const composite& clustering_key, const column_definition& cdef, collection_mutation::view collection);
public:
// Allow the test cases from sstable_test.cc to test private methods. We use
// a placeholder to avoid cluttering this class too much. The sstable_test class
// will then re-export as public every method it needs.
friend class test;
};
using shared_sstable = lw_shared_ptr<sstable>;
}
<commit_msg>sstables: keep current timestamp<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*
*/
#pragma once
#include "core/file.hh"
#include "core/fstream.hh"
#include "core/future.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
#include "core/shared_ptr.hh"
#include "core/distributed.hh"
#include <unordered_set>
#include <unordered_map>
#include "types.hh"
#include "core/enum.hh"
#include "compress.hh"
#include "row.hh"
#include "database.hh"
#include "dht/i_partitioner.hh"
#include "schema.hh"
#include "mutation.hh"
#include "utils/i_filter.hh"
#include "core/stream.hh"
#include "writer.hh"
#include "metadata_collector.hh"
#include "filter.hh"
namespace sstables {
// data_consume_context is an object returned by sstable::data_consume_rows()
// which allows knowing when the consumer stops reading, and starting it again
// (e.g., when the consumer wants to stop after every sstable row).
//
// The read() method initiates reading into the consumer, and continues to
// read and feed data into the consumer until one of the consumer's callbacks
// requests to stop, or until we reach the end of the data range originally
// requested. read() returns a future which completes when reading stopped.
// If we're at the end-of-file, the read may complete without reading anything
// so it's the consumer class's task to check if anything was consumed.
// Note:
// The caller MUST ensure that between calling read() on this object,
// and the time the returned future is completed, the object lives on.
// Moreover, the sstable object used for the sstable::data_consume_rows()
// call which created this data_consume_context, must also be kept alive.
class data_consume_context {
class impl;
std::unique_ptr<impl> _pimpl;
// This object can only be constructed by sstable::data_consume_rows()
data_consume_context(std::unique_ptr<impl>);
friend class sstable;
public:
future<> read();
// Define (as defaults) the destructor and move operations in the source
// file, so here we don't need to know the incomplete impl type.
~data_consume_context();
data_consume_context(data_consume_context&&);
data_consume_context& operator=(data_consume_context&&);
};
// mutation_reader is an object returned by sstable::read_rows() et al. which
// allows getting each sstable row in sequence, in mutation format.
//
// The read() method reads the next mutation, returning a disengaged optional
// on EOF. As usual for future-returning functions, a caller which starts a
// read() MUST ensure that the mutation_reader object continues to live until
// the returned future is fulfilled. Moreover, the sstable whose read_rows()
// method was used to open this mutation_reader must also live between the
// time read() is called and its future ends.
// As soon as the future returned by read() completes, the object may safely
// be deleted. In other words, when the read() future is fulfilled, we can
// be sure there are no background tasks still scheduled.
class mutation_reader {
class impl;
std::unique_ptr<impl> _pimpl;
// This object can only be constructed by sstable::read_rows() et al.
mutation_reader(std::unique_ptr<impl>);
friend class sstable;
public:
future<mutation_opt> read();
// Define (as defaults) the destructor and move operations in the source
// file, so here we don't need to know the incomplete impl type.
~mutation_reader();
mutation_reader(mutation_reader&&);
mutation_reader& operator=(mutation_reader&&);
};
class key;
class malformed_sstable_exception : public std::exception {
sstring _msg;
public:
malformed_sstable_exception(sstring s) : _msg(s) {}
const char *what() const noexcept {
return _msg.c_str();
}
};
using index_list = std::vector<index_entry>;
class sstable {
public:
enum class component_type {
Index,
CompressionInfo,
Data,
TOC,
Summary,
Digest,
CRC,
Filter,
Statistics,
};
enum class version_types { la };
enum class format_types { big };
public:
sstable(sstring dir, unsigned long generation, version_types v, format_types f, gc_clock::time_point now = gc_clock::now())
: _dir(dir)
, _generation(generation)
, _version(v)
, _format(f)
, _filter_tracker(make_lw_shared<distributed<filter_tracker>>())
, _now(now)
{ }
sstable& operator=(const sstable&) = delete;
sstable(const sstable&) = delete;
sstable(sstable&&) = default;
~sstable();
// Read one or few rows at the given byte range from the data file,
// feeding them into the consumer. This function reads the entire given
// byte range at once into memory, so it should not be used for iterating
// over all the rows in the data file (see the next function for that.
// The function returns a future which completes after all the data has
// been fed into the consumer. The caller needs to ensure the "consumer"
// object lives until then (e.g., using the do_with() idiom).
future<> data_consume_rows_at_once(row_consumer& consumer, uint64_t pos, uint64_t end);
// data_consume_rows() iterates over all rows in the data file (or rows in
// a particular range), feeding them into the consumer. The iteration is
// done as efficiently as possible - reading only the data file (not the
// summary or index files) and reading data in batches.
//
// The consumer object may request the iteration to stop before reaching
// the end of the requested data range (e.g. stop after each sstable row).
// A context object is returned which allows to resume this consumption:
// This context's read() method requests that consumption begins, and
// returns a future which will be resolved when it ends (because the
// consumer asked to stop, or the data range ended). Only after the
// returned future is resolved, may read() be called again to consume
// more.
// The caller must ensure (e.g., using do_with()) that the context object,
// as well as the sstable, remains alive as long as a read() is in
// progress (i.e., returned a future which hasn't completed yet).
data_consume_context data_consume_rows(row_consumer& consumer,
uint64_t start = 0, uint64_t end = 0);
static version_types version_from_sstring(sstring& s);
static format_types format_from_sstring(sstring& s);
static const sstring filename(sstring dir, version_types version, unsigned long generation,
format_types format, component_type component);
future<> load();
// Used to serialize sstable components, but so far only for the purpose
// of testing.
future<> store();
void set_generation(unsigned long generation) {
_generation = generation;
}
unsigned long generation() const {
return _generation;
}
future<mutation_opt> read_row(schema_ptr schema, const key& k);
/**
* @param schema a schema_ptr object describing this table
* @param min the minimum token we want to search for (inclusive)
* @param max the maximum token we want to search for (inclusive)
* @return a mutation_reader object that can be used to iterate over
* mutations.
*/
mutation_reader read_range_rows(schema_ptr schema,
const dht::token& min, const dht::token& max);
// read_rows() returns each of the rows in the sstable, in sequence,
// converted to a "mutation" data structure.
// This function is implemented efficiently - doing buffered, sequential
// read of the data file (no need to access the index file).
// A "mutation_reader" object is returned with which the caller can
// fetch mutations in sequence, and allows stop iteration any time
// after getting each row.
//
// The caller must ensure (e.g., using do_with()) that the context object,
// as well as the sstable, remains alive as long as a read() is in
// progress (i.e., returned a future which hasn't completed yet).
mutation_reader read_rows(schema_ptr schema);
// Write sstable components from a memtable.
future<> write_components(const memtable& mt);
future<> write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema);
uint64_t get_estimated_key_count() const {
return ((uint64_t)_summary.header.size_at_full_sampling + 1) *
_summary.header.min_index_interval;
}
// mark_for_deletion() specifies that the on-disk files for this sstable
// should be deleted as soon as the in-memory object is destructed.
void mark_for_deletion() {
_marked_for_deletion = true;
}
void add_ancestor(int generation) {
_collector.add_ancestor(generation);
}
private:
void do_write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema, file_writer& out);
void prepare_write_components(::mutation_reader mr,
uint64_t estimated_partitions, schema_ptr schema);
static std::unordered_map<version_types, sstring, enum_hash<version_types>> _version_string;
static std::unordered_map<format_types, sstring, enum_hash<format_types>> _format_string;
static std::unordered_map<component_type, sstring, enum_hash<component_type>> _component_map;
std::unordered_set<component_type, enum_hash<component_type>> _components;
compression _compression;
utils::filter_ptr _filter;
summary _summary;
statistics _statistics;
metadata_collector _collector;
column_stats _c_stats;
lw_shared_ptr<file> _index_file;
lw_shared_ptr<file> _data_file;
uint64_t _data_file_size;
sstring _dir;
unsigned long _generation = 0;
version_types _version;
format_types _format;
lw_shared_ptr<distributed<filter_tracker>> _filter_tracker;
bool _marked_for_deletion = false;
gc_clock::time_point _now;
const bool has_component(component_type f);
const sstring filename(component_type f);
template <sstable::component_type Type, typename T>
future<> read_simple(T& comp);
template <sstable::component_type Type, typename T>
future<> write_simple(T& comp);
uint64_t data_size();
future<> read_toc();
future<> write_toc();
future<> read_compression();
future<> write_compression();
future<> read_filter();
future<> write_filter();
future<> read_summary() {
return read_simple<component_type::Summary>(_summary);
}
future<> write_summary() {
return write_simple<component_type::Summary>(_summary);
}
future<> read_statistics();
future<> write_statistics();
future<> open_data();
future<> create_data();
future<index_list> read_indexes(uint64_t position, uint64_t quantity);
future<index_list> read_indexes(uint64_t position) {
return read_indexes(position, _summary.header.sampling_level);
}
input_stream<char> data_stream_at(uint64_t pos);
// Read exactly the specific byte range from the data file (after
// uncompression, if the file is compressed). This can be used to read
// a specific row from the data file (its position and length can be
// determined using the index file).
// This function is intended (and optimized for) random access, not
// for iteration through all the rows.
future<temporary_buffer<char>> data_read(uint64_t pos, size_t len);
future<uint64_t> data_end_position(int summary_idx, int index_idx, const index_list& il);
template <typename T>
int binary_search(const T& entries, const key& sk, const dht::token& token);
template <typename T>
int binary_search(const T& entries, const key& sk) {
return binary_search(entries, sk, dht::global_partitioner().get_token(key_view(sk)));
}
future<summary_entry&> read_summary_entry(size_t i);
// FIXME: pending on Bloom filter implementation
bool filter_has_key(const key& key) { return _filter->is_present(bytes_view(key)); }
bool filter_has_key(const schema& s, const dht::decorated_key& dk) { return filter_has_key(key::from_partition_key(s, dk._key)); }
// NOTE: functions used to generate sstable components.
void write_row_marker(file_writer& out, const rows_entry& clustered_row, const composite& clustering_key);
void write_clustered_row(file_writer& out, const schema& schema, const rows_entry& clustered_row);
void write_static_row(file_writer& out, const schema& schema, const row& static_row);
void write_cell(file_writer& out, atomic_cell_view cell);
void write_column_name(file_writer& out, const composite& clustering_key, const std::vector<bytes_view>& column_names, composite_marker m = composite_marker::none);
void write_range_tombstone(file_writer& out, const composite& clustering_prefix, std::vector<bytes_view> suffix, const tombstone t);
void write_collection(file_writer& out, const composite& clustering_key, const column_definition& cdef, collection_mutation::view collection);
public:
// Allow the test cases from sstable_test.cc to test private methods. We use
// a placeholder to avoid cluttering this class too much. The sstable_test class
// will then re-export as public every method it needs.
friend class test;
};
using shared_sstable = lw_shared_ptr<sstable>;
}
<|endoftext|>
|
<commit_before>#include "vast/util/editline.h"
#include <cassert>
#include <iostream>
#include <map>
#include <vector>
#include <histedit.h>
#include "vast/util/color.h"
namespace vast {
namespace util {
struct editline::history::impl
{
impl(int size, bool unique, std::string filename)
: filename_{std::move(filename)}
{
hist = ::history_init();
assert(hist != nullptr);
::history(hist, &hist_event, H_SETSIZE, size);
::history(hist, &hist_event, H_SETUNIQUE, unique ? 1 : 0);
load();
}
~impl()
{
save();
::history_end(hist);
}
void save()
{
if (! filename_.empty())
::history(hist, &hist_event, H_SAVE, filename_.c_str());
}
void load()
{
if (! filename_.empty())
::history(hist, &hist_event, H_LOAD, filename_.c_str());
}
void add(std::string const& str)
{
::history(hist, &hist_event, H_ADD, str.c_str());
save();
}
void append(std::string const& str)
{
::history(hist, &hist_event, H_APPEND, str.c_str());
}
void enter(std::string const& str)
{
::history(hist, &hist_event, H_ENTER, str.c_str());
}
History* hist;
HistEvent hist_event;
std::string filename_;
};
editline::history::history(int size, bool unique, std::string filename)
: impl_{new impl{size, unique, std::move(filename)}}
{
}
editline::history::~history()
{
}
void editline::history::save()
{
impl_->save();
}
void editline::history::load()
{
impl_->load();
}
void editline::history::add(std::string const& str)
{
impl_->add(str);
}
void editline::history::append(std::string const& str)
{
impl_->append(str);
}
void editline::history::enter(std::string const& str)
{
impl_->enter(str);
}
editline::prompt::prompt(std::string str, char const* color, char esc)
: esc_{esc}
{
push(std::move(str), color);
}
void editline::prompt::push(std::string str, char const* color)
{
if (str.empty())
return;
if (color)
str_ += esc_ + std::string{color} + esc_;
str_ += std::move(str);
if (color)
str_ += esc_ + std::string{util::color::reset} + esc_;
}
char const* editline::prompt::display() const
{
return str_.c_str();
}
char editline::prompt::escape() const
{
return esc_;
}
namespace {
// Given a query string *pfx* and map *m* whose keys represent the full
// matches, retrieves all matching entries in *m* where *pfx* is a full prefix
// of the key.
std::vector<std::string>
match(std::map<std::string, std::string> const& m, std::string const& pfx)
{
std::vector<std::string> matches;
for (auto& p : m)
{
auto& key = p.first;
if (pfx.size() >= key.size())
continue;
auto result = std::mismatch(pfx.begin(), pfx.end(), key.begin());
if (result.first == pfx.end())
matches.push_back(key);
}
return matches;
}
// Scope-wise setting of terminal editing mode via EL_PREP_TERM.
struct scope_setter
{
scope_setter(EditLine* el, int flag)
: el{el}, flag{flag}
{
el_set(el, flag, 1);
}
~scope_setter()
{
assert(el);
el_set(el, flag, 0);
}
EditLine* el;
int flag;
};
} // namespace <anonymous>
struct editline::impl
{
static char* prompt_function(EditLine* el)
{
impl* instance;
el_get(el, EL_CLIENTDATA, &instance);
return const_cast<char*>(instance->prompt_.display());
}
static unsigned char handle_complete(EditLine* el, int)
{
impl* instance;
el_get(el, EL_CLIENTDATA, &instance);
auto prefix = instance->cursor_line();
auto matches = match(instance->completions_, prefix);
if (matches.empty())
return CC_REFRESH_BEEP;
if (matches.size() == 1)
{
instance->insert(matches.front().substr(prefix.size()));
}
else
{
std::cout << '\n';
for (auto& match : matches)
std::cout << match << std::endl;
}
return CC_REDISPLAY;
}
impl(char const* name, char const* comp_key = "\t")
: el_{el_init(name, stdin, stdout, stderr)},
completion_key_{comp_key}
{
assert(el_ != nullptr);
// Sane defaults.
el_set(el_, EL_EDITOR, "vi");
// Make ourselves available in callbacks.
el_set(el_, EL_CLIENTDATA, this);
// Setup completion.
el_set(el_, EL_ADDFN, "vast-complete", "VAST complete", &handle_complete);
el_set(el_, EL_BIND, completion_key_, "vast-complete", NULL);
// FIXME: this is a fix for folks that have "bind -v" in their .editrc.
// Most of these also have "bind ^I rl_complete" in there to re-enable tab
// completion, which "bind -v" somehow disabled. A better solution to
// handle this problem would be desirable.
el_set(el_, EL_ADDFN, "rl_complete", "default complete", &handle_complete);
}
~impl()
{
el_end(el_);
}
bool source(char const* filename)
{
return el_source(el_, filename) != -1;
}
void set(prompt p)
{
prompt_ = std::move(p);
el_set(el_, EL_PROMPT_ESC, &prompt_function, prompt_.escape());
}
void set(history& hist)
{
el_set(el_, EL_HIST, ::history, hist.impl_->hist);
}
bool complete(std::string cmd, std::string desc)
{
if (completions_.count(cmd))
return false;
completions_.emplace(std::move(cmd), std::move(desc));
return true;
}
bool get(char& c)
{
return el_getc(el_, &c) == 1;
}
bool get(std::string& line)
{
scope_setter ss{el_, EL_PREP_TERM};
int n;
auto str = el_gets(el_, &n);
if (n == -1)
return false;
if (str == nullptr)
line.clear();
else
line.assign(str);
if (! line.empty() && (line.back() == '\n' || line.back() == '\r'))
line.pop_back();
return true;
}
void insert(std::string const& str)
{
el_insertstr(el_, str.c_str());
}
size_t cursor()
{
auto info = el_line(el_);
return info->cursor - info->buffer;
}
std::string line()
{
auto info = el_line(el_);
return {info->buffer,
static_cast<std::string::size_type>(info->lastchar - info->buffer)};
}
std::string cursor_line()
{
auto info = el_line(el_);
return {info->buffer,
static_cast<std::string::size_type>(info->cursor - info->buffer)};
}
void reset()
{
el_reset(el_);
}
void resize()
{
el_resize(el_);
}
void beep()
{
el_beep(el_);
}
EditLine* el_;
char const* completion_key_;
prompt prompt_;
std::map<std::string, std::string> completions_;
};
editline::editline(char const* name)
: impl_{new impl{name}}
{
}
editline::~editline()
{
}
bool editline::source(char const* filename)
{
return impl_->source(filename);
}
void editline::set(prompt p)
{
impl_->set(std::move(p));
}
void editline::set(history& hist)
{
impl_->set(hist);
}
bool editline::complete(std::string cmd, std::string desc)
{
return impl_->complete(std::move(cmd), std::move(desc));
}
bool editline::get(char& c)
{
return impl_->get(c);
}
bool editline::get(std::string& line)
{
return impl_->get(line);
}
void editline::put(std::string const& str)
{
impl_->insert(str);
}
std::string editline::line()
{
return impl_->line();
}
size_t editline::cursor()
{
return impl_->cursor();
}
void editline::reset()
{
impl_->reset();
}
} // namespace util
} // namespace vast
<commit_msg>Complete command prefix in yellow color.<commit_after>#include "vast/util/editline.h"
#include <cassert>
#include <iostream>
#include <map>
#include <vector>
#include <histedit.h>
#include "vast/util/color.h"
namespace vast {
namespace util {
struct editline::history::impl
{
impl(int size, bool unique, std::string filename)
: filename_{std::move(filename)}
{
hist = ::history_init();
assert(hist != nullptr);
::history(hist, &hist_event, H_SETSIZE, size);
::history(hist, &hist_event, H_SETUNIQUE, unique ? 1 : 0);
load();
}
~impl()
{
save();
::history_end(hist);
}
void save()
{
if (! filename_.empty())
::history(hist, &hist_event, H_SAVE, filename_.c_str());
}
void load()
{
if (! filename_.empty())
::history(hist, &hist_event, H_LOAD, filename_.c_str());
}
void add(std::string const& str)
{
::history(hist, &hist_event, H_ADD, str.c_str());
save();
}
void append(std::string const& str)
{
::history(hist, &hist_event, H_APPEND, str.c_str());
}
void enter(std::string const& str)
{
::history(hist, &hist_event, H_ENTER, str.c_str());
}
History* hist;
HistEvent hist_event;
std::string filename_;
};
editline::history::history(int size, bool unique, std::string filename)
: impl_{new impl{size, unique, std::move(filename)}}
{
}
editline::history::~history()
{
}
void editline::history::save()
{
impl_->save();
}
void editline::history::load()
{
impl_->load();
}
void editline::history::add(std::string const& str)
{
impl_->add(str);
}
void editline::history::append(std::string const& str)
{
impl_->append(str);
}
void editline::history::enter(std::string const& str)
{
impl_->enter(str);
}
editline::prompt::prompt(std::string str, char const* color, char esc)
: esc_{esc}
{
push(std::move(str), color);
}
void editline::prompt::push(std::string str, char const* color)
{
if (str.empty())
return;
if (color)
str_ += esc_ + std::string{color} + esc_;
str_ += std::move(str);
if (color)
str_ += esc_ + std::string{util::color::reset} + esc_;
}
char const* editline::prompt::display() const
{
return str_.c_str();
}
char editline::prompt::escape() const
{
return esc_;
}
namespace {
// Given a query string *pfx* and map *m* whose keys represent the full
// matches, retrieves all matching entries in *m* where *pfx* is a full prefix
// of the key.
std::vector<std::string>
match(std::map<std::string, std::string> const& m, std::string const& pfx)
{
std::vector<std::string> matches;
for (auto& p : m)
{
auto& key = p.first;
if (pfx.size() >= key.size())
continue;
auto result = std::mismatch(pfx.begin(), pfx.end(), key.begin());
if (result.first == pfx.end())
matches.push_back(key);
}
return matches;
}
// RAII enabling of editline settings.
struct scope_setter
{
scope_setter(EditLine* el, int flag)
: el{el}, flag{flag}
{
el_set(el, flag, 1);
}
~scope_setter()
{
assert(el);
el_set(el, flag, 0);
}
EditLine* el;
int flag;
};
} // namespace <anonymous>
struct editline::impl
{
static char* prompt_function(EditLine* el)
{
impl* instance;
el_get(el, EL_CLIENTDATA, &instance);
return const_cast<char*>(instance->prompt_.display());
}
static unsigned char handle_complete(EditLine* el, int)
{
impl* instance;
el_get(el, EL_CLIENTDATA, &instance);
auto prefix = instance->cursor_line();
auto matches = match(instance->completions_, prefix);
if (matches.empty())
return CC_REFRESH_BEEP;
if (matches.size() == 1)
{
instance->insert(matches.front().substr(prefix.size()));
}
else
{
std::cout << '\n';
for (auto& match : matches)
std::cout
<< util::color::yellow << prefix << util::color::reset
<< match.substr(prefix.size()) << std::endl;
}
return CC_REDISPLAY;
}
impl(char const* name, char const* comp_key = "\t")
: el_{el_init(name, stdin, stdout, stderr)},
completion_key_{comp_key}
{
assert(el_ != nullptr);
// Sane defaults.
el_set(el_, EL_EDITOR, "vi");
// Make ourselves available in callbacks.
el_set(el_, EL_CLIENTDATA, this);
// Setup completion.
el_set(el_, EL_ADDFN, "vast-complete", "VAST complete", &handle_complete);
el_set(el_, EL_BIND, completion_key_, "vast-complete", NULL);
// FIXME: this is a fix for folks that have "bind -v" in their .editrc.
// Most of these also have "bind ^I rl_complete" in there to re-enable tab
// completion, which "bind -v" somehow disabled. A better solution to
// handle this problem would be desirable.
el_set(el_, EL_ADDFN, "rl_complete", "default complete", &handle_complete);
}
~impl()
{
el_end(el_);
}
bool source(char const* filename)
{
return el_source(el_, filename) != -1;
}
void set(prompt p)
{
prompt_ = std::move(p);
el_set(el_, EL_PROMPT_ESC, &prompt_function, prompt_.escape());
}
void set(history& hist)
{
el_set(el_, EL_HIST, ::history, hist.impl_->hist);
}
bool complete(std::string cmd, std::string desc)
{
if (completions_.count(cmd))
return false;
completions_.emplace(std::move(cmd), std::move(desc));
return true;
}
bool get(char& c)
{
return el_getc(el_, &c) == 1;
}
bool get(std::string& line)
{
scope_setter ss{el_, EL_PREP_TERM};
int n;
auto str = el_gets(el_, &n);
if (n == -1)
return false;
if (str == nullptr)
line.clear();
else
line.assign(str);
if (! line.empty() && (line.back() == '\n' || line.back() == '\r'))
line.pop_back();
return true;
}
void insert(std::string const& str)
{
el_insertstr(el_, str.c_str());
}
size_t cursor()
{
auto info = el_line(el_);
return info->cursor - info->buffer;
}
std::string line()
{
auto info = el_line(el_);
return {info->buffer,
static_cast<std::string::size_type>(info->lastchar - info->buffer)};
}
std::string cursor_line()
{
auto info = el_line(el_);
return {info->buffer,
static_cast<std::string::size_type>(info->cursor - info->buffer)};
}
void reset()
{
el_reset(el_);
}
void resize()
{
el_resize(el_);
}
void beep()
{
el_beep(el_);
}
EditLine* el_;
char const* completion_key_;
prompt prompt_;
std::map<std::string, std::string> completions_;
};
editline::editline(char const* name)
: impl_{new impl{name}}
{
}
editline::~editline()
{
}
bool editline::source(char const* filename)
{
return impl_->source(filename);
}
void editline::set(prompt p)
{
impl_->set(std::move(p));
}
void editline::set(history& hist)
{
impl_->set(hist);
}
bool editline::complete(std::string cmd, std::string desc)
{
return impl_->complete(std::move(cmd), std::move(desc));
}
bool editline::get(char& c)
{
return impl_->get(c);
}
bool editline::get(std::string& line)
{
return impl_->get(line);
}
void editline::put(std::string const& str)
{
impl_->insert(str);
}
std::string editline::line()
{
return impl_->line();
}
size_t editline::cursor()
{
return impl_->cursor();
}
void editline::reset()
{
impl_->reset();
}
} // namespace util
} // namespace vast
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Tests that log rolling and excess logfile cleanup logic works correctly.
#include <algorithm>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "kudu/gutil/strings/substitute.h"
#include "kudu/integration-tests/external_mini_cluster.h"
#include "kudu/util/env.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
using std::string;
using std::vector;
using strings::Substitute;
namespace kudu {
static int64_t CountInfoLogs(const string& log_dir) {
vector<string> logfiles;
string pattern = Substitute("$0/*.$1.*", log_dir, "INFO");
CHECK_OK(Env::Default()->Glob(pattern, &logfiles));
return logfiles.size();
}
// Tests that logs roll on startup, and get cleaned up appropriately.
TEST(LogRollingITest, TestLogCleanupOnStartup) {
ExternalMiniClusterOptions opts;
opts.num_masters = 1;
opts.num_tablet_servers = 0;
opts.extra_master_flags = { "--max_log_files=3", };
opts.logtostderr = false;
ExternalMiniCluster cluster(std::move(opts));
ASSERT_OK(cluster.Start());
// Explicitly wait for the catalog manager because we've got no tservers in
// our cluster, which means the usual waiting in ExternalMiniCluster::Start()
// won't work.
//
// This is only needed the first time the master starts so that it can write
// the catalog out to disk.
ASSERT_OK(cluster.master()->WaitForCatalogManager());
for (int i = 1; i <= 10; i++) {
ASSERT_EVENTUALLY([&] () {
ASSERT_EQ(std::min(3, i), CountInfoLogs(cluster.master()->log_dir()));
});
cluster.master()->Shutdown();
ASSERT_OK(cluster.master()->Restart());
}
}
} // namespace kudu
<commit_msg>log-rolling-itest: delete test files when test ends<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Tests that log rolling and excess logfile cleanup logic works correctly.
#include <algorithm>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "kudu/gutil/strings/substitute.h"
#include "kudu/integration-tests/external_mini_cluster.h"
#include "kudu/util/env.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
using std::string;
using std::vector;
using strings::Substitute;
namespace kudu {
class LogRollingITest : public KuduTest {};
static int64_t CountInfoLogs(const string& log_dir) {
vector<string> logfiles;
string pattern = Substitute("$0/*.$1.*", log_dir, "INFO");
CHECK_OK(Env::Default()->Glob(pattern, &logfiles));
return logfiles.size();
}
// Tests that logs roll on startup, and get cleaned up appropriately.
TEST_F(LogRollingITest, TestLogCleanupOnStartup) {
ExternalMiniClusterOptions opts;
opts.num_masters = 1;
opts.num_tablet_servers = 0;
opts.extra_master_flags = { "--max_log_files=3", };
opts.logtostderr = false;
ExternalMiniCluster cluster(std::move(opts));
ASSERT_OK(cluster.Start());
// Explicitly wait for the catalog manager because we've got no tservers in
// our cluster, which means the usual waiting in ExternalMiniCluster::Start()
// won't work.
//
// This is only needed the first time the master starts so that it can write
// the catalog out to disk.
ASSERT_OK(cluster.master()->WaitForCatalogManager());
for (int i = 1; i <= 10; i++) {
ASSERT_EVENTUALLY([&] () {
ASSERT_EQ(std::min(3, i), CountInfoLogs(cluster.master()->log_dir()));
});
cluster.master()->Shutdown();
ASSERT_OK(cluster.master()->Restart());
}
}
} // namespace kudu
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginCommandLineArgs
// INPUTS: {suburb2.jpeg}
// OUTPUTS: {EdgeDensityOutput.png}, {PrettyEdgeDensityOutput.png}
// 3 30 10 1.0 0.01
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{EdgeDensityImageFilter}.
// This filter computes a local density of edges on an image and can
// be useful to detect man made objects or urban areas, for
// instance. The filter has been implemented in a generic way, so that
// the way the edges are detected and the way their density is
// computed can be chosen by the user.
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbEdgeDensityImageFilter.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We will also include the header files for the edge detector (a
// Canny filter) and the density estimation (a simple count on a
// binary image).
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkCannyEdgeDetectionImageFilter.h"
#include "otbBinaryImageDensityFunction.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[] )
{
const char * infname = argv[1];
const char * outfname = argv[2];
const char * prettyfilename = argv[3];
const unsigned int radius = atoi(argv[4]);
/*--*/
const unsigned int Dimension = 2;
typedef float PixelType;
/** Variables for the canny detector*/
const PixelType upperThreshold = static_cast<PixelType>(atof(argv[5]));
const PixelType lowerThreshold = static_cast<PixelType>(atof(argv[6]));
const double variance = atof(argv[7]);
const double maximumError = atof(argv[8]);
// Software Guide : BeginLatex
//
// As usual, we start by defining the types for the images, the reader
// and the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image< PixelType, Dimension > ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<ImageType> WriterType;
// Software Guide : BeginCodeSnippet
// Software Guide : BeginLatex
//
// We define now the type for the function which will be used by the
// edge density filter to estimate this density. Here we choose a
// function which counts the number of non null pixels per area. The
// fucntion takes as template the type of the image to be processed.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::BinaryImageDensityFunction<ImageType> CountFunctionType;
// Software Guide : BeginCodeSnippet
// Software Guide : BeginLatex
//
// These {\em non null pixels} will be the result of an edge
// detector. We use here the classical Canny edge detector, which is
// templated over the input and output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CannyEdgeDetectionImageFilter<ImageType, ImageType>
CannyDetectorType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we can define the type for the edge density filter which
// takes as template the input and output image types, the edge
// detector type, and the count fucntion type..
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::EdgeDensityImageFilter<ImageType, ImageType, CannyDetectorType,
CountFunctionType> EdgeDensityFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now instantiate the different processing objects of the
// pipeline using the \code{New()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
EdgeDensityFilterType::Pointer filter = EdgeDensityFilterType::New();
CannyDetectorType::Pointer cannyFilter = CannyDetectorType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The edge detection filter needs to be instantiated because we
// need to set its parameters. This is what we do here for the Canny
// filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
cannyFilter->SetUpperThreshold(upperThreshold);
cannyFilter->SetLowerThreshold(lowerThreshold);
cannyFilter->SetVariance(variance);
cannyFilter->SetMaximumError(maximumError);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// After that, we can pass the edge detector to the filter which
// will use it internally.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetDetector(cannyFilter);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we set the file names for the input and the output
// images and we plug the pipeline. The \code{Update()} method of
// the writer will trigger the processing.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->SetFileName(infname);
writer->SetFileName(outfname);
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure~\ref{fig:EDGEDENSITY_FILTER} shows the result of applying
// the edge density filter to an image.
// \begin{figure}
// \center
// \includegraphics[width=0.25\textwidth]{suburb2.eps}
// \includegraphics[width=0.25\textwidth]{PrettyEdgeDensityOutput.eps}
// \itkcaption[Edge Density Filter]{Result of applying the
// \doxygen{otb}{EdgeDensityImageFilter} to an image. From left to right :
// original image, edge density.}
// \label{fig:EDGEDENSITY_FILTER}
// \end{figure}
//
// Software Guide : EndLatex
/************* Image for printing **************/
typedef otb::Image< unsigned char, 2 > OutputImageType;
typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType >
RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->SetInput( filter->GetOutput() );
typedef otb::ImageFileWriter< OutputImageType > OutputWriterType;
OutputWriterType::Pointer outwriter = OutputWriterType::New();
outwriter->SetFileName( prettyfilename );
outwriter->SetInput( rescaler->GetOutput() );
outwriter->Update();
return EXIT_SUCCESS;
}
<commit_msg>DOC: set good parameters<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginCommandLineArgs
// INPUTS: {suburb2.jpeg}
// OUTPUTS: {EdgeDensityOutput.tif}, {PrettyEdgeDensityOutput.png}
// 7 50 10 1.0 0.01
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{EdgeDensityImageFilter}.
// This filter computes a local density of edges on an image and can
// be useful to detect man made objects or urban areas, for
// instance. The filter has been implemented in a generic way, so that
// the way the edges are detected and the way their density is
// computed can be chosen by the user.
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbEdgeDensityImageFilter.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We will also include the header files for the edge detector (a
// Canny filter) and the density estimation (a simple count on a
// binary image).
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkCannyEdgeDetectionImageFilter.h"
#include "otbBinaryImageDensityFunction.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[] )
{
const char * infname = argv[1];
const char * outfname = argv[2];
const char * prettyfilename = argv[3];
const unsigned int radius = atoi(argv[4]);
/*--*/
const unsigned int Dimension = 2;
typedef float PixelType;
/** Variables for the canny detector*/
const PixelType upperThreshold = static_cast<PixelType>(atof(argv[5]));
const PixelType lowerThreshold = static_cast<PixelType>(atof(argv[6]));
const double variance = atof(argv[7]);
const double maximumError = atof(argv[8]);
// Software Guide : BeginLatex
//
// As usual, we start by defining the types for the images, the reader
// and the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image< PixelType, Dimension > ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<ImageType> WriterType;
// Software Guide : BeginCodeSnippet
// Software Guide : BeginLatex
//
// We define now the type for the function which will be used by the
// edge density filter to estimate this density. Here we choose a
// function which counts the number of non null pixels per area. The
// fucntion takes as template the type of the image to be processed.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::BinaryImageDensityFunction<ImageType> CountFunctionType;
// Software Guide : BeginCodeSnippet
// Software Guide : BeginLatex
//
// These {\em non null pixels} will be the result of an edge
// detector. We use here the classical Canny edge detector, which is
// templated over the input and output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CannyEdgeDetectionImageFilter<ImageType, ImageType>
CannyDetectorType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we can define the type for the edge density filter which
// takes as template the input and output image types, the edge
// detector type, and the count fucntion type..
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::EdgeDensityImageFilter<ImageType, ImageType, CannyDetectorType,
CountFunctionType> EdgeDensityFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now instantiate the different processing objects of the
// pipeline using the \code{New()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
EdgeDensityFilterType::Pointer filter = EdgeDensityFilterType::New();
CannyDetectorType::Pointer cannyFilter = CannyDetectorType::New();
WriterType::Pointer writer = WriterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The edge detection filter needs to be instantiated because we
// need to set its parameters. This is what we do here for the Canny
// filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
cannyFilter->SetUpperThreshold(upperThreshold);
cannyFilter->SetLowerThreshold(lowerThreshold);
cannyFilter->SetVariance(variance);
cannyFilter->SetMaximumError(maximumError);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// After that, we can pass the edge detector to the filter which
// will use it internally.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetDetector(cannyFilter);
filter->SetNeighborhoodRadius( radius );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we set the file names for the input and the output
// images and we plug the pipeline. The \code{Update()} method of
// the writer will trigger the processing.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader->SetFileName(infname);
writer->SetFileName(outfname);
filter->SetInput(reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure~\ref{fig:EDGEDENSITY_FILTER} shows the result of applying
// the edge density filter to an image.
// \begin{figure}
// \center
// \includegraphics[width=0.25\textwidth]{suburb2.eps}
// \includegraphics[width=0.25\textwidth]{PrettyEdgeDensityOutput.eps}
// \itkcaption[Edge Density Filter]{Result of applying the
// \doxygen{otb}{EdgeDensityImageFilter} to an image. From left to right :
// original image, edge density.}
// \label{fig:EDGEDENSITY_FILTER}
// \end{figure}
//
// Software Guide : EndLatex
/************* Image for printing **************/
typedef otb::Image< unsigned char, 2 > OutputImageType;
typedef itk::RescaleIntensityImageFilter< ImageType, OutputImageType >
RescalerType;
RescalerType::Pointer rescaler = RescalerType::New();
rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->SetInput( filter->GetOutput() );
typedef otb::ImageFileWriter< OutputImageType > OutputWriterType;
OutputWriterType::Pointer outwriter = OutputWriterType::New();
outwriter->SetFileName( prettyfilename );
outwriter->SetInput( rescaler->GetOutput() );
outwriter->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before><commit_msg>Render sprites using textures' samplers<commit_after><|endoftext|>
|
<commit_before>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-30 GONG Chen <[email protected]>
//
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/schema.h>
#include <rime/impl/syllablizer.h>
#include <rime/impl/table.h>
#include <rime/impl/user_db.h>
#include <rime/impl/user_dictionary.h>
namespace rime {
// UserDictionary members
UserDictionary::UserDictionary(const shared_ptr<UserDb> &user_db)
: db_(user_db), tick_(0) {
}
UserDictionary::~UserDictionary() {
}
void UserDictionary::Attach(const shared_ptr<Table> &table, const shared_ptr<Prism> &prism) {
table_ = table;
prism_ = prism;
}
bool UserDictionary::Load() {
if (!db_ || !db_->Open())
return false;
if (!FetchTickCount() && !Initialize())
return false;
return true;
}
bool UserDictionary::loaded() const {
return db_ && db_->loaded();
}
struct DfsState {
Code code;
shared_ptr<UserDictEntryCollector> collector;
shared_ptr<UserDbAccessor> accessor;
std::string key;
std::string value;
bool IsExactMatch(const std::string &prefix) {
size_t prefix_len = prefix.length();
return key.length() > prefix_len && key[prefix_len] == '\t';
}
bool IsPrefixMatch(const std::string &prefix) {
return boost::starts_with(key, prefix);
}
void SaveEntry(int pos);
bool NextEntry() {
if (!accessor->GetNextRecord(&key, &value)) {
key.clear();
value.clear();
return false; // reached the end
}
return true;
}
bool ForwardScan(const std::string &prefix) {
if (!accessor->Forward(prefix))
return false;
return NextEntry();
}
};
void DfsState::SaveEntry(int pos) {
DictEntry e;
size_t seperator_pos = key.find('\t');
if (seperator_pos == std::string::npos)
return;
e.text = key.substr(seperator_pos + 1);
// TODO: Magicalc
e.weight = 1.0;
e.commit_count = 1;
e.code = code;
(*collector)[pos].push_back(e);
}
bool UserDictionary::DfsLookup(const SyllableGraph &syll_graph, size_t current_pos,
const std::string ¤t_prefix,
DfsState *state) {
EdgeMap::const_iterator edges = syll_graph.edges.find(current_pos);
if (edges == syll_graph.edges.end()) {
return true; // continue DFS lookup
}
std::string prefix;
BOOST_FOREACH(const EndVertexMap::value_type &edge, edges->second) {
int end_vertex_pos = edge.first;
const SpellingMap &spellings(edge.second);
BOOST_FOREACH(const SpellingMap::value_type &spelling, spellings) {
SyllableId syll_id = spelling.first;
state->code.push_back(syll_id);
if (!TranslateCodeToString(state->code, &prefix))
continue;
if (prefix > state->key) { // 'a b c |d ' > 'a b c \tabracadabra'
if (!state->ForwardScan(prefix)) {
return false; // terminate DFS lookup
}
}
while (state->IsExactMatch(prefix)) { // 'b |e ' vs. 'b e \tBe'
state->SaveEntry(end_vertex_pos);
if (!state->NextEntry())
return false;
}
if (state->IsPrefixMatch(prefix)) { // 'b |e ' vs. 'b e f \tBefore'
if (!DfsLookup(syll_graph, end_vertex_pos, prefix, state))
return false;
}
state->code.pop_back();
if (!state->IsPrefixMatch(current_prefix)) { // 'b |' vs. 'g o \tGo'
return true; // pruning: done with the current prefix code
}
// 'b |e ' vs. 'b y \tBy'
}
}
return true; // finished traversing the syllable graph
}
shared_ptr<UserDictEntryCollector> UserDictionary::Lookup(const SyllableGraph &syll_graph, size_t start_pos) {
if (!table_ || !prism_ || !loaded() ||
start_pos >= syll_graph.interpreted_length)
return shared_ptr<UserDictEntryCollector>();
DfsState state;
state.collector.reset(new UserDictEntryCollector);
state.accessor.reset(new UserDbAccessor(db_->Query("")));
state.accessor->Forward(" "); // skip metadata
std::string prefix;
DfsLookup(syll_graph, start_pos, prefix, &state);
if (state.collector->empty())
return shared_ptr<UserDictEntryCollector>();
// sort each group of homophones by weight ASC (to retrieve with pop_back())
BOOST_FOREACH(UserDictEntryCollector::value_type &v, *state.collector) {
std::sort(v.second.begin(), v.second.end());
}
return state.collector;
}
bool UserDictionary::UpdateEntry(const DictEntry &entry, int commit) {
std::string code_str;
if (!TranslateCodeToString(entry.code, &code_str))
return false;
std::string key(code_str + '\t' + entry.text);
double weight = entry.weight;
int commit_count = entry.commit_count;
if (commit > 0) {
// TODO: Magicalc
weight += commit;
commit_count += commit;
}
else if (commit < 0) {
commit_count = (std::min)(-1, -commit_count);
}
std::string value(boost::str(boost::format("c=%1% w=%2% t=%3%") % commit_count % weight % tick_));
return db_->Update(key, value);
}
bool UserDictionary::UpdateTickCount(TickCount increment) {
tick_ += increment;
try {
return db_->Update("\0x01/tick", boost::lexical_cast<std::string>(tick_));
}
catch (...) {
return false;
}
}
bool UserDictionary::Initialize() {
// TODO: something else?
return db_->Update("\0x01/tick", "0");
}
bool UserDictionary::FetchTickCount() {
std::string value;
try {
if (!db_->Fetch("\0x01/tick", &value))
return false;
tick_ = boost::lexical_cast<TickCount>(value);
return true;
}
catch (...) {
tick_ = 0;
return false;
}
}
bool UserDictionary::TranslateCodeToString(const Code &code, std::string* result) {
if (!table_ || !result) return false;
result->clear();
BOOST_FOREACH(const int &syllable_id, code) {
const char *spelling = table_->GetSyllableById(syllable_id);
if (!spelling) {
result->clear();
return false;
}
*result += spelling;
*result += ' ';
}
return true;
}
// UserDictionaryComponent members
UserDictionaryComponent::UserDictionaryComponent() {
}
UserDictionary* UserDictionaryComponent::Create(Schema *schema) {
if (!schema) return NULL;
Config *config = schema->config();
const std::string &schema_id(schema->schema_id());
std::string dict_name;
if (!config->GetString("translator/dictionary", &dict_name)) {
EZLOGGERPRINT("Error: dictionary not specified in schema '%s'.",
schema_id.c_str());
return NULL;
}
// obtain userdb object
shared_ptr<UserDb> user_db(user_db_pool_[dict_name].lock());
if (!user_db) {
user_db.reset(new UserDb(dict_name));
user_db_pool_[dict_name] = user_db;
}
return new UserDictionary(user_db);
}
} // namespace rime
<commit_msg>Confused with the buffers.<commit_after>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-30 GONG Chen <[email protected]>
//
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/schema.h>
#include <rime/impl/syllablizer.h>
#include <rime/impl/table.h>
#include <rime/impl/user_db.h>
#include <rime/impl/user_dictionary.h>
namespace rime {
// UserDictionary members
UserDictionary::UserDictionary(const shared_ptr<UserDb> &user_db)
: db_(user_db), tick_(0) {
}
UserDictionary::~UserDictionary() {
}
void UserDictionary::Attach(const shared_ptr<Table> &table, const shared_ptr<Prism> &prism) {
table_ = table;
prism_ = prism;
}
bool UserDictionary::Load() {
if (!db_ || !db_->Open())
return false;
if (!FetchTickCount() && !Initialize())
return false;
return true;
}
bool UserDictionary::loaded() const {
return db_ && db_->loaded();
}
struct DfsState {
Code code;
shared_ptr<UserDictEntryCollector> collector;
shared_ptr<UserDbAccessor> accessor;
std::string key;
std::string value;
bool IsExactMatch(const std::string &prefix) {
size_t prefix_len = prefix.length();
return key.length() > prefix_len && key[prefix_len] == '\t';
}
bool IsPrefixMatch(const std::string &prefix) {
return boost::starts_with(key, prefix);
}
void SaveEntry(int pos);
bool NextEntry() {
if (!accessor->GetNextRecord(&key, &value)) {
key.clear();
value.clear();
return false; // reached the end
}
return true;
}
bool ForwardScan(const std::string &prefix) {
if (!accessor->Forward(prefix))
return false;
return NextEntry();
}
};
void DfsState::SaveEntry(int pos) {
DictEntry e;
size_t seperator_pos = key.find('\t');
if (seperator_pos == std::string::npos)
return;
e.text = key.substr(seperator_pos + 1);
// TODO: Magicalc
e.weight = 1.0;
e.commit_count = 1;
e.code = code;
(*collector)[pos].push_back(e);
}
bool UserDictionary::DfsLookup(const SyllableGraph &syll_graph, size_t current_pos,
const std::string ¤t_prefix,
DfsState *state) {
EdgeMap::const_iterator edges = syll_graph.edges.find(current_pos);
if (edges == syll_graph.edges.end()) {
return true; // continue DFS lookup
}
std::string prefix;
BOOST_FOREACH(const EndVertexMap::value_type &edge, edges->second) {
int end_vertex_pos = edge.first;
const SpellingMap &spellings(edge.second);
BOOST_FOREACH(const SpellingMap::value_type &spelling, spellings) {
SyllableId syll_id = spelling.first;
state->code.push_back(syll_id);
if (!TranslateCodeToString(state->code, &prefix))
continue;
if (prefix > state->key) { // 'a b c |d ' > 'a b c \tabracadabra'
if (!state->ForwardScan(prefix)) {
return false; // terminate DFS lookup
}
}
while (state->IsExactMatch(prefix)) { // 'b |e ' vs. 'b e \tBe'
state->SaveEntry(end_vertex_pos);
if (!state->NextEntry())
return false;
}
if (state->IsPrefixMatch(prefix)) { // 'b |e ' vs. 'b e f \tBefore'
if (!DfsLookup(syll_graph, end_vertex_pos, prefix, state))
return false;
}
state->code.pop_back();
if (!state->IsPrefixMatch(current_prefix)) { // 'b |' vs. 'g o \tGo'
return true; // pruning: done with the current prefix code
}
// 'b |e ' vs. 'b y \tBy'
}
}
return true; // finished traversing the syllable graph
}
shared_ptr<UserDictEntryCollector> UserDictionary::Lookup(const SyllableGraph &syll_graph, size_t start_pos) {
if (!table_ || !prism_ || !loaded() ||
start_pos >= syll_graph.interpreted_length)
return shared_ptr<UserDictEntryCollector>();
DfsState state;
state.collector.reset(new UserDictEntryCollector);
state.accessor.reset(new UserDbAccessor(db_->Query("")));
state.accessor->Forward(" "); // skip metadata
std::string prefix;
DfsLookup(syll_graph, start_pos, prefix, &state);
if (state.collector->empty())
return shared_ptr<UserDictEntryCollector>();
// sort each group of homophones by weight ASC (to retrieve with pop_back())
BOOST_FOREACH(UserDictEntryCollector::value_type &v, *state.collector) {
std::sort(v.second.begin(), v.second.end());
}
return state.collector;
}
bool UserDictionary::UpdateEntry(const DictEntry &entry, int commit) {
std::string code_str;
if (!TranslateCodeToString(entry.code, &code_str))
return false;
std::string key(code_str + '\t' + entry.text);
double weight = entry.weight;
int commit_count = entry.commit_count;
if (commit > 0) {
// TODO: Magicalc
weight += commit;
commit_count += commit;
}
else if (commit < 0) {
commit_count = (std::min)(-1, -commit_count);
}
std::string value(boost::str(boost::format("c=%1% w=%2% t=%3%") % commit_count % weight % tick_));
return db_->Update(key, value);
}
bool UserDictionary::UpdateTickCount(TickCount increment) {
tick_ += increment;
try {
return db_->Update("\0x01/tick", boost::lexical_cast<std::string>(tick_));
}
catch (...) {
return false;
}
}
bool UserDictionary::Initialize() {
// TODO: something else?
return db_->Update("\0x01/tick", "0");
}
bool UserDictionary::FetchTickCount() {
std::string value;
try {
if (!db_->Fetch("\0x01/tick", &value))
return false;
tick_ = boost::lexical_cast<TickCount>(value);
return true;
}
catch (...) {
tick_ = 0;
return false;
}
}
bool UserDictionary::TranslateCodeToString(const Code &code, std::string* result) {
if (!table_ || !result) return false;
result->clear();
BOOST_FOREACH(const int &syllable_id, code) {
const char *spelling = table_->GetSyllableById(syllable_id);
if (!spelling) {
result->clear();
return false;
}
*result += spelling;
*result += ' ';
}
return true;
}
// UserDictionaryComponent members
UserDictionaryComponent::UserDictionaryComponent() {
}
UserDictionary* UserDictionaryComponent::Create(Schema *schema) {
if (!schema) return NULL;
Config *config = schema->config();
bool enable_user_dict = true;
config->GetBool("translator/enable_user_dict", &enable_user_dict);
if (!enable_user_dict)
return NULL;
std::string dict_name;
if (!config->GetString("translator/dictionary", &dict_name)) {
EZLOGGERPRINT("Error: dictionary not specified in schema '%s'.",
schema->schema_id().c_str());
return NULL;
}
// obtain userdb object
shared_ptr<UserDb> user_db(user_db_pool_[dict_name].lock());
if (!user_db) {
user_db.reset(new UserDb(dict_name));
user_db_pool_[dict_name] = user_db;
}
return new UserDictionary(user_db);
}
} // namespace rime
<|endoftext|>
|
<commit_before>namespace query {
class qr_cell stub [[writable]] {
std::optional<api::timestamp_type> timestamp; // present when send_timestamp option set in partition_slice
std::optional<gc_clock::time_point> expiry; // present when send_expiry option set in partition_slice
// Specified by CQL binary protocol, according to cql_serialization_format in read_command.
bytes value;
std::optional<gc_clock::duration> ttl [[version 1.3]]; // present when send_ttl option set in partition_slice
};
class qr_row stub [[writable]] {
std::vector<std::optional<qr_cell>> cells; // ordered as requested in partition_slice
};
class qr_clustered_row stub [[writable]] {
std::optional<clustering_key> key; // present when send_clustering_key option set in partition_slice
qr_row cells; // ordered as requested in partition_slice
};
class qr_partition stub [[writable]] {
std::optional<partition_key> key; // present when send_partition_key option set in partition_slice
qr_row static_row;
std::vector<qr_clustered_row> rows; // ordered by key
};
class query_result stub [[writable]] {
std::vector<qr_partition> partitions; // in ring order
};
enum class digest_algorithm : uint8_t {
none = 0, // digest not required
MD5 = 1,
xxHash = 2,// default algorithm
};
}
<commit_msg>query_idl: Make qr_partition::rows/query_result::partitions chunked<commit_after>namespace query {
class qr_cell stub [[writable]] {
std::optional<api::timestamp_type> timestamp; // present when send_timestamp option set in partition_slice
std::optional<gc_clock::time_point> expiry; // present when send_expiry option set in partition_slice
// Specified by CQL binary protocol, according to cql_serialization_format in read_command.
bytes value;
std::optional<gc_clock::duration> ttl [[version 1.3]]; // present when send_ttl option set in partition_slice
};
class qr_row stub [[writable]] {
std::vector<std::optional<qr_cell>> cells; // ordered as requested in partition_slice
};
class qr_clustered_row stub [[writable]] {
std::optional<clustering_key> key; // present when send_clustering_key option set in partition_slice
qr_row cells; // ordered as requested in partition_slice
};
class qr_partition stub [[writable]] {
std::optional<partition_key> key; // present when send_partition_key option set in partition_slice
qr_row static_row;
utils::chunked_vector<qr_clustered_row> rows; // ordered by key
};
class query_result stub [[writable]] {
utils::chunked_vector<qr_partition> partitions; // in ring order
};
enum class digest_algorithm : uint8_t {
none = 0, // digest not required
MD5 = 1,
xxHash = 2,// default algorithm
};
}
<|endoftext|>
|
<commit_before>/************************************************************************
*
* vapor3D Engine © (2008-2010)
*
* <http://www.vapor3d.org>
*
************************************************************************/
#include "Core/API.h"
#ifndef VAPOR_PLATFORM_WINDOWS
#include "Thread.h"
#include "Log.h"
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
namespace vapor {
//-----------------------------------//
static void* _ThreadMain(void* ptr)
{
Thread* thread = (Thread*)ptr;
thread->threadMain();
return nullptr;
}
//-----------------------------------//
Thread::Thread()
: mRunning(false)
, mThread(0)
, mPriority(ThreadPriority::Normal)
{ }
//-----------------------------------//
Thread::~Thread()
{
assert(!mRunning);
}
//-----------------------------------//
bool Thread::startThread()
{
if (mRunning)
return false;
mRunning = true;
bool result = pthread_create((pthread_t*)&mThread, NULL, &_ThreadMain, this) == 0;
if (result)
setPriority(mPriority);
return result;
}
//-----------------------------------//
void Thread::wait()
{
assert(pthread_join((pthread_t)mThread, NULL) == 0);
mRunning = false;
}
//-----------------------------------//
bool Thread::suspend()
{
assert( false && "Thread::Suspend Not Implemented" );
return false;
}
//-----------------------------------//
bool Thread::resume()
{
assert( false && "Thread::Resume Not Implemented" );
return false;
}
//-----------------------------------//
void Thread::setPriority(ThreadPriority::Enum priority)
{
// Update our internal state
mPriority = priority;
// Propogate to the thread if its running
if ( mRunning )
{
int policy;
sched_param param;
memset(¶m, 0, sizeof(param));
// Get current policy
assert( pthread_getschedparam( (pthread_t)mThread, &policy, ¶m ) == 0 );
// Calculate priority range
int max = sched_get_priority_max( policy );
int min = sched_get_priority_min( policy );
int range = max - min;
int mid = range / 2;
int new_priority = sched_get_priority_min( policy ) + mid + (int)priority;
// Clear parameters
memset(¶m, 0, sizeof(param));
param.sched_priority = new_priority;
// Set new priority
assert( pthread_setschedparam( (pthread_t)mThread, policy, ¶m ) == 0 );
}
}
//-----------------------------------//
bool Thread::isRunning()
{
return mRunning;
}
//-----------------------------------//
uintptr_t Thread::getCurrentThreadID()
{
return (uintptr_t)pthread_self();
}
//-----------------------------------//
void Thread::threadMain()
{
mInvoker->Invoke();
delete mInvoker;
mInvoker = nullptr;
mRunning = false;
}
//-----------------------------------//
} // end namespace
#endif
<commit_msg>Added much improved POSIX thread support.<commit_after>/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "Core/API.h"
#if !defined(PLATFORM_WINDOWS)
#include "Core/Concurrency.h"
#include "Core/Log.h"
#include <pthread.h>
#include <sched.h>
NAMESPACE_CORE_BEGIN
//-----------------------------------//
static void* _ThreadMain(void* ptr)
{
Thread* thread = (Thread*) ptr;
thread->Function(thread, thread->Userdata);
thread->Handle = nullptr;
thread->IsRunning = false;
return nullptr;
}
bool ThreadStart(Thread* thread, ThreadFunction function, void* data)
{
if (!thread || !function || thread->IsRunning)
return false;
thread->Function = function;
thread->Userdata = data;
bool result = pthread_create((pthread_t*)&thread->Handle, /*attr=*/0,
&_ThreadMain, thread) == 0;
if (result)
{
thread->IsRunning = true;
ThreadResume(thread);
}
return result;
}
bool ThreadJoin(Thread* thread)
{
int res = pthread_join((pthread_t)thread->Handle, 0);
assert(res == 0);
thread->IsRunning = false;
return res == 0;
}
bool ThreadPause(Thread* thread)
{
assert(false && "ThreadPause not implemented");
return false;
}
bool ThreadResume(Thread* thread)
{
assert(false && "ThreadResume not implemented");
return false;
}
bool ThreadSetPriority(Thread* thread, ThreadPriority priority)
{
// Update our internal state
thread->Priority = priority;
int res = pthread_setschedprio((pthread_t)thread->Handle, (int) priority);
return res == 0;
#if 0
// Propogate to the thread if its running
if (thread->IsRunning)
{
int policy;
sched_param param;
memset(¶m, 0, sizeof(param));
// Get current policy
assert( pthread_getschedparam( (pthread_t)thread->Handle, &policy, ¶m ) == 0 );
// Calculate priority range
int max = sched_get_priority_max(policy);
int min = sched_get_priority_min(policy);
int range = max - min;
int mid = range / 2;
int new_priority = sched_get_priority_min(policy) + mid + (int)priority;
// Clear parameters
memset(¶m, 0, sizeof(param));
param.sched_priority = new_priority;
// Set new priority
int res = pthread_setschedparam((pthread_t)thread->Handle, policy, ¶m);
assert(res == 0);
}
#endif
}
void ThreadSetName(Thread*, const char* name)
{
// TODO:
//prctl(PR_SET_NAME);
}
//-----------------------------------//
struct Mutex
{
pthread_mutex_t Handle;
};
Mutex* MutexCreate(Allocator* alloc)
{
Mutex* mutex = Allocate(alloc, Mutex);
MutexInit(mutex);
return mutex;
}
void MutexInit(Mutex* mutex)
{
if (!mutex) return;
int res = pthread_mutex_init(&mutex->Handle, /*attr=*/0);
assert((res == 0) && "Could not initialize critical section");
}
void MutexDestroy(Mutex* mutex)
{
if (!mutex) return;
int res = pthread_mutex_destroy(&mutex->Handle);
assert((res == 0) && "Could not destroy critical section");
Deallocate(mutex);
}
void MutexLock(Mutex* mutex)
{
int res = pthread_mutex_lock(&mutex->Handle);
assert((res == 0) && "Could not lock critical section");
}
void MutexUnlock(Mutex* mutex)
{
int res = pthread_mutex_lock(&mutex->Handle);
assert((res == 0) && "Could not unlock critical section");
}
//-----------------------------------//
struct Condition
{
pthread_cond_t Handle;
};
Condition* ConditionCreate(Allocator* alloc)
{
Condition* cond = Allocate(alloc, Condition);
ConditionInit(cond);
return cond;
}
void ConditionDestroy(Condition* cond)
{
int res = pthread_cond_destroy(&cond->Handle);
assert((res == 0) && "Could not destroy condition variable");
Deallocate(cond);
}
void ConditionInit(Condition* cond)
{
int res = pthread_cond_init(&cond->Handle, /*cond_attr=*/0);
assert((res == 0) && "Could not destroy condition variable");
}
void ConditionWait(Condition* cond, Mutex* mutex)
{
int res = pthread_cond_wait(&cond->Handle, &mutex->Handle);
assert((res == 0) && "Could not wait on condition variable");
}
void ConditionWakeOne(Condition* cond)
{
int res = pthread_cond_signal(&cond->Handle);
assert((res == 0) && "Could not signal condition variable");
}
void ConditionWakeAll(Condition* cond)
{
int res = pthread_cond_broadcast(&cond->Handle);
assert((res == 0) && "Could not broadcast condition variable");
}
//-----------------------------------//
int32 AtomicRead(volatile Atomic* atomic)
{
return __sync_add_and_fetch(atomic, 0);
}
int32 AtomicWrite(volatile Atomic* atomic, int32 value)
{
return __sync_lock_test_and_set(atomic, value);
}
int32 AtomicAdd(volatile Atomic* atomic, int32 value)
{
return __sync_add_and_fetch(atomic, value);
}
int32 AtomicIncrement(volatile Atomic* atomic)
{
return __sync_add_and_fetch(atomic, 1);
}
int32 AtomicDecrement(volatile Atomic* atomic)
{
return __sync_sub_and_fetch(atomic, 1);
}
//-----------------------------------//
NAMESPACE_CORE_END
#endif<|endoftext|>
|
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "sk_tool_utils.h"
// Hue, Saturation, Color, and Luminosity blend modes are oddballs.
// They nominally convert their inputs to unpremul, then to HSL, then
// mix-and-match H,S,and L from Src and Dst, then convert back, then premul.
//
// In practice that's slow, so instead we pick the color with the correct
// Hue, and then (approximately) apply the other's Saturation and/or Luminosity.
// This isn't just an optimization... it's how the modes are specified.
//
// Each mode's name describes the Src H,S,L components to keep, taking the
// others from Dst, where Color == Hue + Saturation. Color and Luminosity
// are each other's complements; Hue and Saturation have no complement.
//
// All these modes were originally designed to operate on gamma-encoded values,
// and that's what everyone's used to seeing. It's unclear wehther they make
// any sense in a gamma-correct world. They certainly won't look at all similar.
//
// We have had many inconsistent implementations of these modes.
// This GM tries to demonstrate unambigously how they should work.
//
// To go along with our inconsistent implementations, there are two slightly
// inconsistent specifications of how to perform these blends,
// web: https://www.w3.org/TR/compositing-1/#blendingnonseparable
// KHR: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_blend_equation_advanced.txt
// It looks like these are meant to be identical, but they disagree on at least ClipColor().
// I think the KHR version is just wrong... it produces values >1.
//
// We'll draw reference colors according to both specs, testing colors where they differ.
static float min(float r, float g, float b) { return SkTMin(r, SkTMin(g, b)); }
static float max(float r, float g, float b) { return SkTMax(r, SkTMax(g, b)); }
static float sat(float r, float g, float b) { return max(r,g,b) - min(r,g,b); }
static float lum(float r, float g, float b) { return r*0.30f + g*0.59f + b*0.11f; }
// The two SetSat() routines in the specs look different, but they're logically equivalent.
// Both map the minimum channel to 0, maximum to s, and scale the middle proportionately.
// The KHR version has done a better job at simplifying its math, so we use it here.
static void set_sat(float* r, float* g, float* b, float s) {
auto channel = [&](float c) {
float mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
return mx == mn ? 0
: (c - mn) * s / (mx - mn);
};
*r = channel(*r);
*g = channel(*g);
*b = channel(*b);
}
static void set_lum(float* r, float* g, float* b, float l) {
float diff = l - lum(*r,*g,*b);
*r += diff;
*g += diff;
*b += diff;
// We do clip_color() here as specified, just moved from set_lum() to blend().
}
static void clip_color_web(float* r, float* g, float* b) {
auto clip = [&](float c) {
float l = lum(*r,*g,*b),
mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
if (mn < 0) { c = l + (c - l) * ( l) / (l - mn); }
if (mx > 1) { c = l + (c - l) * (1 - l) / (mx - l); } // <--- notice "1-l"
//SkASSERT(0 <= c); // This may end up very slightly negative...
SkASSERT(c <= 1);
return c;
};
*r = clip(*r);
*g = clip(*g);
*b = clip(*b);
}
static void clip_color_KHR(float* r, float* g, float* b) {
auto clip = [&](float c) {
float l = lum(*r,*g,*b),
mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
if (mn < 0) { c = l + (c - l) * l / (l - mn); }
if (mx > 1) { c = l + (c - l) * l / (mx - l); } // <--- notice "l"
//SkASSERT(0 <= c); // This may end up very slightly negative...
//SkASSERT(c <= 1); // I think the mx > 1 logic is incorrect...
return c;
};
*r = clip(*r);
*g = clip(*g);
*b = clip(*b);
}
static void hue(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Hue of Src, Saturation and Luminosity of Dst.
float R = *sr,
G = *sg,
B = *sb;
set_sat(&R,&G,&B, sat(dr,dg,db));
set_lum(&R,&G,&B, lum(dr,dg,db));
*sr = R;
*sg = G;
*sb = B;
}
static void saturation(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Saturation of Src, Hue and Luminosity of Dst
float R = dr,
G = dg,
B = db;
set_sat(&R,&G,&B, sat(*sr,*sg,*sb));
set_lum(&R,&G,&B, lum( dr, dg, db)); // This may seem redundant. TODO: is it?
*sr = R;
*sg = G;
*sb = B;
}
static void color(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Hue and Saturation of Src, Luminosity of Dst.
float R = *sr,
G = *sg,
B = *sb;
set_lum(&R,&G,&B, lum(dr,dg,db));
*sr = R;
*sg = G;
*sb = B;
}
static void luminosity(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Luminosity of Src, Hue and Saturation of Dst.
float R = dr,
G = dg,
B = db;
set_lum(&R,&G,&B, lum(*sr,*sg,*sb));
*sr = R;
*sg = G;
*sb = B;
}
static SkColor blend(SkColor dst, SkColor src,
void (*mode)(float,float,float, float*,float*,float*),
void (*clip_color)(float*,float*,float*),
bool legacy) {
SkASSERT(SkColorGetA(dst) == 0xff
&& SkColorGetA(src) == 0xff); // Not fundamental, just simplifying for this GM.
auto to_float = [&](SkColor c) {
if (legacy) {
return SkColor4f{
SkColorGetR(c) * (1/255.0f),
SkColorGetG(c) * (1/255.0f),
SkColorGetB(c) * (1/255.0f),
1.0f,
};
}
return SkColor4f::FromColor(c);
};
SkColor4f d = to_float(dst),
s = to_float(src);
mode( d.fR, d.fG, d.fB,
&s.fR, &s.fG, &s.fB);
clip_color(&s.fR, &s.fG, &s.fB);
if (legacy) {
// We need to be a little careful here to show off clip_color_KHR()'s overflow
// while avoiding SkASSERTs inside SkColorSetRGB().
return SkColorSetRGB((int)(s.fR * 255.0f + 0.5f) & 0xff,
(int)(s.fG * 255.0f + 0.5f) & 0xff,
(int)(s.fB * 255.0f + 0.5f) & 0xff);
}
return s.toSkColor();
}
DEF_SIMPLE_GM(hsl, canvas, 600, 100) {
SkPaint label;
sk_tool_utils::set_portable_typeface(&label);
label.setAntiAlias(true);
const char* comment = "HSL blend modes are correct when you see no circles in the squares. "
"2 circles means the standards disagree.";
canvas->drawText(comment, strlen(comment), 10,10, label);
// Just to keep things reaaaal simple, we'll only use opaque colors.
SkPaint bg, fg;
bg.setColor(0xff00ff00); // Fully-saturated bright green, H = 120°, S = 100%, L = 50%.
fg.setColor(0xff7f3f7f); // Partly-saturated dim magenta, H = 300°, S = ~33%, L = ~37%.
struct {
SkBlendMode mode;
void (*reference)(float,float,float, float*,float*,float*);
} tests[] = {
{ SkBlendMode::kSrc, nullptr },
{ SkBlendMode::kDst, nullptr },
{ SkBlendMode::kHue, hue },
{ SkBlendMode::kSaturation, saturation },
{ SkBlendMode::kColor, color },
{ SkBlendMode::kLuminosity, luminosity },
};
bool legacy = !canvas->imageInfo().colorSpace();
for (auto test : tests) {
canvas->drawRect({20,20,80,80}, bg);
fg.setBlendMode(test.mode);
canvas->drawRect({20,20,80,80}, fg);
if (test.reference) {
SkPaint web,KHR;
auto dst = bg.getColor(),
src = fg.getColor();
web.setColor(blend(dst, src, test.reference, clip_color_web, legacy));
KHR.setColor(blend(dst, src, test.reference, clip_color_KHR, legacy));
canvas->drawCircle(50,50, 20, web);
canvas->drawCircle(50,50, 10, KHR); // This circle may be very wrong.
}
const char* name = SkBlendMode_Name(test.mode);
canvas->drawText(name, strlen(name), 20,90, label);
canvas->translate(100,0);
}
}
<commit_msg>bug fix in hsl GM reference impls<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "sk_tool_utils.h"
// Hue, Saturation, Color, and Luminosity blend modes are oddballs.
// They nominally convert their inputs to unpremul, then to HSL, then
// mix-and-match H,S,and L from Src and Dst, then convert back, then premul.
//
// In practice that's slow, so instead we pick the color with the correct
// Hue, and then (approximately) apply the other's Saturation and/or Luminosity.
// This isn't just an optimization... it's how the modes are specified.
//
// Each mode's name describes the Src H,S,L components to keep, taking the
// others from Dst, where Color == Hue + Saturation. Color and Luminosity
// are each other's complements; Hue and Saturation have no complement.
//
// All these modes were originally designed to operate on gamma-encoded values,
// and that's what everyone's used to seeing. It's unclear wehther they make
// any sense in a gamma-correct world. They certainly won't look at all similar.
//
// We have had many inconsistent implementations of these modes.
// This GM tries to demonstrate unambigously how they should work.
//
// To go along with our inconsistent implementations, there are two slightly
// inconsistent specifications of how to perform these blends,
// web: https://www.w3.org/TR/compositing-1/#blendingnonseparable
// KHR: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_blend_equation_advanced.txt
// It looks like these are meant to be identical, but they disagree on at least ClipColor().
// I think the KHR version is just wrong... it produces values >1.
//
// We'll draw reference colors according to both specs, testing colors where they differ.
static float min(float r, float g, float b) { return SkTMin(r, SkTMin(g, b)); }
static float max(float r, float g, float b) { return SkTMax(r, SkTMax(g, b)); }
static float sat(float r, float g, float b) { return max(r,g,b) - min(r,g,b); }
static float lum(float r, float g, float b) { return r*0.30f + g*0.59f + b*0.11f; }
// The two SetSat() routines in the specs look different, but they're logically equivalent.
// Both map the minimum channel to 0, maximum to s, and scale the middle proportionately.
// The KHR version has done a better job at simplifying its math, so we use it here.
static void set_sat(float* r, float* g, float* b, float s) {
float mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
auto channel = [=](float c) {
return mx == mn ? 0
: (c - mn) * s / (mx - mn);
};
*r = channel(*r);
*g = channel(*g);
*b = channel(*b);
}
static void set_lum(float* r, float* g, float* b, float l) {
float diff = l - lum(*r,*g,*b);
*r += diff;
*g += diff;
*b += diff;
// We do clip_color() here as specified, just moved from set_lum() to blend().
}
static void clip_color_web(float* r, float* g, float* b) {
float l = lum(*r,*g,*b),
mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
auto clip = [=](float c) {
if (mn < 0) { c = l + (c - l) * ( l) / (l - mn); }
if (mx > 1) { c = l + (c - l) * (1 - l) / (mx - l); } // <--- notice "1-l"
//SkASSERT(0 <= c); // This may end up very slightly negative...
SkASSERT(c <= 1);
return c;
};
*r = clip(*r);
*g = clip(*g);
*b = clip(*b);
}
static void clip_color_KHR(float* r, float* g, float* b) {
float l = lum(*r,*g,*b),
mn = min(*r,*g,*b),
mx = max(*r,*g,*b);
auto clip = [=](float c) {
if (mn < 0) { c = l + (c - l) * l / (l - mn); }
if (mx > 1) { c = l + (c - l) * l / (mx - l); } // <--- notice "l"
//SkASSERT(0 <= c); // This may end up very slightly negative...
//SkASSERT(c <= 1); // I think the mx > 1 logic is incorrect...
return c;
};
*r = clip(*r);
*g = clip(*g);
*b = clip(*b);
}
static void hue(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Hue of Src, Saturation and Luminosity of Dst.
float R = *sr,
G = *sg,
B = *sb;
set_sat(&R,&G,&B, sat(dr,dg,db));
set_lum(&R,&G,&B, lum(dr,dg,db));
*sr = R;
*sg = G;
*sb = B;
}
static void saturation(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Saturation of Src, Hue and Luminosity of Dst
float R = dr,
G = dg,
B = db;
set_sat(&R,&G,&B, sat(*sr,*sg,*sb));
set_lum(&R,&G,&B, lum( dr, dg, db)); // This may seem redundant. TODO: is it?
*sr = R;
*sg = G;
*sb = B;
}
static void color(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Hue and Saturation of Src, Luminosity of Dst.
float R = *sr,
G = *sg,
B = *sb;
set_lum(&R,&G,&B, lum(dr,dg,db));
*sr = R;
*sg = G;
*sb = B;
}
static void luminosity(float dr, float dg, float db,
float* sr, float* sg, float* sb) {
// Luminosity of Src, Hue and Saturation of Dst.
float R = dr,
G = dg,
B = db;
set_lum(&R,&G,&B, lum(*sr,*sg,*sb));
*sr = R;
*sg = G;
*sb = B;
}
static SkColor blend(SkColor dst, SkColor src,
void (*mode)(float,float,float, float*,float*,float*),
void (*clip_color)(float*,float*,float*),
bool legacy) {
SkASSERT(SkColorGetA(dst) == 0xff
&& SkColorGetA(src) == 0xff); // Not fundamental, just simplifying for this GM.
auto to_float = [&](SkColor c) {
if (legacy) {
return SkColor4f{
SkColorGetR(c) * (1/255.0f),
SkColorGetG(c) * (1/255.0f),
SkColorGetB(c) * (1/255.0f),
1.0f,
};
}
return SkColor4f::FromColor(c);
};
SkColor4f d = to_float(dst),
s = to_float(src);
mode( d.fR, d.fG, d.fB,
&s.fR, &s.fG, &s.fB);
clip_color(&s.fR, &s.fG, &s.fB);
if (legacy) {
// We need to be a little careful here to show off clip_color_KHR()'s overflow
// while avoiding SkASSERTs inside SkColorSetRGB().
return SkColorSetRGB((int)(s.fR * 255.0f + 0.5f) & 0xff,
(int)(s.fG * 255.0f + 0.5f) & 0xff,
(int)(s.fB * 255.0f + 0.5f) & 0xff);
}
return s.toSkColor();
}
DEF_SIMPLE_GM(hsl, canvas, 600, 100) {
SkPaint label;
sk_tool_utils::set_portable_typeface(&label);
label.setAntiAlias(true);
const char* comment = "HSL blend modes are correct when you see no circles in the squares. "
"2 circles means the standards disagree.";
canvas->drawText(comment, strlen(comment), 10,10, label);
// Just to keep things reaaaal simple, we'll only use opaque colors.
SkPaint bg, fg;
bg.setColor(0xff00ff00); // Fully-saturated bright green, H = 120°, S = 100%, L = 50%.
fg.setColor(0xff7f3f7f); // Partly-saturated dim magenta, H = 300°, S = ~33%, L = ~37%.
struct {
SkBlendMode mode;
void (*reference)(float,float,float, float*,float*,float*);
} tests[] = {
{ SkBlendMode::kSrc, nullptr },
{ SkBlendMode::kDst, nullptr },
{ SkBlendMode::kHue, hue },
{ SkBlendMode::kSaturation, saturation },
{ SkBlendMode::kColor, color },
{ SkBlendMode::kLuminosity, luminosity },
};
bool legacy = !canvas->imageInfo().colorSpace();
for (auto test : tests) {
canvas->drawRect({20,20,80,80}, bg);
fg.setBlendMode(test.mode);
canvas->drawRect({20,20,80,80}, fg);
if (test.reference) {
SkPaint web,KHR;
auto dst = bg.getColor(),
src = fg.getColor();
web.setColor(blend(dst, src, test.reference, clip_color_web, legacy));
KHR.setColor(blend(dst, src, test.reference, clip_color_KHR, legacy));
canvas->drawCircle(50,50, 20, web);
canvas->drawCircle(50,50, 10, KHR); // This circle may be very wrong.
}
const char* name = SkBlendMode_Name(test.mode);
canvas->drawText(name, strlen(name), 20,90, label);
canvas->translate(100,0);
}
}
<|endoftext|>
|
<commit_before>#include "feature_styler.hpp"
#include "geometry_processors.hpp"
#include "proto_to_styles.hpp"
#include "../indexer/drawing_rules.hpp"
#include "../indexer/feature.hpp"
#include "../indexer/feature_visibility.hpp"
#ifdef OMIM_PRODUCTION
#include "../indexer/drules_struct_lite.pb.h"
#else
#include "../indexer/drules_struct.pb.h"
#endif
#include "../geometry/screenbase.hpp"
#include "../graphics/glyph_cache.hpp"
#include "../base/stl_add.hpp"
#include "../std/iterator_facade.hpp"
namespace
{
struct less_depth
{
bool operator() (di::DrawRule const & r1, di::DrawRule const & r2) const
{
return (r1.m_depth < r2.m_depth);
}
};
}
namespace di
{
uint32_t DrawRule::GetID(size_t threadSlot) const
{
return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot));
}
void DrawRule::SetID(size_t threadSlot, uint32_t id) const
{
m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id);
}
FeatureStyler::FeatureStyler(FeatureType const & f,
int const zoom,
double const visualScale,
graphics::GlyphCache * glyphCache,
ScreenBase const * convertor,
m2::RectD const * rect)
: m_hasPathText(false),
m_visualScale(visualScale),
m_glyphCache(glyphCache),
m_convertor(convertor),
m_rect(rect)
{
vector<drule::Key> keys;
string names; // for debug use only, in release it's empty
pair<int, bool> type = feature::GetDrawRule(f, zoom, keys, names);
// don't try to do anything to invisible feature
if (keys.empty())
return;
m_hasLineStyles = false;
m_geometryType = type.first;
m_isCoastline = type.second;
f.GetPreferredNames(m_primaryText, m_secondaryText);
// Get house number if feature has one.
string houseNumber = f.GetHouseNumber();
if (!houseNumber.empty())
{
if (m_primaryText.empty())
houseNumber.swap(m_primaryText);
else
m_primaryText = m_primaryText + " (" + houseNumber + ")";
}
m_refText = f.GetRoadNumber();
double const population = static_cast<double>(f.GetPopulation());
if (population == 1)
m_popRank = 0.0;
else
{
double const upperBound = 3.0E6;
m_popRank = min(upperBound, population) / upperBound / 4;
}
// low zoom heuristics
if (zoom <= 5)
{
// hide superlong names on low zoom
if (m_primaryText.size() > 50)
m_primaryText.clear();
}
double area = 0.0;
if (m_geometryType != feature::GEOM_POINT)
{
m2::RectD const bbox = f.GetLimitRect(zoom);
area = bbox.SizeX() * bbox.SizeY();
}
double priorityModifier;
if (area != 0)
priorityModifier = min(1., area*10000.); // making area larger so it's not lost on double conversions
else
priorityModifier = static_cast<double>(population) / 7E9; // dividing by planet population to get priorityModifier < 1
drule::MakeUnique(keys);
int layer = f.GetLayer();
bool isTransparent = false;
if (layer == feature::LAYER_TRANSPARENT_TUNNEL)
layer = 0;
bool hasIcon = false;
bool hasCaptionWithoutOffset = false;
m_fontSize = 0;
size_t const count = keys.size();
m_rules.resize(count);
for (size_t i = 0; i < count; ++i)
{
double depth = keys[i].m_priority;
if ((layer != 0) && (depth < 19000))
depth = (layer * drule::layer_base_priority) + fmod(depth, drule::layer_base_priority);
if (keys[i].m_type == drule::symbol)
hasIcon = true;
if ((keys[i].m_type == drule::caption)
|| (keys[i].m_type == drule::symbol)
|| (keys[i].m_type == drule::circle)
|| (keys[i].m_type == drule::pathtext)
|| (keys[i].m_type == drule::waymarker))
{
// show labels of larger objects first
depth += priorityModifier;
}
else if (keys[i].m_type == drule::area)
{
// show smaller polygons on top
depth -= priorityModifier;
}
if (!m_hasLineStyles && (keys[i].m_type == drule::line))
m_hasLineStyles = true;
m_rules[i] = di::DrawRule( drule::rules().Find(keys[i]), depth, isTransparent);
if ((m_geometryType == feature::GEOM_LINE) && !m_hasPathText && !m_primaryText.empty())
if (m_rules[i].m_rule->GetCaption(0) != 0)
{
m_hasPathText = true;
if (!FilterTextSize(m_rules[i].m_rule))
m_fontSize = max(m_fontSize, GetTextFontSize(m_rules[i].m_rule));
}
if (keys[i].m_type == drule::caption)
if (m_rules[i].m_rule->GetCaption(0) != 0)
hasCaptionWithoutOffset = !m_rules[i].m_rule->GetCaption(0)->has_offset_y();
}
// placing a text on the path
if (m_hasPathText && (m_fontSize != 0))
{
typedef gp::filter_screenpts_adapter<gp::get_path_intervals> functor_t;
functor_t::params p;
p.m_convertor = m_convertor;
p.m_rect = m_rect;
p.m_intervals = &m_intervals;
functor_t fun(p);
f.ForEachPointRef(fun, zoom);
LayoutTexts(fun.m_length);
}
if (hasIcon && hasCaptionWithoutOffset)
// we need to delete symbol style (single one due to MakeUnique call above)
for (size_t i = 0; i < count; ++i)
{
if (keys[i].m_type == drule::symbol)
{
m_rules[i] = m_rules[m_rules.size() - 1];
m_rules.pop_back();
break;
}
}
sort(m_rules.begin(), m_rules.end(), less_depth());
}
typedef pair<double, double> RangeT;
template <class IterT> class RangeIterT :
public iterator_facade<RangeIterT<IterT>, RangeT, forward_traversal_tag, RangeT>
{
IterT m_iter;
public:
RangeIterT(IterT iter) : m_iter(iter) {}
RangeT dereference() const
{
IterT next = m_iter;
++next;
return RangeT(*m_iter, *next);
}
bool equal(RangeIterT const & r) const { return (m_iter == r.m_iter); }
void increment()
{
++m_iter; ++m_iter;
}
};
template <class ContT> class RangeInserter
{
ContT & m_cont;
public:
RangeInserter(ContT & cont) : m_cont(cont) {}
RangeInserter & operator*() { return *this; }
RangeInserter & operator++(int) { return *this; }
RangeInserter & operator=(RangeT const & r)
{
m_cont.push_back(r.first);
m_cont.push_back(r.second);
return *this;
}
};
void FeatureStyler::LayoutTexts(double pathLength)
{
double const textLength = m_glyphCache->getTextLength(m_fontSize, GetPathName());
/// @todo Choose best constant for minimal space.
double const emptySize = max(200 * m_visualScale, textLength);
// multiply on factor because tiles will be rendered in smaller scales
double const minPeriodSize = 1.5 * (emptySize + textLength);
size_t textCnt = 0;
double firstTextOffset = 0;
if (pathLength > textLength)
{
textCnt = ceil((pathLength - textLength) / minPeriodSize);
firstTextOffset = 0.5 * (pathLength - (textCnt * textLength + (textCnt - 1) * emptySize));
}
if (textCnt != 0 && !m_intervals.empty())
{
buffer_vector<RangeT, 8> deadZones;
for (size_t i = 0; i < textCnt; ++i)
{
double const deadZoneStart = firstTextOffset + minPeriodSize * i;
double const deadZoneEnd = deadZoneStart + textLength;
if (deadZoneStart > m_intervals.back())
break;
deadZones.push_back(make_pair(deadZoneStart, deadZoneEnd));
}
if (!deadZones.empty())
{
buffer_vector<double, 16> res;
// accumulate text layout intervals with cliping intervals
typedef RangeIterT<ClipIntervalsT::iterator> IterT;
AccumulateIntervals1With2(IterT(m_intervals.begin()), IterT(m_intervals.end()),
deadZones.begin(), deadZones.end(),
RangeInserter<ClipIntervalsT>(res));
m_intervals = res;
ASSERT_EQUAL(m_intervals.size() % 2, 0, ());
// get final text offsets (belongs to final clipping intervals)
size_t i = 0;
size_t j = 0;
while (i != deadZones.size() && j != m_intervals.size())
{
ASSERT_LESS(deadZones[i].first, deadZones[i].second, ());
ASSERT_LESS(m_intervals[j], m_intervals[j+1], ());
if (deadZones[i].first < m_intervals[j])
{
++i;
continue;
}
if (m_intervals[j+1] <= deadZones[i].first)
{
j += 2;
continue;
}
ASSERT_LESS_OR_EQUAL(m_intervals[j], deadZones[i].first, ());
ASSERT_LESS_OR_EQUAL(deadZones[i].second, m_intervals[j+1], ());
m_offsets.push_back(deadZones[i].first);
++i;
}
}
}
}
string const FeatureStyler::GetPathName() const
{
if (m_secondaryText.empty())
return m_primaryText;
else
return m_primaryText + " " + m_secondaryText;
}
bool FeatureStyler::IsEmpty() const
{
return m_rules.empty();
}
uint8_t FeatureStyler::GetTextFontSize(drule::BaseRule const * pRule) const
{
return pRule->GetCaption(0)->height() * m_visualScale;
}
bool FeatureStyler::FilterTextSize(drule::BaseRule const * pRule) const
{
if (pRule->GetCaption(0))
return (GetFontSize(pRule->GetCaption(0)) < 3);
else
{
// this rule is not a caption at all
return true;
}
}
}
<commit_msg>[map] remove repeated labels from house numbers, disabled layer= for overlayElements<commit_after>#include "feature_styler.hpp"
#include "geometry_processors.hpp"
#include "proto_to_styles.hpp"
#include "../indexer/drawing_rules.hpp"
#include "../indexer/feature.hpp"
#include "../indexer/feature_visibility.hpp"
#ifdef OMIM_PRODUCTION
#include "../indexer/drules_struct_lite.pb.h"
#else
#include "../indexer/drules_struct.pb.h"
#endif
#include "../geometry/screenbase.hpp"
#include "../graphics/glyph_cache.hpp"
#include "../base/stl_add.hpp"
#include "../std/iterator_facade.hpp"
namespace
{
struct less_depth
{
bool operator() (di::DrawRule const & r1, di::DrawRule const & r2) const
{
return (r1.m_depth < r2.m_depth);
}
};
}
namespace di
{
uint32_t DrawRule::GetID(size_t threadSlot) const
{
return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot));
}
void DrawRule::SetID(size_t threadSlot, uint32_t id) const
{
m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id);
}
FeatureStyler::FeatureStyler(FeatureType const & f,
int const zoom,
double const visualScale,
graphics::GlyphCache * glyphCache,
ScreenBase const * convertor,
m2::RectD const * rect)
: m_hasPathText(false),
m_visualScale(visualScale),
m_glyphCache(glyphCache),
m_convertor(convertor),
m_rect(rect)
{
vector<drule::Key> keys;
string names; // for debug use only, in release it's empty
pair<int, bool> type = feature::GetDrawRule(f, zoom, keys, names);
// don't try to do anything to invisible feature
if (keys.empty())
return;
m_hasLineStyles = false;
m_geometryType = type.first;
m_isCoastline = type.second;
f.GetPreferredNames(m_primaryText, m_secondaryText);
// Get house number if feature has one.
string houseNumber = f.GetHouseNumber();
if (!houseNumber.empty())
{
if (m_primaryText.empty() || houseNumber.find(m_primaryText) != string::npos)
houseNumber.swap(m_primaryText);
else
m_primaryText = m_primaryText + " (" + houseNumber + ")";
}
m_refText = f.GetRoadNumber();
double const population = static_cast<double>(f.GetPopulation());
if (population == 1)
m_popRank = 0.0;
else
{
double const upperBound = 3.0E6;
m_popRank = min(upperBound, population) / upperBound / 4;
}
// low zoom heuristics
if (zoom <= 5)
{
// hide superlong names on low zoom
if (m_primaryText.size() > 50)
m_primaryText.clear();
}
double area = 0.0;
if (m_geometryType != feature::GEOM_POINT)
{
m2::RectD const bbox = f.GetLimitRect(zoom);
area = bbox.SizeX() * bbox.SizeY();
}
double priorityModifier;
if (area != 0)
priorityModifier = min(1., area*10000.); // making area larger so it's not lost on double conversions
else
priorityModifier = static_cast<double>(population) / 7E9; // dividing by planet population to get priorityModifier < 1
drule::MakeUnique(keys);
int layer = f.GetLayer();
bool isTransparent = false;
if (layer == feature::LAYER_TRANSPARENT_TUNNEL)
layer = 0;
bool hasIcon = false;
bool hasCaptionWithoutOffset = false;
m_fontSize = 0;
size_t const count = keys.size();
m_rules.resize(count);
for (size_t i = 0; i < count; ++i)
{
double depth = keys[i].m_priority;
if ((layer != 0) && (depth < 19000)
&& ((keys[i].m_type == drule::area)
|| (keys[i].m_type == drule::line)
|| (keys[i].m_type == drule::waymarker)))
depth = (layer * drule::layer_base_priority) + fmod(depth, drule::layer_base_priority);
if (keys[i].m_type == drule::symbol)
hasIcon = true;
if ((keys[i].m_type == drule::caption)
|| (keys[i].m_type == drule::symbol)
|| (keys[i].m_type == drule::circle)
|| (keys[i].m_type == drule::pathtext))
{
// show labels of larger objects first
depth += priorityModifier;
}
else if (keys[i].m_type == drule::area)
{
// show smaller polygons on top
depth -= priorityModifier;
}
if (!m_hasLineStyles && (keys[i].m_type == drule::line))
m_hasLineStyles = true;
m_rules[i] = di::DrawRule( drule::rules().Find(keys[i]), depth, isTransparent);
if ((m_geometryType == feature::GEOM_LINE) && !m_hasPathText && !m_primaryText.empty())
if (m_rules[i].m_rule->GetCaption(0) != 0)
{
m_hasPathText = true;
if (!FilterTextSize(m_rules[i].m_rule))
m_fontSize = max(m_fontSize, GetTextFontSize(m_rules[i].m_rule));
}
if (keys[i].m_type == drule::caption)
if (m_rules[i].m_rule->GetCaption(0) != 0)
hasCaptionWithoutOffset = !m_rules[i].m_rule->GetCaption(0)->has_offset_y();
}
// placing a text on the path
if (m_hasPathText && (m_fontSize != 0))
{
typedef gp::filter_screenpts_adapter<gp::get_path_intervals> functor_t;
functor_t::params p;
p.m_convertor = m_convertor;
p.m_rect = m_rect;
p.m_intervals = &m_intervals;
functor_t fun(p);
f.ForEachPointRef(fun, zoom);
LayoutTexts(fun.m_length);
}
if (hasIcon && hasCaptionWithoutOffset)
// we need to delete symbol style (single one due to MakeUnique call above)
for (size_t i = 0; i < count; ++i)
{
if (keys[i].m_type == drule::symbol)
{
m_rules[i] = m_rules[m_rules.size() - 1];
m_rules.pop_back();
break;
}
}
sort(m_rules.begin(), m_rules.end(), less_depth());
}
typedef pair<double, double> RangeT;
template <class IterT> class RangeIterT :
public iterator_facade<RangeIterT<IterT>, RangeT, forward_traversal_tag, RangeT>
{
IterT m_iter;
public:
RangeIterT(IterT iter) : m_iter(iter) {}
RangeT dereference() const
{
IterT next = m_iter;
++next;
return RangeT(*m_iter, *next);
}
bool equal(RangeIterT const & r) const { return (m_iter == r.m_iter); }
void increment()
{
++m_iter; ++m_iter;
}
};
template <class ContT> class RangeInserter
{
ContT & m_cont;
public:
RangeInserter(ContT & cont) : m_cont(cont) {}
RangeInserter & operator*() { return *this; }
RangeInserter & operator++(int) { return *this; }
RangeInserter & operator=(RangeT const & r)
{
m_cont.push_back(r.first);
m_cont.push_back(r.second);
return *this;
}
};
void FeatureStyler::LayoutTexts(double pathLength)
{
double const textLength = m_glyphCache->getTextLength(m_fontSize, GetPathName());
/// @todo Choose best constant for minimal space.
double const emptySize = max(200 * m_visualScale, textLength);
// multiply on factor because tiles will be rendered in smaller scales
double const minPeriodSize = 1.5 * (emptySize + textLength);
size_t textCnt = 0;
double firstTextOffset = 0;
if (pathLength > textLength)
{
textCnt = ceil((pathLength - textLength) / minPeriodSize);
firstTextOffset = 0.5 * (pathLength - (textCnt * textLength + (textCnt - 1) * emptySize));
}
if (textCnt != 0 && !m_intervals.empty())
{
buffer_vector<RangeT, 8> deadZones;
for (size_t i = 0; i < textCnt; ++i)
{
double const deadZoneStart = firstTextOffset + minPeriodSize * i;
double const deadZoneEnd = deadZoneStart + textLength;
if (deadZoneStart > m_intervals.back())
break;
deadZones.push_back(make_pair(deadZoneStart, deadZoneEnd));
}
if (!deadZones.empty())
{
buffer_vector<double, 16> res;
// accumulate text layout intervals with cliping intervals
typedef RangeIterT<ClipIntervalsT::iterator> IterT;
AccumulateIntervals1With2(IterT(m_intervals.begin()), IterT(m_intervals.end()),
deadZones.begin(), deadZones.end(),
RangeInserter<ClipIntervalsT>(res));
m_intervals = res;
ASSERT_EQUAL(m_intervals.size() % 2, 0, ());
// get final text offsets (belongs to final clipping intervals)
size_t i = 0;
size_t j = 0;
while (i != deadZones.size() && j != m_intervals.size())
{
ASSERT_LESS(deadZones[i].first, deadZones[i].second, ());
ASSERT_LESS(m_intervals[j], m_intervals[j+1], ());
if (deadZones[i].first < m_intervals[j])
{
++i;
continue;
}
if (m_intervals[j+1] <= deadZones[i].first)
{
j += 2;
continue;
}
ASSERT_LESS_OR_EQUAL(m_intervals[j], deadZones[i].first, ());
ASSERT_LESS_OR_EQUAL(deadZones[i].second, m_intervals[j+1], ());
m_offsets.push_back(deadZones[i].first);
++i;
}
}
}
}
string const FeatureStyler::GetPathName() const
{
if (m_secondaryText.empty())
return m_primaryText;
else
return m_primaryText + " " + m_secondaryText;
}
bool FeatureStyler::IsEmpty() const
{
return m_rules.empty();
}
uint8_t FeatureStyler::GetTextFontSize(drule::BaseRule const * pRule) const
{
return pRule->GetCaption(0)->height() * m_visualScale;
}
bool FeatureStyler::FilterTextSize(drule::BaseRule const * pRule) const
{
if (pRule->GetCaption(0))
return (GetFontSize(pRule->GetCaption(0)) < 3);
else
{
// this rule is not a caption at all
return true;
}
}
}
<|endoftext|>
|
<commit_before># include "matrice.h"
Matrice::Matrice(size_t nbl, size_t nbc) : nbl(nbl), nbc(nbc)
{
if(nbc!=0 && nbl!=0)
{
mat=new int* [nbc];
for(size_t i=0; i<nbc; i++)
{
mat[i]=new int [nbl];
for(size_t j=0; j<nbl; j++)
{
mat[i][j]=0;
}
}
}
}
Matrice::~Matrice()
{
for(size_t i=0;i<nbc;i++)
{
delete [] mat[i];
}
delete [] mat;
}
int** Matrice:: getMat()const
{
return mat;
}
size_t Matrice:: getNbc()const
{
return nbc;
}
size_t Matrice:: getNbl()const
{
return nbl;
}
void Matrice::afficheM(std::ostream &os)const
{
for(size_t i=0; i<nbc;i++)
{
os << "\n" << "L|C[" << i << "] : ";
for(size_t j=0;j<nbl;j++)
{
os<<mat[i][j];
}
}
os << std::endl;
}
size_t Matrice::estNoire()
{
int nbrEstNoire =0;
Cell c;
for(size_t i=0;i<nbc;i++)
{
for(size_t j=0;j<nbl;j++)
{
if (c.getVal()==-1){
nbrEstNoire+=1;
}
return nbrEstNoire;
}
}
}
bool Matrice::lignesFinies( Liste &L, Cell& c)
{
for(size_t i=0;i<nbc;i++)
{
for(size_t j=0;j<nbl; j++)
{
if (c.getVal()!=0 && L.somElem()==estNoire()){
return true;
}else
return false;
}
}
}
std::ostream &operator<<(std::ostream &os, Matrice &M)
{
M.afficheM(os);
return os;
}
<commit_msg>petite modif d'affichage prenad en charge les -1 de maniere plus lisible<commit_after># include "matrice.h"
Matrice::Matrice(size_t nbl, size_t nbc) : nbl(nbl), nbc(nbc)
{
if(nbc!=0 && nbl!=0)
{
mat=new int* [nbc];
for(size_t i=0; i<nbc; i++)
{
mat[i]=new int [nbl];
for(size_t j=0; j<nbl; j++)
{
mat[i][j]=0;
}
}
}
}
//donc T[colonnes][lignes]
Matrice::~Matrice()
{
for(size_t i=0;i<nbc;i++)
{
delete [] mat[i];
}
delete [] mat;
}
int** Matrice:: getMat()const
{
return mat;
}
size_t Matrice:: getNbc()const
{
return nbc;
}
size_t Matrice:: getNbl()const
{
return nbl;
}
void Matrice::afficheM(std::ostream &os)const
{
for(size_t i=0; i<nbc;i++)
{
os << "\n" << "L|C[" << i << "] : ";
for(size_t j=0;j<nbl;j++)
{
if(mat[i][j]>=0)
{
os<<" "<<mat[i][j]<<" ";
}
else
{
os<<" "<<mat[i][j]<<" ";
}
}
}
os << std::endl;
}
size_t Matrice::estNoire()
{
int nbrEstNoire =0;
Cell c;
for(size_t i=0;i<nbc;i++)
{
for(size_t j=0;j<nbl;j++)
{
if (c.getVal()==-1){
nbrEstNoire+=1;
}
return nbrEstNoire;
}
}
}
bool Matrice::lignesFinies( Liste &L, Cell& c)
{
for(size_t i=0;i<nbc;i++)
{
for(size_t j=0;j<nbl; j++)
{
if (c.getVal()!=0 && L.somElem()==estNoire()){
return true;
}else
return false;
}
}
}
std::ostream &operator<<(std::ostream &os, Matrice &M)
{
M.afficheM(os);
return os;
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <VBE/system/sdl2/StorageImpl.hpp>
// static
std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) {
// Open in binary mode so Windows doesn't change LF to CRLF,
// which will corrupt binary files such as images.
return std::unique_ptr<std::istream>(new std::ifstream("assets/"+filename, std::ios::binary));
}
<commit_msg>Check that assets are opened properly.<commit_after>#include <fstream>
#include <VBE/system/sdl2/StorageImpl.hpp>
#include <VBE/system/Log.hpp>
// static
std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) {
// Open in binary mode so Windows doesn't change LF to CRLF,
// which will corrupt binary files such as images.
std::ifstream* stream = new std::ifstream("assets/"+filename, std::ios::binary);
VBE_ASSERT(stream->good(), "Could not open asset: "+filename);
return std::unique_ptr<std::istream>(stream);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 [email protected].
*
* 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/>.
*/
#if !defined(XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD)
#define XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD
/**
* $State$
*
* @author Scott Boag ([email protected])
* */
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
// Xalan header files.
#include <XSLT/ProblemListener.hpp>
/**
* The implementation of the default error handling for Xalan.
*/
class XALAN_XSLT_EXPORT ProblemListenerDefault : public ProblemListener
{
public:
ProblemListenerDefault(PrintWriter* pw = 0);
virtual
~ProblemListenerDefault();
// These methods are inherited from ProblemListener ...
virtual void
setPrintWriter(PrintWriter* pw);
virtual void
problem(
eProblemSource where,
eClassification classification,
const XalanNode* sourceNode,
const XalanNode* styleNode,
const XalanDOMString& msg,
const XalanDOMChar* uri,
int lineNo,
int charOffset);
private:
PrintWriter* m_pw;
};
#endif // XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD
<commit_msg>Added accessor.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 [email protected].
*
* 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/>.
*/
#if !defined(XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD)
#define XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD
/**
* $State$
*
* @author Scott Boag ([email protected])
* */
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
// Xalan header files.
#include <XSLT/ProblemListener.hpp>
/**
* The implementation of the default error handling for Xalan.
*/
class XALAN_XSLT_EXPORT ProblemListenerDefault : public ProblemListener
{
public:
ProblemListenerDefault(PrintWriter* pw = 0);
virtual
~ProblemListenerDefault();
// These methods are inherited from ProblemListener ...
virtual void
setPrintWriter(PrintWriter* pw);
virtual void
problem(
eProblemSource where,
eClassification classification,
const XalanNode* sourceNode,
const XalanNode* styleNode,
const XalanDOMString& msg,
const XalanDOMChar* uri,
int lineNo,
int charOffset);
// These methods are new...
PrintWriter*
getPrintWriter() const
{
return m_pw;
}
private:
PrintWriter* m_pw;
};
#endif // XALAN_PROBLEMLISTENERDEFAULT_HEADER_GUARD
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// boost
#include <boost/foreach.hpp>
// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_helpers.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/vertex_converters.hpp>
// agg
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_scanline_p.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
// stl
#include <string>
#include <cmath>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(line_symbolizer const& sym,
mapnik::feature_ptr const& feature,
proj_transform const& prj_trans)
{
stroke const& stroke_ = sym.get_stroke();
color const& col = stroke_.get_color();
unsigned r=col.red();
unsigned g=col.green();
unsigned b=col.blue();
unsigned a=col.alpha();
ras_ptr->reset();
set_gamma_method(stroke_, ras_ptr);
agg::rendering_buffer buf(current_buffer_->raw_data(),width_,height_, width_ * 4);
typedef agg::rgba8 color_type;
typedef agg::order_rgba order_type;
typedef agg::pixel32_type pixel_type;
typedef agg::comp_op_adaptor_rgba<color_type, order_type> blender_type; // comp blender
typedef agg::pixfmt_custom_blend_rgba<blender_type, agg::rendering_buffer> pixfmt_comp_type;
typedef agg::renderer_base<pixfmt_comp_type> renderer_base;
pixfmt_comp_type pixf(buf);
renderer_base renb(pixf);
agg::trans_affine tr;
evaluate_transform(tr, *feature, sym.get_transform());
if (sym.get_rasterizer() == RASTERIZER_FAST)
{
typedef agg::renderer_outline_aa<renderer_base> renderer_type;
typedef agg::rasterizer_outline_aa<renderer_type> rasterizer_type;
// need to reduce width by half to match standard rasterizer look
double scaled = scale_factor_ * .5;
agg::line_profile_aa profile(stroke_.get_width() * scaled, agg::gamma_power(stroke_.get_gamma()));
renderer_type ren(renb, profile);
ren.color(agg::rgba8(r, g, b, int(a*stroke_.get_opacity())));
rasterizer_type ras(ren);
set_join_caps_aa(stroke_,ras);
typedef boost::mpl::vector<clip_line_tag,transform_tag, offset_transform_tag, affine_transform_tag, smooth_tag, dash_tag, stroke_tag> conv_types;
vertex_converter<box2d<double>, rasterizer_type, line_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(query_extent_,ras,sym,t_,prj_trans,tr,scaled);
if (sym.clip()) converter.set<clip_line_tag>(); // optional clip (default: true)
converter.set<transform_tag>(); // always transform
if (fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
converter.set<affine_transform_tag>(); // optional affine transform
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
if (stroke_.has_dash()) converter.set<dash_tag>();
converter.set<stroke_tag>(); //always stroke
BOOST_FOREACH( geometry_type & geom, feature->paths())
{
if (geom.num_points() > 1)
{
converter.apply(geom);
}
}
}
else
{
typedef boost::mpl::vector<clip_line_tag,transform_tag, offset_transform_tag, affine_transform_tag, smooth_tag, dash_tag, stroke_tag> conv_types;
vertex_converter<box2d<double>, rasterizer, line_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(query_extent_,*ras_ptr,sym,t_,prj_trans,tr,scale_factor_);
if (sym.clip()) converter.set<clip_line_tag>(); // optional clip (default: true)
converter.set<transform_tag>(); // always transform
if (fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
converter.set<affine_transform_tag>(); // optional affine transform
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
if (stroke_.has_dash()) converter.set<dash_tag>();
converter.set<stroke_tag>(); //always stroke
BOOST_FOREACH( geometry_type & geom, feature->paths())
{
if (geom.num_points() > 1)
{
converter.apply(geom);
}
}
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_type;
pixf.comp_op(static_cast<agg::comp_op_e>(sym.comp_op()));
renderer_base renb(pixf);
renderer_type ren(renb);
ren.color(agg::rgba8(r, g, b, int(a * stroke_.get_opacity())));
agg::scanline_u8 sl;
agg::render_scanlines(*ras_ptr, sl, ren);
}
}
template void agg_renderer<image_32>::process(line_symbolizer const&,
mapnik::feature_ptr const&,
proj_transform const&);
}
<commit_msg>expand clipping box for lines to avoid trimmed edges - TODO - make sensitive to line width - refs #1215<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// boost
#include <boost/foreach.hpp>
// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_helpers.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/line_symbolizer.hpp>
#include <mapnik/vertex_converters.hpp>
// agg
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_scanline_p.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
// stl
#include <string>
#include <cmath>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(line_symbolizer const& sym,
mapnik::feature_ptr const& feature,
proj_transform const& prj_trans)
{
stroke const& stroke_ = sym.get_stroke();
color const& col = stroke_.get_color();
unsigned r=col.red();
unsigned g=col.green();
unsigned b=col.blue();
unsigned a=col.alpha();
ras_ptr->reset();
set_gamma_method(stroke_, ras_ptr);
agg::rendering_buffer buf(current_buffer_->raw_data(),width_,height_, width_ * 4);
typedef agg::rgba8 color_type;
typedef agg::order_rgba order_type;
typedef agg::pixel32_type pixel_type;
typedef agg::comp_op_adaptor_rgba<color_type, order_type> blender_type; // comp blender
typedef agg::pixfmt_custom_blend_rgba<blender_type, agg::rendering_buffer> pixfmt_comp_type;
typedef agg::renderer_base<pixfmt_comp_type> renderer_base;
pixfmt_comp_type pixf(buf);
renderer_base renb(pixf);
agg::trans_affine tr;
evaluate_transform(tr, *feature, sym.get_transform());
box2d<double> ext = query_extent_ * 1.1;
if (sym.get_rasterizer() == RASTERIZER_FAST)
{
typedef agg::renderer_outline_aa<renderer_base> renderer_type;
typedef agg::rasterizer_outline_aa<renderer_type> rasterizer_type;
// need to reduce width by half to match standard rasterizer look
double scaled = scale_factor_ * .5;
agg::line_profile_aa profile(stroke_.get_width() * scaled, agg::gamma_power(stroke_.get_gamma()));
renderer_type ren(renb, profile);
ren.color(agg::rgba8(r, g, b, int(a*stroke_.get_opacity())));
rasterizer_type ras(ren);
set_join_caps_aa(stroke_,ras);
typedef boost::mpl::vector<clip_line_tag,transform_tag, offset_transform_tag, affine_transform_tag, smooth_tag, dash_tag, stroke_tag> conv_types;
vertex_converter<box2d<double>, rasterizer_type, line_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(ext,ras,sym,t_,prj_trans,tr,scaled);
if (sym.clip()) converter.set<clip_line_tag>(); // optional clip (default: true)
converter.set<transform_tag>(); // always transform
if (fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
converter.set<affine_transform_tag>(); // optional affine transform
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
if (stroke_.has_dash()) converter.set<dash_tag>();
converter.set<stroke_tag>(); //always stroke
BOOST_FOREACH( geometry_type & geom, feature->paths())
{
if (geom.num_points() > 1)
{
converter.apply(geom);
}
}
}
else
{
typedef boost::mpl::vector<clip_line_tag,transform_tag, offset_transform_tag, affine_transform_tag, smooth_tag, dash_tag, stroke_tag> conv_types;
vertex_converter<box2d<double>, rasterizer, line_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(ext,*ras_ptr,sym,t_,prj_trans,tr,scale_factor_);
if (sym.clip()) converter.set<clip_line_tag>(); // optional clip (default: true)
converter.set<transform_tag>(); // always transform
if (fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
converter.set<affine_transform_tag>(); // optional affine transform
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
if (stroke_.has_dash()) converter.set<dash_tag>();
converter.set<stroke_tag>(); //always stroke
BOOST_FOREACH( geometry_type & geom, feature->paths())
{
if (geom.num_points() > 1)
{
converter.apply(geom);
}
}
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_type;
pixf.comp_op(static_cast<agg::comp_op_e>(sym.comp_op()));
renderer_base renb(pixf);
renderer_type ren(renb);
ren.color(agg::rgba8(r, g, b, int(a * stroke_.get_opacity())));
agg::scanline_u8 sl;
agg::render_scanlines(*ras_ptr, sl, ren);
}
}
template void agg_renderer<image_32>::process(line_symbolizer const&,
mapnik::feature_ptr const&,
proj_transform const&);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/symbolizer_helpers.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/font_util.hpp>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(text_symbolizer const& sym,
mapnik::feature_impl & feature,
proj_transform const& prj_trans)
{
text_symbolizer_helper<face_manager<freetype_engine>,
label_collision_detector4> helper(
sym, feature, prj_trans,
width_,height_,
scale_factor_,
t_, font_manager_, *detector_,
clipping_extent());
text_renderer<T> ren(*current_buffer_,
font_manager_,
sym.get_halo_rasterizer(),
sym.comp_op(),
scale_factor_);
while (helper.next())
{
placements_type const& placements = helper.placements();
for (unsigned int ii = 0; ii < placements.size(); ++ii)
{
ren.prepare_glyphs(placements[ii]);
ren.render(placements[ii].center);
}
}
}
template void agg_renderer<image_32>::process(text_symbolizer const&,
mapnik::feature_impl &,
proj_transform const&);
}
<commit_msg>fix text related test failures on ubuntu precise/g++-4.7 - refs #2049<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/symbolizer_helpers.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/font_util.hpp>
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(text_symbolizer const& sym,
mapnik::feature_impl & feature,
proj_transform const& prj_trans)
{
box2d<double> bb = clipping_extent();
text_symbolizer_helper<face_manager<freetype_engine>,
label_collision_detector4> helper(
sym, feature, prj_trans,
width_,height_,
scale_factor_,
t_, font_manager_, *detector_,
bb);
text_renderer<T> ren(*current_buffer_,
font_manager_,
sym.get_halo_rasterizer(),
sym.comp_op(),
scale_factor_);
while (helper.next())
{
placements_type const& placements = helper.placements();
for (unsigned int ii = 0; ii < placements.size(); ++ii)
{
ren.prepare_glyphs(placements[ii]);
ren.render(placements[ii].center);
}
}
}
template void agg_renderer<image_32>::process(text_symbolizer const&,
mapnik::feature_impl &,
proj_transform const&);
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the FreeStreamer project,
* (C)Copyright 2011-2014 Matias Muhonen <[email protected]>
* See the file ''LICENSE'' for using the code.
*
* https://github.com/muhku/FreeStreamer
*/
#include "file_stream.h"
namespace astreamer {
File_Stream::File_Stream() :
m_url(0),
m_readStream(0),
m_scheduledInRunLoop(false),
m_readPending(false),
m_fileReadBuffer(0),
m_id3Parser(new ID3_Parser())
{
m_id3Parser->m_delegate = this;
}
File_Stream::~File_Stream()
{
close();
if (m_fileReadBuffer) {
delete [] m_fileReadBuffer, m_fileReadBuffer = 0;
}
if (m_url) {
CFRelease(m_url), m_url = 0;
}
delete m_id3Parser, m_id3Parser = 0;
}
Input_Stream_Position File_Stream::position()
{
return m_position;
}
CFStringRef File_Stream::contentType()
{
CFStringRef contentType = CFSTR("");
CFStringRef pathComponent = 0;
CFIndex len = 0;
CFRange range;
CFStringRef suffix = 0;
if (!m_url) {
goto done;
}
pathComponent = CFURLCopyLastPathComponent(m_url);
if (!pathComponent) {
goto done;
}
len = CFStringGetLength(pathComponent);
if (len > 5) {
range.length = 4;
range.location = len - 4;
suffix = CFStringCreateWithSubstring(kCFAllocatorDefault,
pathComponent,
range);
if (!suffix) {
goto done;
}
// TODO: we should do the content-type resolvation in a better way.
if (CFStringCompare(suffix, CFSTR(".mp3"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/mpeg");
} else if (CFStringCompare(suffix, CFSTR(".m4a"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/x-m4a");
} else if (CFStringCompare(suffix, CFSTR(".mp3"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/mp4");
} else if (CFStringCompare(suffix, CFSTR(".aac"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/aac");
}
}
done:
if (pathComponent) {
CFRelease(pathComponent);
}
if (suffix) {
CFRelease(suffix);
}
return contentType;
}
size_t File_Stream::contentLength()
{
SInt32 errorCode;
CFTypeRef prop;
if ((prop = CFURLCreatePropertyFromResource(kCFAllocatorDefault, m_url, kCFURLFileLength, &errorCode)) != NULL) {
CFNumberRef length = (CFNumberRef)prop;
CFIndex fileLength;
if (CFNumberGetValue(length, kCFNumberCFIndexType, &fileLength)) {
CFRelease(prop);
return fileLength;
}
CFRelease(prop);
}
return 0;
}
bool File_Stream::open()
{
Input_Stream_Position position;
position.start = 0;
position.end = 0;
m_id3Parser->reset();
return open(position);
}
bool File_Stream::open(const Input_Stream_Position& position)
{
bool success = false;
CFStreamClientContext CTX = { 0, this, NULL, NULL, NULL };
/* Already opened a read stream, return */
if (m_readStream) {
goto out;
}
if (!m_url) {
goto out;
}
/* Reset state */
m_position = position;
m_readPending = false;
/* Failed to create a stream */
if (!(m_readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, m_url))) {
goto out;
}
if (m_position.start > 0) {
CFNumberRef position = CFNumberCreate(0, kCFNumberLongLongType, &m_position.start);
CFReadStreamSetProperty(m_readStream, kCFStreamPropertyFileCurrentOffset, position);
CFRelease(position);
}
if (!CFReadStreamSetClient(m_readStream, kCFStreamEventHasBytesAvailable |
kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred, readCallBack, &CTX)) {
CFRelease(m_readStream), m_readStream = 0;
goto out;
}
setScheduledInRunLoop(true);
if (!CFReadStreamOpen(m_readStream)) {
/* Open failed: clean */
CFReadStreamSetClient(m_readStream, 0, NULL, NULL);
setScheduledInRunLoop(false);
if (m_readStream) {
CFRelease(m_readStream), m_readStream = 0;
}
goto out;
}
success = true;
out:
if (success) {
if (m_delegate) {
m_delegate->streamIsReadyRead();
}
}
return success;
}
void File_Stream::close()
{
/* The stream has been already closed */
if (!m_readStream) {
return;
}
CFReadStreamSetClient(m_readStream, 0, NULL, NULL);
setScheduledInRunLoop(false);
CFReadStreamClose(m_readStream);
CFRelease(m_readStream), m_readStream = 0;
}
void File_Stream::setScheduledInRunLoop(bool scheduledInRunLoop)
{
/* The stream has not been opened, or it has been already closed */
if (!m_readStream) {
return;
}
/* The state doesn't change */
if (m_scheduledInRunLoop == scheduledInRunLoop) {
return;
}
if (m_scheduledInRunLoop) {
CFReadStreamUnscheduleFromRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
} else {
if (m_readPending) {
m_readPending = false;
readCallBack(m_readStream, kCFStreamEventHasBytesAvailable, this);
}
CFReadStreamScheduleWithRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
m_scheduledInRunLoop = scheduledInRunLoop;
}
void File_Stream::setUrl(CFURLRef url)
{
if (m_url) {
CFRelease(m_url);
}
if (url) {
m_url = (CFURLRef)CFRetain(url);
} else {
m_url = NULL;
}
}
bool File_Stream::canHandleUrl(CFURLRef url)
{
if (!url) {
return false;
}
CFStringRef scheme = CFURLCopyScheme(url);
if (scheme) {
if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
CFRelease(scheme);
// The only scheme we claim to handle are the local files
return true;
}
CFRelease(scheme);
}
// We don't handle anything else but local files
return false;
}
/* ID3_Parser_Delegate */
void File_Stream::id3metaDataAvailable(std::map<CFStringRef,CFStringRef> metaData)
{
if (m_delegate) {
m_delegate->streamMetaDataAvailable(metaData);
}
}
void File_Stream::readCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo)
{
File_Stream *THIS = static_cast<File_Stream*>(clientCallBackInfo);
switch (eventType) {
case kCFStreamEventHasBytesAvailable: {
if (!THIS->m_fileReadBuffer) {
THIS->m_fileReadBuffer = new UInt8[1024];
}
while (CFReadStreamHasBytesAvailable(stream)) {
if (!THIS->m_scheduledInRunLoop) {
/*
* This is critical - though the stream has data available,
* do not try to feed the audio queue with data, if it has
* indicated that it doesn't want more data due to buffers
* full.
*/
THIS->m_readPending = true;
break;
}
CFIndex bytesRead = CFReadStreamRead(stream, THIS->m_fileReadBuffer, 1024);
if (CFReadStreamGetStatus(stream) == kCFStreamStatusError ||
bytesRead < 0) {
if (THIS->m_delegate) {
THIS->m_delegate->streamErrorOccurred();
}
break;
}
if (bytesRead > 0) {
if (THIS->m_delegate) {
THIS->m_delegate->streamHasBytesAvailable(THIS->m_fileReadBuffer, (UInt32)bytesRead);
}
if (THIS->m_id3Parser->wantData()) {
THIS->m_id3Parser->feedData(THIS->m_fileReadBuffer, (UInt32)bytesRead);
}
}
}
break;
}
case kCFStreamEventEndEncountered: {
if (THIS->m_delegate) {
THIS->m_delegate->streamEndEncountered();
}
break;
}
case kCFStreamEventErrorOccurred: {
if (THIS->m_delegate) {
THIS->m_delegate->streamErrorOccurred();
}
break;
}
}
}
} // namespace astreamer<commit_msg>Fix the deprecated file size retrieval.<commit_after>/*
* This file is part of the FreeStreamer project,
* (C)Copyright 2011-2014 Matias Muhonen <[email protected]>
* See the file ''LICENSE'' for using the code.
*
* https://github.com/muhku/FreeStreamer
*/
#include "file_stream.h"
namespace astreamer {
File_Stream::File_Stream() :
m_url(0),
m_readStream(0),
m_scheduledInRunLoop(false),
m_readPending(false),
m_fileReadBuffer(0),
m_id3Parser(new ID3_Parser())
{
m_id3Parser->m_delegate = this;
}
File_Stream::~File_Stream()
{
close();
if (m_fileReadBuffer) {
delete [] m_fileReadBuffer, m_fileReadBuffer = 0;
}
if (m_url) {
CFRelease(m_url), m_url = 0;
}
delete m_id3Parser, m_id3Parser = 0;
}
Input_Stream_Position File_Stream::position()
{
return m_position;
}
CFStringRef File_Stream::contentType()
{
CFStringRef contentType = CFSTR("");
CFStringRef pathComponent = 0;
CFIndex len = 0;
CFRange range;
CFStringRef suffix = 0;
if (!m_url) {
goto done;
}
pathComponent = CFURLCopyLastPathComponent(m_url);
if (!pathComponent) {
goto done;
}
len = CFStringGetLength(pathComponent);
if (len > 5) {
range.length = 4;
range.location = len - 4;
suffix = CFStringCreateWithSubstring(kCFAllocatorDefault,
pathComponent,
range);
if (!suffix) {
goto done;
}
// TODO: we should do the content-type resolvation in a better way.
if (CFStringCompare(suffix, CFSTR(".mp3"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/mpeg");
} else if (CFStringCompare(suffix, CFSTR(".m4a"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/x-m4a");
} else if (CFStringCompare(suffix, CFSTR(".mp3"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/mp4");
} else if (CFStringCompare(suffix, CFSTR(".aac"), 0) == kCFCompareEqualTo) {
contentType = CFSTR("audio/aac");
}
}
done:
if (pathComponent) {
CFRelease(pathComponent);
}
if (suffix) {
CFRelease(suffix);
}
return contentType;
}
size_t File_Stream::contentLength()
{
CFNumberRef length = NULL;
CFErrorRef err = NULL;
if (CFURLCopyResourcePropertyForKey(m_url, kCFURLFileSizeKey, &length, &err)) {
CFIndex fileLength;
if (CFNumberGetValue(length, kCFNumberCFIndexType, &fileLength)) {
CFRelease(length);
return fileLength;
}
}
return 0;
}
bool File_Stream::open()
{
Input_Stream_Position position;
position.start = 0;
position.end = 0;
m_id3Parser->reset();
return open(position);
}
bool File_Stream::open(const Input_Stream_Position& position)
{
bool success = false;
CFStreamClientContext CTX = { 0, this, NULL, NULL, NULL };
/* Already opened a read stream, return */
if (m_readStream) {
goto out;
}
if (!m_url) {
goto out;
}
/* Reset state */
m_position = position;
m_readPending = false;
/* Failed to create a stream */
if (!(m_readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, m_url))) {
goto out;
}
if (m_position.start > 0) {
CFNumberRef position = CFNumberCreate(0, kCFNumberLongLongType, &m_position.start);
CFReadStreamSetProperty(m_readStream, kCFStreamPropertyFileCurrentOffset, position);
CFRelease(position);
}
if (!CFReadStreamSetClient(m_readStream, kCFStreamEventHasBytesAvailable |
kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred, readCallBack, &CTX)) {
CFRelease(m_readStream), m_readStream = 0;
goto out;
}
setScheduledInRunLoop(true);
if (!CFReadStreamOpen(m_readStream)) {
/* Open failed: clean */
CFReadStreamSetClient(m_readStream, 0, NULL, NULL);
setScheduledInRunLoop(false);
if (m_readStream) {
CFRelease(m_readStream), m_readStream = 0;
}
goto out;
}
success = true;
out:
if (success) {
if (m_delegate) {
m_delegate->streamIsReadyRead();
}
}
return success;
}
void File_Stream::close()
{
/* The stream has been already closed */
if (!m_readStream) {
return;
}
CFReadStreamSetClient(m_readStream, 0, NULL, NULL);
setScheduledInRunLoop(false);
CFReadStreamClose(m_readStream);
CFRelease(m_readStream), m_readStream = 0;
}
void File_Stream::setScheduledInRunLoop(bool scheduledInRunLoop)
{
/* The stream has not been opened, or it has been already closed */
if (!m_readStream) {
return;
}
/* The state doesn't change */
if (m_scheduledInRunLoop == scheduledInRunLoop) {
return;
}
if (m_scheduledInRunLoop) {
CFReadStreamUnscheduleFromRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
} else {
if (m_readPending) {
m_readPending = false;
readCallBack(m_readStream, kCFStreamEventHasBytesAvailable, this);
}
CFReadStreamScheduleWithRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
m_scheduledInRunLoop = scheduledInRunLoop;
}
void File_Stream::setUrl(CFURLRef url)
{
if (m_url) {
CFRelease(m_url);
}
if (url) {
m_url = (CFURLRef)CFRetain(url);
} else {
m_url = NULL;
}
}
bool File_Stream::canHandleUrl(CFURLRef url)
{
if (!url) {
return false;
}
CFStringRef scheme = CFURLCopyScheme(url);
if (scheme) {
if (CFStringCompare(scheme, CFSTR("file"), 0) == kCFCompareEqualTo) {
CFRelease(scheme);
// The only scheme we claim to handle are the local files
return true;
}
CFRelease(scheme);
}
// We don't handle anything else but local files
return false;
}
/* ID3_Parser_Delegate */
void File_Stream::id3metaDataAvailable(std::map<CFStringRef,CFStringRef> metaData)
{
if (m_delegate) {
m_delegate->streamMetaDataAvailable(metaData);
}
}
void File_Stream::readCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo)
{
File_Stream *THIS = static_cast<File_Stream*>(clientCallBackInfo);
switch (eventType) {
case kCFStreamEventHasBytesAvailable: {
if (!THIS->m_fileReadBuffer) {
THIS->m_fileReadBuffer = new UInt8[1024];
}
while (CFReadStreamHasBytesAvailable(stream)) {
if (!THIS->m_scheduledInRunLoop) {
/*
* This is critical - though the stream has data available,
* do not try to feed the audio queue with data, if it has
* indicated that it doesn't want more data due to buffers
* full.
*/
THIS->m_readPending = true;
break;
}
CFIndex bytesRead = CFReadStreamRead(stream, THIS->m_fileReadBuffer, 1024);
if (CFReadStreamGetStatus(stream) == kCFStreamStatusError ||
bytesRead < 0) {
if (THIS->m_delegate) {
THIS->m_delegate->streamErrorOccurred();
}
break;
}
if (bytesRead > 0) {
if (THIS->m_delegate) {
THIS->m_delegate->streamHasBytesAvailable(THIS->m_fileReadBuffer, (UInt32)bytesRead);
}
if (THIS->m_id3Parser->wantData()) {
THIS->m_id3Parser->feedData(THIS->m_fileReadBuffer, (UInt32)bytesRead);
}
}
}
break;
}
case kCFStreamEventEndEncountered: {
if (THIS->m_delegate) {
THIS->m_delegate->streamEndEncountered();
}
break;
}
case kCFStreamEventErrorOccurred: {
if (THIS->m_delegate) {
THIS->m_delegate->streamErrorOccurred();
}
break;
}
}
}
} // namespace astreamer<|endoftext|>
|
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2019 Martin Davis <[email protected]>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/InteriorPointArea.java (JTS-1.17+)
* https://github.com/locationtech/jts/commit/a140ca30cc51be4f65c950a30b0a8f51a6df75ba
*
**********************************************************************/
#include <geos/algorithm/InteriorPointArea.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Envelope.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/util/Interrupt.h>
#include <algorithm>
#include <vector>
#include <typeinfo>
#include <memory> // for unique_ptr
using namespace std;
using namespace geos::geom;
namespace geos {
namespace algorithm { // geos.algorithm
// file statics
namespace {
double
avg(double a, double b)
{
return (a + b) / 2.0;
}
/**
* Finds a safe scan line Y ordinate by projecting
* the polygon segments
* to the Y axis and finding the
* Y-axis interval which contains the centre of the Y extent.
* The centre of
* this interval is returned as the scan line Y-ordinate.
* <p>
* Note that in the case of (degenerate, invalid)
* zero-area polygons the computed Y value
* may be equal to a vertex Y-ordinate.
*
* @author mdavis
*
*/
class ScanLineYOrdinateFinder {
public:
static double
getScanLineY(const Polygon& poly)
{
ScanLineYOrdinateFinder finder(poly);
return finder.getScanLineY();
}
ScanLineYOrdinateFinder(const Polygon& nPoly)
: poly(nPoly)
{
// initialize using extremal values
hiY = poly.getEnvelopeInternal()->getMaxY();
loY = poly.getEnvelopeInternal()->getMinY();
centreY = avg(loY, hiY);
}
double
getScanLineY()
{
process(*poly.getExteriorRing());
for(size_t i = 0; i < poly.getNumInteriorRing(); i++) {
process(*poly.getInteriorRingN(i));
}
double bisectY = avg(hiY, loY);
return bisectY;
}
private:
const Polygon& poly;
double centreY;
double hiY;
double loY;
void
process(const LineString& line)
{
const CoordinateSequence* seq = line.getCoordinatesRO();
for(std::size_t i = 0, s = seq->size(); i < s; i++) {
double y = seq->getY(i);
updateInterval(y);
}
}
void
updateInterval(double y)
{
if(y <= centreY) {
if(y > loY) {
loY = y;
}
}
else if(y > centreY) {
if(y < hiY) {
hiY = y;
}
}
}
};
class InteriorPointPolygon {
public:
InteriorPointPolygon(const Polygon& poly)
: polygon(poly)
{
interiorPointY = ScanLineYOrdinateFinder::getScanLineY(polygon);
}
bool
getInteriorPoint(Coordinate& ret) const
{
ret = interiorPoint;
return true;
}
double getWidth()
{
return interiorSectionWidth;
}
void
process()
{
/**
* This results in returning a null Coordinate
*/
if (polygon.isEmpty()) return;
/**
* set default interior point in case polygon has zero area
*/
interiorPoint = *polygon.getCoordinate();
const LinearRing* shell = dynamic_cast<const LinearRing*>(polygon.getExteriorRing());
scanRing( *shell );
for (size_t i = 0; i < polygon.getNumInteriorRing(); i++) {
const LinearRing* hole = dynamic_cast<const LinearRing*>(polygon.getInteriorRingN(i));
scanRing( *hole );
}
findBestMidpoint(crossings);
}
private:
const Polygon& polygon;
double interiorPointY;
double interiorSectionWidth = 0.0;
vector<double> crossings;
Coordinate interiorPoint;
void scanRing(const LinearRing& ring)
{
// skip rings which don't cross scan line
if ( ! intersectsHorizontalLine( ring.getEnvelopeInternal(), interiorPointY) )
return;
const CoordinateSequence* seq = ring.getCoordinatesRO();
for (size_t i = 1; i < seq->size(); i++) {
Coordinate ptPrev = seq->getAt(i - 1);
Coordinate pt = seq->getAt(i);
addEdgeCrossing(ptPrev, pt, interiorPointY, crossings);
}
}
void addEdgeCrossing(Coordinate& p0, Coordinate& p1, double scanY, vector<double>& crossings) {
// skip non-crossing segments
if ( !intersectsHorizontalLine(p0, p1, scanY) )
return;
if (! isEdgeCrossingCounted(p0, p1, scanY) )
return;
// edge intersects scan line, so add a crossing
double xInt = intersection(p0, p1, scanY);
crossings.push_back(xInt);
//checkIntersectionDD(p0, p1, scanY, xInt);
}
void findBestMidpoint(vector<double>& crossings)
{
// zero-area polygons will have no crossings
if (crossings.size() == 0) return;
//Assert.isTrue(0 == crossings.size() % 2, "Interior Point robustness failure: odd number of scanline crossings");
sort(crossings.begin(), crossings.end());
/*
* Entries in crossings list are expected to occur in pairs representing a
* section of the scan line interior to the polygon (which may be zero-length)
*/
for (size_t i = 0; i < crossings.size(); i += 2) {
double x1 = crossings[i];
// crossings count must be even so this should be safe
double x2 = crossings[i + 1];
double width = x2 - x1;
if ( width > interiorSectionWidth ) {
interiorSectionWidth = width;
double interiorPointX = avg(x1, x2);
interiorPoint = Coordinate(interiorPointX, interiorPointY);
}
}
}
static bool
isEdgeCrossingCounted(Coordinate& p0, Coordinate& p1, double scanY) {
// skip horizontal lines
if ( p0.y == p1.y )
return false;
// handle cases where vertices lie on scan-line
// downward segment does not include start point
if ( p0.y == scanY && p1.y < scanY )
return false;
// upward segment does not include endpoint
if ( p1.y == scanY && p0.y < scanY )
return false;
return true;
}
static double
intersection(const Coordinate& p0, const Coordinate& p1, double Y)
{
double x0 = p0.x;
double x1 = p1.x;
if ( x0 == x1 )
return x0;
// Assert: segDX is non-zero, due to previous equality test
double segDX = x1 - x0;
double segDY = p1.y - p0.y;
double m = segDY / segDX;
double x = x0 + ((Y - p0.y) / m);
return x;
}
static bool
intersectsHorizontalLine(const Envelope* env, double y)
{
if ( y < env->getMinY() )
return false;
if ( y > env->getMaxY() )
return false;
return true;
}
static bool
intersectsHorizontalLine(const Coordinate& p0, const Coordinate& p1, double y) {
// both ends above?
if ( p0.y > y && p1.y > y )
return false;
// both ends below?
if ( p0.y < y && p1.y < y )
return false;
// segment must intersect line
return true;
}
};
} // anonymous namespace
InteriorPointArea::InteriorPointArea(const Geometry* g)
{
maxWidth = -1;
process(g);
}
InteriorPointArea::~InteriorPointArea()
{
}
bool
InteriorPointArea::getInteriorPoint(Coordinate& ret) const
{
// GEOS-specific code
if (maxWidth < 0)
return false;
ret = interiorPoint;
return true;
}
/*private*/
void
InteriorPointArea::process(const Geometry* geom)
{
if (geom->isEmpty())
return;
const Polygon* poly = dynamic_cast<const Polygon*>(geom);
if(poly) {
processPolygon(poly);
return;
}
const GeometryCollection* gc = dynamic_cast<const GeometryCollection*>(geom);
if(gc) {
for(std::size_t i = 0, n = gc->getNumGeometries(); i < n; i++) {
process(gc->getGeometryN(i));
GEOS_CHECK_FOR_INTERRUPTS();
}
}
}
/*private*/
void
InteriorPointArea::processPolygon(const Polygon* polygon)
{
InteriorPointPolygon intPtPoly(*polygon);
intPtPoly.process();
double width = intPtPoly.getWidth();
if ( width > maxWidth ) {
maxWidth = width;
intPtPoly.getInteriorPoint(interiorPoint);
}
}
} // namespace geos.algorithm
} // namespace geos
<commit_msg>src/algorithm/InteriorPointArea.cpp: fix -Wshadow warning (fixes #954)<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2019 Martin Davis <[email protected]>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/InteriorPointArea.java (JTS-1.17+)
* https://github.com/locationtech/jts/commit/a140ca30cc51be4f65c950a30b0a8f51a6df75ba
*
**********************************************************************/
#include <geos/algorithm/InteriorPointArea.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Envelope.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/util/Interrupt.h>
#include <algorithm>
#include <vector>
#include <typeinfo>
#include <memory> // for unique_ptr
using namespace std;
using namespace geos::geom;
namespace geos {
namespace algorithm { // geos.algorithm
// file statics
namespace {
double
avg(double a, double b)
{
return (a + b) / 2.0;
}
/**
* Finds a safe scan line Y ordinate by projecting
* the polygon segments
* to the Y axis and finding the
* Y-axis interval which contains the centre of the Y extent.
* The centre of
* this interval is returned as the scan line Y-ordinate.
* <p>
* Note that in the case of (degenerate, invalid)
* zero-area polygons the computed Y value
* may be equal to a vertex Y-ordinate.
*
* @author mdavis
*
*/
class ScanLineYOrdinateFinder {
public:
static double
getScanLineY(const Polygon& poly)
{
ScanLineYOrdinateFinder finder(poly);
return finder.getScanLineY();
}
ScanLineYOrdinateFinder(const Polygon& nPoly)
: poly(nPoly)
{
// initialize using extremal values
hiY = poly.getEnvelopeInternal()->getMaxY();
loY = poly.getEnvelopeInternal()->getMinY();
centreY = avg(loY, hiY);
}
double
getScanLineY()
{
process(*poly.getExteriorRing());
for(size_t i = 0; i < poly.getNumInteriorRing(); i++) {
process(*poly.getInteriorRingN(i));
}
double bisectY = avg(hiY, loY);
return bisectY;
}
private:
const Polygon& poly;
double centreY;
double hiY;
double loY;
void
process(const LineString& line)
{
const CoordinateSequence* seq = line.getCoordinatesRO();
for(std::size_t i = 0, s = seq->size(); i < s; i++) {
double y = seq->getY(i);
updateInterval(y);
}
}
void
updateInterval(double y)
{
if(y <= centreY) {
if(y > loY) {
loY = y;
}
}
else if(y > centreY) {
if(y < hiY) {
hiY = y;
}
}
}
};
class InteriorPointPolygon {
public:
InteriorPointPolygon(const Polygon& poly)
: polygon(poly)
{
interiorPointY = ScanLineYOrdinateFinder::getScanLineY(polygon);
}
bool
getInteriorPoint(Coordinate& ret) const
{
ret = interiorPoint;
return true;
}
double getWidth()
{
return interiorSectionWidth;
}
void
process()
{
vector<double> crossings;
/**
* This results in returning a null Coordinate
*/
if (polygon.isEmpty()) return;
/**
* set default interior point in case polygon has zero area
*/
interiorPoint = *polygon.getCoordinate();
const LinearRing* shell = dynamic_cast<const LinearRing*>(polygon.getExteriorRing());
scanRing( *shell, crossings );
for (size_t i = 0; i < polygon.getNumInteriorRing(); i++) {
const LinearRing* hole = dynamic_cast<const LinearRing*>(polygon.getInteriorRingN(i));
scanRing( *hole, crossings );
}
findBestMidpoint(crossings);
}
private:
const Polygon& polygon;
double interiorPointY;
double interiorSectionWidth = 0.0;
Coordinate interiorPoint;
void scanRing(const LinearRing& ring, vector<double>& crossings)
{
// skip rings which don't cross scan line
if ( ! intersectsHorizontalLine( ring.getEnvelopeInternal(), interiorPointY) )
return;
const CoordinateSequence* seq = ring.getCoordinatesRO();
for (size_t i = 1; i < seq->size(); i++) {
Coordinate ptPrev = seq->getAt(i - 1);
Coordinate pt = seq->getAt(i);
addEdgeCrossing(ptPrev, pt, interiorPointY, crossings);
}
}
void addEdgeCrossing(Coordinate& p0, Coordinate& p1, double scanY, vector<double>& crossings) {
// skip non-crossing segments
if ( !intersectsHorizontalLine(p0, p1, scanY) )
return;
if (! isEdgeCrossingCounted(p0, p1, scanY) )
return;
// edge intersects scan line, so add a crossing
double xInt = intersection(p0, p1, scanY);
crossings.push_back(xInt);
//checkIntersectionDD(p0, p1, scanY, xInt);
}
void findBestMidpoint(vector<double>& crossings)
{
// zero-area polygons will have no crossings
if (crossings.size() == 0) return;
//Assert.isTrue(0 == crossings.size() % 2, "Interior Point robustness failure: odd number of scanline crossings");
sort(crossings.begin(), crossings.end());
/*
* Entries in crossings list are expected to occur in pairs representing a
* section of the scan line interior to the polygon (which may be zero-length)
*/
for (size_t i = 0; i < crossings.size(); i += 2) {
double x1 = crossings[i];
// crossings count must be even so this should be safe
double x2 = crossings[i + 1];
double width = x2 - x1;
if ( width > interiorSectionWidth ) {
interiorSectionWidth = width;
double interiorPointX = avg(x1, x2);
interiorPoint = Coordinate(interiorPointX, interiorPointY);
}
}
}
static bool
isEdgeCrossingCounted(Coordinate& p0, Coordinate& p1, double scanY) {
// skip horizontal lines
if ( p0.y == p1.y )
return false;
// handle cases where vertices lie on scan-line
// downward segment does not include start point
if ( p0.y == scanY && p1.y < scanY )
return false;
// upward segment does not include endpoint
if ( p1.y == scanY && p0.y < scanY )
return false;
return true;
}
static double
intersection(const Coordinate& p0, const Coordinate& p1, double Y)
{
double x0 = p0.x;
double x1 = p1.x;
if ( x0 == x1 )
return x0;
// Assert: segDX is non-zero, due to previous equality test
double segDX = x1 - x0;
double segDY = p1.y - p0.y;
double m = segDY / segDX;
double x = x0 + ((Y - p0.y) / m);
return x;
}
static bool
intersectsHorizontalLine(const Envelope* env, double y)
{
if ( y < env->getMinY() )
return false;
if ( y > env->getMaxY() )
return false;
return true;
}
static bool
intersectsHorizontalLine(const Coordinate& p0, const Coordinate& p1, double y) {
// both ends above?
if ( p0.y > y && p1.y > y )
return false;
// both ends below?
if ( p0.y < y && p1.y < y )
return false;
// segment must intersect line
return true;
}
};
} // anonymous namespace
InteriorPointArea::InteriorPointArea(const Geometry* g)
{
maxWidth = -1;
process(g);
}
InteriorPointArea::~InteriorPointArea()
{
}
bool
InteriorPointArea::getInteriorPoint(Coordinate& ret) const
{
// GEOS-specific code
if (maxWidth < 0)
return false;
ret = interiorPoint;
return true;
}
/*private*/
void
InteriorPointArea::process(const Geometry* geom)
{
if (geom->isEmpty())
return;
const Polygon* poly = dynamic_cast<const Polygon*>(geom);
if(poly) {
processPolygon(poly);
return;
}
const GeometryCollection* gc = dynamic_cast<const GeometryCollection*>(geom);
if(gc) {
for(std::size_t i = 0, n = gc->getNumGeometries(); i < n; i++) {
process(gc->getGeometryN(i));
GEOS_CHECK_FOR_INTERRUPTS();
}
}
}
/*private*/
void
InteriorPointArea::processPolygon(const Polygon* polygon)
{
InteriorPointPolygon intPtPoly(*polygon);
intPtPoly.process();
double width = intPtPoly.getWidth();
if ( width > maxWidth ) {
maxWidth = width;
intPtPoly.getInteriorPoint(interiorPoint);
}
}
} // namespace geos.algorithm
} // namespace geos
<|endoftext|>
|
<commit_before>/*
Copyright 2016 aboru
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 <cstdlib>
#include <iostream>
#include <string>
#include "config.hpp"
#include "board/board.hpp"
int main(int argument_count, char **arguments) {
for (int i = 0; i < argument_count; i++) {
std::string argument = std::string(arguments[i]);
if (argument == "-v" || argument == "--version") {
std::cout << "aboru checkers" << std::endl;
std::cout << "version: @" << VERSION << std::endl;
return EXIT_SUCCESS;
}
}
checkers::board board;
std::cout << board.to_string();
return EXIT_SUCCESS;
}
<commit_msg>adds a help flag that points the user to the project on github<commit_after>/*
Copyright 2016 aboru
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 <cstdlib>
#include <iostream>
#include <string>
#include "config.hpp"
#include "board/board.hpp"
int main(int argument_count, char **arguments) {
for (int i = 0; i < argument_count; i++) {
std::string argument = std::string(arguments[i]);
if (argument == "-v" || argument == "--version") {
std::cout << "aboru checkers" << std::endl;
std::cout << "version: @" << VERSION << std::endl;
return EXIT_SUCCESS;
}
if (argument == "-h" || argument == "--help") {
std::cout << "view the documentation on the project site: ";
std::cout << "https://github.com/aboru/checkers" << std::endl;
return EXIT_SUCCESS;
}
}
checkers::board board;
std::cout << board.to_string();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <GL/gl.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>
// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
namespace qm {
struct Env {
Display* dpy;
Window win;
GLXContext ctx;
};
struct Shader {
GLuint vs;
GLuint fs;
GLuint prog;
};
const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
void main() \
{ \
gl_FrontColor= gl_Color; \
gl_TexCoord[0]= gl_MultiTexCoord0; \
gl_Position= gl_Vertex; \
v_pos= (gl_ModelViewProjectionMatrix*gl_Vertex).xyz; \
} \
\n";
const GLchar* g_fs= "\
#version 120\n\
varying vec3 v_pos; \
void main() \
{ \
float length= dot(v_pos, v_pos); \
gl_FragColor= vec4(sin(v_pos.x*10.0)*0.5 + 0.5, cos(v_pos.y*10.0 + v_pos.x*5.0)*0.5 + 0.5, v_pos.z, sin(v_pos.x*10.0) + 1.0 - length); \
} \
\n";
typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
voidFunc f= glXGetProcAddressARB((const GLubyte*)name);
if (!f) {
std::printf("Failed to query function: %s", name);
std::abort();
}
return f;
}
void checkShaderStatus(GLuint shd)
{
GLint status;
glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
if (!status) {
const GLsizei max_len= 512;
GLchar log[max_len];
glGetShaderInfoLog(shd, max_len, NULL, log);
std::printf("Shader compilation failed: %s", log);
std::abort();
}
}
void checkProgramStatus(GLuint prog)
{
GLint link_status;
glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
if (!link_status) {
const GLsizei size= 512;
GLchar log[size];
glGetProgramInfoLog(prog, size, NULL, log);
std::printf("Program link failed: %s", log);
std::abort();
}
}
void init(Env& env, Shader& shd)
{
{ // Create window
env.dpy= XOpenDisplay(NULL);
if(env.dpy == NULL)
std::abort();
Window root= DefaultRootWindow(env.dpy);
GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);
if(vi == NULL)
std::abort();
Colormap cmap;
cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap= cmap;
swa.event_mask= ExposureMask | KeyPressMask;
env.win=
XCreateWindow( env.dpy,
root,
0, 0, 600, 600, 0,
vi->depth,
InputOutput,
vi->visual,
CWColormap | CWEventMask,
&swa);
XMapWindow(env.dpy, env.win);
XStoreName(env.dpy, env.win, "QM Test");
env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(env.dpy, env.win, env.ctx);
}
{ // Query necessary GL functions
glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
}
{ // Create shaders
{ // Vertex
shd.vs= glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shd.vs, 1, &g_vs, NULL);
glCompileShader(shd.vs);
checkShaderStatus(shd.vs);
}
{ // Fragment
shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(shd.fs, 1, &g_fs, NULL);
glCompileShader(shd.fs);
checkShaderStatus(shd.fs);
}
{ // Shader program
shd.prog= glCreateProgram();
glAttachShader(shd.prog, shd.vs);
glAttachShader(shd.prog, shd.fs);
glLinkProgram(shd.prog);
checkProgramStatus(shd.prog);
}
}
{ // Setup initial GL state
glClearColor(0.0, 0.0, 0.0, 1.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
void quit(const Env& env, const Shader& shd)
{
{ // Close window
glXMakeCurrent(env.dpy, None, NULL);
glXDestroyContext(env.dpy, env.ctx);
XDestroyWindow(env.dpy, env.win);
XCloseDisplay(env.dpy);
}
{ // Destroy shaders
glDetachShader(shd.prog, shd.vs);
glDeleteShader(shd.vs);
glDetachShader(shd.prog, shd.fs);
glDeleteShader(shd.fs);
glDeleteProgram(shd.prog);
}
}
void draw(const Shader& shd)
{
glUseProgram(shd.prog);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
static float rot;
rot += 5;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(rot, 1.0, 0.1, 1.0);
float step= 0.1;
glBegin(GL_QUADS);
for (int i= 0; i < 100; ++i) {
glVertex3f(-.75, -.75, step*i);
glVertex3f( .75, -.75, step*i);
glVertex3f( .75, .75, step*i);
glVertex3f(-.75, .75, step*i);
}
glEnd();
}
bool loop(const Env& env, const Shader& shd)
{
XWindowAttributes gwa;
XGetWindowAttributes(env.dpy, env.win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
qm::draw(shd);
usleep(1);
glXSwapBuffers(env.dpy, env.win);
while(XPending(env.dpy)) {
XEvent xev;
XNextEvent(env.dpy, &xev);
if(xev.type == KeyPress)
return false;
}
return true;
}
} // qm
int main()
{
qm::Env env;
qm::Shader shd;
qm::init(env, shd);
while(loop(env, shd));
qm::quit(env, shd);
}
<commit_msg>Fixed perspective<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <GL/gl.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>
// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
namespace qm {
struct Env {
Display* dpy;
Window win;
GLXContext ctx;
};
struct Shader {
GLuint vs;
GLuint fs;
GLuint prog;
};
const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
void main() \
{ \
gl_FrontColor= gl_Color; \
gl_TexCoord[0]= gl_MultiTexCoord0; \
gl_Position= vec4(gl_Vertex.x, gl_Vertex.y, 0.0, 1.0); \
v_pos= (gl_ModelViewProjectionMatrix*gl_Vertex).xyz; \
} \
\n";
const GLchar* g_fs= "\
#version 120\n\
varying vec3 v_pos; \
void main() \
{ \
float beam_a= 0.001/(v_pos.z*v_pos.z + v_pos.y*v_pos.y) + 0.005/(v_pos.x*v_pos.x + 0.05*(v_pos.z*v_pos.z + v_pos.y*v_pos.y)); \
vec3 beam_c= vec3(0.3 + abs(v_pos.x), 0.8, 1.0); \
float hole_a= pow(min(1.0, 0.1/(dot(v_pos, v_pos))), 3.0); \
float lerp= clamp(beam_a*(1.0 - hole_a), 0.0, 1.0); \
gl_FragColor= vec4(beam_c*lerp, beam_a + hole_a); \
} \
\n";
typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
voidFunc f= glXGetProcAddressARB((const GLubyte*)name);
if (!f) {
std::printf("Failed to query function: %s", name);
std::abort();
}
return f;
}
void checkShaderStatus(GLuint shd)
{
GLint status;
glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
if (!status) {
const GLsizei max_len= 512;
GLchar log[max_len];
glGetShaderInfoLog(shd, max_len, NULL, log);
std::printf("Shader compilation failed: %s", log);
std::abort();
}
}
void checkProgramStatus(GLuint prog)
{
GLint link_status;
glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
if (!link_status) {
const GLsizei size= 512;
GLchar log[size];
glGetProgramInfoLog(prog, size, NULL, log);
std::printf("Program link failed: %s", log);
std::abort();
}
}
void init(Env& env, Shader& shd)
{
{ // Create window
env.dpy= XOpenDisplay(NULL);
if(env.dpy == NULL)
std::abort();
Window root= DefaultRootWindow(env.dpy);
GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);
if(vi == NULL)
std::abort();
Colormap cmap;
cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap= cmap;
swa.event_mask= ExposureMask | KeyPressMask;
env.win=
XCreateWindow( env.dpy,
root,
0, 0, 600, 600, 0,
vi->depth,
InputOutput,
vi->visual,
CWColormap | CWEventMask,
&swa);
XMapWindow(env.dpy, env.win);
XStoreName(env.dpy, env.win, "QM Test");
env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
glXMakeCurrent(env.dpy, env.win, env.ctx);
}
{ // Query necessary GL functions
glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
}
{ // Create shaders
{ // Vertex
shd.vs= glCreateShader(GL_VERTEX_SHADER);
glShaderSource(shd.vs, 1, &g_vs, NULL);
glCompileShader(shd.vs);
checkShaderStatus(shd.vs);
}
{ // Fragment
shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(shd.fs, 1, &g_fs, NULL);
glCompileShader(shd.fs);
checkShaderStatus(shd.fs);
}
{ // Shader program
shd.prog= glCreateProgram();
glAttachShader(shd.prog, shd.vs);
glAttachShader(shd.prog, shd.fs);
glLinkProgram(shd.prog);
checkProgramStatus(shd.prog);
}
}
{ // Setup initial GL state
glClearColor(0.0, 0.0, 0.0, 1.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
}
void quit(const Env& env, const Shader& shd)
{
{ // Close window
glXMakeCurrent(env.dpy, None, NULL);
glXDestroyContext(env.dpy, env.ctx);
XDestroyWindow(env.dpy, env.win);
XCloseDisplay(env.dpy);
}
{ // Destroy shaders
glDetachShader(shd.prog, shd.vs);
glDeleteShader(shd.vs);
glDetachShader(shd.prog, shd.fs);
glDeleteShader(shd.fs);
glDeleteProgram(shd.prog);
}
}
void draw(const Shader& shd)
{
glUseProgram(shd.prog);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum( -1.0, // left
1.0, // right
-1.0, // bottom
1.0, // top
1.0, // near
1000.0); // far
static float rot;
rot += 2;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -2.0);
glRotatef(rot, 0.9, 0.1, 0.8);
int slices= 50;
glBegin(GL_QUADS);
for (int i= 0; i < slices; ++i) {
float z= -1.0 + i*2.0/slices; // -1.0 -> 1.0
glVertex3f(-1, -1, z);
glVertex3f(1, -1, z);
glVertex3f(1, 1, z);
glVertex3f(-1, 1, z);
}
glEnd();
}
bool loop(const Env& env, const Shader& shd)
{
XWindowAttributes gwa;
XGetWindowAttributes(env.dpy, env.win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
qm::draw(shd);
usleep(1);
glXSwapBuffers(env.dpy, env.win);
while(XPending(env.dpy)) {
XEvent xev;
XNextEvent(env.dpy, &xev);
if(xev.type == KeyPress)
return false;
}
return true;
}
} // qm
int main()
{
qm::Env env;
qm::Shader shd;
qm::init(env, shd);
while(loop(env, shd));
qm::quit(env, shd);
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <sys/errno.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress("Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
// Clear bottom screen on both buffers.
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
RemoteFile file = ui_accept_remote_file();
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(confirmStream.str(), true)) {
int ret = app_install(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret);
}
ui_prompt(resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(prompt.str(), true)) {
int ret = 0;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message("Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret);
}
ui_prompt(resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<commit_msg>Update to latest ctrcommon.<commit_after>#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <sys/errno.h>
typedef enum {
INSTALL,
DELETE
} Mode;
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
bool netInstall = false;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
if(input_is_pressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
stream << "Y - Receive an app over the network" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](int progress) {
ui_display_progress("Installing", "Press B to cancel.", true, progress);
input_poll();
return !input_is_pressed(BUTTON_B);
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
return onLoop();
});
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(netInstall) {
netInstall = false;
// Clear bottom screen on both buffers.
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
screen_begin_draw(BOTTOM_SCREEN);
screen_clear(0, 0, 0);
screen_end_draw();
screen_swap_buffers();
RemoteFile file = ui_accept_remote_file();
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(ui_prompt(confirmStream.str(), true)) {
int ret = app_install(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret);
}
ui_prompt(resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(obtained) {
std::stringstream prompt;
if(mode == INSTALL) {
prompt << "Install ";
} else if(mode == DELETE) {
prompt << "Delete ";
}
prompt << "the selected title?";
if(ui_prompt(prompt.str(), true)) {
int ret = 0;
if(mode == INSTALL) {
ret = app_install_file(destination, targetInstall, onProgress);
} else if(mode == DELETE) {
ui_display_message("Deleting title...");
ret = app_delete(targetDelete);
}
std::stringstream resultMsg;
if(mode == INSTALL) {
resultMsg << "Install ";
} else if(mode == DELETE) {
resultMsg << "Delete ";
}
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << app_get_result_string(ret);
}
ui_prompt(resultMsg.str(), false);
freeSpace = fs_get_free_space(destination);
}
}
}
platform_cleanup();
return 0;
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// NSolver
//
// Created by 乔磊 on 15/3/1.
// Copyright (c) 2015年 乔磊. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <NSolver/solver/NSolver.h>
#include <NSolver/print_version.h>
int main (int argc, char *argv[])
{
using namespace dealii;
using namespace NSFEMSolver;
try
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, /* int max_num_threads */ 1);
print_version (std::cout);
deallog.depth_console (0);
char *input_file (0);
char default_input_file[10] = "input.prm";
if (argc < 2)
{
input_file = default_input_file;
}
else
{
input_file = argv[1];
}
{
const unsigned int dimension (2);
Parameters::AllParameters<dimension> solver_parameters;
SmartPointer<Parameters::AllParameters<dimension> > prt_solver_parameters (&solver_parameters);
{
ParameterHandler prm;
solver_parameters.declare_parameters (prm);
prm.read_input (input_file);
solver_parameters.parse_parameters (prm);
}
NSolver<dimension> cons (prt_solver_parameters);
cons.run();
}
}
catch (std::exception &exc)
{
std::ofstream error_info;
{
std::string filename ("slot");
filename = filename + Utilities::int_to_string (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD), 4);
filename = filename + ("_runtime.error");
error_info.open (filename.c_str());
}
if (!error_info)
{
std::cerr << " Can not open error log file! \n"
<< " Aborting!" << std::endl;
return (7);
}
error_info << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info.close();
return (2);
}
catch (...)
{
std::ofstream error_info;
{
std::string filename ("slot");
filename = filename + Utilities::int_to_string (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD), 4);
filename = filename + ("_runtime.error");
error_info.open (filename.c_str());
}
if (!error_info)
{
std::cerr << " Can not open error log file! \n"
<< " Aborting!" << std::endl;
return (7);
}
error_info << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info.close();
return (-1);
};
std::ofstream run_info ("run.success");
run_info << "Task finished successfully." << std::endl;
run_info.close();
return (0);
}
<commit_msg>print version stamp into run time log file<commit_after>//
// main.cpp
// NSolver
//
// Created by 乔磊 on 15/3/1.
// Copyright (c) 2015年 乔磊. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <NSolver/solver/NSolver.h>
#include <NSolver/print_version.h>
int main (int argc, char *argv[])
{
using namespace dealii;
using namespace NSFEMSolver;
try
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, /* int max_num_threads */ 1);
print_version (std::cout);
deallog.depth_console (0);
char *input_file (0);
char default_input_file[10] = "input.prm";
if (argc < 2)
{
input_file = default_input_file;
}
else
{
input_file = argv[1];
}
{
const unsigned int dimension (2);
Parameters::AllParameters<dimension> solver_parameters;
SmartPointer<Parameters::AllParameters<dimension> > prt_solver_parameters (&solver_parameters);
{
ParameterHandler prm;
solver_parameters.declare_parameters (prm);
prm.read_input (input_file);
solver_parameters.parse_parameters (prm);
}
NSolver<dimension> cons (prt_solver_parameters);
cons.run();
}
}
catch (std::exception &exc)
{
std::ofstream error_info;
{
std::string filename ("slot");
filename = filename + Utilities::int_to_string (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD), 4);
filename = filename + ("_runtime.error");
error_info.open (filename.c_str());
}
if (!error_info)
{
std::cerr << " Can not open error log file! \n"
<< " Aborting!" << std::endl;
return (7);
}
print_version (error_info);
error_info << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info.close();
return (2);
}
catch (...)
{
std::ofstream error_info;
{
std::string filename ("slot");
filename = filename + Utilities::int_to_string (Utilities::MPI::this_mpi_process (MPI_COMM_WORLD), 4);
filename = filename + ("_runtime.error");
error_info.open (filename.c_str());
}
if (!error_info)
{
std::cerr << " Can not open error log file! \n"
<< " Aborting!" << std::endl;
return (7);
}
print_version (error_info);
error_info << std::endl << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
error_info.close();
return (-1);
};
std::ofstream run_info ("run.success");
print_version (run_info);
run_info << "Task finished successfully." << std::endl;
run_info.close();
return (0);
}
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <iostream>
#include "Stranded.h"
int main(int argc, char* argv[])
{
std::vector<std::string> arguments;
for (int i = 1; i < argc; ++i)
{
arguments.push_back(std::string(argv[i]));
}
Stranded game;
if (game.init(arguments))
{
game.run();
}
return 0;
}
<commit_msg>Improved std::vector usage in main<commit_after>#include <iostream>
#include <string>
#include <vector>
#include "Stranded.h"
int main(int argc, char * argv[])
{
std::vector<std::string> arguments(argv+1, argv+argc);
Stranded game;
if (game.init(arguments))
{
game.run();
}
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/mathcore:$Name: $:$Id: Boost.cpp,v 1.2 2005/11/18 21:55:45 marafino Exp $
// Authors: M. Fischler 2005
/**********************************************************************
* *
* Copyright (c) 2005 , LCG ROOT FNAL MathLib Team *
* *
* *
**********************************************************************/
// Header file for class Boost, a 4x4 symmetric matrix representation of
// an axial Lorentz transformation
//
// Created by: Mark Fischler Mon Nov 1 2005
//
#include "Math/GenVector/Boost.h"
#include "Math/GenVector/LorentzVector.h"
#include "Math/GenVector/PxPyPzE4D.h"
#include "Math/GenVector/DisplacementVector3D.h"
#include "Math/GenVector/Cartesian3D.h"
#include "Math/GenVector/GenVector_exception.h"
#include <cmath>
#include <algorithm>
#ifdef TEX
A variable names bgamma appears in several places in this file. A few
words of elaboration are needed to make it's meaning clear. On page 69
of Misner, Thorne and Wheeler, (Exercise 2.7) the elements of the matrix
for a general Lorentz boost are given as
\Lambda^j'_k = \Lambda^k'_j
= (\gamma - 1) n^j n^k + \delta^{jk}
where the n^i are unit vectors in the direction of the three spatial
axes. Using the definitions, n^i = \beta_i/\beta, then, for example,
\Lambda_{xy} = (\gamma - 1) n_x n_y
= (\gamma - 1) \beta_x \beta_y/\beta^2
By definition, \gamma^2 = 1/(1 - \beta^2)
so that \gamma^2 \beta^2 = \gamma^2 - 1
or \beta^2 = (\gamma^2 - 1)/\gamma^2
If we insert this into the expression for \Lambda_{xy}, we get
\Lambda_{xy} = (\gamma - 1) \gamma^2/(\gamma^2 - 1) \beta_x \beta_y
or, finally
\Lambda_{xy} = \gamma^2/(\gamma+1) \beta_x \beta_y
The expression \gamma^2/(\gamma+1) is what we call bgamma in the code below.
#endif
namespace ROOT {
namespace Math {
Boost::Boost() {
fM[XX] = 1.0; fM[XY] = 0.0; fM[XZ] = 0.0; fM[XT] = 0.0;
fM[YY] = 1.0; fM[YZ] = 0.0; fM[YT] = 0.0;
fM[ZZ] = 1.0; fM[ZT] = 0.0;
fM[TT] = 1.0;
}
void
Boost::SetComponents (Scalar bx, Scalar by, Scalar bz) {
Scalar bp2 = bx*bx + by*by + bz*bz;
if (bp2 >= 1) {
GenVector_exception e (
"Beta Vector supplied to set Boost represents speed >= c");
Throw(e);
return;
}
Scalar gamma = 1.0 / std::sqrt(1.0 - bp2);
Scalar bgamma = gamma * gamma / (1.0 + gamma);
fM[XX] = 1.0 + bgamma * bx * bx;
fM[YY] = 1.0 + bgamma * by * by;
fM[ZZ] = 1.0 + bgamma * bz * bz;
fM[XY] = bgamma * bx * by;
fM[XZ] = bgamma * bx * bz;
fM[YZ] = bgamma * by * bz;
fM[XT] = gamma * bx;
fM[YT] = gamma * by;
fM[ZT] = gamma * bz;
fM[TT] = gamma;
}
void
Boost::GetComponents (Scalar& bx, Scalar& by, Scalar& bz) const {
Scalar gaminv = 1.0/fM[TT];
bx = fM[XT]*gaminv;
by = fM[YT]*gaminv;
bz = fM[ZT]*gaminv;
}
DisplacementVector3D< Cartesian3D<Boost::Scalar> >
Boost::BetaVector() const {
Scalar gaminv = 1.0/fM[TT];
return DisplacementVector3D< Cartesian3D<Scalar> >
( fM[XT]*gaminv, fM[YT]*gaminv, fM[ZT]*gaminv );
}
void
Boost::GetLorentzRotation (Scalar r[]) const {
r[LXX] = fM[XX]; r[LXY] = fM[XY]; r[LXZ] = fM[XZ]; r[LXT] = fM[XT];
r[LYX] = fM[XY]; r[LYY] = fM[YY]; r[LYZ] = fM[YZ]; r[LYT] = fM[YT];
r[LZX] = fM[XZ]; r[LZY] = fM[YZ]; r[LZZ] = fM[ZZ]; r[LZT] = fM[ZT];
r[LTX] = fM[XT]; r[LTY] = fM[YT]; r[LTZ] = fM[ZT]; r[LTT] = fM[TT];
}
void
Boost::
Rectify() {
// Assuming the representation of this is close to a true Lorentz Rotation,
// but may have drifted due to round-off error from many operations,
// this forms an "exact" orthosymplectic matrix for the Lorentz Rotation
// again.
if (fM[TT] <= 0) {
GenVector_exception e (
"Attempt to rectify a boost with non-positive gamma");
Throw(e);
return;
}
DisplacementVector3D< Cartesian3D<Scalar> > beta ( fM[XT], fM[YT], fM[ZT] );
beta /= fM[TT];
if ( beta.mag2() >= 1 ) {
beta /= ( beta.R() * ( 1.0 + 1.0e-16 ) );
}
SetComponents ( beta );
}
LorentzVector< PxPyPzE4D<double> >
Boost::
operator() (const LorentzVector< PxPyPzE4D<double> > & v) const {
Scalar x = v.Px();
Scalar y = v.Py();
Scalar z = v.Pz();
Scalar t = v.E();
return LorentzVector< PxPyPzE4D<double> >
( fM[XX]*x + fM[XY]*y + fM[XZ]*z + fM[XT]*t
, fM[XY]*x + fM[YY]*y + fM[YZ]*z + fM[YT]*t
, fM[XZ]*x + fM[YZ]*y + fM[ZZ]*z + fM[ZT]*t
, fM[XT]*x + fM[YT]*y + fM[ZT]*z + fM[TT]*t );
}
void
Boost::
Invert() {
fM[XT] = -fM[XT];
fM[YT] = -fM[YT];
fM[ZT] = -fM[ZT];
}
Boost
Boost::
Inverse() const {
Boost I(*this);
I.Invert();
return I;
}
} //namespace Math
} //namespace ROOT
<commit_msg>fix problem with termination charachter on Linux<commit_after>// @(#)root/mathcore:$Name: $:$Id: Boost.cxx,v 1.1 2005/11/24 14:45:50 moneta Exp $
// Authors: M. Fischler 2005
/**********************************************************************
* *
* Copyright (c) 2005 , LCG ROOT FNAL MathLib Team *
* *
* *
**********************************************************************/
// Header file for class Boost, a 4x4 symmetric matrix representation of
// an axial Lorentz transformation
//
// Created by: Mark Fischler Mon Nov 1 2005
//
#include "Math/GenVector/Boost.h"
#include "Math/GenVector/LorentzVector.h"
#include "Math/GenVector/PxPyPzE4D.h"
#include "Math/GenVector/DisplacementVector3D.h"
#include "Math/GenVector/Cartesian3D.h"
#include "Math/GenVector/GenVector_exception.h"
#include <cmath>
#include <algorithm>
#ifdef TEX
A variable names bgamma appears in several places in this file. A few
words of elaboration are needed to make its meaning clear. On page 69
of Misner, Thorne and Wheeler, (Exercise 2.7) the elements of the matrix
for a general Lorentz boost are given as
\Lambda^j'_k = \Lambda^k'_j
= (\gamma - 1) n^j n^k + \delta^{jk}
where the n^i are unit vectors in the direction of the three spatial
axes. Using the definitions, n^i = \beta_i/\beta, then, for example,
\Lambda_{xy} = (\gamma - 1) n_x n_y
= (\gamma - 1) \beta_x \beta_y/\beta^2
By definition, \gamma^2 = 1/(1 - \beta^2)
so that \gamma^2 \beta^2 = \gamma^2 - 1
or \beta^2 = (\gamma^2 - 1)/\gamma^2
If we insert this into the expression for \Lambda_{xy}, we get
\Lambda_{xy} = (\gamma - 1) \gamma^2/(\gamma^2 - 1) \beta_x \beta_y
or, finally
\Lambda_{xy} = \gamma^2/(\gamma+1) \beta_x \beta_y
The expression \gamma^2/(\gamma+1) is what we call bgamma in the code below.
#endif
namespace ROOT {
namespace Math {
Boost::Boost() {
fM[XX] = 1.0; fM[XY] = 0.0; fM[XZ] = 0.0; fM[XT] = 0.0;
fM[YY] = 1.0; fM[YZ] = 0.0; fM[YT] = 0.0;
fM[ZZ] = 1.0; fM[ZT] = 0.0;
fM[TT] = 1.0;
}
void
Boost::SetComponents (Scalar bx, Scalar by, Scalar bz) {
Scalar bp2 = bx*bx + by*by + bz*bz;
if (bp2 >= 1) {
GenVector_exception e (
"Beta Vector supplied to set Boost represents speed >= c");
Throw(e);
return;
}
Scalar gamma = 1.0 / std::sqrt(1.0 - bp2);
Scalar bgamma = gamma * gamma / (1.0 + gamma);
fM[XX] = 1.0 + bgamma * bx * bx;
fM[YY] = 1.0 + bgamma * by * by;
fM[ZZ] = 1.0 + bgamma * bz * bz;
fM[XY] = bgamma * bx * by;
fM[XZ] = bgamma * bx * bz;
fM[YZ] = bgamma * by * bz;
fM[XT] = gamma * bx;
fM[YT] = gamma * by;
fM[ZT] = gamma * bz;
fM[TT] = gamma;
}
void
Boost::GetComponents (Scalar& bx, Scalar& by, Scalar& bz) const {
Scalar gaminv = 1.0/fM[TT];
bx = fM[XT]*gaminv;
by = fM[YT]*gaminv;
bz = fM[ZT]*gaminv;
}
DisplacementVector3D< Cartesian3D<Boost::Scalar> >
Boost::BetaVector() const {
Scalar gaminv = 1.0/fM[TT];
return DisplacementVector3D< Cartesian3D<Scalar> >
( fM[XT]*gaminv, fM[YT]*gaminv, fM[ZT]*gaminv );
}
void
Boost::GetLorentzRotation (Scalar r[]) const {
r[LXX] = fM[XX]; r[LXY] = fM[XY]; r[LXZ] = fM[XZ]; r[LXT] = fM[XT];
r[LYX] = fM[XY]; r[LYY] = fM[YY]; r[LYZ] = fM[YZ]; r[LYT] = fM[YT];
r[LZX] = fM[XZ]; r[LZY] = fM[YZ]; r[LZZ] = fM[ZZ]; r[LZT] = fM[ZT];
r[LTX] = fM[XT]; r[LTY] = fM[YT]; r[LTZ] = fM[ZT]; r[LTT] = fM[TT];
}
void
Boost::
Rectify() {
// Assuming the representation of this is close to a true Lorentz Rotation,
// but may have drifted due to round-off error from many operations,
// this forms an "exact" orthosymplectic matrix for the Lorentz Rotation
// again.
if (fM[TT] <= 0) {
GenVector_exception e (
"Attempt to rectify a boost with non-positive gamma");
Throw(e);
return;
}
DisplacementVector3D< Cartesian3D<Scalar> > beta ( fM[XT], fM[YT], fM[ZT] );
beta /= fM[TT];
if ( beta.mag2() >= 1 ) {
beta /= ( beta.R() * ( 1.0 + 1.0e-16 ) );
}
SetComponents ( beta );
}
LorentzVector< PxPyPzE4D<double> >
Boost::
operator() (const LorentzVector< PxPyPzE4D<double> > & v) const {
Scalar x = v.Px();
Scalar y = v.Py();
Scalar z = v.Pz();
Scalar t = v.E();
return LorentzVector< PxPyPzE4D<double> >
( fM[XX]*x + fM[XY]*y + fM[XZ]*z + fM[XT]*t
, fM[XY]*x + fM[YY]*y + fM[YZ]*z + fM[YT]*t
, fM[XZ]*x + fM[YZ]*y + fM[ZZ]*z + fM[ZT]*t
, fM[XT]*x + fM[YT]*y + fM[ZT]*z + fM[TT]*t );
}
void
Boost::
Invert() {
fM[XT] = -fM[XT];
fM[YT] = -fM[YT];
fM[ZT] = -fM[ZT];
}
Boost
Boost::
Inverse() const {
Boost I(*this);
I.Invert();
return I;
}
} //namespace Math
} //namespace ROOT
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium OS 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 "window_manager/layer_visitor.h"
#include <algorithm>
#include "window_manager/geometry.h"
#include "window_manager/real_compositor.h"
#include "window_manager/util.h"
namespace window_manager {
using std::ceil;
using std::max;
using std::min;
using window_manager::util::NextPowerOfTwo;
enum CullingResult {
CULLING_WINDOW_OFFSCREEN,
CULLING_WINDOW_ONSCREEN,
CULLING_WINDOW_FULLSCREEN
};
const float LayerVisitor::kMinDepth = 0.0f;
const float LayerVisitor::kMaxDepth = 4096.0f + LayerVisitor::kMinDepth;
static inline float min4(float a, float b, float c, float d) {
return min(min(min(a, b), c), d);
}
static inline float max4(float a, float b, float c, float d) {
return max(max(max(a, b), c), d);
}
static inline bool IsBoxOnScreen(const LayerVisitor::BoundingBox& a) {
// The window has corners top left (-1, 1) and bottom right (1, -1).
return !(a.x_max <= -1.0 || a.x_min >= 1.0 ||
a.y_max <= -1.0 || a.y_min >= 1.0);
}
static inline bool IsBoxFullScreen(const LayerVisitor::BoundingBox& a) {
// The bounding box must be equal or greater than the area (-1, 1) - (1, -1)
// in case of full screen.
return a.x_max >= 1.0 && a.x_min <= -1.0 &&
a.y_max >= 1.0 && a.y_min <= -1.0;
}
// The input region is in window coordinates where top_left is (0, 0) and
// bottom_right is (1, 1). Output is the bounding box of the transformed window
// in GL coordinates where bottom_left is (-1, -1) and top_right is (1, 1).
static LayerVisitor::BoundingBox ComputeTransformedBoundingBox(
const RealCompositor::StageActor& stage,
const RealCompositor::QuadActor& actor,
const LayerVisitor::BoundingBox& region) {
const Matrix4& transform = stage.projection() * actor.model_view();
Vector4 v0(region.x_min, region.y_min, 0, 1);
Vector4 v1(region.x_min, region.y_max, 0, 1);
Vector4 v2(region.x_max, region.y_max, 0, 1);
Vector4 v3(region.x_max, region.y_min, 0, 1);
v0 = transform * v0;
v1 = transform * v1;
v2 = transform * v2;
v3 = transform * v3;
return LayerVisitor::BoundingBox(min4(v0[0], v1[0], v2[0], v3[0]),
max4(v0[0], v1[0], v2[0], v3[0]),
min4(v0[1], v1[1], v2[1], v3[1]),
max4(v0[1], v1[1], v2[1], v3[1]));
}
static CullingResult PerformActorCullingTest(
const RealCompositor::StageActor& stage,
const RealCompositor::QuadActor& actor) {
static const LayerVisitor::BoundingBox region(0, 1, 0, 1);
LayerVisitor::BoundingBox box =
ComputeTransformedBoundingBox(stage, actor, region);
if (!IsBoxOnScreen(box))
return CULLING_WINDOW_OFFSCREEN;
if (IsBoxFullScreen(box))
return CULLING_WINDOW_FULLSCREEN;
return CULLING_WINDOW_ONSCREEN;
}
// The input region is defined in the actor's window coordinates.
static LayerVisitor::BoundingBox MapRegionToGlCoordinates(
const RealCompositor::StageActor& stage,
const RealCompositor::TexturePixmapActor& actor,
const Rect& region) {
DCHECK(actor.width() > 0 && actor.height() > 0);
float x_min = region.x;
x_min /= actor.width();
float x_max = region.x + region.width;
x_max /= actor.width();
float y_min = region.y;
y_min /= actor.height();
float y_max = region.y + region.height;
y_max /= actor.height();
LayerVisitor::BoundingBox box(x_min, x_max, y_min, y_max);
return ComputeTransformedBoundingBox(stage, actor, box);
}
void LayerVisitor::VisitActor(RealCompositor::Actor* actor) {
actor->set_z(depth_);
depth_ += layer_thickness_;
actor->set_is_opaque(actor->opacity() > 0.999f);
}
void LayerVisitor::VisitStage(
RealCompositor::StageActor* actor) {
if (!actor->IsVisible())
return;
// This calculates the next power of two for the actor count, so
// that we can avoid roundoff errors when computing the depth.
// Also, add two empty layers at the front and the back that we
// won't use in order to avoid issues at the extremes. The eventual
// plan here is to have three depth ranges, one in the front that is
// 4096 deep, one in the back that is 4096 deep, and the remaining
// in the middle for drawing 3D UI elements. Currently, this code
// represents just the front layer range. Note that the number of
// layers is NOT limited to 4096 (this is an arbitrary value that is
// a power of two) -- the maximum number of layers depends on the
// number of actors and the bit-depth of the hardware's z-buffer.
uint32 count = NextPowerOfTwo(static_cast<uint32>(count_ + 2));
layer_thickness_ = (kMaxDepth - kMinDepth) / count;
// Don't start at the very edge of the z-buffer depth.
depth_ = kMinDepth + layer_thickness_;
stage_actor_ = actor;
top_fullscreen_actor_ = NULL;
visiting_top_visible_actor_ = true;
has_fullscreen_actor_ = false;
if (use_partial_updates_)
updated_area_.clear();
actor->UpdateProjection();
VisitContainer(actor);
}
void LayerVisitor::VisitContainer(
RealCompositor::ContainerActor* actor) {
CHECK(actor);
if (!actor->IsVisible())
return;
// No culling test for ContainerActor because the container does not bound
// its children actors. No need to set_z first because container doesn't
// use z in its model view matrix.
actor->UpdateModelView();
RealCompositor::ActorVector children = actor->GetChildren();
for (RealCompositor::ActorVector::const_iterator it = children.begin();
it != children.end(); ++it) {
if (*it)
(*it)->Accept(this);
}
// The containers should be "further" than all their children.
this->VisitActor(actor);
}
void LayerVisitor::VisitTexturedQuadActor(
RealCompositor::QuadActor* actor, bool is_texture_opaque) {
actor->set_culled(has_fullscreen_actor_);
if (!actor->IsVisible())
return;
VisitActor(actor);
actor->set_is_opaque(actor->is_opaque() && is_texture_opaque);
// Must update model view matrix before culling test.
actor->UpdateModelView();
CullingResult result =
PerformActorCullingTest(*stage_actor_, *actor);
actor->set_culled(result == CULLING_WINDOW_OFFSCREEN);
if (actor->culled())
return;
if (actor->is_opaque() && result == CULLING_WINDOW_FULLSCREEN)
has_fullscreen_actor_ = true;
visiting_top_visible_actor_ = false;
}
void LayerVisitor::VisitQuad(
RealCompositor::QuadActor* actor) {
DCHECK(actor->texture_data() == NULL);
VisitTexturedQuadActor(actor, true);
}
void LayerVisitor::VisitImage(
RealCompositor::ImageActor* actor) {
VisitTexturedQuadActor(actor, actor->IsImageOpaque());
}
void LayerVisitor::VisitTexturePixmap(
RealCompositor::TexturePixmapActor* actor) {
bool visiting_top_visible_actor = visiting_top_visible_actor_;
// OpenGlPixmapData is not created until OpenGlDrawVisitor has traversed
// through the tree, which happens after the LayerVisitor, so we cannot rely
// on actor->texture_data()->has_alpha() because texture_data() is NULL
// in the beginning.
// TODO: combine VisitQuad and VisitTexturePixmap.
VisitTexturedQuadActor(actor, actor->pixmap_is_opaque());
if (!actor->IsVisible() || actor->width() <= 0 || actor->height() <= 0)
return;
if (visiting_top_visible_actor && has_fullscreen_actor_)
top_fullscreen_actor_ = actor;
if (use_partial_updates_) {
BoundingBox region = MapRegionToGlCoordinates(
*stage_actor_,
*actor,
actor->GetDamagedRegion());
updated_area_.merge(region);
}
actor->ResetDamagedRegion();
}
Rect LayerVisitor::GetDamagedRegion(int stage_width, int stage_height) {
Rect region;
if (use_partial_updates_) {
float x_min = (updated_area_.x_min + 1.f) / 2.f * stage_width;
float y_min = (updated_area_.y_min + 1.f) / 2.f * stage_height;
float x_max = (updated_area_.x_max + 1.f) / 2.f * stage_width;
float y_max = (updated_area_.y_max + 1.f) / 2.f * stage_height;
region.x = static_cast<int>(x_min);
region.y = static_cast<int>(y_min);
// Important: To be properly conservative, the differences below need to
// happen after the conversion to int.
region.width = static_cast<int>(ceil(x_max)) - region.x;
region.height = static_cast<int>(ceil(y_max)) - region.y;
}
return region;
}
} // namespace window_manager
<commit_msg>add perspective division to computing bounding box<commit_after>// Copyright (c) 2010 The Chromium OS 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 "window_manager/layer_visitor.h"
#include <algorithm>
#include "window_manager/geometry.h"
#include "window_manager/real_compositor.h"
#include "window_manager/util.h"
namespace window_manager {
using std::ceil;
using std::max;
using std::min;
using window_manager::util::NextPowerOfTwo;
enum CullingResult {
CULLING_WINDOW_OFFSCREEN,
CULLING_WINDOW_ONSCREEN,
CULLING_WINDOW_FULLSCREEN
};
const float LayerVisitor::kMinDepth = 0.0f;
const float LayerVisitor::kMaxDepth = 4096.0f + LayerVisitor::kMinDepth;
static inline float min4(float a, float b, float c, float d) {
return min(min(min(a, b), c), d);
}
static inline float max4(float a, float b, float c, float d) {
return max(max(max(a, b), c), d);
}
static inline bool IsBoxOnScreen(const LayerVisitor::BoundingBox& a) {
// The window has corners top left (-1, 1) and bottom right (1, -1).
return !(a.x_max <= -1.0 || a.x_min >= 1.0 ||
a.y_max <= -1.0 || a.y_min >= 1.0);
}
static inline bool IsBoxFullScreen(const LayerVisitor::BoundingBox& a) {
// The bounding box must be equal or greater than the area (-1, 1) - (1, -1)
// in case of full screen.
return a.x_max >= 1.0 && a.x_min <= -1.0 &&
a.y_max >= 1.0 && a.y_min <= -1.0;
}
// The input region is in window coordinates where top_left is (0, 0) and
// bottom_right is (1, 1). Output is the bounding box of the transformed window
// in GL coordinates where bottom_left is (-1, -1) and top_right is (1, 1).
static LayerVisitor::BoundingBox ComputeTransformedBoundingBox(
const RealCompositor::StageActor& stage,
const RealCompositor::QuadActor& actor,
const LayerVisitor::BoundingBox& region) {
const Matrix4& transform = stage.projection() * actor.model_view();
Vector4 v0(region.x_min, region.y_min, 0, 1);
Vector4 v1(region.x_min, region.y_max, 0, 1);
Vector4 v2(region.x_max, region.y_max, 0, 1);
Vector4 v3(region.x_max, region.y_min, 0, 1);
v0 = transform * v0;
v1 = transform * v1;
v2 = transform * v2;
v3 = transform * v3;
v0 /= v0[3];
v1 /= v1[3];
v2 /= v2[3];
v3 /= v3[3];
return LayerVisitor::BoundingBox(min4(v0[0], v1[0], v2[0], v3[0]),
max4(v0[0], v1[0], v2[0], v3[0]),
min4(v0[1], v1[1], v2[1], v3[1]),
max4(v0[1], v1[1], v2[1], v3[1]));
}
static CullingResult PerformActorCullingTest(
const RealCompositor::StageActor& stage,
const RealCompositor::QuadActor& actor) {
static const LayerVisitor::BoundingBox region(0, 1, 0, 1);
LayerVisitor::BoundingBox box =
ComputeTransformedBoundingBox(stage, actor, region);
if (!IsBoxOnScreen(box))
return CULLING_WINDOW_OFFSCREEN;
if (IsBoxFullScreen(box))
return CULLING_WINDOW_FULLSCREEN;
return CULLING_WINDOW_ONSCREEN;
}
// The input region is defined in the actor's window coordinates.
static LayerVisitor::BoundingBox MapRegionToGlCoordinates(
const RealCompositor::StageActor& stage,
const RealCompositor::TexturePixmapActor& actor,
const Rect& region) {
DCHECK(actor.width() > 0 && actor.height() > 0);
float x_min = region.x;
x_min /= actor.width();
float x_max = region.x + region.width;
x_max /= actor.width();
float y_min = region.y;
y_min /= actor.height();
float y_max = region.y + region.height;
y_max /= actor.height();
LayerVisitor::BoundingBox box(x_min, x_max, y_min, y_max);
return ComputeTransformedBoundingBox(stage, actor, box);
}
void LayerVisitor::VisitActor(RealCompositor::Actor* actor) {
actor->set_z(depth_);
depth_ += layer_thickness_;
actor->set_is_opaque(actor->opacity() > 0.999f);
}
void LayerVisitor::VisitStage(
RealCompositor::StageActor* actor) {
if (!actor->IsVisible())
return;
// This calculates the next power of two for the actor count, so
// that we can avoid roundoff errors when computing the depth.
// Also, add two empty layers at the front and the back that we
// won't use in order to avoid issues at the extremes. The eventual
// plan here is to have three depth ranges, one in the front that is
// 4096 deep, one in the back that is 4096 deep, and the remaining
// in the middle for drawing 3D UI elements. Currently, this code
// represents just the front layer range. Note that the number of
// layers is NOT limited to 4096 (this is an arbitrary value that is
// a power of two) -- the maximum number of layers depends on the
// number of actors and the bit-depth of the hardware's z-buffer.
uint32 count = NextPowerOfTwo(static_cast<uint32>(count_ + 2));
layer_thickness_ = (kMaxDepth - kMinDepth) / count;
// Don't start at the very edge of the z-buffer depth.
depth_ = kMinDepth + layer_thickness_;
stage_actor_ = actor;
top_fullscreen_actor_ = NULL;
visiting_top_visible_actor_ = true;
has_fullscreen_actor_ = false;
if (use_partial_updates_)
updated_area_.clear();
actor->UpdateProjection();
VisitContainer(actor);
}
void LayerVisitor::VisitContainer(
RealCompositor::ContainerActor* actor) {
CHECK(actor);
if (!actor->IsVisible())
return;
// No culling test for ContainerActor because the container does not bound
// its children actors. No need to set_z first because container doesn't
// use z in its model view matrix.
actor->UpdateModelView();
RealCompositor::ActorVector children = actor->GetChildren();
for (RealCompositor::ActorVector::const_iterator it = children.begin();
it != children.end(); ++it) {
if (*it)
(*it)->Accept(this);
}
// The containers should be "further" than all their children.
this->VisitActor(actor);
}
void LayerVisitor::VisitTexturedQuadActor(
RealCompositor::QuadActor* actor, bool is_texture_opaque) {
actor->set_culled(has_fullscreen_actor_);
if (!actor->IsVisible())
return;
VisitActor(actor);
actor->set_is_opaque(actor->is_opaque() && is_texture_opaque);
// Must update model view matrix before culling test.
actor->UpdateModelView();
CullingResult result =
PerformActorCullingTest(*stage_actor_, *actor);
actor->set_culled(result == CULLING_WINDOW_OFFSCREEN);
if (actor->culled())
return;
if (actor->is_opaque() && result == CULLING_WINDOW_FULLSCREEN)
has_fullscreen_actor_ = true;
visiting_top_visible_actor_ = false;
}
void LayerVisitor::VisitQuad(
RealCompositor::QuadActor* actor) {
DCHECK(actor->texture_data() == NULL);
VisitTexturedQuadActor(actor, true);
}
void LayerVisitor::VisitImage(
RealCompositor::ImageActor* actor) {
VisitTexturedQuadActor(actor, actor->IsImageOpaque());
}
void LayerVisitor::VisitTexturePixmap(
RealCompositor::TexturePixmapActor* actor) {
bool visiting_top_visible_actor = visiting_top_visible_actor_;
// OpenGlPixmapData is not created until OpenGlDrawVisitor has traversed
// through the tree, which happens after the LayerVisitor, so we cannot rely
// on actor->texture_data()->has_alpha() because texture_data() is NULL
// in the beginning.
// TODO: combine VisitQuad and VisitTexturePixmap.
VisitTexturedQuadActor(actor, actor->pixmap_is_opaque());
if (!actor->IsVisible() || actor->width() <= 0 || actor->height() <= 0)
return;
if (visiting_top_visible_actor && has_fullscreen_actor_)
top_fullscreen_actor_ = actor;
if (use_partial_updates_) {
BoundingBox region = MapRegionToGlCoordinates(
*stage_actor_,
*actor,
actor->GetDamagedRegion());
updated_area_.merge(region);
}
actor->ResetDamagedRegion();
}
Rect LayerVisitor::GetDamagedRegion(int stage_width, int stage_height) {
Rect region;
if (use_partial_updates_) {
float x_min = (updated_area_.x_min + 1.f) / 2.f * stage_width;
float y_min = (updated_area_.y_min + 1.f) / 2.f * stage_height;
float x_max = (updated_area_.x_max + 1.f) / 2.f * stage_width;
float y_max = (updated_area_.y_max + 1.f) / 2.f * stage_height;
region.x = static_cast<int>(x_min);
region.y = static_cast<int>(y_min);
// Important: To be properly conservative, the differences below need to
// happen after the conversion to int.
region.width = static_cast<int>(ceil(x_max)) - region.x;
region.height = static_cast<int>(ceil(y_max)) - region.y;
}
return region;
}
} // namespace window_manager
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.