text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/pybind/pybind.h"
#include "paddle/fluid/string/string_helper.h"
std::map<std::string, std::set<std::string>> op_ins_map = {
{"layer_norm", {"X", "Scale", "Bias"}},
{"gru_unit", {"Input", "HiddenPrev", "Weight", "Bias"}},
{"label_smooth", {"X", "PriorDist"}},
{"assign", {"X"}},
};
std::map<std::string, std::set<std::string>> op_passing_out_map = {
{"sgd", {"ParamOut"}},
{"adam",
{"ParamOut", "Moment1Out", "Moment2Out", "Beta1PowOut", "Beta2PowOut"}},
{"momentum", {"ParamOut", "VelocityOut"}},
{"batch_norm", {"MeanOut", "VarianceOut"}},
{"accuracy", {"Correct", "Total"}},
{"fill_constant", {"Out"}},
{"matmul", {"Out"}}};
// clang-format off
const char* OUT_INITIALIZER_TEMPLATE =
R"({"%s", {std::shared_ptr<imperative::VarBase>(new imperative::VarBase(tracer->GenerateUniqueName()))}})";
const char* OUT_DUPLICABLE_INITIALIZER_TEMPLATE = R"({"%s", ConstructDuplicableOutput(%s)})";
const char* INPUT_INITIALIZER_TEMPLATE = R"({"%s", {%s}})";
const char* INPUT_LIST_INITIALIZER_TEMPLATE = R"({"%s", %s})";
const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL = R"(
if (%s != nullptr) {
ins["%s"] = {%s};
}
)";
const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST = R"(
if (%s != nullptr) {
ins["%s"] = %s;
}
)";
// if inputs is list, no need {}
const char* ARG_OUT_NUM = R"(%sNum)";
const char* ARG_OUT_NUM_TYPE = R"(size_t )";
const char* VAR_TYPE = R"(std::shared_ptr<imperative::VarBase>)";
const char* VAR_LIST_TYPE = R"(std::vector<std::shared_ptr<imperative::VarBase>>)";
const char* ARG_TEMPLATE = R"(const %s& %s)";
const char* RETURN_TUPLE_TYPE = R"(std::tuple<%s>)";
const char* RETURN_TYPE = R"(%s)";
const char* RETURN_TUPLE_TEMPLATE = R"(std::make_tuple(%s))";
const char* RETURN_LIST_TEMPLATE = R"(outs["%s"])";
const char* RETURN_TEMPLATE = R"(outs["%s"][0])";
const char* FUNCTION_ARGS = R"(%s, const py::args& args)";
const char* FUNCTION_ARGS_NO_INPUT = R"(const py::args& args)";
const char* OP_FUNCTION_TEMPLATE =
R"(
%s %s(%s)
{
framework::AttributeMap attrs;
ConstructAttrMapFromPyArgs(&attrs, args);
{
py::gil_scoped_release release;
auto tracer = imperative::GetCurrentTracer();
imperative::NameVarBaseMap outs = %s;
imperative::NameVarBaseMap ins = %s;
%s
tracer->TraceOp("%s", ins, outs, attrs);
return %s;
}
})";
const char* PYBIND_ITEM_TEMPLATE = R"( %s.def("%s", &%s);)";
// clang-format on
static inline bool FindInputInSpecialization(const std::string& op_type,
const std::string& in_name) {
return op_ins_map[op_type].count(in_name);
}
static inline bool FindOutoutInSpecialization(const std::string& op_type,
const std::string& out_name) {
return op_passing_out_map[op_type].count(out_name);
}
static std::tuple<std::vector<std::string>, std::vector<std::string>>
GenerateOpFunctions(const std::string& module_name) {
auto& op_info_map = paddle::framework::OpInfoMap::Instance().map();
std::vector<std::string> op_function_list, bind_function_list;
auto& all_kernels = paddle::framework::OperatorWithKernel::AllOpKernels();
for (auto& pair : op_info_map) {
auto& op_info = pair.second;
auto op_proto = op_info.proto_;
if (op_proto == nullptr) {
continue;
}
auto& op_type = op_proto->type();
// Skip ooerator which is not inherit form OperatorWithKernel, like while,
// since only OperatorWithKernel can run in dygraph mode.
if (!all_kernels.count(op_type)) {
continue;
}
std::string input_args = "";
std::string ins_initializer = "{";
std::string ins_initializer_with_null = "";
std::string py_arg = "";
for (auto& input : op_proto->inputs()) {
auto& in_name = input.name();
// skip those dispensable inputs, like ResidualData in conv2d
if (input.dispensable() && !FindInputInSpecialization(op_type, in_name)) {
continue;
}
const auto in_type = input.duplicable() ? VAR_LIST_TYPE : VAR_TYPE;
auto input_arg = paddle::string::Sprintf(ARG_TEMPLATE, in_type, in_name);
input_args += input_arg;
input_args += ",";
if (input.dispensable()) {
const auto in_template = input.duplicable()
? INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST
: INPUT_INITIALIZER_TEMPLATE_WITH_NULL;
ins_initializer_with_null +=
paddle::string::Sprintf(in_template, in_name, in_name, in_name);
} else {
const auto in_template = input.duplicable()
? INPUT_LIST_INITIALIZER_TEMPLATE
: INPUT_INITIALIZER_TEMPLATE;
ins_initializer +=
paddle::string::Sprintf(in_template, in_name, in_name);
ins_initializer += ",";
}
}
if (ins_initializer.back() == ',') {
ins_initializer.pop_back();
}
ins_initializer += "}";
if (input_args.back() == ',') {
input_args.pop_back();
}
// Generate outs initializer
std::string outs_initializer = "{";
std::string return_type = "";
std::string return_str = "";
int outs_num = 0;
for (auto& output : op_proto->outputs()) {
if (output.dispensable()) {
continue;
}
const auto out_type = output.duplicable() ? VAR_LIST_TYPE : VAR_TYPE;
const auto return_template =
output.duplicable() ? RETURN_LIST_TEMPLATE : RETURN_TEMPLATE;
auto& out_name = output.name();
std::string out_initializer_str;
if (FindOutoutInSpecialization(op_type, out_name)) {
if (input_args != "") {
input_args += ",";
}
input_args += out_type;
input_args += out_name;
const auto out_template = output.duplicable()
? INPUT_LIST_INITIALIZER_TEMPLATE
: INPUT_INITIALIZER_TEMPLATE;
out_initializer_str +=
paddle::string::Sprintf(out_template, out_name, out_name);
} else {
// There are few Operators that have duplicable output, like `Out` in
// split op. We need to specify the number of variables for the
// duplicable output, as the argument OutNum;
if (output.duplicable()) {
if (input_args != "") {
input_args += ",";
}
auto out_num_str = paddle::string::Sprintf(ARG_OUT_NUM, out_name);
input_args += ARG_OUT_NUM_TYPE;
input_args += out_num_str;
out_initializer_str = paddle::string::Sprintf(
OUT_DUPLICABLE_INITIALIZER_TEMPLATE, out_name, out_num_str);
} else {
out_initializer_str =
paddle::string::Sprintf(OUT_INITIALIZER_TEMPLATE, out_name);
}
}
return_type += out_type;
return_type += ",";
return_str += paddle::string::Sprintf(return_template, out_name);
return_str += ",";
outs_num += 1;
outs_initializer += out_initializer_str;
outs_initializer += ",";
}
if (outs_initializer.back() == ',') {
outs_initializer.pop_back();
return_type.pop_back();
return_str.pop_back();
}
outs_initializer += "}";
if (outs_num == 0) {
return_type = "void";
}
if (outs_num > 1) {
return_str = paddle::string::Sprintf(RETURN_TUPLE_TEMPLATE, return_str);
return_type = paddle::string::Sprintf(RETURN_TUPLE_TYPE, return_type);
}
std::string function_args = "";
if (input_args == "") {
function_args = FUNCTION_ARGS_NO_INPUT;
} else {
function_args = paddle::string::Sprintf(FUNCTION_ARGS, input_args);
}
std::string func_name = "imperative_" + op_type;
// generate op funtcion body
auto op_function_str = paddle::string::Sprintf(
OP_FUNCTION_TEMPLATE, return_type, func_name, function_args,
outs_initializer, ins_initializer, ins_initializer_with_null, op_type,
return_str);
// generate pybind item
auto bind_function_str = paddle::string::Sprintf(
PYBIND_ITEM_TEMPLATE, module_name, op_type, func_name);
op_function_list.emplace_back(std::move(op_function_str));
bind_function_list.emplace_back(std::move(bind_function_str));
}
return std::make_tuple(op_function_list, bind_function_list);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "argc must be 2" << std::endl;
return -1;
}
std::vector<std::string> headers{"\"paddle/fluid/imperative/tracer.h\""};
std::ofstream out(argv[1], std::ios::out);
out << "#pragma once\n\n";
for (auto& header : headers) {
out << "#include " + header + "\n";
}
auto op_funcs = GenerateOpFunctions("m");
out << "namespace py = pybind11;"
<< "\n";
out << "namespace paddle {\n"
<< "namespace pybind {\n";
out << paddle::string::join_strings(std::get<0>(op_funcs), '\n');
out << "\n\n";
out << "inline void BindOpFunctions(pybind11::module *module) {\n"
<< " auto m = module->def_submodule(\"ops\");\n\n";
out << paddle::string::join_strings(std::get<1>(op_funcs), '\n');
out << "\n";
out << "}\n\n"
<< "} // namespace pybind\n"
<< "} // namespace paddle\n";
out.close();
return 0;
}
<commit_msg>specify outs, test=develop (#24537)<commit_after>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/pybind/pybind.h"
#include "paddle/fluid/string/string_helper.h"
// NOTE(zhiqiu): Commonly, the inputs in auto-generated OP function are
// determined by the OP`s proto automatically, i.e., all the inputs registered
// in OpMaker.
// However, some OPs have dispensable inputs, which means the input can
// be none for some conditions. It is discovered that most dispensable inputs
// is not used in imperative mode, so we drop those inputs when generating OP
// functions. While, for very few OPs, the dispensable inputs are used, we
// need to manually specify them in this map.
std::map<std::string, std::set<std::string>> op_ins_map = {
{"layer_norm", {"X", "Scale", "Bias"}},
{"gru_unit", {"Input", "HiddenPrev", "Weight", "Bias"}},
{"label_smooth", {"X", "PriorDist"}},
{"assign", {"X"}},
{"fake_quantize_dequantize_moving_average_abs_max",
{"X", "InScale", "InAccum", "InState"}},
};
// NOTE(zhiqiu): Like op_ins_map.
// Commonly, the outputs in auto-generated OP function are determined by the
// OP`s proto automatically, i.e., all the outputs registered in OpMaker.
// However, some OPs have dispensable outputs, which means the output can
// be none for some conditions. It is discovered that most dispensable outputs
// is not used in imperative mode, so we drop those outputs when generating OP
// functions. While, for very few OPs, the dispensable outputs are used, we
// need to manually specify them in this map.
std::map<std::string, std::set<std::string>> op_outs_map = {
{"fake_quantize_dequantize_moving_average_abs_max",
{"Out", "OutScale", "OutAccum", "OutState"}},
};
// NOTE(zhiqiu): Commonly, the outputs in auto-generated OP function are
// generated in C++ automatically.
// However, some OPs need to pass the outputs from Python instead of generating
// them in C++. There are mainly 2 reasons for that,
// (1) Optimizer OPs need to update the input param in-place, like sgd.
// So they need to pass the output which is same as input param.
// (2) Very few python APIs has out in their arguments, like fill_constant.
// So they need to pass the python output to C++.
// Actually, this is not a good design, since it may break the SSA graph,
// especially in declarative mode.
// For those OPs, we need to manually specify the outs need to pass in this map.
std::map<std::string, std::set<std::string>> op_passing_outs_map = {
{"sgd", {"ParamOut"}},
{"adam",
{"ParamOut", "Moment1Out", "Moment2Out", "Beta1PowOut", "Beta2PowOut"}},
{"momentum", {"ParamOut", "VelocityOut"}},
{"batch_norm", {"MeanOut", "VarianceOut"}},
{"accuracy", {"Correct", "Total"}},
{"fill_constant", {"Out"}},
{"matmul", {"Out"}},
{"fake_quantize_dequantize_moving_average_abs_max",
{"OutScale", "OutAccum", "OutState"}},
};
// clang-format off
const char* OUT_INITIALIZER_TEMPLATE =
R"({"%s", {std::shared_ptr<imperative::VarBase>(new imperative::VarBase(tracer->GenerateUniqueName()))}})";
const char* OUT_DUPLICABLE_INITIALIZER_TEMPLATE = R"({"%s", ConstructDuplicableOutput(%s)})";
const char* INPUT_INITIALIZER_TEMPLATE = R"({"%s", {%s}})";
const char* INPUT_LIST_INITIALIZER_TEMPLATE = R"({"%s", %s})";
const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL = R"(
if (%s != nullptr) {
ins["%s"] = {%s};
}
)";
const char* INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST = R"(
if (%s.size() != 0) {
ins["%s"] = %s;
}
)";
const char* OUTPUT_INITIALIZER_TEMPLATE_WITH_NULL = R"(
if (%s != nullptr) {
outs["%s"] = {%s};
}
)";
const char* OUTPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST = R"(
if (%s.size() != 0) {
outs["%s"] = %s;
}
)";
// if inputs is list, no need {}
const char* ARG_OUT_NUM = R"(%sNum)";
const char* ARG_OUT_NUM_TYPE = R"(size_t )";
const char* VAR_TYPE = R"(std::shared_ptr<imperative::VarBase>)";
const char* VAR_LIST_TYPE = R"(std::vector<std::shared_ptr<imperative::VarBase>>)";
const char* ARG_TEMPLATE = R"(const %s& %s)";
const char* RETURN_TUPLE_TYPE = R"(std::tuple<%s>)";
const char* RETURN_TYPE = R"(%s)";
const char* RETURN_TUPLE_TEMPLATE = R"(std::make_tuple(%s))";
const char* RETURN_LIST_TEMPLATE = R"(outs["%s"])";
const char* RETURN_TEMPLATE = R"(outs["%s"][0])";
const char* FUNCTION_ARGS = R"(%s, const py::args& args)";
const char* FUNCTION_ARGS_NO_INPUT = R"(const py::args& args)";
const char* OP_FUNCTION_TEMPLATE =
R"(
%s %s(%s)
{
framework::AttributeMap attrs;
ConstructAttrMapFromPyArgs(&attrs, args);
{
py::gil_scoped_release release;
auto tracer = imperative::GetCurrentTracer();
imperative::NameVarBaseMap outs = %s;
imperative::NameVarBaseMap ins = %s;
%s
tracer->TraceOp("%s", ins, outs, attrs);
return %s;
}
})";
const char* PYBIND_ITEM_TEMPLATE = R"( %s.def("%s", &%s);)";
// clang-format on
static inline bool FindInsMap(const std::string& op_type,
const std::string& in_name) {
return op_ins_map[op_type].count(in_name);
}
static inline bool FindOutsMap(const std::string& op_type,
const std::string& out_name) {
return op_outs_map[op_type].count(out_name);
}
static inline bool FindPassingOutsMap(const std::string& op_type,
const std::string& out_name) {
return op_passing_outs_map[op_type].count(out_name);
}
static std::tuple<std::vector<std::string>, std::vector<std::string>>
GenerateOpFunctions(const std::string& module_name) {
auto& op_info_map = paddle::framework::OpInfoMap::Instance().map();
std::vector<std::string> op_function_list, bind_function_list;
auto& all_kernels = paddle::framework::OperatorWithKernel::AllOpKernels();
for (auto& pair : op_info_map) {
auto& op_info = pair.second;
auto op_proto = op_info.proto_;
if (op_proto == nullptr) {
continue;
}
auto& op_type = op_proto->type();
// Skip ooerator which is not inherit form OperatorWithKernel, like while,
// since only OperatorWithKernel can run in dygraph mode.
if (!all_kernels.count(op_type)) {
continue;
}
std::string input_args = "";
std::string ins_initializer = "{";
std::string ins_initializer_with_null = "";
std::string py_arg = "";
for (auto& input : op_proto->inputs()) {
auto& in_name = input.name();
// skip those dispensable inputs, like ResidualData in conv2d
if (input.dispensable() && !FindInsMap(op_type, in_name)) {
continue;
}
const auto in_type = input.duplicable() ? VAR_LIST_TYPE : VAR_TYPE;
auto input_arg = paddle::string::Sprintf(ARG_TEMPLATE, in_type, in_name);
input_args += input_arg;
input_args += ",";
if (input.dispensable()) {
const auto in_template = input.duplicable()
? INPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST
: INPUT_INITIALIZER_TEMPLATE_WITH_NULL;
ins_initializer_with_null +=
paddle::string::Sprintf(in_template, in_name, in_name, in_name);
} else {
const auto in_template = input.duplicable()
? INPUT_LIST_INITIALIZER_TEMPLATE
: INPUT_INITIALIZER_TEMPLATE;
ins_initializer +=
paddle::string::Sprintf(in_template, in_name, in_name);
ins_initializer += ",";
}
}
if (ins_initializer.back() == ',') {
ins_initializer.pop_back();
}
ins_initializer += "}";
if (input_args.back() == ',') {
input_args.pop_back();
}
// Generate outs initializer
std::string outs_initializer = "{";
std::string outs_initializer_with_null = "";
std::string return_type = "";
std::string return_str = "";
int outs_num = 0;
for (auto& output : op_proto->outputs()) {
auto& out_name = output.name();
// skip those dispensable oututs
if (output.dispensable() && !FindOutsMap(op_type, out_name)) {
continue;
}
const auto out_type = output.duplicable() ? VAR_LIST_TYPE : VAR_TYPE;
const auto return_template =
output.duplicable() ? RETURN_LIST_TEMPLATE : RETURN_TEMPLATE;
if (FindPassingOutsMap(op_type, out_name)) {
if (input_args != "") {
input_args += ",";
}
input_args += out_type;
input_args += out_name;
if (output.dispensable()) {
const auto out_template =
output.duplicable() ? OUTPUT_INITIALIZER_TEMPLATE_WITH_NULL_LIST
: OUTPUT_INITIALIZER_TEMPLATE_WITH_NULL;
outs_initializer_with_null += paddle::string::Sprintf(
out_template, out_name, out_name, out_name);
} else {
const auto out_template = output.duplicable()
? INPUT_LIST_INITIALIZER_TEMPLATE
: INPUT_INITIALIZER_TEMPLATE;
outs_initializer +=
paddle::string::Sprintf(out_template, out_name, out_name);
outs_initializer += ",";
}
} else {
// There are few Operators that have duplicable output, like `Out` in
// split op. We need to specify the number of variables for the
// duplicable output, as the argument OutNum;
if (output.duplicable()) {
if (input_args != "") {
input_args += ",";
}
auto out_num_str = paddle::string::Sprintf(ARG_OUT_NUM, out_name);
input_args += ARG_OUT_NUM_TYPE;
input_args += out_num_str;
outs_initializer += paddle::string::Sprintf(
OUT_DUPLICABLE_INITIALIZER_TEMPLATE, out_name, out_num_str);
} else {
outs_initializer +=
paddle::string::Sprintf(OUT_INITIALIZER_TEMPLATE, out_name);
}
outs_initializer += ",";
}
return_type += out_type;
return_type += ",";
return_str += paddle::string::Sprintf(return_template, out_name);
return_str += ",";
outs_num += 1;
}
if (outs_initializer.back() == ',') {
outs_initializer.pop_back();
return_type.pop_back();
return_str.pop_back();
}
outs_initializer += "}";
if (outs_num == 0) {
return_type = "void";
}
if (outs_num > 1) {
return_str = paddle::string::Sprintf(RETURN_TUPLE_TEMPLATE, return_str);
return_type = paddle::string::Sprintf(RETURN_TUPLE_TYPE, return_type);
}
std::string function_args = "";
if (input_args == "") {
function_args = FUNCTION_ARGS_NO_INPUT;
} else {
function_args = paddle::string::Sprintf(FUNCTION_ARGS, input_args);
}
std::string func_name = "imperative_" + op_type;
// generate op funtcion body
auto op_function_str = paddle::string::Sprintf(
OP_FUNCTION_TEMPLATE, return_type, func_name, function_args,
outs_initializer, ins_initializer,
ins_initializer_with_null + outs_initializer_with_null, op_type,
return_str);
// generate pybind item
auto bind_function_str = paddle::string::Sprintf(
PYBIND_ITEM_TEMPLATE, module_name, op_type, func_name);
op_function_list.emplace_back(std::move(op_function_str));
bind_function_list.emplace_back(std::move(bind_function_str));
}
return std::make_tuple(op_function_list, bind_function_list);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "argc must be 2" << std::endl;
return -1;
}
std::vector<std::string> headers{"\"paddle/fluid/imperative/tracer.h\""};
std::ofstream out(argv[1], std::ios::out);
out << "#pragma once\n\n";
for (auto& header : headers) {
out << "#include " + header + "\n";
}
auto op_funcs = GenerateOpFunctions("m");
out << "namespace py = pybind11;"
<< "\n";
out << "namespace paddle {\n"
<< "namespace pybind {\n";
out << paddle::string::join_strings(std::get<0>(op_funcs), '\n');
out << "\n\n";
out << "inline void BindOpFunctions(pybind11::module *module) {\n"
<< " auto m = module->def_submodule(\"ops\");\n\n";
out << paddle::string::join_strings(std::get<1>(op_funcs), '\n');
out << "\n";
out << "}\n\n"
<< "} // namespace pybind\n"
<< "} // namespace paddle\n";
out.close();
return 0;
}
<|endoftext|> |
<commit_before>// Filename: collisionHandlerPusher.cxx
// Created by: drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// [email protected] .
//
////////////////////////////////////////////////////////////////////
#include "collisionHandlerPusher.h"
#include "collisionNode.h"
#include "collisionEntry.h"
#include "collisionPolygon.h"
#include "config_collide.h"
#include "dcast.h"
TypeHandle CollisionHandlerPusher::_type_handle;
///////////////////////////////////////////////////////////////////
// Class : ShoveData
// Description : The ShoveData class is used within
// CollisionHandlerPusher::handle_entries(), to track
// multiple shoves onto a given collider. It's not
// exported outside this file.
////////////////////////////////////////////////////////////////////
class ShoveData {
public:
LVector3f _vector;
float _length;
bool _valid;
CollisionEntry *_entry;
};
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerPusher::
CollisionHandlerPusher() {
_horizontal = true;
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerPusher::
~CollisionHandlerPusher() {
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::handle_entries
// Access: Protected, Virtual
// Description: Called by the parent class after all collisions have
// been detected, this manages the various collisions
// and moves around the nodes as necessary.
//
// The return value is normally true, but it may be
// false to indicate the CollisionTraverser should
// disable this handler from being called in the future.
////////////////////////////////////////////////////////////////////
bool CollisionHandlerPusher::
handle_entries() {
bool okflag = true;
FromEntries::const_iterator fi;
for (fi = _from_entries.begin(); fi != _from_entries.end(); ++fi) {
CollisionNode *from_node = (*fi).first;
nassertr(from_node != (CollisionNode *)NULL, false);
const Entries &entries = (*fi).second;
Colliders::iterator ci;
ci = _colliders.find(from_node);
if (ci == _colliders.end()) {
// Hmm, someone added a CollisionNode to a traverser and gave
// it this CollisionHandler pointer--but they didn't tell us
// about the node.
collide_cat.error()
<< "CollisionHandlerPusher doesn't know about "
<< *from_node << ", disabling.\n";
okflag = false;
} else {
ColliderDef &def = (*ci).second;
if (!def.is_valid()) {
collide_cat.error()
<< "Removing invalid collider " << *from_node << " from "
<< get_type() << "\n";
_colliders.erase(ci);
} else {
// How to apply multiple shoves from different solids onto the
// same collider? One's first intuition is to vector sum all
// the shoves. However, this causes problems when two parallel
// walls shove on the collider, because we end up with a double
// shove. We hack around this by testing if two shove vectors
// share nearly the same direction, and if so, we keep only the
// longer of the two.
typedef pvector<ShoveData> Shoves;
Shoves shoves;
Entries::const_iterator ei;
for (ei = entries.begin(); ei != entries.end(); ++ei) {
CollisionEntry *entry = (*ei);
nassertr(entry != (CollisionEntry *)NULL, false);
nassertr(from_node == entry->get_from_node(), false);
if (!entry->has_from_surface_normal() ||
!entry->has_from_depth()) {
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Cannot shove on " << *from_node << " for collision into "
<< *entry->get_into_node() << "; no normal/depth information.\n";
}
#endif
} else {
// Shove it just enough to clear the volume.
if (entry->get_from_depth() != 0.0f) {
LVector3f normal = entry->get_from_surface_normal();
if (_horizontal) {
normal[2] = 0.0f;
}
// Just to be on the safe size, we normalize the normal
// vector, even though it really ought to be unit-length
// already (unless we just forced it horizontal, above).
normal.normalize();
ShoveData sd;
sd._vector = normal;
sd._length = entry->get_from_depth();
sd._valid = true;
sd._entry = entry;
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Shove on " << *from_node << " from "
<< *entry->get_into_node() << ": " << sd._vector
<< " times " << sd._length << "\n";
}
#endif
shoves.push_back(sd);
}
}
}
if (!shoves.empty()) {
// Now we look for two shoves that are largely in the same
// direction, so we can combine them into a single shove of
// the same magnitude; we also check for two shoves at 90
// degrees, so we can detect whether we are hitting an inner
// or an outer corner.
Shoves::iterator si;
for (si = shoves.begin(); si != shoves.end(); ++si) {
ShoveData &sd = (*si);
Shoves::iterator sj;
for (sj = shoves.begin(); sj != si; ++sj) {
ShoveData &sd2 = (*sj);
if (sd2._valid) {
float d = sd._vector.dot(sd2._vector);
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Considering dot product " << d << "\n";
}
if (d > 0.9) {
// These two shoves are largely in the same direction;
// save the larger of the two.
if (sd2._length < sd._length) {
sd2._valid = false;
} else {
sd._valid = false;
}
} else {
// These two shoves are not in the same direction.
// If they are both from polygons that are a child
// of the same node, try to determine the shape of
// the corner (convex or concave).
const CollisionSolid *s1 = sd._entry->get_into();
const CollisionSolid *s2 = sd2._entry->get_into();
if (s1 != (CollisionSolid *)NULL &&
s2 != (CollisionSolid *)NULL &&
s1->is_exact_type(CollisionPolygon::get_class_type()) &&
s2->is_exact_type(CollisionPolygon::get_class_type()) &&
sd._entry->get_into_node_path() ==
sd2._entry->get_into_node_path()) {
const CollisionPolygon *p1 = DCAST(CollisionPolygon, s1);
const CollisionPolygon *p2 = DCAST(CollisionPolygon, s2);
if (p1->dist_to_plane(p2->get_collision_origin()) < 0 &&
p2->dist_to_plane(p1->get_collision_origin()) < 0) {
// Each polygon is behind the other one. That
// means we have a convex corner, and therefore
// we should discard one of the shoves (or the
// user will get stuck coming at a convex
// corner).
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Discarding shove from convex corner.\n";
}
// This time, unlike the case of two parallel
// walls above, we discard the larger of the two
// shoves, not the smaller. This is because as
// we slide off the convex corner, the wall we
// are sliding away from will get a bigger and
// bigger shove--and we need to keep ignoring
// the same wall as we slide.
if (sd2._length < sd._length) {
sd._valid = false;
} else {
sd2._valid = false;
}
}
}
}
}
}
}
// Now we can determine the net shove.
LVector3f net_shove(0.0f, 0.0f, 0.0f);
LVector3f force_normal(0.0f, 0.0f, 0.0f);
for (si = shoves.begin(); si != shoves.end(); ++si) {
const ShoveData &sd = (*si);
if (sd._valid) {
net_shove += sd._vector * sd._length;
force_normal += sd._vector;
}
}
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Net shove on " << *from_node << " is: "
<< net_shove << "\n";
}
#endif
if (def._node != (PandaNode *)NULL) {
// If we are adjusting a plain PandaNode, get the
// transform and adjust just the position to preserve
// maximum precision.
CPT(TransformState) trans = def._node->get_transform();
LVecBase3f pos = trans->get_pos();
pos += net_shove * trans->get_mat();
def._node->set_transform(trans->set_pos(pos));
} else {
// Otherwise, go ahead and do the matrix math to do things
// the old and clumsy way.
LMatrix4f mat;
def.get_mat(mat);
def.set_mat(LMatrix4f::translate_mat(net_shove) * mat);
}
apply_linear_force(def, force_normal);
}
}
}
}
return okflag;
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::apply_linear_force
// Access: Protected, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void CollisionHandlerPusher::
apply_linear_force(ColliderDef &, const LVector3f &) {
}
<commit_msg>calling apply_linear_force if node is a PandaNode<commit_after>// Filename: collisionHandlerPusher.cxx
// Created by: drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// [email protected] .
//
////////////////////////////////////////////////////////////////////
#include "collisionHandlerPusher.h"
#include "collisionNode.h"
#include "collisionEntry.h"
#include "collisionPolygon.h"
#include "config_collide.h"
#include "dcast.h"
TypeHandle CollisionHandlerPusher::_type_handle;
///////////////////////////////////////////////////////////////////
// Class : ShoveData
// Description : The ShoveData class is used within
// CollisionHandlerPusher::handle_entries(), to track
// multiple shoves onto a given collider. It's not
// exported outside this file.
////////////////////////////////////////////////////////////////////
class ShoveData {
public:
LVector3f _vector;
float _length;
bool _valid;
CollisionEntry *_entry;
};
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerPusher::
CollisionHandlerPusher() {
_horizontal = true;
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerPusher::
~CollisionHandlerPusher() {
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::handle_entries
// Access: Protected, Virtual
// Description: Called by the parent class after all collisions have
// been detected, this manages the various collisions
// and moves around the nodes as necessary.
//
// The return value is normally true, but it may be
// false to indicate the CollisionTraverser should
// disable this handler from being called in the future.
////////////////////////////////////////////////////////////////////
bool CollisionHandlerPusher::
handle_entries() {
bool okflag = true;
FromEntries::const_iterator fi;
for (fi = _from_entries.begin(); fi != _from_entries.end(); ++fi) {
CollisionNode *from_node = (*fi).first;
nassertr(from_node != (CollisionNode *)NULL, false);
const Entries &entries = (*fi).second;
Colliders::iterator ci;
ci = _colliders.find(from_node);
if (ci == _colliders.end()) {
// Hmm, someone added a CollisionNode to a traverser and gave
// it this CollisionHandler pointer--but they didn't tell us
// about the node.
collide_cat.error()
<< "CollisionHandlerPusher doesn't know about "
<< *from_node << ", disabling.\n";
okflag = false;
} else {
ColliderDef &def = (*ci).second;
if (!def.is_valid()) {
collide_cat.error()
<< "Removing invalid collider " << *from_node << " from "
<< get_type() << "\n";
_colliders.erase(ci);
} else {
// How to apply multiple shoves from different solids onto the
// same collider? One's first intuition is to vector sum all
// the shoves. However, this causes problems when two parallel
// walls shove on the collider, because we end up with a double
// shove. We hack around this by testing if two shove vectors
// share nearly the same direction, and if so, we keep only the
// longer of the two.
typedef pvector<ShoveData> Shoves;
Shoves shoves;
Entries::const_iterator ei;
for (ei = entries.begin(); ei != entries.end(); ++ei) {
CollisionEntry *entry = (*ei);
nassertr(entry != (CollisionEntry *)NULL, false);
nassertr(from_node == entry->get_from_node(), false);
if (!entry->has_from_surface_normal() ||
!entry->has_from_depth()) {
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Cannot shove on " << *from_node << " for collision into "
<< *entry->get_into_node() << "; no normal/depth information.\n";
}
#endif
} else {
// Shove it just enough to clear the volume.
if (entry->get_from_depth() != 0.0f) {
LVector3f normal = entry->get_from_surface_normal();
if (_horizontal) {
normal[2] = 0.0f;
}
// Just to be on the safe size, we normalize the normal
// vector, even though it really ought to be unit-length
// already (unless we just forced it horizontal, above).
normal.normalize();
ShoveData sd;
sd._vector = normal;
sd._length = entry->get_from_depth();
sd._valid = true;
sd._entry = entry;
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Shove on " << *from_node << " from "
<< *entry->get_into_node() << ": " << sd._vector
<< " times " << sd._length << "\n";
}
#endif
shoves.push_back(sd);
}
}
}
if (!shoves.empty()) {
// Now we look for two shoves that are largely in the same
// direction, so we can combine them into a single shove of
// the same magnitude; we also check for two shoves at 90
// degrees, so we can detect whether we are hitting an inner
// or an outer corner.
Shoves::iterator si;
for (si = shoves.begin(); si != shoves.end(); ++si) {
ShoveData &sd = (*si);
Shoves::iterator sj;
for (sj = shoves.begin(); sj != si; ++sj) {
ShoveData &sd2 = (*sj);
if (sd2._valid) {
float d = sd._vector.dot(sd2._vector);
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Considering dot product " << d << "\n";
}
if (d > 0.9) {
// These two shoves are largely in the same direction;
// save the larger of the two.
if (sd2._length < sd._length) {
sd2._valid = false;
} else {
sd._valid = false;
}
} else {
// These two shoves are not in the same direction.
// If they are both from polygons that are a child
// of the same node, try to determine the shape of
// the corner (convex or concave).
const CollisionSolid *s1 = sd._entry->get_into();
const CollisionSolid *s2 = sd2._entry->get_into();
if (s1 != (CollisionSolid *)NULL &&
s2 != (CollisionSolid *)NULL &&
s1->is_exact_type(CollisionPolygon::get_class_type()) &&
s2->is_exact_type(CollisionPolygon::get_class_type()) &&
sd._entry->get_into_node_path() ==
sd2._entry->get_into_node_path()) {
const CollisionPolygon *p1 = DCAST(CollisionPolygon, s1);
const CollisionPolygon *p2 = DCAST(CollisionPolygon, s2);
if (p1->dist_to_plane(p2->get_collision_origin()) < 0 &&
p2->dist_to_plane(p1->get_collision_origin()) < 0) {
// Each polygon is behind the other one. That
// means we have a convex corner, and therefore
// we should discard one of the shoves (or the
// user will get stuck coming at a convex
// corner).
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Discarding shove from convex corner.\n";
}
// This time, unlike the case of two parallel
// walls above, we discard the larger of the two
// shoves, not the smaller. This is because as
// we slide off the convex corner, the wall we
// are sliding away from will get a bigger and
// bigger shove--and we need to keep ignoring
// the same wall as we slide.
if (sd2._length < sd._length) {
sd._valid = false;
} else {
sd2._valid = false;
}
}
}
}
}
}
}
// Now we can determine the net shove.
LVector3f net_shove(0.0f, 0.0f, 0.0f);
LVector3f force_normal(0.0f, 0.0f, 0.0f);
for (si = shoves.begin(); si != shoves.end(); ++si) {
const ShoveData &sd = (*si);
if (sd._valid) {
net_shove += sd._vector * sd._length;
force_normal += sd._vector;
}
}
#ifndef NDEBUG
if (collide_cat.is_debug()) {
collide_cat.debug()
<< "Net shove on " << *from_node << " is: "
<< net_shove << "\n";
}
#endif
if (def._node != (PandaNode *)NULL) {
// If we are adjusting a plain PandaNode, get the
// transform and adjust just the position to preserve
// maximum precision.
CPT(TransformState) trans = def._node->get_transform();
LVecBase3f pos = trans->get_pos();
pos += net_shove * trans->get_mat();
def._node->set_transform(trans->set_pos(pos));
apply_linear_force(def, force_normal);
} else {
// Otherwise, go ahead and do the matrix math to do things
// the old and clumsy way.
LMatrix4f mat;
def.get_mat(mat);
def.set_mat(LMatrix4f::translate_mat(net_shove) * mat);
}
}
}
}
}
return okflag;
}
////////////////////////////////////////////////////////////////////
// Function: CollisionHandlerPusher::apply_linear_force
// Access: Protected, Virtual
// Description:
////////////////////////////////////////////////////////////////////
void CollisionHandlerPusher::
apply_linear_force(ColliderDef &, const LVector3f &) {
}
<|endoftext|> |
<commit_before>// Filename: config_parametrics.cxx
// Created by: drose (19Mar00)
//
////////////////////////////////////////////////////////////////////
#include "classicNurbsCurve.h"
#include "config_parametrics.h"
#include "cubicCurveseg.h"
#include "curveFitter.h"
#include "hermiteCurve.h"
#include "nurbsCurveDrawer.h"
#include "nurbsCurveInterface.h"
#include "parametricCurve.h"
#include "parametricCurveDrawer.h"
#include "piecewiseCurve.h"
#ifdef HAVE_NURBSPP
#include "nurbsPPCurve.h"
#endif
#include "get_config_path.h"
Configure(config_parametrics);
NotifyCategoryDef(parametrics, "");
ConfigureFn(config_parametrics) {
ClassicNurbsCurve::init_type();
CubicCurveseg::init_type();
CurveFitter::init_type();
HermiteCurve::init_type();
NurbsCurveDrawer::init_type();
NurbsCurveInterface::init_type();
NurbsPPCurve::init_type();
ParametricCurve::init_type();
ParametricCurveDrawer::init_type();
PiecewiseCurve::init_type();
#ifdef HAVE_NURBSPP
NurbsPPCurve::init_type();
#endif
ClassicNurbsCurve::register_with_read_factory();
CubicCurveseg::register_with_read_factory();
HermiteCurve::register_with_read_factory();
}
const DSearchPath &
get_parametrics_path() {
static DSearchPath *parametrics_path = NULL;
return get_config_path("parametrics-path", parametrics_path);
}
<commit_msg>*** empty log message ***<commit_after>// Filename: config_parametrics.cxx
// Created by: drose (19Mar00)
//
////////////////////////////////////////////////////////////////////
#include "classicNurbsCurve.h"
#include "config_parametrics.h"
#include "cubicCurveseg.h"
#include "curveFitter.h"
#include "hermiteCurve.h"
#include "nurbsCurveDrawer.h"
#include "nurbsCurveInterface.h"
#include "parametricCurve.h"
#include "parametricCurveDrawer.h"
#include "piecewiseCurve.h"
#ifdef HAVE_NURBSPP
#include "nurbsPPCurve.h"
#endif
#include "get_config_path.h"
Configure(config_parametrics);
NotifyCategoryDef(parametrics, "");
ConfigureFn(config_parametrics) {
ClassicNurbsCurve::init_type();
CubicCurveseg::init_type();
CurveFitter::init_type();
HermiteCurve::init_type();
NurbsCurveDrawer::init_type();
NurbsCurveInterface::init_type();
ParametricCurve::init_type();
ParametricCurveDrawer::init_type();
PiecewiseCurve::init_type();
#ifdef HAVE_NURBSPP
NurbsPPCurve::init_type();
#endif
ClassicNurbsCurve::register_with_read_factory();
CubicCurveseg::register_with_read_factory();
HermiteCurve::register_with_read_factory();
}
const DSearchPath &
get_parametrics_path() {
static DSearchPath *parametrics_path = NULL;
return get_config_path("parametrics-path", parametrics_path);
}
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include <rapidcheck/catch.h>
#include <numeric>
#include "rapidcheck/detail/BitStream.h"
#include "rapidcheck/detail/Utility.h"
using namespace rc;
using namespace rc::detail;
template <typename T>
class SeqSource {
public:
template <typename Arg,
typename = typename std::enable_if<
!std::is_same<Decay<Arg>, SeqSource>::value>::type>
SeqSource(Arg &&arg)
: m_seq(std::forward<Arg>(arg))
, m_requested(0) {}
T next() {
auto value = m_seq.next();
RC_ASSERT(value);
m_requested++;
return *value;
}
int requested() const { return m_requested; }
private:
Seq<T> m_seq;
int m_requested;
};
template <typename T>
SeqSource<T> makeSource(Seq<T> seq) {
return SeqSource<T>(std::move(seq));
}
TEST_CASE("BitStream") {
SECTION("next") {
const auto bitSizes =
gen::container<std::vector<int>>(gen::inRange(0, 100));
prop("requests the correct number of bits",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
const auto sizes = *bitSizes;
int totalSize = 0;
for (int size : sizes) {
totalSize += size;
stream.next<uint64_t>(size);
}
int expected = totalSize / 8;
if ((totalSize % 8) != 0) {
expected++;
}
RC_ASSERT(source.requested() == expected);
});
prop("spills no bits",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
const auto sizes = *gen::suchThat(bitSizes,
[](const std::vector<int> &x) {
return std::accumulate(
begin(x), end(x), 0) >= 64;
});
uint64_t value = 0;
int n = 64;
for (int size : sizes) {
if (n == 0) {
break;
}
const auto r = std::min(n, size);
const auto bits = stream.next<uint64_t>(r);
value |= (bits << (64ULL - n));
n -= r;
}
RC_ASSERT(value == x);
});
prop("takes multiple values per request if required to fill result",
[](uint8_t byte) {
auto source = makeSource(seq::take(8, seq::repeat(byte)));
auto stream = bitStreamOf(source);
uint64_t value = stream.next<uint64_t>(64);
uint64_t expected = 0;
for (int i = 0; i < 8; i++) {
expected <<= 8ULL;
expected |= byte;
}
RC_ASSERT(value == expected);
});
prop("does not return more bits than requested (unsigned)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
int n = *gen::inRange(1, 64);
RC_ASSERT((stream.next<uint64_t>(n) & ~bitMask<uint64_t>(n)) == 0U);
});
prop("does not return more bits than requested (signed)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
const auto n = *gen::inRange(1, 64);
const bool sign = (x & (1LL << (n - 1LL))) != 0;
const auto mask = ~bitMask<int64_t>(n);
if (sign) {
RC_ASSERT((stream.next<int64_t>(n) & mask) == mask);
} else {
RC_ASSERT((stream.next<int64_t>(n) & mask) == 0);
}
});
prop("does not return any bits when none are requested",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
RC_ASSERT((stream.next<uint64_t>(0) & bitMask<uint64_t>(64)) == 0U);
});
prop("does not return any bits when none are requested (signed)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
RC_ASSERT((stream.next<int64_t>(0) & bitMask<int64_t>(64)) == 0);
});
prop("works with booleans",
[](uint64_t x) {
auto source = makeSource(seq::just(x));
auto stream = bitStreamOf(source);
uint64_t value = 0;
for (uint64_t i = 0; i < 64ULL; i++) {
if (stream.next<bool>(1)) {
value |= 1ULL << i;
}
}
RC_ASSERT(value == x);
});
}
SECTION("nextWithSize") {
prop("requests full number of bits for kNominalSize",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::inRange(0, 100);
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(kNominalSize);
}
RC_ASSERT(source.requested() == n);
});
prop("requests half number of bits for kNominalSize / 2",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::suchThat(gen::inRange(0, 100),
[](int x) { return (x % 2) == 0; });
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(kNominalSize / 2);
}
RC_ASSERT(source.requested() == (n / 2));
});
prop("requests no bits for size 0",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::inRange(0, 100);
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(0);
}
RC_ASSERT(source.requested() == 0);
});
}
SECTION("bitStreamOf") {
SECTION("copies source if const") {
auto source = makeSource(seq::just(0, 1));
const auto &constSource = source;
auto stream = bitStreamOf(constSource);
stream.next<int>();
REQUIRE(source.next() == 0);
}
SECTION("references source if non-const") {
auto source = makeSource(seq::just(0, 1));
auto &nonConstSource = source;
auto stream = bitStreamOf(nonConstSource);
stream.next<int>();
REQUIRE(source.next() == 1);
}
}
}
<commit_msg>Simplify a pair of test cases<commit_after>#include <catch.hpp>
#include <rapidcheck/catch.h>
#include <numeric>
#include "rapidcheck/detail/BitStream.h"
#include "rapidcheck/detail/Utility.h"
using namespace rc;
using namespace rc::detail;
template <typename T>
class SeqSource {
public:
template <typename Arg,
typename = typename std::enable_if<
!std::is_same<Decay<Arg>, SeqSource>::value>::type>
SeqSource(Arg &&arg)
: m_seq(std::forward<Arg>(arg))
, m_requested(0) {}
T next() {
auto value = m_seq.next();
RC_ASSERT(value);
m_requested++;
return *value;
}
int requested() const { return m_requested; }
private:
Seq<T> m_seq;
int m_requested;
};
template <typename T>
SeqSource<T> makeSource(Seq<T> seq) {
return SeqSource<T>(std::move(seq));
}
TEST_CASE("BitStream") {
SECTION("next") {
const auto bitSizes =
gen::container<std::vector<int>>(gen::inRange(0, 100));
prop("requests the correct number of bits",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
const auto sizes = *bitSizes;
int totalSize = 0;
for (int size : sizes) {
totalSize += size;
stream.next<uint64_t>(size);
}
int expected = totalSize / 8;
if ((totalSize % 8) != 0) {
expected++;
}
RC_ASSERT(source.requested() == expected);
});
prop("spills no bits",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
const auto sizes = *gen::suchThat(bitSizes,
[](const std::vector<int> &x) {
return std::accumulate(
begin(x), end(x), 0) >= 64;
});
uint64_t value = 0;
int n = 64;
for (int size : sizes) {
if (n == 0) {
break;
}
const auto r = std::min(n, size);
const auto bits = stream.next<uint64_t>(r);
value |= (bits << (64ULL - n));
n -= r;
}
RC_ASSERT(value == x);
});
prop("takes multiple values per request if required to fill result",
[](uint8_t byte) {
auto source = makeSource(seq::take(8, seq::repeat(byte)));
auto stream = bitStreamOf(source);
uint64_t value = stream.next<uint64_t>(64);
uint64_t expected = 0;
for (int i = 0; i < 8; i++) {
expected <<= 8ULL;
expected |= byte;
}
RC_ASSERT(value == expected);
});
prop("does not return more bits than requested (unsigned)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
int n = *gen::inRange(1, 64);
RC_ASSERT((stream.next<uint64_t>(n) & ~bitMask<uint64_t>(n)) == 0U);
});
prop("does not return more bits than requested (signed)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
const auto n = *gen::inRange(1, 64);
const bool sign = (x & (1LL << (n - 1LL))) != 0;
const auto mask = ~bitMask<int64_t>(n);
if (sign) {
RC_ASSERT((stream.next<int64_t>(n) & mask) == mask);
} else {
RC_ASSERT((stream.next<int64_t>(n) & mask) == 0);
}
});
prop("does not return any bits when none are requested",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
RC_ASSERT(stream.next<uint64_t>(0) == 0U);
});
prop("does not return any bits when none are requested (signed)",
[=](uint64_t x) {
auto source = makeSource(seq::repeat(x));
auto stream = bitStreamOf(source);
RC_ASSERT(stream.next<int64_t>(0) == 0);
});
prop("works with booleans",
[](uint64_t x) {
auto source = makeSource(seq::just(x));
auto stream = bitStreamOf(source);
uint64_t value = 0;
for (uint64_t i = 0; i < 64ULL; i++) {
if (stream.next<bool>(1)) {
value |= 1ULL << i;
}
}
RC_ASSERT(value == x);
});
}
SECTION("nextWithSize") {
prop("requests full number of bits for kNominalSize",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::inRange(0, 100);
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(kNominalSize);
}
RC_ASSERT(source.requested() == n);
});
prop("requests half number of bits for kNominalSize / 2",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::suchThat(gen::inRange(0, 100),
[](int x) { return (x % 2) == 0; });
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(kNominalSize / 2);
}
RC_ASSERT(source.requested() == (n / 2));
});
prop("requests no bits for size 0",
[=] {
auto source = makeSource(seq::repeat('\xAB'));
auto stream = bitStreamOf(source);
int n = *gen::inRange(0, 100);
for (int i = 0; i < n; i++) {
stream.nextWithSize<char>(0);
}
RC_ASSERT(source.requested() == 0);
});
}
SECTION("bitStreamOf") {
SECTION("copies source if const") {
auto source = makeSource(seq::just(0, 1));
const auto &constSource = source;
auto stream = bitStreamOf(constSource);
stream.next<int>();
REQUIRE(source.next() == 0);
}
SECTION("references source if non-const") {
auto source = makeSource(seq::just(0, 1));
auto &nonConstSource = source;
auto stream = bitStreamOf(nonConstSource);
stream.next<int>();
REQUIRE(source.next() == 1);
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Added comments.<commit_after><|endoftext|> |
<commit_before>#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"
#include<algorithm>
#include<deque>
#include<map>
#include<list>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<vector>
// TODO: get, operator[], count, equal_range, erase, lower_bound, upper_bound
template<typename V>
void BM_advance(benchmark::State& state) {
int N = state.range(0);
V v;
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.begin();
std::advance(it, i);
benchmark::DoNotOptimize(it);
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_access(benchmark::State& state) {
int N = state.range(0);
V v;
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.begin();
std::advance(it, i);
benchmark::DoNotOptimize(*it);
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_at(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i)
benchmark::DoNotOptimize(v.at(i));
}
state.SetComplexityN(N);
}
// Insert random elements
template<typename V>
void BM_assoc_find_random(benchmark::State& state) {
int N = state.range(0);
using CVT = typename V::value_type;
using VT = typename remove_const<CVT>::type;
using KT = typename std::remove_const<typename V::key_type>::type;
std::vector<KT> temp(N);
fill_random(temp, N);
V v;
random_device r;
for (int i = 0; i < N; ++i)
v.insert(get_rand<VT>(r, RAND_MAX));
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i)
benchmark::DoNotOptimize(v.find(temp[i]));
}
state.SetComplexityN(N);
}
template<typename V>
void BM_assoc_find_seq(benchmark::State& state) {
int N = state.range(0);
using CVT = typename V::value_type;
using VT = typename remove_const<CVT>::type;
using KT = typename std::remove_const<typename V::key_type>::type;
std::vector<VT> temp(N);
fill_seq(temp);
V v;
for (int i = 0; i < N; ++i)
v.insert(temp[i]);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.find(i);
benchmark::DoNotOptimize(it);
assert (it != v.end());
}
}
state.SetComplexityN(N);
}
static const int MSize = L1;
#define BENCH_STD_MAP(T) SINGLE_ARG(std::map<T, T>)
#define BENCH_STD_UNORDERED_MAP(T) SINGLE_ARG(std::unordered_map<T, T>)
#define COMPLEXITY_BENCHMARK_GEN_T(T) \
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_at, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_at, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, std::set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, std::unordered_set<T>, MSize);\
\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, BENCH_STD_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, BENCH_STD_UNORDERED_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, std::set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, std::unordered_set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, BENCH_STD_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, BENCH_STD_UNORDERED_MAP(T), MSize);
COMPLEXITY_BENCHMARK_GEN_T(int)
COMPLEXITY_BENCHMARK_GEN_T(aggregate)
BENCHMARK_MAIN()
<commit_msg>Fix segfault in case of deque<aggregate><commit_after>#include "benchmark/benchmark_api.h"
#include "test_configs.h"
#include "test_utils.h"
#include<algorithm>
#include<deque>
#include<map>
#include<list>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<vector>
// TODO: get, operator[], count, equal_range, erase, lower_bound, upper_bound
template<typename V>
void BM_advance(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.begin();
std::advance(it, i);
benchmark::DoNotOptimize(it);
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_access(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.begin();
std::advance(it, i);
benchmark::DoNotOptimize(*it);
}
}
state.SetComplexityN(N);
}
template<typename V>
void BM_at(benchmark::State& state) {
int N = state.range(0);
V v(N);
fill_seq(v);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i)
benchmark::DoNotOptimize(v.at(i));
}
state.SetComplexityN(N);
}
// Insert random elements
template<typename V>
void BM_assoc_find_random(benchmark::State& state) {
int N = state.range(0);
using CVT = typename V::value_type;
using VT = typename remove_const<CVT>::type;
using KT = typename std::remove_const<typename V::key_type>::type;
std::vector<KT> temp(N);
fill_random(temp, N);
V v;
random_device r;
for (int i = 0; i < N; ++i)
v.insert(get_rand<VT>(r, RAND_MAX));
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i)
benchmark::DoNotOptimize(v.find(temp[i]));
}
state.SetComplexityN(N);
}
template<typename V>
void BM_assoc_find_seq(benchmark::State& state) {
int N = state.range(0);
using CVT = typename V::value_type;
using VT = typename remove_const<CVT>::type;
using KT = typename std::remove_const<typename V::key_type>::type;
std::vector<VT> temp(N);
fill_seq(temp);
V v;
for (int i = 0; i < N; ++i)
v.insert(temp[i]);
while (state.KeepRunning()) {
for (int i = 0; i < N; ++i) {
auto it = v.find(i);
benchmark::DoNotOptimize(it);
assert (it != v.end());
}
}
state.SetComplexityN(N);
}
static const int MSize = L1;
#define BENCH_STD_MAP(T) SINGLE_ARG(std::map<T, T>)
#define BENCH_STD_UNORDERED_MAP(T) SINGLE_ARG(std::unordered_map<T, T>)
#define COMPLEXITY_BENCHMARK_GEN_T(T) \
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_advance, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::list<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_access, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_at, std::vector<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_at, std::deque<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, std::set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, std::unordered_set<T>, MSize);\
\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, BENCH_STD_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_random, BENCH_STD_UNORDERED_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, std::set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, std::unordered_set<T>, MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, BENCH_STD_MAP(T), MSize);\
COMPLEXITY_BENCHMARK_GEN(BM_assoc_find_seq, BENCH_STD_UNORDERED_MAP(T), MSize);
COMPLEXITY_BENCHMARK_GEN_T(int)
COMPLEXITY_BENCHMARK_GEN_T(aggregate)
BENCHMARK_MAIN()
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/android/device_info_android.h"
#include <algorithm>
#include <sstream>
#include <vector>
#include "json/json.h"
#include "third_party/icu/source/common/unicode/unistr.h"
#include "webrtc/modules/video_capture/android/video_capture_android.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/ref_count.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace videocapturemodule {
// Helper for storing lists of pairs of ints. Used e.g. for resolutions & FPS
// ranges.
typedef std::pair<int, int> IntPair;
typedef std::vector<IntPair> IntPairs;
static std::string IntPairsToString(const IntPairs& pairs, char separator) {
std::stringstream stream;
for (size_t i = 0; i < pairs.size(); ++i) {
if (i > 0)
stream << ", ";
stream << "(" << pairs[i].first << separator << pairs[i].second << ")";
}
return stream.str();
}
struct AndroidCameraInfo {
std::string name;
bool front_facing;
int orientation;
IntPairs resolutions; // Pairs are: (width,height).
// Pairs are (min,max) in units of FPS*1000 ("milli-frame-per-second").
IntPairs mfpsRanges;
std::string ToString() {
std::stringstream stream;
stream << "Name: [" << name << "], MFPS ranges: ["
<< IntPairsToString(mfpsRanges, ':')
<< "], front_facing: " << front_facing
<< ", orientation: " << orientation << ", resolutions: ["
<< IntPairsToString(resolutions, 'x') << "]";
return stream.str();
}
};
// Camera info; populated during DeviceInfoAndroid::Initialize() and immutable
// thereafter.
static std::vector<AndroidCameraInfo>* g_camera_info = NULL;
// Set |*index| to the index of |name| in g_camera_info or return false if no
// match found.
static bool FindCameraIndexByName(const std::string& name, size_t* index) {
for (size_t i = 0; i < g_camera_info->size(); ++i) {
if (g_camera_info->at(i).name == name) {
*index = i;
return true;
}
}
return false;
}
// Returns a pointer to the named member of g_camera_info, or NULL if no match
// is found.
static AndroidCameraInfo* FindCameraInfoByName(const std::string& name) {
size_t index = 0;
if (FindCameraIndexByName(name, &index))
return &g_camera_info->at(index);
return NULL;
}
// static
void DeviceInfoAndroid::Initialize(JNIEnv* jni) {
// TODO(henrike): this "if" would make a lot more sense as an assert, but
// Java_org_webrtc_videoengineapp_ViEAndroidJavaAPI_GetVideoEngine() and
// Java_org_webrtc_videoengineapp_ViEAndroidJavaAPI_Terminate() conspire to
// prevent this. Once that code is made to only
// VideoEngine::SetAndroidObjects() once per process, this can turn into an
// assert.
if (g_camera_info)
return;
g_camera_info = new std::vector<AndroidCameraInfo>();
jclass j_info_class =
jni->FindClass("org/webrtc/videoengine/VideoCaptureDeviceInfoAndroid");
assert(j_info_class);
jmethodID j_initialize = jni->GetStaticMethodID(
j_info_class, "getDeviceInfo", "()Ljava/lang/String;");
jstring j_json_info = static_cast<jstring>(
jni->CallStaticObjectMethod(j_info_class, j_initialize));
const jchar* jchars = jni->GetStringChars(j_json_info, NULL);
icu::UnicodeString ustr(jchars, jni->GetStringLength(j_json_info));
jni->ReleaseStringChars(j_json_info, jchars);
std::string json_info;
ustr.toUTF8String(json_info);
Json::Value cameras;
Json::Reader reader(Json::Features::strictMode());
bool parsed = reader.parse(json_info, cameras);
if (!parsed) {
std::stringstream stream;
stream << "Failed to parse configuration:\n"
<< reader.getFormattedErrorMessages();
assert(false);
return;
}
for (Json::ArrayIndex i = 0; i < cameras.size(); ++i) {
const Json::Value& camera = cameras[i];
AndroidCameraInfo info;
info.name = camera["name"].asString();
info.front_facing = camera["front_facing"].asBool();
info.orientation = camera["orientation"].asInt();
Json::Value sizes = camera["sizes"];
for (Json::ArrayIndex j = 0; j < sizes.size(); ++j) {
const Json::Value& size = sizes[j];
info.resolutions.push_back(std::make_pair(
size["width"].asInt(), size["height"].asInt()));
}
Json::Value mfpsRanges = camera["mfpsRanges"];
for (Json::ArrayIndex j = 0; j < mfpsRanges.size(); ++j) {
const Json::Value& mfpsRange = mfpsRanges[j];
info.mfpsRanges.push_back(std::make_pair(mfpsRange["min_mfps"].asInt(),
mfpsRange["max_mfps"].asInt()));
}
g_camera_info->push_back(info);
}
}
void DeviceInfoAndroid::DeInitialize() {
if (g_camera_info) {
delete g_camera_info;
g_camera_info = NULL;
}
}
VideoCaptureModule::DeviceInfo* VideoCaptureImpl::CreateDeviceInfo(
const int32_t id) {
return new videocapturemodule::DeviceInfoAndroid(id);
}
DeviceInfoAndroid::DeviceInfoAndroid(const int32_t id) :
DeviceInfoImpl(id) {
}
DeviceInfoAndroid::~DeviceInfoAndroid() {
}
bool DeviceInfoAndroid::FindCameraIndex(const char* deviceUniqueIdUTF8,
size_t* index) {
return FindCameraIndexByName(deviceUniqueIdUTF8, index);
}
int32_t DeviceInfoAndroid::Init() {
return 0;
}
uint32_t DeviceInfoAndroid::NumberOfDevices() {
return g_camera_info->size();
}
int32_t DeviceInfoAndroid::GetDeviceName(
uint32_t deviceNumber,
char* deviceNameUTF8,
uint32_t deviceNameLength,
char* deviceUniqueIdUTF8,
uint32_t deviceUniqueIdUTF8Length,
char* /*productUniqueIdUTF8*/,
uint32_t /*productUniqueIdUTF8Length*/) {
if (deviceNumber >= g_camera_info->size())
return -1;
const AndroidCameraInfo& info = g_camera_info->at(deviceNumber);
if (info.name.length() + 1 > deviceNameLength ||
info.name.length() + 1 > deviceUniqueIdUTF8Length) {
return -1;
}
memcpy(deviceNameUTF8, info.name.c_str(), info.name.length() + 1);
memcpy(deviceUniqueIdUTF8, info.name.c_str(), info.name.length() + 1);
return 0;
}
int32_t DeviceInfoAndroid::CreateCapabilityMap(
const char* deviceUniqueIdUTF8) {
_captureCapabilities.clear();
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL)
return -1;
for (size_t i = 0; i < info->resolutions.size(); ++i) {
for (size_t j = 0; j < info->mfpsRanges.size(); ++j) {
const IntPair& size = info->resolutions[i];
const IntPair& mfpsRange = info->mfpsRanges[j];
VideoCaptureCapability cap;
cap.width = size.first;
cap.height = size.second;
cap.maxFPS = mfpsRange.second / 1000;
cap.expectedCaptureDelay = kExpectedCaptureDelay;
cap.rawType = kVideoNV21;
_captureCapabilities.push_back(cap);
}
}
return _captureCapabilities.size();
}
int32_t DeviceInfoAndroid::GetOrientation(
const char* deviceUniqueIdUTF8,
VideoCaptureRotation& orientation) {
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL ||
!VideoCaptureImpl::RotationFromDegrees(info->orientation, &orientation)) {
return -1;
}
return 0;
}
void DeviceInfoAndroid::GetMFpsRange(const char* deviceUniqueIdUTF8,
int max_fps_to_match,
int* min_mfps, int* max_mfps) {
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL)
return;
int desired_mfps = max_fps_to_match * 1000;
int best_diff_mfps = 0;
LOG(LS_INFO) << "Search for best target mfps " << desired_mfps;
// Search for best fps range with preference shifted to constant fps modes.
for (size_t i = 0; i < info->mfpsRanges.size(); ++i) {
int diff_mfps = abs(info->mfpsRanges[i].first - desired_mfps) +
abs(info->mfpsRanges[i].second - desired_mfps) +
(info->mfpsRanges[i].second - info->mfpsRanges[i].first) / 2;
LOG(LS_INFO) << "Fps range " << info->mfpsRanges[i].first << ":" <<
info->mfpsRanges[i].second << ". Distance: " << diff_mfps;
if (i == 0 || diff_mfps < best_diff_mfps) {
best_diff_mfps = diff_mfps;
*min_mfps = info->mfpsRanges[i].first;
*max_mfps = info->mfpsRanges[i].second;
}
}
}
} // namespace videocapturemodule
} // namespace webrtc
<commit_msg>Getting orientation is not working properly. VideoCaptureImpl::RotationFromDegrees returns -1 in case fails not 0. So we need to change the if statement.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_capture/android/device_info_android.h"
#include <algorithm>
#include <sstream>
#include <vector>
#include "json/json.h"
#include "third_party/icu/source/common/unicode/unistr.h"
#include "webrtc/modules/video_capture/android/video_capture_android.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/ref_count.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace videocapturemodule {
// Helper for storing lists of pairs of ints. Used e.g. for resolutions & FPS
// ranges.
typedef std::pair<int, int> IntPair;
typedef std::vector<IntPair> IntPairs;
static std::string IntPairsToString(const IntPairs& pairs, char separator) {
std::stringstream stream;
for (size_t i = 0; i < pairs.size(); ++i) {
if (i > 0)
stream << ", ";
stream << "(" << pairs[i].first << separator << pairs[i].second << ")";
}
return stream.str();
}
struct AndroidCameraInfo {
std::string name;
bool front_facing;
int orientation;
IntPairs resolutions; // Pairs are: (width,height).
// Pairs are (min,max) in units of FPS*1000 ("milli-frame-per-second").
IntPairs mfpsRanges;
std::string ToString() {
std::stringstream stream;
stream << "Name: [" << name << "], MFPS ranges: ["
<< IntPairsToString(mfpsRanges, ':')
<< "], front_facing: " << front_facing
<< ", orientation: " << orientation << ", resolutions: ["
<< IntPairsToString(resolutions, 'x') << "]";
return stream.str();
}
};
// Camera info; populated during DeviceInfoAndroid::Initialize() and immutable
// thereafter.
static std::vector<AndroidCameraInfo>* g_camera_info = NULL;
// Set |*index| to the index of |name| in g_camera_info or return false if no
// match found.
static bool FindCameraIndexByName(const std::string& name, size_t* index) {
for (size_t i = 0; i < g_camera_info->size(); ++i) {
if (g_camera_info->at(i).name == name) {
*index = i;
return true;
}
}
return false;
}
// Returns a pointer to the named member of g_camera_info, or NULL if no match
// is found.
static AndroidCameraInfo* FindCameraInfoByName(const std::string& name) {
size_t index = 0;
if (FindCameraIndexByName(name, &index))
return &g_camera_info->at(index);
return NULL;
}
// static
void DeviceInfoAndroid::Initialize(JNIEnv* jni) {
// TODO(henrike): this "if" would make a lot more sense as an assert, but
// Java_org_webrtc_videoengineapp_ViEAndroidJavaAPI_GetVideoEngine() and
// Java_org_webrtc_videoengineapp_ViEAndroidJavaAPI_Terminate() conspire to
// prevent this. Once that code is made to only
// VideoEngine::SetAndroidObjects() once per process, this can turn into an
// assert.
if (g_camera_info)
return;
g_camera_info = new std::vector<AndroidCameraInfo>();
jclass j_info_class =
jni->FindClass("org/webrtc/videoengine/VideoCaptureDeviceInfoAndroid");
assert(j_info_class);
jmethodID j_initialize = jni->GetStaticMethodID(
j_info_class, "getDeviceInfo", "()Ljava/lang/String;");
jstring j_json_info = static_cast<jstring>(
jni->CallStaticObjectMethod(j_info_class, j_initialize));
const jchar* jchars = jni->GetStringChars(j_json_info, NULL);
icu::UnicodeString ustr(jchars, jni->GetStringLength(j_json_info));
jni->ReleaseStringChars(j_json_info, jchars);
std::string json_info;
ustr.toUTF8String(json_info);
Json::Value cameras;
Json::Reader reader(Json::Features::strictMode());
bool parsed = reader.parse(json_info, cameras);
if (!parsed) {
std::stringstream stream;
stream << "Failed to parse configuration:\n"
<< reader.getFormattedErrorMessages();
assert(false);
return;
}
for (Json::ArrayIndex i = 0; i < cameras.size(); ++i) {
const Json::Value& camera = cameras[i];
AndroidCameraInfo info;
info.name = camera["name"].asString();
info.front_facing = camera["front_facing"].asBool();
info.orientation = camera["orientation"].asInt();
Json::Value sizes = camera["sizes"];
for (Json::ArrayIndex j = 0; j < sizes.size(); ++j) {
const Json::Value& size = sizes[j];
info.resolutions.push_back(std::make_pair(
size["width"].asInt(), size["height"].asInt()));
}
Json::Value mfpsRanges = camera["mfpsRanges"];
for (Json::ArrayIndex j = 0; j < mfpsRanges.size(); ++j) {
const Json::Value& mfpsRange = mfpsRanges[j];
info.mfpsRanges.push_back(std::make_pair(mfpsRange["min_mfps"].asInt(),
mfpsRange["max_mfps"].asInt()));
}
g_camera_info->push_back(info);
}
}
void DeviceInfoAndroid::DeInitialize() {
if (g_camera_info) {
delete g_camera_info;
g_camera_info = NULL;
}
}
VideoCaptureModule::DeviceInfo* VideoCaptureImpl::CreateDeviceInfo(
const int32_t id) {
return new videocapturemodule::DeviceInfoAndroid(id);
}
DeviceInfoAndroid::DeviceInfoAndroid(const int32_t id) :
DeviceInfoImpl(id) {
}
DeviceInfoAndroid::~DeviceInfoAndroid() {
}
bool DeviceInfoAndroid::FindCameraIndex(const char* deviceUniqueIdUTF8,
size_t* index) {
return FindCameraIndexByName(deviceUniqueIdUTF8, index);
}
int32_t DeviceInfoAndroid::Init() {
return 0;
}
uint32_t DeviceInfoAndroid::NumberOfDevices() {
return g_camera_info->size();
}
int32_t DeviceInfoAndroid::GetDeviceName(
uint32_t deviceNumber,
char* deviceNameUTF8,
uint32_t deviceNameLength,
char* deviceUniqueIdUTF8,
uint32_t deviceUniqueIdUTF8Length,
char* /*productUniqueIdUTF8*/,
uint32_t /*productUniqueIdUTF8Length*/) {
if (deviceNumber >= g_camera_info->size())
return -1;
const AndroidCameraInfo& info = g_camera_info->at(deviceNumber);
if (info.name.length() + 1 > deviceNameLength ||
info.name.length() + 1 > deviceUniqueIdUTF8Length) {
return -1;
}
memcpy(deviceNameUTF8, info.name.c_str(), info.name.length() + 1);
memcpy(deviceUniqueIdUTF8, info.name.c_str(), info.name.length() + 1);
return 0;
}
int32_t DeviceInfoAndroid::CreateCapabilityMap(
const char* deviceUniqueIdUTF8) {
_captureCapabilities.clear();
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL)
return -1;
for (size_t i = 0; i < info->resolutions.size(); ++i) {
for (size_t j = 0; j < info->mfpsRanges.size(); ++j) {
const IntPair& size = info->resolutions[i];
const IntPair& mfpsRange = info->mfpsRanges[j];
VideoCaptureCapability cap;
cap.width = size.first;
cap.height = size.second;
cap.maxFPS = mfpsRange.second / 1000;
cap.expectedCaptureDelay = kExpectedCaptureDelay;
cap.rawType = kVideoNV21;
_captureCapabilities.push_back(cap);
}
}
return _captureCapabilities.size();
}
int32_t DeviceInfoAndroid::GetOrientation(
const char* deviceUniqueIdUTF8,
VideoCaptureRotation& orientation) {
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL ||
VideoCaptureImpl::RotationFromDegrees(info->orientation,
&orientation) != 0) {
return -1;
}
return 0;
}
void DeviceInfoAndroid::GetMFpsRange(const char* deviceUniqueIdUTF8,
int max_fps_to_match,
int* min_mfps, int* max_mfps) {
const AndroidCameraInfo* info = FindCameraInfoByName(deviceUniqueIdUTF8);
if (info == NULL)
return;
int desired_mfps = max_fps_to_match * 1000;
int best_diff_mfps = 0;
LOG(LS_INFO) << "Search for best target mfps " << desired_mfps;
// Search for best fps range with preference shifted to constant fps modes.
for (size_t i = 0; i < info->mfpsRanges.size(); ++i) {
int diff_mfps = abs(info->mfpsRanges[i].first - desired_mfps) +
abs(info->mfpsRanges[i].second - desired_mfps) +
(info->mfpsRanges[i].second - info->mfpsRanges[i].first) / 2;
LOG(LS_INFO) << "Fps range " << info->mfpsRanges[i].first << ":" <<
info->mfpsRanges[i].second << ". Distance: " << diff_mfps;
if (i == 0 || diff_mfps < best_diff_mfps) {
best_diff_mfps = diff_mfps;
*min_mfps = info->mfpsRanges[i].first;
*max_mfps = info->mfpsRanges[i].second;
}
}
}
} // namespace videocapturemodule
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* LucasCandaePyramidTracker.cpp
*
* Created on: Feb 21, 2013
* Author: link
*/
#include "LucasCandaePyramidTracker.hpp"
#include "opencv2/video/tracking.hpp"
const cv::TermCriteria DEFAULT_TERM_CRITERIA = cv::TermCriteria(
CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 40, 0.001);
const cv::Size DEFAULT_WINDOW_SIZE = cv::Size(21, 21);
const unsigned int DEFAULT_MAX_LEVEL = 3;
const unsigned int DEFAULT_FLAGS = 0;
const double DEFAULT_MIN_EIGENVALUE_THRESHOLD = 1e-4;
const double DEFAULT_MAX_ERROR_THRESHOLD = 500;
LucasCandaePyramidTracker::LucasCandaePyramidTracker() :
_windowSize(DEFAULT_WINDOW_SIZE), _maxLevel(DEFAULT_MAX_LEVEL), _flags(
DEFAULT_FLAGS), _minEigenvalueThreshold(
DEFAULT_MIN_EIGENVALUE_THRESHOLD), _maxErrorThreshold(
DEFAULT_MAX_ERROR_THRESHOLD), _termCrit(DEFAULT_TERM_CRITERIA) {
}
LucasCandaePyramidTracker::~LucasCandaePyramidTracker() {
// TODO Auto-generated destructor stub
}
LucasCandaePyramidTracker::LucasCandaePyramidTracker(
const LucasCandaePyramidTracker &toCopy) :
_windowSize(toCopy._windowSize), _maxLevel(toCopy._maxLevel), _flags(
toCopy._flags), _minEigenvalueThreshold(
toCopy._minEigenvalueThreshold), _maxErrorThreshold(
toCopy._maxErrorThreshold), _termCrit(toCopy._termCrit) {
}
LucasCandaePyramidTracker::LucasCandaePyramidTracker(const cv::Size &windowSize,
const unsigned int &maxLevel, const int &flags,
const cv::TermCriteria &terminationCriteria,
const double &minEigenvalueThreshold, const double &maxErrorValue):
_windowSize(windowSize), _maxLevel(maxLevel), _flags(flags),
_minEigenvalueThreshold(minEigenvalueThreshold),
_maxErrorThreshold(maxErrorValue), _termCrit(terminationCriteria){
}
FeatureTracker *LucasCandaePyramidTracker::constructCopy()const{
return new LucasCandaePyramidTracker(*this);
}
void LucasCandaePyramidTracker::trackFeatures(const cv::Mat &oldInput,
const cv::Mat &newInput,
std::vector<std::list<cv::Point2f> > &trackedFeatures) {
std::vector<uchar> status;
std::vector<float> err; //thou shall not use double instead of float!!
std::vector<cv::Point2f> oldFeatures(trackedFeatures.size());
std::vector<cv::Point2f> newFeatures(trackedFeatures.size());
for (unsigned int i = 0; i < trackedFeatures.size(); ++i) {
oldFeatures[i] = trackedFeatures[i].front();
}
cv::calcOpticalFlowPyrLK(oldInput, newInput, oldFeatures, newFeatures, status,
err, _windowSize, _maxLevel, _termCrit, _flags,
_minEigenvalueThreshold);
for (unsigned i = 0; i < newFeatures.size(); ++i) {
if (!status[i] || (err[i] > _maxErrorThreshold)) {
newFeatures.erase(newFeatures.begin() + i);
//oldFeatures.erase(oldFeatures.begin() + i);
status.erase(status.begin() + i);
err.erase(err.begin() + i);
trackedFeatures.erase(trackedFeatures.begin() + i);
--i;
} else {
trackedFeatures[i].push_front(newFeatures[i]);
}
}
}
<commit_msg>Fixed code formatting of LucasCandaePyramidTracker.cpp<commit_after>/*
* LucasCandaePyramidTracker.cpp
*
* Created on: Feb 21, 2013
* Author: link
*/
#include "LucasCandaePyramidTracker.hpp"
#include "opencv2/video/tracking.hpp"
const cv::TermCriteria DEFAULT_TERM_CRITERIA = cv::TermCriteria(
CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 40, 0.001);
const cv::Size DEFAULT_WINDOW_SIZE = cv::Size(21, 21);
const unsigned int DEFAULT_MAX_LEVEL = 3;
const unsigned int DEFAULT_FLAGS = 0;
const double DEFAULT_MIN_EIGENVALUE_THRESHOLD = 1e-4;
const double DEFAULT_MAX_ERROR_THRESHOLD = 500;
LucasCandaePyramidTracker::LucasCandaePyramidTracker() :
_windowSize(DEFAULT_WINDOW_SIZE), _maxLevel(DEFAULT_MAX_LEVEL), _flags(
DEFAULT_FLAGS), _minEigenvalueThreshold(
DEFAULT_MIN_EIGENVALUE_THRESHOLD), _maxErrorThreshold(
DEFAULT_MAX_ERROR_THRESHOLD), _termCrit(DEFAULT_TERM_CRITERIA) {
}
LucasCandaePyramidTracker::~LucasCandaePyramidTracker() {
// TODO Auto-generated destructor stub
}
LucasCandaePyramidTracker::LucasCandaePyramidTracker(
const LucasCandaePyramidTracker &toCopy) :
_windowSize(toCopy._windowSize), _maxLevel(toCopy._maxLevel), _flags(
toCopy._flags), _minEigenvalueThreshold(
toCopy._minEigenvalueThreshold), _maxErrorThreshold(
toCopy._maxErrorThreshold), _termCrit(toCopy._termCrit) {
}
LucasCandaePyramidTracker::LucasCandaePyramidTracker(const cv::Size &windowSize,
const unsigned int &maxLevel, const int &flags,
const cv::TermCriteria &terminationCriteria,
const double &minEigenvalueThreshold, const double &maxErrorValue) :
_windowSize(windowSize), _maxLevel(maxLevel), _flags(flags), _minEigenvalueThreshold(
minEigenvalueThreshold), _maxErrorThreshold(maxErrorValue), _termCrit(
terminationCriteria) {
}
FeatureTracker *LucasCandaePyramidTracker::constructCopy() const {
return new LucasCandaePyramidTracker(*this);
}
void LucasCandaePyramidTracker::trackFeatures(const cv::Mat &oldInput,
const cv::Mat &newInput,
std::vector<std::list<cv::Point2f> > &trackedFeatures) {
std::vector<uchar> status;
std::vector<float> err; //thou shall not use double instead of float!!
std::vector<cv::Point2f> oldFeatures(trackedFeatures.size());
std::vector<cv::Point2f> newFeatures(trackedFeatures.size());
for (unsigned int i = 0; i < trackedFeatures.size(); ++i) {
oldFeatures[i] = trackedFeatures[i].front();
}
cv::calcOpticalFlowPyrLK(oldInput, newInput, oldFeatures, newFeatures,
status, err, _windowSize, _maxLevel, _termCrit, _flags,
_minEigenvalueThreshold);
for (unsigned i = 0; i < newFeatures.size(); ++i) {
if (!status[i] || (err[i] > _maxErrorThreshold)) {
newFeatures.erase(newFeatures.begin() + i);
//oldFeatures.erase(oldFeatures.begin() + i);
status.erase(status.begin() + i);
err.erase(err.begin() + i);
trackedFeatures.erase(trackedFeatures.begin() + i);
--i;
} else {
trackedFeatures[i].push_front(newFeatures[i]);
}
}
}
<|endoftext|> |
<commit_before>/* AddRepoWindow.cpp
* Copyright 2016 Brian Hill
* All rights reserved. Distributed under the terms of the BSD License.
*/
#include "AddRepoWindow.h"
#include <Alert.h>
#include <Application.h>
#include <Catalog.h>
#include <Clipboard.h>
#include <LayoutBuilder.h>
#include "constants.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "AddRepoWindow"
static float sAddWindowWidth = 500.0;
AddRepoWindow::AddRepoWindow(BRect size, BLooper *looper)
:
BWindow(BRect(0,0,sAddWindowWidth,10), "AddWindow", B_MODAL_WINDOW,
B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS | B_CLOSE_ON_ESCAPE),
fReplyLooper(looper)
{
fView = new BView("view", B_SUPPORTS_LAYOUT);
fText = new BTextControl("text", B_TRANSLATE_COMMENT("Depot URL:",
"Text box label"), "", new BMessage(ADD_BUTTON_PRESSED));
fAddButton = new BButton(B_TRANSLATE_COMMENT("Add", "Button label"),
new BMessage(ADD_BUTTON_PRESSED));
fAddButton->MakeDefault(true);
fCancelButton = new BButton(kCancelLabel,
new BMessage(CANCEL_BUTTON_PRESSED));
BLayoutBuilder::Group<>(fView, B_VERTICAL)
.SetInsets(B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING,
B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING)
.Add(fText)
.AddGroup(B_HORIZONTAL, B_USE_DEFAULT_SPACING)
.AddGlue()
.Add(fCancelButton)
.Add(fAddButton);
BLayoutBuilder::Group<>(this, B_VERTICAL)
.Add(fView);
_GetClipboardData();
fText->MakeFocus();
// Move to the center of the preflet window
CenterIn(size);
float widthDifference = size.Width() - Frame().Width();
if(widthDifference < 0)
MoveBy(widthDifference/2.0, 0);
Show();
}
void
AddRepoWindow::Quit()
{
fReplyLooper->PostMessage(ADD_WINDOW_CLOSED);
BWindow::Quit();
}
void
AddRepoWindow::MessageReceived(BMessage* message)
{
switch(message->what)
{
case CANCEL_BUTTON_PRESSED: {
if(QuitRequested())
Quit();
break;
}
case ADD_BUTTON_PRESSED: {
BString url(fText->Text());
if(url != "") {
// URL must have a protocol
if(url.FindFirst("://") == B_ERROR) {
BAlert *alert = new BAlert("error",
B_TRANSLATE_COMMENT("The URL must start with a "
"protocol, for example http:// or https://",
"Add URL error message"),
kOKLabel, NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT);
alert->SetFeel(B_MODAL_APP_WINDOW_FEEL);
alert->Go(NULL);
// Center the alert to this window and move down some
alert->CenterIn(Frame());
alert->MoveBy(0, kAddWindowOffset);
}
else {
BMessage *addMessage = new BMessage(ADD_REPO_URL);
addMessage->AddString(key_url, url);
fReplyLooper->PostMessage(addMessage);
Quit();
}
}
break;
}
default:
BWindow::MessageReceived(message);
}
}
void
AddRepoWindow::FrameResized(float newWidth, float newHeight)
{
sAddWindowWidth = newWidth;
}
status_t
AddRepoWindow::_GetClipboardData()
{
if (be_clipboard->Lock()) {
const char *string;
int32 stringLen;
BMessage *clip = be_clipboard->Data();
clip->FindData("text/plain", B_MIME_TYPE, (const void **)&string,
&stringLen);
be_clipboard->Unlock();
// The string must contain a web protocol
BString clipString(string, stringLen);
int32 ww = clipString.FindFirst("://");
if(ww == B_ERROR)
return B_ERROR;
else
fText->SetText(clipString);
}
return B_OK;
}
<commit_msg>Fix variable type for GCC4<commit_after>/* AddRepoWindow.cpp
* Copyright 2016 Brian Hill
* All rights reserved. Distributed under the terms of the BSD License.
*/
#include "AddRepoWindow.h"
#include <Alert.h>
#include <Application.h>
#include <Catalog.h>
#include <Clipboard.h>
#include <LayoutBuilder.h>
#include "constants.h"
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "AddRepoWindow"
static float sAddWindowWidth = 500.0;
AddRepoWindow::AddRepoWindow(BRect size, BLooper *looper)
:
BWindow(BRect(0,0,sAddWindowWidth,10), "AddWindow", B_MODAL_WINDOW,
B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS | B_CLOSE_ON_ESCAPE),
fReplyLooper(looper)
{
fView = new BView("view", B_SUPPORTS_LAYOUT);
fText = new BTextControl("text", B_TRANSLATE_COMMENT("Depot URL:",
"Text box label"), "", new BMessage(ADD_BUTTON_PRESSED));
fAddButton = new BButton(B_TRANSLATE_COMMENT("Add", "Button label"),
new BMessage(ADD_BUTTON_PRESSED));
fAddButton->MakeDefault(true);
fCancelButton = new BButton(kCancelLabel,
new BMessage(CANCEL_BUTTON_PRESSED));
BLayoutBuilder::Group<>(fView, B_VERTICAL)
.SetInsets(B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING,
B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING)
.Add(fText)
.AddGroup(B_HORIZONTAL, B_USE_DEFAULT_SPACING)
.AddGlue()
.Add(fCancelButton)
.Add(fAddButton);
BLayoutBuilder::Group<>(this, B_VERTICAL)
.Add(fView);
_GetClipboardData();
fText->MakeFocus();
// Move to the center of the preflet window
CenterIn(size);
float widthDifference = size.Width() - Frame().Width();
if(widthDifference < 0)
MoveBy(widthDifference/2.0, 0);
Show();
}
void
AddRepoWindow::Quit()
{
fReplyLooper->PostMessage(ADD_WINDOW_CLOSED);
BWindow::Quit();
}
void
AddRepoWindow::MessageReceived(BMessage* message)
{
switch(message->what)
{
case CANCEL_BUTTON_PRESSED: {
if(QuitRequested())
Quit();
break;
}
case ADD_BUTTON_PRESSED: {
BString url(fText->Text());
if(url != "") {
// URL must have a protocol
if(url.FindFirst("://") == B_ERROR) {
BAlert *alert = new BAlert("error",
B_TRANSLATE_COMMENT("The URL must start with a "
"protocol, for example http:// or https://",
"Add URL error message"),
kOKLabel, NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT);
alert->SetFeel(B_MODAL_APP_WINDOW_FEEL);
alert->Go(NULL);
// Center the alert to this window and move down some
alert->CenterIn(Frame());
alert->MoveBy(0, kAddWindowOffset);
}
else {
BMessage *addMessage = new BMessage(ADD_REPO_URL);
addMessage->AddString(key_url, url);
fReplyLooper->PostMessage(addMessage);
Quit();
}
}
break;
}
default:
BWindow::MessageReceived(message);
}
}
void
AddRepoWindow::FrameResized(float newWidth, float newHeight)
{
sAddWindowWidth = newWidth;
}
status_t
AddRepoWindow::_GetClipboardData()
{
if (be_clipboard->Lock()) {
const char *string;
ssize_t stringLen;
BMessage *clip = be_clipboard->Data();
clip->FindData("text/plain", B_MIME_TYPE, (const void **)&string,
&stringLen);
be_clipboard->Unlock();
// The string must contain a web protocol
BString clipString(string, stringLen);
int32 ww = clipString.FindFirst("://");
if(ww == B_ERROR)
return B_ERROR;
else
fText->SetText(clipString);
}
return B_OK;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPointwiseMutualInformation.cxx
-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkArrayCoordinates.h"
#include "vtkCommand.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPointwiseMutualInformation.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkTypedArray.h"
#include <cmath>
#include <algorithm>
#include <vtkstd/stdexcept>
///////////////////////////////////////////////////////////////////////////////
// vtkPointwiseMutualInformation
vtkCxxRevisionMacro(vtkPointwiseMutualInformation, "1.1");
vtkStandardNewMacro(vtkPointwiseMutualInformation);
vtkPointwiseMutualInformation::vtkPointwiseMutualInformation()
{
}
vtkPointwiseMutualInformation::~vtkPointwiseMutualInformation()
{
}
void vtkPointwiseMutualInformation::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
int vtkPointwiseMutualInformation::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
try
{
// Enforce our input preconditions ...
vtkArrayData* const input_data = vtkArrayData::GetData(inputVector[0]);
if(!input_data)
throw vtkstd::runtime_error("Missing vtkArrayData on input port 0.");
if(input_data->GetNumberOfArrays() != 1)
throw vtkstd::runtime_error("vtkArrayData on input port 0 must contain exactly one vtkArray.");
vtkTypedArray<double>* const input_array = vtkTypedArray<double>::SafeDownCast(input_data->GetArray(0));
if(!input_array)
throw vtkstd::runtime_error("Unsupported input array type.");
const vtkIdType dimension_count = input_array->GetDimensions();
const vtkIdType value_count = input_array->GetNonNullSize();
// This is a portable way to compute log base-2 ...
static const double ln2 = log(2.0);
// Compute array value sums along each dimension ...
double array_sum = 0.0;
vtkstd::vector<vtkstd::vector<double> > dimension_sums(dimension_count);
for(vtkIdType i = 0; i != dimension_count; ++i)
{
dimension_sums[i].resize(input_array->GetExtents()[i], 0.0);
}
vtkArrayCoordinates coordinates;
for(vtkIdType n = 0; n != value_count; ++n)
{
const double value = input_array->GetValueN(n);
input_array->GetCoordinatesN(n, coordinates);
array_sum += value;
for(vtkIdType i = 0; i != dimension_count; ++i)
{
dimension_sums[i][coordinates[i]] += value;
}
}
if(!array_sum)
throw vtkstd::runtime_error("Cannot compute PMI with zero array probability.");
for(vtkIdType i = 0; i != dimension_count; ++i)
{
if(vtkstd::count(dimension_sums[i].begin(), dimension_sums[i].end(), 0))
throw vtkstd::runtime_error("Cannot compute PMI with zero dimension sums.");
}
// Create an output array ...
vtkTypedArray<double>* const output_array = vtkTypedArray<double>::SafeDownCast(input_array->DeepCopy());
vtkArrayData* const output = vtkArrayData::GetData(outputVector);
output->ClearArrays();
output->AddArray(output_array);
output_array->Delete();
// Compute the PMI for each array value ...
for(vtkIdType n = 0; n != value_count; ++n)
{
const double value = input_array->GetValueN(n);
if(!value)
{
output_array->SetValueN(n, 0);
continue;
}
input_array->GetCoordinatesN(n, coordinates);
double result = value / array_sum;
for(vtkIdType i = 0; i != dimension_count; ++i)
{
result /= (value / dimension_sums[i][coordinates[i]]);
}
output_array->SetValueN(n, vtkstd::log(result) / ln2);
}
}
catch(vtkstd::exception& e)
{
vtkErrorMacro(<< "unhandled exception: " << e.what());
return 0;
}
catch(...)
{
vtkErrorMacro(<< "unknown exception");
return 0;
}
return 1;
}
<commit_msg>BUG: Enable vtkPointwiseMutualInformation filter to handle empty input data gracefully.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPointwiseMutualInformation.cxx
-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkArrayCoordinates.h"
#include "vtkCommand.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPointwiseMutualInformation.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkTypedArray.h"
#include <cmath>
#include <algorithm>
#include <vtkstd/stdexcept>
///////////////////////////////////////////////////////////////////////////////
// vtkPointwiseMutualInformation
vtkCxxRevisionMacro(vtkPointwiseMutualInformation, "1.2");
vtkStandardNewMacro(vtkPointwiseMutualInformation);
vtkPointwiseMutualInformation::vtkPointwiseMutualInformation()
{
}
vtkPointwiseMutualInformation::~vtkPointwiseMutualInformation()
{
}
void vtkPointwiseMutualInformation::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
int vtkPointwiseMutualInformation::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
try
{
// Enforce our input preconditions ...
vtkArrayData* const input_data = vtkArrayData::GetData(inputVector[0]);
if(!input_data)
throw vtkstd::runtime_error("Missing vtkArrayData on input port 0.");
if(input_data->GetNumberOfArrays() != 1)
throw vtkstd::runtime_error("vtkArrayData on input port 0 must contain exactly one vtkArray.");
vtkTypedArray<double>* const input_array = vtkTypedArray<double>::SafeDownCast(input_data->GetArray(0));
if(!input_array)
throw vtkstd::runtime_error("Unsupported input array type.");
// Create an output array ...
vtkTypedArray<double>* const output_array = vtkTypedArray<double>::SafeDownCast(input_array->DeepCopy());
vtkArrayData* const output = vtkArrayData::GetData(outputVector);
output->ClearArrays();
output->AddArray(output_array);
output_array->Delete();
const vtkIdType dimension_count = input_array->GetDimensions();
const vtkIdType value_count = input_array->GetNonNullSize();
if(value_count == 0)
{
// Allow for an empty input
return 1;
}
// This is a portable way to compute log base-2 ...
static const double ln2 = log(2.0);
// Compute array value sums along each dimension ...
double array_sum = 0.0;
vtkstd::vector<vtkstd::vector<double> > dimension_sums(dimension_count);
for(vtkIdType i = 0; i != dimension_count; ++i)
{
dimension_sums[i].resize(input_array->GetExtents()[i], 0.0);
}
vtkArrayCoordinates coordinates;
for(vtkIdType n = 0; n != value_count; ++n)
{
const double value = input_array->GetValueN(n);
input_array->GetCoordinatesN(n, coordinates);
array_sum += value;
for(vtkIdType i = 0; i != dimension_count; ++i)
{
dimension_sums[i][coordinates[i]] += value;
}
}
if(!array_sum)
throw vtkstd::runtime_error("Cannot compute PMI with zero array probability.");
for(vtkIdType i = 0; i != dimension_count; ++i)
{
if(vtkstd::count(dimension_sums[i].begin(), dimension_sums[i].end(), 0))
throw vtkstd::runtime_error("Cannot compute PMI with zero dimension sums.");
}
// Compute the PMI for each array value ...
for(vtkIdType n = 0; n != value_count; ++n)
{
const double value = input_array->GetValueN(n);
if(!value)
{
output_array->SetValueN(n, 0);
continue;
}
input_array->GetCoordinatesN(n, coordinates);
double result = value / array_sum;
for(vtkIdType i = 0; i != dimension_count; ++i)
{
result /= (value / dimension_sums[i][coordinates[i]]);
}
output_array->SetValueN(n, vtkstd::log(result) / ln2);
}
}
catch(vtkstd::exception& e)
{
vtkErrorMacro(<< "unhandled exception: " << e.what());
return 0;
}
catch(...)
{
vtkErrorMacro(<< "unknown exception");
return 0;
}
return 1;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2007 Marc Boris Duerner
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
namespace std {
locale::id numpunct<cxxtools::Char>::id;
numpunct<cxxtools::Char>::numpunct(size_t refs)
: locale::facet(refs)
{ }
numpunct<cxxtools::Char>::~numpunct()
{ }
cxxtools::Char numpunct<cxxtools::Char>::decimal_point() const
{ return this->do_decimal_point(); }
cxxtools::Char numpunct<cxxtools::Char>::thousands_sep() const
{ return this->do_thousands_sep(); }
string numpunct<cxxtools::Char>::grouping() const
{ return this->do_grouping(); }
cxxtools::String numpunct<cxxtools::Char>::truename() const
{ return this->do_truename(); }
cxxtools::String numpunct<cxxtools::Char>::falsename() const
{ return this->do_falsename(); }
cxxtools::Char numpunct<cxxtools::Char>::do_decimal_point() const
{ return '.'; }
cxxtools::Char numpunct<cxxtools::Char>::do_thousands_sep() const
{ return ','; }
std::string numpunct<cxxtools::Char>::do_grouping() const
{ return ""; }
cxxtools::String numpunct<cxxtools::Char>::do_truename() const
{
static const cxxtools::Char truename[] = {'t', 'r', 'u', 'e', '\0'};
return truename;
}
cxxtools::String numpunct<cxxtools::Char>::do_falsename() const
{
static const cxxtools::Char falsename[] = {'f', 'a', 'l', 's', 'e', '\0'};
return falsename;
}
}
<commit_msg>added #include facets.h in facets.cpp<commit_after>/*
* Copyright (C) 2004-2007 Marc Boris Duerner
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cxxtools/facets.h>
namespace std {
locale::id numpunct<cxxtools::Char>::id;
numpunct<cxxtools::Char>::numpunct(size_t refs)
: locale::facet(refs)
{ }
numpunct<cxxtools::Char>::~numpunct()
{ }
cxxtools::Char numpunct<cxxtools::Char>::decimal_point() const
{ return this->do_decimal_point(); }
cxxtools::Char numpunct<cxxtools::Char>::thousands_sep() const
{ return this->do_thousands_sep(); }
string numpunct<cxxtools::Char>::grouping() const
{ return this->do_grouping(); }
cxxtools::String numpunct<cxxtools::Char>::truename() const
{ return this->do_truename(); }
cxxtools::String numpunct<cxxtools::Char>::falsename() const
{ return this->do_falsename(); }
cxxtools::Char numpunct<cxxtools::Char>::do_decimal_point() const
{ return '.'; }
cxxtools::Char numpunct<cxxtools::Char>::do_thousands_sep() const
{ return ','; }
std::string numpunct<cxxtools::Char>::do_grouping() const
{ return ""; }
cxxtools::String numpunct<cxxtools::Char>::do_truename() const
{
static const cxxtools::Char truename[] = {'t', 'r', 'u', 'e', '\0'};
return truename;
}
cxxtools::String numpunct<cxxtools::Char>::do_falsename() const
{
static const cxxtools::Char falsename[] = {'f', 'a', 'l', 's', 'e', '\0'};
return falsename;
}
}
<|endoftext|> |
<commit_before>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>
AndroidClientCache::AndroidClientCache(JNIEnv * _env) {
_env->GetJavaVM(&javaVM);
auto env = getJNIEnv();
cookieManagerClass = (jclass) env->NewGlobalRef(env->FindClass("android/webkit/CookieManager"));
httpClass = (jclass) env->NewGlobalRef(env->FindClass("java/net/HttpURLConnection"));
urlClass = (jclass) env->NewGlobalRef(env->FindClass("java/net/URL"));
inputStreamClass = (jclass) env->NewGlobalRef(env->FindClass("java/io/InputStream"));
frameworkClass = (jclass) env->NewGlobalRef(env->FindClass("com/sometrik/framework/FrameWork"));
getHeaderMethod = env->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
getHeaderMethodInt = env->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
getHeaderKeyMethod = env->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
urlConstructor = env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
connectMethod = env->GetMethodID(httpClass, "connect", "()V");
getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
setRequestPropertyMethod = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
clearCookiesMethod = env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
getInputStreamMethod = env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
getErrorStreamMethod = env->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
handleThrowableMethod = env->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V");
}
AndroidClientCache::~AndroidClientCache() {
auto env = getJNIEnv();
env->DeleteGlobalRef(cookieManagerClass);
env->DeleteGlobalRef(httpClass);
env->DeleteGlobalRef(urlClass);
env->DeleteGlobalRef(inputStreamClass);
env->DeleteGlobalRef(frameworkClass);
}
class AndroidClient : public HTTPClient {
public:
AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
: HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) {
}
void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) {
JNIEnv * env = cache->getJNIEnv();
__android_log_print(ANDROID_LOG_INFO, "AndroidClien", "Host = %s", req.getURI().c_str());
jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, env->NewStringUTF(req.getURI().c_str()));
jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod);
env->DeleteLocalRef(url),
//Authorization example
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
// std::string auth_header = auth.createHeader();
// if (!auth_header.empty()) {
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
// }
env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);
//Apply user agent
const char * cuser_agent = user_agent.c_str();
const char * cuser_agent_key = "User-Agent";
jstring juser_agent = env->NewStringUTF(user_agent.c_str());
jstring juser_agent_key = env->NewStringUTF(cuser_agent_key);
env->CallVoidMethod(connection, cache->setRequestProperty, juser_agent_key, juser_agent);
env->DeleteLocalRef(juser_agent);
env->DeleteLocalRef(juser_agent_key);
// Setting headers for request
std::map<std::string, std::string> combined_headers;
for (auto & hd : default_headers) {
combined_headers[hd.first] = hd.second;
}
for (auto & hd : req.getHeaders()) {
combined_headers[hd.first] = hd.second;
}
for (auto & hd : combined_headers) {
jstring firstHeader = env->NewStringUTF(hd.first.c_str());
jstring secondHeader = env->NewStringUTF(hd.second.c_str());
env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader);
env->ReleaseStringUTFChars(firstHeader, hd.first.c_str());
env->ReleaseStringUTFChars(secondHeader, hd.second.c_str());
}
env->CallVoidMethod(connection, cache->setRequestMethod, env->NewStringUTF(req.getTypeString()));
int responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod);
__android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "the real problem is here?");
// Server not found error
if (env->ExceptionCheck()) {
jthrowable error = env->ExceptionOccurred();
env->ExceptionClear();
env->CallStaticVoidMethod(cache->frameworkClass, cache->handleThrowableMethod, error);
env->DeleteLocalRef(error);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCEPTION http request responsecode = %i", responseCode);
callback.handleResultCode(500);
// callback->handleResultText("Server not found");
return;
}
callback.handleResultCode(responseCode);
const char *errorMessage = "";
jobject input;
if (responseCode >= 400 && responseCode <= 599) {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "request responsecode = %i", responseCode);
jstring javaMessage = (jstring)env->CallObjectMethod(connection, cache->getResponseMessageMethod);
errorMessage = env->GetStringUTFChars(javaMessage, 0);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "errorMessage = %s", errorMessage);
input = env->CallObjectMethod(connection, cache->getErrorStreamMethod);
} else {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);
input = env->CallObjectMethod(connection, cache->getInputStreamMethod);
env->ExceptionClear();
}
jbyteArray array = env->NewByteArray(4096);
int g = 0;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Starting to gather content");
// Gather headers and values
for (int i = 0; ; i++) {
jstring jheaderKey = (jstring)env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i);
const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header key = %s", headerKey);
jstring jheader = (jstring)env->CallObjectMethod(connection, cache->getHeaderMethodInt, i);
const char * header = env->GetStringUTFChars(jheader, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header value = %s", header);
if (headerKey == NULL) {
break;
}
callback.handleHeader(headerKey, header);
env->ReleaseStringUTFChars(jheaderKey, headerKey);
env->ReleaseStringUTFChars(jheader, header);
env->DeleteLocalRef(jheaderKey);
env->DeleteLocalRef(jheader);
}
// Gather content
while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) {
jbyte* content_array = env->GetByteArrayElements(array, NULL);
callback.handleChunk(g, (char*) content_array);
env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
}
env->DeleteLocalRef(array);
if (responseCode >= 300 && responseCode <= 399) {
jstring followURL = (jstring)env->CallObjectMethod(connection, cache->getHeaderMethod, env->NewStringUTF("location"));
const char *followString = env->GetStringUTFChars(followURL, 0);
callback.handleRedirectUrl(followString);
__android_log_print(ANDROID_LOG_INFO, "content", "followURL = %s", followString);
env->ReleaseStringUTFChars(followURL, followString);
env->DeleteLocalRef(followURL);
}
__android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "nope");
env->DeleteLocalRef(input);
env->DeleteLocalRef(connection);
}
void clearCookies() {
JNIEnv * env = cache->getJNIEnv();
env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod);
}
private:
std::shared_ptr<AndroidClientCache> cache;
};
std::unique_ptr<HTTPClient>
AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive));
}
<commit_msg>Remove stupid print<commit_after>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>
AndroidClientCache::AndroidClientCache(JNIEnv * _env) {
_env->GetJavaVM(&javaVM);
auto env = getJNIEnv();
cookieManagerClass = (jclass) env->NewGlobalRef(env->FindClass("android/webkit/CookieManager"));
httpClass = (jclass) env->NewGlobalRef(env->FindClass("java/net/HttpURLConnection"));
urlClass = (jclass) env->NewGlobalRef(env->FindClass("java/net/URL"));
inputStreamClass = (jclass) env->NewGlobalRef(env->FindClass("java/io/InputStream"));
frameworkClass = (jclass) env->NewGlobalRef(env->FindClass("com/sometrik/framework/FrameWork"));
getHeaderMethod = env->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
getHeaderMethodInt = env->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
getHeaderKeyMethod = env->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
urlConstructor = env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
connectMethod = env->GetMethodID(httpClass, "connect", "()V");
getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
setRequestPropertyMethod = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
clearCookiesMethod = env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
getInputStreamMethod = env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
getErrorStreamMethod = env->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
handleThrowableMethod = env->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V");
}
AndroidClientCache::~AndroidClientCache() {
auto env = getJNIEnv();
env->DeleteGlobalRef(cookieManagerClass);
env->DeleteGlobalRef(httpClass);
env->DeleteGlobalRef(urlClass);
env->DeleteGlobalRef(inputStreamClass);
env->DeleteGlobalRef(frameworkClass);
}
class AndroidClient : public HTTPClient {
public:
AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
: HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) {
}
void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) {
JNIEnv * env = cache->getJNIEnv();
__android_log_print(ANDROID_LOG_INFO, "AndroidClien", "Host = %s", req.getURI().c_str());
jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, env->NewStringUTF(req.getURI().c_str()));
jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod);
env->DeleteLocalRef(url),
//Authorization example
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
// std::string auth_header = auth.createHeader();
// if (!auth_header.empty()) {
// env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
// }
env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);
//Apply user agent
const char * cuser_agent = user_agent.c_str();
const char * cuser_agent_key = "User-Agent";
jstring juser_agent = env->NewStringUTF(user_agent.c_str());
jstring juser_agent_key = env->NewStringUTF(cuser_agent_key);
env->CallVoidMethod(connection, cache->setRequestProperty, juser_agent_key, juser_agent);
env->DeleteLocalRef(juser_agent);
env->DeleteLocalRef(juser_agent_key);
// Setting headers for request
std::map<std::string, std::string> combined_headers;
for (auto & hd : default_headers) {
combined_headers[hd.first] = hd.second;
}
for (auto & hd : req.getHeaders()) {
combined_headers[hd.first] = hd.second;
}
for (auto & hd : combined_headers) {
jstring firstHeader = env->NewStringUTF(hd.first.c_str());
jstring secondHeader = env->NewStringUTF(hd.second.c_str());
env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader);
env->ReleaseStringUTFChars(firstHeader, hd.first.c_str());
env->ReleaseStringUTFChars(secondHeader, hd.second.c_str());
}
env->CallVoidMethod(connection, cache->setRequestMethod, env->NewStringUTF(req.getTypeString()));
int responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod);
__android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "the real problem is here?");
// Server not found error
if (env->ExceptionCheck()) {
jthrowable error = env->ExceptionOccurred();
env->ExceptionClear();
env->CallStaticVoidMethod(cache->frameworkClass, cache->handleThrowableMethod, error);
env->DeleteLocalRef(error);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCEPTION http request responsecode = %i", responseCode);
callback.handleResultCode(500);
// callback->handleResultText("Server not found");
return;
}
callback.handleResultCode(responseCode);
const char *errorMessage = "";
jobject input;
if (responseCode >= 400 && responseCode <= 599) {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "request responsecode = %i", responseCode);
jstring javaMessage = (jstring)env->CallObjectMethod(connection, cache->getResponseMessageMethod);
errorMessage = env->GetStringUTFChars(javaMessage, 0);
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "errorMessage = %s", errorMessage);
input = env->CallObjectMethod(connection, cache->getErrorStreamMethod);
} else {
__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);
input = env->CallObjectMethod(connection, cache->getInputStreamMethod);
env->ExceptionClear();
}
jbyteArray array = env->NewByteArray(4096);
int g = 0;
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Starting to gather content");
// Gather headers and values
for (int i = 0; ; i++) {
jstring jheaderKey = (jstring)env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i);
if (jheaderKey == NULL) {
break;
}
const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header key = %s", headerKey);
jstring jheader = (jstring)env->CallObjectMethod(connection, cache->getHeaderMethodInt, i);
const char * header = env->GetStringUTFChars(jheader, 0);
__android_log_print(ANDROID_LOG_INFO, "content", "header value = %s", header);
callback.handleHeader(headerKey, header);
env->ReleaseStringUTFChars(jheaderKey, headerKey);
env->ReleaseStringUTFChars(jheader, header);
env->DeleteLocalRef(jheaderKey);
env->DeleteLocalRef(jheader);
}
// Gather content
while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) {
jbyte* content_array = env->GetByteArrayElements(array, NULL);
callback.handleChunk(g, (char*) content_array);
env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
}
env->DeleteLocalRef(array);
if (responseCode >= 300 && responseCode <= 399) {
jstring followURL = (jstring)env->CallObjectMethod(connection, cache->getHeaderMethod, env->NewStringUTF("location"));
const char *followString = env->GetStringUTFChars(followURL, 0);
callback.handleRedirectUrl(followString);
__android_log_print(ANDROID_LOG_INFO, "content", "followURL = %s", followString);
env->ReleaseStringUTFChars(followURL, followString);
env->DeleteLocalRef(followURL);
}
env->DeleteLocalRef(input);
env->DeleteLocalRef(connection);
}
void clearCookies() {
JNIEnv * env = cache->getJNIEnv();
env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod);
}
private:
std::shared_ptr<AndroidClientCache> cache;
};
std::unique_ptr<HTTPClient>
AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive));
}
<|endoftext|> |
<commit_before>// ElementSet.cpp
#include "ElementSet.h"
//------------------------------------------------------------------------------------------
// Element
//------------------------------------------------------------------------------------------
Element::Element( void )
{
collection = nullptr;
}
Element::Element( const Element& element )
{
collection = nullptr;
element.permutation.GetCopy( permutation );
element.word.GetCopy( word );
}
Element::~Element( void )
{
}
void Element::Identity( void )
{
word.termList.clear();
permutation.map->clear();
}
bool Element::operator==( const Element& element ) const
{
if( collection )
return collection->AreEqual( *this, element );
return permutation.IsEqualTo( element.permutation );
}
void Element::operator=( const Element& element )
{
element.word.GetCopy( word );
element.permutation.GetCopy( permutation );
}
bool Element::Multiply( const Element& elementA, const Element& elementB )
{
word.Multiply( elementA.word, elementB.word );
permutation.Multiply( elementA.permutation, elementB.permutation );
return true;
}
bool Element::MultiplyOnRight( const Element& element )
{
word.MultiplyOnRight( element.word );
permutation.MultiplyOnRight( element.permutation );
return true;
}
bool Element::MultiplyOnLeft( const Element& element )
{
word.MultiplyOnLeft( element.word );
permutation.MultiplyOnleft( element.permutation );
return true;
}
bool Element::SetInverse( const Element& element )
{
return element.GetInverse( *this );
}
bool Element::GetInverse( Element& element ) const
{
word.GetInverse( element.word );
return permutation.GetInverse( element.permutation );
}
std::size_t Element::CalcHash( void ) const
{
if( collection )
return collection->CalcHash( *this );
return permutation.CalcHash();
}
void Element::Print( std::ostream& ostream ) const
{
word.Print( ostream );
ostream << " = ";
permutation.Print( ostream );
ostream << "\n";
}
//------------------------------------------------------------------------------------------
// ElementCollection
//------------------------------------------------------------------------------------------
ElementCollection::ElementCollection( void )
{
}
/*virtual*/ ElementCollection::~ElementCollection( void )
{
}
bool ElementCollection::AddElement( Element& element )
{
ElementSet::iterator iter;
if( IsMember( element, &iter ) )
return false;
element.collection = this;
elementSet.insert( element );
return true;
}
bool ElementCollection::RemoveElement( Element& element )
{
ElementSet::iterator iter;
if( !IsMember( element, &iter ) )
return false;
element.collection = nullptr;
elementSet.erase( iter );
return true;
}
void ElementCollection::RemoveAllElements( void )
{
elementSet.clear();
}
bool ElementCollection::IsMember( Element& element, ElementSet::iterator* foundIter /*= nullptr*/ )
{
ElementSet::iterator iter = elementSet.find( element );
if( iter == elementSet.end() )
return false;
if( foundIter )
*foundIter = iter;
return true;
}
/*virtual*/ bool ElementCollection::AreEqual( const Element& elementA, const Element& elementB )
{
return elementA.permutation.IsEqualTo( elementB.permutation );
}
/*virtual*/ std::size_t ElementCollection::CalcHash( const Element& element ) const
{
return element.permutation.CalcHash();
}
bool ElementCollection::GenerateGroup( std::ostream* ostream /*= nullptr*/ )
{
ElementSet elementQueue;
while( elementSet.size() > 0 )
{
ElementSet::iterator iter = elementSet.begin();
const Element& element = *iter;
if( !element.permutation.IsValid() )
return false;
elementQueue.insert( element );
elementSet.erase( iter );
}
Element identity;
elementSet.insert( identity );
while( elementQueue.size() > 0 )
{
ElementSet::iterator queueIter = elementQueue.begin();
Element newElement = *queueIter;
elementQueue.erase( queueIter );
// TODO: Despite this conditional, can I prove the correctness of this algorithm?
if( !IsMember( newElement ) )
{
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& element = *iter;
for( int i = 0; i < 2; i++ )
{
Element product;
if( i == 0 )
product.Multiply( newElement, element );
else
product.Multiply( element, newElement );
bool foundInSet = IsMember( product );
bool foundInQueue = ( elementQueue.find( product ) == elementQueue.end() ) ? false : true;
if( !( foundInSet || foundInQueue ) )
elementQueue.insert( product );
}
}
elementSet.insert( newElement );
if( ostream )
*ostream << "SetSize: " << elementSet.size() << ", QueueSize: " << elementQueue.size() << "\n";
}
}
return true;
}
// Of course, if we're a group, then this is the order of the group.
uint ElementCollection::Cardinality( void ) const
{
return ( uint )elementSet.size();
}
void ElementCollection::Print( std::ostream& ostream ) const
{
ostream << "Cardinality: " << Cardinality() << "\n";
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& element = *iter;
element.Print( ostream );
}
}
//------------------------------------------------------------------------------------------
// CosetCollection
//------------------------------------------------------------------------------------------
CosetCollection::CosetCollection( void )
{
}
/*virtual*/ CosetCollection::~CosetCollection( void )
{
}
bool CosetCollection::AreInSameCoset( const Permutation& permutationA, const Permutation& permutationB ) const
{
Permutation invPermutationA;
permutationA.GetInverse( invPermutationA );
Permutation product;
product.Multiply( invPermutationA, permutationB );
return IsInQuotientGroup( product );
}
bool CosetCollection::IsInQuotientGroup( const Permutation& permutation ) const
{
NaturalNumberSet permUnstableSet;
permutation.GetUnstableSet( permUnstableSet );
return permUnstableSet.IsSubsetOf( unstableSet );
}
/*virtual*/ bool CosetCollection::AreEqual( const Element& elementA, const Element& elementB )
{
return AreInSameCoset( elementA.permutation, elementB.permutation );
}
/*virtual*/ std::size_t CosetCollection::CalcHash( const Element& element ) const
{
// Unfortunately, I'm not sure how to get around doing this linear search.
// What it means is that we're essentially defeating the purpose of using a hash table.
// What we would have to do to fix this is make sure that elements that would fall
// under the same coset always hash to the same value. I'm not sure how to do that.
const Element* cosetRepresentative = FindCosetRepresentative( element );
if( cosetRepresentative )
return cosetRepresentative->CalcHash();
return element.CalcHash();
}
const Element* CosetCollection::FindCosetRepresentative( const Element& element ) const
{
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& existingElement = *iter;
if( AreInSameCoset( existingElement.permutation, element.permutation ) )
return &existingElement;
}
return nullptr;
}
// ElementSet.cpp<commit_msg>i feel dumb<commit_after>// ElementSet.cpp
#include "ElementSet.h"
//------------------------------------------------------------------------------------------
// Element
//------------------------------------------------------------------------------------------
Element::Element( void )
{
collection = nullptr;
}
Element::Element( const Element& element )
{
collection = nullptr;
element.permutation.GetCopy( permutation );
element.word.GetCopy( word );
}
Element::~Element( void )
{
}
void Element::Identity( void )
{
word.termList.clear();
permutation.map->clear();
}
bool Element::operator==( const Element& element ) const
{
if( collection )
return collection->AreEqual( *this, element );
return permutation.IsEqualTo( element.permutation );
}
void Element::operator=( const Element& element )
{
element.word.GetCopy( word );
element.permutation.GetCopy( permutation );
}
bool Element::Multiply( const Element& elementA, const Element& elementB )
{
word.Multiply( elementA.word, elementB.word );
permutation.Multiply( elementA.permutation, elementB.permutation );
return true;
}
bool Element::MultiplyOnRight( const Element& element )
{
word.MultiplyOnRight( element.word );
permutation.MultiplyOnRight( element.permutation );
return true;
}
bool Element::MultiplyOnLeft( const Element& element )
{
word.MultiplyOnLeft( element.word );
permutation.MultiplyOnLeft( element.permutation );
return true;
}
bool Element::SetInverse( const Element& element )
{
return element.GetInverse( *this );
}
bool Element::GetInverse( Element& element ) const
{
word.GetInverse( element.word );
return permutation.GetInverse( element.permutation );
}
std::size_t Element::CalcHash( void ) const
{
if( collection )
return collection->CalcHash( *this );
return permutation.CalcHash();
}
void Element::Print( std::ostream& ostream ) const
{
word.Print( ostream );
ostream << " = ";
permutation.Print( ostream );
ostream << "\n";
}
//------------------------------------------------------------------------------------------
// ElementCollection
//------------------------------------------------------------------------------------------
ElementCollection::ElementCollection( void )
{
}
/*virtual*/ ElementCollection::~ElementCollection( void )
{
}
bool ElementCollection::AddElement( Element& element )
{
ElementSet::iterator iter;
if( IsMember( element, &iter ) )
return false;
element.collection = this;
elementSet.insert( element );
return true;
}
bool ElementCollection::RemoveElement( Element& element )
{
ElementSet::iterator iter;
if( !IsMember( element, &iter ) )
return false;
element.collection = nullptr;
elementSet.erase( iter );
return true;
}
void ElementCollection::RemoveAllElements( void )
{
elementSet.clear();
}
bool ElementCollection::IsMember( Element& element, ElementSet::iterator* foundIter /*= nullptr*/ )
{
ElementSet::iterator iter = elementSet.find( element );
if( iter == elementSet.end() )
return false;
if( foundIter )
*foundIter = iter;
return true;
}
/*virtual*/ bool ElementCollection::AreEqual( const Element& elementA, const Element& elementB )
{
return elementA.permutation.IsEqualTo( elementB.permutation );
}
/*virtual*/ std::size_t ElementCollection::CalcHash( const Element& element ) const
{
return element.permutation.CalcHash();
}
bool ElementCollection::GenerateGroup( std::ostream* ostream /*= nullptr*/ )
{
ElementSet elementQueue;
while( elementSet.size() > 0 )
{
ElementSet::iterator iter = elementSet.begin();
const Element& element = *iter;
if( !element.permutation.IsValid() )
return false;
elementQueue.insert( element );
elementSet.erase( iter );
}
Element identity;
elementSet.insert( identity );
while( elementQueue.size() > 0 )
{
ElementSet::iterator queueIter = elementQueue.begin();
Element newElement = *queueIter;
elementQueue.erase( queueIter );
// TODO: Despite this conditional, can I prove the correctness of this algorithm?
// One approach is to use an inductive argument on the size of the generating
// set under the condition that our queue be a stack. I just can't quite see
// the final argument. We have H<G, and g in G-H. Will we take H to G using g?
// I think we can argue that we'll get H, gH, ..., g^{|g|-1}H, but the index of
// H in G is not necessarily |g|. Here's a better argument. We know the algorithm
// terminates. Fine. Now consider the result as an array of elements. Can we
// argue that for any element in that array, it has been compared with all elements
// left of it and all elements right of it in the array? I think we can, but that's
// not quite enough.
if( !IsMember( newElement ) )
{
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& element = *iter;
for( int i = 0; i < 2; i++ )
{
Element product;
if( i == 0 )
product.Multiply( newElement, element );
else
product.Multiply( element, newElement );
bool foundInSet = IsMember( product );
bool foundInQueue = ( elementQueue.find( product ) == elementQueue.end() ) ? false : true;
if( !( foundInSet || foundInQueue ) )
elementQueue.insert( product );
}
}
elementSet.insert( newElement );
if( ostream )
*ostream << "SetSize: " << elementSet.size() << ", QueueSize: " << elementQueue.size() << "\n";
}
}
return true;
}
// Of course, if we're a group, then this is the order of the group.
uint ElementCollection::Cardinality( void ) const
{
return ( uint )elementSet.size();
}
void ElementCollection::Print( std::ostream& ostream ) const
{
ostream << "Cardinality: " << Cardinality() << "\n";
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& element = *iter;
element.Print( ostream );
}
}
//------------------------------------------------------------------------------------------
// CosetCollection
//------------------------------------------------------------------------------------------
CosetCollection::CosetCollection( void )
{
}
/*virtual*/ CosetCollection::~CosetCollection( void )
{
}
bool CosetCollection::AreInSameCoset( const Permutation& permutationA, const Permutation& permutationB ) const
{
Permutation invPermutationA;
permutationA.GetInverse( invPermutationA );
Permutation product;
product.Multiply( invPermutationA, permutationB );
return IsInQuotientGroup( product );
}
bool CosetCollection::IsInQuotientGroup( const Permutation& permutation ) const
{
NaturalNumberSet permUnstableSet;
permutation.GetUnstableSet( permUnstableSet );
return permUnstableSet.IsSubsetOf( unstableSet );
}
/*virtual*/ bool CosetCollection::AreEqual( const Element& elementA, const Element& elementB )
{
return AreInSameCoset( elementA.permutation, elementB.permutation );
}
/*virtual*/ std::size_t CosetCollection::CalcHash( const Element& element ) const
{
// Unfortunately, I'm not sure how to get around doing this linear search.
// What it means is that we're essentially defeating the purpose of using a hash table.
// What we would have to do to fix this is make sure that elements that would fall
// under the same coset always hash to the same value. I'm not sure how to do that.
const Element* cosetRepresentative = FindCosetRepresentative( element );
if( cosetRepresentative )
return cosetRepresentative->CalcHash();
return element.CalcHash();
}
const Element* CosetCollection::FindCosetRepresentative( const Element& element ) const
{
for( ElementSet::const_iterator iter = elementSet.cbegin(); iter != elementSet.cend(); iter++ )
{
const Element& existingElement = *iter;
if( AreInSameCoset( existingElement.permutation, element.permutation ) )
return &existingElement;
}
return nullptr;
}
// ElementSet.cpp<|endoftext|> |
<commit_before>#include "pch.h"
#include "AudioRenderer.h"
namespace SaneAudioRenderer
{
AudioRenderer::AudioRenderer(ISettings* pSettings, IMyClock* pClock, HRESULT& result)
: m_deviceManager(result)
, m_myClock(pClock)
, m_flush(TRUE/*manual reset*/)
, m_dspVolume(*this)
, m_dspBalance(*this)
, m_settings(pSettings)
{
if (FAILED(result))
return;
try
{
if (!m_settings || !m_myClock)
throw E_UNEXPECTED;
ThrowIfFailed(m_myClock->QueryInterface(IID_PPV_ARGS(&m_myGraphClock)));
if (static_cast<HANDLE>(m_flush) == NULL)
{
throw E_OUTOFMEMORY;
}
}
catch (HRESULT ex)
{
result = ex;
}
}
AudioRenderer::~AudioRenderer()
{
// Just in case.
if (m_state != State_Stopped)
Stop();
}
void AudioRenderer::SetClock(IReferenceClock* pClock)
{
CAutoLock objectLock(this);
m_graphClock = pClock;
if (m_graphClock && m_graphClock != m_myGraphClock)
{
if (!m_externalClock)
ClearDevice();
m_externalClock = true;
}
else
{
if (m_externalClock)
ClearDevice();
m_externalClock = false;
}
}
bool AudioRenderer::OnExternalClock()
{
CAutoLock objectLock(this);
return m_externalClock;
}
bool AudioRenderer::Enqueue(IMediaSample* pSample, AM_SAMPLE2_PROPERTIES& sampleProps, CAMEvent* pFilledEvent)
{
DspChunk chunk;
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_state != State_Stopped);
try
{
// Clear the device if related settings were changed.
CheckDeviceSettings();
// Create the device if needed.
if (!m_device)
CreateDevice();
// Apply sample corrections (pad, crop, guess timings).
chunk = m_sampleCorrection.ProcessSample(pSample, sampleProps);
// Apply clock corrections (graph clock and rate dsp).
if (m_device && m_state == State_Running)
ApplyClockCorrection();
// Apply dsp chain.
if (m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
pDsp->Process(chunk);
};
EnumerateProcessors(f);
DspChunk::ToFormat(m_device->GetDspFormat(), chunk);
}
}
catch (std::bad_alloc&)
{
ClearDevice();
chunk = DspChunk();
}
}
// Send processed sample to the device.
return Push(chunk, pFilledEvent);
}
bool AudioRenderer::Finish(bool blockUntilEnd, CAMEvent* pFilledEvent)
{
DspChunk chunk;
{
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
// No device - nothing to block on.
if (!m_device)
blockUntilEnd = false;
try
{
// Apply dsp chain.
if (m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
pDsp->Finish(chunk);
};
EnumerateProcessors(f);
DspChunk::ToFormat(m_device->GetDspFormat(), chunk);
}
}
catch (std::bad_alloc&)
{
chunk = DspChunk();
assert(chunk.IsEmpty());
}
}
auto doBlock = [this]
{
// Increase system timer resolution.
TimePeriodHelper timePeriodHelper(1);
// Unslave the clock because no more samples are going to be pushed.
m_myClock->UnslaveClockFromAudio();
for (;;)
{
int64_t actual = INT64_MAX;
int64_t target;
{
CAutoLock objectLock(this);
if (!m_device)
return true;
const auto previous = actual;
actual = m_device->GetPosition();
target = m_device->GetEnd();
// Return if the end of stream is reached.
if (actual == target)
return true;
// Stalling protection.
if (actual == previous && m_state == State_Running)
return true;
}
// Sleep until predicted end of stream.
if (m_flush.Wait(std::max(1, (int32_t)((target - actual) * 1000 / OneSecond))))
return false;
}
};
// Send processed sample to the device, and block until the buffer is drained (if requested).
return Push(chunk, pFilledEvent) && (!blockUntilEnd || doBlock());
}
void AudioRenderer::BeginFlush()
{
m_flush.Set();
}
void AudioRenderer::EndFlush()
{
CAutoLock objectLock(this);
assert(m_state != State_Running);
if (m_device)
{
m_device->Reset();
m_sampleCorrection.NewDeviceBuffer();
}
m_flush.Reset();
}
bool AudioRenderer::CheckFormat(SharedWaveFormat inputFormat)
{
assert(inputFormat);
if (DspFormatFromWaveFormat(*inputFormat) != DspFormat::Unknown)
return true;
BOOL exclusive;
m_settings->GetOuputDevice(nullptr, &exclusive, nullptr);
BOOL bitstreamingAllowed;
m_settings->GetAllowBitstreaming(&bitstreamingAllowed);
if (!exclusive || !bitstreamingAllowed)
return false;
CAutoLock objectLock(this);
return m_deviceManager.BitstreamFormatSupported(inputFormat, m_settings);
}
void AudioRenderer::SetFormat(SharedWaveFormat inputFormat, bool live)
{
CAutoLock objectLock(this);
m_inputFormat = inputFormat;
m_live = live;
m_sampleCorrection.NewFormat(inputFormat);
ClearDevice();
}
void AudioRenderer::NewSegment(double rate)
{
CAutoLock objectLock(this);
m_startClockOffset = 0;
m_rate = rate;
m_sampleCorrection.NewSegment(m_rate);
assert(m_inputFormat);
if (m_device)
InitializeProcessors();
}
void AudioRenderer::Play(REFERENCE_TIME startTime)
{
CAutoLock objectLock(this);
assert(m_state != State_Running);
m_state = State_Running;
m_startTime = startTime;
StartDevice();
}
void AudioRenderer::Pause()
{
CAutoLock objectLock(this);
m_state = State_Paused;
if (m_device)
{
m_myClock->UnslaveClockFromAudio();
m_device->Stop();
}
}
void AudioRenderer::Stop()
{
CAutoLock objectLock(this);
m_state = State_Stopped;
ClearDevice();
}
SharedWaveFormat AudioRenderer::GetInputFormat()
{
CAutoLock objectLock(this);
return m_inputFormat;
}
AudioDevice const* AudioRenderer::GetAudioDevice()
{
assert(CritCheckIn(this));
return m_device.get();
}
std::vector<std::wstring> AudioRenderer::GetActiveProcessors()
{
CAutoLock objectLock(this);
std::vector<std::wstring> ret;
if (m_inputFormat && m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
if (pDsp->Active())
ret.emplace_back(pDsp->Name());
};
EnumerateProcessors(f);
}
return ret;
}
void AudioRenderer::CheckDeviceSettings()
{
CAutoLock objectLock(this);
UINT32 serial = m_settings->GetSerial();
if (m_device && m_deviceSettingsSerial != serial)
{
LPWSTR pDeviceName = nullptr;
BOOL exclusive;
UINT32 buffer;
if (SUCCEEDED(m_settings->GetOuputDevice(&pDeviceName, &exclusive, &buffer)))
{
if (m_device->IsExclusive() != !!exclusive ||
m_device->GetBufferDuration() != buffer ||
(pDeviceName && *pDeviceName && wcscmp(pDeviceName, m_device->GetFriendlyName()->c_str())) ||
((!pDeviceName || !*pDeviceName) && !m_device->IsDefault()))
{
ClearDevice();
assert(!m_device);
}
else
{
m_deviceSettingsSerial = serial;
}
CoTaskMemFree(pDeviceName);
}
}
}
void AudioRenderer::StartDevice()
{
CAutoLock objectLock(this);
assert(m_state == State_Running);
if (m_device)
{
m_myClock->SlaveClockToAudio(m_device->GetClock(), m_startTime + m_startClockOffset);
m_startClockOffset = 0;
m_device->Start();
}
}
void AudioRenderer::CreateDevice()
{
CAutoLock objectLock(this);
assert(!m_device);
assert(m_inputFormat);
m_deviceSettingsSerial = m_settings->GetSerial();
m_device = m_deviceManager.CreateDevice(m_inputFormat, m_live, m_settings);
if (m_device)
{
m_sampleCorrection.NewDeviceBuffer();
InitializeProcessors();
m_startClockOffset = m_sampleCorrection.GetLastSampleEnd();
if (m_state == State_Running)
StartDevice();
}
}
void AudioRenderer::ClearDevice()
{
CAutoLock objectLock(this);
if (m_device)
{
m_myClock->UnslaveClockFromAudio();
m_device->Stop();
m_device = nullptr;
}
}
void AudioRenderer::ApplyClockCorrection()
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_device);
assert(m_state == State_Running);
// Apply corrections to internal clock.
{
REFERENCE_TIME offset = m_sampleCorrection.GetTimingsError() - m_myClock->GetSlavedClockOffset();
if (std::abs(offset) > 1000)
{
m_myClock->OffsetSlavedClock(offset);
DebugOut("AudioRenderer offset internal clock by", offset / 10000., "ms");
}
}
/*
// Try to match internal clock with graph clock if they're different.
// We do it in the roundabout way by dynamically changing audio sampling rate.
if (m_externalClock && !m_device->bitstream)
{
assert(m_dspRate.Active());
REFERENCE_TIME graphTime, myTime, myStartTime;
if (SUCCEEDED(m_myClock->GetAudioClockStartTime(&myStartTime)) &&
SUCCEEDED(m_myClock->GetAudioClockTime(&myTime, nullptr)) &&
SUCCEEDED(GetGraphTime(graphTime)) &&
myTime > myStartTime)
{
REFERENCE_TIME offset = graphTime - myTime - m_correctedWithRateDsp;
if (std::abs(offset) > MILLISECONDS_TO_100NS_UNITS(2))
{
m_dspRate.Adjust(offset);
m_correctedWithRateDsp += offset;
DebugOut("AudioRenderer offset internal clock indirectly by", offset / 10000., "ms");
}
}
}
*/
}
HRESULT AudioRenderer::GetGraphTime(REFERENCE_TIME& time)
{
CAutoLock objectLock(this);
return m_graphClock ?
m_graphClock->GetTime(&time) :
m_myGraphClock->GetTime(&time);
}
void AudioRenderer::InitializeProcessors()
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_device);
m_correctedWithRateDsp = 0;
if (m_device->IsBitstream())
return;
const auto inRate = m_inputFormat->nSamplesPerSec;
const auto inChannels = m_inputFormat->nChannels;
const auto inMask = DspMatrix::GetChannelMask(*m_inputFormat);
const auto outRate = m_device->GetWaveFormat()->nSamplesPerSec;
const auto outChannels = m_device->GetWaveFormat()->nChannels;
const auto outMask = DspMatrix::GetChannelMask(*m_device->GetWaveFormat());
m_dspMatrix.Initialize(inChannels, inMask, outChannels, outMask);
m_dspRate.Initialize(m_externalClock, inRate, outRate, outChannels);
m_dspVariableRate.Initialize(m_externalClock, inRate, outRate, outChannels);
m_dspTempo.Initialize(m_rate, outRate, outChannels);
m_dspCrossfeed.Initialize(m_settings, outRate, outChannels, outMask);
m_dspVolume.Initialize(m_device->IsExclusive());
m_dspLimiter.Initialize(m_settings, outRate, m_device->IsExclusive());
m_dspDither.Initialize(m_device->GetDspFormat());
}
bool AudioRenderer::Push(DspChunk& chunk, CAMEvent* pFilledEvent)
{
bool firstIteration = true;
uint32_t sleepDuration = 0;
while (!chunk.IsEmpty())
{
// The device buffer is full or almost full at the beginning of the second and subsequent iterations.
// Sleep until the buffer may have significant amount of free space. Unless interrupted.
if (!firstIteration && m_flush.Wait(sleepDuration))
return false;
firstIteration = false;
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
if (m_device)
{
try
{
m_device->Push(chunk, pFilledEvent);
sleepDuration = m_device->GetBufferDuration() / 4;
}
catch (HRESULT)
{
ClearDevice();
sleepDuration = 0;
}
}
else
{
// The code below emulates null audio device.
if (pFilledEvent)
pFilledEvent->Set();
sleepDuration = 1;
// Loop until the graph time passes the current sample end.
REFERENCE_TIME graphTime;
if (m_state == State_Running &&
SUCCEEDED(GetGraphTime(graphTime)) &&
graphTime > m_startTime + m_sampleCorrection.GetLastSampleEnd())
{
break;
}
}
}
return true;
}
}
<commit_msg>Don't slave graph clock in live mode<commit_after>#include "pch.h"
#include "AudioRenderer.h"
namespace SaneAudioRenderer
{
AudioRenderer::AudioRenderer(ISettings* pSettings, IMyClock* pClock, HRESULT& result)
: m_deviceManager(result)
, m_myClock(pClock)
, m_flush(TRUE/*manual reset*/)
, m_dspVolume(*this)
, m_dspBalance(*this)
, m_settings(pSettings)
{
if (FAILED(result))
return;
try
{
if (!m_settings || !m_myClock)
throw E_UNEXPECTED;
ThrowIfFailed(m_myClock->QueryInterface(IID_PPV_ARGS(&m_myGraphClock)));
if (static_cast<HANDLE>(m_flush) == NULL)
{
throw E_OUTOFMEMORY;
}
}
catch (HRESULT ex)
{
result = ex;
}
}
AudioRenderer::~AudioRenderer()
{
// Just in case.
if (m_state != State_Stopped)
Stop();
}
void AudioRenderer::SetClock(IReferenceClock* pClock)
{
CAutoLock objectLock(this);
m_graphClock = pClock;
if (m_graphClock && m_graphClock != m_myGraphClock)
{
if (!m_externalClock)
ClearDevice();
m_externalClock = true;
}
else
{
if (m_externalClock)
ClearDevice();
m_externalClock = false;
}
}
bool AudioRenderer::OnExternalClock()
{
CAutoLock objectLock(this);
return m_externalClock;
}
bool AudioRenderer::Enqueue(IMediaSample* pSample, AM_SAMPLE2_PROPERTIES& sampleProps, CAMEvent* pFilledEvent)
{
DspChunk chunk;
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_state != State_Stopped);
try
{
// Clear the device if related settings were changed.
CheckDeviceSettings();
// Create the device if needed.
if (!m_device)
CreateDevice();
// Apply sample corrections (pad, crop, guess timings).
chunk = m_sampleCorrection.ProcessSample(pSample, sampleProps);
// Apply clock corrections (graph clock and rate dsp).
if (m_device && m_state == State_Running)
ApplyClockCorrection();
// Apply dsp chain.
if (m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
pDsp->Process(chunk);
};
EnumerateProcessors(f);
DspChunk::ToFormat(m_device->GetDspFormat(), chunk);
}
}
catch (std::bad_alloc&)
{
ClearDevice();
chunk = DspChunk();
}
}
// Send processed sample to the device.
return Push(chunk, pFilledEvent);
}
bool AudioRenderer::Finish(bool blockUntilEnd, CAMEvent* pFilledEvent)
{
DspChunk chunk;
{
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
// No device - nothing to block on.
if (!m_device)
blockUntilEnd = false;
try
{
// Apply dsp chain.
if (m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
pDsp->Finish(chunk);
};
EnumerateProcessors(f);
DspChunk::ToFormat(m_device->GetDspFormat(), chunk);
}
}
catch (std::bad_alloc&)
{
chunk = DspChunk();
assert(chunk.IsEmpty());
}
}
auto doBlock = [this]
{
// Increase system timer resolution.
TimePeriodHelper timePeriodHelper(1);
// Unslave the clock because no more samples are going to be pushed.
m_myClock->UnslaveClockFromAudio();
for (;;)
{
int64_t actual = INT64_MAX;
int64_t target;
{
CAutoLock objectLock(this);
if (!m_device)
return true;
const auto previous = actual;
actual = m_device->GetPosition();
target = m_device->GetEnd();
// Return if the end of stream is reached.
if (actual == target)
return true;
// Stalling protection.
if (actual == previous && m_state == State_Running)
return true;
}
// Sleep until predicted end of stream.
if (m_flush.Wait(std::max(1, (int32_t)((target - actual) * 1000 / OneSecond))))
return false;
}
};
// Send processed sample to the device, and block until the buffer is drained (if requested).
return Push(chunk, pFilledEvent) && (!blockUntilEnd || doBlock());
}
void AudioRenderer::BeginFlush()
{
m_flush.Set();
}
void AudioRenderer::EndFlush()
{
CAutoLock objectLock(this);
assert(m_state != State_Running);
if (m_device)
{
m_device->Reset();
m_sampleCorrection.NewDeviceBuffer();
}
m_flush.Reset();
}
bool AudioRenderer::CheckFormat(SharedWaveFormat inputFormat)
{
assert(inputFormat);
if (DspFormatFromWaveFormat(*inputFormat) != DspFormat::Unknown)
return true;
BOOL exclusive;
m_settings->GetOuputDevice(nullptr, &exclusive, nullptr);
BOOL bitstreamingAllowed;
m_settings->GetAllowBitstreaming(&bitstreamingAllowed);
if (!exclusive || !bitstreamingAllowed)
return false;
CAutoLock objectLock(this);
return m_deviceManager.BitstreamFormatSupported(inputFormat, m_settings);
}
void AudioRenderer::SetFormat(SharedWaveFormat inputFormat, bool live)
{
CAutoLock objectLock(this);
m_inputFormat = inputFormat;
m_live = live;
m_sampleCorrection.NewFormat(inputFormat);
ClearDevice();
}
void AudioRenderer::NewSegment(double rate)
{
CAutoLock objectLock(this);
m_startClockOffset = 0;
m_rate = rate;
m_sampleCorrection.NewSegment(m_rate);
assert(m_inputFormat);
if (m_device)
InitializeProcessors();
}
void AudioRenderer::Play(REFERENCE_TIME startTime)
{
CAutoLock objectLock(this);
assert(m_state != State_Running);
m_state = State_Running;
m_startTime = startTime;
StartDevice();
}
void AudioRenderer::Pause()
{
CAutoLock objectLock(this);
m_state = State_Paused;
if (m_device)
{
m_myClock->UnslaveClockFromAudio();
m_device->Stop();
}
}
void AudioRenderer::Stop()
{
CAutoLock objectLock(this);
m_state = State_Stopped;
ClearDevice();
}
SharedWaveFormat AudioRenderer::GetInputFormat()
{
CAutoLock objectLock(this);
return m_inputFormat;
}
AudioDevice const* AudioRenderer::GetAudioDevice()
{
assert(CritCheckIn(this));
return m_device.get();
}
std::vector<std::wstring> AudioRenderer::GetActiveProcessors()
{
CAutoLock objectLock(this);
std::vector<std::wstring> ret;
if (m_inputFormat && m_device && !m_device->IsBitstream())
{
auto f = [&](DspBase* pDsp)
{
if (pDsp->Active())
ret.emplace_back(pDsp->Name());
};
EnumerateProcessors(f);
}
return ret;
}
void AudioRenderer::CheckDeviceSettings()
{
CAutoLock objectLock(this);
UINT32 serial = m_settings->GetSerial();
if (m_device && m_deviceSettingsSerial != serial)
{
LPWSTR pDeviceName = nullptr;
BOOL exclusive;
UINT32 buffer;
if (SUCCEEDED(m_settings->GetOuputDevice(&pDeviceName, &exclusive, &buffer)))
{
if (m_device->IsExclusive() != !!exclusive ||
m_device->GetBufferDuration() != buffer ||
(pDeviceName && *pDeviceName && wcscmp(pDeviceName, m_device->GetFriendlyName()->c_str())) ||
((!pDeviceName || !*pDeviceName) && !m_device->IsDefault()))
{
ClearDevice();
assert(!m_device);
}
else
{
m_deviceSettingsSerial = serial;
}
CoTaskMemFree(pDeviceName);
}
}
}
void AudioRenderer::StartDevice()
{
CAutoLock objectLock(this);
assert(m_state == State_Running);
if (m_device)
{
assert(m_live == m_device->IsLive());
if (!m_live)
m_myClock->SlaveClockToAudio(m_device->GetClock(), m_startTime + m_startClockOffset);
m_device->Start();
}
}
void AudioRenderer::CreateDevice()
{
CAutoLock objectLock(this);
assert(!m_device);
assert(m_inputFormat);
m_deviceSettingsSerial = m_settings->GetSerial();
m_device = m_deviceManager.CreateDevice(m_inputFormat, m_live, m_settings);
if (m_device)
{
m_sampleCorrection.NewDeviceBuffer();
InitializeProcessors();
m_startClockOffset = m_sampleCorrection.GetLastSampleEnd();
if (m_state == State_Running)
StartDevice();
}
}
void AudioRenderer::ClearDevice()
{
CAutoLock objectLock(this);
if (m_device)
{
m_myClock->UnslaveClockFromAudio();
m_device->Stop();
m_device = nullptr;
}
}
void AudioRenderer::ApplyClockCorrection()
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_device);
assert(m_state == State_Running);
// Apply corrections to internal clock.
{
REFERENCE_TIME offset = m_sampleCorrection.GetTimingsError() - m_myClock->GetSlavedClockOffset();
if (std::abs(offset) > 1000)
{
m_myClock->OffsetSlavedClock(offset);
DebugOut("AudioRenderer offset internal clock by", offset / 10000., "ms");
}
}
/*
// Try to match internal clock with graph clock if they're different.
// We do it in the roundabout way by dynamically changing audio sampling rate.
if (m_externalClock && !m_device->bitstream)
{
assert(m_dspRate.Active());
REFERENCE_TIME graphTime, myTime, myStartTime;
if (SUCCEEDED(m_myClock->GetAudioClockStartTime(&myStartTime)) &&
SUCCEEDED(m_myClock->GetAudioClockTime(&myTime, nullptr)) &&
SUCCEEDED(GetGraphTime(graphTime)) &&
myTime > myStartTime)
{
REFERENCE_TIME offset = graphTime - myTime - m_correctedWithRateDsp;
if (std::abs(offset) > MILLISECONDS_TO_100NS_UNITS(2))
{
m_dspRate.Adjust(offset);
m_correctedWithRateDsp += offset;
DebugOut("AudioRenderer offset internal clock indirectly by", offset / 10000., "ms");
}
}
}
*/
}
HRESULT AudioRenderer::GetGraphTime(REFERENCE_TIME& time)
{
CAutoLock objectLock(this);
return m_graphClock ?
m_graphClock->GetTime(&time) :
m_myGraphClock->GetTime(&time);
}
void AudioRenderer::InitializeProcessors()
{
CAutoLock objectLock(this);
assert(m_inputFormat);
assert(m_device);
m_correctedWithRateDsp = 0;
if (m_device->IsBitstream())
return;
const auto inRate = m_inputFormat->nSamplesPerSec;
const auto inChannels = m_inputFormat->nChannels;
const auto inMask = DspMatrix::GetChannelMask(*m_inputFormat);
const auto outRate = m_device->GetWaveFormat()->nSamplesPerSec;
const auto outChannels = m_device->GetWaveFormat()->nChannels;
const auto outMask = DspMatrix::GetChannelMask(*m_device->GetWaveFormat());
m_dspMatrix.Initialize(inChannels, inMask, outChannels, outMask);
m_dspRate.Initialize(m_externalClock, inRate, outRate, outChannels);
m_dspVariableRate.Initialize(m_externalClock, inRate, outRate, outChannels);
m_dspTempo.Initialize(m_rate, outRate, outChannels);
m_dspCrossfeed.Initialize(m_settings, outRate, outChannels, outMask);
m_dspVolume.Initialize(m_device->IsExclusive());
m_dspLimiter.Initialize(m_settings, outRate, m_device->IsExclusive());
m_dspDither.Initialize(m_device->GetDspFormat());
}
bool AudioRenderer::Push(DspChunk& chunk, CAMEvent* pFilledEvent)
{
bool firstIteration = true;
uint32_t sleepDuration = 0;
while (!chunk.IsEmpty())
{
// The device buffer is full or almost full at the beginning of the second and subsequent iterations.
// Sleep until the buffer may have significant amount of free space. Unless interrupted.
if (!firstIteration && m_flush.Wait(sleepDuration))
return false;
firstIteration = false;
CAutoLock objectLock(this);
assert(m_state != State_Stopped);
if (m_device)
{
try
{
m_device->Push(chunk, pFilledEvent);
sleepDuration = m_device->GetBufferDuration() / 4;
}
catch (HRESULT)
{
ClearDevice();
sleepDuration = 0;
}
}
else
{
// The code below emulates null audio device.
if (pFilledEvent)
pFilledEvent->Set();
sleepDuration = 1;
// Loop until the graph time passes the current sample end.
REFERENCE_TIME graphTime;
if (m_state == State_Running &&
SUCCEEDED(GetGraphTime(graphTime)) &&
graphTime > m_startTime + m_sampleCorrection.GetLastSampleEnd())
{
break;
}
}
}
return true;
}
}
<|endoftext|> |
<commit_before>#include <vector>
#include <fstream>
#include <iostream>
#include <cassert>
#include <cmath>
#include "RandomNumberGenerator.h"
using namespace std;
using namespace DNest3;
class Data
{
private:
vector<double> logw, run_id;
vector< vector<double> > scalars;
int N;
public:
Data()
{ }
void load()
{
logw.clear(); run_id.clear(); scalars.clear();
double temp;
fstream fin("logw.txt", ios::in);
int k = 0;
while(fin >> temp)
{
logw.push_back(temp);
if(k == 0)
run_id.push_back(0);
else if(logw.back() == -1.)
run_id.push_back(run_id.back() + 1);
else
run_id.push_back(run_id.back());
k++;
}
fin.close();
fin.open("scalars.txt", ios::in);
double temp2;
while(fin >> temp && fin >> temp2)
{
vector<double> vec(2);
vec[0] = temp; vec[1] = temp2;
scalars.push_back(vec);
}
fin.close();
if(scalars.size() < logw.size())
{
logw.erase(logw.begin() + scalars.size(),
logw.end());
run_id.erase(run_id.begin() + scalars.size(),
run_id.end());
}
if(logw.size() < scalars.size())
{
scalars.erase(scalars.begin() + logw.size(),
scalars.end());
}
assert(logw.size() == scalars.size());
assert(logw.size() == run_id.size());
N = logw.size();
cout<<"# Loaded "<<N<<" points."<<endl;
}
friend class Assignment;
};
/************************************************************************/
class Assignment
{
private:
const Data& data;
vector<double> logX;
public:
Assignment(const Data& data)
:data(data)
{
}
void initialise()
{
logX.assign(data.N, 0.);
for(int i=0; i<data.N; i++)
{
if(data.logw[i] == -1.)
logX[i] = log(randomU());
else
logX[i] = logX[i-1] + log(randomU());
}
}
int update_all()
{
int total = 0;
for(int i=0; i<data.N; i++)
{
total += update(i);
cout<<"."<<flush;
}
cout<<endl;
return total;
}
// Gibbs sample one value
int update(int i)
{
double proposal;
// Range of values for proposal
double lower = -1E300;
double upper = 0.;
// Lower limit -- next point in same run (if it exists)
if( (i != (data.N-1)) &&
(data.run_id[i+1] == data.run_id[i]))
lower = logX[i+1];
// Upper limit -- previous point in same run (if it exists)
if( (i != 0) &&
(data.run_id[i-1] == data.run_id[i]))
upper = logX[i-1];
// If lower limit exists, generate uniformly between limits
if(lower != -1E300)
proposal = lower + (upper - lower)*randomU();
else // otherwise use exponential distribution
proposal = upper + log(randomU());
// Measure inconsistency
int inconsistency_old = 0;
int inconsistency_new = 0;
bool outside, inside;
for(int j=0; j<data.N; j++)
{
if(data.run_id[j] != data.run_id[i])
{
// See if distribution j is outside,
// inside, or unknown
outside = true;
inside = true;
for(int k=0; k<2; k++)
{
if(data.scalars[j][k] > data.scalars[i][k])
outside = false;
if(data.scalars[j][k] < data.scalars[i][k])
inside = false;
}
if(outside && (logX[j] < logX[i]))
inconsistency_old++;
if(inside && (logX[j] > logX[i]))
inconsistency_old++;
if(outside && (logX[j] < proposal))
inconsistency_new++;
if(inside && (logX[j] > proposal))
inconsistency_new++;
}
}
int inconsistency = inconsistency_old;
if(inconsistency_new <= inconsistency_old)
{
logX[i] = proposal;
inconsistency = inconsistency_new;
}
return inconsistency;
}
void save()
{
fstream fout("logX.txt", ios::out);
for(int i=0; i<data.N; i++)
fout<<logX[i]<<endl;
fout.close();
}
};
int main()
{
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
Data data;
data.load();
Assignment assignment(data);
assignment.initialise();
for(int i=0; i<10000000; i++)
{
cout<<assignment.update_all()<<endl;
assignment.save();
}
return 0;
}
<commit_msg>Do 100 sweeps (can be increased)<commit_after>#include <vector>
#include <fstream>
#include <iostream>
#include <cassert>
#include <cmath>
#include "RandomNumberGenerator.h"
using namespace std;
using namespace DNest3;
class Data
{
private:
vector<double> logw, run_id;
vector< vector<double> > scalars;
int N;
public:
Data()
{ }
void load()
{
logw.clear(); run_id.clear(); scalars.clear();
double temp;
fstream fin("logw.txt", ios::in);
int k = 0;
while(fin >> temp)
{
logw.push_back(temp);
if(k == 0)
run_id.push_back(0);
else if(logw.back() == -1.)
run_id.push_back(run_id.back() + 1);
else
run_id.push_back(run_id.back());
k++;
}
fin.close();
fin.open("scalars.txt", ios::in);
double temp2;
while(fin >> temp && fin >> temp2)
{
vector<double> vec(2);
vec[0] = temp; vec[1] = temp2;
scalars.push_back(vec);
}
fin.close();
if(scalars.size() < logw.size())
{
logw.erase(logw.begin() + scalars.size(),
logw.end());
run_id.erase(run_id.begin() + scalars.size(),
run_id.end());
}
if(logw.size() < scalars.size())
{
scalars.erase(scalars.begin() + logw.size(),
scalars.end());
}
assert(logw.size() == scalars.size());
assert(logw.size() == run_id.size());
N = logw.size();
cout<<"# Loaded "<<N<<" points."<<endl;
}
friend class Assignment;
};
/************************************************************************/
class Assignment
{
private:
const Data& data;
vector<double> logX;
public:
Assignment(const Data& data)
:data(data)
{
}
void initialise()
{
logX.assign(data.N, 0.);
for(int i=0; i<data.N; i++)
{
if(data.logw[i] == -1.)
logX[i] = log(randomU());
else
logX[i] = logX[i-1] + log(randomU());
}
}
int update_all()
{
int total = 0;
for(int i=0; i<data.N; i++)
{
total += update(i);
cout<<"."<<flush;
}
cout<<endl;
return total;
}
// Gibbs sample one value
int update(int i)
{
double proposal;
// Range of values for proposal
double lower = -1E300;
double upper = 0.;
// Lower limit -- next point in same run (if it exists)
if( (i != (data.N-1)) &&
(data.run_id[i+1] == data.run_id[i]))
lower = logX[i+1];
// Upper limit -- previous point in same run (if it exists)
if( (i != 0) &&
(data.run_id[i-1] == data.run_id[i]))
upper = logX[i-1];
// If lower limit exists, generate uniformly between limits
if(lower != -1E300)
proposal = lower + (upper - lower)*randomU();
else // otherwise use exponential distribution
proposal = upper + log(randomU());
// Measure inconsistency
int inconsistency_old = 0;
int inconsistency_new = 0;
bool outside, inside;
for(int j=0; j<data.N; j++)
{
if(data.run_id[j] != data.run_id[i])
{
// See if distribution j is outside,
// inside, or unknown
outside = true;
inside = true;
for(int k=0; k<2; k++)
{
if(data.scalars[j][k] > data.scalars[i][k])
outside = false;
if(data.scalars[j][k] < data.scalars[i][k])
inside = false;
}
if(outside && (logX[j] < logX[i]))
inconsistency_old++;
if(inside && (logX[j] > logX[i]))
inconsistency_old++;
if(outside && (logX[j] < proposal))
inconsistency_new++;
if(inside && (logX[j] > proposal))
inconsistency_new++;
}
}
int inconsistency = inconsistency_old;
if(inconsistency_new <= inconsistency_old)
{
logX[i] = proposal;
inconsistency = inconsistency_new;
}
return inconsistency;
}
void save()
{
fstream fout("logX.txt", ios::out);
for(int i=0; i<data.N; i++)
fout<<logX[i]<<endl;
fout.close();
}
};
int main()
{
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
Data data;
data.load();
Assignment assignment(data);
assignment.initialise();
for(int i=0; i<100; i++)
{
cout<<assignment.update_all()<<endl;
assignment.save();
}
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file help.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primecount x [OPTION]...\n"
"Count the primes below x < 2^63 using the prime counting function, by\n"
"default uses the Deleglise & Rivat algorithm (-d).\n"
"\n"
"Options:\n"
" -d, --deleglise_rivat LMO with Deleglise and Rivat improvements\n"
" --legendre Count primes using Legendre's formula\n"
" -m, --meissel Count primes using Meissel's formula\n"
" -l, --lehmer Count primes using Lehmer's formula\n"
" --lmo Count primes using Lagarias-Miller-Odlyzko\n"
" --Li Approximate pi(x) using the logarithmic integral\n"
" --Li_inverse Approximate the nth prime using Li^-1(x)\n"
" -n, --nthprime Calculate the nth prime\n"
" --phi Calculate phi(x, a), requires 2 arguments\n"
" -p, --primesieve Count primes using the sieve of Eratosthenes\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Examples:\n"
" primecount 10**13\n"
" primecount 10**13 --nthprime"
);
const string versionInfo(
"primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
"Copyright (C) 2014 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primecount {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace primecount
<commit_msg>Update help text<commit_after>///
/// @file help.cpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primecount x [OPTION]...\n"
"Count the primes below x <= 10^27 using the prime counting function,\n"
"by default the Deleglise-Rivat algorithm (-d) is used.\n"
"\n"
"Options:\n"
" -d, --deleglise_rivat LMO with Deleglise and Rivat improvements\n"
" --legendre Count primes using Legendre's formula\n"
" -m, --meissel Count primes using Meissel's formula\n"
" -l, --lehmer Count primes using Lehmer's formula\n"
" --lmo Count primes using Lagarias-Miller-Odlyzko\n"
" --Li Approximate pi(x) using the logarithmic integral\n"
" --Li_inverse Approximate the nth prime using Li^-1(x)\n"
" -n, --nthprime Calculate the nth prime\n"
" --phi Calculate phi(x, a), requires 2 arguments\n"
" -p, --primesieve Count primes using the sieve of Eratosthenes\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Examples:\n"
" primecount 10**13\n"
" primecount 10**13 --nthprime"
);
const string versionInfo(
"primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
"Copyright (C) 2014 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primecount {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace primecount
<|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "http_server.h"
#include "date.h"
#include "file_interpreter.h"
#include "path_resolution.h"
using namespace std;
#define BUFFER_SIZE 32
HTTPServer::HTTPServer(unsigned short port) : Server(port) {
}
void HTTPServer::handle() {
Socket client = socket_.accept();
string reply = process(accept(client));
client.send(reply);
client.close();
}
string HTTPServer::accept(Socket& client) {
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
int received_size = 0;
string message = "";
received_size = client.receive(BUFFER_SIZE, buffer);
message.append(buffer);
while (!is_valid_http_message(message) && received_size > 0) {
memset(buffer, 0, BUFFER_SIZE);
received_size = client.receive(BUFFER_SIZE, buffer);
message.append(buffer);
}
return message;
}
string HTTPServer::process(const string& message) {
string type;
std::stringstream trimmer;
trimmer << message;
trimmer >> type;
if (type == "GET") {
string path;
trimmer << message;
trimmer >> path;
path = vv::resolve_path(path, "/");
if (path[path.length() - 1] == '/') {
if (vv::file_exists(path + "index.ssjs")) {
path += "index.ssjs";
} else if (vv::file_exists(path + "index.html")) {
path += "index.html";
}
}
unique_ptr<FileInterpreter> interpreter = FileInterpreter::file_interpreter_for_path(path);
string content = "";
try {
content = interpreter.get()->interpret();
} catch (const HTTPException& e) {
switch (e.code()) {
case 404: return NotFound();
default: return InternalServerError();
}
}
return OK(content, interpreter.get()->mime());
}
return NotImplemented();
}
bool HTTPServer::is_valid_http_message(string& message) {
if (message[message.length() - 1] == '\n') {
return true;
}
return false;
}
string HTTPServer::OK(const string& message, const string mime) {
stringstream response;
response << "HTTP/1.1 200 OK" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Accept-Ranges: bytes" << endl;
response << "Content-Length: " << message.length() << endl;
response << "Connection: close" << endl;
response << "Content-Type: " << mime << endl << endl;
response << message << endl;
return response.str();
}
string HTTPServer::BadRequest(const string& message) {
stringstream response;
response << "HTTP/1.0 400 Bad Request" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::NotFound(const string& message) {
stringstream response;
response << "HTTP/1.0 404 Not Found" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::InternalServerError(const string& message) {
stringstream response;
response << "HTTP/1.0 500 Internal Server Error" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::NotImplemented(const string& message) {
stringstream response;
response << "HTTP/1.0 502 Not Implemented" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
<commit_msg>Fix buffer issue with receiving data from a socket.<commit_after>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "http_server.h"
#include "date.h"
#include "file_interpreter.h"
#include "path_resolution.h"
using namespace std;
#define BUFFER_SIZE 128
HTTPServer::HTTPServer(unsigned short port) : Server(port) {
}
void HTTPServer::handle() {
Socket client = socket_.accept();
string reply = process(accept(client));
client.send(reply);
client.close();
}
string HTTPServer::accept(Socket& client) {
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
int received_size = 0;
string message = "";
received_size = client.receive(BUFFER_SIZE, buffer);
message.append(buffer, received_size);
while (!is_valid_http_message(message) && received_size > 0) {
memset(buffer, 0, BUFFER_SIZE);
received_size = client.receive(BUFFER_SIZE, buffer);
message.append(buffer, received_size);
}
return message;
}
string HTTPServer::process(const string& message) {
string type;
std::stringstream trimmer;
trimmer << message;
trimmer >> type;
if (type == "GET") {
string path;
trimmer << message;
trimmer >> path;
path = vv::resolve_path(path, "/");
if (path[path.length() - 1] == '/') {
if (vv::file_exists(path + "index.ssjs")) {
path += "index.ssjs";
} else if (vv::file_exists(path + "index.html")) {
path += "index.html";
}
}
unique_ptr<FileInterpreter> interpreter = FileInterpreter::file_interpreter_for_path(path);
string content = "";
try {
content = interpreter.get()->interpret();
} catch (const HTTPException& e) {
switch (e.code()) {
case 404: return NotFound();
default: return InternalServerError();
}
}
return OK(content, interpreter.get()->mime());
}
return NotImplemented();
}
bool HTTPServer::is_valid_http_message(string& message) {
if (message[message.length() - 1] == '\n') {
return true;
}
return false;
}
string HTTPServer::OK(const string& message, const string mime) {
stringstream response;
response << "HTTP/1.1 200 OK" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Accept-Ranges: bytes" << endl;
response << "Content-Length: " << message.length() << endl;
response << "Connection: close" << endl;
response << "Content-Type: " << mime << endl << endl;
response << message << endl;
return response.str();
}
string HTTPServer::BadRequest(const string& message) {
stringstream response;
response << "HTTP/1.0 400 Bad Request" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::NotFound(const string& message) {
stringstream response;
response << "HTTP/1.0 404 Not Found" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::InternalServerError(const string& message) {
stringstream response;
response << "HTTP/1.0 500 Internal Server Error" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
string HTTPServer::NotImplemented(const string& message) {
stringstream response;
response << "HTTP/1.0 502 Not Implemented" << endl;
response << "Date: " << Date::now("%a, %d %b %Y %H:%M:%S %Z") << endl;
response << "Content-Type: text/html" << endl;
response << "Content-Length: " << message.length() << endl;
response << message;
return response.str();
}
<|endoftext|> |
<commit_before>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include <QApplication>
#include <QBoxLayout>
#include <QDockWidget>
#include <QMenu>
#include <QProcess>
#include <QToolBar>
#include <QToolButton>
#include <KConfigGroup>
#include <KSharedConfig>
#include <KDE/KConfigGroup>
#include <KDE/KMainWindow>
#include "widgets/applicationcomponents.h"
#include "widgets/availablepagesview.h"
#include "widgets/availablesourcesview.h"
#include "widgets/datasourcecombobox.h"
#include "widgets/editorview.h"
#include "widgets/pageview.h"
#include "presentation/applicationmodel.h"
#include "dependencies.h"
#include <iostream>
int main(int argc, char **argv)
{
App::initializeDependencies();
QApplication app(argc, argv);
KSharedConfig::Ptr config = KSharedConfig::openConfig("zanshin-migratorrc");
KConfigGroup group = config->group("Migrations");
if (!group.readEntry("Migrated021Projects", false)) {
std::cerr << "Migrating data from zanshin 0.2, please wait..." << std::endl;
QProcess proc;
proc.start("zanshin-migrator");
proc.waitForFinished();
std::cerr << "Migration done" << std::endl;
}
auto widget = new QWidget;
auto components = new Widgets::ApplicationComponents(widget);
components->setModel(new Presentation::ApplicationModel(components));
QVBoxLayout *layout = new QVBoxLayout;
QHBoxLayout *hbox = new QHBoxLayout;
hbox->addWidget(components->defaultTaskSourceCombo());
hbox->addWidget(components->defaultNoteSourceCombo());
layout->addLayout(hbox);
layout->addWidget(components->pageView());
widget->setLayout(layout);
auto sourcesDock = new QDockWidget(QObject::tr("Sources"));
sourcesDock->setObjectName("sourcesDock");
sourcesDock->setWidget(components->availableSourcesView());
auto pagesDock = new QDockWidget(QObject::tr("Pages"));
pagesDock->setObjectName("pagesDock");
pagesDock->setWidget(components->availablePagesView());
auto editorDock = new QDockWidget(QObject::tr("Editor"));
editorDock->setObjectName("editorDock");
editorDock->setWidget(components->editorView());
auto configureMenu = new QMenu(widget);
foreach (QAction *action, components->configureActions()) {
configureMenu->addAction(action);
}
auto configureButton = new QToolButton(widget);
configureButton->setIcon(QIcon::fromTheme("configure"));
configureButton->setText(QObject::tr("Settings"));
configureButton->setToolTip(configureButton ->text());
configureButton->setPopupMode(QToolButton::InstantPopup);
configureButton->setMenu(configureMenu);
auto window = new KMainWindow;
window->resize(1024, 600);
window->setAutoSaveSettings("MainWindow");
window->setCentralWidget(widget);
QToolBar *mainToolBar = window->addToolBar(QObject::tr("Main"));
mainToolBar->setObjectName("mainToolBar");
mainToolBar->addWidget(configureButton);
window->addDockWidget(Qt::RightDockWidgetArea, editorDock);
window->addDockWidget(Qt::LeftDockWidgetArea, pagesDock);
window->addDockWidget(Qt::LeftDockWidgetArea, sourcesDock);
window->show();
return app.exec();
}
<commit_msg>Create main component data, to avoid warning in KGlobal::locale() later.<commit_after>/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include <QApplication>
#include <QBoxLayout>
#include <QDockWidget>
#include <QMenu>
#include <QProcess>
#include <QToolBar>
#include <QToolButton>
#include <KConfigGroup>
#include <KSharedConfig>
#include <KComponentData>
#include <KMainWindow>
#include "widgets/applicationcomponents.h"
#include "widgets/availablepagesview.h"
#include "widgets/availablesourcesview.h"
#include "widgets/datasourcecombobox.h"
#include "widgets/editorview.h"
#include "widgets/pageview.h"
#include "presentation/applicationmodel.h"
#include "dependencies.h"
#include <iostream>
int main(int argc, char **argv)
{
App::initializeDependencies();
QApplication app(argc, argv);
KComponentData mainComponentData("zanshin");
KSharedConfig::Ptr config = KSharedConfig::openConfig("zanshin-migratorrc");
KConfigGroup group = config->group("Migrations");
if (!group.readEntry("Migrated021Projects", false)) {
std::cerr << "Migrating data from zanshin 0.2, please wait..." << std::endl;
QProcess proc;
proc.start("zanshin-migrator");
proc.waitForFinished();
std::cerr << "Migration done" << std::endl;
}
auto widget = new QWidget;
auto components = new Widgets::ApplicationComponents(widget);
components->setModel(new Presentation::ApplicationModel(components));
QVBoxLayout *layout = new QVBoxLayout;
QHBoxLayout *hbox = new QHBoxLayout;
hbox->addWidget(components->defaultTaskSourceCombo());
hbox->addWidget(components->defaultNoteSourceCombo());
layout->addLayout(hbox);
layout->addWidget(components->pageView());
widget->setLayout(layout);
auto sourcesDock = new QDockWidget(QObject::tr("Sources"));
sourcesDock->setObjectName("sourcesDock");
sourcesDock->setWidget(components->availableSourcesView());
auto pagesDock = new QDockWidget(QObject::tr("Pages"));
pagesDock->setObjectName("pagesDock");
pagesDock->setWidget(components->availablePagesView());
auto editorDock = new QDockWidget(QObject::tr("Editor"));
editorDock->setObjectName("editorDock");
editorDock->setWidget(components->editorView());
auto configureMenu = new QMenu(widget);
foreach (QAction *action, components->configureActions()) {
configureMenu->addAction(action);
}
auto configureButton = new QToolButton(widget);
configureButton->setIcon(QIcon::fromTheme("configure"));
configureButton->setText(QObject::tr("Settings"));
configureButton->setToolTip(configureButton ->text());
configureButton->setPopupMode(QToolButton::InstantPopup);
configureButton->setMenu(configureMenu);
auto window = new KMainWindow;
window->resize(1024, 600);
window->setAutoSaveSettings("MainWindow");
window->setCentralWidget(widget);
QToolBar *mainToolBar = window->addToolBar(QObject::tr("Main"));
mainToolBar->setObjectName("mainToolBar");
mainToolBar->addWidget(configureButton);
window->addDockWidget(Qt::RightDockWidgetArea, editorDock);
window->addDockWidget(Qt::LeftDockWidgetArea, pagesDock);
window->addDockWidget(Qt::LeftDockWidgetArea, sourcesDock);
window->show();
return app.exec();
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qtsingleapplication.h"
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <extensionsystem/iplugin.h>
#include <QtCore/QDir>
#include <QtCore/QTextStream>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtCore/QLibraryInfo>
#include <QtCore/QTranslator>
#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtNetwork/QNetworkProxyFactory>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
enum { OptionIndent = 4, DescriptionIndent = 24 };
static const char *appNameC = "Qt Creator";
static const char *corePluginNameC = "Core";
static const char *fixedOptionsC =
" [OPTION]... [FILE]...\n"
"Options:\n"
" -help Display this help\n"
" -version Display program version\n"
" -client Attempt to connect to already running instance\n";
static const char *HELP_OPTION1 = "-h";
static const char *HELP_OPTION2 = "-help";
static const char *HELP_OPTION3 = "/h";
static const char *HELP_OPTION4 = "--help";
static const char *VERSION_OPTION = "-version";
static const char *CLIENT_OPTION = "-client";
typedef QList<ExtensionSystem::PluginSpec *> PluginSpecSet;
// Helpers for displaying messages. Note that there is no console on Windows.
#ifdef Q_OS_WIN
// Format as <pre> HTML
static inline void toHtml(QString &t)
{
t.replace(QLatin1Char('&'), QLatin1String("&"));
t.replace(QLatin1Char('<'), QLatin1String("<"));
t.replace(QLatin1Char('>'), QLatin1String(">"));
t.insert(0, QLatin1String("<html><pre>"));
t.append(QLatin1String("</pre></html>"));
}
static void displayHelpText(QString t) // No console on Windows.
{
toHtml(t);
QMessageBox::information(0, QLatin1String(appNameC), t);
}
static void displayError(const QString &t) // No console on Windows.
{
QMessageBox::critical(0, QLatin1String(appNameC), t);
}
#else
static void displayHelpText(const QString &t)
{
qWarning("%s", qPrintable(t));
}
static void displayError(const QString &t)
{
qCritical("%s", qPrintable(t));
}
#endif
static void printVersion(const ExtensionSystem::PluginSpec *coreplugin,
const ExtensionSystem::PluginManager &pm)
{
QString version;
QTextStream str(&version);
str << '\n' << appNameC << ' ' << coreplugin->version()<< " based on Qt " << qVersion() << "\n\n";
pm.formatPluginVersions(str);
str << '\n' << coreplugin->copyright() << '\n';
displayHelpText(version);
}
static void printHelp(const QString &a0, const ExtensionSystem::PluginManager &pm)
{
QString help;
QTextStream str(&help);
str << "Usage: " << a0 << fixedOptionsC;
ExtensionSystem::PluginManager::formatOptions(str, OptionIndent, DescriptionIndent);
pm.formatPluginOptions(str, OptionIndent, DescriptionIndent);
displayHelpText(help);
}
static inline QString msgCoreLoadFailure(const QString &why)
{
return QCoreApplication::translate("Application", "Failed to load core: %1").arg(why);
}
static inline QString msgSendArgumentFailed()
{
return QCoreApplication::translate("Application", "Unable to send command line arguments to the already running instance. It appears to be not responding.");
}
static inline QStringList getPluginPaths()
{
QStringList rc;
// Figure out root: Up one from 'bin'
QDir rootDir = QApplication::applicationDirPath();
rootDir.cdUp();
const QString rootDirPath = rootDir.canonicalPath();
// 1) "plugins" (Win/Linux)
QString pluginPath = rootDirPath;
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String(IDE_LIBRARY_BASENAME);
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("qtcreator");
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("plugins");
rc.push_back(pluginPath);
// 2) "PlugIns" (OS X)
pluginPath = rootDirPath;
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("PlugIns");
rc.push_back(pluginPath);
return rc;
}
#ifdef Q_OS_MAC
# define SHARE_PATH "/../Resources"
#else
# define SHARE_PATH "/../share/qtcreator"
#endif
int main(int argc, char **argv)
{
#ifdef Q_OS_MAC
// increase the number of file that can be opened in Qt Creator.
struct rlimit rl;
getrlimit(RLIMIT_NOFILE, &rl);
rl.rlim_cur = rl.rlim_max;
setrlimit(RLIMIT_NOFILE, &rl);
#endif
SharedTools::QtSingleApplication app((QLatin1String(appNameC)), argc, argv);
QTranslator translator;
QTranslator qtTranslator;
QString locale = QLocale::system().name();
// Must be done before any QSettings class is created
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
QCoreApplication::applicationDirPath()+QLatin1String(SHARE_PATH));
// Work around bug in QSettings which gets triggered on Windows & Mac only
#ifdef Q_OS_MAC
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
QDir::homePath()+"/.config");
#endif
#ifdef Q_OS_WIN
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
qgetenv("appdata"));
#endif
// keep this in sync with the MainWindow ctor in coreplugin/mainwindow.cpp
const QSettings settings(QSettings::IniFormat, QSettings::UserScope,
QLatin1String("Nokia"), QLatin1String("QtCreator"));
locale = settings.value("General/OverrideLanguage", locale).toString();
const QString &creatorTrPath = QCoreApplication::applicationDirPath()
+ QLatin1String(SHARE_PATH "/translations");
if (translator.load(QLatin1String("qtcreator_") + locale, creatorTrPath)) {
const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString &qtTrFile = QLatin1String("qt_") + locale;
// Binary installer puts Qt tr files into creatorTrPath
if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, creatorTrPath)) {
app.installTranslator(&translator);
app.installTranslator(&qtTranslator);
app.setProperty("qtc_locale", locale);
} else {
translator.load(QString()); // unload()
}
}
// Make sure we honor the system's proxy settings
QNetworkProxyFactory::setUseSystemConfiguration(true);
// Load
ExtensionSystem::PluginManager pluginManager;
pluginManager.setFileExtension(QLatin1String("pluginspec"));
const QStringList pluginPaths = getPluginPaths();
pluginManager.setPluginPaths(pluginPaths);
const QStringList arguments = app.arguments();
QMap<QString, QString> foundAppOptions;
if (arguments.size() > 1) {
QMap<QString, bool> appOptions;
appOptions.insert(QLatin1String(HELP_OPTION1), false);
appOptions.insert(QLatin1String(HELP_OPTION2), false);
appOptions.insert(QLatin1String(HELP_OPTION3), false);
appOptions.insert(QLatin1String(HELP_OPTION4), false);
appOptions.insert(QLatin1String(VERSION_OPTION), false);
appOptions.insert(QLatin1String(CLIENT_OPTION), false);
QString errorMessage;
if (!pluginManager.parseOptions(arguments,
appOptions,
&foundAppOptions,
&errorMessage)) {
displayError(errorMessage);
printHelp(QFileInfo(app.applicationFilePath()).baseName(), pluginManager);
return -1;
}
}
const PluginSpecSet plugins = pluginManager.plugins();
ExtensionSystem::PluginSpec *coreplugin = 0;
foreach (ExtensionSystem::PluginSpec *spec, plugins) {
if (spec->name() == QLatin1String(corePluginNameC)) {
coreplugin = spec;
break;
}
}
if (!coreplugin) {
QString nativePaths = QDir::toNativeSeparators(pluginPaths.join(QLatin1String(",")));
const QString reason = QCoreApplication::translate("Application", "Could not find 'Core.pluginspec' in %1").arg(nativePaths);
displayError(msgCoreLoadFailure(reason));
return 1;
}
if (coreplugin->hasError()) {
displayError(msgCoreLoadFailure(coreplugin->errorString()));
return 1;
}
if (foundAppOptions.contains(QLatin1String(VERSION_OPTION))) {
printVersion(coreplugin, pluginManager);
return 0;
}
if (foundAppOptions.contains(QLatin1String(HELP_OPTION1))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION2))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION3))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION4))) {
printHelp(QFileInfo(app.applicationFilePath()).baseName(), pluginManager);
return 0;
}
const bool isFirstInstance = !app.isRunning();
if (!isFirstInstance && foundAppOptions.contains(QLatin1String(CLIENT_OPTION))) {
if (!app.sendMessage(pluginManager.serializedArguments())) {
displayError(msgSendArgumentFailed());
return -1;
}
return 0;
}
pluginManager.loadPlugins();
if (coreplugin->hasError()) {
displayError(msgCoreLoadFailure(coreplugin->errorString()));
return 1;
}
{
QStringList errors;
foreach (ExtensionSystem::PluginSpec *p, pluginManager.plugins())
if (p->hasError())
errors.append(p->errorString());
if (!errors.isEmpty())
QMessageBox::warning(0,
QCoreApplication::translate("Application", "Qt Creator - Plugin loader messages"),
errors.join(QString::fromLatin1("\n\n")));
}
if (isFirstInstance) {
// Set up lock and remote arguments for the first instance only.
// Silently fallback to unconnected instances for any subsequent
// instances.
app.initialize();
QObject::connect(&app, SIGNAL(messageReceived(QString)),
&pluginManager, SLOT(remoteArguments(QString)));
}
QObject::connect(&app, SIGNAL(fileOpenRequest(QString)), coreplugin->plugin(), SLOT(fileOpenRequest(QString)));
// Do this after the event loop has started
QTimer::singleShot(100, &pluginManager, SLOT(startTests()));
return app.exec();
}
<commit_msg>remove startup error messages from plugins that are disabled by user User can still see errors in About Plugins for disabled ones, too<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qtsingleapplication.h"
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <extensionsystem/iplugin.h>
#include <QtCore/QDir>
#include <QtCore/QTextStream>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtCore/QLibraryInfo>
#include <QtCore/QTranslator>
#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtNetwork/QNetworkProxyFactory>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
enum { OptionIndent = 4, DescriptionIndent = 24 };
static const char *appNameC = "Qt Creator";
static const char *corePluginNameC = "Core";
static const char *fixedOptionsC =
" [OPTION]... [FILE]...\n"
"Options:\n"
" -help Display this help\n"
" -version Display program version\n"
" -client Attempt to connect to already running instance\n";
static const char *HELP_OPTION1 = "-h";
static const char *HELP_OPTION2 = "-help";
static const char *HELP_OPTION3 = "/h";
static const char *HELP_OPTION4 = "--help";
static const char *VERSION_OPTION = "-version";
static const char *CLIENT_OPTION = "-client";
typedef QList<ExtensionSystem::PluginSpec *> PluginSpecSet;
// Helpers for displaying messages. Note that there is no console on Windows.
#ifdef Q_OS_WIN
// Format as <pre> HTML
static inline void toHtml(QString &t)
{
t.replace(QLatin1Char('&'), QLatin1String("&"));
t.replace(QLatin1Char('<'), QLatin1String("<"));
t.replace(QLatin1Char('>'), QLatin1String(">"));
t.insert(0, QLatin1String("<html><pre>"));
t.append(QLatin1String("</pre></html>"));
}
static void displayHelpText(QString t) // No console on Windows.
{
toHtml(t);
QMessageBox::information(0, QLatin1String(appNameC), t);
}
static void displayError(const QString &t) // No console on Windows.
{
QMessageBox::critical(0, QLatin1String(appNameC), t);
}
#else
static void displayHelpText(const QString &t)
{
qWarning("%s", qPrintable(t));
}
static void displayError(const QString &t)
{
qCritical("%s", qPrintable(t));
}
#endif
static void printVersion(const ExtensionSystem::PluginSpec *coreplugin,
const ExtensionSystem::PluginManager &pm)
{
QString version;
QTextStream str(&version);
str << '\n' << appNameC << ' ' << coreplugin->version()<< " based on Qt " << qVersion() << "\n\n";
pm.formatPluginVersions(str);
str << '\n' << coreplugin->copyright() << '\n';
displayHelpText(version);
}
static void printHelp(const QString &a0, const ExtensionSystem::PluginManager &pm)
{
QString help;
QTextStream str(&help);
str << "Usage: " << a0 << fixedOptionsC;
ExtensionSystem::PluginManager::formatOptions(str, OptionIndent, DescriptionIndent);
pm.formatPluginOptions(str, OptionIndent, DescriptionIndent);
displayHelpText(help);
}
static inline QString msgCoreLoadFailure(const QString &why)
{
return QCoreApplication::translate("Application", "Failed to load core: %1").arg(why);
}
static inline QString msgSendArgumentFailed()
{
return QCoreApplication::translate("Application", "Unable to send command line arguments to the already running instance. It appears to be not responding.");
}
static inline QStringList getPluginPaths()
{
QStringList rc;
// Figure out root: Up one from 'bin'
QDir rootDir = QApplication::applicationDirPath();
rootDir.cdUp();
const QString rootDirPath = rootDir.canonicalPath();
// 1) "plugins" (Win/Linux)
QString pluginPath = rootDirPath;
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String(IDE_LIBRARY_BASENAME);
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("qtcreator");
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("plugins");
rc.push_back(pluginPath);
// 2) "PlugIns" (OS X)
pluginPath = rootDirPath;
pluginPath += QLatin1Char('/');
pluginPath += QLatin1String("PlugIns");
rc.push_back(pluginPath);
return rc;
}
#ifdef Q_OS_MAC
# define SHARE_PATH "/../Resources"
#else
# define SHARE_PATH "/../share/qtcreator"
#endif
int main(int argc, char **argv)
{
#ifdef Q_OS_MAC
// increase the number of file that can be opened in Qt Creator.
struct rlimit rl;
getrlimit(RLIMIT_NOFILE, &rl);
rl.rlim_cur = rl.rlim_max;
setrlimit(RLIMIT_NOFILE, &rl);
#endif
SharedTools::QtSingleApplication app((QLatin1String(appNameC)), argc, argv);
QTranslator translator;
QTranslator qtTranslator;
QString locale = QLocale::system().name();
// Must be done before any QSettings class is created
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope,
QCoreApplication::applicationDirPath()+QLatin1String(SHARE_PATH));
// Work around bug in QSettings which gets triggered on Windows & Mac only
#ifdef Q_OS_MAC
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
QDir::homePath()+"/.config");
#endif
#ifdef Q_OS_WIN
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
qgetenv("appdata"));
#endif
// keep this in sync with the MainWindow ctor in coreplugin/mainwindow.cpp
const QSettings settings(QSettings::IniFormat, QSettings::UserScope,
QLatin1String("Nokia"), QLatin1String("QtCreator"));
locale = settings.value("General/OverrideLanguage", locale).toString();
const QString &creatorTrPath = QCoreApplication::applicationDirPath()
+ QLatin1String(SHARE_PATH "/translations");
if (translator.load(QLatin1String("qtcreator_") + locale, creatorTrPath)) {
const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString &qtTrFile = QLatin1String("qt_") + locale;
// Binary installer puts Qt tr files into creatorTrPath
if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, creatorTrPath)) {
app.installTranslator(&translator);
app.installTranslator(&qtTranslator);
app.setProperty("qtc_locale", locale);
} else {
translator.load(QString()); // unload()
}
}
// Make sure we honor the system's proxy settings
QNetworkProxyFactory::setUseSystemConfiguration(true);
// Load
ExtensionSystem::PluginManager pluginManager;
pluginManager.setFileExtension(QLatin1String("pluginspec"));
const QStringList pluginPaths = getPluginPaths();
pluginManager.setPluginPaths(pluginPaths);
const QStringList arguments = app.arguments();
QMap<QString, QString> foundAppOptions;
if (arguments.size() > 1) {
QMap<QString, bool> appOptions;
appOptions.insert(QLatin1String(HELP_OPTION1), false);
appOptions.insert(QLatin1String(HELP_OPTION2), false);
appOptions.insert(QLatin1String(HELP_OPTION3), false);
appOptions.insert(QLatin1String(HELP_OPTION4), false);
appOptions.insert(QLatin1String(VERSION_OPTION), false);
appOptions.insert(QLatin1String(CLIENT_OPTION), false);
QString errorMessage;
if (!pluginManager.parseOptions(arguments,
appOptions,
&foundAppOptions,
&errorMessage)) {
displayError(errorMessage);
printHelp(QFileInfo(app.applicationFilePath()).baseName(), pluginManager);
return -1;
}
}
const PluginSpecSet plugins = pluginManager.plugins();
ExtensionSystem::PluginSpec *coreplugin = 0;
foreach (ExtensionSystem::PluginSpec *spec, plugins) {
if (spec->name() == QLatin1String(corePluginNameC)) {
coreplugin = spec;
break;
}
}
if (!coreplugin) {
QString nativePaths = QDir::toNativeSeparators(pluginPaths.join(QLatin1String(",")));
const QString reason = QCoreApplication::translate("Application", "Could not find 'Core.pluginspec' in %1").arg(nativePaths);
displayError(msgCoreLoadFailure(reason));
return 1;
}
if (coreplugin->hasError()) {
displayError(msgCoreLoadFailure(coreplugin->errorString()));
return 1;
}
if (foundAppOptions.contains(QLatin1String(VERSION_OPTION))) {
printVersion(coreplugin, pluginManager);
return 0;
}
if (foundAppOptions.contains(QLatin1String(HELP_OPTION1))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION2))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION3))
|| foundAppOptions.contains(QLatin1String(HELP_OPTION4))) {
printHelp(QFileInfo(app.applicationFilePath()).baseName(), pluginManager);
return 0;
}
const bool isFirstInstance = !app.isRunning();
if (!isFirstInstance && foundAppOptions.contains(QLatin1String(CLIENT_OPTION))) {
if (!app.sendMessage(pluginManager.serializedArguments())) {
displayError(msgSendArgumentFailed());
return -1;
}
return 0;
}
pluginManager.loadPlugins();
if (coreplugin->hasError()) {
displayError(msgCoreLoadFailure(coreplugin->errorString()));
return 1;
}
{
QStringList errors;
foreach (ExtensionSystem::PluginSpec *p, pluginManager.plugins())
// only show errors on startup if plugin is enabled.
if (p->hasError() && p->isEnabled() && !p->isDisabledByDependency())
errors.append(p->name() + "\n" + p->errorString());
if (!errors.isEmpty())
QMessageBox::warning(0,
QCoreApplication::translate("Application", "Qt Creator - Plugin loader messages"),
errors.join(QString::fromLatin1("\n\n")));
}
if (isFirstInstance) {
// Set up lock and remote arguments for the first instance only.
// Silently fallback to unconnected instances for any subsequent
// instances.
app.initialize();
QObject::connect(&app, SIGNAL(messageReceived(QString)),
&pluginManager, SLOT(remoteArguments(QString)));
}
QObject::connect(&app, SIGNAL(fileOpenRequest(QString)), coreplugin->plugin(), SLOT(fileOpenRequest(QString)));
// Do this after the event loop has started
QTimer::singleShot(100, &pluginManager, SLOT(startTests()));
return app.exec();
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <node.h>
#include <v8.h>
#include <string>
#include "Types.h"
#include "JuliaExecEnv.h"
using namespace std;
using namespace v8;
static JuliaExecEnv *J = 0;
void returnNull(const FunctionCallbackInfo<Value> &args,Isolate *I)
{
args.GetReturnValue().SetNull();
}
void returnString(const FunctionCallbackInfo<Value> &args,Isolate *I,const string &s)
{
args.GetReturnValue().Set(String::NewFromUtf8(I,s.c_str()));
}
void callback(const FunctionCallbackInfo<Value>& args,Isolate *I,const Local<Function> &cb,int argc,Local<Value> *argv)
{
cb->Call(I->GetCurrentContext()->Global(),argc,argv);
}
void buildPrimitive(Isolate *I,const nj::Primitive &primitive,int index,Local<Value> *argv)
{
switch(primitive.type()->getId())
{
case nj::null_type:
printf("arg is null\n");
argv[index] = Null(I);
break;
case nj::boolean_type:
printf("arg is %d\n",primitive.toBoolean());
argv[index] = Boolean::New(I,primitive.toBoolean());
break;
case nj::int_type:
printf("arg is %lld\n",primitive.toInt());
argv[index] = Number::New(I,primitive.toInt());
break;
case nj::float_type:
printf("arg is %f\n",primitive.toFloat());
argv[index] = Number::New(I,primitive.toFloat());
break;
case nj::string_type:
printf("arg is %s\n",primitive.toString().c_str());
argv[index] = String::NewFromUtf8(I,primitive.toString().c_str());
break;
}
}
void buildArray(Isolate *I,const shared_ptr<nj::Value> &value,Local<Value> &arg)
{
const nj::Array_t *array_type = static_cast<const nj::Array_t*>(value->type());
const nj::Type *element_type = array_type->getElementType();
switch(element_type->getId())
{
case nj::float_type:
{
const nj::Array<double,nj::Float_t> &array = static_cast<const nj::Array<double,nj::Float_t>&>(*value);
if(array.dims().size() == 1)
{
size_t size0 = array.dims()[0];
double *p = array.ptr();
Local<Array> dest = Array::New(I,size0);
for(size_t i = 0;i < size0;i++) dest->Set(i,Number::New(I,p[i]));
arg = dest;
}
else if(array.dims().size() == 2)
{
size_t size0 = array.dims()[0];
size_t size1 = array.dims()[1];
double *p = array.ptr();
Local<Array> dest = Array::New(I,size0);
for(size_t i = 0;i < size0;i++)
{
Local<Array> row = Array::New(I,size1);
dest->Set(i,row);
for(size_t j = 0;j < size1;j++) row->Set(j,Number::New(I,*(p + size0*j + i)));
}
arg = dest;
}
}
}
//arg = Array::New(I,array);
}
int buildArgs(Isolate *I,const shared_ptr<vector<shared_ptr<nj::Value>>> &res,int argc,Local<Value> *argv)
{
int index = 0;
for(shared_ptr<nj::Value> value: *res)
{
if(value.get())
{
printf("building arg %d\n",index);
if(value->isPrimitive())
{
const nj::Primitive &primitive = static_cast<const nj::Primitive&>(*value);
buildPrimitive(I,primitive,index++,argv);
}
else
{
buildArray(I,value,argv[index++]);
}
}
}
return index;
}
void doEval(const FunctionCallbackInfo<Value> &args)
{
Isolate *I = Isolate::GetCurrent();
HandleScope scope(I);
int numArgs = args.Length();
if(numArgs < 2 || !J)
{
returnNull(args,I);
return;
}
Local<String> arg0 = args[0]->ToString();
String::Utf8Value text(arg0);
Local<Function> cb = Local<Function>::Cast(args[1]);
JMain *engine;
if(text.length() > 0 && (engine = J->getEngine()))
{
engine->evalQueuePut(*text);
shared_ptr<vector<shared_ptr<nj::Value>>> res = engine->resultQueueGet();
if(res.get())
{
int argc = res->size();
Local<Value> *argv = new Local<Value>[argc];
argc = buildArgs(I,res,argc,argv);
callback(args,I,cb,argc,argv);
}
}
else
{
const unsigned argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(I,"") };
callback(args,I,cb,argc,argv);
}
}
void doStart(const FunctionCallbackInfo<Value> &args)
{
Isolate *I = Isolate::GetCurrent();
HandleScope scope(I);
int numArgs = args.Length();
if(numArgs == 0)
{
returnString(args,I,"");
return;
}
Local<String> arg0 = args[0]->ToString();
String::Utf8Value plainText_av(arg0);
if(plainText_av.length() > 0)
{
if(!J) J = new JuliaExecEnv(*plainText_av);
returnString(args,I,"Julia Started");
}
else returnString(args,I,"");
}
void init(Handle<Object> exports)
{
NODE_SET_METHOD(exports,"start",doStart);
NODE_SET_METHOD(exports,"eval",doEval);
}
NODE_MODULE(nj,init)
<commit_msg>Debugging<commit_after>#include <stdio.h>
#include <node.h>
#include <v8.h>
#include <string>
#include "Types.h"
#include "JuliaExecEnv.h"
using namespace std;
using namespace v8;
static JuliaExecEnv *J = 0;
void returnNull(const FunctionCallbackInfo<Value> &args,Isolate *I)
{
args.GetReturnValue().SetNull();
}
void returnString(const FunctionCallbackInfo<Value> &args,Isolate *I,const string &s)
{
args.GetReturnValue().Set(String::NewFromUtf8(I,s.c_str()));
}
void callback(const FunctionCallbackInfo<Value>& args,Isolate *I,const Local<Function> &cb,int argc,Local<Value> *argv)
{
cb->Call(I->GetCurrentContext()->Global(),argc,argv);
}
void buildPrimitive(Isolate *I,const nj::Primitive &primitive,int index,Local<Value> *argv)
{
switch(primitive.type()->getId())
{
case nj::null_type:
printf("arg is null\n");
argv[index] = Null(I);
break;
case nj::boolean_type:
printf("arg is %d\n",primitive.toBoolean());
argv[index] = Boolean::New(I,primitive.toBoolean());
break;
case nj::int_type:
printf("arg is %lld\n",primitive.toInt());
argv[index] = Number::New(I,primitive.toInt());
break;
case nj::float_type:
printf("arg is %f\n",primitive.toFloat());
argv[index] = Number::New(I,primitive.toFloat());
break;
case nj::string_type:
printf("arg is %s\n",primitive.toString().c_str());
argv[index] = String::NewFromUtf8(I,primitive.toString().c_str());
break;
}
}
void buildArray(Isolate *I,const shared_ptr<nj::Value> &value,Local<Value> &arg)
{
const nj::Array_t *array_type = static_cast<const nj::Array_t*>(value->type());
const nj::Type *element_type = array_type->getElementType();
switch(element_type->getId())
{
case nj::float_type:
{
const nj::Array<double,nj::Float_t> &array = static_cast<const nj::Array<double,nj::Float_t>&>(*value);
if(array.dims().size() == 1)
{
size_t size0 = array.dims()[0];
double *p = array.ptr();
Local<Array> dest = Array::New(I,size0);
for(size_t i = 0;i < size0;i++) dest->Set(i,Number::New(I,p[i]));
arg = dest;
}
else if(array.dims().size() == 2)
{
size_t size0 = array.dims()[0];
size_t size1 = array.dims()[1];
double *p = array.ptr();
Local<Array> dest = Array::New(I,size0);
for(size_t i = 0;i < size0;i++)
{
Local<Array> row = Array::New(I,size1);
dest->Set(i,row);
for(size_t j = 0;j < size1;j++)
{
printf("Storing X(%zu,%zu) = %f\n",i,j,p[size0*j + i]);
row->Set(j,Number::New(I,*(p + size0*j + i)));
}
}
arg = dest;
}
}
}
//arg = Array::New(I,array);
}
int buildArgs(Isolate *I,const shared_ptr<vector<shared_ptr<nj::Value>>> &res,int argc,Local<Value> *argv)
{
int index = 0;
for(shared_ptr<nj::Value> value: *res)
{
if(value.get())
{
printf("building arg %d\n",index);
if(value->isPrimitive())
{
const nj::Primitive &primitive = static_cast<const nj::Primitive&>(*value);
buildPrimitive(I,primitive,index++,argv);
}
else
{
buildArray(I,value,argv[index++]);
}
}
}
return index;
}
void doEval(const FunctionCallbackInfo<Value> &args)
{
Isolate *I = Isolate::GetCurrent();
HandleScope scope(I);
int numArgs = args.Length();
if(numArgs < 2 || !J)
{
returnNull(args,I);
return;
}
Local<String> arg0 = args[0]->ToString();
String::Utf8Value text(arg0);
Local<Function> cb = Local<Function>::Cast(args[1]);
JMain *engine;
if(text.length() > 0 && (engine = J->getEngine()))
{
engine->evalQueuePut(*text);
shared_ptr<vector<shared_ptr<nj::Value>>> res = engine->resultQueueGet();
if(res.get())
{
int argc = res->size();
Local<Value> *argv = new Local<Value>[argc];
argc = buildArgs(I,res,argc,argv);
callback(args,I,cb,argc,argv);
}
}
else
{
const unsigned argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(I,"") };
callback(args,I,cb,argc,argv);
}
}
void doStart(const FunctionCallbackInfo<Value> &args)
{
Isolate *I = Isolate::GetCurrent();
HandleScope scope(I);
int numArgs = args.Length();
if(numArgs == 0)
{
returnString(args,I,"");
return;
}
Local<String> arg0 = args[0]->ToString();
String::Utf8Value plainText_av(arg0);
if(plainText_av.length() > 0)
{
if(!J) J = new JuliaExecEnv(*plainText_av);
returnString(args,I,"Julia Started");
}
else returnString(args,I,"");
}
void init(Handle<Object> exports)
{
NODE_SET_METHOD(exports,"start",doStart);
NODE_SET_METHOD(exports,"eval",doEval);
}
NODE_MODULE(nj,init)
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "QtUiAsset.h"
#include "UiProxyWidget.h"
#include "Application.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "LoggingFunctions.h"
#include <QEvent>
#include <QLayout>
#include <QVBoxLayout>
#include <QScrollBar>
#include <QUiLoader>
#include <QFile>
#include <QDir>
#include "MemoryLeakCheck.h"
/// The SuppressedPaintWidget is used as a viewport for the main QGraphicsView.
/** Its purpose is to disable all automatic drawing of the QGraphicsView to screen so that
we can composite an Ogre 3D render with the Qt widgets added to a QGraphicsScene. */
class SuppressedPaintWidget : public QWidget {
public:
SuppressedPaintWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~SuppressedPaintWidget() {}
protected:
virtual bool event(QEvent *event);
virtual void paintEvent(QPaintEvent *event);
};
SuppressedPaintWidget::SuppressedPaintWidget(QWidget *parent, Qt::WindowFlags f)
:QWidget(parent, f)
{
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_OpaquePaintEvent, true);
}
bool SuppressedPaintWidget::event(QEvent *event)
{
switch(event->type())
{
case QEvent::UpdateRequest:
case QEvent::Paint:
case QEvent::Wheel:
case QEvent::Resize:
return true;
default:
return QWidget::event(event);
}
}
void SuppressedPaintWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
}
UiAPI::UiAPI(Framework *owner_) :
owner(owner_),
mainWindow(0),
graphicsView(0),
graphicsScene(0)
{
if (owner_->IsHeadless())
{
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("QtUiFile")));
return;
}
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<QtUiAsset>("QtUiFile")));
mainWindow = new UiMainWindow(owner);
mainWindow->setAutoFillBackground(false);
mainWindow->setWindowIcon(QIcon(Application::InstallationDirectory() + "data/ui/images/icon/naali_logo_32px_RC1.ico"));
connect(mainWindow, SIGNAL(WindowCloseEvent()), owner, SLOT(Exit()));
// Prepare graphics view and scene
graphicsView = new UiGraphicsView(mainWindow);
///\todo Memory leak below, see very end of ~Renderer() for comments.
// QMainWindow has a layout by default. It will not let you set another.
// Leave this check here if the window type changes to for example QWidget so we dont crash then.
if (!mainWindow->layout())
mainWindow->setLayout(new QVBoxLayout());
mainWindow->layout()->setMargin(0);
mainWindow->layout()->setContentsMargins(0,0,0,0);
mainWindow->layout()->addWidget(graphicsView);
viewportWidget = new SuppressedPaintWidget();
graphicsView->setViewport(viewportWidget);
// viewportWidget->setAttribute(Qt::WA_DontShowOnScreen, true);
viewportWidget->setGeometry(0, 0, graphicsView->width(), graphicsView->height());
viewportWidget->setContentsMargins(0,0,0,0);
mainWindow->setContentsMargins(0,0,0,0);
graphicsView->setContentsMargins(0,0,0,0);
graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->horizontalScrollBar()->setValue(0);
graphicsView->horizontalScrollBar()->setRange(0, 0);
graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->verticalScrollBar()->setValue(0);
graphicsView->verticalScrollBar()->setRange(0, 0);
graphicsScene = new QGraphicsScene(this);
graphicsView->setScene(graphicsScene);
graphicsView->scene()->setSceneRect(graphicsView->rect());
connect(graphicsScene, SIGNAL(changed(const QList<QRectF> &)), graphicsView, SLOT(HandleSceneChanged(const QList<QRectF> &)));
connect(graphicsScene, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(OnSceneRectChanged(const QRectF &)));
connect(mainWindow, SIGNAL(WindowResizeEvent(int,int)), graphicsView, SLOT(Resize(int,int)));
mainWindow->LoadWindowSettingsFromFile();
graphicsView->Resize(mainWindow->width(), mainWindow->height());
graphicsView->show();
mainWindow->show();
viewportWidget->show();
/// Do a full repaint of the view now that we've shown it.
graphicsView->MarkViewUndirty();
}
UiAPI::~UiAPI()
{
// If we have a mainwindow delete it, note this will be null on headless mode
// so this if check needs to be here.
if (mainWindow)
{
mainWindow->close();
delete mainWindow.data();
}
// viewportWidget will be null after main window is deleted above
// as it is inside the main window (is a child so gets deleted)
if (!viewportWidget.isNull())
{
viewportWidget->close();
delete viewportWidget.data();
}
}
UiMainWindow *UiAPI::MainWindow() const
{
return mainWindow;
}
UiGraphicsView *UiAPI::GraphicsView() const
{
return graphicsView;
}
QGraphicsScene *UiAPI::GraphicsScene() const
{
return graphicsScene;
}
UiProxyWidget *UiAPI::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return 0;
}
// QGraphicsProxyWidget maintains symmetry for the following states:
// state, enabled, visible, geometry, layoutDirection, style, palette,
// font, cursor, sizeHint, getContentsMargins and windowTitle
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddProxyWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiAPI::AddProxyWidgetToScene(UiProxyWidget *widget)
{
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return false;
}
if (!widget->widget())
{
LogError("AddWidgetToScene called for proxy widget that does not embed a widget!");
return false;
}
if (widgets.contains(widget))
{
LogWarning("AddWidgetToScene: Scene already contains the given widget!");
return false;
}
connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets << widget;
widget->setGeometry(graphicsScene->sceneRect().toRect());
}
graphicsScene->addItem(widget);
return true;
}
void UiAPI::RemoveWidgetFromScene(QWidget *widget)
{
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget->graphicsProxyWidget());
widgets.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets.removeOne(widget->graphicsProxyWidget());
}
void UiAPI::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget);
widgets.removeOne(widget);
fullScreenWidgets.removeOne(widget);
}
void UiAPI::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets.removeOne(proxy);
fullScreenWidgets.removeOne(proxy);
}
QWidget *UiAPI::LoadFromFile(const QString &filePath, bool addToScene, QWidget *parent)
{
QWidget *widget = 0;
AssetAPI::AssetRefType refType = AssetAPI::ParseAssetRef(filePath);
if (refType != AssetAPI::AssetRefLocalPath && refType != AssetAPI::AssetRefRelativePath)
{
AssetPtr asset = owner->Asset()->GetAsset(filePath);
if (!asset)
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return 0;
}
QtUiAsset *uiAsset = dynamic_cast<QtUiAsset*>(asset.get());
if (!uiAsset)
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" is not of type QtUiFile!").toStdString());
return 0;
}
if (!uiAsset->IsLoaded())
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" data is not valid!").toStdString());
return 0;
}
// Get the asset data with the assetrefs replaced to point to the disk sources on the current local system.
QByteArray data = uiAsset->GetRefReplacedAssetData();
QUiLoader loader;
QDataStream dataStream(&data, QIODevice::ReadOnly);
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QString path = filePath;
// If the user submitted a relative path, try to lookup whether a path relative to cwd or the application installation directory was meant.
if (QDir::isRelativePath(path))
{
QString cwdPath = Application::CurrentWorkingDirectory() + filePath;
if (QFile::exists(cwdPath))
path = cwdPath;
else
path = Application::InstallationDirectory() + filePath;
}
QFile file(path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError(("LoadFromFile: Failed to load widget from file \"" + filePath + "\"!").toStdString());
return 0;
}
if (addToScene && widget)
AddWidgetToScene(widget);
return widget;
}
void UiAPI::EmitContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
emit ContextMenuAboutToOpen(menu,targets);
}
void UiAPI::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiAPI::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiAPI::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
graphicsScene->setActiveWindow(widget->graphicsProxyWidget());
graphicsScene->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiAPI::BringProxyWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
graphicsScene->setActiveWindow(widget);
graphicsScene->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiAPI::OnSceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets)
widget->setGeometry(rect);
}
void UiAPI::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<commit_msg>UiAPI crash bug: Check headless mode when AddWidget*() functions are called, stupid code might call this even in headless mode and we crashed to graphics scene ptr being null. Make a informative print and ask the user to check his code ;)<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "QtUiAsset.h"
#include "UiProxyWidget.h"
#include "Application.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "GenericAssetFactory.h"
#include "NullAssetFactory.h"
#include "LoggingFunctions.h"
#include <QEvent>
#include <QLayout>
#include <QVBoxLayout>
#include <QScrollBar>
#include <QUiLoader>
#include <QFile>
#include <QDir>
#include "MemoryLeakCheck.h"
/// The SuppressedPaintWidget is used as a viewport for the main QGraphicsView.
/** Its purpose is to disable all automatic drawing of the QGraphicsView to screen so that
we can composite an Ogre 3D render with the Qt widgets added to a QGraphicsScene. */
class SuppressedPaintWidget : public QWidget {
public:
SuppressedPaintWidget(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~SuppressedPaintWidget() {}
protected:
virtual bool event(QEvent *event);
virtual void paintEvent(QPaintEvent *event);
};
SuppressedPaintWidget::SuppressedPaintWidget(QWidget *parent, Qt::WindowFlags f)
:QWidget(parent, f)
{
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_OpaquePaintEvent, true);
}
bool SuppressedPaintWidget::event(QEvent *event)
{
switch(event->type())
{
case QEvent::UpdateRequest:
case QEvent::Paint:
case QEvent::Wheel:
case QEvent::Resize:
return true;
default:
return QWidget::event(event);
}
}
void SuppressedPaintWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
}
UiAPI::UiAPI(Framework *owner_) :
owner(owner_),
mainWindow(0),
graphicsView(0),
graphicsScene(0)
{
if (owner_->IsHeadless())
{
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new NullAssetFactory("QtUiFile")));
return;
}
owner_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<QtUiAsset>("QtUiFile")));
mainWindow = new UiMainWindow(owner);
mainWindow->setAutoFillBackground(false);
mainWindow->setWindowIcon(QIcon(Application::InstallationDirectory() + "data/ui/images/icon/naali_logo_32px_RC1.ico"));
connect(mainWindow, SIGNAL(WindowCloseEvent()), owner, SLOT(Exit()));
// Prepare graphics view and scene
graphicsView = new UiGraphicsView(mainWindow);
///\todo Memory leak below, see very end of ~Renderer() for comments.
// QMainWindow has a layout by default. It will not let you set another.
// Leave this check here if the window type changes to for example QWidget so we dont crash then.
if (!mainWindow->layout())
mainWindow->setLayout(new QVBoxLayout());
mainWindow->layout()->setMargin(0);
mainWindow->layout()->setContentsMargins(0,0,0,0);
mainWindow->layout()->addWidget(graphicsView);
viewportWidget = new SuppressedPaintWidget();
graphicsView->setViewport(viewportWidget);
//viewportWidget->setAttribute(Qt::WA_DontShowOnScreen, true);
viewportWidget->setGeometry(0, 0, graphicsView->width(), graphicsView->height());
viewportWidget->setContentsMargins(0,0,0,0);
mainWindow->setContentsMargins(0,0,0,0);
graphicsView->setContentsMargins(0,0,0,0);
graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->horizontalScrollBar()->setValue(0);
graphicsView->horizontalScrollBar()->setRange(0, 0);
graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->verticalScrollBar()->setValue(0);
graphicsView->verticalScrollBar()->setRange(0, 0);
graphicsScene = new QGraphicsScene(this);
graphicsView->setScene(graphicsScene);
graphicsView->scene()->setSceneRect(graphicsView->rect());
connect(graphicsScene, SIGNAL(changed(const QList<QRectF> &)), graphicsView, SLOT(HandleSceneChanged(const QList<QRectF> &)));
connect(graphicsScene, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(OnSceneRectChanged(const QRectF &)));
connect(mainWindow, SIGNAL(WindowResizeEvent(int,int)), graphicsView, SLOT(Resize(int,int)));
mainWindow->LoadWindowSettingsFromFile();
graphicsView->Resize(mainWindow->width(), mainWindow->height());
graphicsView->show();
mainWindow->show();
viewportWidget->show();
/// Do a full repaint of the view now that we've shown it.
graphicsView->MarkViewUndirty();
}
UiAPI::~UiAPI()
{
// If we have a mainwindow delete it, note this will be null on headless mode
// so this if check needs to be here.
if (mainWindow)
{
mainWindow->close();
delete mainWindow.data();
}
// viewportWidget will be null after main window is deleted above
// as it is inside the main window (is a child so gets deleted)
if (!viewportWidget.isNull())
{
viewportWidget->close();
delete viewportWidget.data();
}
}
UiMainWindow *UiAPI::MainWindow() const
{
return mainWindow;
}
UiGraphicsView *UiAPI::GraphicsView() const
{
return graphicsView;
}
QGraphicsScene *UiAPI::GraphicsScene() const
{
return graphicsScene;
}
UiProxyWidget *UiAPI::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to add widgets to scene on a headless run, check your code!");
return 0;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return 0;
}
// QGraphicsProxyWidget maintains symmetry for the following states:
// state, enabled, visible, geometry, layoutDirection, style, palette,
// font, cursor, sizeHint, getContentsMargins and windowTitle
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget() == widget);
// Synchronize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddProxyWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiAPI::AddProxyWidgetToScene(UiProxyWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to add widgets to scene on a headless run, check your code!");
return false;
}
if (!widget)
{
LogError("AddWidgetToScene called with a null proxy widget!");
return false;
}
if (!widget->widget())
{
LogError("AddWidgetToScene called for proxy widget that does not embed a widget!");
return false;
}
if (widgets.contains(widget))
{
LogWarning("AddWidgetToScene: Scene already contains the given widget!");
return false;
}
connect(widget, SIGNAL(destroyed(QObject *)), this, SLOT(OnProxyDestroyed(QObject *)));
widgets.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF() && !(widget->widget()->windowState() & Qt::WindowFullScreen))
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets << widget;
widget->setGeometry(graphicsScene->sceneRect().toRect());
}
graphicsScene->addItem(widget);
return true;
}
void UiAPI::RemoveWidgetFromScene(QWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget->graphicsProxyWidget());
widgets.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets.removeOne(widget->graphicsProxyWidget());
}
void UiAPI::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (owner->IsHeadless())
{
LogWarning("UiAPI: You are trying to remove widgets from scene on a headless run, check your code!");
return;
}
if (!widget)
return;
if (graphicsScene)
graphicsScene->removeItem(widget);
widgets.removeOne(widget);
fullScreenWidgets.removeOne(widget);
}
void UiAPI::OnProxyDestroyed(QObject* obj)
{
// Make sure we don't get dangling pointers
// Note: at this point it's a QObject, not a QGraphicsProxyWidget anymore
QGraphicsProxyWidget* proxy = static_cast<QGraphicsProxyWidget*>(obj);
widgets.removeOne(proxy);
fullScreenWidgets.removeOne(proxy);
}
QWidget *UiAPI::LoadFromFile(const QString &filePath, bool addToScene, QWidget *parent)
{
QWidget *widget = 0;
AssetAPI::AssetRefType refType = AssetAPI::ParseAssetRef(filePath);
if (refType != AssetAPI::AssetRefLocalPath && refType != AssetAPI::AssetRefRelativePath)
{
AssetPtr asset = owner->Asset()->GetAsset(filePath);
if (!asset)
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" is not loaded to the asset system. Call RequestAsset prior to use!").toStdString());
return 0;
}
QtUiAsset *uiAsset = dynamic_cast<QtUiAsset*>(asset.get());
if (!uiAsset)
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" is not of type QtUiFile!").toStdString());
return 0;
}
if (!uiAsset->IsLoaded())
{
LogError(("LoadFromFile: Asset \"" + filePath + "\" data is not valid!").toStdString());
return 0;
}
// Get the asset data with the assetrefs replaced to point to the disk sources on the current local system.
QByteArray data = uiAsset->GetRefReplacedAssetData();
QUiLoader loader;
QDataStream dataStream(&data, QIODevice::ReadOnly);
widget = loader.load(dataStream.device(), parent);
}
else // The file is from absolute source location.
{
QString path = filePath;
// If the user submitted a relative path, try to lookup whether a path relative to cwd or the application installation directory was meant.
if (QDir::isRelativePath(path))
{
QString cwdPath = Application::CurrentWorkingDirectory() + filePath;
if (QFile::exists(cwdPath))
path = cwdPath;
else
path = Application::InstallationDirectory() + filePath;
}
QFile file(path);
QUiLoader loader;
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
}
if (!widget)
{
LogError(("LoadFromFile: Failed to load widget from file \"" + filePath + "\"!").toStdString());
return 0;
}
if (addToScene && widget)
{
if (!owner->IsHeadless())
AddWidgetToScene(widget);
else
LogWarning("UiAPI::LoadFromFile: You have addToScene = true, but this is a headless run (hence no ui scene).");
}
return widget;
}
void UiAPI::EmitContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
emit ContextMenuAboutToOpen(menu,targets);
}
void UiAPI::ShowWidget(QWidget *widget) const
{
if (!widget)
{
LogError("ShowWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiAPI::HideWidget(QWidget *widget) const
{
if (!widget)
{
LogError("HideWidget called on a null widget!");
return;
}
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiAPI::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null widget!");
return;
}
ShowWidget(widget);
graphicsScene->setActiveWindow(widget->graphicsProxyWidget());
graphicsScene->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiAPI::BringProxyWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
{
LogError("BringWidgetToFront called on a null QGraphicsProxyWidget!");
return;
}
graphicsScene->setActiveWindow(widget);
graphicsScene->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiAPI::OnSceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets)
widget->setGeometry(rect);
}
void UiAPI::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<|endoftext|> |
<commit_before>#include <boost/filesystem.hpp>
#include <boost/range/algorithm/mismatch.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <unordered_set>
#include <fstream>
#include <iostream>
namespace meka {
namespace folder {
auto const build = "build";
auto const src = "src";
auto const include = "include";
auto const test = "test";
}
namespace extension {
auto const cpp = { ".cpp", ".cc", ".C", ".c++", ".cxx" };
auto const hpp = { ".hpp", ".hh", ".H", ".h++", ".hxx" };
auto const c = { ".c" };
auto const h = { ".h" };
auto const obj = ".o";
auto const arc = ".a";
}
namespace suffix {
auto const test = "_test";
}
auto const mekaninja = R"(
ninja_required_version = 1.3
builddir = build
cblk = [30m
cred = [31m
cgrn = [32m
cylw = [33m
cblu = [34m
cprp = [35m
ccyn = [36m
cwht = [37m
crgb = [38m
cdef = [39m
crst = [0m
cbblk = ${cblk}[1m
cbred = ${cred}[1m
cbgrn = ${cgrn}[1m
cbylw = ${cylw}[1m
cbblu = ${cblu}[1m
cbprp = ${cprp}[1m
cbcyn = ${ccyn}[1m
cbwht = ${cwht}[1m
cbrgb = ${crgb}[1m
cbdef = ${cdef}[1m
cbrst = ${crst}[1m
cxx = clang++-3.6
cc = clang-3.6
ar = ar
cflags = -std=c11 -fpic -g -O0
cxxflags = -std=c++1y -fpic -g -O0
ldflags = -L$builddir/lib -Wl,-rpath,$builddir/lib -L/usr/local/lib
rule cxx
command = $cxx -MMD -MT $out -MF $out.d $cxxflags $incdirs -xc++ -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule cc
command = $cc -MMD -MT $out -MF $out.d $cflags $incdirs -xc -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule arc
command = rm -f $out && $ar crs $out $in
description = ${cylw}AR${crst} ${cblu}$out${crst}
rule exe
command = $cxx -o $out $in $ldflags -Wl,--start-group $libs -Wl,--end-group
description = ${cylw}EXE${crst} ${cblu}$out${crst}
)";
namespace fs {
using namespace ::boost::filesystem;
auto const filename = [](fs::path path) { return std::move(path).filename().string(); };
auto const relative = [](fs::path from, fs::path to) {
auto const pair = boost::mismatch(from, to);
if (pair.first == std::begin(from))
return std::move(to);
auto rel = fs::path {};
std::for_each(pair.first, from.end(), [&](fs::path const& i) { rel /= ".."; });
std::for_each(pair.second, to.end(), [&](fs::path const& i) { rel /= i; });
return std::move(rel);
};
auto const is_file = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::directory_file:
case fs::type_unknown:
return false;
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return true;
}
};
auto const is_directory = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::type_unknown:
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return false;
case fs::directory_file:
return true;
}
};
}
struct project {
std::string name;
fs::path path;
std::vector<fs::path> sources;
std::vector<fs::path> tests;
std::vector<fs::path> objects = {};
std::vector<fs::path> binaries = {};
};
auto const find_sources = [](fs::path root) {
auto sources = std::vector<fs::path> {};
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp) &&
std::find(std::begin(extension::c), std::end(extension::c), ext) == std::end(extension::c))
continue;
if (boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
sources.emplace_back(fs::relative(root, *it));
}
return std::move(sources);
};
auto const find_tests = [](fs::path root) {
auto tests = std::vector<fs::path> {};
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
if (!boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
tests.emplace_back(fs::relative(root, *it));
}
if (!fs::exists(root / folder::test))
return std::move(tests);
for (auto it = fs::recursive_directory_iterator{root / folder::test}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
tests.emplace_back(fs::relative(root, *it));
}
return std::move(tests);
};
auto const find_projects = [](fs::path root) {
auto names = std::unordered_set<std::string> {};
auto projects = std::vector<project> {};
for (auto it = fs::recursive_directory_iterator{root}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_directory(it))
continue;
auto const base = fs::filename(*it);
if (base == folder::build) {
it.no_push();
continue;
}
if (base != folder::src)
continue;
it.no_push();
auto const path = fs::path(*it).parent_path();
auto const relp = fs::relative(root, path);
auto const name = fs::filename(path);
if (names.find(name) != names.end()) {
std::cerr << "W: project " << name << " in " << path << " already found, ignoring\n";
continue;
}
names.insert(name);
projects.push_back({ name, relp, find_sources(path), find_tests(path) });
}
return std::move(projects);
};
extern "C" int main(int, char*[]) {
auto const root = fs::current_path();
auto const ninja = std::string { std::getenv("NINJA") ? std::getenv("NINJA") : "ninja" };
auto const builddir = fs::path(folder::build);
auto const objdir = builddir / "obj";
auto const libdir = builddir / "lib";
auto const bindir = builddir / "bin";
auto projects = find_projects(root);
{
auto const ninjafile = (objdir / "build.ninja").string();
fs::create_directories(objdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto incdirs = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(incdirs), [&root](auto project) { return "-I" + (project.path / folder::include).string(); });
for (auto const& p : projects) {
for (auto const& s : p.sources) {
if (std::find(std::begin(extension::c), std::end(extension::c), fs::extension(s)) == std::end(extension::c))
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).string() << ": cxx " << (p.path / s).string() << "\n";
else
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).string() << ": cc " << (p.path / s).string() << "\n";
out << " incdirs = -I" << (p.path / folder::src).string() << " " << boost::algorithm::join(incdirs, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (libdir / "build.ninja").string();
fs::create_directories(libdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
for (auto& p : projects) {
for (auto const& s : p.sources) {
auto const object = fs::change_extension(objdir / p.name / s, extension::obj);
auto const command = "nm " + object.string() + " --defined-only | grep --quiet ' T main'";
auto const result = std::system(command.c_str());
if (result)
p.objects.emplace_back(std::move(object));
else
p.binaries.emplace_back(std::move(object));
}
auto objects = std::vector<std::string> {};
std::transform(std::begin(p.objects), std::end(p.objects), std::back_inserter(objects), [](auto path) { return path.string(); });
out << "build " << (libdir / p.name).string() << extension::arc << ": arc $\n";
for (auto const& o : objects)
out << " " << o << " $\n";
out << "\n";
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (bindir / "build.ninja").string();
fs::create_directories(bindir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto archives = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(archives), [libdir](auto project) { return (libdir / project.name).string() + extension::arc; });
for (auto const& p : projects) {
for (auto const& o : p.binaries) {
out << "build " << (bindir / p.name / fs::basename(o)).string() << ": exe " << o.string() << " | " << boost::algorithm::join(archives, " $\n ") << "\n";
out << " libs = " << boost::algorithm::join(archives, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
return 0;
}
}
<commit_msg>Support header-only libraries and add their include folder to the include path.<commit_after>#include <boost/filesystem.hpp>
#include <boost/range/algorithm/mismatch.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <unordered_set>
#include <fstream>
#include <iostream>
namespace meka {
namespace folder {
auto const build = "build";
auto const src = "src";
auto const include = "include";
auto const test = "test";
}
namespace extension {
auto const cpp = { ".cpp", ".cc", ".C", ".c++", ".cxx" };
auto const hpp = { ".hpp", ".hh", ".H", ".h++", ".hxx" };
auto const c = { ".c" };
auto const h = { ".h" };
auto const obj = ".o";
auto const arc = ".a";
}
namespace suffix {
auto const test = "_test";
}
auto const mekaninja = R"(
ninja_required_version = 1.3
builddir = build
cblk = [30m
cred = [31m
cgrn = [32m
cylw = [33m
cblu = [34m
cprp = [35m
ccyn = [36m
cwht = [37m
crgb = [38m
cdef = [39m
crst = [0m
cbblk = ${cblk}[1m
cbred = ${cred}[1m
cbgrn = ${cgrn}[1m
cbylw = ${cylw}[1m
cbblu = ${cblu}[1m
cbprp = ${cprp}[1m
cbcyn = ${ccyn}[1m
cbwht = ${cwht}[1m
cbrgb = ${crgb}[1m
cbdef = ${cdef}[1m
cbrst = ${crst}[1m
cxx = clang++-3.6
cc = clang-3.6
ar = ar
cflags = -std=c11 -fpic -g -O0
cxxflags = -std=c++1y -fpic -g -O0
ldflags = -L$builddir/lib -Wl,-rpath,$builddir/lib -L/usr/local/lib
rule cxx
command = $cxx -MMD -MT $out -MF $out.d $cxxflags $incdirs -xc++ -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule cc
command = $cc -MMD -MT $out -MF $out.d $cflags $incdirs -xc -c $in -o $out
description = ${cylw}CXX${crst} ${cgrn}$out${crst}
depfile = $out.d
deps = gcc
rule arc
command = rm -f $out && $ar crs $out $in
description = ${cylw}AR${crst} ${cblu}$out${crst}
rule exe
command = $cxx -o $out $in $ldflags -Wl,--start-group $libs -Wl,--end-group
description = ${cylw}EXE${crst} ${cblu}$out${crst}
)";
namespace fs {
using namespace ::boost::filesystem;
auto const filename = [](fs::path path) { return std::move(path).filename().string(); };
auto const relative = [](fs::path from, fs::path to) {
auto const pair = boost::mismatch(from, to);
if (pair.first == std::begin(from))
return std::move(to);
auto rel = fs::path {};
std::for_each(pair.first, from.end(), [&](fs::path const& i) { rel /= ".."; });
std::for_each(pair.second, to.end(), [&](fs::path const& i) { rel /= i; });
return std::move(rel);
};
auto const is_file = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::directory_file:
case fs::type_unknown:
return false;
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return true;
}
};
auto const is_directory = [](auto it) {
switch (it.status().type()) {
default:
case fs::status_error:
case fs::file_not_found:
case fs::type_unknown:
case fs::regular_file:
case fs::symlink_file:
case fs::block_file:
case fs::character_file:
case fs::fifo_file:
case fs::socket_file:
return false;
case fs::directory_file:
return true;
}
};
}
struct project {
project() = default;
project(std::string name, fs::path path, std::vector<fs::path> sources, std::vector<fs::path> tests)
: name(std::move(name)), path(std::move(path)), sources(std::move(sources)), tests(std::move(tests)) {}
std::string name;
fs::path path;
std::vector<fs::path> sources;
std::vector<fs::path> tests;
std::vector<fs::path> objects = {};
std::vector<fs::path> binaries = {};
};
auto const find_sources = [](fs::path root) {
auto sources = std::vector<fs::path> {};
if (!fs::exists(root / folder::src))
return std::move(sources);
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp) &&
std::find(std::begin(extension::c), std::end(extension::c), ext) == std::end(extension::c))
continue;
if (boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
sources.emplace_back(fs::relative(root, *it));
}
return std::move(sources);
};
auto const find_tests = [](fs::path root) {
auto tests = std::vector<fs::path> {};
if (fs::exists(root / folder::src)) {
for (auto it = fs::recursive_directory_iterator{root / folder::src}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
if (!boost::algorithm::ends_with(fs::filename(path), suffix::test + ext))
continue;
tests.emplace_back(fs::relative(root, *it));
}
}
if (!fs::exists(root / folder::test))
return std::move(tests);
for (auto it = fs::recursive_directory_iterator{root / folder::test}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_file(it))
continue;
auto const path = *it;
auto const ext = fs::extension(path);
if (std::find(std::begin(extension::cpp), std::end(extension::cpp), ext) == std::end(extension::cpp))
continue;
tests.emplace_back(fs::relative(root, *it));
}
return std::move(tests);
};
auto const find_projects = [](fs::path root) {
auto names = std::unordered_set<std::string> {};
auto projects = std::vector<project> {};
for (auto it = fs::recursive_directory_iterator{root}, end = fs::recursive_directory_iterator {}; it != end; ++it) {
if (!fs::is_directory(it))
continue;
auto const base = fs::filename(*it);
if (base == folder::build) {
it.no_push();
continue;
}
if (base == folder::include && fs::exists(*it / ".." / folder::src))
continue;
if (base != folder::src && base != folder::include)
continue;
it.no_push();
auto const path = fs::path(*it).parent_path();
auto const relp = fs::relative(root, path);
auto const name = fs::filename(path);
if (names.find(name) != names.end()) {
std::cerr << "W: project " << name << " in " << path << " already found, ignoring\n";
continue;
}
names.insert(name);
projects.emplace_back(name, relp, find_sources(path), find_tests(path));
}
return std::move(projects);
};
extern "C" int main(int, char*[]) {
auto const root = fs::current_path();
auto const ninja = std::string { std::getenv("NINJA") ? std::getenv("NINJA") : "ninja" };
auto const builddir = fs::path(folder::build);
auto const objdir = builddir / "obj";
auto const libdir = builddir / "lib";
auto const bindir = builddir / "bin";
auto projects = find_projects(root);
{
auto const ninjafile = (objdir / "build.ninja").string();
fs::create_directories(objdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto incdirs = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(incdirs), [&root](auto project) { return "-I" + (project.path / folder::include).string(); });
for (auto const& p : projects) {
for (auto const& s : p.sources) {
if (std::find(std::begin(extension::c), std::end(extension::c), fs::extension(s)) == std::end(extension::c))
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).string() << ": cxx " << (p.path / s).string() << "\n";
else
out << "build " << fs::change_extension(objdir / p.name / s, extension::obj).string() << ": cc " << (p.path / s).string() << "\n";
out << " incdirs = -I" << (p.path / folder::src).string() << " " << boost::algorithm::join(incdirs, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (libdir / "build.ninja").string();
fs::create_directories(libdir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
for (auto& p : projects) {
for (auto const& s : p.sources) {
auto const object = fs::change_extension(objdir / p.name / s, extension::obj);
auto const command = "nm " + object.string() + " --defined-only | grep --quiet ' T main'";
auto const result = std::system(command.c_str());
if (result)
p.objects.emplace_back(std::move(object));
else
p.binaries.emplace_back(std::move(object));
}
auto objects = std::vector<std::string> {};
std::transform(std::begin(p.objects), std::end(p.objects), std::back_inserter(objects), [](auto path) { return path.string(); });
out << "build " << (libdir / p.name).string() << extension::arc << ": arc $\n";
for (auto const& o : objects)
out << " " << o << " $\n";
out << "\n";
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
{
auto const ninjafile = (bindir / "build.ninja").string();
fs::create_directories(bindir);
{
auto && out = std::ofstream { ninjafile };
out << mekaninja;
auto archives = std::vector<std::string> {};
std::transform(std::begin(projects), std::end(projects), std::back_inserter(archives), [libdir](auto project) { return (libdir / project.name).string() + extension::arc; });
for (auto const& p : projects) {
for (auto const& o : p.binaries) {
out << "build " << (bindir / p.name / fs::basename(o)).string() << ": exe " << o.string() << " | " << boost::algorithm::join(archives, " $\n ") << "\n";
out << " libs = " << boost::algorithm::join(archives, " ") << "\n";
out << "\n";
}
}
}
auto const command = ninja + " -f " + ninjafile + " -k0";
auto const result = std::system(command.c_str());
if (result)
return result;
}
return 0;
}
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_CORE_IMAGE_HPP
#define DO_CORE_IMAGE_HPP
#include "Color.hpp"
#include "MultiArray.hpp"
namespace DO {
// ======================================================================== //
/*!
\ingroup Core
\defgroup Image Image
@{
*/
//! \brief The specialized element traits class when the entry is a color.
template <typename T, typename Layout>
struct ElementTraits<Pixel<T, Layout> >
{
typedef Array<T, Layout::size, 1> value_type; //!< STL-like typedef.
typedef size_t size_type; //!< STL-like typedef.
typedef value_type * pointer; //!< STL-like typedef.
typedef const value_type * const_pointer; //!< STL-like typedef.
typedef value_type& reference; //!< STL-like typedef.
typedef const value_type& const_reference; //!< STL-like typedef.
typedef value_type * iterator; //!< STL-like typedef.
typedef const value_type * const_iterator; //!< STL-like typedef.
static const bool is_scalar = false; //!< STL-like typedef.
};
//! The forward declaration of the image class.
template <typename Color, int N = 2> class Image;
//! \brief Helper function for color conversion.
template <typename T, typename U, int N>
void convert(Image<T, N>& dst, const Image<U, N>& src);
//! \brief The image class.
template <typename Color, int N>
class Image : public MultiArray<Color, N, ColMajor>
{
typedef MultiArray<Color, N, ColMajor> base_type;
public: /* interface */
//! N-dimensional integral vector type.
typedef typename base_type::vector_type vector_type, Vector;
//! Default constructor.
inline Image()
: base_type() {}
//! Constructor with specified sizes.
inline explicit Image(const vector_type& sizes)
: base_type(sizes) {}
//! Constructor which wraps raw data.
inline Image(Color *data, const vector_type& sizes,
bool getOwnership = false)
: base_type(data, sizes, getOwnership) {}
//! Constructor with specified sizes.
inline Image(int width, int height)
: base_type(width, height) {}
//! Constructor with specified sizes.
inline Image(int width, int height, int depth)
: base_type(width, height, depth) {}
//! Copy constructor.
inline Image(const base_type& x)
: base_type(x) {}
//! Assignment operators.
inline const Image& operator=(const Image& I)
{ base_type::operator=(I); return *this;}
//! Constant width accessor.
inline int width() const { return this->base_type::rows(); }
//! Constant height accessor.
inline int height() const { return this->base_type::cols(); }
//! Constant depth accessor (only for volumetric image.)
inline int depth() const { return this->base_type::depth(); }
//! Color conversion method.
template <typename Color2>
Image<Color2, N> convert() const
{
Image<Color2, N> dst(base_type::sizes());
DO::convert(dst, *this);
return dst;
}
//! Convenient helper for chaining filters.
template <template<typename, int> class Filter>
inline typename Filter<Color, N>::ReturnType
compute() const
{ return Filter<Color, N>(*this)(); }
template <template<typename, int> class Filter>
inline typename Filter<Color, N>::ReturnType
compute(const typename Filter<Color, N>::ParamType& param) const
{ return Filter<Color, N>(*this)(param); }
};
// ====================================================================== //
// Construct image views from row major multi-array.
//! \todo Check this functionality...
#define DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Colorspace) \
/*! \brief Reinterpret column-major matrix as an image. */ \
template <typename T> \
inline Image<Color<T, Colorspace>, Colorspace::size> \
as##Colorspace##Image(const MultiArray<Matrix<T,3,1>, \
Colorspace::size, \
ColMajor>& M) \
{ \
return Image<Color<T, Colorspace> >( \
reinterpret_cast<Color<T, Colorspace> *>(M.data()), \
M.sizes() ); \
}
DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Rgb)
DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Rgba)
DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Cmyk)
DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY(Yuv)
#undef DEFINE_IMAGE_VIEW_FROM_COLMAJOR_MULTIARRAY
// ====================================================================== //
// Generic image conversion function.
//! \brief Generic image converter class.
template <typename T, typename U, int N>
struct ConvertImage {
//! Implementation of the image conversion.
static void apply(Image<T, N>& dst, const Image<U, N>& src)
{
if (dst.sizes() != src.sizes())
dst.resize(src.sizes());
const U *src_first = src.data();
const U *src_last = src_first + src.size();
T *dst_first = dst.data();
for ( ; src_first != src_last; ++src_first, ++dst_first)
convertColor(*dst_first, *src_first);
}
};
//! \brief Specialized image converter class when the source and color types
//! are the same.
template <typename T, int N>
struct ConvertImage<T,T,N> {
//! Implementation of the image conversion.
static void apply(Image<T, N>& dst, const Image<T, N>& src)
{
dst = src;
}
};
template <typename T, typename U, int N>
inline void convert(Image<T, N>& dst, const Image<U, N>& src)
{
ConvertImage<T,U,N>::apply(dst, src);
}
// ====================================================================== //
// Find min and max values in images according to point-wise comparison.
//! \brief Find min and max pixel values of the image.
template <typename T, int N, typename Layout>
void findMinMax(Pixel<T, Layout>& min, Pixel<T, Layout>& max,
const Image<Pixel<T, Layout>, N>& src)
{
const Pixel<T,Layout> *src_first = src.data();
const Pixel<T,Layout> *src_last = src_first + src.size();
min = *src_first;
max = *src_first;
for ( ; src_first != src_last; ++src_first)
{
min = min.cwiseMin(*src_first);
max = max.cwiseMax(*src_first);
}
}
//! Macro that defines min-max value functions for a specific grayscale
//! color types.
#define DEFINE_FINDMINMAX_GRAY(T) \
/*! \brief Find min and max grayscale values of the image. */ \
template <int N> \
inline void findMinMax(T& min, T& max, const Image<T, N>& src)\
{ \
const T *src_first = src.data(); \
const T *src_last = src_first + src.size(); \
\
min = *std::min_element(src_first, src_last); \
max = *std::max_element(src_first, src_last); \
}
DEFINE_FINDMINMAX_GRAY(unsigned char)
DEFINE_FINDMINMAX_GRAY(char)
DEFINE_FINDMINMAX_GRAY(unsigned short)
DEFINE_FINDMINMAX_GRAY(short)
DEFINE_FINDMINMAX_GRAY(unsigned int)
DEFINE_FINDMINMAX_GRAY(int)
DEFINE_FINDMINMAX_GRAY(float)
DEFINE_FINDMINMAX_GRAY(double)
#undef DEFINE_FINDMINMAX_GRAY
// ====================================================================== //
// Image rescaling functions
//! \brief color rescaling function.
template <typename T, typename Layout, int N>
inline Image<Pixel<T,Layout>, N> colorRescale(
const Image<Pixel<T,Layout>, N>& src,
const Pixel<T, Layout>& a = black<T>(),
const Pixel<T, Layout>& b = white<T>())
{
Image<Pixel<T,Layout>, N> dst(src.sizes());
const Pixel<T,Layout> *src_first = src.data();
const Pixel<T,Layout> *src_last = src_first + src.size();
Pixel<T,Layout> *dst_first = dst.data();
Pixel<T,Layout> min(*src_first);
Pixel<T,Layout> max(*src_first);
for ( ; src_first != src_last; ++src_first)
{
min = min.cwiseMin(*src_first);
max = max.cwiseMax(*src_first);
}
if (min == max)
{
std::cerr << "Warning: min == max!" << std::endl;
return dst;
}
for (src_first = src.data(); src_first != src_last;
++src_first, ++dst_first)
*dst_first = a + (*src_first-min).cwiseProduct(b-a).
cwiseQuotient(max-min);
return dst;
}
//! Macro that defines a color rescaling function for a specific grayscale
//! color type.
#define DEFINE_RESCALE_GRAY(T) \
/*! \brief Rescales color values properly for viewing. */ \
template <int N> \
inline Image<T, N> colorRescale(const Image<T, N>& src, \
T a = ColorTraits<T>::min(), \
T b = ColorTraits<T>::max()) \
{ \
Image<T, N> dst(src.sizes()); \
\
const T *src_first = src.data(); \
const T *src_last = src_first + src.size(); \
T *dst_first = dst.data(); \
\
T min = *std::min_element(src_first, src_last); \
T max = *std::max_element(src_first, src_last); \
\
if (min == max) \
{ \
std::cerr << "Warning: min == max!" << std::endl; \
return dst; \
} \
\
for ( ; src_first != src_last; ++src_first, ++dst_first) \
*dst_first = a + (b-a)*(*src_first-min)/(max-min); \
\
return dst; \
}
DEFINE_RESCALE_GRAY(unsigned char)
DEFINE_RESCALE_GRAY(char)
DEFINE_RESCALE_GRAY(unsigned short)
DEFINE_RESCALE_GRAY(short)
DEFINE_RESCALE_GRAY(unsigned int)
DEFINE_RESCALE_GRAY(int)
DEFINE_RESCALE_GRAY(float)
DEFINE_RESCALE_GRAY(double)
#undef DEFINE_RESCALE_GRAY
//! \brief color rescaling functor helper.
template <typename T, int N>
struct ColorRescale
{
typedef Image<T, N> ReturnType;
ColorRescale(const Image<T, N>& src) : src_(src) {}
ReturnType operator()() const { return colorRescale(src_); }
const Image<T, N>& src_;
};
//! @}
} /* namespace DO */
#endif /* DO_CORE_IMAGE_HPP */<commit_msg>Remove unused and untested function.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_CORE_IMAGE_HPP
#define DO_CORE_IMAGE_HPP
#include "Color.hpp"
#include "MultiArray.hpp"
namespace DO {
// ======================================================================== //
/*!
\ingroup Core
\defgroup Image Image
@{
*/
//! \brief The specialized element traits class when the entry is a color.
template <typename T, typename Layout>
struct ElementTraits<Pixel<T, Layout> >
{
typedef Array<T, Layout::size, 1> value_type; //!< STL-like typedef.
typedef size_t size_type; //!< STL-like typedef.
typedef value_type * pointer; //!< STL-like typedef.
typedef const value_type * const_pointer; //!< STL-like typedef.
typedef value_type& reference; //!< STL-like typedef.
typedef const value_type& const_reference; //!< STL-like typedef.
typedef value_type * iterator; //!< STL-like typedef.
typedef const value_type * const_iterator; //!< STL-like typedef.
static const bool is_scalar = false; //!< STL-like typedef.
};
//! The forward declaration of the image class.
template <typename Color, int N = 2> class Image;
//! \brief Helper function for color conversion.
template <typename T, typename U, int N>
void convert(Image<T, N>& dst, const Image<U, N>& src);
//! \brief The image class.
template <typename Color, int N>
class Image : public MultiArray<Color, N, ColMajor>
{
typedef MultiArray<Color, N, ColMajor> base_type;
public: /* interface */
//! N-dimensional integral vector type.
typedef typename base_type::vector_type vector_type, Vector;
//! Default constructor.
inline Image()
: base_type() {}
//! Constructor with specified sizes.
inline explicit Image(const vector_type& sizes)
: base_type(sizes) {}
//! Constructor which wraps raw data.
inline Image(Color *data, const vector_type& sizes,
bool getOwnership = false)
: base_type(data, sizes, getOwnership) {}
//! Constructor with specified sizes.
inline Image(int width, int height)
: base_type(width, height) {}
//! Constructor with specified sizes.
inline Image(int width, int height, int depth)
: base_type(width, height, depth) {}
//! Copy constructor.
inline Image(const base_type& x)
: base_type(x) {}
//! Assignment operators.
inline const Image& operator=(const Image& I)
{ base_type::operator=(I); return *this;}
//! Constant width accessor.
inline int width() const { return this->base_type::rows(); }
//! Constant height accessor.
inline int height() const { return this->base_type::cols(); }
//! Constant depth accessor (only for volumetric image.)
inline int depth() const { return this->base_type::depth(); }
//! Color conversion method.
template <typename Color2>
Image<Color2, N> convert() const
{
Image<Color2, N> dst(base_type::sizes());
DO::convert(dst, *this);
return dst;
}
//! Convenient helper for chaining filters.
template <template<typename, int> class Filter>
inline typename Filter<Color, N>::ReturnType
compute() const
{ return Filter<Color, N>(*this)(); }
template <template<typename, int> class Filter>
inline typename Filter<Color, N>::ReturnType
compute(const typename Filter<Color, N>::ParamType& param) const
{ return Filter<Color, N>(*this)(param); }
};
// ====================================================================== //
// Generic image conversion function.
//! \brief Generic image converter class.
template <typename T, typename U, int N>
struct ConvertImage {
//! Implementation of the image conversion.
static void apply(Image<T, N>& dst, const Image<U, N>& src)
{
if (dst.sizes() != src.sizes())
dst.resize(src.sizes());
const U *src_first = src.data();
const U *src_last = src_first + src.size();
T *dst_first = dst.data();
for ( ; src_first != src_last; ++src_first, ++dst_first)
convertColor(*dst_first, *src_first);
}
};
//! \brief Specialized image converter class when the source and color types
//! are the same.
template <typename T, int N>
struct ConvertImage<T,T,N> {
//! Implementation of the image conversion.
static void apply(Image<T, N>& dst, const Image<T, N>& src)
{
dst = src;
}
};
template <typename T, typename U, int N>
inline void convert(Image<T, N>& dst, const Image<U, N>& src)
{
ConvertImage<T,U,N>::apply(dst, src);
}
// ====================================================================== //
// Find min and max values in images according to point-wise comparison.
//! \brief Find min and max pixel values of the image.
template <typename T, int N, typename Layout>
void findMinMax(Pixel<T, Layout>& min, Pixel<T, Layout>& max,
const Image<Pixel<T, Layout>, N>& src)
{
const Pixel<T,Layout> *src_first = src.data();
const Pixel<T,Layout> *src_last = src_first + src.size();
min = *src_first;
max = *src_first;
for ( ; src_first != src_last; ++src_first)
{
min = min.cwiseMin(*src_first);
max = max.cwiseMax(*src_first);
}
}
//! Macro that defines min-max value functions for a specific grayscale
//! color types.
#define DEFINE_FINDMINMAX_GRAY(T) \
/*! \brief Find min and max grayscale values of the image. */ \
template <int N> \
inline void findMinMax(T& min, T& max, const Image<T, N>& src)\
{ \
const T *src_first = src.data(); \
const T *src_last = src_first + src.size(); \
\
min = *std::min_element(src_first, src_last); \
max = *std::max_element(src_first, src_last); \
}
DEFINE_FINDMINMAX_GRAY(unsigned char)
DEFINE_FINDMINMAX_GRAY(char)
DEFINE_FINDMINMAX_GRAY(unsigned short)
DEFINE_FINDMINMAX_GRAY(short)
DEFINE_FINDMINMAX_GRAY(unsigned int)
DEFINE_FINDMINMAX_GRAY(int)
DEFINE_FINDMINMAX_GRAY(float)
DEFINE_FINDMINMAX_GRAY(double)
#undef DEFINE_FINDMINMAX_GRAY
// ====================================================================== //
// Image rescaling functions
//! \brief color rescaling function.
template <typename T, typename Layout, int N>
inline Image<Pixel<T,Layout>, N> colorRescale(
const Image<Pixel<T,Layout>, N>& src,
const Pixel<T, Layout>& a = black<T>(),
const Pixel<T, Layout>& b = white<T>())
{
Image<Pixel<T,Layout>, N> dst(src.sizes());
const Pixel<T,Layout> *src_first = src.data();
const Pixel<T,Layout> *src_last = src_first + src.size();
Pixel<T,Layout> *dst_first = dst.data();
Pixel<T,Layout> min(*src_first);
Pixel<T,Layout> max(*src_first);
for ( ; src_first != src_last; ++src_first)
{
min = min.cwiseMin(*src_first);
max = max.cwiseMax(*src_first);
}
if (min == max)
{
std::cerr << "Warning: min == max!" << std::endl;
return dst;
}
for (src_first = src.data(); src_first != src_last;
++src_first, ++dst_first)
*dst_first = a + (*src_first-min).cwiseProduct(b-a).
cwiseQuotient(max-min);
return dst;
}
//! Macro that defines a color rescaling function for a specific grayscale
//! color type.
#define DEFINE_RESCALE_GRAY(T) \
/*! \brief Rescales color values properly for viewing. */ \
template <int N> \
inline Image<T, N> colorRescale(const Image<T, N>& src, \
T a = ColorTraits<T>::min(), \
T b = ColorTraits<T>::max()) \
{ \
Image<T, N> dst(src.sizes()); \
\
const T *src_first = src.data(); \
const T *src_last = src_first + src.size(); \
T *dst_first = dst.data(); \
\
T min = *std::min_element(src_first, src_last); \
T max = *std::max_element(src_first, src_last); \
\
if (min == max) \
{ \
std::cerr << "Warning: min == max!" << std::endl; \
return dst; \
} \
\
for ( ; src_first != src_last; ++src_first, ++dst_first) \
*dst_first = a + (b-a)*(*src_first-min)/(max-min); \
\
return dst; \
}
DEFINE_RESCALE_GRAY(unsigned char)
DEFINE_RESCALE_GRAY(char)
DEFINE_RESCALE_GRAY(unsigned short)
DEFINE_RESCALE_GRAY(short)
DEFINE_RESCALE_GRAY(unsigned int)
DEFINE_RESCALE_GRAY(int)
DEFINE_RESCALE_GRAY(float)
DEFINE_RESCALE_GRAY(double)
#undef DEFINE_RESCALE_GRAY
//! \brief color rescaling functor helper.
template <typename T, int N>
struct ColorRescale
{
typedef Image<T, N> ReturnType;
ColorRescale(const Image<T, N>& src) : src_(src) {}
ReturnType operator()() const { return colorRescale(src_); }
const Image<T, N>& src_;
};
//! @}
} /* namespace DO */
#endif /* DO_CORE_IMAGE_HPP */<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n = 0;
cin >> n;
vector<long long> v(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
// Alice opration
bool Alicefound = false;
long long diff = 0;
while (true)
{
AliceOperation:for (int i = 0; i < v.size(); ++i)
{
for (int j = i + 1; j < v.size(); ++j)
{
diff = abs(v[i] - v[j]);
if (count(v.begin(), v.end(), diff) == 0)
{
v.push_back(diff);
Alicefound = true;
goto BobOperation;
}
}
}
if (!Alicefound)
{
cout << "Bob" << endl;
break;
}
// Bob operation
BobOperation: for (int i = 0; i < v.size(); ++i)
{
for (int j = i + 1; j < v.size(); ++j)
{
diff = abs(v[i] - v[j]);
if (count(v.begin(), v.end(), diff) == 0)
{
v.push_back(diff);
Alicefound = false;
goto AliceOperation;
}
}
}
if (Alicefound)
{
cout << "Alice" << endl;
break;
}
}
return 0;
}
<commit_msg>use GCD of array to solve it elegant, refer to other's algorithm, good<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Greatest Common Divisor between a and b
long long gcd(long long a, long long b)
{
while (b != 0)
{
long long r = a % b;
a = b;
b = r;
}
return a;
}
// return the greatest common divisor among all values in v
// Time complexity:
long long arrayGcd(vector<long long> v)
{
long long result = v[0];
for (int i = 1; i < v.size(); ++i)
{
result = gcd(result, v[i]);
}
return result;
}
int main()
{
// read input
int n = 0;
cin >> n;
vector<long long> v(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
long long max_elem = *max_element(v.begin(), v.end());
long long d = arrayGcd(v);
long long remain_round = max_elem / d - v.size();
if (remain_round % 2 == 1)
{
cout << "Alice" << endl;
}
else
{
cout << "Bob" << endl;
}
return 0;
}
// Summary:
// 1. calculate GCD use Euler Algorithm
// 2. calculate other GCD always depends on Euler's GCD Algorithm
// 3. figure out why we can achieve all the differece |x-y| in such
// way, what's behind ? Number Theory ?
<|endoftext|> |
<commit_before>#pragma once
#include <fc/reflect/variant.hpp>
#include <functional>
#include <string>
#include <fc/optional.hpp>
#include <fc/variant.hpp>
//#include <fc/network/ip.hpp>
//#include <fc/variant.hpp>
namespace bts { namespace api {
enum method_prerequisites
{
no_prerequisites = 0,
json_authenticated = 1,
wallet_open = 2,
wallet_unlocked = 4,
connected_to_network = 8,
};
enum parameter_classification
{
required_positional,
required_positional_hidden, /* Hide in help e.g. interactive password entry */
optional_positional,
optional_named
};
struct parameter_data
{
std::string name;
std::string type;
parameter_classification classification;
fc::ovariant default_value;
parameter_data(const parameter_data& rhs) :
name(rhs.name),
type(rhs.type),
classification(rhs.classification),
default_value(rhs.default_value)
{}
parameter_data(const parameter_data&& rhs) :
name(std::move(rhs.name)),
type(std::move(rhs.type)),
classification(std::move(rhs.classification)),
default_value(std::move(rhs.default_value))
{}
parameter_data(std::string name,
std::string type,
parameter_classification classification,
fc::ovariant default_value) :
name(name),
type(type),
classification(classification),
default_value(default_value)
{}
};
typedef std::function<fc::variant(const fc::variants& params)> json_api_method_type;
struct method_data
{
std::string name;
json_api_method_type method;
std::string description;
std::string return_type;
std::vector<parameter_data> parameters;
uint32_t prerequisites;
std::string detailed_description;
std::vector<std::string> aliases;
};
} } // end namespace bts::api
FC_REFLECT_ENUM(bts::api::method_prerequisites, (no_prerequisites)(json_authenticated)(wallet_open)(wallet_unlocked)(connected_to_network))
<commit_msg>Add operator= that gcc wants to use<commit_after>#pragma once
#include <fc/reflect/variant.hpp>
#include <functional>
#include <string>
#include <fc/optional.hpp>
#include <fc/variant.hpp>
//#include <fc/network/ip.hpp>
//#include <fc/variant.hpp>
namespace bts { namespace api {
enum method_prerequisites
{
no_prerequisites = 0,
json_authenticated = 1,
wallet_open = 2,
wallet_unlocked = 4,
connected_to_network = 8,
};
enum parameter_classification
{
required_positional,
required_positional_hidden, /* Hide in help e.g. interactive password entry */
optional_positional,
optional_named
};
struct parameter_data
{
std::string name;
std::string type;
parameter_classification classification;
fc::ovariant default_value;
parameter_data(const parameter_data& rhs) :
name(rhs.name),
type(rhs.type),
classification(rhs.classification),
default_value(rhs.default_value)
{}
parameter_data(const parameter_data&& rhs) :
name(std::move(rhs.name)),
type(std::move(rhs.type)),
classification(std::move(rhs.classification)),
default_value(std::move(rhs.default_value))
{}
parameter_data(std::string name,
std::string type,
parameter_classification classification,
fc::ovariant default_value) :
name(name),
type(type),
classification(classification),
default_value(default_value)
{}
parameter_data& operator=(const parameter_data& rhs)
{
name = rhs.name;
type = rhs.type;
classification = rhs.classification;
default_value = rhs.default_value;
return *this;
}
};
typedef std::function<fc::variant(const fc::variants& params)> json_api_method_type;
struct method_data
{
std::string name;
json_api_method_type method;
std::string description;
std::string return_type;
std::vector<parameter_data> parameters;
uint32_t prerequisites;
std::string detailed_description;
std::vector<std::string> aliases;
};
} } // end namespace bts::api
FC_REFLECT_ENUM(bts::api::method_prerequisites, (no_prerequisites)(json_authenticated)(wallet_open)(wallet_unlocked)(connected_to_network))
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CIRCULARBUFFER_HPP_INCLUDE
#define CIRCULARBUFFER_HPP_INCLUDE
#include <stdlib.h>
#include <vector>
namespace geopm
{
/// @brief Templated container for a circular buffer implementation.
///
/// The CircularBuffer container implements a fixed size buffer. Once
/// at capacity, any new insertions cause the oldest entry to be dropped.
template <class type>
class CircularBuffer
{
public:
/// @brief Constructor ofr the CircularBuffer template.
///
/// Creates an empty circular buffer with a set capacity.
///
/// @param [in] size Requested capacity for the buffer.
CircularBuffer(const unsigned int size);
/// @brief CircularBuffer destructor, virtual
virtual ~CircularBuffer();
/// @brief Resize the circular buffer.
///
/// Resets the capacity of the circular buffer without
/// modifying it's current contents.
///
/// @param [in] size Requested capacity for the buffer.
void set_capacity(const unsigned int size);
/// @brief Clears all entries fron the buffer.
void clear(void);
/// @brief Size of the buffer contents.
///
/// Returns the number of items in the buffer. This
/// value will be less than or equal to the current
/// capacity of the buffer.
//
/// @retrun Size of the buffer contents.
int size(void) const;
/// @brief Capacity of the buffer.
///
/// Returns the current size of the circular buffer at
/// the time of the call.
///
/// @return Capacity of the buffer.
int capacity(void) const;
/// @brief Insert a value into the buffer.
///
/// If the buffer is not full, the nae value is simply
/// added to the buffer. It the buffer is at capacity,
/// The head of the buffer is dropped and moved to the
/// next oldest entry and the new value is then inserted
/// at the end of the buffer.
///
/// @param [in] value The value to be inserted.
void insert(const type value);
/// @brief Returns a value from the buffer.
///
/// Accesses the contents of the circular buffer
/// at a particular index. Valid indicies range
/// from 0 to [size-1]. Where size is the number
/// of valid entries in the buffer. An attemp to
/// retrieve a value for an out of bound index a
/// geopm::Exception will be thrown with an
/// error_value() of GEOPM_ERROR_INVALID.
///
/// @param [in] index Buffer index to retrieve.
///
/// @return Value from the specified buffer index.
type value(const unsigned int index) const;
protected:
/// @brief Vector holding the buffer data.
std::vector<type> m_buffer;
/// @brief Index of the current head of the buffer.
unsigned long m_head;
/// @brief The number of valid enrties in the buffer.
unsigned long m_count;
/// @brief Current capacity of the buffer.
size_t m_max_size;
};
template <class type>
CircularBuffer<type>::CircularBuffer(const unsigned int size)
{
m_max_size = size;
m_head = 0;
m_count = 0;
}
template <class type>
CircularBuffer<type>::~CircularBuffer()
{
}
template <class type>
int CircularBuffer<type>::size() const
{
return m_count;
}
template <class type>
int CircularBuffer<type>::capacity() const
{
return m_max_size;
}
template <class type>
void CircularBuffer<type>::clear()
{
m_buffer.clear();
m_head = 0;
m_count = 0;
}
template <class type>
void CircularBuffer<type>::set_capacity(const unsigned int size)
{
if (size < m_count) {
int size_diff = m_count - size;
std::vector<type> temp;
//Copy newest data into temporary vector
for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) {
temp.push_back(m_buffer[i]);
}
//now resize and swap out with tmp vector data
m_buffer.resize(size);
m_buffer.swap(temp);
m_count = size;
}
else {
m_buffer.resize(size);
}
m_head = 0;
m_max_size = size;
}
template <class type>
void CircularBuffer<type>::insert(const type value)
{
if (m_count < m_max_size) {
m_buffer.push_back(value);
m_count++;
}
else {
m_buffer[m_head] = value;
m_head = ((m_head + 1) % m_max_size);
}
}
template <class type>
type CircularBuffer<type>::value(const unsigned int index) const
{
return m_buffer[(m_head+index) % m_max_size];
}
}
#endif
<commit_msg>Added throws on error conditions on inserting and retrieving values from a CircularBuffer.<commit_after>/*
* Copyright (c) 2015, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CIRCULARBUFFER_HPP_INCLUDE
#define CIRCULARBUFFER_HPP_INCLUDE
#include <stdlib.h>
#include <vector>
#include "Exception.hpp"
namespace geopm
{
/// @brief Templated container for a circular buffer implementation.
///
/// The CircularBuffer container implements a fixed size buffer. Once
/// at capacity, any new insertions cause the oldest entry to be dropped.
template <class type>
class CircularBuffer
{
public:
/// @brief Constructor ofr the CircularBuffer template.
///
/// Creates an empty circular buffer with a set capacity.
///
/// @param [in] size Requested capacity for the buffer.
CircularBuffer(const unsigned int size);
/// @brief CircularBuffer destructor, virtual
virtual ~CircularBuffer();
/// @brief Resize the circular buffer.
///
/// Resets the capacity of the circular buffer without
/// modifying it's current contents.
///
/// @param [in] size Requested capacity for the buffer.
void set_capacity(const unsigned int size);
/// @brief Clears all entries fron the buffer.
void clear(void);
/// @brief Size of the buffer contents.
///
/// Returns the number of items in the buffer. This
/// value will be less than or equal to the current
/// capacity of the buffer.
//
/// @retrun Size of the buffer contents.
int size(void) const;
/// @brief Capacity of the buffer.
///
/// Returns the current size of the circular buffer at
/// the time of the call.
///
/// @return Capacity of the buffer.
int capacity(void) const;
/// @brief Insert a value into the buffer.
///
/// If the buffer is not full, the nae value is simply
/// added to the buffer. It the buffer is at capacity,
/// The head of the buffer is dropped and moved to the
/// next oldest entry and the new value is then inserted
/// at the end of the buffer.
///
/// @param [in] value The value to be inserted.
void insert(const type value);
/// @brief Returns a value from the buffer.
///
/// Accesses the contents of the circular buffer
/// at a particular index. Valid indicies range
/// from 0 to [size-1]. Where size is the number
/// of valid entries in the buffer. An attemp to
/// retrieve a value for an out of bound index a
/// geopm::Exception will be thrown with an
/// error_value() of GEOPM_ERROR_INVALID.
///
/// @param [in] index Buffer index to retrieve.
///
/// @return Value from the specified buffer index.
type value(const unsigned int index) const;
protected:
/// @brief Vector holding the buffer data.
std::vector<type> m_buffer;
/// @brief Index of the current head of the buffer.
unsigned long m_head;
/// @brief The number of valid enrties in the buffer.
unsigned long m_count;
/// @brief Current capacity of the buffer.
size_t m_max_size;
};
template <class type>
CircularBuffer<type>::CircularBuffer(const unsigned int size)
{
m_max_size = size;
m_head = 0;
m_count = 0;
}
template <class type>
CircularBuffer<type>::~CircularBuffer()
{
}
template <class type>
int CircularBuffer<type>::size() const
{
return m_count;
}
template <class type>
int CircularBuffer<type>::capacity() const
{
return m_max_size;
}
template <class type>
void CircularBuffer<type>::clear()
{
m_buffer.clear();
m_head = 0;
m_count = 0;
}
template <class type>
void CircularBuffer<type>::set_capacity(const unsigned int size)
{
if (size < m_count) {
int size_diff = m_count - size;
std::vector<type> temp;
//Copy newest data into temporary vector
for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) {
temp.push_back(m_buffer[i]);
}
//now resize and swap out with tmp vector data
m_buffer.resize(size);
m_buffer.swap(temp);
m_count = size;
}
else {
m_buffer.resize(size);
}
m_head = 0;
m_max_size = size;
}
template <class type>
void CircularBuffer<type>::insert(const type value)
{
if (m_max_size < 1) {
throw Exception("CircularBuffer::insert(): Cannot insert into a bufffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (m_count < m_max_size) {
m_buffer.push_back(value);
m_count++;
}
else {
m_buffer[m_head] = value;
m_head = ((m_head + 1) % m_max_size);
}
}
template <class type>
type CircularBuffer<type>::value(const unsigned int index) const
{
if (index >= m_count) {
throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
return m_buffer[(m_head+index) % m_max_size];
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 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: Nathan Binkert
* Dave Greene
*/
#ifndef __MISC_HH__
#define __MISC_HH__
#include <assert.h>
#include "base/cprintf.hh"
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
void __panic(const std::string&, cp::ArgList &, const char*, const char*, int)
__attribute__((noreturn));
#define __panic__(format, args...) \
__panic(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define panic(args...) \
__panic__(args, cp::ArgListNull())
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls exit(1), i.e., a
// "normal" exit with an error code, as opposed to abort() like
// panic() does.
//
void __fatal(const std::string&, cp::ArgList &, const char*, const char*, int)
__attribute__((noreturn));
#define __fatal__(format, args...) \
__fatal(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define fatal(args...) \
__fatal__(args, cp::ArgListNull())
//
// This implements a cprintf based warn
//
void __warn(const std::string&, cp::ArgList &, const char*, const char*, int);
#define __warn__(format, args...) \
__warn(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define warn(args...) \
__warn__(args, cp::ArgListNull())
//
// assert() that prints out the current cycle
//
#define m5_assert(TEST) \
if (!(TEST)) { \
std::cerr << "Assertion failure, curTick = " << curTick << std::endl; \
} \
assert(TEST);
#endif // __MISC_HH__
<commit_msg>add warn_once which will print any given warning message only once.<commit_after>/*
* Copyright (c) 2002-2005 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: Nathan Binkert
* Dave Greene
*/
#ifndef __MISC_HH__
#define __MISC_HH__
#include <assert.h>
#include "base/cprintf.hh"
//
// This implements a cprintf based panic() function. panic() should
// be called when something happens that should never ever happen
// regardless of what the user does (i.e., an acutal m5 bug). panic()
// calls abort which can dump core or enter the debugger.
//
//
void __panic(const std::string&, cp::ArgList &, const char*, const char*, int)
__attribute__((noreturn));
#define __panic__(format, args...) \
__panic(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define panic(args...) \
__panic__(args, cp::ArgListNull())
//
// This implements a cprintf based fatal() function. fatal() should
// be called when the simulation cannot continue due to some condition
// that is the user's fault (bad configuration, invalid arguments,
// etc.) and not a simulator bug. fatal() calls exit(1), i.e., a
// "normal" exit with an error code, as opposed to abort() like
// panic() does.
//
void __fatal(const std::string&, cp::ArgList &, const char*, const char*, int)
__attribute__((noreturn));
#define __fatal__(format, args...) \
__fatal(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define fatal(args...) \
__fatal__(args, cp::ArgListNull())
//
// This implements a cprintf based warn
//
void __warn(const std::string&, cp::ArgList &, const char*, const char*, int);
#define __warn__(format, args...) \
__warn(format, (*(new cp::ArgList), args), \
__FUNCTION__, __FILE__, __LINE__)
#define warn(args...) \
__warn__(args, cp::ArgListNull())
// Only print the warning message the first time it is seen. This
// doesn't check the warning string itself, it just only lets one
// warning come from the statement. So, even if the arguments change
// and that would have resulted in a different warning message,
// subsequent messages would still be supressed.
#define warn_once(args...) do { \
static bool once = false; \
if (!once) { \
__warn__(args, cp::ArgListNull()); \
once = true; \
} \
} while (0)
//
// assert() that prints out the current cycle
//
#define m5_assert(TEST) \
if (!(TEST)) { \
std::cerr << "Assertion failure, curTick = " << curTick << std::endl; \
} \
assert(TEST);
#endif // __MISC_HH__
<|endoftext|> |
<commit_before>/*****************************************************************************
bedtools.cpp
bedtools command line interface.
Thanks to Heng Li, as this interface is inspired and
based upon his samtools interface.
(c) 2009-2011 - Aaron Quinlan
Quinlan Laboratory
Department of Public Health Sciences
Center for Public Health genomics
University of Virginia
[email protected]
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools"
// colors for the term's menu
#define RESET "\033[m"
#define GREEN "\033[1;32m"
#define BLUE "\033[1;34m"
#define RED "\033[1;31m"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
int annotate_main(int argc, char* argv[]);//
int bamtobed_main(int argc, char* argv[]);//
int bamtofastq_main(int argc, char* argv[]);//
int bed12tobed6_main(int argc, char* argv[]); //
int bedtobam_main(int argc, char* argv[]);//
int bedtoigv_main(int argc, char* argv[]);//
int bedpetobam_main(int argc, char* argv[]);//
int closest_main(int argc, char* argv[]); //
int cluster_main(int argc, char* argv[]); //
int complement_main(int argc, char* argv[]);//
int coverage_main(int argc, char* argv[]); //
int expand_main(int argc, char* argv[]);//
int fastafrombed_main(int argc, char* argv[]);//
int flank_main(int argc, char* argv[]); //
int genomecoverage_main(int argc, char* argv[]);//
int getoverlap_main(int argc, char* argv[]);//
int groupby_main(int argc, char* argv[]);//
int intersect_main(int argc, char* argv[]); //
int links_main(int argc, char* argv[]);//
int maskfastafrombed_main(int argc, char* argv[]);//
int map_main(int argc, char* argv[]); //
int merge_main(int argc, char* argv[]); //
int multibamcov_main(int argc, char* argv[]);//
int multiintersect_main(int argc, char* argv[]);//
int nuc_main(int argc, char* argv[]);//
int pairtobed_main(int argc, char* argv[]);//
int pairtopair_main(int argc, char* argv[]);//
int random_main(int argc, char* argv[]); //
int shuffle_main(int argc, char* argv[]); //
int slop_main(int argc, char* argv[]); //
int sort_main(int argc, char* argv[]); //
int subtract_main(int argc, char* argv[]); //
int tagbam_main(int argc, char* argv[]);//
int unionbedgraphs_main(int argc, char* argv[]);//
int window_main(int argc, char* argv[]); //
int windowmaker_main(int argc, char* argv[]); //
int bedtools_help(void);
int bedtools_faq(void);
int main(int argc, char *argv[])
{
// make sure the user at least entered a sub_command
if (argc < 2) return bedtools_help();
std::string sub_cmd = argv[1];
// genome arithmetic tools
if (sub_cmd == "intersect") return intersect_main(argc-1, argv+1);
else if (sub_cmd == "window") return window_main(argc-1, argv+1);
else if (sub_cmd == "closest") return closest_main(argc-1, argv+1);
else if (sub_cmd == "coverage") return coverage_main(argc-1, argv+1);
else if (sub_cmd == "map") return map_main(argc-1, argv+1);
else if (sub_cmd == "genomecov") return genomecoverage_main(argc-1, argv+1);
else if (sub_cmd == "merge") return merge_main(argc-1, argv+1);
else if (sub_cmd == "cluster") return cluster_main(argc-1, argv+1);
else if (sub_cmd == "complement") return complement_main(argc-1, argv+1);
else if (sub_cmd == "subtract") return subtract_main(argc-1, argv+1);
else if (sub_cmd == "slop") return slop_main(argc-1, argv+1);
else if (sub_cmd == "flank") return flank_main(argc-1, argv+1);
else if (sub_cmd == "sort") return sort_main(argc-1, argv+1);
else if (sub_cmd == "random") return random_main(argc-1, argv+1);
else if (sub_cmd == "shuffle") return shuffle_main(argc-1, argv+1);
else if (sub_cmd == "annotate") return annotate_main(argc-1, argv+1);
// Multi-way file comparisonstools
else if (sub_cmd == "multiinter") return multiintersect_main(argc-1, argv+1);
else if (sub_cmd == "unionbedg") return unionbedgraphs_main(argc-1, argv+1);
// paired-end conversion tools
else if (sub_cmd == "pairtobed") return pairtobed_main(argc-1, argv+1);
else if (sub_cmd == "pairtopair") return pairtopair_main(argc-1, argv+1);
// format conversion tools
else if (sub_cmd == "bamtobed") return bamtobed_main(argc-1, argv+1);
else if (sub_cmd == "bedtobam") return bedtobam_main(argc-1, argv+1);
else if (sub_cmd == "bamtofastq") return bamtofastq_main(argc-1, argv+1);
else if (sub_cmd == "bedpetobam") return bedpetobam_main(argc-1, argv+1);
else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1);
// BAM-specific tools
else if (sub_cmd == "multicov") return multibamcov_main(argc-1, argv+1);
else if (sub_cmd == "tag") return tagbam_main(argc-1, argv+1);
// fasta tools
else if (sub_cmd == "getfasta") return fastafrombed_main(argc-1, argv+1);
else if (sub_cmd == "maskfasta") return maskfastafrombed_main(argc-1, argv+1);
else if (sub_cmd == "nuc") return nuc_main(argc-1, argv+1);
// misc. tools
else if (sub_cmd == "overlap") return getoverlap_main(argc-1, argv+1);
else if (sub_cmd == "igv") return bedtoigv_main(argc-1, argv+1);
else if (sub_cmd == "links") return links_main(argc-1, argv+1);
else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1);
else if (sub_cmd == "groupby") return groupby_main(argc-1, argv+1);
else if (sub_cmd == "expand") return expand_main(argc-1, argv+1);
// help
else if (sub_cmd == "-h" || sub_cmd == "--help" ||
sub_cmd == "-help")
return bedtools_help();
// frequently asked questions
else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" ||
sub_cmd == "-FAQ" || sub_cmd == "-faq")
return bedtools_faq();
// verison information
else if (sub_cmd == "-version" || sub_cmd == "--version")
cout << "bedtools " << VERSION << endl;
// verison information
else if (sub_cmd == "-contact" || sub_cmd == "--contact")
{
cout << endl;
cout << "- For further help, or to report a bug, please " << endl;
cout << " email the bedtools mailing list: " << endl;
cout << " [email protected]" << endl << endl;
cout << "- Stable releases of bedtools can be found at: " << endl;
cout << " http://bedtools.googlecode.com" << endl << endl;
cout << "- The development repository can be found at: " << endl;
cout << " https://github.com/arq5x/bedtools" << endl << endl;
}
// unknown
else {
// TODO: Implement a Levenstein-based "did you mean???"
cerr << "error: unrecognized command: " << argv[1] << endl << endl;
return 1;
}
return 0;
}
int bedtools_help(void)
{
cout << PROGRAM_NAME << ": flexible tools for genome arithmetic and DNA sequence analysis.\n";
cout << "usage: bedtools <subcommand> [options]" << endl << endl;
cout << "The bedtools sub-commands include:" << endl;
cout << endl;
cout << "[ Genome arithmetic ]" << endl;
cout << " intersect " << "Find overlapping intervals in various ways.\n";
cout << " window " << "Find overlapping intervals within a window around an interval.\n";
cout << " closest " << "Find the closest, potentially non-overlapping interval.\n";
cout << " coverage " << "Compute the coverage over defined intervals.\n";
cout << " map " << "Apply a function to a column for each overlapping interval.\n";
cout << " genomecov " << "Compute the coverage over an entire genome.\n";
cout << " merge " << "Combine overlapping/nearby intervals into a single interval.\n";
cout << " cluster " << "Cluster (but don't merge) overlapping/nearby intervals.\n";
cout << " complement " << "Extract intervals _not_ represented by an interval file.\n";
cout << " subtract " << "Remove intervals based on overlaps b/w two files.\n";
cout << " slop " << "Adjust the size of intervals.\n";
cout << " flank " << "Create new intervals from the flanks of existing intervals.\n";
cout << " sort " << "Order the intervals in a file.\n";
cout << " random " << "Generate random intervals in a genome.\n";
cout << " shuffle " << "Randomly redistrubute intervals in a genome.\n";
cout << " annotate " << "Annotate coverage of features from multiple files.\n";
cout << endl;
cout << "[ Multi-way file comparisons ]" << endl;
cout << " multiinter " << "Identifies common intervals among multiple interval files.\n";
cout << " unionbedg " << "Combines coverage intervals from multiple BEDGRAPH files.\n";
cout << endl;
cout << "[ Paired-end manipulation ]" << endl;
cout << " pairtobed " << "Find pairs that overlap intervals in various ways.\n";
cout << " pairtopair " << "Find pairs that overlap other pairs in various ways.\n";
cout << endl;
cout << "[ Format conversion ]" << endl;
cout << " bamtobed " << "Convert BAM alignments to BED (& other) formats.\n";
cout << " bedtobam " << "Convert intervals to BAM records.\n";
cout << " bedtofastq " << "Convert BAM records to FASTQ records.\n";
cout << " bedpetobam " << "Convert BEDPE intervals to BAM records.\n";
cout << " bed12tobed6 " << "Breaks BED12 intervals into discrete BED6 intervals.\n";
cout << endl;
cout << "[ Fasta manipulation ]" << endl;
cout << " getfasta " << "Use intervals to extract sequences from a FASTA file.\n";
cout << " maskfasta " << "Use intervals to mask sequences from a FASTA file.\n";
cout << " nuc " << "Profile the nucleotide content of intervals in a FASTA file.\n";
cout << endl;
cout << "[ BAM focused tools ]" << endl;
cout << " multicov " << "Counts coverage from multiple BAMs at specific intervals.\n";
cout << " tag " << "Tag BAM alignments based on overlaps with interval files.\n";
cout << endl;
cout << "[ Miscellaneous tools ]" << endl;
cout << " overlap " << "Computes the amount of overlap from two intervals.\n";
cout << " igv " << "Create an IGV snapshot batch script.\n";
cout << " links " << "Create a HTML page of links to UCSC locations.\n";
cout << " makewindows " << "Make interval \"windows\" across a genome.\n";
cout << " groupby " << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n";
cout << " expand " << "Replicate lines based on lists of values in columns.\n";
cout << endl;
cout << "[ General help ]" << endl;
cout << " --help " << "Print this help menu.\n";
//cout << " --faq " << "Frequently asked questions.\n"; TODO
cout << " --version " << "What version of bedtools are you using?.\n";
cout << " --contact " << "Feature requests, bugs, mailing lists, etc.\n";
cout << "\n";
return 0;
}
int bedtools_faq(void)
{
cout << "\n";
cout << "Q1. How do I see the help for a given command?" << endl;
cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl;
cout << " will provide the help menu if you just type the command line " << endl;
cout << " followed by enter. " << endl;
cout << "\n";
return 0;
}
<commit_msg>menu typo<commit_after>/*****************************************************************************
bedtools.cpp
bedtools command line interface.
Thanks to Heng Li, as this interface is inspired and
based upon his samtools interface.
(c) 2009-2011 - Aaron Quinlan
Quinlan Laboratory
Department of Public Health Sciences
Center for Public Health genomics
University of Virginia
[email protected]
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools"
// colors for the term's menu
#define RESET "\033[m"
#define GREEN "\033[1;32m"
#define BLUE "\033[1;34m"
#define RED "\033[1;31m"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
int annotate_main(int argc, char* argv[]);//
int bamtobed_main(int argc, char* argv[]);//
int bamtofastq_main(int argc, char* argv[]);//
int bed12tobed6_main(int argc, char* argv[]); //
int bedtobam_main(int argc, char* argv[]);//
int bedtoigv_main(int argc, char* argv[]);//
int bedpetobam_main(int argc, char* argv[]);//
int closest_main(int argc, char* argv[]); //
int cluster_main(int argc, char* argv[]); //
int complement_main(int argc, char* argv[]);//
int coverage_main(int argc, char* argv[]); //
int expand_main(int argc, char* argv[]);//
int fastafrombed_main(int argc, char* argv[]);//
int flank_main(int argc, char* argv[]); //
int genomecoverage_main(int argc, char* argv[]);//
int getoverlap_main(int argc, char* argv[]);//
int groupby_main(int argc, char* argv[]);//
int intersect_main(int argc, char* argv[]); //
int links_main(int argc, char* argv[]);//
int maskfastafrombed_main(int argc, char* argv[]);//
int map_main(int argc, char* argv[]); //
int merge_main(int argc, char* argv[]); //
int multibamcov_main(int argc, char* argv[]);//
int multiintersect_main(int argc, char* argv[]);//
int nuc_main(int argc, char* argv[]);//
int pairtobed_main(int argc, char* argv[]);//
int pairtopair_main(int argc, char* argv[]);//
int random_main(int argc, char* argv[]); //
int shuffle_main(int argc, char* argv[]); //
int slop_main(int argc, char* argv[]); //
int sort_main(int argc, char* argv[]); //
int subtract_main(int argc, char* argv[]); //
int tagbam_main(int argc, char* argv[]);//
int unionbedgraphs_main(int argc, char* argv[]);//
int window_main(int argc, char* argv[]); //
int windowmaker_main(int argc, char* argv[]); //
int bedtools_help(void);
int bedtools_faq(void);
int main(int argc, char *argv[])
{
// make sure the user at least entered a sub_command
if (argc < 2) return bedtools_help();
std::string sub_cmd = argv[1];
// genome arithmetic tools
if (sub_cmd == "intersect") return intersect_main(argc-1, argv+1);
else if (sub_cmd == "window") return window_main(argc-1, argv+1);
else if (sub_cmd == "closest") return closest_main(argc-1, argv+1);
else if (sub_cmd == "coverage") return coverage_main(argc-1, argv+1);
else if (sub_cmd == "map") return map_main(argc-1, argv+1);
else if (sub_cmd == "genomecov") return genomecoverage_main(argc-1, argv+1);
else if (sub_cmd == "merge") return merge_main(argc-1, argv+1);
else if (sub_cmd == "cluster") return cluster_main(argc-1, argv+1);
else if (sub_cmd == "complement") return complement_main(argc-1, argv+1);
else if (sub_cmd == "subtract") return subtract_main(argc-1, argv+1);
else if (sub_cmd == "slop") return slop_main(argc-1, argv+1);
else if (sub_cmd == "flank") return flank_main(argc-1, argv+1);
else if (sub_cmd == "sort") return sort_main(argc-1, argv+1);
else if (sub_cmd == "random") return random_main(argc-1, argv+1);
else if (sub_cmd == "shuffle") return shuffle_main(argc-1, argv+1);
else if (sub_cmd == "annotate") return annotate_main(argc-1, argv+1);
// Multi-way file comparisonstools
else if (sub_cmd == "multiinter") return multiintersect_main(argc-1, argv+1);
else if (sub_cmd == "unionbedg") return unionbedgraphs_main(argc-1, argv+1);
// paired-end conversion tools
else if (sub_cmd == "pairtobed") return pairtobed_main(argc-1, argv+1);
else if (sub_cmd == "pairtopair") return pairtopair_main(argc-1, argv+1);
// format conversion tools
else if (sub_cmd == "bamtobed") return bamtobed_main(argc-1, argv+1);
else if (sub_cmd == "bedtobam") return bedtobam_main(argc-1, argv+1);
else if (sub_cmd == "bamtofastq") return bamtofastq_main(argc-1, argv+1);
else if (sub_cmd == "bedpetobam") return bedpetobam_main(argc-1, argv+1);
else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1);
// BAM-specific tools
else if (sub_cmd == "multicov") return multibamcov_main(argc-1, argv+1);
else if (sub_cmd == "tag") return tagbam_main(argc-1, argv+1);
// fasta tools
else if (sub_cmd == "getfasta") return fastafrombed_main(argc-1, argv+1);
else if (sub_cmd == "maskfasta") return maskfastafrombed_main(argc-1, argv+1);
else if (sub_cmd == "nuc") return nuc_main(argc-1, argv+1);
// misc. tools
else if (sub_cmd == "overlap") return getoverlap_main(argc-1, argv+1);
else if (sub_cmd == "igv") return bedtoigv_main(argc-1, argv+1);
else if (sub_cmd == "links") return links_main(argc-1, argv+1);
else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1);
else if (sub_cmd == "groupby") return groupby_main(argc-1, argv+1);
else if (sub_cmd == "expand") return expand_main(argc-1, argv+1);
// help
else if (sub_cmd == "-h" || sub_cmd == "--help" ||
sub_cmd == "-help")
return bedtools_help();
// frequently asked questions
else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" ||
sub_cmd == "-FAQ" || sub_cmd == "-faq")
return bedtools_faq();
// verison information
else if (sub_cmd == "-version" || sub_cmd == "--version")
cout << "bedtools " << VERSION << endl;
// verison information
else if (sub_cmd == "-contact" || sub_cmd == "--contact")
{
cout << endl;
cout << "- For further help, or to report a bug, please " << endl;
cout << " email the bedtools mailing list: " << endl;
cout << " [email protected]" << endl << endl;
cout << "- Stable releases of bedtools can be found at: " << endl;
cout << " http://bedtools.googlecode.com" << endl << endl;
cout << "- The development repository can be found at: " << endl;
cout << " https://github.com/arq5x/bedtools" << endl << endl;
}
// unknown
else {
// TODO: Implement a Levenstein-based "did you mean???"
cerr << "error: unrecognized command: " << argv[1] << endl << endl;
return 1;
}
return 0;
}
int bedtools_help(void)
{
cout << PROGRAM_NAME << ": flexible tools for genome arithmetic and DNA sequence analysis.\n";
cout << "usage: bedtools <subcommand> [options]" << endl << endl;
cout << "The bedtools sub-commands include:" << endl;
cout << endl;
cout << "[ Genome arithmetic ]" << endl;
cout << " intersect " << "Find overlapping intervals in various ways.\n";
cout << " window " << "Find overlapping intervals within a window around an interval.\n";
cout << " closest " << "Find the closest, potentially non-overlapping interval.\n";
cout << " coverage " << "Compute the coverage over defined intervals.\n";
cout << " map " << "Apply a function to a column for each overlapping interval.\n";
cout << " genomecov " << "Compute the coverage over an entire genome.\n";
cout << " merge " << "Combine overlapping/nearby intervals into a single interval.\n";
cout << " cluster " << "Cluster (but don't merge) overlapping/nearby intervals.\n";
cout << " complement " << "Extract intervals _not_ represented by an interval file.\n";
cout << " subtract " << "Remove intervals based on overlaps b/w two files.\n";
cout << " slop " << "Adjust the size of intervals.\n";
cout << " flank " << "Create new intervals from the flanks of existing intervals.\n";
cout << " sort " << "Order the intervals in a file.\n";
cout << " random " << "Generate random intervals in a genome.\n";
cout << " shuffle " << "Randomly redistrubute intervals in a genome.\n";
cout << " annotate " << "Annotate coverage of features from multiple files.\n";
cout << endl;
cout << "[ Multi-way file comparisons ]" << endl;
cout << " multiinter " << "Identifies common intervals among multiple interval files.\n";
cout << " unionbedg " << "Combines coverage intervals from multiple BEDGRAPH files.\n";
cout << endl;
cout << "[ Paired-end manipulation ]" << endl;
cout << " pairtobed " << "Find pairs that overlap intervals in various ways.\n";
cout << " pairtopair " << "Find pairs that overlap other pairs in various ways.\n";
cout << endl;
cout << "[ Format conversion ]" << endl;
cout << " bamtobed " << "Convert BAM alignments to BED (& other) formats.\n";
cout << " bedtobam " << "Convert intervals to BAM records.\n";
cout << " bamtofastq " << "Convert BAM records to FASTQ records.\n";
cout << " bedpetobam " << "Convert BEDPE intervals to BAM records.\n";
cout << " bed12tobed6 " << "Breaks BED12 intervals into discrete BED6 intervals.\n";
cout << endl;
cout << "[ Fasta manipulation ]" << endl;
cout << " getfasta " << "Use intervals to extract sequences from a FASTA file.\n";
cout << " maskfasta " << "Use intervals to mask sequences from a FASTA file.\n";
cout << " nuc " << "Profile the nucleotide content of intervals in a FASTA file.\n";
cout << endl;
cout << "[ BAM focused tools ]" << endl;
cout << " multicov " << "Counts coverage from multiple BAMs at specific intervals.\n";
cout << " tag " << "Tag BAM alignments based on overlaps with interval files.\n";
cout << endl;
cout << "[ Miscellaneous tools ]" << endl;
cout << " overlap " << "Computes the amount of overlap from two intervals.\n";
cout << " igv " << "Create an IGV snapshot batch script.\n";
cout << " links " << "Create a HTML page of links to UCSC locations.\n";
cout << " makewindows " << "Make interval \"windows\" across a genome.\n";
cout << " groupby " << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n";
cout << " expand " << "Replicate lines based on lists of values in columns.\n";
cout << endl;
cout << "[ General help ]" << endl;
cout << " --help " << "Print this help menu.\n";
//cout << " --faq " << "Frequently asked questions.\n"; TODO
cout << " --version " << "What version of bedtools are you using?.\n";
cout << " --contact " << "Feature requests, bugs, mailing lists, etc.\n";
cout << "\n";
return 0;
}
int bedtools_faq(void)
{
cout << "\n";
cout << "Q1. How do I see the help for a given command?" << endl;
cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl;
cout << " will provide the help menu if you just type the command line " << endl;
cout << " followed by enter. " << endl;
cout << "\n";
return 0;
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Asher Elmquist, Rainer Gericke
// =============================================================================
//
// Sample test program for sequential lmtv 2.5 ton simulation. It demonstrates
// chassis torsion due to random wheel excitation.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
// All units SI.
//
// =============================================================================
#define USE_IRRLICHT
#include "chrono_vehicle/ChConfigVehicle.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#ifdef USE_IRRLICHT
#include "chrono_vehicle/driver/ChIrrGuiDriver.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#endif
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_models/vehicle/mtv/LMTV.h"
#include "chrono_thirdparty/filesystem/path.h"
#include <chrono>
#include <thread>
#include <math.h>
using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::mtv;
// =============================================================================
// Initial vehicle location and orientation
ChVector<> initLoc(0, 0, 1.0);
ChQuaternion<> initRot(1, 0, 0, 0);
// Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE)
VisualizationType chassis_vis_type = VisualizationType::MESH;
VisualizationType suspension_vis_type = VisualizationType::PRIMITIVES;
VisualizationType steering_vis_type = VisualizationType::PRIMITIVES;
VisualizationType wheel_vis_type = VisualizationType::MESH;
VisualizationType tire_vis_type = VisualizationType::MESH;
// Type of tire model (RIGID, TMEASY)
TireModelType tire_model = TireModelType::TMEASY;
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.75);
ChVector<> vehCOM(-1.933, 0.014, 0.495);
// Simulation step sizes
double step_size = 1e-3;
double tire_step_size = step_size;
// Simulation end time
double tend = 60;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
double output_step_size = 1e-2;
// vehicle driver inputs
// Desired vehicle speed (m/s)
double mph_to_ms = 0.44704;
double target_speed = 5 * mph_to_ms;
// output directory
const std::string out_dir = "../LMTV_QUALITY";
const std::string pov_dir = out_dir + "/POVRAY";
bool povray_output = false;
bool data_output = true;
std::string path_file("paths/straightOrigin.txt");
std::string steering_controller_file("mtv/SteeringController.json");
std::string speed_controller_file("mtv/SpeedController.json");
std::string rnd_1("terrain/meshes/uneven_300m_6m_10mm.obj");
std::string rnd_2("terrain/meshes/uneven_300m_6m_20mm.obj");
std::string rnd_3("terrain/meshes/uneven_300m_6m_30mm.obj");
std::string rnd_4("terrain/meshes/uneven_300m_6m_40mm.obj");
std::string output_file_name("quality");
std::string terrainFile = rnd_1;
// =============================================================================
int main(int argc, char* argv[]) {
int terrainCode = 1;
// read in argument as simulation duration
switch (argc) {
default:
case 1:
target_speed = 5;
break;
case 2:
target_speed = atof(argv[1]);
break;
case 3:
target_speed = atof(argv[1]);
terrainCode = atoi(argv[2]);
break;
}
switch (terrainCode) {
case 1:
terrainFile = rnd_1;
break;
case 2:
terrainFile = rnd_2;
break;
case 3:
terrainFile = rnd_3;
break;
case 4:
terrainFile = rnd_4;
break;
default:
std::cout << "Invalid Terrain Code - (1-4)";
}
output_file_name += "_" + std::to_string((int)target_speed);
output_file_name += "_" + std::to_string((int)terrainCode);
target_speed = target_speed * mph_to_ms;
// --------------
// Create systems
// --------------
// Create the vehicle, set parameters, and initialize
LMTV lmtv;
lmtv.SetContactMethod(ChContactMethod::NSC);
lmtv.SetChassisFixed(false);
lmtv.SetInitPosition(ChCoordsys<>(initLoc, initRot));
lmtv.SetTireType(tire_model);
lmtv.SetTireStepSize(tire_step_size);
lmtv.Initialize();
lmtv.SetChassisVisualizationType(chassis_vis_type);
lmtv.SetSuspensionVisualizationType(suspension_vis_type);
lmtv.SetSteeringVisualizationType(steering_vis_type);
lmtv.SetWheelVisualizationType(wheel_vis_type);
lmtv.SetTireVisualizationType(tire_vis_type);
std::cout << "Vehicle mass: " << lmtv.GetVehicle().GetVehicleMass() << std::endl;
std::cout << "Vehicle mass (with tires): " << lmtv.GetTotalMass() << std::endl;
// ------------------
// Create the terrain
// ------------------
double swept_radius = 0.01;
auto patch_mat = chrono_types::make_shared<ChMaterialSurfaceNSC>();
patch_mat->SetFriction(0.9f);
patch_mat->SetRestitution(0.01f);
RigidTerrain terrain(lmtv.GetSystem());
auto patch = terrain.AddPatch(patch_mat, CSYSNORM, vehicle::GetDataFile(terrainFile), "test_mesh", swept_radius);
patch->SetColor(ChColor(0.8f, 0.8f, 0.5f));
patch->SetTexture(vehicle::GetDataFile("terrain/textures/dirt.jpg"), 12, 12);
terrain.Initialize();
// create the driver
auto path = ChBezierCurve::read(vehicle::GetDataFile(path_file));
ChPathFollowerDriver driver(lmtv.GetVehicle(), vehicle::GetDataFile(steering_controller_file),
vehicle::GetDataFile(speed_controller_file), path, "my_path", target_speed, false);
driver.Initialize();
// -------------------------------------
// Create the vehicle Irrlicht interface
// Create the driver system
// -------------------------------------
#ifdef USE_IRRLICHT
ChWheeledVehicleIrrApp app(&lmtv.GetVehicle(), L"LMTV ride & twist test");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(trackPoint, 6.0, 0.5);
/*app.SetTimestep(step_size);*/
app.AssetBindAll();
app.AssetUpdateAll();
// Visualization of controller points (sentinel & target)
irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);
#endif
// -------------
// Prepare output
// -------------
if (data_output || povray_output) {
if (!filesystem::create_directory(filesystem::path(out_dir))) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
}
if (povray_output) {
if (!filesystem::create_directory(filesystem::path(pov_dir))) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
driver.ExportPathPovray(out_dir);
}
utils::CSV_writer csv("\t");
csv.stream().setf(std::ios::scientific | std::ios::showpos);
csv.stream().precision(6);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
csv << "time";
csv << "throttle";
csv << "MotorSpeed";
csv << "CurrentTransmissionGear";
for (int i = 0; i < 4; i++) {
csv << "WheelTorque";
}
for (int i = 0; i < 4; i++) {
csv << "WheelAngVelX";
csv << "WheelAngVelY";
csv << "WheelAngVelZ";
}
csv << "VehicleSpeed";
csv << "VehicleDriverAccelerationX";
csv << "VehicleDriverAccelerationY";
csv << "VehicleDriverAccelerationZ";
csv << "VehicleCOMAccelerationX";
csv << "VehicleCOMAccelerationY";
csv << "VehicleCOMAccelerationZ";
for (int i = 0; i < 4; i++) {
csv << "TireForce";
}
csv << "EngineTorque";
csv << "W0 Pos x"
<< "W0 Pos Y"
<< "W0 Pos Z"
<< "W1 Pos x"
<< "W1 Pos Y"
<< "W1 Pos Z";
csv << "W2 Pos x"
<< "W2 Pos Y"
<< "W2 Pos Z"
<< "W3 Pos x"
<< "W3 Pos Y"
<< "W3 Pos Z";
for (auto& axle : lmtv.GetVehicle().GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
csv << wheel->GetPos();
}
}
csv << std::endl;
// ---------------
// Simulation loop
// ---------------
std::cout << "data at: " << vehicle::GetDataFile(steering_controller_file) << std::endl;
std::cout << "data at: " << vehicle::GetDataFile(speed_controller_file) << std::endl;
std::cout << "data at: " << vehicle::GetDataFile(path_file) << std::endl;
int step_number = 0;
int render_frame = 0;
double time = 0;
#ifdef USE_IRRLICHT
while (app.GetDevice()->run() && (time < tend)) {
#else
while (time < tend) {
#endif
time = lmtv.GetSystem()->GetChTime();
#ifdef USE_IRRLICHT
// path visualization
const ChVector<>& pS = driver.GetSteeringController().GetSentinelLocation();
const ChVector<>& pT = driver.GetSteeringController().GetTargetLocation();
ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));
// std::cout<<"Target:\t"<<(irr::f32)pT.x()<<",\t "<<(irr::f32)pT.y()<<",\t "<<(irr::f32)pT.z()<<std::endl;
// std::cout<<"Vehicle:\t"<<lmtv.GetVehicle().GetChassisBody()->GetPos().x()
// <<",\t "<<lmtv.GetVehicle().GetChassisBody()->GetPos().y()<<",\t "
// <<lmtv.GetVehicle().GetChassisBody()->GetPos().z()<<std::endl;
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
app.EndScene();
}
#endif
if (povray_output && step_number % render_steps == 0) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(lmtv.GetSystem(), filename);
render_frame++;
}
// Driver inputs
ChDriver::Inputs driver_inputs = driver.GetInputs();
// Update modules (process inputs from other modules)
driver.Synchronize(time);
terrain.Synchronize(time);
lmtv.Synchronize(time, driver_inputs, terrain);
#ifdef USE_IRRLICHT
app.Synchronize("Follower driver", driver_inputs);
#endif
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
lmtv.Advance(step_size);
#ifdef USE_IRRLICHT
app.Advance(step_size);
#endif
if (data_output && step_number % output_steps == 0) {
// std::cout << time << std::endl;
csv << time;
csv << driver_inputs.m_throttle;
csv << lmtv.GetVehicle().GetPowertrain()->GetMotorSpeed();
csv << lmtv.GetVehicle().GetPowertrain()->GetCurrentTransmissionGear();
for (int axle = 0; axle < 2; axle++) {
csv << lmtv.GetVehicle().GetDriveline()->GetSpindleTorque(axle, LEFT);
csv << lmtv.GetVehicle().GetDriveline()->GetSpindleTorque(axle, RIGHT);
}
for (int axle = 0; axle < 2; axle++) {
csv << lmtv.GetVehicle().GetSpindleAngVel(axle, LEFT);
csv << lmtv.GetVehicle().GetSpindleAngVel(axle, RIGHT);
}
csv << lmtv.GetVehicle().GetVehicleSpeed();
csv << lmtv.GetVehicle().GetVehicleAcceleration(
lmtv.GetVehicle().GetChassis()->GetLocalDriverCoordsys().pos);
csv << lmtv.GetVehicle().GetVehicleAcceleration(vehCOM);
for (auto& axle : lmtv.GetVehicle().GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
csv << wheel->GetTire()->ReportTireForce(&terrain).force;
}
}
csv << lmtv.GetVehicle().GetPowertrain()->GetMotorTorque();
csv << std::endl;
}
// Increment frame number
step_number++;
}
if (data_output) {
csv.write_to_file(out_dir + "/" + output_file_name + ".dat");
}
return 0;
}
<commit_msg>Fix output path for LMTV vehicle demo<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Asher Elmquist, Rainer Gericke
// =============================================================================
//
// Sample test program for sequential lmtv 2.5 ton simulation. It demonstrates
// chassis torsion due to random wheel excitation.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
// All units SI.
//
// =============================================================================
#define USE_IRRLICHT
#include "chrono_vehicle/ChConfigVehicle.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#ifdef USE_IRRLICHT
#include "chrono_vehicle/driver/ChIrrGuiDriver.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#endif
#include "chrono_vehicle/driver/ChPathFollowerDriver.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_models/vehicle/mtv/LMTV.h"
#include "chrono_thirdparty/filesystem/path.h"
#include <chrono>
#include <thread>
#include <math.h>
using namespace chrono;
using namespace chrono::vehicle;
using namespace chrono::vehicle::mtv;
// =============================================================================
// Initial vehicle location and orientation
ChVector<> initLoc(0, 0, 1.0);
ChQuaternion<> initRot(1, 0, 0, 0);
// Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE)
VisualizationType chassis_vis_type = VisualizationType::MESH;
VisualizationType suspension_vis_type = VisualizationType::PRIMITIVES;
VisualizationType steering_vis_type = VisualizationType::PRIMITIVES;
VisualizationType wheel_vis_type = VisualizationType::MESH;
VisualizationType tire_vis_type = VisualizationType::MESH;
// Type of tire model (RIGID, TMEASY)
TireModelType tire_model = TireModelType::TMEASY;
// Point on chassis tracked by the camera
ChVector<> trackPoint(0.0, 0.0, 1.75);
ChVector<> vehCOM(-1.933, 0.014, 0.495);
// Simulation step sizes
double step_size = 1e-3;
double tire_step_size = step_size;
// Simulation end time
double tend = 60;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
double output_step_size = 1e-2;
// vehicle driver inputs
// Desired vehicle speed (m/s)
double mph_to_ms = 0.44704;
double target_speed = 5 * mph_to_ms;
// output directory
const std::string out_dir = GetChronoOutputPath() + "LMTV_QUALITY";
const std::string pov_dir = out_dir + "/POVRAY";
bool povray_output = false;
bool data_output = true;
std::string path_file("paths/straightOrigin.txt");
std::string steering_controller_file("mtv/SteeringController.json");
std::string speed_controller_file("mtv/SpeedController.json");
std::string rnd_1("terrain/meshes/uneven_300m_6m_10mm.obj");
std::string rnd_2("terrain/meshes/uneven_300m_6m_20mm.obj");
std::string rnd_3("terrain/meshes/uneven_300m_6m_30mm.obj");
std::string rnd_4("terrain/meshes/uneven_300m_6m_40mm.obj");
std::string output_file_name("quality");
std::string terrainFile = rnd_1;
// =============================================================================
int main(int argc, char* argv[]) {
int terrainCode = 1;
// read in argument as simulation duration
switch (argc) {
default:
case 1:
target_speed = 5;
break;
case 2:
target_speed = atof(argv[1]);
break;
case 3:
target_speed = atof(argv[1]);
terrainCode = atoi(argv[2]);
break;
}
switch (terrainCode) {
case 1:
terrainFile = rnd_1;
break;
case 2:
terrainFile = rnd_2;
break;
case 3:
terrainFile = rnd_3;
break;
case 4:
terrainFile = rnd_4;
break;
default:
std::cout << "Invalid Terrain Code - (1-4)";
}
output_file_name += "_" + std::to_string((int)target_speed);
output_file_name += "_" + std::to_string((int)terrainCode);
target_speed = target_speed * mph_to_ms;
// --------------
// Create systems
// --------------
// Create the vehicle, set parameters, and initialize
LMTV lmtv;
lmtv.SetContactMethod(ChContactMethod::NSC);
lmtv.SetChassisFixed(false);
lmtv.SetInitPosition(ChCoordsys<>(initLoc, initRot));
lmtv.SetTireType(tire_model);
lmtv.SetTireStepSize(tire_step_size);
lmtv.Initialize();
lmtv.SetChassisVisualizationType(chassis_vis_type);
lmtv.SetSuspensionVisualizationType(suspension_vis_type);
lmtv.SetSteeringVisualizationType(steering_vis_type);
lmtv.SetWheelVisualizationType(wheel_vis_type);
lmtv.SetTireVisualizationType(tire_vis_type);
std::cout << "Vehicle mass: " << lmtv.GetVehicle().GetVehicleMass() << std::endl;
std::cout << "Vehicle mass (with tires): " << lmtv.GetTotalMass() << std::endl;
// ------------------
// Create the terrain
// ------------------
double swept_radius = 0.01;
auto patch_mat = chrono_types::make_shared<ChMaterialSurfaceNSC>();
patch_mat->SetFriction(0.9f);
patch_mat->SetRestitution(0.01f);
RigidTerrain terrain(lmtv.GetSystem());
auto patch = terrain.AddPatch(patch_mat, CSYSNORM, vehicle::GetDataFile(terrainFile), "test_mesh", swept_radius);
patch->SetColor(ChColor(0.8f, 0.8f, 0.5f));
patch->SetTexture(vehicle::GetDataFile("terrain/textures/dirt.jpg"), 12, 12);
terrain.Initialize();
// create the driver
auto path = ChBezierCurve::read(vehicle::GetDataFile(path_file));
ChPathFollowerDriver driver(lmtv.GetVehicle(), vehicle::GetDataFile(steering_controller_file),
vehicle::GetDataFile(speed_controller_file), path, "my_path", target_speed, false);
driver.Initialize();
// -------------------------------------
// Create the vehicle Irrlicht interface
// Create the driver system
// -------------------------------------
#ifdef USE_IRRLICHT
ChWheeledVehicleIrrApp app(&lmtv.GetVehicle(), L"LMTV ride & twist test");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(trackPoint, 6.0, 0.5);
/*app.SetTimestep(step_size);*/
app.AssetBindAll();
app.AssetUpdateAll();
// Visualization of controller points (sentinel & target)
irr::scene::IMeshSceneNode* ballS = app.GetSceneManager()->addSphereSceneNode(0.1f);
irr::scene::IMeshSceneNode* ballT = app.GetSceneManager()->addSphereSceneNode(0.1f);
ballS->getMaterial(0).EmissiveColor = irr::video::SColor(0, 255, 0, 0);
ballT->getMaterial(0).EmissiveColor = irr::video::SColor(0, 0, 255, 0);
#endif
// -------------
// Prepare output
// -------------
if (data_output || povray_output) {
if (!filesystem::create_directory(filesystem::path(out_dir))) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
}
if (povray_output) {
if (!filesystem::create_directory(filesystem::path(pov_dir))) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
driver.ExportPathPovray(out_dir);
}
utils::CSV_writer csv("\t");
csv.stream().setf(std::ios::scientific | std::ios::showpos);
csv.stream().precision(6);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
csv << "time";
csv << "throttle";
csv << "MotorSpeed";
csv << "CurrentTransmissionGear";
for (int i = 0; i < 4; i++) {
csv << "WheelTorque";
}
for (int i = 0; i < 4; i++) {
csv << "WheelAngVelX";
csv << "WheelAngVelY";
csv << "WheelAngVelZ";
}
csv << "VehicleSpeed";
csv << "VehicleDriverAccelerationX";
csv << "VehicleDriverAccelerationY";
csv << "VehicleDriverAccelerationZ";
csv << "VehicleCOMAccelerationX";
csv << "VehicleCOMAccelerationY";
csv << "VehicleCOMAccelerationZ";
for (int i = 0; i < 4; i++) {
csv << "TireForce";
}
csv << "EngineTorque";
csv << "W0 Pos x"
<< "W0 Pos Y"
<< "W0 Pos Z"
<< "W1 Pos x"
<< "W1 Pos Y"
<< "W1 Pos Z";
csv << "W2 Pos x"
<< "W2 Pos Y"
<< "W2 Pos Z"
<< "W3 Pos x"
<< "W3 Pos Y"
<< "W3 Pos Z";
for (auto& axle : lmtv.GetVehicle().GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
csv << wheel->GetPos();
}
}
csv << std::endl;
// ---------------
// Simulation loop
// ---------------
std::cout << "data at: " << vehicle::GetDataFile(steering_controller_file) << std::endl;
std::cout << "data at: " << vehicle::GetDataFile(speed_controller_file) << std::endl;
std::cout << "data at: " << vehicle::GetDataFile(path_file) << std::endl;
int step_number = 0;
int render_frame = 0;
double time = 0;
#ifdef USE_IRRLICHT
while (app.GetDevice()->run() && (time < tend)) {
#else
while (time < tend) {
#endif
time = lmtv.GetSystem()->GetChTime();
#ifdef USE_IRRLICHT
// path visualization
const ChVector<>& pS = driver.GetSteeringController().GetSentinelLocation();
const ChVector<>& pT = driver.GetSteeringController().GetTargetLocation();
ballS->setPosition(irr::core::vector3df((irr::f32)pS.x(), (irr::f32)pS.y(), (irr::f32)pS.z()));
ballT->setPosition(irr::core::vector3df((irr::f32)pT.x(), (irr::f32)pT.y(), (irr::f32)pT.z()));
// std::cout<<"Target:\t"<<(irr::f32)pT.x()<<",\t "<<(irr::f32)pT.y()<<",\t "<<(irr::f32)pT.z()<<std::endl;
// std::cout<<"Vehicle:\t"<<lmtv.GetVehicle().GetChassisBody()->GetPos().x()
// <<",\t "<<lmtv.GetVehicle().GetChassisBody()->GetPos().y()<<",\t "
// <<lmtv.GetVehicle().GetChassisBody()->GetPos().z()<<std::endl;
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
app.EndScene();
}
#endif
if (povray_output && step_number % render_steps == 0) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(lmtv.GetSystem(), filename);
render_frame++;
}
// Driver inputs
ChDriver::Inputs driver_inputs = driver.GetInputs();
// Update modules (process inputs from other modules)
driver.Synchronize(time);
terrain.Synchronize(time);
lmtv.Synchronize(time, driver_inputs, terrain);
#ifdef USE_IRRLICHT
app.Synchronize("Follower driver", driver_inputs);
#endif
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
lmtv.Advance(step_size);
#ifdef USE_IRRLICHT
app.Advance(step_size);
#endif
if (data_output && step_number % output_steps == 0) {
// std::cout << time << std::endl;
csv << time;
csv << driver_inputs.m_throttle;
csv << lmtv.GetVehicle().GetPowertrain()->GetMotorSpeed();
csv << lmtv.GetVehicle().GetPowertrain()->GetCurrentTransmissionGear();
for (int axle = 0; axle < 2; axle++) {
csv << lmtv.GetVehicle().GetDriveline()->GetSpindleTorque(axle, LEFT);
csv << lmtv.GetVehicle().GetDriveline()->GetSpindleTorque(axle, RIGHT);
}
for (int axle = 0; axle < 2; axle++) {
csv << lmtv.GetVehicle().GetSpindleAngVel(axle, LEFT);
csv << lmtv.GetVehicle().GetSpindleAngVel(axle, RIGHT);
}
csv << lmtv.GetVehicle().GetVehicleSpeed();
csv << lmtv.GetVehicle().GetVehicleAcceleration(
lmtv.GetVehicle().GetChassis()->GetLocalDriverCoordsys().pos);
csv << lmtv.GetVehicle().GetVehicleAcceleration(vehCOM);
for (auto& axle : lmtv.GetVehicle().GetAxles()) {
for (auto& wheel : axle->GetWheels()) {
csv << wheel->GetTire()->ReportTireForce(&terrain).force;
}
}
csv << lmtv.GetVehicle().GetPowertrain()->GetMotorTorque();
csv << std::endl;
}
// Increment frame number
step_number++;
}
if (data_output) {
csv.write_to_file(out_dir + "/" + output_file_name + ".dat");
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef MEMORY_ARENA_HPP
#define MEMORY_ARENA_HPP
#include <cstdint>
#include <cstdlib>
#include <utility>
#include <vector>
#include "slice.hpp"
/**
* A memory arena.
*/
template <size_t MIN_CHUNK_SIZE=4096>
class MemoryArena
{
struct Chunk {
size_t size = 0;
size_t used = 0;
char* data = nullptr;
};
std::vector<Chunk> chunks;
void add_chunk(size_t size) {
Chunk c;
c.size = size;
if (size > 0) {
c.data = new char[size];
}
chunks.push_back(c);
}
void clear_chunks() {
for (auto& c: chunks) {
if (c.data != nullptr)
delete[] c.data;
}
chunks.clear();
}
/**
* Allocates enough contiguous space for count items of type T, and
* returns a pointer to the front of that space.
*/
template <typename T>
T* _alloc(size_t count) {
// Figure out how much padding we need between elements for proper
// memory alignment if we put them in an array.
const auto array_pad = (alignof(T) - (sizeof(T) % alignof(T))) % alignof(T);
// Total needed bytes for the requested array of data
const auto needed_bytes = (sizeof(T) * count) + (array_pad * (count - 1));
// Figure out how much padding we need at the beginning to put the
// first element in the right place for memory alignment.
const auto mem_addr = (uintptr_t)(chunks.back().data + chunks.back().used);
const auto begin_pad = (alignof(T) - (mem_addr % alignof(T))) % alignof(T);
// Get the number of bytes left in the current chunk
const auto available_bytes = chunks.back().size - chunks.back().used;
// If we don't have enough space in this chunk, then we need to create
// a new chunk.
if ((begin_pad + needed_bytes) > available_bytes) {
// Calculate the minimum needed bytes to guarantee that we can
// accommodate properlyaligned data.
const auto min_needed_bytes = needed_bytes + alignof(T);
// Make sure we don't get a chunk smaller than MIN_CHUNK_SIZE
const size_t new_chunk_size = min_needed_bytes > MIN_CHUNK_SIZE ? min_needed_bytes : MIN_CHUNK_SIZE;
// Create the new chunk, and then recurse for DRY purposes.
// TODO: if we break things up differently, we could perhaps
// avoid the redundant work caused by recursing while still
// being DRY. Super low priority, though, unless this somehow
// turns out to be a performance bottleneck.
add_chunk(new_chunk_size);
return _alloc<T>(count);
}
// Otherwise, proceed in getting the pointer and recording how much
// of the chunk we used.
T* ptr = reinterpret_cast<T*>(chunks.back().data + chunks.back().used + begin_pad);
for (int i=0; i < count; ++i) {
new(ptr+i) T();
}
chunks.back().used += begin_pad + needed_bytes;
// Ta da!
return ptr;
}
public:
MemoryArena() {
// Start with a single chunk of size zero,
// to simplify the logic in _alloc()
add_chunk(0);
}
~MemoryArena() {
clear_chunks();
}
// No copying, only moving, but...
// HACK: MSVC is stupid, so we're making
// the copy-constructors behave like
// move constructors.
#ifdef _MSC_VER
MemoryArena(MemoryArena& other) {
chunks = std::move(other.chunks);
}
MemoryArena& operator=(MemoryArena& other) {
chunks = std::move(other.chunks);
return *this;
}
#else
MemoryArena(MemoryArena& other) = delete;
MemoryArena& operator=(MemoryArena& other) = delete;
#endif
MemoryArena(MemoryArena&& other) {
chunks = std::move(other.chunks);
}
MemoryArena& operator=(MemoryArena&& other) {
chunks = std::move(other.chunks);
return *this;
}
/**
* Allocates space for a single element of type T and returns a
* raw pointer to that space.
*/
template <typename T>
T* alloc() {
return _alloc<T>(1);
}
/**
* Allocates space for a single element of type T, initializes it with
* init, and returns a raw pointer to that space.
*/
template <typename T>
T* alloc(const T& init) {
auto ptr = _alloc<T>(1);
*ptr = init;
return ptr;
}
/**
* Allocates enough space for count elements of type T, and returns
* a Slice to that space.
*/
template <typename T>
Slice<T> alloc_array(size_t count) {
if (count <= 0)
return Slice<T>();
return Slice<T>(_alloc<T>(count), count);
}
/**
* Allocates space to hold the contents of the iters, and copys the
* iter's contents over. Returns a Slice to that memory.
*/
template <typename ITER, typename T=typename ITER::value_type>
Slice<T> alloc_from_iters(ITER begin, ITER end) {
const size_t size = std::distance(begin, end);
if (size <= 0)
return Slice<T>();
auto ptr = _alloc<T>(size);
for (size_t i = 0; i < size; ++i) {
ptr[i] = *begin;
++begin;
}
return Slice<T>(ptr, size);
}
};
#endif // MEMORY_ARENA_HPP<commit_msg>MSVC: Adding defines for alignof and alignas<commit_after>#ifndef MEMORY_ARENA_HPP
#define MEMORY_ARENA_HPP
#include <cstdint>
#include <cstdlib>
#include <utility>
#include <vector>
#include "slice.hpp"
#ifdef _MSC_VER
#define alignof(T) __alignof(T)
#define alignas(T) __declspec(align(T))
#endif
/**
* A memory arena.
*/
template <size_t MIN_CHUNK_SIZE=4096>
class MemoryArena
{
struct Chunk {
size_t size = 0;
size_t used = 0;
char* data = nullptr;
};
std::vector<Chunk> chunks;
void add_chunk(size_t size) {
Chunk c;
c.size = size;
if (size > 0) {
c.data = new char[size];
}
chunks.push_back(c);
}
void clear_chunks() {
for (auto& c: chunks) {
if (c.data != nullptr)
delete[] c.data;
}
chunks.clear();
}
/**
* Allocates enough contiguous space for count items of type T, and
* returns a pointer to the front of that space.
*/
template <typename T>
T* _alloc(size_t count) {
// Figure out how much padding we need between elements for proper
// memory alignment if we put them in an array.
const auto array_pad = (alignof(T) - (sizeof(T) % alignof(T))) % alignof(T);
// Total needed bytes for the requested array of data
const auto needed_bytes = (sizeof(T) * count) + (array_pad * (count - 1));
// Figure out how much padding we need at the beginning to put the
// first element in the right place for memory alignment.
const auto mem_addr = (uintptr_t)(chunks.back().data + chunks.back().used);
const auto begin_pad = (alignof(T) - (mem_addr % alignof(T))) % alignof(T);
// Get the number of bytes left in the current chunk
const auto available_bytes = chunks.back().size - chunks.back().used;
// If we don't have enough space in this chunk, then we need to create
// a new chunk.
if ((begin_pad + needed_bytes) > available_bytes) {
// Calculate the minimum needed bytes to guarantee that we can
// accommodate properlyaligned data.
const auto min_needed_bytes = needed_bytes + alignof(T);
// Make sure we don't get a chunk smaller than MIN_CHUNK_SIZE
const size_t new_chunk_size = min_needed_bytes > MIN_CHUNK_SIZE ? min_needed_bytes : MIN_CHUNK_SIZE;
// Create the new chunk, and then recurse for DRY purposes.
// TODO: if we break things up differently, we could perhaps
// avoid the redundant work caused by recursing while still
// being DRY. Super low priority, though, unless this somehow
// turns out to be a performance bottleneck.
add_chunk(new_chunk_size);
return _alloc<T>(count);
}
// Otherwise, proceed in getting the pointer and recording how much
// of the chunk we used.
T* ptr = reinterpret_cast<T*>(chunks.back().data + chunks.back().used + begin_pad);
for (int i=0; i < count; ++i) {
new(ptr+i) T();
}
chunks.back().used += begin_pad + needed_bytes;
// Ta da!
return ptr;
}
public:
MemoryArena() {
// Start with a single chunk of size zero,
// to simplify the logic in _alloc()
add_chunk(0);
}
~MemoryArena() {
clear_chunks();
}
// No copying, only moving, but...
// HACK: MSVC is stupid, so we're making
// the copy-constructors behave like
// move constructors.
#ifdef _MSC_VER
MemoryArena(MemoryArena& other) {
chunks = std::move(other.chunks);
}
MemoryArena& operator=(MemoryArena& other) {
chunks = std::move(other.chunks);
return *this;
}
#else
MemoryArena(MemoryArena& other) = delete;
MemoryArena& operator=(MemoryArena& other) = delete;
#endif
MemoryArena(MemoryArena&& other) {
chunks = std::move(other.chunks);
}
MemoryArena& operator=(MemoryArena&& other) {
chunks = std::move(other.chunks);
return *this;
}
/**
* Allocates space for a single element of type T and returns a
* raw pointer to that space.
*/
template <typename T>
T* alloc() {
return _alloc<T>(1);
}
/**
* Allocates space for a single element of type T, initializes it with
* init, and returns a raw pointer to that space.
*/
template <typename T>
T* alloc(const T& init) {
auto ptr = _alloc<T>(1);
*ptr = init;
return ptr;
}
/**
* Allocates enough space for count elements of type T, and returns
* a Slice to that space.
*/
template <typename T>
Slice<T> alloc_array(size_t count) {
if (count <= 0)
return Slice<T>();
return Slice<T>(_alloc<T>(count), count);
}
/**
* Allocates space to hold the contents of the iters, and copys the
* iter's contents over. Returns a Slice to that memory.
*/
template <typename ITER, typename T=typename ITER::value_type>
Slice<T> alloc_from_iters(ITER begin, ITER end) {
const size_t size = std::distance(begin, end);
if (size <= 0)
return Slice<T>();
auto ptr = _alloc<T>(size);
for (size_t i = 0; i < size; ++i) {
ptr[i] = *begin;
++begin;
}
return Slice<T>(ptr, size);
}
};
#endif // MEMORY_ARENA_HPP<|endoftext|> |
<commit_before>#ifndef STRAGGLER_EVENT_HPP
#define STRAGGLER_EVENT_HPP
namespace warped {
// This is a Straggler event class
class StragglerEvent : public Event {
public:
StragglerEvent() = default;
StragglerEvent( const std::string& receiver_name,
const std::string& sender_name,
unsigned int timestamp )
: receiver_name_(receiver_name),
sender_name_(sender_name),
timestamp_(timestamp)
{}
const std::string& receiverName() const { return receiver_name_; }
const std::string& senderName() const { return sender_name_; }
unsigned int timestamp() const { return timestamp_; }
std::string receiver_name_;
std::string sender_name_;
unsigned int timestamp_;
const std::vector<const std::unique_ptr<Event>> events_to_cancel_;
};
} // namespace warped
#endif
<commit_msg>removed unused StragglerEvent file<commit_after><|endoftext|> |
<commit_before>#include "Riostream.h"
#include "Coefficient.h"
#include "RooAbsReal.h"
#include <math.h>
#include "TMath.h"
ClassImp(doofit::roofit::functions::bdecay::Coefficient)
namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {
Coefficient::Coefficient(const std::string& name,
RooAbsReal& _cp_coeff_,
CoeffType _coeff_type_,
RooAbsReal& _tag_,
RooAbsReal& _mistag_b_,
RooAbsReal& _mistag_bbar_,
RooAbsReal& _production_asym_
) :
RooAbsReal(name.c_str(),name.c_str()),
cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
coeff_type_(_coeff_type_),
tag_("tag_","tag_",this,_tag_),
mistag_b_("mistag_b_","mistag_b_",this,_mistag_b_),
mistag_bbar_("mistag_bbar_","mistag_bbar_",this,_mistag_bbar_),
production_asym_("production_asym_","production_asym_",this,_production_asym_)
{
}
Coefficient::Coefficient(const Coefficient& other, const char* name) :
RooAbsReal(other,name),
cp_coeff_("cp_coeff_",this,other.cp_coeff_),
coeff_type_(other.coeff_type_),
tag_("tag_",this,other.tag_),
mistag_b_("mistag_b_",this,other.mistag_b_),
mistag_bbar_("mistag_bbar_",this,other.mistag_bbar_),
production_asym_("production_asym_",this,other.production_asym_)
{
}
inline Double_t Coefficient::evaluate() const
{
if (coeff_type_ == kSin){
return -1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kCos){
return +1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kSinh){
// TODO: Implement Sinh coefficient if necessary!
return cp_coeff_;
}
else if (coeff_type_ == kCosh){
return cp_coeff_ * ( 1.0 + tag_ * production_asym_ * ( 1.0 - mistag_b_ - mistag_bbar_ ) + tag_ * ( mistag_b_ - mistag_bbar_ ) );
}
else{
std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
abort();
}
}
Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars/**, const char* rangeName**/) const{
// WARNING: works only if untagged events hold a tag state of ±1
// return 1: integration over one tag state
// return 2: integration over two tag states
// Now we have to handle the different possibilities:
// 1.) a uncalibrated + uncombined tag is used (single RooRealVar)
// 2.) a calibrated + uncombined tag ist used (single RooAbsReal)
// 3.) a calibrated + combined tag is used (two RooAbsReals)
// since we cannot access the observables, we have to trust that only
// two possible integrals are requested, namely the integral over
// a single tag state or the integral over two tag states.
// For all other cases this implementation fails.
if (allVars.getSize() == 0){
std::printf("ERROR: In %s line %u (%s): allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
else if (allVars.getSize() == 1){
// case 1. and 2.: only one tag
return 1;
}
else if (allVars.getSize() == 2){
// case 3.: integration over two tag states
return 2;
}
else{
std::printf("ERROR: In %s line %u (%s): allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
}
Double_t Coefficient::analyticalIntegral(Int_t code/**, const char* rangeName**/) const{
if (code != 1 || code != 2){
std::printf("ERROR: In %s line %u (%s)", __func__, __LINE__, __FILE__);
return 0;
abort();
}
if (coeff_type_ == kSin){
return +2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kCos){
return -2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kSinh){
return 2.0 * cp_coeff_ * code;
}
else if (coeff_type_ == kCosh){
return 2.0 * cp_coeff_ * code;
}
else{
std::printf("ERROR: In %s line %u (%s)", __func__, __LINE__, __FILE__);
return 0;
abort();
}
}
} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<commit_msg>doofit::roofit::functions::pdfs::bdecay::Coefficient: corrected wrong sign in osh coefficient<commit_after>#include "Riostream.h"
#include "Coefficient.h"
#include "RooAbsReal.h"
#include <math.h>
#include "TMath.h"
ClassImp(doofit::roofit::functions::bdecay::Coefficient)
namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {
Coefficient::Coefficient(const std::string& name,
RooAbsReal& _cp_coeff_,
CoeffType _coeff_type_,
RooAbsReal& _tag_,
RooAbsReal& _mistag_b_,
RooAbsReal& _mistag_bbar_,
RooAbsReal& _production_asym_
) :
RooAbsReal(name.c_str(),name.c_str()),
cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
coeff_type_(_coeff_type_),
tag_("tag_","tag_",this,_tag_),
mistag_b_("mistag_b_","mistag_b_",this,_mistag_b_),
mistag_bbar_("mistag_bbar_","mistag_bbar_",this,_mistag_bbar_),
production_asym_("production_asym_","production_asym_",this,_production_asym_)
{
}
Coefficient::Coefficient(const Coefficient& other, const char* name) :
RooAbsReal(other,name),
cp_coeff_("cp_coeff_",this,other.cp_coeff_),
coeff_type_(other.coeff_type_),
tag_("tag_",this,other.tag_),
mistag_b_("mistag_b_",this,other.mistag_b_),
mistag_bbar_("mistag_bbar_",this,other.mistag_bbar_),
production_asym_("production_asym_",this,other.production_asym_)
{
}
inline Double_t Coefficient::evaluate() const
{
if (coeff_type_ == kSin){
return -1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kCos){
return +1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kSinh){
// TODO: Implement Sinh coefficient
return cp_coeff_;
}
else if (coeff_type_ == kCosh){
return cp_coeff_ * ( 1.0 - tag_ * production_asym_ * ( 1.0 - mistag_b_ - mistag_bbar_ ) - tag_ * ( mistag_b_ - mistag_bbar_ ) );
}
else{
std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
abort();
}
}
Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars/**, const char* rangeName**/) const{
// WARNING: works only if untagged events hold a tag state of ±1
// return 1: integration over one tag state
// return 2: integration over two tag states
// Now we have to handle the different possibilities:
// 1.) a uncalibrated + uncombined tag is used (single RooRealVar)
// 2.) a calibrated + uncombined tag ist used (single RooAbsReal)
// 3.) a calibrated + combined tag is used (two RooAbsReals)
// since we cannot access the observables, we have to trust that only
// two possible integrals are requested, namely the integral over
// a single tag state or the integral over two tag states.
// For all other cases this implementation fails.
if (allVars.getSize() == 0){
std::printf("ERROR: In %s line %u (%s): allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
else if (allVars.getSize() == 1){
// case 1. and 2.: only one tag
return 1;
}
else if (allVars.getSize() == 2){
// case 3.: integration over two tag states
return 2;
}
else{
std::printf("ERROR: In %s line %u (%s): allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
}
Double_t Coefficient::analyticalIntegral(Int_t code/**, const char* rangeName**/) const{
if (code != 1 || code != 2){
std::printf("ERROR: In %s line %u (%s)", __func__, __LINE__, __FILE__);
return 0;
abort();
}
if (coeff_type_ == kSin){
return +2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kCos){
return -2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kSinh){
return 2.0 * cp_coeff_ * code;
}
else if (coeff_type_ == kCosh){
return 2.0 * cp_coeff_ * code;
}
else{
std::printf("ERROR: In %s line %u (%s)", __func__, __LINE__, __FILE__);
return 0;
abort();
}
}
} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: macropg.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2005-01-21 14:55:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _MACROPG_HXX
#define _MACROPG_HXX
#include <sfx2/basedlgs.hxx>
#include <sfx2/tabdlg.hxx>
#include <com/sun/star/container/XNameReplace.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/uno/Reference.hxx>
#ifndef _SFXMACITEM_HXX //autogen
#include <svtools/macitem.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#include <rtl/ustring.hxx>
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#include <hash_map>
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString, ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > EventsHash;
typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > UIEventsStringHash;
class _SvxMacroTabPage;
class SvStringsDtor;
class SvTabListBox;
class Edit;
class String;
class _HeaderTabListBox;
class _SvxMacroTabPage_Impl;
class _SvxMacroTabPage : public SfxTabPage
{
#if _SOLAR__PRIVATE
DECL_STATIC_LINK( _SvxMacroTabPage, SelectEvent_Impl, SvTabListBox * );
DECL_STATIC_LINK( _SvxMacroTabPage, AssignDeleteHdl_Impl, PushButton * );
#endif
protected:
_SvxMacroTabPage_Impl* mpImpl;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xAppEvents;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xDocEvents;
::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > m_xModifiable;
EventsHash m_appEventsHash;
EventsHash m_docEventsHash;
bool bReadOnly, bDocModified, bAppEvents, bInitialized;
UIEventsStringHash aUIStrings;
_SvxMacroTabPage( Window* pParent, const ResId& rId, const SfxItemSet& rItemSet );
void EnableButtons( const String& rLanguage );
::com::sun::star::uno::Any GetPropsByName( const ::rtl::OUString& eventName, const EventsHash& eventsHash );
::std::pair< ::rtl::OUString, ::rtl::OUString > GetPairFromAny( ::com::sun::star::uno::Any aAny );
public:
virtual ~_SvxMacroTabPage();
void InitResources();
void InitAndSetHandler( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xAppEvents, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xDocEvents, ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > xModifiable );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset();
void DisplayAppEvents( bool appEvents);
void SetReadOnly( BOOL bSet );
BOOL IsReadOnly() const;
};
class SvxMacroTabPage : public _SvxMacroTabPage
{
public:
SvxMacroTabPage( Window* pParent, const ResId& rId,
const SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
virtual ~SvxMacroTabPage();
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
};
class SVX_DLLPUBLIC SvxMacroAssignDlg : public SfxSingleTabDialog
{
public:
SvxMacroAssignDlg( Window* pParent, SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
virtual ~SvxMacroAssignDlg();
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.430); FILE MERGED 2005/09/05 14:15:46 rt 1.5.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macropg.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:02:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _MACROPG_HXX
#define _MACROPG_HXX
#include <sfx2/basedlgs.hxx>
#include <sfx2/tabdlg.hxx>
#include <com/sun/star/container/XNameReplace.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/uno/Reference.hxx>
#ifndef _SFXMACITEM_HXX //autogen
#include <svtools/macitem.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#include <rtl/ustring.hxx>
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#include <hash_map>
typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString, ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > EventsHash;
typedef ::std::hash_map< ::rtl::OUString, ::rtl::OUString, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > UIEventsStringHash;
class _SvxMacroTabPage;
class SvStringsDtor;
class SvTabListBox;
class Edit;
class String;
class _HeaderTabListBox;
class _SvxMacroTabPage_Impl;
class _SvxMacroTabPage : public SfxTabPage
{
#if _SOLAR__PRIVATE
DECL_STATIC_LINK( _SvxMacroTabPage, SelectEvent_Impl, SvTabListBox * );
DECL_STATIC_LINK( _SvxMacroTabPage, AssignDeleteHdl_Impl, PushButton * );
#endif
protected:
_SvxMacroTabPage_Impl* mpImpl;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xAppEvents;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > m_xDocEvents;
::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > m_xModifiable;
EventsHash m_appEventsHash;
EventsHash m_docEventsHash;
bool bReadOnly, bDocModified, bAppEvents, bInitialized;
UIEventsStringHash aUIStrings;
_SvxMacroTabPage( Window* pParent, const ResId& rId, const SfxItemSet& rItemSet );
void EnableButtons( const String& rLanguage );
::com::sun::star::uno::Any GetPropsByName( const ::rtl::OUString& eventName, const EventsHash& eventsHash );
::std::pair< ::rtl::OUString, ::rtl::OUString > GetPairFromAny( ::com::sun::star::uno::Any aAny );
public:
virtual ~_SvxMacroTabPage();
void InitResources();
void InitAndSetHandler( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xAppEvents, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xDocEvents, ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifiable > xModifiable );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset();
void DisplayAppEvents( bool appEvents);
void SetReadOnly( BOOL bSet );
BOOL IsReadOnly() const;
};
class SvxMacroTabPage : public _SvxMacroTabPage
{
public:
SvxMacroTabPage( Window* pParent, const ResId& rId,
const SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
virtual ~SvxMacroTabPage();
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
};
class SVX_DLLPUBLIC SvxMacroAssignDlg : public SfxSingleTabDialog
{
public:
SvxMacroAssignDlg( Window* pParent, SfxItemSet& rSet, ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > xNameReplace, sal_uInt16 nSelectedIndex=0 );
virtual ~SvxMacroAssignDlg();
};
#endif
<|endoftext|> |
<commit_before>#include "dg/llvm/analysis/PointsTo/PointerSubgraph.h"
#include "llvm/llvm-utils.h"
namespace dg {
namespace analysis {
namespace pta {
PSNode *LLVMPointerSubgraphBuilder::createAlloc(const llvm::Instruction *Inst)
{
PSNodeAlloc *node = PSNodeAlloc::get(PS.create(PSNodeType::ALLOC));
addNode(Inst, node);
const llvm::AllocaInst *AI = llvm::dyn_cast<llvm::AllocaInst>(Inst);
if (AI)
node->setSize(getAllocatedSize(AI, DL));
return node;
}
PSNode * LLVMPointerSubgraphBuilder::createLifetimeEnd(const llvm::Instruction *Inst)
{
PSNode *op1 = getOperand(Inst->getOperand(1));
PSNode *node = PS.create(PSNodeType::INVALIDATE_OBJECT, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createStore(const llvm::Instruction *Inst)
{
const llvm::Value *valOp = Inst->getOperand(0);
PSNode *op1 = getOperand(valOp);
PSNode *op2 = getOperand(Inst->getOperand(1));
PSNode *node = PS.create(PSNodeType::STORE, op1, op2);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createLoad(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::LOAD, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createGEP(const llvm::Instruction *Inst)
{
using namespace llvm;
const GetElementPtrInst *GEP = cast<GetElementPtrInst>(Inst);
const Value *ptrOp = GEP->getPointerOperand();
unsigned bitwidth = getPointerBitwidth(DL, ptrOp);
APInt offset(bitwidth, 0);
PSNode *node = nullptr;
PSNode *op = getOperand(ptrOp);
if (*_options.fieldSensitivity > 0
&& GEP->accumulateConstantOffset(*DL, offset)) {
// is offset in given bitwidth?
if (offset.isIntN(bitwidth)) {
// is 0 < offset < field_sensitivity ?
uint64_t off = offset.getLimitedValue(*_options.fieldSensitivity);
if (off == 0 || off < *_options.fieldSensitivity)
node = PS.create(PSNodeType::GEP, op, offset.getZExtValue());
} else
errs() << "WARN: GEP offset greater than " << bitwidth << "-bit";
// fall-through to Offset::UNKNOWN in this case
}
// we didn't create the node with concrete offset,
// in which case we are supposed to create a node
// with Offset::UNKNOWN
if (!node)
node = PS.create(PSNodeType::GEP, op, Offset::UNKNOWN);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createSelect(const llvm::Instruction *Inst)
{
// with ptrtoint/inttoptr it may not be a pointer
// assert(Inst->getType()->isPointerTy() && "BUG: This select is not a pointer");
// select <cond> <op1> <op2>
PSNode *op1 = getOperand(Inst->getOperand(1));
PSNode *op2 = getOperand(Inst->getOperand(2));
// select works as a PHI in points-to analysis
PSNode *node = PS.create(PSNodeType::PHI, op1, op2, nullptr);
addNode(Inst, node);
assert(node);
return node;
}
Offset accumulateEVOffsets(const llvm::ExtractValueInst *EV,
const llvm::DataLayout& DL) {
Offset off{0};
llvm::CompositeType *type
= llvm::dyn_cast<llvm::CompositeType>(EV->getAggregateOperand()->getType());
assert(type && "Don't have composite type in extractvalue");
for (unsigned idx : EV->indices()) {
assert(type->indexValid(idx) && "Invalid index");
if (llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(type)) {
const llvm::StructLayout *SL = DL.getStructLayout(STy);
off += SL->getElementOffset(idx);
} else {
// array or vector, so just move in the array
auto seqTy = llvm::cast<llvm::SequentialType>(type);
off += idx + DL.getTypeAllocSize(seqTy->getElementType());
}
type = llvm::dyn_cast<llvm::CompositeType>(type->getTypeAtIndex(idx));
if (!type)
break; // we're done
}
return off;
}
PSNodesSeq
LLVMPointerSubgraphBuilder::createExtract(const llvm::Instruction *Inst)
{
using namespace llvm;
const ExtractValueInst *EI = cast<ExtractValueInst>(Inst);
// extract <agg> <idx> {<idx>, ...}
PSNode *op1 = getOperand(EI->getAggregateOperand());
PSNode *G = PS.create(PSNodeType::GEP, op1, accumulateEVOffsets(EI, *DL));
PSNode *L = PS.create(PSNodeType::LOAD, G);
G->addSuccessor(L);
PSNodesSeq ret = PSNodesSeq(G, L);
addNode(Inst, ret);
return ret;
}
PSNode *LLVMPointerSubgraphBuilder::createPHI(const llvm::Instruction *Inst)
{
PSNode *node = PS.create(PSNodeType::PHI, nullptr);
addNode(Inst, node);
// NOTE: we didn't add operands to PHI node here, but after building
// the whole function, because some blocks may not have been built
// when we were creating the phi node
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createCast(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::CAST, op1);
addNode(Inst, node);
assert(node);
return node;
}
// ptrToInt work just as a bitcast
PSNode *LLVMPointerSubgraphBuilder::createPtrToInt(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
// NOTE: we don't support arithmetic operations, so instead of
// just casting the value do gep with unknown offset -
// this way we cover any shift of the pointer due to arithmetic
// operations
// PSNode *node = PS.create(PSNodeType::CAST, op1);
PSNode *node = PS.create(PSNodeType::GEP, op1, 0);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createIntToPtr(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1;
if (llvm::isa<llvm::Constant>(op)) {
llvm::errs() << "PTA warning: IntToPtr with constant: "
<< *Inst << "\n";
// if this is inttoptr with constant, just make the pointer
// unknown
op1 = UNKNOWN_MEMORY;
} else
op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::CAST, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createAdd(const llvm::Instruction *Inst)
{
using namespace llvm;
PSNode *node;
PSNode *op;
const Value *val = nullptr;
uint64_t off = Offset::UNKNOWN;
if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(1));
val = Inst->getOperand(0);
} else if (isa<ConstantInt>(Inst->getOperand(1))) {
op = getOperand(Inst->getOperand(0));
val = Inst->getOperand(1);
} else {
// the operands are both non-constant. Check if we
// can get an operand as one of them and if not,
// fall-back to unknown memory, because we
// would need to track down both operads...
op = tryGetOperand(Inst->getOperand(0));
if (!op)
op = tryGetOperand(Inst->getOperand(1));
if (!op)
return createUnknown(Inst);
}
assert(op && "Don't have operand for add");
if (val)
off = getConstantValue(val);
node = PS.create(PSNodeType::GEP, op, off);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createArithmetic(const llvm::Instruction *Inst)
{
using namespace llvm;
PSNode *node;
PSNode *op;
// we don't know if the operand is the first or
// the other operand
if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(1));
} else if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(0));
} else {
// the operands are both non-constant. Check if we
// can get an operand as one of them and if not,
// fall-back to unknown memory, because we
// would need to track down both operads...
op = tryGetOperand(Inst->getOperand(0));
if (!op)
op = tryGetOperand(Inst->getOperand(1));
if (!op)
return createUnknown(Inst);
}
// we don't know what the operation does,
// so set unknown offset
node = PS.create(PSNodeType::GEP, op, Offset::UNKNOWN);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createReturn(const llvm::Instruction *Inst)
{
PSNode *op1 = nullptr;
// is nullptr if this is 'ret void'
llvm::Value *retVal = llvm::cast<llvm::ReturnInst>(Inst)->getReturnValue();
// we create even void and non-pointer return nodes,
// since these modify CFG (they won't bear any
// points-to information though)
// XXX is that needed?
// DONT: if(retVal->getType()->isPointerTy())
// we have ptrtoint which break the types...
if (retVal) {
// A struct is being returned. In this case,
// return the address of the local variable
// that holds the return value, so that
// we can then do a load on this object
if (retVal->getType()->isAggregateType()) {
if (llvm::LoadInst *LI = llvm::dyn_cast<llvm::LoadInst>(retVal)) {
op1 = getOperand(LI->getPointerOperand());
}
if (!op1) {
llvm::errs() << "WARN: Unsupported return of an aggregate type\n";
llvm::errs() << *Inst << "\n";
op1 = UNKNOWN_MEMORY;
}
}
if (llvm::isa<llvm::ConstantPointerNull>(retVal)
|| isConstantZero(retVal))
op1 = NULLPTR;
else if (typeCanBePointer(DL, retVal->getType()) &&
(!isInvalid(retVal->stripPointerCasts(), invalidate_nodes) ||
llvm::isa<llvm::ConstantExpr>(retVal) ||
llvm::isa<llvm::UndefValue>(retVal)))
op1 = getOperand(retVal);
}
assert((op1 || !retVal || !retVal->getType()->isPointerTy())
&& "Don't have an operand for ReturnInst with pointer");
PSNode *node = PS.create(PSNodeType::RETURN, op1, nullptr);
addNode(Inst, node);
return node;
}
} // namespace pta
} // namespace analysis
} // namespace dg
<commit_msg>PTA: fix compatibility with LLVM < 3.7<commit_after>#include "dg/llvm/analysis/PointsTo/PointerSubgraph.h"
#include "llvm/llvm-utils.h"
namespace dg {
namespace analysis {
namespace pta {
PSNode *LLVMPointerSubgraphBuilder::createAlloc(const llvm::Instruction *Inst)
{
PSNodeAlloc *node = PSNodeAlloc::get(PS.create(PSNodeType::ALLOC));
addNode(Inst, node);
const llvm::AllocaInst *AI = llvm::dyn_cast<llvm::AllocaInst>(Inst);
if (AI)
node->setSize(getAllocatedSize(AI, DL));
return node;
}
PSNode * LLVMPointerSubgraphBuilder::createLifetimeEnd(const llvm::Instruction *Inst)
{
PSNode *op1 = getOperand(Inst->getOperand(1));
PSNode *node = PS.create(PSNodeType::INVALIDATE_OBJECT, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createStore(const llvm::Instruction *Inst)
{
const llvm::Value *valOp = Inst->getOperand(0);
PSNode *op1 = getOperand(valOp);
PSNode *op2 = getOperand(Inst->getOperand(1));
PSNode *node = PS.create(PSNodeType::STORE, op1, op2);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createLoad(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::LOAD, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createGEP(const llvm::Instruction *Inst)
{
using namespace llvm;
const GetElementPtrInst *GEP = cast<GetElementPtrInst>(Inst);
const Value *ptrOp = GEP->getPointerOperand();
unsigned bitwidth = getPointerBitwidth(DL, ptrOp);
APInt offset(bitwidth, 0);
PSNode *node = nullptr;
PSNode *op = getOperand(ptrOp);
if (*_options.fieldSensitivity > 0
&& GEP->accumulateConstantOffset(*DL, offset)) {
// is offset in given bitwidth?
if (offset.isIntN(bitwidth)) {
// is 0 < offset < field_sensitivity ?
uint64_t off = offset.getLimitedValue(*_options.fieldSensitivity);
if (off == 0 || off < *_options.fieldSensitivity)
node = PS.create(PSNodeType::GEP, op, offset.getZExtValue());
} else
errs() << "WARN: GEP offset greater than " << bitwidth << "-bit";
// fall-through to Offset::UNKNOWN in this case
}
// we didn't create the node with concrete offset,
// in which case we are supposed to create a node
// with Offset::UNKNOWN
if (!node)
node = PS.create(PSNodeType::GEP, op, Offset::UNKNOWN);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createSelect(const llvm::Instruction *Inst)
{
// with ptrtoint/inttoptr it may not be a pointer
// assert(Inst->getType()->isPointerTy() && "BUG: This select is not a pointer");
// select <cond> <op1> <op2>
PSNode *op1 = getOperand(Inst->getOperand(1));
PSNode *op2 = getOperand(Inst->getOperand(2));
// select works as a PHI in points-to analysis
PSNode *node = PS.create(PSNodeType::PHI, op1, op2, nullptr);
addNode(Inst, node);
assert(node);
return node;
}
Offset accumulateEVOffsets(const llvm::ExtractValueInst *EV,
const llvm::DataLayout& DL) {
Offset off{0};
llvm::CompositeType *type
= llvm::dyn_cast<llvm::CompositeType>(EV->getAggregateOperand()->getType());
assert(type && "Don't have composite type in extractvalue");
for (unsigned idx : EV->getIndices()) {
assert(type->indexValid(idx) && "Invalid index");
if (llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(type)) {
const llvm::StructLayout *SL = DL.getStructLayout(STy);
off += SL->getElementOffset(idx);
} else {
// array or vector, so just move in the array
auto seqTy = llvm::cast<llvm::SequentialType>(type);
off += idx + DL.getTypeAllocSize(seqTy->getElementType());
}
type = llvm::dyn_cast<llvm::CompositeType>(type->getTypeAtIndex(idx));
if (!type)
break; // we're done
}
return off;
}
PSNodesSeq
LLVMPointerSubgraphBuilder::createExtract(const llvm::Instruction *Inst)
{
using namespace llvm;
const ExtractValueInst *EI = cast<ExtractValueInst>(Inst);
// extract <agg> <idx> {<idx>, ...}
PSNode *op1 = getOperand(EI->getAggregateOperand());
PSNode *G = PS.create(PSNodeType::GEP, op1, accumulateEVOffsets(EI, *DL));
PSNode *L = PS.create(PSNodeType::LOAD, G);
G->addSuccessor(L);
PSNodesSeq ret = PSNodesSeq(G, L);
addNode(Inst, ret);
return ret;
}
PSNode *LLVMPointerSubgraphBuilder::createPHI(const llvm::Instruction *Inst)
{
PSNode *node = PS.create(PSNodeType::PHI, nullptr);
addNode(Inst, node);
// NOTE: we didn't add operands to PHI node here, but after building
// the whole function, because some blocks may not have been built
// when we were creating the phi node
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createCast(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::CAST, op1);
addNode(Inst, node);
assert(node);
return node;
}
// ptrToInt work just as a bitcast
PSNode *LLVMPointerSubgraphBuilder::createPtrToInt(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1 = getOperand(op);
// NOTE: we don't support arithmetic operations, so instead of
// just casting the value do gep with unknown offset -
// this way we cover any shift of the pointer due to arithmetic
// operations
// PSNode *node = PS.create(PSNodeType::CAST, op1);
PSNode *node = PS.create(PSNodeType::GEP, op1, 0);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createIntToPtr(const llvm::Instruction *Inst)
{
const llvm::Value *op = Inst->getOperand(0);
PSNode *op1;
if (llvm::isa<llvm::Constant>(op)) {
llvm::errs() << "PTA warning: IntToPtr with constant: "
<< *Inst << "\n";
// if this is inttoptr with constant, just make the pointer
// unknown
op1 = UNKNOWN_MEMORY;
} else
op1 = getOperand(op);
PSNode *node = PS.create(PSNodeType::CAST, op1);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createAdd(const llvm::Instruction *Inst)
{
using namespace llvm;
PSNode *node;
PSNode *op;
const Value *val = nullptr;
uint64_t off = Offset::UNKNOWN;
if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(1));
val = Inst->getOperand(0);
} else if (isa<ConstantInt>(Inst->getOperand(1))) {
op = getOperand(Inst->getOperand(0));
val = Inst->getOperand(1);
} else {
// the operands are both non-constant. Check if we
// can get an operand as one of them and if not,
// fall-back to unknown memory, because we
// would need to track down both operads...
op = tryGetOperand(Inst->getOperand(0));
if (!op)
op = tryGetOperand(Inst->getOperand(1));
if (!op)
return createUnknown(Inst);
}
assert(op && "Don't have operand for add");
if (val)
off = getConstantValue(val);
node = PS.create(PSNodeType::GEP, op, off);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createArithmetic(const llvm::Instruction *Inst)
{
using namespace llvm;
PSNode *node;
PSNode *op;
// we don't know if the operand is the first or
// the other operand
if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(1));
} else if (isa<ConstantInt>(Inst->getOperand(0))) {
op = getOperand(Inst->getOperand(0));
} else {
// the operands are both non-constant. Check if we
// can get an operand as one of them and if not,
// fall-back to unknown memory, because we
// would need to track down both operads...
op = tryGetOperand(Inst->getOperand(0));
if (!op)
op = tryGetOperand(Inst->getOperand(1));
if (!op)
return createUnknown(Inst);
}
// we don't know what the operation does,
// so set unknown offset
node = PS.create(PSNodeType::GEP, op, Offset::UNKNOWN);
addNode(Inst, node);
assert(node);
return node;
}
PSNode *LLVMPointerSubgraphBuilder::createReturn(const llvm::Instruction *Inst)
{
PSNode *op1 = nullptr;
// is nullptr if this is 'ret void'
llvm::Value *retVal = llvm::cast<llvm::ReturnInst>(Inst)->getReturnValue();
// we create even void and non-pointer return nodes,
// since these modify CFG (they won't bear any
// points-to information though)
// XXX is that needed?
// DONT: if(retVal->getType()->isPointerTy())
// we have ptrtoint which break the types...
if (retVal) {
// A struct is being returned. In this case,
// return the address of the local variable
// that holds the return value, so that
// we can then do a load on this object
if (retVal->getType()->isAggregateType()) {
if (llvm::LoadInst *LI = llvm::dyn_cast<llvm::LoadInst>(retVal)) {
op1 = getOperand(LI->getPointerOperand());
}
if (!op1) {
llvm::errs() << "WARN: Unsupported return of an aggregate type\n";
llvm::errs() << *Inst << "\n";
op1 = UNKNOWN_MEMORY;
}
}
if (llvm::isa<llvm::ConstantPointerNull>(retVal)
|| isConstantZero(retVal))
op1 = NULLPTR;
else if (typeCanBePointer(DL, retVal->getType()) &&
(!isInvalid(retVal->stripPointerCasts(), invalidate_nodes) ||
llvm::isa<llvm::ConstantExpr>(retVal) ||
llvm::isa<llvm::UndefValue>(retVal)))
op1 = getOperand(retVal);
}
assert((op1 || !retVal || !retVal->getType()->isPointerTy())
&& "Don't have an operand for ReturnInst with pointer");
PSNode *node = PS.create(PSNodeType::RETURN, op1, nullptr);
addNode(Inst, node);
return node;
}
} // namespace pta
} // namespace analysis
} // namespace dg
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date( time_t date )
{
static char buf[ 12 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date_year( time_t date )
{
static char buf[ 15 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%02d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a time value which is encoded as seconds since the UNIX
"epoch". We return a string in the format dd+hh:mm:ss, indicating
days, hours, minutes, and seconds. The string is in static data
space, and will be overwritten by the next call to this function.
*/
char *
format_time( int tot_secs )
{
int days;
int hours;
int min;
int secs;
static char answer[25];
if ( tot_secs < 0 ) {
sprintf(answer,"[?????]");
return answer;
}
days = tot_secs / DAY;
tot_secs %= DAY;
hours = tot_secs / HOUR;
tot_secs %= HOUR;
min = tot_secs / MINUTE;
secs = tot_secs % MINUTE;
(void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs );
return answer;
}
<commit_msg>Changed the format_time from MM/DD/YY to MM/DD/YYYY.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date( time_t date )
{
static char buf[ 12 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date_year( time_t date )
{
static char buf[ 15 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%02d/%-4d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, (tm->tm_year + 1900), tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a time value which is encoded as seconds since the UNIX
"epoch". We return a string in the format dd+hh:mm:ss, indicating
days, hours, minutes, and seconds. The string is in static data
space, and will be overwritten by the next call to this function.
*/
char *
format_time( int tot_secs )
{
int days;
int hours;
int min;
int secs;
static char answer[25];
if ( tot_secs < 0 ) {
sprintf(answer,"[?????]");
return answer;
}
days = tot_secs / DAY;
tot_secs %= DAY;
hours = tot_secs / HOUR;
tot_secs %= HOUR;
min = tot_secs / MINUTE;
secs = tot_secs % MINUTE;
(void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs );
return answer;
}
<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#ifndef WIN32
#include "types.h"
#endif
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date( time_t date )
{
static char buf[ 12 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date_year( time_t date )
{
static char buf[ 15 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%02d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a time value which is encoded as seconds since the UNIX
"epoch". We return a string in the format dd+hh:mm:ss, indicating
days, hours, minutes, and seconds. The string is in static data
space, and will be overwritten by the next call to this function.
*/
char *
format_time( int tot_secs )
{
int days;
int hours;
int min;
int secs;
static char answer[25];
days = tot_secs / DAY;
tot_secs %= DAY;
hours = tot_secs / HOUR;
tot_secs %= HOUR;
min = tot_secs / MINUTE;
secs = tot_secs % MINUTE;
(void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs );
return answer;
}
<commit_msg>file types.h has gone away, so we shouldn't include it!<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date( time_t date )
{
static char buf[ 12 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a date expressed in "UNIX time" into "month/day hour:minute".
*/
char *
format_date_year( time_t date )
{
static char buf[ 15 ];
struct tm *tm;
if (date<0) {
strcpy(buf," ??? ");
return buf;
}
tm = localtime( &date );
sprintf( buf, "%2d/%02d/%-2d %02d:%02d",
(tm->tm_mon)+1, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min
);
return buf;
}
/*
Format a time value which is encoded as seconds since the UNIX
"epoch". We return a string in the format dd+hh:mm:ss, indicating
days, hours, minutes, and seconds. The string is in static data
space, and will be overwritten by the next call to this function.
*/
char *
format_time( int tot_secs )
{
int days;
int hours;
int min;
int secs;
static char answer[25];
days = tot_secs / DAY;
tot_secs %= DAY;
hours = tot_secs / HOUR;
tot_secs %= HOUR;
min = tot_secs / MINUTE;
secs = tot_secs % MINUTE;
(void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs );
return answer;
}
<|endoftext|> |
<commit_before>#include "env.hpp"
namespace Vole {
Env::Env(Env* par)
: parent(par) { }
Value Env::lookup(Symbol name) {
for (auto current = this; current; current = current->parent) {
if (current->bindings.count(name)) {
return current->bindings[name];
}
}
throw "unbound variable";
}
void Env::bind(Symbol name, Value value) {
bindings[name] = value;
}
void Env::assign(Symbol name, Value value) {
for (auto current = this; current; current = current->parent) {
if (current->bindings.count(name)) {
current->bindings[name] = value;
return;
}
}
throw "assignment to unbound variable";
}
}<commit_msg>whitespace tweak<commit_after>#include "env.hpp"
namespace Vole {
Env::Env(Env* par)
: parent(par) { }
Value Env::lookup(Symbol name) {
for (auto current = this; current; current = current->parent) {
if (current->bindings.count(name)) {
return current->bindings[name];
}
}
throw "unbound variable";
}
void Env::bind(Symbol name, Value value) {
bindings[name] = value;
}
void Env::assign(Symbol name, Value value) {
for (auto current = this; current; current = current->parent) {
if (current->bindings.count(name)) {
current->bindings[name] = value;
return;
}
}
throw "assignment to unbound variable";
}
}<|endoftext|> |
<commit_before>/*=============================================================================
Copyright (c) 2012-2013 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// N-Dimensional uniform grid
#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID
#include <vector>
struct NDGrid {
template <typename Func> static void sample(
const double min_extent,
const double max_extent,
const std::size_t dimension,
const double grid_points_per_major_axis,
const Func &func,
std::vector<double>& address) {
if (address.size() == dimension) {
// terminating condition; address is complete
func(address);
}
else {
double step = (max_extent - min_extent) / grid_points_per_major_axis;
for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
double location = step*j + min_extent;
address.push_back(location);
// recursive step
NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
address.pop_back(); // remove the element we just added (this way avoids copying)
}
}
}
template <typename Func> static inline void sample(
const double min_extent,
const double max_extent,
const std::size_t dimension,
const double grid_points_per_major_axis,
const Func &func) {
std::vector<double> address;
NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
}
};
#endif
<commit_msg>Dimension-dependent bounds for NDGrid<commit_after>/*=============================================================================
Copyright (c) 2012-2013 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// N-Dimensional uniform grid
#ifndef INCLUDED_NDGRID
#define INCLUDED_NDGRID
#include <vector>
#include <utility>
struct NDGrid {
template <typename Func> static void sample(
const std::vector<std::pair<double,double> > &extents,
const double grid_points_per_major_axis,
const Func &func,
std::vector<double>& address) {
if (address.size() == extents.size()) {
// terminating condition; address is complete
func(address);
}
else {
const double max_extent = extents[address.size()].second;
const double min_extent = extents[address.size()].first;
double step = (max_extent - min_extent) / grid_points_per_major_axis;
for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
double location = step*j + min_extent;
address.push_back(location);
// recursive step
NDGrid::sample(extents, grid_points_per_major_axis, func, address);
address.pop_back(); // remove the element we just added (this way avoids copying)
}
}
}
template <typename Func> static inline void sample(
const std::vector<std::pair<double,double> > &extents,
const double grid_points_per_major_axis,
const Func &func) {
std::vector<double> address;
NDGrid::sample(extents, grid_points_per_major_axis, func, address);
}
template <typename Func> static void sample(
const double min_extent,
const double max_extent,
const std::size_t dimension,
const double grid_points_per_major_axis,
const Func &func,
std::vector<double>& address) {
if (address.size() == dimension) {
// terminating condition; address is complete
func(address);
}
else {
double step = (max_extent - min_extent) / grid_points_per_major_axis;
for (auto j = 0; j <= grid_points_per_major_axis; ++j) {
double location = step*j + min_extent;
address.push_back(location);
// recursive step
NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
address.pop_back(); // remove the element we just added (this way avoids copying)
}
}
}
template <typename Func> static inline void sample(
const double min_extent,
const double max_extent,
const std::size_t dimension,
const double grid_points_per_major_axis,
const Func &func) {
std::vector<double> address;
NDGrid::sample(min_extent, max_extent, dimension, grid_points_per_major_axis, func, address);
}
};
#endif
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Laurent LEC <[email protected]>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include <qimessaging/qt/QiTransportSocket>
#include "src/qitransportsocket_p.h"
#include <QTcpSocket>
#include <QSslSocket>
#include <QHostAddress>
#include <qimessaging/message.hpp>
#include <qimessaging/buffer.hpp>
#include "../src/message_p.hpp"
QiTransportSocketPrivate::QiTransportSocketPrivate(QiTransportSocket* self)
: _self(self)
, _device(0)
, _msg(0)
{
}
QiTransportSocketPrivate::~QiTransportSocketPrivate()
{
if (_msg)
{
delete _msg;
_msg = 0;
}
foreach (qi::Message* msg, _pendingMessages)
{
delete msg;
msg = 0;
}
delete _device;
_device = 0;
}
void QiTransportSocketPrivate::read()
{
while (true)
{
if (_msg == 0)
{
_msg = new qi::Message();
_readHdr = true;
}
if (_readHdr)
{
if (_device->bytesAvailable()
>= static_cast<qint64>(sizeof(qi::MessagePrivate::MessageHeader)))
{
_device->read(static_cast<char*>(_msg->_p->getHeader()),
sizeof(qi::MessagePrivate::MessageHeader));
if (!_msg->isValid())
{
qiLogError("QiTransportSocket") << "incorrect message, dropped";
// TODO: implement error recovery...
return;
}
_readHdr = false;
}
else
{
break;
}
}
if (!_readHdr)
{
qint64 bufferSize = static_cast<qi::MessagePrivate::MessageHeader*>(_msg->_p->getHeader())->size;
if (_device->bytesAvailable()
>= static_cast<qint64>(bufferSize))
{
qi::Buffer buffer;
buffer.reserve(bufferSize);
_msg->setBuffer(buffer);
_device->read(static_cast<char*>(buffer.data()), bufferSize);
_pendingMessages.append(_msg);
_readHdr = true;
_msg = 0;
emit readyRead();
}
else
{
break;
}
}
}
}
QiTransportSocket::QiTransportSocket(QObject *parent)
: QObject(parent)
, _p(new QiTransportSocketPrivate(this))
{
connect(_p, SIGNAL(readyRead()), this, SIGNAL(readyRead()));
}
QiTransportSocket::~QiTransportSocket()
{
close();
delete _p;
}
void QiTransportSocket::close()
{
if (_p->_device)
{
_p->_device->close();
}
}
void QiTransportSocket::write(const qi::Message& message)
{
qint64 writtenSize = 0;
message._p->complete();
writtenSize = _p->_device->write(static_cast<char*>(message._p->getHeader()),
sizeof(qi::MessagePrivate::MessageHeader));
if (writtenSize != sizeof(qi::MessagePrivate::MessageHeader))
{
qiLogError("QiTransportSocket") << "write error, (" << writtenSize << ")" << _p->_device->errorString().toUtf8().constData();
}
writtenSize = _p->_device->write(static_cast<char*>(message._p->buffer.data()),
message._p->buffer.size());
if (writtenSize != static_cast<qint64>(message._p->buffer.size()))
{
qiLogError("QiTransportSocket") << "write error, (" << writtenSize << ")";
}
}
qi::Message *QiTransportSocket::read()
{
return _p->_pendingMessages.empty() ? 0 : _p->_pendingMessages.dequeue();
}
void QiTransportSocket::connectToHost(const QUrl& address)
{
if (address.scheme() == "tcp")
{
QTcpSocket* socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SIGNAL(connected()));
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
connect(socket, SIGNAL(readyRead()), _p, SLOT(read()));
QHostAddress host(address.host());
socket->connectToHost(host, address.port());
_p->_peer = address;
_p->_device = socket;
}
else if (address.scheme() == "tcps")
{
QSslSocket* socket = new QSslSocket(this);
connect(socket, SIGNAL(encrypted()), this, SIGNAL(connected()));
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
connect(socket, SIGNAL(readyRead()), _p, SLOT(read()));
socket->setProtocol(QSsl::TlsV1SslV3);
socket->connectToHostEncrypted(address.host(), address.port());
_p->_peer = address;
_p->_device = socket;
}
qiLogError("QiTransportServer") << "Protocol `"
<< address.scheme().toUtf8().constData()
<< "' is not supported, can't connect";
}
QUrl QiTransportSocket::peer()
{
return _p->_peer;
}
QiTransportSocket::SocketState QiTransportSocket::state() const
{
if (!_p->_device)
{
return SocketState_Unconnected;
}
/*
* This function must return a SocketState, which is mirroring the values
* of QAbstractSocket.
* If the socket is a QAbstractSocket, we can directly return the state
* given by the API.
*/
QAbstractSocket *socket;
if ((socket = dynamic_cast<QAbstractSocket*>(_p->_device)))
{
return static_cast<SocketState>(socket->state());
}
/*
* Just in case...
*/
return SocketState_Unknown;
}
<commit_msg>Improve log messages<commit_after>/*
** Author(s):
** - Laurent LEC <[email protected]>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include <qimessaging/qt/QiTransportSocket>
#include "src/qitransportsocket_p.h"
#include <QTcpSocket>
#include <QSslSocket>
#include <QHostAddress>
#include <qimessaging/message.hpp>
#include <qimessaging/buffer.hpp>
#include "../src/message_p.hpp"
QiTransportSocketPrivate::QiTransportSocketPrivate(QiTransportSocket* self)
: _self(self)
, _device(0)
, _msg(0)
{
}
QiTransportSocketPrivate::~QiTransportSocketPrivate()
{
if (_msg)
{
delete _msg;
_msg = 0;
}
foreach (qi::Message* msg, _pendingMessages)
{
delete msg;
msg = 0;
}
delete _device;
_device = 0;
}
void QiTransportSocketPrivate::read()
{
while (true)
{
if (_msg == 0)
{
_msg = new qi::Message();
_readHdr = true;
}
if (_readHdr)
{
if (_device->bytesAvailable()
>= static_cast<qint64>(sizeof(qi::MessagePrivate::MessageHeader)))
{
_device->read(static_cast<char*>(_msg->_p->getHeader()),
sizeof(qi::MessagePrivate::MessageHeader));
if (!_msg->isValid())
{
qiLogError("QiTransportSocket") << "incorrect message, dropped";
// TODO: implement error recovery...
return;
}
_readHdr = false;
}
else
{
break;
}
}
if (!_readHdr)
{
qint64 bufferSize = static_cast<qi::MessagePrivate::MessageHeader*>(_msg->_p->getHeader())->size;
if (_device->bytesAvailable()
>= static_cast<qint64>(bufferSize))
{
qi::Buffer buffer;
buffer.reserve(bufferSize);
_msg->setBuffer(buffer);
_device->read(static_cast<char*>(buffer.data()), bufferSize);
_pendingMessages.append(_msg);
_readHdr = true;
_msg = 0;
emit readyRead();
}
else
{
break;
}
}
}
}
QiTransportSocket::QiTransportSocket(QObject *parent)
: QObject(parent)
, _p(new QiTransportSocketPrivate(this))
{
connect(_p, SIGNAL(readyRead()), this, SIGNAL(readyRead()));
}
QiTransportSocket::~QiTransportSocket()
{
close();
delete _p;
}
void QiTransportSocket::close()
{
if (_p->_device)
{
_p->_device->close();
}
}
void QiTransportSocket::write(const qi::Message& message)
{
qint64 writtenSize = 0;
message._p->complete();
writtenSize = _p->_device->write(static_cast<char*>(message._p->getHeader()),
sizeof(qi::MessagePrivate::MessageHeader));
if (writtenSize != sizeof(qi::MessagePrivate::MessageHeader))
{
qiLogError("QiTransportSocket") << "write error, (" << writtenSize << ")" << _p->_device->errorString().toUtf8().constData();
}
writtenSize = _p->_device->write(static_cast<char*>(message._p->buffer.data()),
message._p->buffer.size());
if (writtenSize != static_cast<qint64>(message._p->buffer.size()))
{
qiLogError("QiTransportSocket") << "write error, (" << writtenSize << ")";
}
}
qi::Message *QiTransportSocket::read()
{
return _p->_pendingMessages.empty() ? 0 : _p->_pendingMessages.dequeue();
}
void QiTransportSocket::connectToHost(const QUrl& address)
{
qiLogDebug("QiTransportSocket") << "Connecting to " << address.toString().toUtf8().constData();
if (address.scheme() == "tcp")
{
QTcpSocket* socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SIGNAL(connected()));
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
connect(socket, SIGNAL(readyRead()), _p, SLOT(read()));
QHostAddress host(address.host());
socket->connectToHost(host, address.port());
_p->_peer = address;
_p->_device = socket;
}
else if (address.scheme() == "tcps")
{
QSslSocket* socket = new QSslSocket(this);
connect(socket, SIGNAL(encrypted()), this, SIGNAL(connected()));
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
connect(socket, SIGNAL(readyRead()), _p, SLOT(read()));
socket->setProtocol(QSsl::TlsV1SslV3);
socket->connectToHostEncrypted(address.host(), address.port());
_p->_peer = address;
_p->_device = socket;
}
else
{
qiLogError("QiTransportServer") << "Protocol `"
<< address.scheme().toUtf8().constData()
<< "' is not supported, can't connect";
}
}
QUrl QiTransportSocket::peer()
{
return _p->_peer;
}
QiTransportSocket::SocketState QiTransportSocket::state() const
{
if (!_p->_device)
{
return SocketState_Unconnected;
}
/*
* This function must return a SocketState, which is mirroring the values
* of QAbstractSocket.
* If the socket is a QAbstractSocket, we can directly return the state
* given by the API.
*/
QAbstractSocket *socket;
if ((socket = dynamic_cast<QAbstractSocket*>(_p->_device)))
{
return static_cast<SocketState>(socket->state());
}
/*
* Just in case...
*/
return SocketState_Unknown;
}
<|endoftext|> |
<commit_before>/*
ESP8266WiFiSTA.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "ESP8266WiFi.h"
#include "ESP8266WiFiGeneric.h"
#include "ESP8266WiFiAP.h"
extern "C" {
#include "c_types.h"
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"
}
#include "debug.h"
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
static bool softap_config_equal(const softap_config& lhs, const softap_config& rhs);
/**
* compare two AP configurations
* @param lhs softap_config
* @param rhs softap_config
* @return equal
*/
static bool softap_config_equal(const softap_config& lhs, const softap_config& rhs) {
if(strcmp(reinterpret_cast<const char*>(lhs.ssid), reinterpret_cast<const char*>(rhs.ssid)) != 0) {
return false;
}
if(strcmp(reinterpret_cast<const char*>(lhs.password), reinterpret_cast<const char*>(rhs.password)) != 0) {
return false;
}
if(lhs.channel != rhs.channel) {
return false;
}
if(lhs.ssid_hidden != rhs.ssid_hidden) {
return false;
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- AP function -----------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* Set up an access point
* @param ssid Pointer to the SSID (max 63 char).
* @param passphrase (for WPA2 min 8 char, for open use NULL)
* @param channel WiFi channel number, 1 - 13.
* @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID)
*/
bool ESP8266WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden) {
if(!WiFi.enableAP(true)) {
// enable AP failed
DEBUG_WIFI("[AP] enableAP failed!\n");
return false;
}
if(!ssid || *ssid == 0 || strlen(ssid) > 31) {
// fail SSID too long or missing!
DEBUG_WIFI("[AP] SSID too long or missing!\n");
return false;
}
if(passphrase && (strlen(passphrase) > 63 || strlen(passphrase) < 8)) {
// fail passphrase to long or short!
DEBUG_WIFI("[AP] fail passphrase to long or short!\n");
return false;
}
bool ret = false;
struct softap_config conf;
strcpy(reinterpret_cast<char*>(conf.ssid), ssid);
conf.channel = channel;
conf.ssid_len = strlen(ssid);
conf.ssid_hidden = ssid_hidden;
conf.max_connection = 4;
conf.beacon_interval = 100;
if(!passphrase || strlen(passphrase) == 0) {
conf.authmode = AUTH_OPEN;
*conf.password = 0;
} else {
conf.authmode = AUTH_WPA2_PSK;
strcpy(reinterpret_cast<char*>(conf.password), passphrase);
}
struct softap_config conf_current;
wifi_softap_get_config(&conf_current);
if(!softap_config_equal(conf, conf_current)) {
ETS_UART_INTR_DISABLE();
if(WiFi._persistent) {
ret = wifi_softap_set_config(&conf);
} else {
ret = wifi_softap_set_config_current(&conf);
}
ETS_UART_INTR_ENABLE();
if(!ret) {
DEBUG_WIFI("[AP] set_config failed!\n");
return false;
}
} else {
DEBUG_WIFI("[AP] softap config unchanged\n");
}
if(wifi_softap_dhcps_status() != DHCP_STARTED) {
DEBUG_WIFI("[AP] DHCP not started, starting...\n");
if(!wifi_softap_dhcps_start()) {
DEBUG_WIFI("[AP] wifi_softap_dhcps_start failed!\n");
ret = false;
}
}
// check IP config
struct ip_info ip;
if(wifi_get_ip_info(SOFTAP_IF, &ip)) {
if(ip.ip.addr == 0x00000000) {
// Invalid config
DEBUG_WIFI("[AP] IP config Invalid resetting...\n");
//192.168.244.1 , 192.168.244.1 , 255.255.255.0
ret = softAPConfig(0x01F4A8C0, 0x01F4A8C0, 0x00FFFFFF);
if(!ret) {
DEBUG_WIFI("[AP] softAPConfig failed!\n");
ret = false;
}
}
} else {
DEBUG_WIFI("[AP] wifi_get_ip_info failed!\n");
ret = false;
}
return ret;
}
/**
* Configure access point
* @param local_ip access point IP
* @param gateway gateway IP
* @param subnet subnet mask
*/
bool ESP8266WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) {
DEBUG_WIFI("[APConfig] local_ip: %s gateway: %s subnet: %s\n", local_ip.toString().c_str(), gateway.toString().c_str(), subnet.toString().c_str());
if(!WiFi.enableAP(true)) {
// enable AP failed
DEBUG_WIFI("[APConfig] enableAP failed!\n");
return false;
}
bool ret = true;
struct ip_info info;
info.ip.addr = static_cast<uint32_t>(local_ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
if(!wifi_softap_dhcps_stop()) {
DEBUG_WIFI("[APConfig] wifi_softap_dhcps_stop failed!\n");
}
if(!wifi_set_ip_info(SOFTAP_IF, &info)) {
DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n");
ret = false;
}
struct dhcps_lease dhcp_lease;
IPAddress ip = local_ip;
ip[3] += 99;
dhcp_lease.start_ip.addr = static_cast<uint32_t>(ip);
DEBUG_WIFI("[APConfig] DHCP IP start: %s\n", ip.toString().c_str());
ip[3] += 100;
dhcp_lease.end_ip.addr = static_cast<uint32_t>(ip);
DEBUG_WIFI("[APConfig] DHCP IP end: %s\n", ip.toString().c_str());
if(!wifi_softap_set_dhcps_lease(&dhcp_lease)) {
DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n");
ret = false;
}
// set lease time to 720min --> 12h
if(!wifi_softap_set_dhcps_lease_time(720)) {
DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_lease_time failed!\n");
ret = false;
}
uint8 mode = 1;
if(!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) {
DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_offer_option failed!\n");
ret = false;
}
if(!wifi_softap_dhcps_start()) {
DEBUG_WIFI("[APConfig] wifi_softap_dhcps_start failed!\n");
ret = false;
}
// check config
if(wifi_get_ip_info(SOFTAP_IF, &info)) {
if(info.ip.addr == 0x00000000) {
DEBUG_WIFI("[APConfig] IP config Invalid?!\n");
ret = false;
} else if(local_ip != info.ip.addr) {
ip = info.ip.addr;
DEBUG_WIFI("[APConfig] IP config not set correct?! new IP: %s\n", ip.toString().c_str());
ret = false;
}
} else {
DEBUG_WIFI("[APConfig] wifi_get_ip_info failed!\n");
ret = false;
}
return ret;
}
/**
* Disconnect from the network (close AP)
* @param wifioff disable mode?
* @return one value of wl_status_t enum
*/
bool ESP8266WiFiAPClass::softAPdisconnect(bool wifioff) {
bool ret;
struct softap_config conf;
*conf.ssid = 0;
*conf.password = 0;
ETS_UART_INTR_DISABLE();
if(WiFi._persistent) {
ret = wifi_softap_set_config(&conf);
} else {
ret = wifi_softap_set_config_current(&conf);
}
ETS_UART_INTR_ENABLE();
if(!ret) {
DEBUG_WIFI("[APdisconnect] set_config failed!\n");
}
if(wifioff) {
ret = WiFi.enableAP(false);
}
return ret;
}
/**
* Get the count of the Station / client that are connected to the softAP interface
* @return Stations count
*/
uint8_t ESP8266WiFiAPClass::softAPgetStationNum() {
return wifi_softap_get_station_num();
}
/**
* Get the softAP interface IP address.
* @return IPAddress softAP IP
*/
IPAddress ESP8266WiFiAPClass::softAPIP() {
struct ip_info ip;
wifi_get_ip_info(SOFTAP_IF, &ip);
return IPAddress(ip.ip.addr);
}
/**
* Get the softAP interface MAC address.
* @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
* @return pointer to uint8_t*
*/
uint8_t* ESP8266WiFiAPClass::softAPmacAddress(uint8_t* mac) {
wifi_get_macaddr(SOFTAP_IF, mac);
return mac;
}
/**
* Get the softAP interface MAC address.
* @return String mac
*/
String ESP8266WiFiAPClass::softAPmacAddress(void) {
uint8_t mac[6];
char macStr[18] = { 0 };
wifi_get_macaddr(SOFTAP_IF, mac);
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr);
}
<commit_msg>correct default return value for softAP<commit_after>/*
ESP8266WiFiSTA.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "ESP8266WiFi.h"
#include "ESP8266WiFiGeneric.h"
#include "ESP8266WiFiAP.h"
extern "C" {
#include "c_types.h"
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"
}
#include "debug.h"
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
static bool softap_config_equal(const softap_config& lhs, const softap_config& rhs);
/**
* compare two AP configurations
* @param lhs softap_config
* @param rhs softap_config
* @return equal
*/
static bool softap_config_equal(const softap_config& lhs, const softap_config& rhs) {
if(strcmp(reinterpret_cast<const char*>(lhs.ssid), reinterpret_cast<const char*>(rhs.ssid)) != 0) {
return false;
}
if(strcmp(reinterpret_cast<const char*>(lhs.password), reinterpret_cast<const char*>(rhs.password)) != 0) {
return false;
}
if(lhs.channel != rhs.channel) {
return false;
}
if(lhs.ssid_hidden != rhs.ssid_hidden) {
return false;
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- AP function -----------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* Set up an access point
* @param ssid Pointer to the SSID (max 63 char).
* @param passphrase (for WPA2 min 8 char, for open use NULL)
* @param channel WiFi channel number, 1 - 13.
* @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID)
*/
bool ESP8266WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden) {
if(!WiFi.enableAP(true)) {
// enable AP failed
DEBUG_WIFI("[AP] enableAP failed!\n");
return false;
}
if(!ssid || *ssid == 0 || strlen(ssid) > 31) {
// fail SSID too long or missing!
DEBUG_WIFI("[AP] SSID too long or missing!\n");
return false;
}
if(passphrase && (strlen(passphrase) > 63 || strlen(passphrase) < 8)) {
// fail passphrase to long or short!
DEBUG_WIFI("[AP] fail passphrase to long or short!\n");
return false;
}
bool ret = true;
struct softap_config conf;
strcpy(reinterpret_cast<char*>(conf.ssid), ssid);
conf.channel = channel;
conf.ssid_len = strlen(ssid);
conf.ssid_hidden = ssid_hidden;
conf.max_connection = 4;
conf.beacon_interval = 100;
if(!passphrase || strlen(passphrase) == 0) {
conf.authmode = AUTH_OPEN;
*conf.password = 0;
} else {
conf.authmode = AUTH_WPA2_PSK;
strcpy(reinterpret_cast<char*>(conf.password), passphrase);
}
struct softap_config conf_current;
wifi_softap_get_config(&conf_current);
if(!softap_config_equal(conf, conf_current)) {
ETS_UART_INTR_DISABLE();
if(WiFi._persistent) {
ret = wifi_softap_set_config(&conf);
} else {
ret = wifi_softap_set_config_current(&conf);
}
ETS_UART_INTR_ENABLE();
if(!ret) {
DEBUG_WIFI("[AP] set_config failed!\n");
return false;
}
} else {
DEBUG_WIFI("[AP] softap config unchanged\n");
}
if(wifi_softap_dhcps_status() != DHCP_STARTED) {
DEBUG_WIFI("[AP] DHCP not started, starting...\n");
if(!wifi_softap_dhcps_start()) {
DEBUG_WIFI("[AP] wifi_softap_dhcps_start failed!\n");
ret = false;
}
}
// check IP config
struct ip_info ip;
if(wifi_get_ip_info(SOFTAP_IF, &ip)) {
if(ip.ip.addr == 0x00000000) {
// Invalid config
DEBUG_WIFI("[AP] IP config Invalid resetting...\n");
//192.168.244.1 , 192.168.244.1 , 255.255.255.0
ret = softAPConfig(0x01F4A8C0, 0x01F4A8C0, 0x00FFFFFF);
if(!ret) {
DEBUG_WIFI("[AP] softAPConfig failed!\n");
ret = false;
}
}
} else {
DEBUG_WIFI("[AP] wifi_get_ip_info failed!\n");
ret = false;
}
return ret;
}
/**
* Configure access point
* @param local_ip access point IP
* @param gateway gateway IP
* @param subnet subnet mask
*/
bool ESP8266WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) {
DEBUG_WIFI("[APConfig] local_ip: %s gateway: %s subnet: %s\n", local_ip.toString().c_str(), gateway.toString().c_str(), subnet.toString().c_str());
if(!WiFi.enableAP(true)) {
// enable AP failed
DEBUG_WIFI("[APConfig] enableAP failed!\n");
return false;
}
bool ret = true;
struct ip_info info;
info.ip.addr = static_cast<uint32_t>(local_ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
if(!wifi_softap_dhcps_stop()) {
DEBUG_WIFI("[APConfig] wifi_softap_dhcps_stop failed!\n");
}
if(!wifi_set_ip_info(SOFTAP_IF, &info)) {
DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n");
ret = false;
}
struct dhcps_lease dhcp_lease;
IPAddress ip = local_ip;
ip[3] += 99;
dhcp_lease.start_ip.addr = static_cast<uint32_t>(ip);
DEBUG_WIFI("[APConfig] DHCP IP start: %s\n", ip.toString().c_str());
ip[3] += 100;
dhcp_lease.end_ip.addr = static_cast<uint32_t>(ip);
DEBUG_WIFI("[APConfig] DHCP IP end: %s\n", ip.toString().c_str());
if(!wifi_softap_set_dhcps_lease(&dhcp_lease)) {
DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n");
ret = false;
}
// set lease time to 720min --> 12h
if(!wifi_softap_set_dhcps_lease_time(720)) {
DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_lease_time failed!\n");
ret = false;
}
uint8 mode = 1;
if(!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) {
DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_offer_option failed!\n");
ret = false;
}
if(!wifi_softap_dhcps_start()) {
DEBUG_WIFI("[APConfig] wifi_softap_dhcps_start failed!\n");
ret = false;
}
// check config
if(wifi_get_ip_info(SOFTAP_IF, &info)) {
if(info.ip.addr == 0x00000000) {
DEBUG_WIFI("[APConfig] IP config Invalid?!\n");
ret = false;
} else if(local_ip != info.ip.addr) {
ip = info.ip.addr;
DEBUG_WIFI("[APConfig] IP config not set correct?! new IP: %s\n", ip.toString().c_str());
ret = false;
}
} else {
DEBUG_WIFI("[APConfig] wifi_get_ip_info failed!\n");
ret = false;
}
return ret;
}
/**
* Disconnect from the network (close AP)
* @param wifioff disable mode?
* @return one value of wl_status_t enum
*/
bool ESP8266WiFiAPClass::softAPdisconnect(bool wifioff) {
bool ret;
struct softap_config conf;
*conf.ssid = 0;
*conf.password = 0;
ETS_UART_INTR_DISABLE();
if(WiFi._persistent) {
ret = wifi_softap_set_config(&conf);
} else {
ret = wifi_softap_set_config_current(&conf);
}
ETS_UART_INTR_ENABLE();
if(!ret) {
DEBUG_WIFI("[APdisconnect] set_config failed!\n");
}
if(wifioff) {
ret = WiFi.enableAP(false);
}
return ret;
}
/**
* Get the count of the Station / client that are connected to the softAP interface
* @return Stations count
*/
uint8_t ESP8266WiFiAPClass::softAPgetStationNum() {
return wifi_softap_get_station_num();
}
/**
* Get the softAP interface IP address.
* @return IPAddress softAP IP
*/
IPAddress ESP8266WiFiAPClass::softAPIP() {
struct ip_info ip;
wifi_get_ip_info(SOFTAP_IF, &ip);
return IPAddress(ip.ip.addr);
}
/**
* Get the softAP interface MAC address.
* @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
* @return pointer to uint8_t*
*/
uint8_t* ESP8266WiFiAPClass::softAPmacAddress(uint8_t* mac) {
wifi_get_macaddr(SOFTAP_IF, mac);
return mac;
}
/**
* Get the softAP interface MAC address.
* @return String mac
*/
String ESP8266WiFiAPClass::softAPmacAddress(void) {
uint8_t mac[6];
char macStr[18] = { 0 };
wifi_get_macaddr(SOFTAP_IF, mac);
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr);
}
<|endoftext|> |
<commit_before>/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2016, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "kinematics-precomp.h" // Precompiled header
#include <mrpt/kinematics/CVehicleVelCmd_Holo.h>
#include <mrpt/utils/CStream.h>
using namespace mrpt::kinematics;
using namespace mrpt::utils;
IMPLEMENTS_SERIALIZABLE(CVehicleVelCmd_Holo, CVehicleVelCmd, mrpt::kinematics)
CVehicleVelCmd_Holo::CVehicleVelCmd_Holo() :
vel(.0),
dir_local(.0),
ramp_time(.0),
rot_speed(.0)
{
}
CVehicleVelCmd_Holo::~CVehicleVelCmd_Holo()
{
}
size_t CVehicleVelCmd_Holo::getVelCmdLength() const
{
return 4;
}
std::string CVehicleVelCmd_Holo::getVelCmdDescription(const int index) const
{
switch (index)
{
case 0: return "vel"; break;
case 1: return "dir_local"; break;
case 2: return "ramp_time"; break;
case 3: return "rot_speed"; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i",index);
};
}
double CVehicleVelCmd_Holo::getVelCmdElement(const int index) const
{
switch (index)
{
case 0: return vel; break;
case 1: return dir_local; break;
case 2: return ramp_time; break;
case 3: return rot_speed; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i", index);
};
}
void CVehicleVelCmd_Holo::setVelCmdElement(const int index, const double val)
{
switch (index)
{
case 0: vel=val; break;
case 1: dir_local = val; break;
case 2: ramp_time=val; break;
case 3: rot_speed=val; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i", index);
};
}
bool CVehicleVelCmd_Holo::isStopCmd() const
{
return vel == 0 && rot_speed == 0;
}
void CVehicleVelCmd_Holo::setToStop()
{
vel = dir_local = ramp_time = rot_speed = .0;
}
void CVehicleVelCmd_Holo::readFromStream(mrpt::utils::CStream &in, int version)
{
switch (version)
{
case 0:
in >> vel >> dir_local >> ramp_time >> rot_speed;
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version)
};
}
void CVehicleVelCmd_Holo::writeToStream(mrpt::utils::CStream &out, int *version) const
{
if (version)
{
*version = 0;
return;
}
out << vel << dir_local << ramp_time << rot_speed;
}
void CVehicleVelCmd_Holo::cmdVel_scale(double vel_scale)
{
vel *= vel_scale; // |(vx,vy)|
rot_speed *= vel_scale; // rot_speed
// ramp_time: leave unchanged
}
void CVehicleVelCmd_Holo::cmdVel_limits(const mrpt::kinematics::CVehicleVelCmd &prev_vel_cmd, const double beta, const TVelCmdParams ¶ms)
{
ASSERTMSG_(params.robotMax_V_mps >= .0, "[CVehicleVelCmd_Holo] `robotMax_V_mps` must be set to valid values: either assign values programatically or call loadConfigFile()");
const mrpt::kinematics::CVehicleVelCmd_Holo *prevcmd = dynamic_cast<const mrpt::kinematics::CVehicleVelCmd_Holo*>(&prev_vel_cmd);
ASSERTMSG_(prevcmd, "Expected prevcmd of type `CVehicleVelCmd_Holo`");
double f = 1.0;
if (vel>params.robotMax_V_mps) f = params.robotMax_V_mps / vel;
vel *= f; // |(vx,vy)|
rot_speed *= f; // rot_speed
// ramp_time: leave unchanged
// Blending with "beta" not required, since the ramp_time already blends cmds for holo robots.
}
<commit_msg>[CVehicleVelCmd_Holo::cmdVel_limits] Remove unnecessary cast and assertion<commit_after>/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2016, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "kinematics-precomp.h" // Precompiled header
#include <mrpt/kinematics/CVehicleVelCmd_Holo.h>
#include <mrpt/utils/CStream.h>
using namespace mrpt::kinematics;
using namespace mrpt::utils;
IMPLEMENTS_SERIALIZABLE(CVehicleVelCmd_Holo, CVehicleVelCmd, mrpt::kinematics)
CVehicleVelCmd_Holo::CVehicleVelCmd_Holo() :
vel(.0),
dir_local(.0),
ramp_time(.0),
rot_speed(.0)
{
}
CVehicleVelCmd_Holo::~CVehicleVelCmd_Holo()
{
}
size_t CVehicleVelCmd_Holo::getVelCmdLength() const
{
return 4;
}
std::string CVehicleVelCmd_Holo::getVelCmdDescription(const int index) const
{
switch (index)
{
case 0: return "vel"; break;
case 1: return "dir_local"; break;
case 2: return "ramp_time"; break;
case 3: return "rot_speed"; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i",index);
};
}
double CVehicleVelCmd_Holo::getVelCmdElement(const int index) const
{
switch (index)
{
case 0: return vel; break;
case 1: return dir_local; break;
case 2: return ramp_time; break;
case 3: return rot_speed; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i", index);
};
}
void CVehicleVelCmd_Holo::setVelCmdElement(const int index, const double val)
{
switch (index)
{
case 0: vel=val; break;
case 1: dir_local = val; break;
case 2: ramp_time=val; break;
case 3: rot_speed=val; break;
default:
THROW_EXCEPTION_CUSTOM_MSG1("index out of bounds: %i", index);
};
}
bool CVehicleVelCmd_Holo::isStopCmd() const
{
return vel == 0 && rot_speed == 0;
}
void CVehicleVelCmd_Holo::setToStop()
{
vel = dir_local = ramp_time = rot_speed = .0;
}
void CVehicleVelCmd_Holo::readFromStream(mrpt::utils::CStream &in, int version)
{
switch (version)
{
case 0:
in >> vel >> dir_local >> ramp_time >> rot_speed;
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version)
};
}
void CVehicleVelCmd_Holo::writeToStream(mrpt::utils::CStream &out, int *version) const
{
if (version)
{
*version = 0;
return;
}
out << vel << dir_local << ramp_time << rot_speed;
}
void CVehicleVelCmd_Holo::cmdVel_scale(double vel_scale)
{
vel *= vel_scale; // |(vx,vy)|
rot_speed *= vel_scale; // rot_speed
// ramp_time: leave unchanged
}
void CVehicleVelCmd_Holo::cmdVel_limits(const mrpt::kinematics::CVehicleVelCmd &prev_vel_cmd, const double beta, const TVelCmdParams ¶ms)
{
ASSERTMSG_(params.robotMax_V_mps >= .0, "[CVehicleVelCmd_Holo] `robotMax_V_mps` must be set to valid values: either assign values programatically or call loadConfigFile()");
double f = 1.0;
if (vel>params.robotMax_V_mps) f = params.robotMax_V_mps / vel;
vel *= f; // |(vx,vy)|
rot_speed *= f; // rot_speed
// ramp_time: leave unchanged
// Blending with "beta" not required, since the ramp_time already blends cmds for holo robots.
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/tools/quic/test_tools/http_message_test_utils.h"
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
using base::StringPiece;
using std::string;
using std::vector;
namespace net {
namespace tools {
namespace test {
namespace {
//const char* kContentEncoding = "content-encoding";
const char* kContentLength = "content-length";
const char* kTransferCoding = "transfer-encoding";
// Both kHTTPVersionString and kMethodString arrays are constructed to match
// the enum values defined in Version and Method of HTTPMessage.
const char* kHTTPVersionString[] = {
"",
"HTTP/0.9",
"HTTP/1.0",
"HTTP/1.1"
};
const char* kMethodString[] = {
"",
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT",
"MKCOL",
"UNLOCK",
};
// Returns true if the message represents a complete request or response.
// Messages are considered complete if:
// - Transfer-Encoding: chunked is present and message has a final chunk.
// - Content-Length header is present and matches the message body length.
// - Neither Transfer-Encoding nor Content-Length is present and message
// is tagged as complete.
bool IsCompleteMessage(const HTTPMessage& message) {
return true;
const BalsaHeaders* headers = message.headers();
StringPiece content_length = headers->GetHeader(kContentLength);
if (!content_length.empty()) {
int parsed_content_length;
if (!base::StringToInt(content_length, &parsed_content_length)) {
return false;
}
return (message.body().size() == (uint)parsed_content_length);
} else {
// Assume messages without transfer coding or content-length are
// tagged correctly.
return message.has_complete_message();
}
}
} // namespace
HTTPMessage::Method HTTPMessage::StringToMethod(StringPiece str) {
// Skip the first element of the array since it is empty string.
for (unsigned long i = 1; i < arraysize(kMethodString); ++i) {
if (strncmp(str.data(), kMethodString[i], str.length()) == 0) {
return static_cast<HTTPMessage::Method>(i);
}
}
return HttpConstants::UNKNOWN_METHOD;
}
HTTPMessage::Version HTTPMessage::StringToVersion(StringPiece str) {
// Skip the first element of the array since it is empty string.
for (unsigned long i = 1; i < arraysize(kHTTPVersionString); ++i) {
if (strncmp(str.data(), kHTTPVersionString[i], str.length()) == 0) {
return static_cast<HTTPMessage::Version>(i);
}
}
return HttpConstants::HTTP_UNKNOWN;
}
const char* HTTPMessage::MethodToString(Method method) {
CHECK_LT(static_cast<size_t>(method), arraysize(kMethodString));
return kMethodString[method];
}
const char* HTTPMessage::VersionToString(Version version) {
CHECK_LT(static_cast<size_t>(version), arraysize(kHTTPVersionString));
return kHTTPVersionString[version];
}
HTTPMessage::HTTPMessage()
: is_request_(true) {
InitializeFields();
}
HTTPMessage::HTTPMessage(Version ver, Method request, const string& path)
: is_request_(true) {
InitializeFields();
if (ver != HttpConstants::HTTP_0_9) {
headers()->SetRequestVersion(VersionToString(ver));
}
headers()->SetRequestMethod(MethodToString(request));
headers()->SetRequestUri(path);
}
HTTPMessage::~HTTPMessage() {
}
void HTTPMessage::InitializeFields() {
has_complete_message_ = true;
skip_message_validation_ = false;
}
void HTTPMessage::AddHeader(const string& header, const string& value) {
headers()->AppendHeader(header, value);
}
void HTTPMessage::RemoveHeader(const string& header) {
headers()->RemoveAllOfHeader(header);
}
void HTTPMessage::ReplaceHeader(const string& header, const string& value) {
headers()->ReplaceOrAppendHeader(header, value);
}
void HTTPMessage::AddBody(const string& body, bool add_content_length) {
body_ = body;
// Remove any transfer-encoding that was left by a previous body.
RemoveHeader(kTransferCoding);
if (add_content_length) {
ReplaceHeader(kContentLength, base::IntToString(body.size()));
} else {
RemoveHeader(kContentLength);
}
}
void HTTPMessage::ValidateMessage() const {
if (skip_message_validation_) {
return;
}
vector<StringPiece> transfer_encodings;
headers()->GetAllOfHeader(kTransferCoding, &transfer_encodings);
CHECK_GE(1ul, transfer_encodings.size());
for (vector<StringPiece>::iterator it = transfer_encodings.begin();
it != transfer_encodings.end();
++it) {
CHECK(StringPieceUtils::EqualIgnoreCase("identity", *it) ||
StringPieceUtils::EqualIgnoreCase("chunked", *it)) << *it;
}
vector<StringPiece> content_lengths;
headers()->GetAllOfHeader(kContentLength, &content_lengths);
CHECK_GE(1ul, content_lengths.size());
CHECK_EQ(has_complete_message_, IsCompleteMessage(*this));
}
} // namespace test
} // namespace tools
} // namespace net
<commit_msg>Fix an invalid early return.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/tools/quic/test_tools/http_message_test_utils.h"
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
using base::StringPiece;
using std::string;
using std::vector;
namespace net {
namespace tools {
namespace test {
namespace {
//const char* kContentEncoding = "content-encoding";
const char* kContentLength = "content-length";
const char* kTransferCoding = "transfer-encoding";
// Both kHTTPVersionString and kMethodString arrays are constructed to match
// the enum values defined in Version and Method of HTTPMessage.
const char* kHTTPVersionString[] = {
"",
"HTTP/0.9",
"HTTP/1.0",
"HTTP/1.1"
};
const char* kMethodString[] = {
"",
"OPTIONS",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT",
"MKCOL",
"UNLOCK",
};
// Returns true if the message represents a complete request or response.
// Messages are considered complete if:
// - Transfer-Encoding: chunked is present and message has a final chunk.
// - Content-Length header is present and matches the message body length.
// - Neither Transfer-Encoding nor Content-Length is present and message
// is tagged as complete.
bool IsCompleteMessage(const HTTPMessage& message) {
const BalsaHeaders* headers = message.headers();
StringPiece content_length = headers->GetHeader(kContentLength);
if (!content_length.empty()) {
int parsed_content_length;
if (!base::StringToInt(content_length, &parsed_content_length)) {
return false;
}
return (message.body().size() == (uint)parsed_content_length);
} else {
// Assume messages without transfer coding or content-length are
// tagged correctly.
return message.has_complete_message();
}
}
} // namespace
HTTPMessage::Method HTTPMessage::StringToMethod(StringPiece str) {
// Skip the first element of the array since it is empty string.
for (unsigned long i = 1; i < arraysize(kMethodString); ++i) {
if (strncmp(str.data(), kMethodString[i], str.length()) == 0) {
return static_cast<HTTPMessage::Method>(i);
}
}
return HttpConstants::UNKNOWN_METHOD;
}
HTTPMessage::Version HTTPMessage::StringToVersion(StringPiece str) {
// Skip the first element of the array since it is empty string.
for (unsigned long i = 1; i < arraysize(kHTTPVersionString); ++i) {
if (strncmp(str.data(), kHTTPVersionString[i], str.length()) == 0) {
return static_cast<HTTPMessage::Version>(i);
}
}
return HttpConstants::HTTP_UNKNOWN;
}
const char* HTTPMessage::MethodToString(Method method) {
CHECK_LT(static_cast<size_t>(method), arraysize(kMethodString));
return kMethodString[method];
}
const char* HTTPMessage::VersionToString(Version version) {
CHECK_LT(static_cast<size_t>(version), arraysize(kHTTPVersionString));
return kHTTPVersionString[version];
}
HTTPMessage::HTTPMessage()
: is_request_(true) {
InitializeFields();
}
HTTPMessage::HTTPMessage(Version ver, Method request, const string& path)
: is_request_(true) {
InitializeFields();
if (ver != HttpConstants::HTTP_0_9) {
headers()->SetRequestVersion(VersionToString(ver));
}
headers()->SetRequestMethod(MethodToString(request));
headers()->SetRequestUri(path);
}
HTTPMessage::~HTTPMessage() {
}
void HTTPMessage::InitializeFields() {
has_complete_message_ = true;
skip_message_validation_ = false;
}
void HTTPMessage::AddHeader(const string& header, const string& value) {
headers()->AppendHeader(header, value);
}
void HTTPMessage::RemoveHeader(const string& header) {
headers()->RemoveAllOfHeader(header);
}
void HTTPMessage::ReplaceHeader(const string& header, const string& value) {
headers()->ReplaceOrAppendHeader(header, value);
}
void HTTPMessage::AddBody(const string& body, bool add_content_length) {
body_ = body;
// Remove any transfer-encoding that was left by a previous body.
RemoveHeader(kTransferCoding);
if (add_content_length) {
ReplaceHeader(kContentLength, base::IntToString(body.size()));
} else {
RemoveHeader(kContentLength);
}
}
void HTTPMessage::ValidateMessage() const {
if (skip_message_validation_) {
return;
}
vector<StringPiece> transfer_encodings;
headers()->GetAllOfHeader(kTransferCoding, &transfer_encodings);
CHECK_GE(1ul, transfer_encodings.size());
for (vector<StringPiece>::iterator it = transfer_encodings.begin();
it != transfer_encodings.end();
++it) {
CHECK(StringPieceUtils::EqualIgnoreCase("identity", *it) ||
StringPieceUtils::EqualIgnoreCase("chunked", *it)) << *it;
}
vector<StringPiece> content_lengths;
headers()->GetAllOfHeader(kContentLength, &content_lengths);
CHECK_GE(1ul, content_lengths.size());
CHECK_EQ(has_complete_message_, IsCompleteMessage(*this));
}
} // namespace test
} // namespace tools
} // namespace net
<|endoftext|> |
<commit_before>// Copyright 2010-2012 Google
// 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 <math.h>
#include <string.h>
#include <algorithm>
#include "base/hash.h"
#include <string>
#include <utility>
#include <vector>
#include "base/commandlineflags.h"
#include "base/hash.h"
#include "base/int-type-indexed-vector.h"
#include "base/int-type.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/map-util.h"
#include "base/scoped_ptr.h"
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "constraint_solver/constraint_solveri.h"
#include "util/bitset.h"
#include "util/const_int_array.h"
#include "core/Solver.cc"
namespace operations_research {
namespace {
class SatPropagator : public Constraint {
public:
SatPropagator(Solver* const solver) : Constraint(solver) {}
~SatPropagator() {}
bool Check(IntExpr* const expr) const {
IntVar* expr_var = NULL;
bool expr_negated = false;
return solver()->IsBooleanVar(expr, &expr_var, &expr_negated);
}
bool Check(const std::vector<IntVar*>& vars) const {
for (int i = 0; i < vars.size(); ++i) {
if (!Check(vars[i])) {
return false;
}
}
return true;
}
Minisat::Lit Literal(IntExpr* const expr) {
IntVar* expr_var = NULL;
bool expr_negated = false;
if (!solver()->IsBooleanVar(expr, &expr_var, &expr_negated)) {
return Minisat::lit_Error;
}
if (ContainsKey(indices_, expr_var)) {
return Minisat::mkLit(indices_[expr_var], expr_negated);
} else {
const Minisat::Var var = minisat_.newVar(true, true);
vars_.push_back(expr_var);
return Minisat::mkLit(var, expr_negated);
}
}
void VariableBound(int index) {
// if (indices_[index]->Min() == 0) {
// Flip(Minisat::Var(-1 - index));
// } else {
// Flip(Minisat::Var(1 + index));
// }
}
virtual void Post() {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const d = MakeConstraintDemon1(solver(),
this,
&SatPropagator::VariableBound,
"VariableBound",
indices_[vars_[i]]);
vars_[i]->WhenDomain(d);
}
}
virtual void InitialPropagate() {
for (int i = 0; i < vars_.size(); ++i) {
IntVar* const var = vars_[i];
if (var->Bound()) {
VariableBound(indices_[var]);
}
}
}
// Add a clause to the solver.
bool AddClause (const vec<Lit>& ps) {
return minisat_.addClause(ps);
}
// Add the empty clause, making the solver contradictory.
bool AddEmptyClause() {
return minisat_.addEmptyClause();
}
// Add a unit clause to the solver.
bool AddClause (Lit p) {
return minisat_.addClause(p);
}
// Add a binary clause to the solver.
bool AddClause (Lit p, Lit q) {
return minisat_.addClause(p, q);
}
// Add a ternary clause to the solver.
bool AddClause (Lit p, Lit q, Lit r) {
return minisat_.addClause(p, q, r);
}
private:
Minisat::Solver minisat_;
std::vector<IntVar*> vars_;
hash_map<IntVar*, Minisat::Var> indices_;
};
} // namespace
bool AddBoolEq(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, right_lit);
sat->AddClause(left_lit, ~right_lit);
return true;
}
bool AddBoolLe(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, right_lit);
return true;
}
bool AddBoolNot(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, ~right_lit);
sat->AddClause(left_lit, right_lit);
return true;
}
bool AddBoolAndArrayEqVar(SatPropagator* const sat,
const std::vector<IntVar*>& vars,
IntVar* const target) {
return false;
}
bool AddBoolOrArrayEqualTrue(SatPropagator* const sat,
const std::vector<IntVar*>& vars) {
if (!sat->Check(vars)) {
return false;
}
std::vector<Minisat::Lit> atoms(vars.size());
for (int i = 0; i < vars.size(); ++i) {
atoms[i] = sat->Literal(vars[i]);
}
return false;
}
} // namespace operations_research
<commit_msg>more integration with the minisat<commit_after>// Copyright 2010-2012 Google
// 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 <math.h>
#include <string.h>
#include <algorithm>
#include "base/hash.h"
#include <string>
#include <utility>
#include <vector>
#include "base/commandlineflags.h"
#include "base/hash.h"
#include "base/int-type-indexed-vector.h"
#include "base/int-type.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/map-util.h"
#include "base/scoped_ptr.h"
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "constraint_solver/constraint_solveri.h"
#include "util/bitset.h"
#include "util/const_int_array.h"
#include "core/Solver.cc"
namespace operations_research {
namespace {
class SatPropagator : public Constraint {
public:
SatPropagator(Solver* const solver) : Constraint(solver) {}
~SatPropagator() {}
bool Check(IntExpr* const expr) const {
IntVar* expr_var = NULL;
bool expr_negated = false;
return solver()->IsBooleanVar(expr, &expr_var, &expr_negated);
}
bool Check(const std::vector<IntVar*>& vars) const {
for (int i = 0; i < vars.size(); ++i) {
if (!Check(vars[i])) {
return false;
}
}
return true;
}
Minisat::Lit Literal(IntExpr* const expr) {
IntVar* expr_var = NULL;
bool expr_negated = false;
if (!solver()->IsBooleanVar(expr, &expr_var, &expr_negated)) {
return Minisat::lit_Error;
}
if (ContainsKey(indices_, expr_var)) {
return Minisat::mkLit(indices_[expr_var], expr_negated);
} else {
const Minisat::Var var = minisat_.newVar(true, true);
vars_.push_back(expr_var);
return Minisat::mkLit(var, expr_negated);
}
}
void VariableBound(int index) {
// if (indices_[index]->Min() == 0) {
// Flip(Minisat::Var(-1 - index));
// } else {
// Flip(Minisat::Var(1 + index));
// }
}
virtual void Post() {
for (int i = 0; i < vars_.size(); ++i) {
Demon* const d = MakeConstraintDemon1(solver(),
this,
&SatPropagator::VariableBound,
"VariableBound",
indices_[vars_[i]]);
vars_[i]->WhenDomain(d);
}
}
virtual void InitialPropagate() {
for (int i = 0; i < vars_.size(); ++i) {
IntVar* const var = vars_[i];
if (var->Bound()) {
VariableBound(indices_[var]);
}
}
}
// Add a clause to the solver.
bool AddClause (const vec<Lit>& ps) {
return minisat_.addClause(ps);
}
// Add the empty clause, making the solver contradictory.
bool AddEmptyClause() {
return minisat_.addEmptyClause();
}
// Add a unit clause to the solver.
bool AddClause (Lit p) {
return minisat_.addClause(p);
}
// Add a binary clause to the solver.
bool AddClause (Lit p, Lit q) {
return minisat_.addClause(p, q);
}
// Add a ternary clause to the solver.
bool AddClause (Lit p, Lit q, Lit r) {
return minisat_.addClause(p, q, r);
}
private:
Minisat::Solver minisat_;
std::vector<IntVar*> vars_;
hash_map<IntVar*, Minisat::Var> indices_;
};
} // namespace
bool AddBoolEq(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, right_lit);
sat->AddClause(left_lit, ~right_lit);
return true;
}
bool AddBoolLe(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, right_lit);
return true;
}
bool AddBoolNot(SatPropagator* const sat,
IntExpr* const left,
IntExpr* const right) {
if (!sat->Check(left) || !sat->Check(right)) {
return false;
}
Minisat::Lit left_lit = sat->Literal(left);
Minisat::Lit right_lit = sat->Literal(right);
sat->AddClause(~left_lit, ~right_lit);
sat->AddClause(left_lit, right_lit);
return true;
}
bool AddBoolAndArrayEqVar(SatPropagator* const sat,
const std::vector<IntVar*>& vars,
IntVar* const target) {
return false;
if (!sat->Check(vars) || !sat->Check(target)) {
return false;
}
Minisat::Lit target_lit = sat->Literal(target);
std::vector<Minisat::Lit> lits(vars.size() + 1);
for (int i = 0; i < vars.size(); ++i) {
lits[i] = sat->Literal(vars[i]);
}
lits[vars.size()] = ~target_lit;
sat->AddClause(lits);
}
bool AddBoolOrArrayEqualTrue(SatPropagator* const sat,
const std::vector<IntVar*>& vars) {
if (!sat->Check(vars)) {
return false;
}
std::vector<Minisat::Lit> lits(vars.size());
for (int i = 0; i < vars.size(); ++i) {
lits[i] = sat->Literal(vars[i]);
}
sat->AddClause(lits);
return false;
}
bool AddBoolAndArrayEqualFalse(SatPropagator* const sat,
const std::vector<IntVar*>& vars) {
if (!sat->Check(vars)) {
return false;
}
std::vector<Minisat::Lit> lits(vars.size());
for (int i = 0; i < vars.size(); ++i) {
lits[i] = ~sat->Literal(vars[i]);
}
sat->AddClause(lits);
return false;
}
} // namespace operations_research
<|endoftext|> |
<commit_before>#ifndef TURBO_CONTAINER_SPSC_RING_QUEUE_HPP
#define TURBO_CONTAINER_SPSC_RING_QUEUE_HPP
#include <cstdint>
#include <array>
#include <atomic>
#include <functional>
#include <memory>
#include <vector>
#include <turbo/toolset/attribute.hpp>
namespace turbo {
namespace container {
template <class value_t, class allocator_t = std::allocator<value_t>> class spsc_key;
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_producer
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_key<value_t, allocator_t> key;
enum class result
{
success,
queue_full
};
spsc_producer(const key&,
std::vector<value_t, allocator_t>& buffer,
std::atomic<uint32_t>& head,
std::atomic<uint32_t>& tail);
result try_enqueue_copy(const value_t& input);
result try_enqueue_move(value_t&& input);
private:
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<value_t, allocator_t>& buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t>& head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t>& tail_;
};
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_consumer
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_key<value_t, allocator_t> key;
spsc_consumer(const key&,
std::vector<value_t, allocator_t>& buffer,
std::atomic<uint32_t>& head,
std::atomic<uint32_t>& tail);
enum class result
{
success,
queue_empty
};
result try_dequeue_copy(value_t& output);
result try_dequeue_move(value_t& output);
private:
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<value_t, allocator_t>& buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t>& head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t>& tail_;
};
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_ring_queue
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_producer<value_t, allocator_t> producer;
typedef spsc_consumer<value_t, allocator_t> consumer;
spsc_ring_queue(uint32_t capacity);
producer& get_producer() { return producer_; }
consumer& get_consumer() { return consumer_; }
private:
typedef std::vector<value_t, allocator_t> vector_type;
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<value_t, allocator_t> buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> tail_;
producer producer_;
consumer consumer_;
};
} // namespace container
} // namespace turbo
#endif
<commit_msg>only the producer and consumer objects need alignment, the private fields within them do not require it<commit_after>#ifndef TURBO_CONTAINER_SPSC_RING_QUEUE_HPP
#define TURBO_CONTAINER_SPSC_RING_QUEUE_HPP
#include <cstdint>
#include <atomic>
#include <functional>
#include <memory>
#include <vector>
#include <turbo/toolset/attribute.hpp>
namespace turbo {
namespace container {
template <class value_t, class allocator_t = std::allocator<value_t>> class spsc_key;
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_producer
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_key<value_t, allocator_t> key;
enum class result
{
success,
queue_full
};
spsc_producer(const key&,
std::vector<value_t, allocator_t>& buffer,
std::atomic<uint32_t>& head,
std::atomic<uint32_t>& tail);
result try_enqueue_copy(const value_t& input);
result try_enqueue_move(value_t&& input);
private:
std::vector<value_t, allocator_t>& buffer_;
std::atomic<uint32_t>& head_;
std::atomic<uint32_t>& tail_;
};
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_consumer
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_key<value_t, allocator_t> key;
spsc_consumer(const key&,
std::vector<value_t, allocator_t>& buffer,
std::atomic<uint32_t>& head,
std::atomic<uint32_t>& tail);
enum class result
{
success,
queue_empty
};
result try_dequeue_copy(value_t& output);
result try_dequeue_move(value_t& output);
private:
std::vector<value_t, allocator_t>& buffer_;
std::atomic<uint32_t>& head_;
std::atomic<uint32_t>& tail_;
};
template <class value_t, class allocator_t = std::allocator<value_t>>
class spsc_ring_queue
{
public:
typedef value_t value_type;
typedef allocator_t allocator_type;
typedef spsc_producer<value_t, allocator_t> producer;
typedef spsc_consumer<value_t, allocator_t> consumer;
spsc_ring_queue(uint32_t capacity);
producer& get_producer() { return producer_; }
consumer& get_consumer() { return consumer_; }
private:
typedef std::vector<value_t, allocator_t> vector_type;
alignas(LEVEL1_DCACHE_LINESIZE) std::vector<value_t, allocator_t> buffer_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> head_;
alignas(LEVEL1_DCACHE_LINESIZE) std::atomic<uint32_t> tail_;
alignas(LEVEL1_DCACHE_LINESIZE) producer producer_;
alignas(LEVEL1_DCACHE_LINESIZE) consumer consumer_;
};
} // namespace container
} // namespace turbo
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <climits>
#include <cstddef>
#include <cmath>
#include <uavcan/build_config.hpp>
#ifndef UAVCAN_CPP_VERSION
# error UAVCAN_CPP_VERSION
#endif
#if UAVCAN_CPP_VERSION < UAVCAN_CPP11
# include <float.h> // cfloat may not be available
#else
# include <cfloat> // C++11 mode assumes that all standard headers are available
#endif
namespace uavcan
{
/**
* Usage:
* StaticAssert<expression>::check();
*/
template <bool Value>
struct UAVCAN_EXPORT StaticAssert;
template <>
struct UAVCAN_EXPORT StaticAssert<true>
{
static void check() { }
};
/**
* Usage:
* ShowIntegerAsError<integer_expression>::foobar();
*/
template <long N> struct ShowIntegerAsError;
/**
* Prevents copying when inherited
*/
class UAVCAN_EXPORT Noncopyable
{
Noncopyable(const Noncopyable&);
Noncopyable& operator=(const Noncopyable&);
protected:
Noncopyable() { }
~Noncopyable() { }
};
/**
* Compile time conditions
*/
template <bool B, typename T = void>
struct UAVCAN_EXPORT EnableIf { };
template <typename T>
struct UAVCAN_EXPORT EnableIf<true, T>
{
typedef T Type;
};
/**
* Lightweight type categorization.
*/
template <typename T, typename R = void>
struct UAVCAN_EXPORT EnableIfType
{
typedef R Type;
};
/**
* Compile-time type selection (Alexandrescu)
*/
template <bool Condition, typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select;
template <typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select<true, TrueType, FalseType>
{
typedef TrueType Result;
};
template <typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select<false, TrueType, FalseType>
{
typedef FalseType Result;
};
/**
* Remove reference as in <type_traits>
*/
template <class T> struct RemoveReference { typedef T Type; };
template <class T> struct RemoveReference<T&> { typedef T Type; };
#if UAVCAN_CPP_VERSION > UAVCAN_CPP03
template <class T> struct RemoveReference<T&&> { typedef T Type; };
#endif
/**
* Value types
*/
template <bool> struct UAVCAN_EXPORT BooleanType { };
typedef BooleanType<true> TrueType;
typedef BooleanType<false> FalseType;
/**
* Relations
*/
template <typename T1, typename T2>
class UAVCAN_EXPORT IsImplicitlyConvertibleFromTo
{
template <typename U> static U returner();
struct True_ { char x[2]; };
struct False_ { };
static True_ test(const T2 &);
static False_ test(...);
public:
enum { Result = sizeof(True_) == sizeof(IsImplicitlyConvertibleFromTo<T1, T2>::test(returner<T1>())) };
};
/**
* try_implicit_cast<>(From)
* try_implicit_cast<>(From, To)
* @{
*/
template <typename From, typename To>
struct UAVCAN_EXPORT TryImplicitCastImpl
{
static To impl(const From& from, const To&, TrueType) { return To(from); }
static To impl(const From&, const To& default_, FalseType) { return default_; }
};
/**
* If possible, performs an implicit cast from the type From to the type To.
* If the cast is not possible, returns default_ of type To.
*/
template <typename To, typename From>
UAVCAN_EXPORT
To try_implicit_cast(const From& from, const To& default_)
{
return TryImplicitCastImpl<From, To>::impl(from, default_,
BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>());
}
/**
* If possible, performs an implicit cast from the type From to the type To.
* If the cast is not possible, returns a default constructed object of the type To.
*/
template <typename To, typename From>
UAVCAN_EXPORT
To try_implicit_cast(const From& from)
{
return TryImplicitCastImpl<From, To>::impl(from, To(),
BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>());
}
/**
* @}
*/
/**
* Compile time square root for integers.
* Useful for operations on square matrices.
*/
template <unsigned Value> struct UAVCAN_EXPORT CompileTimeIntSqrt;
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<4> { enum { Result = 2 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<9> { enum { Result = 3 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<16> { enum { Result = 4 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<25> { enum { Result = 5 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<36> { enum { Result = 6 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<49> { enum { Result = 7 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<64> { enum { Result = 8 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<81> { enum { Result = 9 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<100> { enum { Result = 10 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<121> { enum { Result = 11 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<144> { enum { Result = 12 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<169> { enum { Result = 13 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<196> { enum { Result = 14 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<225> { enum { Result = 15 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<256> { enum { Result = 16 }; };
/**
* Replacement for std::copy(..)
*/
template <typename InputIt, typename OutputIt>
UAVCAN_EXPORT
OutputIt copy(InputIt first, InputIt last, OutputIt result)
{
while (first != last)
{
*result = *first;
++first;
++result;
}
return result;
}
/**
* Replacement for std::fill(..)
*/
template <typename ForwardIt, typename T>
UAVCAN_EXPORT
void fill(ForwardIt first, ForwardIt last, const T& value)
{
while (first != last)
{
*first = value;
++first;
}
}
/**
* Replacement for std::fill_n(..)
*/
template<typename OutputIt, typename T>
UAVCAN_EXPORT
void fill_n(OutputIt first, std::size_t n, const T& value)
{
while (n--)
{
*first++ = value;
}
}
/**
* Replacement for std::min(..)
*/
template <typename T>
UAVCAN_EXPORT
const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
/**
* Replacement for std::max(..)
*/
template <typename T>
UAVCAN_EXPORT
const T& max(const T& a, const T& b)
{
return (a < b) ? b : a;
}
/**
* Replacement for std::lexicographical_compare(..)
*/
template<typename InputIt1, typename InputIt2>
UAVCAN_EXPORT
bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2)
{
while ((first1 != last1) && (first2 != last2))
{
if (*first1 < *first2)
{
return true;
}
if (*first2 < *first1)
{
return false;
}
++first1;
++first2;
}
return (first1 == last1) && (first2 != last2);
}
/**
* Replacement for std::equal(..)
*/
template<typename InputIt1, typename InputIt2>
UAVCAN_EXPORT
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2)
{
while (first1 != last1)
{
if (*first1 != *first2)
{
return false;
}
++first1;
++first2;
}
return true;
}
/**
* Numeric traits, like std::numeric_limits<>
*/
template <typename T>
struct UAVCAN_EXPORT NumericTraits;
/// char
template <>
struct UAVCAN_EXPORT NumericTraits<char>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static char max() { return CHAR_MAX; }
static char min() { return CHAR_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<signed char>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static signed char max() { return SCHAR_MAX; }
static signed char min() { return SCHAR_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned char>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned char max() { return UCHAR_MAX; }
static unsigned char min() { return 0; }
};
/// short
template <>
struct UAVCAN_EXPORT NumericTraits<short>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static short max() { return SHRT_MAX; }
static short min() { return SHRT_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned short>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned short max() { return USHRT_MAX; }
static unsigned short min() { return 0; }
};
/// int
template <>
struct UAVCAN_EXPORT NumericTraits<int>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static int max() { return INT_MAX; }
static int min() { return INT_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned int>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned int max() { return UINT_MAX; }
static unsigned int min() { return 0; }
};
/// long
template <>
struct UAVCAN_EXPORT NumericTraits<long>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static long max() { return LONG_MAX; }
static long min() { return LONG_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned long>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned long max() { return ULONG_MAX; }
static unsigned long min() { return 0; }
};
/// long long
template <>
struct UAVCAN_EXPORT NumericTraits<long long>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static long long max() { return LLONG_MAX; }
static long long min() { return LLONG_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned long long>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned long long max() { return ULLONG_MAX; }
static unsigned long long min() { return 0; }
};
/// float
template <>
struct UAVCAN_EXPORT NumericTraits<float>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static float max() { return FLT_MAX; }
static float min() { return FLT_MIN; }
static float infinity() { return INFINITY; }
static float epsilon() { return FLT_EPSILON; }
};
/// double
template <>
struct UAVCAN_EXPORT NumericTraits<double>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static double max() { return DBL_MAX; }
static double min() { return DBL_MIN; }
static double infinity() { return static_cast<double>(INFINITY) * static_cast<double>(INFINITY); }
static double epsilon() { return DBL_EPSILON; }
};
#if defined(LDBL_MAX) && defined(LDBL_MIN) && defined(LDBL_EPSILON)
/// long double
template <>
struct UAVCAN_EXPORT NumericTraits<long double>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static long double max() { return LDBL_MAX; }
static long double min() { return LDBL_MIN; }
static long double infinity() { return static_cast<long double>(INFINITY) * static_cast<long double>(INFINITY); }
static long double epsilon() { return LDBL_EPSILON; }
};
#endif
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
# undef isnan
# undef isinf
# undef signbit
#endif
/**
* Replacement for std::isnan().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool isNaN(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::isnan(arg);
#else
// coverity[same_on_both_sides : FALSE]
// cppcheck-suppress duplicateExpression
return !(arg <= arg);
#endif
}
/**
* Replacement for std::isinf().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool isInfinity(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::isinf(arg);
#else
return (arg >= NumericTraits<T>::infinity()) || (arg <= -NumericTraits<T>::infinity());
#endif
}
/**
* Replacement for std::signbit().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool getSignBit(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::signbit(arg);
#else
return arg < T(0) || (((arg <= T(0)) && (arg >= T(0))) && (T(1) / arg < T(0)));
#endif
}
}
<commit_msg>Added IntToType<><commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#pragma once
#include <climits>
#include <cstddef>
#include <cmath>
#include <uavcan/build_config.hpp>
#ifndef UAVCAN_CPP_VERSION
# error UAVCAN_CPP_VERSION
#endif
#if UAVCAN_CPP_VERSION < UAVCAN_CPP11
# include <float.h> // cfloat may not be available
#else
# include <cfloat> // C++11 mode assumes that all standard headers are available
#endif
namespace uavcan
{
/**
* Usage:
* StaticAssert<expression>::check();
*/
template <bool Value>
struct UAVCAN_EXPORT StaticAssert;
template <>
struct UAVCAN_EXPORT StaticAssert<true>
{
static void check() { }
};
/**
* Usage:
* ShowIntegerAsError<integer_expression>::foobar();
*/
template <long N> struct ShowIntegerAsError;
/**
* Prevents copying when inherited
*/
class UAVCAN_EXPORT Noncopyable
{
Noncopyable(const Noncopyable&);
Noncopyable& operator=(const Noncopyable&);
protected:
Noncopyable() { }
~Noncopyable() { }
};
/**
* Compile time conditions
*/
template <bool B, typename T = void>
struct UAVCAN_EXPORT EnableIf { };
template <typename T>
struct UAVCAN_EXPORT EnableIf<true, T>
{
typedef T Type;
};
/**
* Lightweight type categorization.
*/
template <typename T, typename R = void>
struct UAVCAN_EXPORT EnableIfType
{
typedef R Type;
};
/**
* Compile-time type selection (Alexandrescu)
*/
template <bool Condition, typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select;
template <typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select<true, TrueType, FalseType>
{
typedef TrueType Result;
};
template <typename TrueType, typename FalseType>
struct UAVCAN_EXPORT Select<false, TrueType, FalseType>
{
typedef FalseType Result;
};
/**
* Remove reference as in <type_traits>
*/
template <class T> struct RemoveReference { typedef T Type; };
template <class T> struct RemoveReference<T&> { typedef T Type; };
#if UAVCAN_CPP_VERSION > UAVCAN_CPP03
template <class T> struct RemoveReference<T&&> { typedef T Type; };
#endif
/**
* Value types
*/
template <bool> struct UAVCAN_EXPORT BooleanType { };
typedef BooleanType<true> TrueType;
typedef BooleanType<false> FalseType;
template <int N> struct IntToType { };
/**
* Relations
*/
template <typename T1, typename T2>
class UAVCAN_EXPORT IsImplicitlyConvertibleFromTo
{
template <typename U> static U returner();
struct True_ { char x[2]; };
struct False_ { };
static True_ test(const T2 &);
static False_ test(...);
public:
enum { Result = sizeof(True_) == sizeof(IsImplicitlyConvertibleFromTo<T1, T2>::test(returner<T1>())) };
};
/**
* try_implicit_cast<>(From)
* try_implicit_cast<>(From, To)
* @{
*/
template <typename From, typename To>
struct UAVCAN_EXPORT TryImplicitCastImpl
{
static To impl(const From& from, const To&, TrueType) { return To(from); }
static To impl(const From&, const To& default_, FalseType) { return default_; }
};
/**
* If possible, performs an implicit cast from the type From to the type To.
* If the cast is not possible, returns default_ of type To.
*/
template <typename To, typename From>
UAVCAN_EXPORT
To try_implicit_cast(const From& from, const To& default_)
{
return TryImplicitCastImpl<From, To>::impl(from, default_,
BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>());
}
/**
* If possible, performs an implicit cast from the type From to the type To.
* If the cast is not possible, returns a default constructed object of the type To.
*/
template <typename To, typename From>
UAVCAN_EXPORT
To try_implicit_cast(const From& from)
{
return TryImplicitCastImpl<From, To>::impl(from, To(),
BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>());
}
/**
* @}
*/
/**
* Compile time square root for integers.
* Useful for operations on square matrices.
*/
template <unsigned Value> struct UAVCAN_EXPORT CompileTimeIntSqrt;
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<4> { enum { Result = 2 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<9> { enum { Result = 3 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<16> { enum { Result = 4 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<25> { enum { Result = 5 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<36> { enum { Result = 6 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<49> { enum { Result = 7 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<64> { enum { Result = 8 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<81> { enum { Result = 9 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<100> { enum { Result = 10 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<121> { enum { Result = 11 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<144> { enum { Result = 12 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<169> { enum { Result = 13 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<196> { enum { Result = 14 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<225> { enum { Result = 15 }; };
template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<256> { enum { Result = 16 }; };
/**
* Replacement for std::copy(..)
*/
template <typename InputIt, typename OutputIt>
UAVCAN_EXPORT
OutputIt copy(InputIt first, InputIt last, OutputIt result)
{
while (first != last)
{
*result = *first;
++first;
++result;
}
return result;
}
/**
* Replacement for std::fill(..)
*/
template <typename ForwardIt, typename T>
UAVCAN_EXPORT
void fill(ForwardIt first, ForwardIt last, const T& value)
{
while (first != last)
{
*first = value;
++first;
}
}
/**
* Replacement for std::fill_n(..)
*/
template<typename OutputIt, typename T>
UAVCAN_EXPORT
void fill_n(OutputIt first, std::size_t n, const T& value)
{
while (n--)
{
*first++ = value;
}
}
/**
* Replacement for std::min(..)
*/
template <typename T>
UAVCAN_EXPORT
const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
/**
* Replacement for std::max(..)
*/
template <typename T>
UAVCAN_EXPORT
const T& max(const T& a, const T& b)
{
return (a < b) ? b : a;
}
/**
* Replacement for std::lexicographical_compare(..)
*/
template<typename InputIt1, typename InputIt2>
UAVCAN_EXPORT
bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2)
{
while ((first1 != last1) && (first2 != last2))
{
if (*first1 < *first2)
{
return true;
}
if (*first2 < *first1)
{
return false;
}
++first1;
++first2;
}
return (first1 == last1) && (first2 != last2);
}
/**
* Replacement for std::equal(..)
*/
template<typename InputIt1, typename InputIt2>
UAVCAN_EXPORT
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2)
{
while (first1 != last1)
{
if (*first1 != *first2)
{
return false;
}
++first1;
++first2;
}
return true;
}
/**
* Numeric traits, like std::numeric_limits<>
*/
template <typename T>
struct UAVCAN_EXPORT NumericTraits;
/// char
template <>
struct UAVCAN_EXPORT NumericTraits<char>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static char max() { return CHAR_MAX; }
static char min() { return CHAR_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<signed char>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static signed char max() { return SCHAR_MAX; }
static signed char min() { return SCHAR_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned char>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned char max() { return UCHAR_MAX; }
static unsigned char min() { return 0; }
};
/// short
template <>
struct UAVCAN_EXPORT NumericTraits<short>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static short max() { return SHRT_MAX; }
static short min() { return SHRT_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned short>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned short max() { return USHRT_MAX; }
static unsigned short min() { return 0; }
};
/// int
template <>
struct UAVCAN_EXPORT NumericTraits<int>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static int max() { return INT_MAX; }
static int min() { return INT_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned int>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned int max() { return UINT_MAX; }
static unsigned int min() { return 0; }
};
/// long
template <>
struct UAVCAN_EXPORT NumericTraits<long>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static long max() { return LONG_MAX; }
static long min() { return LONG_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned long>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned long max() { return ULONG_MAX; }
static unsigned long min() { return 0; }
};
/// long long
template <>
struct UAVCAN_EXPORT NumericTraits<long long>
{
enum { IsSigned = 1 };
enum { IsInteger = 1 };
static long long max() { return LLONG_MAX; }
static long long min() { return LLONG_MIN; }
};
template <>
struct UAVCAN_EXPORT NumericTraits<unsigned long long>
{
enum { IsSigned = 0 };
enum { IsInteger = 1 };
static unsigned long long max() { return ULLONG_MAX; }
static unsigned long long min() { return 0; }
};
/// float
template <>
struct UAVCAN_EXPORT NumericTraits<float>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static float max() { return FLT_MAX; }
static float min() { return FLT_MIN; }
static float infinity() { return INFINITY; }
static float epsilon() { return FLT_EPSILON; }
};
/// double
template <>
struct UAVCAN_EXPORT NumericTraits<double>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static double max() { return DBL_MAX; }
static double min() { return DBL_MIN; }
static double infinity() { return static_cast<double>(INFINITY) * static_cast<double>(INFINITY); }
static double epsilon() { return DBL_EPSILON; }
};
#if defined(LDBL_MAX) && defined(LDBL_MIN) && defined(LDBL_EPSILON)
/// long double
template <>
struct UAVCAN_EXPORT NumericTraits<long double>
{
enum { IsSigned = 1 };
enum { IsInteger = 0 };
static long double max() { return LDBL_MAX; }
static long double min() { return LDBL_MIN; }
static long double infinity() { return static_cast<long double>(INFINITY) * static_cast<long double>(INFINITY); }
static long double epsilon() { return LDBL_EPSILON; }
};
#endif
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
# undef isnan
# undef isinf
# undef signbit
#endif
/**
* Replacement for std::isnan().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool isNaN(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::isnan(arg);
#else
// coverity[same_on_both_sides : FALSE]
// cppcheck-suppress duplicateExpression
return !(arg <= arg);
#endif
}
/**
* Replacement for std::isinf().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool isInfinity(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::isinf(arg);
#else
return (arg >= NumericTraits<T>::infinity()) || (arg <= -NumericTraits<T>::infinity());
#endif
}
/**
* Replacement for std::signbit().
* Note that direct float comparison (==, !=) is intentionally avoided.
*/
template <typename T>
inline bool getSignBit(T arg)
{
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
return std::signbit(arg);
#else
return arg < T(0) || (((arg <= T(0)) && (arg >= T(0))) && (T(1) / arg < T(0)));
#endif
}
}
<|endoftext|> |
<commit_before>#include <FWApplication.h>
#include <Dialog.h>
#include <GridView.h>
#include <TableLayout.h>
#include <PlatformThread.h>
#include <SysEvent.h>
#include <LinearLayout.h>
#include <FrameLayout.h>
#include <TextLabel.h>
#include <TextField.h>
#include <Button.h>
using namespace std;
class AppMessageDialog : public Dialog {
public:
AppMessageDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
addChild(mainLayout);
auto dialogMessage = make_shared<TextLabel>(message);
mainLayout->addChild(dialogMessage);
mainLayout->style("margin-left", "8");
mainLayout->style("margin-right", "8");
auto okButton = std::make_shared<Button>("OK");
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "8");
okButton->style("margin-right", "8");
okButton->style("margin-bottom", "2");
mainLayout->addChild(okButton);
}
bool isA(const std::string & className) const override {
if (className == "AppMessageDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
endModal();
}
};
class AppInputDialog : public Dialog {
public:
AppInputDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto topLayout = make_shared<FrameLayout>();
addChild(topLayout);
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
mainLayout->style("background-color", "#ffffff");
mainLayout->style("margin", 4);
topLayout->addChild(mainLayout);
// auto dialogTitle = std::make_shared<TextLabel>(title);
// dialogTitle->style("background-color", "#ffffff");
// dialogTitle->style("width", "match-parent");
// dialogTitle->style("gravity", "center-horizontal");
// dialogTitle->style("height", "wrap-content");
// dialogTitle->style("font-size", "24");
// dialogTitle->style("padding-top", "12");
// dialogTitle->style("padding-bottom", "16");
// dialogTitle->style("font-weight", "bold");
// dialogTitle->style("padding-left", "14");
// dialogTitle->style("padding-right", "14");
// dialogTitle->style("color", "#c1272d");
// mainLayout->addChild(dialogTitle);
auto dialogMessage = make_shared<TextLabel>(message);
dialogMessage->style("padding", "14");
mainLayout->addChild(dialogMessage);
textField = make_shared<TextField>();
textField->style("width", "match-parent");
textField->style("min-width", "100");
textField->style("padding-bottom", "10");
textField->style("padding-top", "10");
textField->style("hint", "Enter code here");
textField->style("padding-left", "14");
textField->style("margin-bottom", 4);
mainLayout->addChild(textField);
auto buttonLayout = make_shared<LinearLayout>(2);
auto okButton = std::make_shared<Button>("OK", 1);
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "4");
okButton->style("margin-right", "2");
okButton->style("margin-bottom", "4");
buttonLayout->addChild(okButton);
auto cancelButton = std::make_shared<Button>("Cancel", 2);
cancelButton->style("width", "match-parent");
cancelButton->style("height", "match-parent");
cancelButton->style("color", "#ffffff");
cancelButton->style("background", "#c1272d");
cancelButton->style("border-radius", "4");
cancelButton->style("weight", "1");
cancelButton->style("margin-left", "4");
cancelButton->style("margin-right", "2");
cancelButton->style("margin-bottom", "4");
buttonLayout->addChild(cancelButton);
mainLayout->addChild(buttonLayout);
}
bool isA(const std::string & className) const override {
if (className == "AppInputDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
if (ev.getElementId() == 1) {
endModal(1);
} else if (ev.getElementId() == 2) {
endModal(0);
}
}
const std::string & getValue() { return textField->getValue(); }
private:
std::shared_ptr<TextField> textField;
};
class DebugDialog : public Dialog {
public:
DebugDialog() : Dialog("Debug") {
auto mainLayout = make_shared<LinearLayout>(FW_VERTICAL);
addChild(mainLayout);
mainLayout->addChild(make_shared<TextLabel>("Debug screen")).style("font-size", "14")
.style("white-space", "nowrap")
.style("margin", 5);
mainLayout->addChild(make_shared<TextLabel>("Stuff")).style("font-size", "12").style("margin", 5);
auto table = make_shared<TableLayout>(2);
table->style("margin", 5);
mainLayout->addChild(table);
mainLayout->addChild(make_shared<TextLabel>("Threads")).style("font-size", "12").style("margin", 5);
auto grid = make_shared<GridView>();
grid->style("margin", 5);
grid->addColumn("Runnable");
grid->addColumn("State");
mainLayout->addChild(grid);
}
void load() {
auto & grid = find("GridView").front();
populateThreads(dynamic_cast<GridView&>(grid), getThread());
}
protected:
void populateThreads(GridView & grid, PlatformThread & thread) {
string runnable_name, runnable_status;
auto runnable = thread.getRunnablePtr();
if (runnable) {
runnable_name = runnable->getName();
runnable_status = runnable->getStatusText();
}
grid.setValue(numThreadRows, 0, runnable_name);
grid.setValue(numThreadRows, 1, runnable_status);
numThreadRows++;
for (auto & td : thread.getSubThreads()) {
populateThreads(grid, *td.second);
}
}
private:
int numThreadRows = 0;
};
void
FWApplication::onSysEvent(SysEvent & ev) {
if (ev.getType() == SysEvent::BACK) {
int poppedView = popViewBackHistory();
if (poppedView != 0) {
Command c(Command::SET_INT_VALUE, poppedView);
c.setValue(3);
sendCommand(c);
} else {
Command c(Command::QUIT_APP, poppedView);
sendCommand(c);
}
} else if (ev.getType() == SysEvent::SHOW_DEBUG) {
auto dialog = make_shared<DebugDialog>();
dialog->showModal(this);
}
}
void
FWApplication::showMessageDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppMessageDialog>(title, message);
dialog->showModal(this);
}
std::string
FWApplication::showInputDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppInputDialog>(title, message);
if (dialog->showModal(this)) {
return dialog->getValue();
} else {
return "";
}
}
<commit_msg>fix back behaviour for iOS<commit_after>#include <FWApplication.h>
#include <Dialog.h>
#include <GridView.h>
#include <TableLayout.h>
#include <PlatformThread.h>
#include <SysEvent.h>
#include <LinearLayout.h>
#include <FrameLayout.h>
#include <TextLabel.h>
#include <TextField.h>
#include <Button.h>
using namespace std;
class AppMessageDialog : public Dialog {
public:
AppMessageDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
addChild(mainLayout);
auto dialogMessage = make_shared<TextLabel>(message);
mainLayout->addChild(dialogMessage);
mainLayout->style("margin-left", "8");
mainLayout->style("margin-right", "8");
auto okButton = std::make_shared<Button>("OK");
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "8");
okButton->style("margin-right", "8");
okButton->style("margin-bottom", "2");
mainLayout->addChild(okButton);
}
bool isA(const std::string & className) const override {
if (className == "AppMessageDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
endModal();
}
};
class AppInputDialog : public Dialog {
public:
AppInputDialog(const std::string & title, const std::string & message) : Dialog(title) {
style("height", "wrap-content");
auto topLayout = make_shared<FrameLayout>();
addChild(topLayout);
auto mainLayout = make_shared<LinearLayout>(1);
mainLayout->style("width", "match-parent");
mainLayout->style("height", "wrap-content");
mainLayout->style("background-color", "#ffffff");
mainLayout->style("margin", 4);
topLayout->addChild(mainLayout);
// auto dialogTitle = std::make_shared<TextLabel>(title);
// dialogTitle->style("background-color", "#ffffff");
// dialogTitle->style("width", "match-parent");
// dialogTitle->style("gravity", "center-horizontal");
// dialogTitle->style("height", "wrap-content");
// dialogTitle->style("font-size", "24");
// dialogTitle->style("padding-top", "12");
// dialogTitle->style("padding-bottom", "16");
// dialogTitle->style("font-weight", "bold");
// dialogTitle->style("padding-left", "14");
// dialogTitle->style("padding-right", "14");
// dialogTitle->style("color", "#c1272d");
// mainLayout->addChild(dialogTitle);
auto dialogMessage = make_shared<TextLabel>(message);
dialogMessage->style("padding", "14");
mainLayout->addChild(dialogMessage);
textField = make_shared<TextField>();
textField->style("width", "match-parent");
textField->style("min-width", "100");
textField->style("padding-bottom", "10");
textField->style("padding-top", "10");
textField->style("hint", "Enter code here");
textField->style("padding-left", "14");
textField->style("margin-bottom", 4);
mainLayout->addChild(textField);
auto buttonLayout = make_shared<LinearLayout>(2);
auto okButton = std::make_shared<Button>("OK", 1);
okButton->style("width", "match-parent");
okButton->style("height", "match-parent");
okButton->style("color", "#ffffff");
okButton->style("background", "#c1272d");
okButton->style("border-radius", "4");
okButton->style("weight", "1");
okButton->style("margin-left", "4");
okButton->style("margin-right", "2");
okButton->style("margin-bottom", "4");
buttonLayout->addChild(okButton);
auto cancelButton = std::make_shared<Button>("Cancel", 2);
cancelButton->style("width", "match-parent");
cancelButton->style("height", "match-parent");
cancelButton->style("color", "#ffffff");
cancelButton->style("background", "#c1272d");
cancelButton->style("border-radius", "4");
cancelButton->style("weight", "1");
cancelButton->style("margin-left", "4");
cancelButton->style("margin-right", "2");
cancelButton->style("margin-bottom", "4");
buttonLayout->addChild(cancelButton);
mainLayout->addChild(buttonLayout);
}
bool isA(const std::string & className) const override {
if (className == "AppInputDialog") return true;
return Dialog::isA(className);
}
void onCommandEvent(CommandEvent & ev) override {
if (ev.getElementId() == 1) {
endModal(1);
} else if (ev.getElementId() == 2) {
endModal(0);
}
}
const std::string & getValue() { return textField->getValue(); }
private:
std::shared_ptr<TextField> textField;
};
class DebugDialog : public Dialog {
public:
DebugDialog() : Dialog("Debug") {
auto mainLayout = make_shared<LinearLayout>(FW_VERTICAL);
addChild(mainLayout);
mainLayout->addChild(make_shared<TextLabel>("Debug screen")).style("font-size", "14")
.style("white-space", "nowrap")
.style("margin", 5);
mainLayout->addChild(make_shared<TextLabel>("Stuff")).style("font-size", "12").style("margin", 5);
auto table = make_shared<TableLayout>(2);
table->style("margin", 5);
mainLayout->addChild(table);
mainLayout->addChild(make_shared<TextLabel>("Threads")).style("font-size", "12").style("margin", 5);
auto grid = make_shared<GridView>();
grid->style("margin", 5);
grid->addColumn("Runnable");
grid->addColumn("State");
mainLayout->addChild(grid);
}
void load() {
auto & grid = find("GridView").front();
populateThreads(dynamic_cast<GridView&>(grid), getThread());
}
protected:
void populateThreads(GridView & grid, PlatformThread & thread) {
string runnable_name, runnable_status;
auto runnable = thread.getRunnablePtr();
if (runnable) {
runnable_name = runnable->getName();
runnable_status = runnable->getStatusText();
}
grid.setValue(numThreadRows, 0, runnable_name);
grid.setValue(numThreadRows, 1, runnable_status);
numThreadRows++;
for (auto & td : thread.getSubThreads()) {
populateThreads(grid, *td.second);
}
}
private:
int numThreadRows = 0;
};
void
FWApplication::onSysEvent(SysEvent & ev) {
if (ev.getType() == SysEvent::BACK) {
int poppedView = popViewBackHistory();
if (poppedView != 0) {
#ifdef __ANDROID__
Command c(Command::SET_INT_VALUE, poppedView);
c.setValue(3);
sendCommand(c);
#else
Element * e = getRegisteredElement(poppedView);
if (e) e->show();
#endif
} else {
Command c(Command::QUIT_APP, poppedView);
sendCommand(c);
}
} else if (ev.getType() == SysEvent::SHOW_DEBUG) {
auto dialog = make_shared<DebugDialog>();
dialog->showModal(this);
}
}
void
FWApplication::showMessageDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppMessageDialog>(title, message);
dialog->showModal(this);
}
std::string
FWApplication::showInputDialog(const std::string & title, const std::string & message) {
auto dialog = make_shared<AppInputDialog>(title, message);
if (dialog->showModal(this)) {
return dialog->getValue();
} else {
return "";
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIDefaultResourceProvider.cpp
created: 8/7/2004
author: James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"
#if defined(__WIN32__) || defined(_WIN32)
# include <io.h>
# include <windows.h>
# include <string>
//----------------------------------------------------------------------------//
std::wstring Utf8ToUtf16(const std::string& utf8text)
{
const int textLen = MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(),
utf8text.size() + 1, 0, 0);
if (textLen == 0)
throw CEGUI::InvalidRequestException(
"Utf8ToUtf16 - MultiByteToWideChar failed");
std::wstring wideStr(textLen, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(), utf8text.size() + 1,
&wideStr[0], wideStr.size());
return wideStr;
}
//----------------------------------------------------------------------------//
#else
# include <sys/types.h>
# include <sys/stat.h>
# include <dirent.h>
# include <fnmatch.h>
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
RawDataContainer& output,
const String& resourceGroup)
{
if (filename.empty())
throw InvalidRequestException("DefaultResourceProvider::load: "
"Filename supplied for data loading must be valid");
const String final_filename(getFinalFilename(filename, resourceGroup));
#if defined(__WIN32__) || defined(_WIN32)
FILE* file = _wfopen(Utf8ToUtf16(final_filename.c_str()).c_str(), L"rb");
#else
FILE* file = fopen(final_filename.c_str(), "rb");
#endif
if (file == 0)
throw InvalidRequestException("DefaultResourceProvider::load: " +
final_filename + " does not exist");
fseek(file, 0, SEEK_END);
const long size = ftell(file);
fseek(file, 0, SEEK_SET);
unsigned char* const buffer = new unsigned char[size];
const size_t size_read = fread(buffer, sizeof(char), size, file);
fclose(file);
if (size_read != size)
{
delete[] buffer;
throw GenericException("DefaultResourceProvider::loadRawDataContainer: "
"A problem occurred while reading file: " + final_filename);
}
output.setData(buffer);
output.setSize(size);
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
uint8* const ptr = data.getDataPtr();
delete[] ptr;
data.setData(0);
data.setSize(0);
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
const String& resourceGroup,
const String& directory)
{
if (directory.length() == 0)
return;
#if defined(_WIN32) || defined(__WIN32__)
// while we rarely use the unportable '\', the user may have
const String separators("\\/");
#else
const String separators("/");
#endif
if (String::npos == separators.find(directory[directory.length() - 1]))
d_resourceGroups[resourceGroup] = directory + '/';
else
d_resourceGroups[resourceGroup] = directory;
}
//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
const String& resourceGroup)
{
return d_resourceGroups[resourceGroup];
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
const String& resourceGroup)
{
ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);
if (iter != d_resourceGroups.end())
d_resourceGroups.erase(iter);
}
//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
const String& filename,
const String& resourceGroup) const
{
String final_filename;
// look up resource group directory
ResourceGroupMap::const_iterator iter =
d_resourceGroups.find(resourceGroup.empty() ?
d_defaultResourceGroup :
resourceGroup);
// if there was an entry for this group, use it's directory as the
// first part of the filename
if (iter != d_resourceGroups.end())
final_filename = (*iter).second;
// append the filename part that we were passed
final_filename += filename;
// return result
return final_filename;
}
//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
std::vector<String>& out_vec,
const String& file_pattern,
const String& resource_group)
{
// look-up resource group name
ResourceGroupMap::const_iterator iter =
d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
resource_group);
// get directory that's set for the resource group
const String dir_name(
iter != d_resourceGroups.end() ? (*iter).second : "./");
size_t entries = 0;
// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
intptr_t f;
struct _finddata_t fd;
if ((f = _findfirst((dir_name + file_pattern).c_str(), &fd)) != -1)
{
do
{
if ((fd.attrib & _A_SUBDIR))
continue;
out_vec.push_back(fd.name);
++entries;
}
while (_findnext(f, &fd) == 0);
_findclose(f);
}
// Everybody else
#else
DIR* dirp;
if ((dirp = opendir(dir_name.c_str())))
{
struct dirent* dp;
while ((dp = readdir(dirp)))
{
const String filename(dir_name + dp->d_name);
struct stat s;
if ((stat(filename.c_str(), &s) == 0) &&
S_ISREG(s.st_mode) &&
(fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
{
out_vec.push_back(dp->d_name);
++entries;
}
}
closedir(dirp);
}
#endif
return entries;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>FIX: The Windows utf-16 / wchar_t patch adding support for filenames encoded as utf16 was missing support for that facility in the DefaultResourceProvider::getResourceGroupFileNames function. This fix adds that support.<commit_after>/***********************************************************************
filename: CEGUIDefaultResourceProvider.cpp
created: 8/7/2004
author: James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUIDefaultResourceProvider.h"
#include "CEGUIExceptions.h"
#if defined(__WIN32__) || defined(_WIN32)
# include <io.h>
# include <windows.h>
# include <string>
//----------------------------------------------------------------------------//
std::wstring Utf8ToUtf16(const std::string& utf8text)
{
const int textLen = MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(),
utf8text.size() + 1, 0, 0);
if (textLen == 0)
throw CEGUI::InvalidRequestException(
"Utf8ToUtf16 - MultiByteToWideChar failed");
std::wstring wideStr(textLen, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8text.c_str(), utf8text.size() + 1,
&wideStr[0], wideStr.size());
return wideStr;
}
//----------------------------------------------------------------------------//
CEGUI::String Utf16ToString(const wchar_t* const utf16text)
{
const int len = WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
0, 0, 0, 0);
if (!len)
throw CEGUI::InvalidRequestException(
"Utf16ToUtf8 - WideCharToMultiByte failed");
CEGUI::utf8* buff = new CEGUI::utf8[len + 1];
WideCharToMultiByte(CP_UTF8, 0, utf16text, -1,
reinterpret_cast<char*>(buff), len, 0, 0);
const CEGUI::String result(buff);
delete[] buff;
return result;
}
//----------------------------------------------------------------------------//
#else
# include <sys/types.h>
# include <sys/stat.h>
# include <dirent.h>
# include <fnmatch.h>
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
RawDataContainer& output,
const String& resourceGroup)
{
if (filename.empty())
throw InvalidRequestException("DefaultResourceProvider::load: "
"Filename supplied for data loading must be valid");
const String final_filename(getFinalFilename(filename, resourceGroup));
#if defined(__WIN32__) || defined(_WIN32)
FILE* file = _wfopen(Utf8ToUtf16(final_filename.c_str()).c_str(), L"rb");
#else
FILE* file = fopen(final_filename.c_str(), "rb");
#endif
if (file == 0)
throw InvalidRequestException("DefaultResourceProvider::load: " +
final_filename + " does not exist");
fseek(file, 0, SEEK_END);
const long size = ftell(file);
fseek(file, 0, SEEK_SET);
unsigned char* const buffer = new unsigned char[size];
const size_t size_read = fread(buffer, sizeof(char), size, file);
fclose(file);
if (size_read != size)
{
delete[] buffer;
throw GenericException("DefaultResourceProvider::loadRawDataContainer: "
"A problem occurred while reading file: " + final_filename);
}
output.setData(buffer);
output.setSize(size);
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
uint8* const ptr = data.getDataPtr();
delete[] ptr;
data.setData(0);
data.setSize(0);
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
const String& resourceGroup,
const String& directory)
{
if (directory.length() == 0)
return;
#if defined(_WIN32) || defined(__WIN32__)
// while we rarely use the unportable '\', the user may have
const String separators("\\/");
#else
const String separators("/");
#endif
if (String::npos == separators.find(directory[directory.length() - 1]))
d_resourceGroups[resourceGroup] = directory + '/';
else
d_resourceGroups[resourceGroup] = directory;
}
//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
const String& resourceGroup)
{
return d_resourceGroups[resourceGroup];
}
//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
const String& resourceGroup)
{
ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);
if (iter != d_resourceGroups.end())
d_resourceGroups.erase(iter);
}
//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
const String& filename,
const String& resourceGroup) const
{
String final_filename;
// look up resource group directory
ResourceGroupMap::const_iterator iter =
d_resourceGroups.find(resourceGroup.empty() ?
d_defaultResourceGroup :
resourceGroup);
// if there was an entry for this group, use it's directory as the
// first part of the filename
if (iter != d_resourceGroups.end())
final_filename = (*iter).second;
// append the filename part that we were passed
final_filename += filename;
// return result
return final_filename;
}
//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
std::vector<String>& out_vec,
const String& file_pattern,
const String& resource_group)
{
// look-up resource group name
ResourceGroupMap::const_iterator iter =
d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
resource_group);
// get directory that's set for the resource group
const String dir_name(
iter != d_resourceGroups.end() ? (*iter).second : "./");
size_t entries = 0;
// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
intptr_t f;
struct _wfinddata_t fd;
if ((f = _wfindfirst(Utf8ToUtf16((dir_name + file_pattern).c_str()).c_str(), &fd)) != -1)
{
do
{
if ((fd.attrib & _A_SUBDIR))
continue;
out_vec.push_back(Utf16ToString(fd.name));
++entries;
}
while (_wfindnext(f, &fd) == 0);
_findclose(f);
}
// Everybody else
#else
DIR* dirp;
if ((dirp = opendir(dir_name.c_str())))
{
struct dirent* dp;
while ((dp = readdir(dirp)))
{
const String filename(dir_name + dp->d_name);
struct stat s;
if ((stat(filename.c_str(), &s) == 0) &&
S_ISREG(s.st_mode) &&
(fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
{
out_vec.push_back(dp->d_name);
++entries;
}
}
closedir(dirp);
}
#endif
return entries;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "network.h"
#include "string.h"
#include "mutex.h"
////////////////////////////////////////////////////////////////////////////////
/// Platforms supporting Socket interface
////////////////////////////////////////////////////////////////////////////////
#if defined(__WIN32__)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
//#include <winsock2.h>
//#include <io.h>
typedef int socklen_t;
#define SHUT_RDWR 0x2
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define closesocket close
#endif
/*! ignore if not supported */
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#define BUFFERING 1
namespace embree
{
namespace network
{
__forceinline void initialize() {
#ifdef __WIN32__
static bool initialized = false;
static MutexSys initMutex;
Lock<MutexSys> lock(initMutex);
WSADATA wsaData;
short version = MAKEWORD(1,1);
if (WSAStartup(version,&wsaData) != 0)
THROW_RUNTIME_ERROR("Winsock initialization failed");
initialized = true;
#endif
}
struct buffered_socket_t
{
buffered_socket_t (SOCKET fd, size_t isize = 64*1024, size_t osize = 64*1024)
: fd(fd),
ibuf(new char[isize]), isize(isize), istart(0), iend(0),
obuf(new char[osize]), osize(osize), oend(0) {
}
~buffered_socket_t () {
delete[] ibuf; ibuf = nullptr;
delete[] obuf; obuf = nullptr;
}
SOCKET fd; //!< file descriptor of the socket
char* ibuf;
size_t isize;
size_t istart,iend;
char* obuf;
size_t osize;
size_t oend;
};
socket_t connect(const char* host, unsigned short port)
{
initialize();
/*! create a new socket */
SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot create socket");
/*! perform DNS lookup */
struct hostent* server = ::gethostbyname(host);
if (server == nullptr) THROW_RUNTIME_ERROR("server "+std::string(host)+" not found");
/*! perform connection */
struct sockaddr_in serv_addr;
memset((char*)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = (unsigned short) htons(port);
memcpy((char*)&serv_addr.sin_addr.s_addr, (char*)server->h_addr, server->h_length);
if (::connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)
THROW_RUNTIME_ERROR("connection to "+std::string(host)+":"+toString(port)+" failed");
/*! enable TCP_NODELAY */
#ifdef TCP_NODELAY
{ int flag = 1; ::setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(int)); }
#endif
/*! we do not want SIGPIPE to be thrown */
#ifdef SO_NOSIGPIPE
{ int flag = 1; setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (const char*) &flag, sizeof(int)); }
#endif
return (socket_t) new buffered_socket_t(sockfd);
}
socket_t bind(unsigned short port)
{
initialize();
/*! create a new socket */
SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot create socket");
/* When the server completes, the server socket enters a time-wait state during which the local
address and port used by the socket are believed to be in use by the OS. The wait state may
last several minutes. This socket option allows bind() to reuse the port immediately. */
#ifdef SO_REUSEADDR
{ int flag = true; ::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(int)); }
#endif
/*! bind socket to port */
struct sockaddr_in serv_addr;
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = (unsigned short) htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (::bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
THROW_RUNTIME_ERROR("binding to port "+toString(port)+" failed");
/*! listen to port, up to 5 pending connections */
if (::listen(sockfd,5) < 0)
THROW_RUNTIME_ERROR("listening on socket failed");
return (socket_t) new buffered_socket_t(sockfd);
}
socket_t listen(socket_t hsock)
{
SOCKET sockfd = ((buffered_socket_t*) hsock)->fd;
/*! accept incoming connection */
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SOCKET fd = ::accept(sockfd, (struct sockaddr *) &addr, &len);
if (fd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot accept connection");
/*! enable TCP_NODELAY */
#ifdef TCP_NODELAY
{ int flag = 1; ::setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char*)&flag,sizeof(int)); }
#endif
/*! we do not want SIGPIPE to be thrown */
#ifdef SO_NOSIGPIPE
{ int flag = 1; setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&flag, sizeof(int)); }
#endif
return (socket_t) new buffered_socket_t(fd);
}
void read(socket_t hsock_i, void* data_i, size_t bytes)
{
#if BUFFERING
char* data = (char*)data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
if (hsock->istart == hsock->iend) {
ssize_t n = ::recv(hsock->fd,hsock->ibuf,int(hsock->isize),MSG_NOSIGNAL);
if (n == 0) throw Disconnect();
else if (n < 0) THROW_RUNTIME_ERROR("error reading from socket");
hsock->istart = 0;
hsock->iend = n;
}
size_t bsize = hsock->iend-hsock->istart;
if (bytes < bsize) bsize = bytes;
memcpy(data,hsock->ibuf+hsock->istart,bsize);
data += bsize;
hsock->istart += bsize;
bytes -= bsize;
}
#else
char* data = (char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
ssize_t n = ::read(hsock->fd,data,bytes);
if (n == 0) throw Disconnect();
else if (n < 0) THROW_RUNTIME_ERROR("error reading from socket");
data+=n;
bytes-=n;
}
#endif
}
void write(socket_t hsock_i, const void* data_i, size_t bytes)
{
#if BUFFERING
const char* data = (const char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
if (hsock->oend == hsock->osize) flush(hsock_i);
size_t bsize = hsock->osize-hsock->oend;
if (bytes < bsize) bsize = bytes;
memcpy(hsock->obuf+hsock->oend,data,bsize);
data += bsize;
hsock->oend += bsize;
bytes -= bsize;
}
#else
const char* data = (const char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
ssize_t n = ::write(hsock->fd,data,bytes);
if (n < 0) THROW_RUNTIME_ERROR("error writing to socket");
data+=n;
bytes-=n;
}
#endif
}
void flush(socket_t hsock_i)
{
#if BUFFERING
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
char* data = hsock->obuf;
size_t bytes = hsock->oend;
while (bytes > 0) {
ssize_t n = ::send(hsock->fd,data,(int)bytes,MSG_NOSIGNAL);
if (n < 0) THROW_RUNTIME_ERROR("error writing to socket");
bytes -= n;
data += n;
}
hsock->oend = 0;
#endif
}
void close(socket_t hsock_i) {
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
::shutdown(hsock->fd,SHUT_RDWR);
delete hsock;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// All Platforms
////////////////////////////////////////////////////////////////////////////////
namespace embree
{
namespace network
{
bool read_bool(socket_t socket)
{
bool value = 0;
read(socket,&value,sizeof(bool));
return value;
}
char read_char(socket_t socket)
{
char value = 0;
read(socket,&value,sizeof(char));
return value;
}
int read_int(socket_t socket)
{
int value = 0;
read(socket,&value,sizeof(int));
return value;
}
float read_float(socket_t socket)
{
float value = 0.0f;
read(socket,&value,sizeof(float));
return value;
}
std::string read_string(socket_t socket)
{
int bytes = read_int(socket);
char* str = new char[bytes+1];
read(socket,str,bytes);
str[bytes] = 0x00;
std::string s(str);
delete[] str;
return s;
}
void write(socket_t socket, bool value) {
write(socket,&value,sizeof(bool));
}
void write(socket_t socket, char value) {
write(socket,&value,sizeof(char));
}
void write(socket_t socket, int value) {
write(socket,&value,sizeof(int));
}
void write(socket_t socket, float value) {
write(socket,&value,sizeof(float));
}
void write(socket_t socket, const std::string& str) {
write(socket,(int)str.size());
write(socket,str.c_str(),str.size());
}
}
}
<commit_msg>made buffered_socket_t non-copyable<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "network.h"
#include "string.h"
#include "mutex.h"
////////////////////////////////////////////////////////////////////////////////
/// Platforms supporting Socket interface
////////////////////////////////////////////////////////////////////////////////
#if defined(__WIN32__)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
//#include <winsock2.h>
//#include <io.h>
typedef int socklen_t;
#define SHUT_RDWR 0x2
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define closesocket close
#endif
/*! ignore if not supported */
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#define BUFFERING 1
namespace embree
{
namespace network
{
__forceinline void initialize() {
#ifdef __WIN32__
static bool initialized = false;
static MutexSys initMutex;
Lock<MutexSys> lock(initMutex);
WSADATA wsaData;
short version = MAKEWORD(1,1);
if (WSAStartup(version,&wsaData) != 0)
THROW_RUNTIME_ERROR("Winsock initialization failed");
initialized = true;
#endif
}
struct buffered_socket_t
{
buffered_socket_t (SOCKET fd, size_t isize = 64*1024, size_t osize = 64*1024)
: fd(fd),
ibuf(new char[isize]), isize(isize), istart(0), iend(0),
obuf(new char[osize]), osize(osize), oend(0) {
}
~buffered_socket_t () {
delete[] ibuf; ibuf = nullptr;
delete[] obuf; obuf = nullptr;
}
private:
buffered_socket_t (const buffered_socket_t& other) DELETED; // do not implement
buffered_socket_t& operator= (const buffered_socket_t& other) DELETED; // do not implement
public:
SOCKET fd; //!< file descriptor of the socket
char* ibuf;
size_t isize;
size_t istart,iend;
char* obuf;
size_t osize;
size_t oend;
};
socket_t connect(const char* host, unsigned short port)
{
initialize();
/*! create a new socket */
SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot create socket");
/*! perform DNS lookup */
struct hostent* server = ::gethostbyname(host);
if (server == nullptr) THROW_RUNTIME_ERROR("server "+std::string(host)+" not found");
/*! perform connection */
struct sockaddr_in serv_addr;
memset((char*)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = (unsigned short) htons(port);
memcpy((char*)&serv_addr.sin_addr.s_addr, (char*)server->h_addr, server->h_length);
if (::connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)
THROW_RUNTIME_ERROR("connection to "+std::string(host)+":"+toString(port)+" failed");
/*! enable TCP_NODELAY */
#ifdef TCP_NODELAY
{ int flag = 1; ::setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(int)); }
#endif
/*! we do not want SIGPIPE to be thrown */
#ifdef SO_NOSIGPIPE
{ int flag = 1; setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (const char*) &flag, sizeof(int)); }
#endif
return (socket_t) new buffered_socket_t(sockfd);
}
socket_t bind(unsigned short port)
{
initialize();
/*! create a new socket */
SOCKET sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot create socket");
/* When the server completes, the server socket enters a time-wait state during which the local
address and port used by the socket are believed to be in use by the OS. The wait state may
last several minutes. This socket option allows bind() to reuse the port immediately. */
#ifdef SO_REUSEADDR
{ int flag = true; ::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(int)); }
#endif
/*! bind socket to port */
struct sockaddr_in serv_addr;
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = (unsigned short) htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (::bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
THROW_RUNTIME_ERROR("binding to port "+toString(port)+" failed");
/*! listen to port, up to 5 pending connections */
if (::listen(sockfd,5) < 0)
THROW_RUNTIME_ERROR("listening on socket failed");
return (socket_t) new buffered_socket_t(sockfd);
}
socket_t listen(socket_t hsock)
{
SOCKET sockfd = ((buffered_socket_t*) hsock)->fd;
/*! accept incoming connection */
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SOCKET fd = ::accept(sockfd, (struct sockaddr *) &addr, &len);
if (fd == INVALID_SOCKET) THROW_RUNTIME_ERROR("cannot accept connection");
/*! enable TCP_NODELAY */
#ifdef TCP_NODELAY
{ int flag = 1; ::setsockopt(fd,IPPROTO_TCP,TCP_NODELAY,(char*)&flag,sizeof(int)); }
#endif
/*! we do not want SIGPIPE to be thrown */
#ifdef SO_NOSIGPIPE
{ int flag = 1; setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&flag, sizeof(int)); }
#endif
return (socket_t) new buffered_socket_t(fd);
}
void read(socket_t hsock_i, void* data_i, size_t bytes)
{
#if BUFFERING
char* data = (char*)data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
if (hsock->istart == hsock->iend) {
ssize_t n = ::recv(hsock->fd,hsock->ibuf,int(hsock->isize),MSG_NOSIGNAL);
if (n == 0) throw Disconnect();
else if (n < 0) THROW_RUNTIME_ERROR("error reading from socket");
hsock->istart = 0;
hsock->iend = n;
}
size_t bsize = hsock->iend-hsock->istart;
if (bytes < bsize) bsize = bytes;
memcpy(data,hsock->ibuf+hsock->istart,bsize);
data += bsize;
hsock->istart += bsize;
bytes -= bsize;
}
#else
char* data = (char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
ssize_t n = ::read(hsock->fd,data,bytes);
if (n == 0) throw Disconnect();
else if (n < 0) THROW_RUNTIME_ERROR("error reading from socket");
data+=n;
bytes-=n;
}
#endif
}
void write(socket_t hsock_i, const void* data_i, size_t bytes)
{
#if BUFFERING
const char* data = (const char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
if (hsock->oend == hsock->osize) flush(hsock_i);
size_t bsize = hsock->osize-hsock->oend;
if (bytes < bsize) bsize = bytes;
memcpy(hsock->obuf+hsock->oend,data,bsize);
data += bsize;
hsock->oend += bsize;
bytes -= bsize;
}
#else
const char* data = (const char*) data_i;
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
while (bytes) {
ssize_t n = ::write(hsock->fd,data,bytes);
if (n < 0) THROW_RUNTIME_ERROR("error writing to socket");
data+=n;
bytes-=n;
}
#endif
}
void flush(socket_t hsock_i)
{
#if BUFFERING
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
char* data = hsock->obuf;
size_t bytes = hsock->oend;
while (bytes > 0) {
ssize_t n = ::send(hsock->fd,data,(int)bytes,MSG_NOSIGNAL);
if (n < 0) THROW_RUNTIME_ERROR("error writing to socket");
bytes -= n;
data += n;
}
hsock->oend = 0;
#endif
}
void close(socket_t hsock_i) {
buffered_socket_t* hsock = (buffered_socket_t*) hsock_i;
::shutdown(hsock->fd,SHUT_RDWR);
delete hsock;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// All Platforms
////////////////////////////////////////////////////////////////////////////////
namespace embree
{
namespace network
{
bool read_bool(socket_t socket)
{
bool value = 0;
read(socket,&value,sizeof(bool));
return value;
}
char read_char(socket_t socket)
{
char value = 0;
read(socket,&value,sizeof(char));
return value;
}
int read_int(socket_t socket)
{
int value = 0;
read(socket,&value,sizeof(int));
return value;
}
float read_float(socket_t socket)
{
float value = 0.0f;
read(socket,&value,sizeof(float));
return value;
}
std::string read_string(socket_t socket)
{
int bytes = read_int(socket);
char* str = new char[bytes+1];
read(socket,str,bytes);
str[bytes] = 0x00;
std::string s(str);
delete[] str;
return s;
}
void write(socket_t socket, bool value) {
write(socket,&value,sizeof(bool));
}
void write(socket_t socket, char value) {
write(socket,&value,sizeof(char));
}
void write(socket_t socket, int value) {
write(socket,&value,sizeof(int));
}
void write(socket_t socket, float value) {
write(socket,&value,sizeof(float));
}
void write(socket_t socket, const std::string& str) {
write(socket,(int)str.size());
write(socket,str.c_str(),str.size());
}
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Fri, 4th July 2014
author: Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders
//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"uniform float4x4 worldViewProjMatrix;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"VS_OUT main(float4 position : POSITION, float4 colour : COLOR)\n"
"{\n"
" VS_OUT o;\n"
"\n"
" o.position = mul(worldViewProjMatrix, position);\n"
" o.colour = colour;\n"
"\n"
" return output;\n"
"}\n"
);
//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
" float4 colour = input.colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"uniform float4x4 worldViewProjMatrix;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VS_OUT main(float4 position : POSITION, float2 uv : TEXCOORD0, float4 colour : COLOR)\n"
"{\n"
" VS_OUT o;\n"
"\n"
" o.position = mul(worldViewProjMatrix, position);\n"
" o.uv = uv;\n"
" o.colour = colour;\n"
"\n"
" return output;\n"
"}\n"
);
/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
" uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
" colour = tex2D(texture0, uv) * colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
"void main(void)"
"{"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_FrontColor = gl_Color;"
" gl_Position = gl_worldViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
"uniform sampler2D texture0;"
"uniform float alphaPercentage;\n"
"void main(void)"
"{"
" gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
"void main(void)"
"{"
" gl_FrontColor = gl_Color;"
" gl_Position = gl_worldViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{"
" gl_FragColor = gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
"#version 150 core\n"
"uniform mat4 worldViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"out vec4 exColour;"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = worldViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
"#version 150 core\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" fragColour = exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
"#version 150 core\n"
"uniform mat4 worldViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"in vec2 uv0;\n"
"out vec2 exTexCoord;\n"
"out vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;\n"
" gl_Position = worldViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
"#version 150 core\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"in vec2 exTexCoord;\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = texture(texture0, exTexCoord) * exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
}
<commit_msg>Made Ogre renderer OpenGL shaders use older version to make it work better on linux<commit_after>/***********************************************************************
created: Fri, 4th July 2014
author: Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders
//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"uniform float4x4 worldViewProjMatrix;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"VS_OUT main(float4 position : POSITION, float4 colour : COLOR)\n"
"{\n"
" VS_OUT o;\n"
"\n"
" o.position = mul(worldViewProjMatrix, position);\n"
" o.colour = colour;\n"
"\n"
" return output;\n"
"}\n"
);
//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
" float4 colour = input.colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"uniform float4x4 worldViewProjMatrix;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VS_OUT main(float4 position : POSITION, float2 uv : TEXCOORD0, float4 colour : COLOR)\n"
"{\n"
" VS_OUT o;\n"
"\n"
" o.position = mul(worldViewProjMatrix, position);\n"
" o.uv = uv;\n"
" o.colour = colour;\n"
"\n"
" return output;\n"
"}\n"
);
/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
" uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
" colour = tex2D(texture0, uv) * colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
"void main(void)"
"{"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_FrontColor = gl_Color;"
" gl_Position = gl_worldViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
"uniform sampler2D texture0;"
"uniform float alphaPercentage;\n"
"void main(void)"
"{"
" gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
"void main(void)"
"{"
" gl_FrontColor = gl_Color;"
" gl_Position = gl_worldViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{"
" gl_FragColor = gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
"#version 130 core\n"
"uniform mat4 worldViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"out vec4 exColour;"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = worldViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
"#version 130 core\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" fragColour = exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
"#version 130 core\n"
"uniform mat4 worldViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"in vec2 uv0;\n"
"out vec2 exTexCoord;\n"
"out vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;\n"
" gl_Position = worldViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
"#version 130 core\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"in vec2 exTexCoord;\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = texture(texture0, exTexCoord) * exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010, 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSMediaRuleImp.h"
#include "ObjectArrayImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace css;
void CSSMediaRuleImp::append(css::CSSRule rule)
{
ruleList.push_back(rule);
}
// CSSRule
unsigned short CSSMediaRuleImp::getType()
{
return CSSRule::MEDIA_RULE;
}
std::u16string CSSMediaRuleImp::getCssText()
{
std::u16string text = u"@media " + mediaList.getMediaText() + u" {";
for (auto i = ruleList.begin(); i != ruleList.end(); ++i)
text += (*i).getCssText();
text += u"}";
std::u16string media = mediaList.getMediaText();
if (!media.empty())
text += u" " + media;
return text;
}
// CSSMediaRule
stylesheets::MediaList CSSMediaRuleImp::getMedia()
{
return &mediaList;
}
void CSSMediaRuleImp::setMedia(const std::u16string& media)
{
mediaList.setMediaText(media);
}
CSSRuleList CSSMediaRuleImp::getCssRules()
{
return new(std::nothrow) ObjectArrayImp<CSSMediaRuleImp, CSSRule, &CSSMediaRuleImp::ruleList>(this);
}
unsigned int CSSMediaRuleImp::insertRule(const std::u16string& rule, unsigned int index)
{
// TODO: implement me!
return 0;
}
void CSSMediaRuleImp::deleteRule(unsigned int index)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(CSSMediaRuleImp::getCssText) : Fix a bug<commit_after>/*
* Copyright 2010-2013 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CSSMediaRuleImp.h"
#include "ObjectArrayImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
using namespace css;
void CSSMediaRuleImp::append(css::CSSRule rule)
{
ruleList.push_back(rule);
}
// CSSRule
unsigned short CSSMediaRuleImp::getType()
{
return CSSRule::MEDIA_RULE;
}
std::u16string CSSMediaRuleImp::getCssText()
{
std::u16string text = u"@media " + mediaList.getMediaText() + u" { ";
for (auto i = ruleList.begin(); i != ruleList.end(); ++i)
text += (*i).getCssText() + u" ";
text += u'}';
return text;
}
// CSSMediaRule
stylesheets::MediaList CSSMediaRuleImp::getMedia()
{
return &mediaList;
}
void CSSMediaRuleImp::setMedia(const std::u16string& media)
{
mediaList.setMediaText(media);
}
CSSRuleList CSSMediaRuleImp::getCssRules()
{
return new(std::nothrow) ObjectArrayImp<CSSMediaRuleImp, CSSRule, &CSSMediaRuleImp::ruleList>(this);
}
unsigned int CSSMediaRuleImp::insertRule(const std::u16string& rule, unsigned int index)
{
// TODO: implement me!
return 0;
}
void CSSMediaRuleImp::deleteRule(unsigned int index)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>#include "chainerx/routines/reduction.h"
#include <cmath>
#include <cstdint>
#include <numeric>
#include <utility>
#include <vector>
#include <absl/types/optional.h>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/reduction.h"
#include "chainerx/macro.h"
#include "chainerx/routines/arithmetic.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/explog.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/routines/statistics.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Sum(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a.dtype();
}
Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SumKernel>(a, sorted_axis, out);
}
BackwardBuilder bb{"sum", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape);
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape);
}
});
}
bb.Finalize();
return out;
}
Array Softmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis.has_value() ? axis : OptionalAxes{1}, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array exps = Exp(x_cast - xmax);
Array sums = Sum(exps, sorted_axis, true);
return exps * Reciprocal(sums);
}
Array LogSumExp(const Array& x, const OptionalAxes& axis, bool keepdims) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array logs = Log(Sum(Exp(x_cast - xmax), sorted_axis, keepdims));
return (keepdims ? xmax : Squeeze(xmax, axis)) + logs;
}
Array LogSoftmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
return x_cast - LogSumExp(x_cast, axis.has_value() ? axis : OptionalAxes{1}, true);
}
Array Cumsum(const Array& a, absl::optional<int8_t> axis) {
int8_t axis_norm;
Array a_reshaped = Copy(a);
if (axis.has_value()) {
axis_norm = internal::NormalizeAxis(*axis, a.ndim());
} else {
axis_norm = 0;
a_reshaped = a.Reshape(Shape{a.GetTotalSize()});
}
Shape out_shape = a_reshaped.shape();
Array out = Empty(out_shape, a_reshaped.dtype(), a_reshaped.device());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a_reshaped.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a_reshaped.dtype();
}
const Array& out_cast = out.AsType(out_dtype);
const Array& a_cast = a_reshaped.dtype() != out_cast.dtype() ? a_reshaped.AsType(out_cast.dtype()) : a_reshaped;
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<CumsumKernel>(a_cast, axis_norm, out_cast);
}
// Backward not implemented yet
return out_cast;
}
} // namespace chainerx
<commit_msg>Remove redundant copy<commit_after>#include "chainerx/routines/reduction.h"
#include <cmath>
#include <cstdint>
#include <numeric>
#include <utility>
#include <vector>
#include <absl/types/optional.h>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward_builder.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/kernels/reduction.h"
#include "chainerx/macro.h"
#include "chainerx/routines/arithmetic.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/explog.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/routines_util.h"
#include "chainerx/routines/statistics.h"
#include "chainerx/routines/type_util.h"
#include "chainerx/shape.h"
namespace chainerx {
Array Sum(const Array& a, const OptionalAxes& axis, bool keepdims) {
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a.dtype();
}
Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device());
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<SumKernel>(a, sorted_axis, out);
}
BackwardBuilder bb{"sum", a, out};
if (BackwardBuilder::Target bt = bb.CreateTarget(0)) {
bt.Define([sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) {
const Array& gout = *bctx.output_grad();
CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end()));
if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) {
Shape out_shape_broadcastable = gout.shape();
for (auto axis : sorted_axis) {
out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1);
}
bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape);
} else {
bctx.input_grad() = gout.BroadcastTo(in_shape);
}
});
}
bb.Finalize();
return out;
}
Array Softmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis.has_value() ? axis : OptionalAxes{1}, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array exps = Exp(x_cast - xmax);
Array sums = Sum(exps, sorted_axis, true);
return exps * Reciprocal(sums);
}
Array LogSumExp(const Array& x, const OptionalAxes& axis, bool keepdims) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
Axes sorted_axis = internal::GetSortedAxesOrAll(axis, x.ndim());
Array xmax = AMax(x_cast, sorted_axis, true);
Array logs = Log(Sum(Exp(x_cast - xmax), sorted_axis, keepdims));
return (keepdims ? xmax : Squeeze(xmax, axis)) + logs;
}
Array LogSoftmax(const Array& x, const OptionalAxes& axis) {
Dtype dtype = internal::GetMathResultDtype(x.dtype());
const Array& x_cast = x.dtype() == dtype ? x : x.AsType(dtype);
return x_cast - LogSumExp(x_cast, axis.has_value() ? axis : OptionalAxes{1}, true);
}
Array Cumsum(const Array& a, absl::optional<int8_t> axis) {
int8_t axis_norm;
Array a_reshaped{};
if (axis.has_value()) {
axis_norm = internal::NormalizeAxis(*axis, a.ndim());
a_reshaped = Copy(a);
} else {
axis_norm = 0;
// TODO(imanishi): Fix after chainerx::Ravel is supported.
a_reshaped = a.Reshape(Shape{a.GetTotalSize()});
}
Shape out_shape = a_reshaped.shape();
Array out = Empty(out_shape, a_reshaped.dtype(), a_reshaped.device());
// Decide the output dtype for integral input dtype.
Dtype out_dtype{};
switch (GetKind(a_reshaped.dtype())) {
case DtypeKind::kBool:
case DtypeKind::kInt: // fallthrough
out_dtype = Dtype::kInt64;
break;
case DtypeKind::kUInt:
out_dtype = Dtype::kInt64; // TODO(niboshi): This should be kUInt64
break;
default:
out_dtype = a_reshaped.dtype();
}
const Array& out_cast = out.AsType(out_dtype);
const Array& a_cast = a_reshaped.dtype() != out_cast.dtype() ? a_reshaped.AsType(out_cast.dtype()) : a_reshaped;
{
NoBackpropModeScope scope{};
a.device().backend().CallKernel<CumsumKernel>(a_cast, axis_norm, out_cast);
}
// Backward not implemented yet
return out_cast;
}
} // namespace chainerx
<|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <[email protected]>
#include "FirmwarePluginManager.h"
#include "FirmwarePlugin.h"
FirmwarePluginManager::FirmwarePluginManager(QGCApplication* app)
: QGCTool(app)
, _genericFirmwarePlugin(NULL)
{
}
FirmwarePluginManager::~FirmwarePluginManager()
{
delete _genericFirmwarePlugin;
}
QList<MAV_AUTOPILOT> FirmwarePluginManager::knownFirmwareTypes(void)
{
if (_knownFirmwareTypes.isEmpty()) {
QList<FirmwarePluginFactory*> factoryList = FirmwarePluginFactoryRegister::instance()->pluginFactories();
for (int i=0; i<factoryList.count(); i++) {
_knownFirmwareTypes.append(factoryList[i]->knownFirmwareTypes());
}
}
_knownFirmwareTypes.append(MAV_AUTOPILOT_GENERIC);
return _knownFirmwareTypes;
}
FirmwarePlugin* FirmwarePluginManager::firmwarePluginForAutopilot(MAV_AUTOPILOT autopilotType, MAV_TYPE vehicleType)
{
FirmwarePlugin* _plugin = NULL;
QList<FirmwarePluginFactory*> factoryList = FirmwarePluginFactoryRegister::instance()->pluginFactories();
// Find the plugin which supports this vehicle
for (int i=0; i<factoryList.count(); i++) {
if ((_plugin = factoryList[i]->firmwarePluginForAutopilot(autopilotType, vehicleType))) {
return _plugin;
}
}
// Default plugin fallback
if (!_genericFirmwarePlugin) {
_genericFirmwarePlugin = new FirmwarePlugin;
}
return _genericFirmwarePlugin;
}
<commit_msg>Add MAV_AUTOPILOT_GENERIC only once.<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <[email protected]>
#include "FirmwarePluginManager.h"
#include "FirmwarePlugin.h"
FirmwarePluginManager::FirmwarePluginManager(QGCApplication* app)
: QGCTool(app)
, _genericFirmwarePlugin(NULL)
{
}
FirmwarePluginManager::~FirmwarePluginManager()
{
delete _genericFirmwarePlugin;
}
QList<MAV_AUTOPILOT> FirmwarePluginManager::knownFirmwareTypes(void)
{
if (_knownFirmwareTypes.isEmpty()) {
QList<FirmwarePluginFactory*> factoryList = FirmwarePluginFactoryRegister::instance()->pluginFactories();
for (int i = 0; i < factoryList.count(); i++) {
_knownFirmwareTypes.append(factoryList[i]->knownFirmwareTypes());
}
_knownFirmwareTypes.append(MAV_AUTOPILOT_GENERIC);
}
return _knownFirmwareTypes;
}
FirmwarePlugin* FirmwarePluginManager::firmwarePluginForAutopilot(MAV_AUTOPILOT autopilotType, MAV_TYPE vehicleType)
{
FirmwarePlugin* _plugin = NULL;
QList<FirmwarePluginFactory*> factoryList = FirmwarePluginFactoryRegister::instance()->pluginFactories();
// Find the plugin which supports this vehicle
for (int i=0; i<factoryList.count(); i++) {
if ((_plugin = factoryList[i]->firmwarePluginForAutopilot(autopilotType, vehicleType))) {
return _plugin;
}
}
// Default plugin fallback
if (!_genericFirmwarePlugin) {
_genericFirmwarePlugin = new FirmwarePlugin;
}
return _genericFirmwarePlugin;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/timer/timer.hpp>
#include "perf_sim.h"
static const uint32 PORT_LATENCY = 1;
static const uint32 PORT_FANOUT = 1;
static const uint32 PORT_BW = 1;
PerfMIPS::PerfMIPS(bool log) : Log( log), rf(), checker()
{
executed_instrs = 0;
wp_fetch_2_decode = make_write_port<uint32>("FETCH_2_DECODE", PORT_BW, PORT_FANOUT);
rp_fetch_2_decode = make_read_port<uint32>("FETCH_2_DECODE", PORT_LATENCY);
wp_decode_2_fetch_stall = make_write_port<bool>("DECODE_2_FETCH_STALL", PORT_BW, PORT_FANOUT);
rp_decode_2_fetch_stall = make_read_port<bool>("DECODE_2_FETCH_STALL", PORT_LATENCY);
wp_decode_2_execute = make_write_port<FuncInstr>("DECODE_2_EXECUTE", PORT_BW, PORT_FANOUT);
rp_decode_2_execute = make_read_port<FuncInstr>("DECODE_2_EXECUTE", PORT_LATENCY);
wp_execute_2_decode_stall = make_write_port<bool>("EXECUTE_2_DECODE_STALL", PORT_BW, PORT_FANOUT);
rp_execute_2_decode_stall = make_read_port<bool>("EXECUTE_2_DECODE_STALL", PORT_LATENCY);
wp_execute_2_memory = make_write_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_BW, PORT_FANOUT);
rp_execute_2_memory = make_read_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_LATENCY);
wp_memory_2_execute_stall = make_write_port<bool>("MEMORY_2_EXECUTE_STALL", PORT_BW, PORT_FANOUT);
rp_memory_2_execute_stall = make_read_port<bool>("MEMORY_2_EXECUTE_STALL", PORT_LATENCY);
wp_memory_2_writeback = make_write_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_BW, PORT_FANOUT);
rp_memory_2_writeback = make_read_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_LATENCY);
wp_writeback_2_memory_stall = make_write_port<bool>("WRITEBACK_2_MEMORY_STALL", PORT_BW, PORT_FANOUT);
rp_writeback_2_memory_stall = make_read_port<bool>("WRITEBACK_2_MEMORY_STALL", PORT_LATENCY);
init_ports();
}
void PerfMIPS::run( const std::string& tr, uint64 instrs_to_run)
{
assert( instrs_to_run < MAX_VAL32);
uint64 cycle = 0;
decode_next_time = false;
mem = new FuncMemory( tr.c_str());
checker.init( tr);
PC = mem->startPC();
PC_is_valid = true;
boost::timer::cpu_timer timer;
while (executed_instrs < instrs_to_run)
{
clock_writeback( cycle);
clock_decode( cycle);
clock_fetch( cycle);
clock_execute( cycle);
clock_memory( cycle);
++cycle;
if ( cycle - last_writeback_cycle >= 1000)
serr << "Deadlock was detected. The process will be aborted.\n\n" << critical;
sout << "Executed instructions: " << executed_instrs << std::endl << std::endl;
check_ports( cycle);
}
auto time = timer.elapsed().wall;
auto frequency = 1e6 * cycle / time;
auto ipc = 1.0 * executed_instrs / cycle;
auto simips = 1e6 * executed_instrs / time;
std::cout << std::endl << "****************************"
<< std::endl << "cycles: " << cycle
<< std::endl << "IPC: " << ipc
<< std::endl << "sim freq: " << frequency << " kHz"
<< std::endl << "sim IPS: " << simips << " kips"
<< std::endl << "****************************"
<< std::endl;
delete mem;
}
void PerfMIPS::clock_fetch( int cycle) {
sout << "fetch cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_decode_2_fetch_stall->read( &is_stall, cycle);
if ( is_stall)
{
sout << "bubble\n";
return;
}
if (PC_is_valid)
{
uint32 module_data = mem->read(PC);
wp_fetch_2_decode->write( module_data, cycle);
sout << std::hex << "0x" << module_data << std::endl;
}
else
{
sout << "bubble\n";
}
}
void PerfMIPS::clock_decode( int cycle) {
sout << "decode cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_execute_2_decode_stall->read( &is_stall, cycle);
if ( is_stall) {
wp_decode_2_fetch_stall->write( true, cycle);
sout << "bubble\n";
return;
}
bool is_anything_from_fetch = rp_fetch_2_decode->read( &decode_data, cycle);
FuncInstr instr( decode_data, PC);
if ( instr.isJump() && is_anything_from_fetch)
PC_is_valid = false;
if ( !is_anything_from_fetch && !decode_next_time)
{
sout << "bubble\n";
return;
}
if ( rf.check( instr.get_src1_num()) &&
rf.check( instr.get_src2_num()) &&
rf.check( instr.get_dst_num()))
{
rf.read_src1( instr);
rf.read_src2( instr);
rf.invalidate( instr.get_dst_num());
wp_decode_2_execute->write( instr, cycle);
decode_next_time = false;
if (!instr.isJump())
PC += 4;
sout << instr << std::endl;
}
else
{
wp_decode_2_fetch_stall->write( true, cycle);
decode_next_time = true;
sout << "bubble\n";
}
}
void PerfMIPS::clock_execute( int cycle)
{
std::ostringstream oss;
sout << "execute cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_memory_2_execute_stall->read( &is_stall, cycle);
if ( is_stall)
{
wp_execute_2_decode_stall->write( true, cycle);
sout << "bubble\n";
return;
}
FuncInstr instr;
if ( !rp_decode_2_execute->read( &instr, cycle))
{
sout << "bubble\n";
return;
}
instr.execute();
wp_execute_2_memory->write( instr, cycle);
sout << instr << std::endl;
}
void PerfMIPS::clock_memory( int cycle)
{
sout << "memory cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_writeback_2_memory_stall->read( &is_stall, cycle);
if ( is_stall)
{
wp_memory_2_execute_stall->write( true, cycle);
sout << "bubble\n";
return;
}
FuncInstr instr;
if ( !rp_execute_2_memory->read( &instr, cycle))
{
sout << "bubble\n";
return;
}
load_store(instr);
wp_memory_2_writeback->write( instr, cycle);
sout << instr << std::endl;
}
void PerfMIPS::clock_writeback( int cycle)
{
sout << "wb cycle " << std::dec << cycle << ":";
FuncInstr instr;
if ( !rp_memory_2_writeback->read( &instr, cycle))
{
sout << "bubble\n";
return;
}
if ( instr.isJump())
{
PC_is_valid = true;
PC = instr.get_new_PC();
}
rf.write_dst( instr);
sout << instr << std::endl;
check(instr);
++executed_instrs;
last_writeback_cycle = cycle;
}
void PerfMIPS::check( const FuncInstr& instr)
{
std::ostringstream perf_dump_s;
perf_dump_s << instr << std::endl;
std::string perf_dump = perf_dump_s.str();
std::ostringstream checker_dump_s;
checker.step(checker_dump_s);
std::string checker_dump = checker_dump_s.str();
if (checker_dump != perf_dump)
{
serr << "****************************" << std::endl
<< "Mismatch: " << std::endl
<< "Checker output: " << checker_dump
<< "PerfSim output: " << perf_dump
<< critical;
}
}
PerfMIPS::~PerfMIPS() {
}
<commit_msg>Move deadlock detector to WB stage<commit_after>#include <iostream>
#include <boost/timer/timer.hpp>
#include "perf_sim.h"
static const uint32 PORT_LATENCY = 1;
static const uint32 PORT_FANOUT = 1;
static const uint32 PORT_BW = 1;
PerfMIPS::PerfMIPS(bool log) : Log( log), rf(), checker()
{
executed_instrs = 0;
wp_fetch_2_decode = make_write_port<uint32>("FETCH_2_DECODE", PORT_BW, PORT_FANOUT);
rp_fetch_2_decode = make_read_port<uint32>("FETCH_2_DECODE", PORT_LATENCY);
wp_decode_2_fetch_stall = make_write_port<bool>("DECODE_2_FETCH_STALL", PORT_BW, PORT_FANOUT);
rp_decode_2_fetch_stall = make_read_port<bool>("DECODE_2_FETCH_STALL", PORT_LATENCY);
wp_decode_2_execute = make_write_port<FuncInstr>("DECODE_2_EXECUTE", PORT_BW, PORT_FANOUT);
rp_decode_2_execute = make_read_port<FuncInstr>("DECODE_2_EXECUTE", PORT_LATENCY);
wp_execute_2_decode_stall = make_write_port<bool>("EXECUTE_2_DECODE_STALL", PORT_BW, PORT_FANOUT);
rp_execute_2_decode_stall = make_read_port<bool>("EXECUTE_2_DECODE_STALL", PORT_LATENCY);
wp_execute_2_memory = make_write_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_BW, PORT_FANOUT);
rp_execute_2_memory = make_read_port<FuncInstr>("EXECUTE_2_MEMORY", PORT_LATENCY);
wp_memory_2_execute_stall = make_write_port<bool>("MEMORY_2_EXECUTE_STALL", PORT_BW, PORT_FANOUT);
rp_memory_2_execute_stall = make_read_port<bool>("MEMORY_2_EXECUTE_STALL", PORT_LATENCY);
wp_memory_2_writeback = make_write_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_BW, PORT_FANOUT);
rp_memory_2_writeback = make_read_port<FuncInstr>("MEMORY_2_WRITEBACK", PORT_LATENCY);
wp_writeback_2_memory_stall = make_write_port<bool>("WRITEBACK_2_MEMORY_STALL", PORT_BW, PORT_FANOUT);
rp_writeback_2_memory_stall = make_read_port<bool>("WRITEBACK_2_MEMORY_STALL", PORT_LATENCY);
init_ports();
}
void PerfMIPS::run( const std::string& tr, uint64 instrs_to_run)
{
assert( instrs_to_run < MAX_VAL32);
uint64 cycle = 0;
decode_next_time = false;
mem = new FuncMemory( tr.c_str());
checker.init( tr);
PC = mem->startPC();
PC_is_valid = true;
boost::timer::cpu_timer timer;
while (executed_instrs < instrs_to_run)
{
clock_writeback( cycle);
clock_decode( cycle);
clock_fetch( cycle);
clock_execute( cycle);
clock_memory( cycle);
++cycle;
sout << "Executed instructions: " << executed_instrs << std::endl << std::endl;
check_ports( cycle);
}
auto time = timer.elapsed().wall;
auto frequency = 1e6 * cycle / time;
auto ipc = 1.0 * executed_instrs / cycle;
auto simips = 1e6 * executed_instrs / time;
std::cout << std::endl << "****************************"
<< std::endl << "cycles: " << cycle
<< std::endl << "IPC: " << ipc
<< std::endl << "sim freq: " << frequency << " kHz"
<< std::endl << "sim IPS: " << simips << " kips"
<< std::endl << "****************************"
<< std::endl;
delete mem;
}
void PerfMIPS::clock_fetch( int cycle) {
sout << "fetch cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_decode_2_fetch_stall->read( &is_stall, cycle);
if ( is_stall)
{
sout << "bubble\n";
return;
}
if (PC_is_valid)
{
uint32 module_data = mem->read(PC);
wp_fetch_2_decode->write( module_data, cycle);
sout << std::hex << "0x" << module_data << std::endl;
}
else
{
sout << "bubble\n";
}
}
void PerfMIPS::clock_decode( int cycle) {
sout << "decode cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_execute_2_decode_stall->read( &is_stall, cycle);
if ( is_stall) {
wp_decode_2_fetch_stall->write( true, cycle);
sout << "bubble\n";
return;
}
bool is_anything_from_fetch = rp_fetch_2_decode->read( &decode_data, cycle);
FuncInstr instr( decode_data, PC);
if ( instr.isJump() && is_anything_from_fetch)
PC_is_valid = false;
if ( !is_anything_from_fetch && !decode_next_time)
{
sout << "bubble\n";
return;
}
if ( rf.check( instr.get_src1_num()) &&
rf.check( instr.get_src2_num()) &&
rf.check( instr.get_dst_num()))
{
rf.read_src1( instr);
rf.read_src2( instr);
rf.invalidate( instr.get_dst_num());
wp_decode_2_execute->write( instr, cycle);
decode_next_time = false;
if (!instr.isJump())
PC += 4;
sout << instr << std::endl;
}
else
{
wp_decode_2_fetch_stall->write( true, cycle);
decode_next_time = true;
sout << "bubble\n";
}
}
void PerfMIPS::clock_execute( int cycle)
{
std::ostringstream oss;
sout << "execute cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_memory_2_execute_stall->read( &is_stall, cycle);
if ( is_stall)
{
wp_execute_2_decode_stall->write( true, cycle);
sout << "bubble\n";
return;
}
FuncInstr instr;
if ( !rp_decode_2_execute->read( &instr, cycle))
{
sout << "bubble\n";
return;
}
instr.execute();
wp_execute_2_memory->write( instr, cycle);
sout << instr << std::endl;
}
void PerfMIPS::clock_memory( int cycle)
{
sout << "memory cycle " << std::dec << cycle << ":";
bool is_stall = false;
rp_writeback_2_memory_stall->read( &is_stall, cycle);
if ( is_stall)
{
wp_memory_2_execute_stall->write( true, cycle);
sout << "bubble\n";
return;
}
FuncInstr instr;
if ( !rp_execute_2_memory->read( &instr, cycle))
{
sout << "bubble\n";
return;
}
load_store(instr);
wp_memory_2_writeback->write( instr, cycle);
sout << instr << std::endl;
}
void PerfMIPS::clock_writeback( int cycle)
{
sout << "wb cycle " << std::dec << cycle << ":";
FuncInstr instr;
if ( !rp_memory_2_writeback->read( &instr, cycle))
{
sout << "bubble\n";
if ( cycle - last_writeback_cycle >= 1000)
{
serr << "Deadlock was detected. The process will be aborted."
<< std::endl << std::endl << critical;
}
return;
}
if ( instr.isJump())
{
PC_is_valid = true;
PC = instr.get_new_PC();
}
rf.write_dst( instr);
sout << instr << std::endl;
check(instr);
++executed_instrs;
last_writeback_cycle = cycle;
}
void PerfMIPS::check( const FuncInstr& instr)
{
std::ostringstream perf_dump_s;
perf_dump_s << instr << std::endl;
std::string perf_dump = perf_dump_s.str();
std::ostringstream checker_dump_s;
checker.step(checker_dump_s);
std::string checker_dump = checker_dump_s.str();
if (checker_dump != perf_dump)
{
serr << "****************************" << std::endl
<< "Mismatch: " << std::endl
<< "Checker output: " << checker_dump
<< "PerfSim output: " << perf_dump
<< critical;
}
}
PerfMIPS::~PerfMIPS() {
}
<|endoftext|> |
<commit_before>/*
* OpenSSL utilities.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef BENG_PROXY_SSL_UNIQUE_HXX
#define BENG_PROXY_SSL_UNIQUE_HXX
#include <openssl/ssl.h>
#include <memory>
struct OpenSslDelete {
void operator()(SSL *ssl) {
SSL_free(ssl);
}
void operator()(SSL_CTX *ssl_ctx) {
SSL_CTX_free(ssl_ctx);
}
void operator()(X509 *x509) {
X509_free(x509);
}
void operator()(X509_NAME *name) {
X509_NAME_free(name);
}
void operator()(X509_EXTENSION *ext) {
X509_EXTENSION_free(ext);
}
void operator()(EC_KEY *key) {
EC_KEY_free(key);
}
void operator()(EVP_PKEY *key) {
EVP_PKEY_free(key);
}
void operator()(EVP_PKEY_CTX *key) {
EVP_PKEY_CTX_free(key);
}
void operator()(BIO *bio) {
BIO_free(bio);
}
};
using UniqueSSL = std::unique_ptr<SSL, OpenSslDelete>;
using UniqueSSL_CTX = std::unique_ptr<SSL_CTX, OpenSslDelete>;
using UniqueX509 = std::unique_ptr<X509, OpenSslDelete>;
using UniqueX509_NAME = std::unique_ptr<X509_NAME, OpenSslDelete>;
using UniqueX509_EXTENSION = std::unique_ptr<X509_EXTENSION, OpenSslDelete>;
using UniqueEC_KEY = std::unique_ptr<EC_KEY, OpenSslDelete>;
using UniqueEVP_PKEY = std::unique_ptr<EVP_PKEY, OpenSslDelete>;
using UniqueEVP_PKEY_CTX = std::unique_ptr<EVP_PKEY_CTX, OpenSslDelete>;
using UniqueBIO = std::unique_ptr<BIO, OpenSslDelete>;
#endif
<commit_msg>ssl/Unique: add overload for GENERAL_NAMES<commit_after>/*
* OpenSSL utilities.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef BENG_PROXY_SSL_UNIQUE_HXX
#define BENG_PROXY_SSL_UNIQUE_HXX
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <memory>
struct OpenSslDelete {
void operator()(SSL *ssl) {
SSL_free(ssl);
}
void operator()(SSL_CTX *ssl_ctx) {
SSL_CTX_free(ssl_ctx);
}
void operator()(X509 *x509) {
X509_free(x509);
}
void operator()(X509_NAME *name) {
X509_NAME_free(name);
}
void operator()(X509_EXTENSION *ext) {
X509_EXTENSION_free(ext);
}
void operator()(GENERAL_NAMES *gn) {
GENERAL_NAMES_free(gn);
}
void operator()(EC_KEY *key) {
EC_KEY_free(key);
}
void operator()(EVP_PKEY *key) {
EVP_PKEY_free(key);
}
void operator()(EVP_PKEY_CTX *key) {
EVP_PKEY_CTX_free(key);
}
void operator()(BIO *bio) {
BIO_free(bio);
}
};
using UniqueSSL = std::unique_ptr<SSL, OpenSslDelete>;
using UniqueSSL_CTX = std::unique_ptr<SSL_CTX, OpenSslDelete>;
using UniqueX509 = std::unique_ptr<X509, OpenSslDelete>;
using UniqueX509_NAME = std::unique_ptr<X509_NAME, OpenSslDelete>;
using UniqueX509_EXTENSION = std::unique_ptr<X509_EXTENSION, OpenSslDelete>;
using UniqueGENERAL_NAMES = std::unique_ptr<GENERAL_NAMES, OpenSslDelete>;
using UniqueEC_KEY = std::unique_ptr<EC_KEY, OpenSslDelete>;
using UniqueEVP_PKEY = std::unique_ptr<EVP_PKEY, OpenSslDelete>;
using UniqueEVP_PKEY_CTX = std::unique_ptr<EVP_PKEY_CTX, OpenSslDelete>;
using UniqueBIO = std::unique_ptr<BIO, OpenSslDelete>;
#endif
<|endoftext|> |
<commit_before><commit_msg>Add const to read-only variables.<commit_after><|endoftext|> |
<commit_before>
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/fscapi.h"
#include "base/util/utils.h"
#include "spds/spdsutils.h"
#include "base/quoted-printable.h"
#include "base/globalsdef.h"
#define BASE64 "base64"
#define QUOTED_PRINTABLE "quoted-printable"
BEGIN_NAMESPACE
// Base64 encoding for files (with newline)
char *uuencode(const char *msg, int len);
SyncMode syncModeCode(const char* syncMode) {
if (strcmp(syncMode,"slow") == 0)
return SYNC_SLOW;
else if (strcmp(syncMode,"two-way") == 0)
return SYNC_TWO_WAY;
else if (strcmp(syncMode,"one-way") == 0) // deprecated
return SYNC_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"one-way-server") == 0 || // deprecated
strcmp(syncMode,"one-way-from-server") == 0 )
return SYNC_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"one-way-client") == 0 || // deprecated
strcmp(syncMode,"one-way-from-client") == 0)
return SYNC_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"refresh") == 0 || // deprecated
strcmp(syncMode,"refresh-server") == 0 || // deprecated
strcmp(syncMode,"refresh-from-server") == 0 )
return SYNC_REFRESH_FROM_SERVER;
else if (strcmp(syncMode,"refresh-client") == 0 || // deprecated
strcmp(syncMode,"refresh-from-client") == 0)
return SYNC_REFRESH_FROM_CLIENT;
//--------- Funambol extension --------------------
else if (strcmp(syncMode,"smart-one-way-from-client") == 0)
return SYNC_SMART_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"smart-one-way-from-server") == 0)
return SYNC_SMART_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"incremental-smart-one-way-from-client") == 0)
return SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"incremental-smart-one-way-from-server") == 0)
return SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode, "addrchange") == 0)
return SYNC_ADDR_CHANGE_NOTIFICATION;
return SYNC_NONE;
}
const char *syncModeKeyword(SyncMode syncMode) {
switch (syncMode) {
case SYNC_SLOW:
return "slow";
case SYNC_TWO_WAY:
return "two-way";
case SYNC_ONE_WAY_FROM_SERVER:
return "one-way-from-server";
case SYNC_ONE_WAY_FROM_CLIENT:
return "one-way-from-client";
case SYNC_REFRESH_FROM_SERVER:
return "refresh-from-server";
case SYNC_REFRESH_FROM_CLIENT:
return "refresh-from-client";
case SYNC_ADDR_CHANGE_NOTIFICATION:
return "addrchange";
case SYNC_NONE:
return "none";
case SYNC_TWO_WAY_BY_SERVER:
return "two-way-by-server";
case SYNC_ONE_WAY_FROM_CLIENT_BY_SERVER:
return "one-way-from-client-by-server";
case SYNC_REFRESH_FROM_CLIENT_BY_SERVER:
return "refresh-from-client-by-server";
case SYNC_ONE_WAY_FROM_SERVER_BY_SERVER:
return "one-way-from-server-by-server";
case SYNC_REFRESH_FROM_SERVER_BY_SERVER:
return "refresh-from-server-by-server";
case SYNC_SMART_ONE_WAY_FROM_CLIENT:
return "smart-one-way-from-client";
case SYNC_SMART_ONE_WAY_FROM_SERVER:
return "smart-one-way-from-server";
case SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_CLIENT:
return "incremental-smart-one-way-from-client";
case SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_SERVER:
return "incremental-smart-one-way-from-server";
}
return "";
}
SyncItemStatus** toSyncItemStatusArray(ArrayList& items) {
int l = items.size();
if (l < 1) {
return NULL;
}
SyncItemStatus** itemArrayStatus = new SyncItemStatus*[l];
for (int i=0; i<l; ++i) {
itemArrayStatus[i] = (SyncItemStatus*)((ArrayElement*)items[i])->clone();
}
return itemArrayStatus;
}
SyncItem** toSyncItemArray(ArrayList& items) {
int l = items.size();
if (l < 1) {
return NULL;
}
SyncItem** itemArray = new SyncItem*[l];
for (int i=0; i<l; ++i) {
itemArray[i] = (SyncItem*)((ArrayElement*)items[i])->clone();
}
return itemArray;
}
/*
* Encode the message in base64, splitting the result in lines of 72 columns
* each.
*/
char *uuencode(const char *msg, int len)
{
int i, step=54, dlen=0;
char *ret = new char[ len * 2 ]; // b64 is 4/3, but we have also the newlines....
for(i=0; i<len; i+=step) {
if(len-i < step)
step = len-i;
dlen += b64_encode(ret+dlen, (void *)(msg+i), step);
if(getLastErrorCode() != 0){
delete [] ret;
return NULL;
}
ret[dlen++]='\n';
}
// Terminate the string
ret[dlen]=0;
return ret;
}
// Get a line from the char buffer msg
// line endings are discarded
// Return the first character after the newline
static const char *getLine(const char *msg, char **line) {
// Null message?
if (!msg)
return 0;
// End of string
if ( *msg == 0)
return 0;
const char *next = strpbrk(msg, "\r\n\0");
int linelen;
if(!next) {
linelen = strlen(msg);
next = msg+linelen;
}
else
linelen = next-msg;
*line= new char[linelen+1];
strncpy(*line, msg, linelen );
(*line)[linelen]=0;
while (*next == '\r' || *next == '\n') {
next++;
}
return next;
}
char* b64EncodeWithSpaces(const char *msg, int len) {
int i, step=54, dlen=0;
char* res = new char[len*3]; // b64 is 4/3, but we have also the newlines....
memset(res, 0, len*3);
res[0] = ' ';
res[1] = ' ';
res[2] = ' ';
res[3] = ' ';
char* ret = &res[4];
for(i=0; i<len; i+=step) {
if(len-i < step) {
step = len-i;
}
dlen += b64_encode(ret+dlen, (void *)(msg+i), step);
ret[dlen++]='\r';
ret[dlen++]='\n';
ret[dlen++]=' ';
ret[dlen++]=' ';
ret[dlen++]=' ';
ret[dlen++]=' ';
}
// Terminate the string
ret[dlen]=0;
int ll = strlen(res);
return res;
}
// This functions works for standard encoded files with new line every
// 72 characters. It does not work if the line length is not multiple of 4.
int uudecode(const char *msg, char **binmsg, size_t *binlen)
{
// Convert the string
const char *buf = msg;
if (!buf)
return -1;
const char *cursor = buf;
char *line;
// Make room for the destination (3/4 of the original)
int outlen = strlen(buf)/4 * 3 + 1;
char *out = new char[outlen+1];
memset(out, 0, outlen);
int len = 0, nl=0;
while( (cursor=getLine(cursor, &line)) != 0) {
if (strstr(line, "]]") != 0)
break;
nl++;
len += b64_decode(out+len, line);
if ( getLastErrorCode() != 0){
delete [] line;
return -1;
}
delete [] line;
}
//delete [] buf;
// Terminate the string
out[len]=0;
// Set return parameters
*binmsg = out;
*binlen = len;
return 0;
}
char *loadAndConvert(const char *filename, const char *encoding)
{
char *msg = 0;
bool binary = true;
size_t msglen=0;
char *ret = 0;
if(!filename)
return 0;
if( strcmp(encoding, "base64") == 0 ) {
binary = true;
}
// Read file
if(!readFile(filename, &msg, &msglen, binary))
return 0;
// Encode the file
if( strcmp(encoding, BASE64) == 0 ) {
ret = uuencode(msg, msglen);
delete [] msg;
}
else if( strcmp(encoding, QUOTED_PRINTABLE) == 0 ) {
if(qp_isNeed(msg))
ret = qp_encode(msg);
delete [] msg;
}
else { // Default 8bit
ret = msg;
}
return ret;
}
int convertAndSave(const char *filename,
const char *s,
const char *encoding)
{
char *buf, *name = stringdup(filename);
bool binary = true;
size_t len;
if(!name)
return -1;
// Decode the file
if( strcmp(encoding, BASE64) == 0 ) {
if( uudecode(s, &buf, &len) ) {
return -1;
}
binary = true;
} else if( strcmp(encoding, QUOTED_PRINTABLE) == 0 ) {
if (s == NULL)
return -1;
buf = qp_decode(s);
len = strlen(buf);
binary = true;
}
else { // Default UTF-8
buf = stringdup(s);
len = strlen(buf);
}
saveFile(name, buf, len, binary);
delete [] buf;
delete [] name;
return 0;
}
const char* getSourceName(const char *uri)
{
#if 0
// FIXME
char nodeName = new char[];
strcpy(nodeName, rootContext); strcat(nodeName, CONTEXT_SPDS_SOURCES);
node = dmt->readManagementNode(nodeName);
if ( ! node ) {
//lastErrorCode = ERR_INVALID_CONTEXT;
//sprintf(lastErrorMsg, ERRMSG_INVALID_CONTEXT, nodeName);
setErrorf(ERR_INVALID_CONTEXT, ERRMSG_INVALID_CONTEXT, nodeName);
goto finally;
}
n = node->getChildrenMaxCount();
for()
#else
// FIXME
return stringdup(uri);
#endif
}
int indent(StringBuffer& content, int space){
StringBuffer buf;
char* startingBuf = new char[space +1];
memset(startingBuf, ' ', space);
startingBuf[space] = 0;
buf = startingBuf;
char* spacebuf = new char[space +2];
spacebuf[0] = '\n';
memset((spacebuf+1), ' ', space);
spacebuf[space+1] = 0;
content.replaceAll("\n", spacebuf);
buf.append(content);
content = buf;
delete [] spacebuf;
delete [] startingBuf;
return 0;
}
END_NAMESPACE
<commit_msg>Code cleanup: avoid warning for unused variable<commit_after>
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/fscapi.h"
#include "base/util/utils.h"
#include "spds/spdsutils.h"
#include "base/quoted-printable.h"
#include "base/globalsdef.h"
#define BASE64 "base64"
#define QUOTED_PRINTABLE "quoted-printable"
BEGIN_NAMESPACE
// Base64 encoding for files (with newline)
char *uuencode(const char *msg, int len);
SyncMode syncModeCode(const char* syncMode) {
if (strcmp(syncMode,"slow") == 0)
return SYNC_SLOW;
else if (strcmp(syncMode,"two-way") == 0)
return SYNC_TWO_WAY;
else if (strcmp(syncMode,"one-way") == 0) // deprecated
return SYNC_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"one-way-server") == 0 || // deprecated
strcmp(syncMode,"one-way-from-server") == 0 )
return SYNC_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"one-way-client") == 0 || // deprecated
strcmp(syncMode,"one-way-from-client") == 0)
return SYNC_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"refresh") == 0 || // deprecated
strcmp(syncMode,"refresh-server") == 0 || // deprecated
strcmp(syncMode,"refresh-from-server") == 0 )
return SYNC_REFRESH_FROM_SERVER;
else if (strcmp(syncMode,"refresh-client") == 0 || // deprecated
strcmp(syncMode,"refresh-from-client") == 0)
return SYNC_REFRESH_FROM_CLIENT;
//--------- Funambol extension --------------------
else if (strcmp(syncMode,"smart-one-way-from-client") == 0)
return SYNC_SMART_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"smart-one-way-from-server") == 0)
return SYNC_SMART_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode,"incremental-smart-one-way-from-client") == 0)
return SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_CLIENT;
else if (strcmp(syncMode,"incremental-smart-one-way-from-server") == 0)
return SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_SERVER;
else if (strcmp(syncMode, "addrchange") == 0)
return SYNC_ADDR_CHANGE_NOTIFICATION;
return SYNC_NONE;
}
const char *syncModeKeyword(SyncMode syncMode) {
switch (syncMode) {
case SYNC_SLOW:
return "slow";
case SYNC_TWO_WAY:
return "two-way";
case SYNC_ONE_WAY_FROM_SERVER:
return "one-way-from-server";
case SYNC_ONE_WAY_FROM_CLIENT:
return "one-way-from-client";
case SYNC_REFRESH_FROM_SERVER:
return "refresh-from-server";
case SYNC_REFRESH_FROM_CLIENT:
return "refresh-from-client";
case SYNC_ADDR_CHANGE_NOTIFICATION:
return "addrchange";
case SYNC_NONE:
return "none";
case SYNC_TWO_WAY_BY_SERVER:
return "two-way-by-server";
case SYNC_ONE_WAY_FROM_CLIENT_BY_SERVER:
return "one-way-from-client-by-server";
case SYNC_REFRESH_FROM_CLIENT_BY_SERVER:
return "refresh-from-client-by-server";
case SYNC_ONE_WAY_FROM_SERVER_BY_SERVER:
return "one-way-from-server-by-server";
case SYNC_REFRESH_FROM_SERVER_BY_SERVER:
return "refresh-from-server-by-server";
case SYNC_SMART_ONE_WAY_FROM_CLIENT:
return "smart-one-way-from-client";
case SYNC_SMART_ONE_WAY_FROM_SERVER:
return "smart-one-way-from-server";
case SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_CLIENT:
return "incremental-smart-one-way-from-client";
case SYNC_INCREMENTAL_SMART_ONE_WAY_FROM_SERVER:
return "incremental-smart-one-way-from-server";
}
return "";
}
SyncItemStatus** toSyncItemStatusArray(ArrayList& items) {
int l = items.size();
if (l < 1) {
return NULL;
}
SyncItemStatus** itemArrayStatus = new SyncItemStatus*[l];
for (int i=0; i<l; ++i) {
itemArrayStatus[i] = (SyncItemStatus*)((ArrayElement*)items[i])->clone();
}
return itemArrayStatus;
}
SyncItem** toSyncItemArray(ArrayList& items) {
int l = items.size();
if (l < 1) {
return NULL;
}
SyncItem** itemArray = new SyncItem*[l];
for (int i=0; i<l; ++i) {
itemArray[i] = (SyncItem*)((ArrayElement*)items[i])->clone();
}
return itemArray;
}
/*
* Encode the message in base64, splitting the result in lines of 72 columns
* each.
*/
char *uuencode(const char *msg, int len)
{
int i, step=54, dlen=0;
char *ret = new char[ len * 2 ]; // b64 is 4/3, but we have also the newlines....
for(i=0; i<len; i+=step) {
if(len-i < step)
step = len-i;
dlen += b64_encode(ret+dlen, (void *)(msg+i), step);
if(getLastErrorCode() != 0){
delete [] ret;
return NULL;
}
ret[dlen++]='\n';
}
// Terminate the string
ret[dlen]=0;
return ret;
}
// Get a line from the char buffer msg
// line endings are discarded
// Return the first character after the newline
static const char *getLine(const char *msg, char **line) {
// Null message?
if (!msg)
return 0;
// End of string
if ( *msg == 0)
return 0;
const char *next = strpbrk(msg, "\r\n\0");
int linelen;
if(!next) {
linelen = strlen(msg);
next = msg+linelen;
}
else
linelen = next-msg;
*line= new char[linelen+1];
strncpy(*line, msg, linelen );
(*line)[linelen]=0;
while (*next == '\r' || *next == '\n') {
next++;
}
return next;
}
char* b64EncodeWithSpaces(const char *msg, int len) {
int i, step=54, dlen=0;
char* res = new char[len*3]; // b64 is 4/3, but we have also the newlines....
memset(res, 0, len*3);
res[0] = ' ';
res[1] = ' ';
res[2] = ' ';
res[3] = ' ';
char* ret = &res[4];
for(i=0; i<len; i+=step) {
if(len-i < step) {
step = len-i;
}
dlen += b64_encode(ret+dlen, (void *)(msg+i), step);
ret[dlen++]='\r';
ret[dlen++]='\n';
ret[dlen++]=' ';
ret[dlen++]=' ';
ret[dlen++]=' ';
ret[dlen++]=' ';
}
// Terminate the string
ret[dlen]=0;
return res;
}
// This functions works for standard encoded files with new line every
// 72 characters. It does not work if the line length is not multiple of 4.
int uudecode(const char *msg, char **binmsg, size_t *binlen)
{
// Convert the string
const char *buf = msg;
if (!buf)
return -1;
const char *cursor = buf;
char *line;
// Make room for the destination (3/4 of the original)
int outlen = strlen(buf)/4 * 3 + 1;
char *out = new char[outlen+1];
memset(out, 0, outlen);
int len = 0, nl=0;
while( (cursor=getLine(cursor, &line)) != 0) {
if (strstr(line, "]]") != 0)
break;
nl++;
len += b64_decode(out+len, line);
if ( getLastErrorCode() != 0){
delete [] line;
return -1;
}
delete [] line;
}
//delete [] buf;
// Terminate the string
out[len]=0;
// Set return parameters
*binmsg = out;
*binlen = len;
return 0;
}
char *loadAndConvert(const char *filename, const char *encoding)
{
char *msg = 0;
bool binary = true;
size_t msglen=0;
char *ret = 0;
if(!filename)
return 0;
if( strcmp(encoding, "base64") == 0 ) {
binary = true;
}
// Read file
if(!readFile(filename, &msg, &msglen, binary))
return 0;
// Encode the file
if( strcmp(encoding, BASE64) == 0 ) {
ret = uuencode(msg, msglen);
delete [] msg;
}
else if( strcmp(encoding, QUOTED_PRINTABLE) == 0 ) {
if(qp_isNeed(msg))
ret = qp_encode(msg);
delete [] msg;
}
else { // Default 8bit
ret = msg;
}
return ret;
}
int convertAndSave(const char *filename,
const char *s,
const char *encoding)
{
char *buf, *name = stringdup(filename);
bool binary = true;
size_t len;
if(!name)
return -1;
// Decode the file
if( strcmp(encoding, BASE64) == 0 ) {
if( uudecode(s, &buf, &len) ) {
return -1;
}
binary = true;
} else if( strcmp(encoding, QUOTED_PRINTABLE) == 0 ) {
if (s == NULL)
return -1;
buf = qp_decode(s);
len = strlen(buf);
binary = true;
}
else { // Default UTF-8
buf = stringdup(s);
len = strlen(buf);
}
saveFile(name, buf, len, binary);
delete [] buf;
delete [] name;
return 0;
}
const char* getSourceName(const char *uri)
{
#if 0
// FIXME
char nodeName = new char[];
strcpy(nodeName, rootContext); strcat(nodeName, CONTEXT_SPDS_SOURCES);
node = dmt->readManagementNode(nodeName);
if ( ! node ) {
//lastErrorCode = ERR_INVALID_CONTEXT;
//sprintf(lastErrorMsg, ERRMSG_INVALID_CONTEXT, nodeName);
setErrorf(ERR_INVALID_CONTEXT, ERRMSG_INVALID_CONTEXT, nodeName);
goto finally;
}
n = node->getChildrenMaxCount();
for()
#else
// FIXME
return stringdup(uri);
#endif
}
int indent(StringBuffer& content, int space){
StringBuffer buf;
char* startingBuf = new char[space +1];
memset(startingBuf, ' ', space);
startingBuf[space] = 0;
buf = startingBuf;
char* spacebuf = new char[space +2];
spacebuf[0] = '\n';
memset((spacebuf+1), ' ', space);
spacebuf[space+1] = 0;
content.replaceAll("\n", spacebuf);
buf.append(content);
content = buf;
delete [] spacebuf;
delete [] startingBuf;
return 0;
}
END_NAMESPACE
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Desktop 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 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "KdeMainWindow.h"
#include <QClipboard>
#include <QtGui/QLabel>
#include <QtGui/QPainter>
#include <KApplication>
#include <KIcon>
#include <KLocale>
#include <KActionCollection>
#include <KStandardAction>
#include <KStatusBar>
#include <KMessageBox>
#include <KFileDialog>
#include <KToggleFullScreenAction>
#include <KPrinter>
#include "settings.h"
// #include <KPrintDialogPage>
MainWindow::MainWindow(QWidget *parent)
: KXmlGuiWindow(parent)
{
m_controlView = new ControlView(this);
setCentralWidget( m_controlView );
setupActions();
setXMLFile("marbleui.rc");
// Create the statusbar and populate it with initial data.
createStatusBar();
connect( m_controlView->marbleWidget(), SIGNAL( zoomChanged( int ) ),
this, SLOT( showZoom( int ) ) );
showZoom( m_controlView->marbleWidget()->zoom() );
setAutoSaveSettings();
}
MainWindow::~MainWindow()
{
writeSettings();
}
void MainWindow::setupActions()
{
// Action: Print Map
m_printMapAction = KStandardAction::print( this, SLOT( printMapScreenShot() ), actionCollection() );
// Action: Export Map
m_exportMapAction = new KAction( this );
actionCollection()->addAction( "exportMap", m_exportMapAction );
m_exportMapAction->setText( i18n( "&Export Map..." ) );
m_exportMapAction->setIcon( KIcon( "document-save-as" ) );
m_exportMapAction->setShortcut( Qt::CTRL + Qt::Key_S );
connect( m_exportMapAction, SIGNAL(triggered( bool ) ),
this, SLOT( exportMapScreenShot() ) );
// Action: Copy Map to the Clipboard
m_copyMapAction = KStandardAction::copy( this, SLOT( copyMap() ), actionCollection() );
m_copyMapAction->setText( i18n( "&Copy Map" ) );
// Action: Open a Gpx or a Kml File
m_openAct = KStandardAction::open( this, SLOT( openFile() ), actionCollection() );
m_openAct->setText( i18n( "&Open Map..." ) );
// m_openAct->setStatusTip( tr( "Open a file for viewing on
// Marble"));
// Standard actions. So far only Quit.
KStandardAction::quit( kapp, SLOT( closeAllWindows() ), actionCollection() );
m_sideBarAct = new KAction( i18n("Show &Navigation Panel"), this );
actionCollection()->addAction( "options_show_sidebar", m_sideBarAct );
m_sideBarAct->setShortcut( Qt::Key_F9 );
m_sideBarAct->setCheckable( true );
m_sideBarAct->setChecked( true );
m_sideBarAct->setStatusTip( i18n( "Show Navigation Panel" ) );
connect( m_sideBarAct, SIGNAL( triggered( bool ) ), this, SLOT( showSideBar( bool ) ) );
m_fullScreenAct = KStandardAction::fullScreen( 0, 0, this, actionCollection() );
connect( m_fullScreenAct, SIGNAL( triggered( bool ) ), this, SLOT( showFullScreen( bool ) ) );
setupGUI();
}
void MainWindow::createStatusBar()
{
// This hides the normal statusbar contents until clearMessage() is called.
//statusBar()->showMessage( i18n( "Ready" ) );
m_zoomLabel = new QLabel( statusBar() );
statusBar()->addWidget(m_zoomLabel);
}
void MainWindow::saveProperties( KConfigGroup &group )
{
Q_UNUSED( group )
}
void MainWindow::readProperties( const KConfigGroup &group )
{
Q_UNUSED( group )
}
void MainWindow::writeSettings()
{
double homeLon = 0;
double homeLat = 0;
int homeZoom = 0;
m_controlView->marbleWidget()->home( homeLon, homeLat, homeZoom );
MarbleSettings::setHomeLongitude( homeLon );
MarbleSettings::setHomeLatitude( homeLat );
MarbleSettings::setHomeZoom( homeZoom );
MarbleSettings::self()->writeConfig();
}
void MainWindow::readSettings()
{
m_controlView->marbleWidget()->setHome(
MarbleSettings::homeLongitude(),
MarbleSettings::homeLatitude(),
MarbleSettings::homeZoom()
);
m_controlView->marbleWidget()->goHome();
}
void MainWindow::showZoom(int zoom)
{
m_zoomLabel->setText( i18n( "Zoom: %1", QString("%1").arg ( zoom, 4 ) ) );
}
void MainWindow::exportMapScreenShot()
{
QPixmap mapPixmap = m_controlView->mapScreenShot();
QString fileName = KFileDialog::getSaveFileName( QDir::homePath(),
i18n( "Images (*.jpg *.png)" ),
this, i18n("Export Map") );
if ( !fileName.isEmpty() ) {
bool success = mapPixmap.save( fileName );
if ( !success ) {
KMessageBox::error( this, i18nc( "Application name", "Marble" ),
i18n( "An error occurred while trying to save the file.\n" ),
KMessageBox::Notify );
}
}
}
void MainWindow::printMapScreenShot()
{
QPixmap mapPixmap = m_controlView->mapScreenShot();
QSize printSize = mapPixmap.size();
KPrinter printer;
if ( printer.setup( this ) ) {
QRect mapPageRect = printer.pageRect();
printSize.scale( ( printer.pageRect() ).size(), Qt::KeepAspectRatio );
QPoint printTopLeft( mapPageRect.x() + mapPageRect.width() / 2
- printSize.width() / 2,
mapPageRect.y() + mapPageRect.height() / 2
- printSize.height() / 2 );
QRect mapPrintRect( printTopLeft, printSize );
QPainter painter( &printer );
painter.drawPixmap( mapPrintRect, mapPixmap, mapPixmap.rect() );
}
}
void MainWindow::openFile()
{
QString fileName;
fileName = KFileDialog::getOpenFileName( KUrl(),
i18n("*.gpx|GPS Data\n*.kml"),
this, i18n("Open File")
);/*
fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
QString(),
tr("GPS Data(*.gpx);;KML(*.kml)"));*/
if ( ! fileName.isNull() ) {
QString extension = fileName.section( '.', -1 );
if ( extension.compare( "gpx", Qt::CaseInsensitive ) == 0 ) {
m_controlView->marbleWidget()->openGpxFile( fileName );
}
else if ( extension.compare( "kml", Qt::CaseInsensitive ) == 0 ) {
m_controlView->marbleWidget()->addPlaceMarkFile( fileName );
}
}
}
#include "KdeMainWindow.moc"
<commit_msg>of course, any settings will be happily ignored if i won't readSettings() at startup...<commit_after>//
// This file is part of the Marble Desktop 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 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "KdeMainWindow.h"
#include <QClipboard>
#include <QtGui/QLabel>
#include <QtGui/QPainter>
#include <KApplication>
#include <KIcon>
#include <KLocale>
#include <KActionCollection>
#include <KStandardAction>
#include <KStatusBar>
#include <KMessageBox>
#include <KFileDialog>
#include <KToggleFullScreenAction>
#include <KPrinter>
#include "settings.h"
// #include <KPrintDialogPage>
MainWindow::MainWindow(QWidget *parent)
: KXmlGuiWindow(parent)
{
m_controlView = new ControlView(this);
setCentralWidget( m_controlView );
setupActions();
setXMLFile("marbleui.rc");
// Create the statusbar and populate it with initial data.
createStatusBar();
connect( m_controlView->marbleWidget(), SIGNAL( zoomChanged( int ) ),
this, SLOT( showZoom( int ) ) );
showZoom( m_controlView->marbleWidget()->zoom() );
setAutoSaveSettings();
}
MainWindow::~MainWindow()
{
writeSettings();
}
void MainWindow::setupActions()
{
// Action: Print Map
m_printMapAction = KStandardAction::print( this, SLOT( printMapScreenShot() ), actionCollection() );
// Action: Export Map
m_exportMapAction = new KAction( this );
actionCollection()->addAction( "exportMap", m_exportMapAction );
m_exportMapAction->setText( i18n( "&Export Map..." ) );
m_exportMapAction->setIcon( KIcon( "document-save-as" ) );
m_exportMapAction->setShortcut( Qt::CTRL + Qt::Key_S );
connect( m_exportMapAction, SIGNAL(triggered( bool ) ),
this, SLOT( exportMapScreenShot() ) );
// Action: Copy Map to the Clipboard
m_copyMapAction = KStandardAction::copy( this, SLOT( copyMap() ), actionCollection() );
m_copyMapAction->setText( i18n( "&Copy Map" ) );
// Action: Open a Gpx or a Kml File
m_openAct = KStandardAction::open( this, SLOT( openFile() ), actionCollection() );
m_openAct->setText( i18n( "&Open Map..." ) );
// m_openAct->setStatusTip( tr( "Open a file for viewing on
// Marble"));
// Standard actions. So far only Quit.
KStandardAction::quit( kapp, SLOT( closeAllWindows() ), actionCollection() );
m_sideBarAct = new KAction( i18n("Show &Navigation Panel"), this );
actionCollection()->addAction( "options_show_sidebar", m_sideBarAct );
m_sideBarAct->setShortcut( Qt::Key_F9 );
m_sideBarAct->setCheckable( true );
m_sideBarAct->setChecked( true );
m_sideBarAct->setStatusTip( i18n( "Show Navigation Panel" ) );
connect( m_sideBarAct, SIGNAL( triggered( bool ) ), this, SLOT( showSideBar( bool ) ) );
m_fullScreenAct = KStandardAction::fullScreen( 0, 0, this, actionCollection() );
connect( m_fullScreenAct, SIGNAL( triggered( bool ) ), this, SLOT( showFullScreen( bool ) ) );
setupGUI();
readSettings();
}
void MainWindow::createStatusBar()
{
// This hides the normal statusbar contents until clearMessage() is called.
//statusBar()->showMessage( i18n( "Ready" ) );
m_zoomLabel = new QLabel( statusBar() );
statusBar()->addWidget(m_zoomLabel);
}
void MainWindow::saveProperties( KConfigGroup &group )
{
Q_UNUSED( group )
}
void MainWindow::readProperties( const KConfigGroup &group )
{
Q_UNUSED( group )
}
void MainWindow::writeSettings()
{
double homeLon = 0;
double homeLat = 0;
int homeZoom = 0;
m_controlView->marbleWidget()->home( homeLon, homeLat, homeZoom );
MarbleSettings::setHomeLongitude( homeLon );
MarbleSettings::setHomeLatitude( homeLat );
MarbleSettings::setHomeZoom( homeZoom );
MarbleSettings::self()->writeConfig();
}
void MainWindow::readSettings()
{
m_controlView->marbleWidget()->setHome(
MarbleSettings::homeLongitude(),
MarbleSettings::homeLatitude(),
MarbleSettings::homeZoom()
);
m_controlView->marbleWidget()->goHome();
}
void MainWindow::showZoom(int zoom)
{
m_zoomLabel->setText( i18n( "Zoom: %1", QString("%1").arg ( zoom, 4 ) ) );
}
void MainWindow::exportMapScreenShot()
{
QPixmap mapPixmap = m_controlView->mapScreenShot();
QString fileName = KFileDialog::getSaveFileName( QDir::homePath(),
i18n( "Images (*.jpg *.png)" ),
this, i18n("Export Map") );
if ( !fileName.isEmpty() ) {
bool success = mapPixmap.save( fileName );
if ( !success ) {
KMessageBox::error( this, i18nc( "Application name", "Marble" ),
i18n( "An error occurred while trying to save the file.\n" ),
KMessageBox::Notify );
}
}
}
void MainWindow::printMapScreenShot()
{
QPixmap mapPixmap = m_controlView->mapScreenShot();
QSize printSize = mapPixmap.size();
KPrinter printer;
if ( printer.setup( this ) ) {
QRect mapPageRect = printer.pageRect();
printSize.scale( ( printer.pageRect() ).size(), Qt::KeepAspectRatio );
QPoint printTopLeft( mapPageRect.x() + mapPageRect.width() / 2
- printSize.width() / 2,
mapPageRect.y() + mapPageRect.height() / 2
- printSize.height() / 2 );
QRect mapPrintRect( printTopLeft, printSize );
QPainter painter( &printer );
painter.drawPixmap( mapPrintRect, mapPixmap, mapPixmap.rect() );
}
}
void MainWindow::openFile()
{
QString fileName;
fileName = KFileDialog::getOpenFileName( KUrl(),
i18n("*.gpx|GPS Data\n*.kml"),
this, i18n("Open File")
);/*
fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
QString(),
tr("GPS Data(*.gpx);;KML(*.kml)"));*/
if ( ! fileName.isNull() ) {
QString extension = fileName.section( '.', -1 );
if ( extension.compare( "gpx", Qt::CaseInsensitive ) == 0 ) {
m_controlView->marbleWidget()->openGpxFile( fileName );
}
else if ( extension.compare( "kml", Qt::CaseInsensitive ) == 0 ) {
m_controlView->marbleWidget()->addPlaceMarkFile( fileName );
}
}
}
#include "KdeMainWindow.moc"
<|endoftext|> |
<commit_before>#include "filedownloader.hpp"
using namespace player;
#define BITRATE 800.0 //kbits
#define DATA_SIZE 4096.0 //byte
FileDownloader::FileDownloader(int interest_lifetime) : m_face(m_ioService)
{
this->interest_lifetime = interest_lifetime;
}
shared_ptr<itec::Buffer> FileDownloader::getFile(string name){
this->buffer.clear();
this->buffer.resize (20,chunk());
this->state = process_state::running;
this->requestRate = 1000000/(BITRATE*1000/DATA_SIZE*8); //microseconds
this->file = shared_ptr<itec::Buffer>(new itec::Buffer());
this->file_name = name;
boost::asio::deadline_timer timer(m_ioService, boost::posix_time::microseconds(requestRate));
sendNextInterest(&timer); // starts the download
// processEvents will block until the requested data received or timeout occurs#
boost::posix_time::ptime startTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time());
m_face.processEvents();
boost::posix_time::ptime endTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time());
boost::posix_time::time_duration downloadDuration = endTime-startTime;
double dwrate = 0.0;
for(int i = 0; i < buffer.size (); i++)
{
if(buffer.at(i).state == chunk_state::received)
dwrate+=buffer.at(i).data->getSize();
}
if(downloadDuration.total_milliseconds () > 0)
{
dwrate = (dwrate * 8) / downloadDuration.total_milliseconds (); //bits/ms
dwrate *= 1000; //bits/s
}
else
dwrate = 0.0;
fprintf(stderr, "dwrate = %f\n", dwrate);
return file;
}
// send next pending interest, returns success-indicator
void FileDownloader::sendNextInterest(boost::asio::deadline_timer* timer)
{
if(allChunksReceived ())// all chunks / file has been downloaded
{
//TODO Cleanup;
onFileReceived();
return;
}
// check if caller cancelled
if(this->state == process_state::cancelled)
{
m_face.shutdown(); // dangerous?
return;
}
for(uint index = 0; index < buffer.size(); index++)
{
if(buffer[index].state == chunk_state::unavailable)
{
expressInterest(index);
buffer[index].state = chunk_state::requested;
timer->expires_at (timer->expires_at ()+ boost::posix_time::microseconds(requestRate));
timer->async_wait(bind(&FileDownloader::sendNextInterest, this, timer));
return;
}
}
timer->expires_at (timer->expires_at ()+ boost::posix_time::microseconds(requestRate));
timer->async_wait(bind(&FileDownloader::sendNextInterest, this, timer));
}
void FileDownloader::expressInterest(int seq_nr)
{
Interest interest(Name(file_name).appendSequenceNumber(seq_nr)); // e.g. "/example/testApp/randomData"
// appendSequenceNumber
interest.setInterestLifetime(time::milliseconds(this->interest_lifetime)); // time::milliseconds(1000)
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&FileDownloader::onData, this, _1, _2),
bind(&FileDownloader::onTimeout, this, _1));
//cout << "Expressing interest #" << seq_nr << " " << interest << endl;
}
// private methods
// react to the reception of a reply from a Producer
void FileDownloader::onData(const Interest& interest, const Data& data)
{
if(!boost::starts_with(data.getName().toUri (), file_name))
return; // data packet for previous requsted file(s)
if(state == process_state::cancelled || state == process_state::finished)
{
//cout << "onData after cancel" << endl;
return;
}
// get sequence number
int seq_nr = interest.getName().at(-1).toSequenceNumber();
//cout << "data-packet #" << seq_nr << " received: " << endl;
const Block& block = data.getContent();
// first data-packet arrived, allocate space
this->finalBockId = boost::lexical_cast<int>(data.getFinalBlockId().toUri());
if(! ((int)buffer.size () == finalBockId+1)) // we assume producer always transmitts a valid final block id
{
this->buffer.resize(finalBockId+1,chunk());
}
// store received data in buffer
shared_ptr<itec::Buffer> b(new itec::Buffer((char*)block.value(), block.value_size()));
buffer[seq_nr].data = b;
buffer[seq_nr].state = chunk_state::received;
}
// check if actually all parts have been downloaded
bool FileDownloader::allChunksReceived(){
for(std::vector<chunk>::iterator it = buffer.begin(); it != buffer.end(); ++it)
{
if((*it).state != chunk_state::received)
return false;
}
return true;
}
// react on the request / Interest timing out
void FileDownloader::onTimeout(const Interest& interest)
{
if(state == process_state::cancelled || state == process_state::finished)
{
//cout << "onTimeout after cancel" << endl;
return;
}
//cout << "Timeout " << interest << endl;
// get sequence number
int seq_nr = interest.getName().at(-1).toSequenceNumber();
buffer[seq_nr].state = chunk_state::unavailable; // reset state to pending -> queue for re-request
}
// cancel downloading, returned file will be empty
void FileDownloader::cancel()
{
this->state = process_state::cancelled;
}
void FileDownloader::onFileReceived ()
{
for(vector<chunk>::iterator it = buffer.begin (); it != buffer.end (); it++)
{
file->append((*it).data->getData(),(*it).data->getSize());
}
state = process_state::finished;
//fprintf(stderr, "File received!\n");
}
<commit_msg>fixed bug for requestRate calculation<commit_after>#include "filedownloader.hpp"
using namespace player;
#define BITRATE 1200.0 //kbits
#define DATA_SIZE 4096.0 //byte
FileDownloader::FileDownloader(int interest_lifetime) : m_face(m_ioService)
{
this->interest_lifetime = interest_lifetime;
}
shared_ptr<itec::Buffer> FileDownloader::getFile(string name){
this->buffer.clear();
this->buffer.resize (20,chunk());
this->state = process_state::running;
this->requestRate = 1000000/((BITRATE*1000)/(DATA_SIZE*8.0)); //microseconds
this->file = shared_ptr<itec::Buffer>(new itec::Buffer());
this->file_name = name;
boost::asio::deadline_timer timer(m_ioService, boost::posix_time::microseconds(requestRate));
sendNextInterest(&timer); // starts the download
// processEvents will block until the requested data received or timeout occurs#
boost::posix_time::ptime startTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time());
m_face.processEvents();
boost::posix_time::ptime endTime = boost::posix_time::ptime(boost::posix_time::microsec_clock::local_time());
boost::posix_time::time_duration downloadDuration = endTime-startTime;
double dwrate = 0.0;
for(int i = 0; i < buffer.size (); i++)
{
if(buffer.at(i).state == chunk_state::received)
dwrate+=buffer.at(i).data->getSize();
}
if(downloadDuration.total_milliseconds () > 0)
{
dwrate = (dwrate * 8.0) / downloadDuration.total_milliseconds (); //bits/ms
dwrate *= 1000; //bits/s
}
else
dwrate = 0.0;
fprintf(stderr, "dwrate = %f\n", dwrate);
return file;
}
// send next pending interest, returns success-indicator
void FileDownloader::sendNextInterest(boost::asio::deadline_timer* timer)
{
if(allChunksReceived ())// all chunks / file has been downloaded
{
//TODO Cleanup;
onFileReceived();
return;
}
// check if caller cancelled
if(this->state == process_state::cancelled)
{
m_face.shutdown(); // dangerous?
return;
}
for(uint index = 0; index < buffer.size(); index++)
{
if(buffer[index].state == chunk_state::unavailable)
{
expressInterest(index);
buffer[index].state = chunk_state::requested;
timer->expires_at (timer->expires_at ()+ boost::posix_time::microseconds(requestRate));
timer->async_wait(bind(&FileDownloader::sendNextInterest, this, timer));
return;
}
}
timer->expires_at (timer->expires_at ()+ boost::posix_time::microseconds(requestRate));
timer->async_wait(bind(&FileDownloader::sendNextInterest, this, timer));
}
void FileDownloader::expressInterest(int seq_nr)
{
Interest interest(Name(file_name).appendSequenceNumber(seq_nr)); // e.g. "/example/testApp/randomData"
// appendSequenceNumber
interest.setInterestLifetime(time::milliseconds(this->interest_lifetime)); // time::milliseconds(1000)
interest.setMustBeFresh(true);
m_face.expressInterest(interest,
bind(&FileDownloader::onData, this, _1, _2),
bind(&FileDownloader::onTimeout, this, _1));
//cout << "Expressing interest #" << seq_nr << " " << interest << endl;
}
// private methods
// react to the reception of a reply from a Producer
void FileDownloader::onData(const Interest& interest, const Data& data)
{
if(!boost::starts_with(data.getName().toUri (), file_name))
return; // data packet for previous requsted file(s)
if(state == process_state::cancelled || state == process_state::finished)
{
//cout << "onData after cancel" << endl;
return;
}
// get sequence number
int seq_nr = interest.getName().at(-1).toSequenceNumber();
//cout << "data-packet #" << seq_nr << " received: " << endl;
const Block& block = data.getContent();
// first data-packet arrived, allocate space
this->finalBockId = boost::lexical_cast<int>(data.getFinalBlockId().toUri());
if(! ((int)buffer.size () == finalBockId+1)) // we assume producer always transmitts a valid final block id
{
this->buffer.resize(finalBockId+1,chunk());
}
// store received data in buffer
shared_ptr<itec::Buffer> b(new itec::Buffer((char*)block.value(), block.value_size()));
buffer[seq_nr].data = b;
buffer[seq_nr].state = chunk_state::received;
}
// check if actually all parts have been downloaded
bool FileDownloader::allChunksReceived(){
for(std::vector<chunk>::iterator it = buffer.begin(); it != buffer.end(); ++it)
{
if((*it).state != chunk_state::received)
return false;
}
return true;
}
// react on the request / Interest timing out
void FileDownloader::onTimeout(const Interest& interest)
{
if(state == process_state::cancelled || state == process_state::finished)
{
//cout << "onTimeout after cancel" << endl;
return;
}
//cout << "Timeout " << interest << endl;
// get sequence number
int seq_nr = interest.getName().at(-1).toSequenceNumber();
buffer[seq_nr].state = chunk_state::unavailable; // reset state to pending -> queue for re-request
}
// cancel downloading, returned file will be empty
void FileDownloader::cancel()
{
this->state = process_state::cancelled;
}
void FileDownloader::onFileReceived ()
{
for(vector<chunk>::iterator it = buffer.begin (); it != buffer.end (); it++)
{
file->append((*it).data->getData(),(*it).data->getSize());
}
state = process_state::finished;
//fprintf(stderr, "File received!\n");
}
<|endoftext|> |
<commit_before>#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/map.hpp>
#include "KinBodyMarker.h"
using boost::ref;
using boost::format;
using boost::str;
using boost::algorithm::ends_with;
using boost::adaptors::map_values;
using OpenRAVE::EnvironmentBasePtr;
using OpenRAVE::KinBodyPtr;
using OpenRAVE::KinBodyWeakPtr;
using OpenRAVE::RobotBase;
using OpenRAVE::RobotBaseWeakPtr;
using visualization_msgs::InteractiveMarkerFeedbackConstPtr;
using interactive_markers::InteractiveMarkerServer;
using interactive_markers::MenuHandler;
typedef OpenRAVE::KinBody::LinkPtr LinkPtr;
typedef OpenRAVE::RobotBase::ManipulatorPtr ManipulatorPtr;
typedef boost::shared_ptr<InteractiveMarkerServer> InteractiveMarkerServerPtr;
typedef MenuHandler::EntryHandle EntryHandle;
namespace or_interactivemarker {
// TODO: Move this to a helper header.
static MenuHandler::CheckState BoolToCheckState(bool const &flag)
{
if (flag) {
return MenuHandler::CHECKED;
} else {
return MenuHandler::UNCHECKED;
}
}
static bool CheckStateToBool(MenuHandler::CheckState const &state)
{
return state == MenuHandler::CHECKED;
}
KinBodyMarker::KinBodyMarker(InteractiveMarkerServerPtr server,
KinBodyPtr kinbody)
: server_(server)
, kinbody_(kinbody)
, robot_(boost::dynamic_pointer_cast<RobotBase>(kinbody))
, has_joint_controls_(false)
{
BOOST_ASSERT(server);
BOOST_ASSERT(kinbody);
#if 0
if (!IsGhost()) {
CreateGhost();
}
#endif
}
KinBodyMarker::~KinBodyMarker()
{
if (ghost_kinbody_) {
ghost_kinbody_->GetEnv()->Remove(ghost_kinbody_);
ghost_kinbody_.reset();
ghost_robot_.reset();
}
}
bool KinBodyMarker::IsGhost() const
{
KinBodyPtr kinbody = kinbody_.lock();
return ends_with(kinbody->GetName(), ".Ghost");
}
void KinBodyMarker::EnvironmentSync()
{
typedef OpenRAVE::KinBody::LinkPtr LinkPtr;
typedef OpenRAVE::KinBody::JointPtr JointPtr;
KinBodyPtr const kinbody = kinbody_.lock();
bool const is_ghost = IsGhost();
// Update links. This includes the geometry of the KinBody.
for (LinkPtr link : kinbody->GetLinks()) {
LinkMarkerWrapper &wrapper = link_markers_[link.get()];
LinkMarkerPtr &link_marker = wrapper.link_marker;
if (!link_marker) {
link_marker = boost::make_shared<LinkMarker>(server_, link, is_ghost);
CreateMenu(wrapper);
UpdateMenu(wrapper);
}
link_marker->EnvironmentSync();
}
// Update joints.
if (has_joint_controls_) {
for (JointPtr joint : kinbody->GetJoints()) {
JointMarkerPtr &joint_marker = joint_markers_[joint.get()];
if (!joint_marker) {
joint_marker = boost::make_shared<JointMarker>(server_, joint);
}
joint_marker->EnvironmentSync();
}
} else {
joint_markers_.clear();
}
#if 0
// Also update manipulators if we're a robot.
if (robot_ && !ManipulatorMarker::IsGhost(kinbody_)) { for (ManipulatorPtr const manipulator : robot_->GetManipulators()) {
auto const it = manipulator_markers_.find(manipulator.get());
BOOST_ASSERT(it != manipulator_markers_.end());
it->second->EnvironmentSync();
}
}
#endif
}
void KinBodyMarker::CreateMenu(LinkMarkerWrapper &link_wrapper)
{
typedef boost::optional<EntryHandle> Opt;
BOOST_ASSERT(!link_wrapper.has_menu);
auto const cb = boost::bind(&KinBodyMarker::MenuCallback, this,
ref(link_wrapper), _1);
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
EntryHandle parent = menu_handler.insert("Body");
link_wrapper.menu_parent = Opt(parent);
link_wrapper.menu_enabled = Opt(menu_handler.insert(parent, "Enabled", cb));
link_wrapper.menu_visible = Opt(menu_handler.insert(parent, "Visible", cb));
link_wrapper.menu_joints = Opt(menu_handler.insert(parent, "Joint Controls", cb));
std::vector<ManipulatorPtr> manipulators;
GetManipulators(link_wrapper.link_marker->link(), &manipulators);
for (ManipulatorPtr const &manipulator : manipulators) {
menu_handler.insert("Manipulator: " + manipulator->GetName());
}
link_wrapper.has_menu = true;
}
void KinBodyMarker::UpdateMenu()
{
for (LinkMarkerWrapper &marker_wrapper : link_markers_ | map_values) {
UpdateMenu(marker_wrapper);
marker_wrapper.link_marker->UpdateMenu();
// TODO: How can the link notify us that our menu changed?
}
}
void KinBodyMarker::UpdateMenu(LinkMarkerWrapper &link_wrapper)
{
if (!link_wrapper.has_menu) {
return;
}
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
LinkPtr const link = link_wrapper.link_marker->link();
menu_handler.setCheckState(*link_wrapper.menu_enabled,
BoolToCheckState(link->IsEnabled()));
menu_handler.setCheckState(*link_wrapper.menu_visible,
BoolToCheckState(link->IsVisible()));
menu_handler.setCheckState(*link_wrapper.menu_joints,
BoolToCheckState(has_joint_controls_));
}
void KinBodyMarker::MenuCallback(LinkMarkerWrapper &link_wrapper,
InteractiveMarkerFeedbackConstPtr const &feedback)
{
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
KinBodyPtr kinbody = kinbody_.lock();
// Toggle kinbody collision checking.
if (feedback->menu_entry_id == *link_wrapper.menu_enabled) {
MenuHandler::CheckState enabled_state;
menu_handler.getCheckState(*link_wrapper.menu_enabled, enabled_state);
bool const is_enabled = !CheckStateToBool(enabled_state);
kinbody->Enable(is_enabled);
RAVELOG_DEBUG("Toggled enable to %d for '%s'\n",
is_enabled, kinbody->GetName().c_str());
}
// Toggle kinbody visibility.
else if (feedback->menu_entry_id == *link_wrapper.menu_visible) {
MenuHandler::CheckState visible_state;
menu_handler.getCheckState(*link_wrapper.menu_visible, visible_state);
bool const is_visible = !CheckStateToBool(visible_state);
kinbody->SetVisible(is_visible);
RAVELOG_DEBUG("Toggled visible to %d for '%s'\n",
is_visible, kinbody->GetName().c_str());
}
// Toggle joint controls.
else if (feedback->menu_entry_id == *link_wrapper.menu_joints) {
MenuHandler::CheckState joints_state;
menu_handler.getCheckState(*link_wrapper.menu_joints, joints_state);
has_joint_controls_ = !CheckStateToBool(joints_state);
RAVELOG_DEBUG("Toggled joint controls to %d for '%s'\n",
has_joint_controls_, kinbody->GetName().c_str());
}
UpdateMenu();
}
void KinBodyMarker::GetManipulators(
LinkPtr link, std::vector<ManipulatorPtr> *manipulators) const
{
BOOST_ASSERT(link);
BOOST_ASSERT(manipulators);
// Only robots have manipulators.
KinBodyPtr const body = link->GetParent();
auto const robot = boost::dynamic_pointer_cast<RobotBase>(body);
if (!robot) {
return;
}
for (ManipulatorPtr const &manipulator : robot->GetManipulators()) {
// Check if this link is in the manipulator chain.
LinkPtr const base_link = manipulator->GetBase();
LinkPtr const tip_link = manipulator->GetEndEffector();
std::vector<LinkPtr> chain_links;
bool const success = robot->GetChain(
base_link->GetIndex(), tip_link->GetIndex(), chain_links);
BOOST_ASSERT(success);
auto const it = std::find(chain_links.begin(), chain_links.end(), link);
if (it != chain_links.end()) {
manipulators->push_back(manipulator);
continue;
}
#if 0
// Check if this link is a child (i.e. part of the end-effector)..
if (manipulator->IsChildLink(link)) {
manipulators->push_back(manipulator);
continue;
}
#endif
}
}
void KinBodyMarker::CreateGhost()
{
KinBodyPtr kinbody = kinbody_.lock();
EnvironmentBasePtr env = kinbody->GetEnv();
if (kinbody->IsRobot()) {
ghost_robot_ = OpenRAVE::RaveCreateRobot(env, "");
ghost_kinbody_ = ghost_robot_;
} else {
ghost_kinbody_ = OpenRAVE::RaveCreateKinBody(env, "");
}
ghost_robot_->Clone(kinbody, OpenRAVE::Clone_Bodies);
ghost_robot_->SetName(kinbody->GetName() + ".Ghost");
ghost_robot_->Enable(false);
env->Add(ghost_kinbody_, true);
}
}
<commit_msg>Fixed manipulator child link logic.<commit_after>#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/map.hpp>
#include "KinBodyMarker.h"
using boost::ref;
using boost::format;
using boost::str;
using boost::algorithm::ends_with;
using boost::adaptors::map_values;
using OpenRAVE::EnvironmentBasePtr;
using OpenRAVE::KinBodyPtr;
using OpenRAVE::KinBodyWeakPtr;
using OpenRAVE::RobotBase;
using OpenRAVE::RobotBaseWeakPtr;
using visualization_msgs::InteractiveMarkerFeedbackConstPtr;
using interactive_markers::InteractiveMarkerServer;
using interactive_markers::MenuHandler;
typedef OpenRAVE::KinBody::LinkPtr LinkPtr;
typedef OpenRAVE::RobotBase::ManipulatorPtr ManipulatorPtr;
typedef boost::shared_ptr<InteractiveMarkerServer> InteractiveMarkerServerPtr;
typedef MenuHandler::EntryHandle EntryHandle;
namespace or_interactivemarker {
// TODO: Move this to a helper header.
static MenuHandler::CheckState BoolToCheckState(bool const &flag)
{
if (flag) {
return MenuHandler::CHECKED;
} else {
return MenuHandler::UNCHECKED;
}
}
static bool CheckStateToBool(MenuHandler::CheckState const &state)
{
return state == MenuHandler::CHECKED;
}
KinBodyMarker::KinBodyMarker(InteractiveMarkerServerPtr server,
KinBodyPtr kinbody)
: server_(server)
, kinbody_(kinbody)
, robot_(boost::dynamic_pointer_cast<RobotBase>(kinbody))
, has_joint_controls_(false)
{
BOOST_ASSERT(server);
BOOST_ASSERT(kinbody);
#if 0
if (!IsGhost()) {
CreateGhost();
}
#endif
}
KinBodyMarker::~KinBodyMarker()
{
if (ghost_kinbody_) {
ghost_kinbody_->GetEnv()->Remove(ghost_kinbody_);
ghost_kinbody_.reset();
ghost_robot_.reset();
}
}
bool KinBodyMarker::IsGhost() const
{
KinBodyPtr kinbody = kinbody_.lock();
return ends_with(kinbody->GetName(), ".Ghost");
}
void KinBodyMarker::EnvironmentSync()
{
typedef OpenRAVE::KinBody::LinkPtr LinkPtr;
typedef OpenRAVE::KinBody::JointPtr JointPtr;
KinBodyPtr const kinbody = kinbody_.lock();
bool const is_ghost = IsGhost();
// Update links. This includes the geometry of the KinBody.
for (LinkPtr link : kinbody->GetLinks()) {
LinkMarkerWrapper &wrapper = link_markers_[link.get()];
LinkMarkerPtr &link_marker = wrapper.link_marker;
if (!link_marker) {
link_marker = boost::make_shared<LinkMarker>(server_, link, is_ghost);
CreateMenu(wrapper);
UpdateMenu(wrapper);
}
link_marker->EnvironmentSync();
}
// Update joints.
if (has_joint_controls_) {
for (JointPtr joint : kinbody->GetJoints()) {
JointMarkerPtr &joint_marker = joint_markers_[joint.get()];
if (!joint_marker) {
joint_marker = boost::make_shared<JointMarker>(server_, joint);
}
joint_marker->EnvironmentSync();
}
} else {
joint_markers_.clear();
}
#if 0
// Also update manipulators if we're a robot.
if (robot_ && !ManipulatorMarker::IsGhost(kinbody_)) { for (ManipulatorPtr const manipulator : robot_->GetManipulators()) {
auto const it = manipulator_markers_.find(manipulator.get());
BOOST_ASSERT(it != manipulator_markers_.end());
it->second->EnvironmentSync();
}
}
#endif
}
void KinBodyMarker::CreateMenu(LinkMarkerWrapper &link_wrapper)
{
typedef boost::optional<EntryHandle> Opt;
BOOST_ASSERT(!link_wrapper.has_menu);
auto const cb = boost::bind(&KinBodyMarker::MenuCallback, this,
ref(link_wrapper), _1);
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
EntryHandle parent = menu_handler.insert("Body");
link_wrapper.menu_parent = Opt(parent);
link_wrapper.menu_enabled = Opt(menu_handler.insert(parent, "Enabled", cb));
link_wrapper.menu_visible = Opt(menu_handler.insert(parent, "Visible", cb));
link_wrapper.menu_joints = Opt(menu_handler.insert(parent, "Joint Controls", cb));
std::vector<ManipulatorPtr> manipulators;
GetManipulators(link_wrapper.link_marker->link(), &manipulators);
for (ManipulatorPtr const &manipulator : manipulators) {
menu_handler.insert("Manipulator: " + manipulator->GetName());
}
link_wrapper.has_menu = true;
}
void KinBodyMarker::UpdateMenu()
{
for (LinkMarkerWrapper &marker_wrapper : link_markers_ | map_values) {
UpdateMenu(marker_wrapper);
marker_wrapper.link_marker->UpdateMenu();
// TODO: How can the link notify us that our menu changed?
}
}
void KinBodyMarker::UpdateMenu(LinkMarkerWrapper &link_wrapper)
{
if (!link_wrapper.has_menu) {
return;
}
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
LinkPtr const link = link_wrapper.link_marker->link();
menu_handler.setCheckState(*link_wrapper.menu_enabled,
BoolToCheckState(link->IsEnabled()));
menu_handler.setCheckState(*link_wrapper.menu_visible,
BoolToCheckState(link->IsVisible()));
menu_handler.setCheckState(*link_wrapper.menu_joints,
BoolToCheckState(has_joint_controls_));
}
void KinBodyMarker::MenuCallback(LinkMarkerWrapper &link_wrapper,
InteractiveMarkerFeedbackConstPtr const &feedback)
{
MenuHandler &menu_handler = link_wrapper.link_marker->menu_handler();
KinBodyPtr kinbody = kinbody_.lock();
// Toggle kinbody collision checking.
if (feedback->menu_entry_id == *link_wrapper.menu_enabled) {
MenuHandler::CheckState enabled_state;
menu_handler.getCheckState(*link_wrapper.menu_enabled, enabled_state);
bool const is_enabled = !CheckStateToBool(enabled_state);
kinbody->Enable(is_enabled);
RAVELOG_DEBUG("Toggled enable to %d for '%s'\n",
is_enabled, kinbody->GetName().c_str());
}
// Toggle kinbody visibility.
else if (feedback->menu_entry_id == *link_wrapper.menu_visible) {
MenuHandler::CheckState visible_state;
menu_handler.getCheckState(*link_wrapper.menu_visible, visible_state);
bool const is_visible = !CheckStateToBool(visible_state);
kinbody->SetVisible(is_visible);
RAVELOG_DEBUG("Toggled visible to %d for '%s'\n",
is_visible, kinbody->GetName().c_str());
}
// Toggle joint controls.
else if (feedback->menu_entry_id == *link_wrapper.menu_joints) {
MenuHandler::CheckState joints_state;
menu_handler.getCheckState(*link_wrapper.menu_joints, joints_state);
has_joint_controls_ = !CheckStateToBool(joints_state);
RAVELOG_DEBUG("Toggled joint controls to %d for '%s'\n",
has_joint_controls_, kinbody->GetName().c_str());
}
UpdateMenu();
}
void KinBodyMarker::GetManipulators(
LinkPtr link, std::vector<ManipulatorPtr> *manipulators) const
{
BOOST_ASSERT(link);
BOOST_ASSERT(manipulators);
// Only robots have manipulators.
KinBodyPtr const body = link->GetParent();
auto const robot = boost::dynamic_pointer_cast<RobotBase>(body);
if (!robot) {
return;
}
for (ManipulatorPtr const &manipulator : robot->GetManipulators()) {
// Check if this link is in the manipulator chain.
LinkPtr const base_link = manipulator->GetBase();
LinkPtr const tip_link = manipulator->GetEndEffector();
std::vector<LinkPtr> chain_links;
bool const success = robot->GetChain(
base_link->GetIndex(), tip_link->GetIndex(), chain_links);
BOOST_ASSERT(success);
auto const chain_it = std::find(chain_links.begin(), chain_links.end(), link);
if (chain_it != chain_links.end()) {
manipulators->push_back(manipulator);
continue;
}
// Check if this link is a child (i.e. part of the end-effector).
// TODO: This is necessary because IsChildLink is broken.
std::vector<LinkPtr> child_links;
manipulator->GetChildLinks(child_links);
auto const child_it = std::find(child_links.begin(), child_links.end(), link);
if (child_it != child_links.end()) {
manipulators->push_back(manipulator);
continue;
}
}
}
void KinBodyMarker::CreateGhost()
{
KinBodyPtr kinbody = kinbody_.lock();
EnvironmentBasePtr env = kinbody->GetEnv();
if (kinbody->IsRobot()) {
ghost_robot_ = OpenRAVE::RaveCreateRobot(env, "");
ghost_kinbody_ = ghost_robot_;
} else {
ghost_kinbody_ = OpenRAVE::RaveCreateKinBody(env, "");
}
ghost_robot_->Clone(kinbody, OpenRAVE::Clone_Bodies);
ghost_robot_->SetName(kinbody->GetName() + ".Ghost");
ghost_robot_->Enable(false);
env->Add(ghost_kinbody_, true);
}
}
<|endoftext|> |
<commit_before>#include <PCU.h>
#include "phPartition.h"
#include "phInput.h"
#include <parma.h>
#include <apfZoltan.h>
#include <apfMDS.h>
#include <apfMesh2.h>
namespace ph {
apf::Migration* getSplitPlan(Input& in, apf::Mesh2* m)
{
assert(in.recursivePtn <= 1);
assert(in.splitFactor >= 1);
apf::Migration* plan;
if (in.splitFactor != 1) {
apf::Splitter* splitter;
if (in.partitionMethod == "rib") { //prefer SCOREC RIB over Zoltan RIB
splitter = Parma_MakeRibSplitter(m);
} else {
std::map<std::string, int> methodMap;
methodMap["graph"] = apf::GRAPH;
methodMap["hypergraph"] = apf::HYPERGRAPH;
int method = methodMap[in.partitionMethod];
splitter = apf::makeZoltanSplitter(m, method, apf::REPARTITION);
}
apf::MeshTag* weights = Parma_WeighByMemory(m);
plan = splitter->split(weights, 1.03, in.splitFactor);
apf::removeTagFromDimension(m, weights, m->getDimension());
m->destroyTag(weights);
delete splitter;
} else {
plan = new apf::Migration(m);
}
return plan;
}
void split(Input& in, apf::Mesh2* m, void (*runAfter)(apf::Mesh2*))
{
apf::splitMdsMesh(m, getSplitPlan(in, m), in.splitFactor, runAfter);
}
apf::Migration* split(Input& in, apf::Mesh2* m)
{
return getSplitPlan(in,m);
}
bool isMixed(apf::Mesh2* m) {
int mixed = 0;
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(m->getDimension());
while ((e = m->iterate(it)))
if ( m->getType(e) != apf::Mesh::TET ) {
mixed = 1;
break;
}
m->end(it);
PCU_Max_Ints(&mixed, 1);
return mixed;
}
void setWeight(apf::Mesh* m, apf::MeshTag* tag, int dim) {
double w = 1.0;
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(dim);
while ((e = m->iterate(it)))
m->setDoubleTag(e, tag, &w);
m->end(it);
}
apf::MeshTag* setWeights(apf::Mesh* m) {
apf::MeshTag* tag = m->createDoubleTag("parma_weight", 1);
setWeight(m, tag, 0);
setWeight(m, tag, m->getDimension());
return tag;
}
void clearTags(apf::Mesh* m, apf::MeshTag* t) {
apf::removeTagFromDimension(m, t, 0);
apf::removeTagFromDimension(m, t, m->getDimension());
}
void balance(apf::Mesh2* m)
{
bool fineStats=false; // set to true for per part stats
Parma_PrintPtnStats(m, "preRefine", fineStats);
if ( isMixed(m) ) {
apf::MeshTag* weights = Parma_WeighByMemory(m);
double tolerance = 1.05;
const double step = 0.2;
const int verbose = 0;
apf::Balancer* balancer = Parma_MakeElmBalancer(m, step, verbose);
balancer->balance(weights, tolerance);
delete balancer;
apf::removeTagFromDimension(m, weights, m->getDimension());
m->destroyTag(weights);
} else {
apf::MeshTag* weights = setWeights(m);
const double vtxImbTol = 1.03;
const double step = 0.3;
const int verbose = 1; // set to 2 for per iteration stats
const double ignored = 42.42;
Parma_ProcessDisconnectedParts(m);
Parma_PrintPtnStats(m, "post ProcessDisconnectedParts", fineStats);
apf::Balancer* balancer = Parma_MakeHpsBalancer(m,verbose);
balancer->balance(weights, ignored);
delete balancer;
Parma_PrintPtnStats(m, "post HPS", fineStats);
for(int i=0; i<3; i++) {
balancer = Parma_MakeVtxElmBalancer(m, step, verbose);
balancer->balance(weights, vtxImbTol);
Parma_PrintPtnStats(m, "post Parma_MakeVtxElmBalancer", fineStats);
delete balancer;
double vtxImb = Parma_GetWeightedEntImbalance(m, weights, 0);
if( vtxImb <= vtxImbTol ) {
if( !PCU_Comm_Self() )
fprintf(stdout, "STATUS vtx imbalance target %.3f reached\n",
vtxImbTol);
break;
}
}
clearTags(m, weights);
m->destroyTag(weights);
}
}
}
<commit_msg>remove hps and disconnected part fixing<commit_after>#include <PCU.h>
#include "phPartition.h"
#include "phInput.h"
#include <parma.h>
#include <apfZoltan.h>
#include <apfMDS.h>
#include <apfMesh2.h>
namespace ph {
apf::Migration* getSplitPlan(Input& in, apf::Mesh2* m)
{
assert(in.recursivePtn <= 1);
assert(in.splitFactor >= 1);
apf::Migration* plan;
if (in.splitFactor != 1) {
apf::Splitter* splitter;
if (in.partitionMethod == "rib") { //prefer SCOREC RIB over Zoltan RIB
splitter = Parma_MakeRibSplitter(m);
} else {
std::map<std::string, int> methodMap;
methodMap["graph"] = apf::GRAPH;
methodMap["hypergraph"] = apf::HYPERGRAPH;
int method = methodMap[in.partitionMethod];
splitter = apf::makeZoltanSplitter(m, method, apf::REPARTITION);
}
apf::MeshTag* weights = Parma_WeighByMemory(m);
plan = splitter->split(weights, 1.03, in.splitFactor);
apf::removeTagFromDimension(m, weights, m->getDimension());
m->destroyTag(weights);
delete splitter;
} else {
plan = new apf::Migration(m);
}
return plan;
}
void split(Input& in, apf::Mesh2* m, void (*runAfter)(apf::Mesh2*))
{
apf::splitMdsMesh(m, getSplitPlan(in, m), in.splitFactor, runAfter);
}
apf::Migration* split(Input& in, apf::Mesh2* m)
{
return getSplitPlan(in,m);
}
bool isMixed(apf::Mesh2* m) {
int mixed = 0;
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(m->getDimension());
while ((e = m->iterate(it)))
if ( m->getType(e) != apf::Mesh::TET ) {
mixed = 1;
break;
}
m->end(it);
PCU_Max_Ints(&mixed, 1);
return mixed;
}
void setWeight(apf::Mesh* m, apf::MeshTag* tag, int dim) {
double w = 1.0;
apf::MeshEntity* e;
apf::MeshIterator* it = m->begin(dim);
while ((e = m->iterate(it)))
m->setDoubleTag(e, tag, &w);
m->end(it);
}
apf::MeshTag* setWeights(apf::Mesh* m) {
apf::MeshTag* tag = m->createDoubleTag("parma_weight", 1);
setWeight(m, tag, 0);
setWeight(m, tag, m->getDimension());
return tag;
}
void clearTags(apf::Mesh* m, apf::MeshTag* t) {
apf::removeTagFromDimension(m, t, 0);
apf::removeTagFromDimension(m, t, m->getDimension());
}
void balance(apf::Mesh2* m)
{
bool fineStats=false; // set to true for per part stats
Parma_PrintPtnStats(m, "preRefine", fineStats);
if ( isMixed(m) ) {
apf::MeshTag* weights = Parma_WeighByMemory(m);
double tolerance = 1.05;
const double step = 0.2;
const int verbose = 0;
apf::Balancer* balancer = Parma_MakeElmBalancer(m, step, verbose);
balancer->balance(weights, tolerance);
delete balancer;
apf::removeTagFromDimension(m, weights, m->getDimension());
m->destroyTag(weights);
} else {
apf::MeshTag* weights = setWeights(m);
const double vtxImbTol = 1.03;
const double step = 0.3;
const int verbose = 1; // set to 2 for per iteration stats
for(int i=0; i<3; i++) {
apf::Balancer* balancer = Parma_MakeVtxElmBalancer(m, step, verbose);
balancer->balance(weights, vtxImbTol);
Parma_PrintPtnStats(m, "post Parma_MakeVtxElmBalancer", fineStats);
delete balancer;
double vtxImb = Parma_GetWeightedEntImbalance(m, weights, 0);
if( vtxImb <= vtxImbTol ) {
if( !PCU_Comm_Self() )
fprintf(stdout, "STATUS vtx imbalance target %.3f reached\n",
vtxImbTol);
break;
}
}
clearTags(m, weights);
m->destroyTag(weights);
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2003 by Unai Garro *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "ingredientsdialog.h"
#include <qheader.h>
IngredientsDialog::IngredientsDialog(QWidget* parent, RecipeDB *db):QWidget(parent)
{
// Store pointer to database
database=db;
// Initialize internal variables
propertiesList= new IngredientPropertyList;
perUnitListBack= new ElementList;
// Design dialog
layout = new QGridLayout( this, 1, 1, 0, 0);
QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( spacer_left, 1,0 );
QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem(spacer_top,0,1);
ingredientListView=new KListView (this);
layout->addMultiCellWidget (ingredientListView,1,4,1,1);
ingredientListView->addColumn("Id");
ingredientListView->addColumn("Ingredient");
ingredientListView->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightIngredients = new QSpacerItem( 5,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_rightIngredients,1,2);
addIngredientButton = new QPushButton( this);
addIngredientButton->setText("+");
layout->addWidget( addIngredientButton, 1, 3 );
addIngredientButton->setMinimumSize(QSize(30,30));
addIngredientButton->setMaximumSize(QSize(30,30));
addIngredientButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addIngredientButton->setFlat(true);
removeIngredientButton = new QPushButton( this);
removeIngredientButton->setText("-");
layout->addWidget( removeIngredientButton, 3, 3 );
removeIngredientButton->setMinimumSize(QSize(30,30));
removeIngredientButton->setMaximumSize(QSize(30,30));
removeIngredientButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removeIngredientButton->setFlat(true);
QSpacerItem* spacer_Ing_Buttons = new QSpacerItem( 5,5, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem(spacer_Ing_Buttons,2,3);
QSpacerItem* spacer_Ing_Units = new QSpacerItem( 30,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_Ing_Units,1,4);
unitsListView=new KListView (this);
unitsListView->addColumn("i.");
unitsListView->addColumn("Units");
layout->addMultiCellWidget (unitsListView,1,4,5,5);
unitsListView->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightUnits = new QSpacerItem( 5,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_rightUnits,1,6);
addUnitButton = new QPushButton( this);
addUnitButton->setText("+");
layout->addWidget( addUnitButton, 1, 7 );
addUnitButton->resize(QSize(30,30));
addUnitButton->setMinimumSize(QSize(30,30));
addUnitButton->setMaximumSize(QSize(30,30));
addUnitButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addUnitButton->setFlat(true);
removeUnitButton = new QPushButton( this);
removeUnitButton->setText("-");
layout->addWidget( removeUnitButton, 3, 7 );
removeUnitButton->resize(QSize(30,30));
removeUnitButton->setMinimumSize(QSize(30,30));
removeUnitButton->setMaximumSize(QSize(30,30));
removeUnitButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removeUnitButton->setFlat(true);
QSpacerItem* spacer_Units_Properties = new QSpacerItem( 30,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_Units_Properties,1,8);
propertiesListView=new KListView (this);
layout->addMultiCellWidget (propertiesListView,1,4,9,9);
propertiesListView->addColumn("Id");
propertiesListView->addColumn("Property");
propertiesListView->addColumn("Amount");
propertiesListView->addColumn("units");
propertiesListView->setAllColumnsShowFocus(true);
propertiesListView->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightProperties= new QSpacerItem(5,5,QSizePolicy::Fixed,QSizePolicy::Minimum);
layout->addItem(spacer_rightProperties,1,10);
addPropertyButton= new QPushButton(this);
addPropertyButton->setText("+");
layout->addWidget( addPropertyButton, 1, 11 );
addPropertyButton->resize(QSize(30,30));
addPropertyButton->setMinimumSize(QSize(30,30));
addPropertyButton->setMaximumSize(QSize(30,30));
addPropertyButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addPropertyButton->setFlat(true);
removePropertyButton=new QPushButton(this);
removePropertyButton->setText("-");
layout->addWidget( removePropertyButton, 3, 11 );
removePropertyButton->resize(QSize(30,30));
removePropertyButton->setMinimumSize(QSize(30,30));
removePropertyButton->setMaximumSize(QSize(30,30));
removePropertyButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removePropertyButton->setFlat(true);
inputBox=new EditBox(this);
inputBox->hide();
// Initialize
ingredientList =new ElementList;
unitList=new ElementList;
reloadIngredientList();
// Signals & Slots
connect(this->ingredientListView,SIGNAL(selectionChanged()),this, SLOT(updateLists()));
connect(this->addIngredientButton,SIGNAL(clicked()),this,SLOT(addIngredient()));
connect(this->addUnitButton,SIGNAL(clicked()),this,SLOT(addUnitToIngredient()));
connect(this->removeUnitButton,SIGNAL(clicked()),this,SLOT(removeUnitFromIngredient()));
connect(this->removeIngredientButton,SIGNAL(clicked()),this,SLOT(removeIngredient()));
connect(this->addPropertyButton,SIGNAL(clicked()),this,SLOT(addPropertyToIngredient()));
connect(this->removePropertyButton,SIGNAL(clicked()),this,SLOT(removePropertyFromIngredient()));
connect(this->propertiesListView,SIGNAL(executed(QListViewItem*)),this,SLOT(insertPropertyEditBox(QListViewItem*)));
connect(this->inputBox,SIGNAL(valueChanged(double)),this,SLOT(setPropertyAmount(double)));
}
IngredientsDialog::~IngredientsDialog()
{
}
void IngredientsDialog::reloadIngredientList(void)
{
ingredientListView->clear();
ingredientList->clear();
database->loadIngredients(ingredientList);
//Populate this data into the KListView
for ( Element *ing =ingredientList->getFirst(); ing; ing =ingredientList->getNext() )
{
QListViewItem *it= new QListViewItem(ingredientListView,QString::number(ing->id),ing->name);
}
// Reload Unit List
updateLists();
}
void IngredientsDialog::reloadUnitList()
{
int ingredientID=-1;
// Find selected ingredient
QListViewItem *it; it=ingredientListView->selectedItem();
if (it){ // Check if an ingredient is selected first
ingredientID=it->text(0).toInt();
}
unitList->clear();
unitsListView->clear();
if (ingredientID>=0)
{
database->loadPossibleUnits(ingredientID,unitList);
//Populate this data into the KListView
for ( Element *unit =unitList->getFirst(); unit; unit =unitList->getNext() )
{
QListViewItem *uit= new QListViewItem(unitsListView,QString::number(unit->id),unit->name);
}
// Select the first unit
unitsListView->setSelected(unitsListView->firstChild(),true);
}
}
void IngredientsDialog::addIngredient(void)
{
CreateElementDialog* elementDialog=new CreateElementDialog(QString("New Ingredient"));
if ( elementDialog->exec() == QDialog::Accepted ) {
QString result = elementDialog->newElementName();
database->createNewIngredient(result); // Create the new ingredient in database
reloadIngredientList(); // Reload the list from database
}
delete elementDialog;
}
void IngredientsDialog::addUnitToIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem())
{
ingredientID=it->text(0).toInt();
}
if (ingredientID>=0) // an ingredient was selected previously
{
ElementList allUnits;
database->loadUnits(&allUnits);
SelectUnitDialog* unitsDialog=new SelectUnitDialog(0,&allUnits);
if ( unitsDialog->exec() == QDialog::Accepted ) {
int result = unitsDialog->unitID();
database->AddUnitToIngredient(ingredientID,result); // Add result chosen unit to ingredient in database
reloadUnitList(); // Reload the list from database
}
}
}
void IngredientsDialog::removeUnitFromIngredient(void)
{
// Find selected ingredient/unit item combination
QListViewItem *it;
int ingredientID=-1, unitID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (it=unitsListView->selectedItem()) unitID=it->text(0).toInt();
if ((ingredientID>=0)&&(unitID>=0)) // an ingredient/unit combination was selected previously
{
ElementList results;
database->findUseOf_Ing_Unit_InRecipes(&results,ingredientID,unitID); // Find if this ingredient-unit combination is being used
if (results.isEmpty()) database->removeUnitFromIngredient(ingredientID,unitID);
else database->removeUnitFromIngredient(ingredientID,unitID); //must warn!
reloadUnitList(); // Reload the list from database
}
}
void IngredientsDialog::removeIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (ingredientID>=0) // an ingredient/unit combination was selected previously
{
ElementList results;
database->findUseOfIngInRecipes(&results,ingredientID);
if (results.isEmpty()) database->removeIngredient(ingredientID);
else database->removeIngredient(ingredientID);
reloadIngredientList();// Reload the list from database
}
}
void IngredientsDialog:: reloadPropertyList(void)
{
propertiesList->clear();
propertiesListView->clear();
perUnitListBack->clear();
//If none is selected, select first item
QListViewItem *it;
it=ingredientListView->selectedItem();
//Populate this data into the KListView
if (it){// make sure that the ingredient list is not empty
database->loadProperties(propertiesList,it->text(0).toInt()); // load the list for this ingredient
for ( IngredientProperty *prop =propertiesList->getFirst(); prop; prop =propertiesList->getNext() )
{
QListViewItem *it= new QListViewItem(propertiesListView,QString::number(prop->id),prop->name,QString::number(prop->amount),prop->units+QString("/")+prop->perUnit.name);
// Store the perUnits with the ID for using later
Element perUnitEl;
perUnitEl.id=prop->perUnit.id;
perUnitEl.name=prop->perUnit.name;
perUnitListBack->add(perUnitEl);
}
}
}
void IngredientsDialog:: updateLists(void)
{
//If no ingredient is selected, select first item
QListViewItem *it;
if (!(it=ingredientListView->selectedItem()))
{
it=ingredientListView->firstChild();
}
reloadUnitList();
reloadPropertyList();
}
void IngredientsDialog::addPropertyToIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem())
{
ingredientID=it->text(0).toInt();
}
if (ingredientID>=0) // an ingredient was selected previously
{
IngredientPropertyList allProperties; database->loadProperties(&allProperties);
ElementList unitList; database->loadPossibleUnits(ingredientID,&unitList);
SelectPropertyDialog* propertyDialog=new SelectPropertyDialog(0,&allProperties,&unitList);
if ( propertyDialog->exec() == QDialog::Accepted ) {
int propertyID = propertyDialog->propertyID();
int perUnitsID = propertyDialog->perUnitsID();
database->addPropertyToIngredient(ingredientID,propertyID,0,perUnitsID); // Add result chosen property to ingredient in database, with amount 0 by default
reloadPropertyList(); // Reload the list from database
}
}
}
void IngredientsDialog::removePropertyFromIngredient(void)
{
// Find selected ingredient/property item combination
QListViewItem *it;
int ingredientID=-1, propertyID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (it=propertiesListView->selectedItem()) propertyID=it->text(0).toInt();
if ((ingredientID>=0)&&(propertyID>=0)) // an ingredient/property combination was selected previously
{
ElementList results;
database->removePropertyFromIngredient(ingredientID,propertyID);
reloadPropertyList(); // Reload the list from database
}
}
void IngredientsDialog::insertPropertyEditBox(QListViewItem* it)
{
QRect r;
r=propertiesListView->header()->sectionRect(2); //Set in position reference to qlistview, and with the column size();
r.moveBy(propertiesListView->pos().x(),propertiesListView->pos().y()); // Move to the position of qlistview
r.moveBy(0,r.height()+propertiesListView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
inputBox->setGeometry(r);
inputBox->show();
}
void IngredientsDialog::setPropertyAmount(double amount)
{
inputBox->hide();
QListViewItem *ing_it=ingredientListView->selectedItem(); // Find selected ingredient
QListViewItem *prop_it=propertiesListView->selectedItem();
if (ing_it && prop_it)// Appart from property, Check if an ingredient is selected first, just in case
{
prop_it->setText(2,QString::number(amount));
int propertyID=prop_it->text(0).toInt();
int ingredientID=ing_it->text(0).toInt();
int per_units=perUnitListBack->getElement(findPropertyNo(prop_it))->id ;
database->changePropertyAmountToIngredient(ingredientID,propertyID,amount,per_units);
}
reloadPropertyList();
}
int IngredientsDialog::findPropertyNo(QListViewItem *it)
{
bool found=false;
int i = 0;
QListViewItem* item = propertiesListView->firstChild();
while (i < propertiesListView->childCount() && !found) {
if (item == propertiesListView->currentItem())
found = true;
else {
item = item->nextSibling();
++i;
}
}
if (found)
{
return (i);
}
else
{
return (-1);
}
}<commit_msg>Actually remove the properties using ingredient+unit combination, if a unit is ddisabled (removed) from that ingredient. The query execution was missing.<commit_after>/***************************************************************************
* Copyright (C) 2003 by Unai Garro *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "ingredientsdialog.h"
#include <qheader.h>
IngredientsDialog::IngredientsDialog(QWidget* parent, RecipeDB *db):QWidget(parent)
{
// Store pointer to database
database=db;
// Initialize internal variables
propertiesList= new IngredientPropertyList;
perUnitListBack= new ElementList;
// Design dialog
layout = new QGridLayout( this, 1, 1, 0, 0);
QSpacerItem* spacer_left = new QSpacerItem( 10,10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( spacer_left, 1,0 );
QSpacerItem* spacer_top = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem(spacer_top,0,1);
ingredientListView=new KListView (this);
layout->addMultiCellWidget (ingredientListView,1,4,1,1);
ingredientListView->addColumn("Id");
ingredientListView->addColumn("Ingredient");
ingredientListView->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightIngredients = new QSpacerItem( 5,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_rightIngredients,1,2);
addIngredientButton = new QPushButton( this);
addIngredientButton->setText("+");
layout->addWidget( addIngredientButton, 1, 3 );
addIngredientButton->setMinimumSize(QSize(30,30));
addIngredientButton->setMaximumSize(QSize(30,30));
addIngredientButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addIngredientButton->setFlat(true);
removeIngredientButton = new QPushButton( this);
removeIngredientButton->setText("-");
layout->addWidget( removeIngredientButton, 3, 3 );
removeIngredientButton->setMinimumSize(QSize(30,30));
removeIngredientButton->setMaximumSize(QSize(30,30));
removeIngredientButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removeIngredientButton->setFlat(true);
QSpacerItem* spacer_Ing_Buttons = new QSpacerItem( 5,5, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem(spacer_Ing_Buttons,2,3);
QSpacerItem* spacer_Ing_Units = new QSpacerItem( 30,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_Ing_Units,1,4);
unitsListView=new KListView (this);
unitsListView->addColumn("i.");
unitsListView->addColumn("Units");
layout->addMultiCellWidget (unitsListView,1,4,5,5);
unitsListView->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightUnits = new QSpacerItem( 5,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_rightUnits,1,6);
addUnitButton = new QPushButton( this);
addUnitButton->setText("+");
layout->addWidget( addUnitButton, 1, 7 );
addUnitButton->resize(QSize(30,30));
addUnitButton->setMinimumSize(QSize(30,30));
addUnitButton->setMaximumSize(QSize(30,30));
addUnitButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addUnitButton->setFlat(true);
removeUnitButton = new QPushButton( this);
removeUnitButton->setText("-");
layout->addWidget( removeUnitButton, 3, 7 );
removeUnitButton->resize(QSize(30,30));
removeUnitButton->setMinimumSize(QSize(30,30));
removeUnitButton->setMaximumSize(QSize(30,30));
removeUnitButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removeUnitButton->setFlat(true);
QSpacerItem* spacer_Units_Properties = new QSpacerItem( 30,5, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem(spacer_Units_Properties,1,8);
propertiesListView=new KListView (this);
layout->addMultiCellWidget (propertiesListView,1,4,9,9);
propertiesListView->addColumn("Id");
propertiesListView->addColumn("Property");
propertiesListView->addColumn("Amount");
propertiesListView->addColumn("units");
propertiesListView->setAllColumnsShowFocus(true);
propertiesListView->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding));
QSpacerItem* spacer_rightProperties= new QSpacerItem(5,5,QSizePolicy::Fixed,QSizePolicy::Minimum);
layout->addItem(spacer_rightProperties,1,10);
addPropertyButton= new QPushButton(this);
addPropertyButton->setText("+");
layout->addWidget( addPropertyButton, 1, 11 );
addPropertyButton->resize(QSize(30,30));
addPropertyButton->setMinimumSize(QSize(30,30));
addPropertyButton->setMaximumSize(QSize(30,30));
addPropertyButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
addPropertyButton->setFlat(true);
removePropertyButton=new QPushButton(this);
removePropertyButton->setText("-");
layout->addWidget( removePropertyButton, 3, 11 );
removePropertyButton->resize(QSize(30,30));
removePropertyButton->setMinimumSize(QSize(30,30));
removePropertyButton->setMaximumSize(QSize(30,30));
removePropertyButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
removePropertyButton->setFlat(true);
inputBox=new EditBox(this);
inputBox->hide();
// Initialize
ingredientList =new ElementList;
unitList=new ElementList;
reloadIngredientList();
// Signals & Slots
connect(this->ingredientListView,SIGNAL(selectionChanged()),this, SLOT(updateLists()));
connect(this->addIngredientButton,SIGNAL(clicked()),this,SLOT(addIngredient()));
connect(this->addUnitButton,SIGNAL(clicked()),this,SLOT(addUnitToIngredient()));
connect(this->removeUnitButton,SIGNAL(clicked()),this,SLOT(removeUnitFromIngredient()));
connect(this->removeIngredientButton,SIGNAL(clicked()),this,SLOT(removeIngredient()));
connect(this->addPropertyButton,SIGNAL(clicked()),this,SLOT(addPropertyToIngredient()));
connect(this->removePropertyButton,SIGNAL(clicked()),this,SLOT(removePropertyFromIngredient()));
connect(this->propertiesListView,SIGNAL(executed(QListViewItem*)),this,SLOT(insertPropertyEditBox(QListViewItem*)));
connect(this->inputBox,SIGNAL(valueChanged(double)),this,SLOT(setPropertyAmount(double)));
}
IngredientsDialog::~IngredientsDialog()
{
}
void IngredientsDialog::reloadIngredientList(void)
{
ingredientListView->clear();
ingredientList->clear();
database->loadIngredients(ingredientList);
//Populate this data into the KListView
for ( Element *ing =ingredientList->getFirst(); ing; ing =ingredientList->getNext() )
{
QListViewItem *it= new QListViewItem(ingredientListView,QString::number(ing->id),ing->name);
}
// Reload Unit List
updateLists();
}
void IngredientsDialog::reloadUnitList()
{
int ingredientID=-1;
// Find selected ingredient
QListViewItem *it; it=ingredientListView->selectedItem();
if (it){ // Check if an ingredient is selected first
ingredientID=it->text(0).toInt();
}
unitList->clear();
unitsListView->clear();
if (ingredientID>=0)
{
database->loadPossibleUnits(ingredientID,unitList);
//Populate this data into the KListView
for ( Element *unit =unitList->getFirst(); unit; unit =unitList->getNext() )
{
QListViewItem *uit= new QListViewItem(unitsListView,QString::number(unit->id),unit->name);
}
// Select the first unit
unitsListView->setSelected(unitsListView->firstChild(),true);
}
}
void IngredientsDialog::addIngredient(void)
{
CreateElementDialog* elementDialog=new CreateElementDialog(QString("New Ingredient"));
if ( elementDialog->exec() == QDialog::Accepted ) {
QString result = elementDialog->newElementName();
database->createNewIngredient(result); // Create the new ingredient in database
reloadIngredientList(); // Reload the list from database
}
delete elementDialog;
}
void IngredientsDialog::addUnitToIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem())
{
ingredientID=it->text(0).toInt();
}
if (ingredientID>=0) // an ingredient was selected previously
{
ElementList allUnits;
database->loadUnits(&allUnits);
SelectUnitDialog* unitsDialog=new SelectUnitDialog(0,&allUnits);
if ( unitsDialog->exec() == QDialog::Accepted ) {
int result = unitsDialog->unitID();
database->AddUnitToIngredient(ingredientID,result); // Add result chosen unit to ingredient in database
reloadUnitList(); // Reload the list from database
}
}
}
void IngredientsDialog::removeUnitFromIngredient(void)
{
// Find selected ingredient/unit item combination
QListViewItem *it;
int ingredientID=-1, unitID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (it=unitsListView->selectedItem()) unitID=it->text(0).toInt();
if ((ingredientID>=0)&&(unitID>=0)) // an ingredient/unit combination was selected previously
{
ElementList results;
database->findUseOf_Ing_Unit_InRecipes(&results,ingredientID,unitID); // Find if this ingredient-unit combination is being used
if (results.isEmpty()) database->removeUnitFromIngredient(ingredientID,unitID);
else database->removeUnitFromIngredient(ingredientID,unitID); //must warn!
reloadUnitList(); // Reload the list from database
reloadPropertyList(); // Properties could have been removed if a unit is removed, so we need to reload.
}
}
void IngredientsDialog::removeIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (ingredientID>=0) // an ingredient/unit combination was selected previously
{
ElementList results;
database->findUseOfIngInRecipes(&results,ingredientID);
if (results.isEmpty()) database->removeIngredient(ingredientID);
else database->removeIngredient(ingredientID);
reloadIngredientList();// Reload the list from database
}
}
void IngredientsDialog:: reloadPropertyList(void)
{
propertiesList->clear();
propertiesListView->clear();
perUnitListBack->clear();
//If none is selected, select first item
QListViewItem *it;
it=ingredientListView->selectedItem();
//Populate this data into the KListView
if (it){// make sure that the ingredient list is not empty
database->loadProperties(propertiesList,it->text(0).toInt()); // load the list for this ingredient
for ( IngredientProperty *prop =propertiesList->getFirst(); prop; prop =propertiesList->getNext() )
{
QListViewItem *it= new QListViewItem(propertiesListView,QString::number(prop->id),prop->name,QString::number(prop->amount),prop->units+QString("/")+prop->perUnit.name);
// Store the perUnits with the ID for using later
Element perUnitEl;
perUnitEl.id=prop->perUnit.id;
perUnitEl.name=prop->perUnit.name;
perUnitListBack->add(perUnitEl);
}
}
}
void IngredientsDialog:: updateLists(void)
{
//If no ingredient is selected, select first item
QListViewItem *it;
if (!(it=ingredientListView->selectedItem()))
{
it=ingredientListView->firstChild();
}
reloadUnitList();
reloadPropertyList();
}
void IngredientsDialog::addPropertyToIngredient(void)
{
// Find selected ingredient item
QListViewItem *it;
int ingredientID=-1;
if (it=ingredientListView->selectedItem())
{
ingredientID=it->text(0).toInt();
}
if (ingredientID>=0) // an ingredient was selected previously
{
IngredientPropertyList allProperties; database->loadProperties(&allProperties);
ElementList unitList; database->loadPossibleUnits(ingredientID,&unitList);
SelectPropertyDialog* propertyDialog=new SelectPropertyDialog(0,&allProperties,&unitList);
if ( propertyDialog->exec() == QDialog::Accepted ) {
int propertyID = propertyDialog->propertyID();
int perUnitsID = propertyDialog->perUnitsID();
database->addPropertyToIngredient(ingredientID,propertyID,0,perUnitsID); // Add result chosen property to ingredient in database, with amount 0 by default
reloadPropertyList(); // Reload the list from database
}
}
}
void IngredientsDialog::removePropertyFromIngredient(void)
{
// Find selected ingredient/property item combination
QListViewItem *it;
int ingredientID=-1, propertyID=-1;
if (it=ingredientListView->selectedItem()) ingredientID=it->text(0).toInt();
if (it=propertiesListView->selectedItem()) propertyID=it->text(0).toInt();
if ((ingredientID>=0)&&(propertyID>=0)) // an ingredient/property combination was selected previously
{
ElementList results;
database->removePropertyFromIngredient(ingredientID,propertyID);
reloadPropertyList(); // Reload the list from database
}
}
void IngredientsDialog::insertPropertyEditBox(QListViewItem* it)
{
QRect r;
r=propertiesListView->header()->sectionRect(2); //Set in position reference to qlistview, and with the column size();
r.moveBy(propertiesListView->pos().x(),propertiesListView->pos().y()); // Move to the position of qlistview
r.moveBy(0,r.height()+propertiesListView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
inputBox->setGeometry(r);
inputBox->show();
}
void IngredientsDialog::setPropertyAmount(double amount)
{
inputBox->hide();
QListViewItem *ing_it=ingredientListView->selectedItem(); // Find selected ingredient
QListViewItem *prop_it=propertiesListView->selectedItem();
if (ing_it && prop_it)// Appart from property, Check if an ingredient is selected first, just in case
{
prop_it->setText(2,QString::number(amount));
int propertyID=prop_it->text(0).toInt();
int ingredientID=ing_it->text(0).toInt();
int per_units=perUnitListBack->getElement(findPropertyNo(prop_it))->id ;
database->changePropertyAmountToIngredient(ingredientID,propertyID,amount,per_units);
}
reloadPropertyList();
}
int IngredientsDialog::findPropertyNo(QListViewItem *it)
{
bool found=false;
int i = 0;
QListViewItem* item = propertiesListView->firstChild();
while (i < propertiesListView->childCount() && !found) {
if (item == propertiesListView->currentItem())
found = true;
else {
item = item->nextSibling();
++i;
}
}
if (found)
{
return (i);
}
else
{
return (-1);
}
}<|endoftext|> |
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* 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 "Server.hxx"
#include "net/SocketConfig.hxx"
#include "net/SocketAddress.hxx"
#include "net/SendMessage.hxx"
#include "util/ByteOrder.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RuntimeError.hxx"
#include "util/WritableBuffer.hxx"
#include <stdexcept>
#include <assert.h>
#include <string.h>
#include <alloca.h>
ControlServer::ControlServer(EventLoop &event_loop, UniqueSocketDescriptor s,
ControlHandler &_handler) noexcept
:handler(_handler), socket(event_loop, std::move(s), *this)
{
}
ControlServer::ControlServer(EventLoop &event_loop, ControlHandler &_handler,
const SocketConfig &config)
:ControlServer(event_loop, config.Create(SOCK_DGRAM), _handler)
{
}
static void
control_server_decode(ControlServer &control_server,
const void *data, size_t length,
WritableBuffer<UniqueFileDescriptor> fds,
SocketAddress address, int uid,
ControlHandler &handler)
{
/* verify the magic number */
const uint32_t *magic = (const uint32_t *)data;
if (length < sizeof(*magic) || FromBE32(*magic) != BengProxy::control_magic) {
handler.OnControlError(std::make_exception_ptr(std::runtime_error("wrong magic")));
return;
}
data = magic + 1;
length -= sizeof(*magic);
if (length % 4 != 0) {
handler.OnControlError(std::make_exception_ptr(FormatRuntimeError("odd control packet (length=%zu)", length)));
return;
}
/* now decode all commands */
while (length > 0) {
const auto *header = (const BengProxy::ControlHeader *)data;
if (length < sizeof(*header)) {
handler.OnControlError(std::make_exception_ptr(FormatRuntimeError("partial header (length=%zu)",
length)));
return;
}
size_t payload_length = FromBE16(header->length);
const auto command = (BengProxy::ControlCommand)
FromBE16(header->command);
data = header + 1;
length -= sizeof(*header);
const char *payload = (const char *)data;
if (length < payload_length) {
handler.OnControlError(std::make_exception_ptr(FormatRuntimeError("partial payload (length=%zu, expected=%zu)",
length, payload_length)));
return;
}
/* this command is ok, pass it to the callback */
handler.OnControlPacket(control_server, command,
{payload_length > 0 ? payload : nullptr, payload_length},
fds,
address, uid);
payload_length = ((payload_length + 3) | 3) - 3; /* apply padding */
data = payload + payload_length;
length -= payload_length;
}
}
bool
ControlServer::OnUdpDatagram(ConstBuffer<void> payload,
WritableBuffer<UniqueFileDescriptor> fds,
SocketAddress address, int uid)
{
if (!handler.OnControlRaw(payload, address, uid))
/* discard datagram if raw() returns false */
return true;
control_server_decode(*this, payload.data, payload.size,
fds, address, uid, handler);
return true;
}
void
ControlServer::OnUdpError(std::exception_ptr ep) noexcept
{
handler.OnControlError(ep);
}
void
ControlServer::Reply(SocketAddress address,
BengProxy::ControlCommand command,
const void *payload, size_t payload_length)
{
const struct BengProxy::ControlHeader header{ToBE16(payload_length), ToBE16(uint16_t(command))};
struct iovec v[] = {
{ const_cast<BengProxy::ControlHeader *>(&header), sizeof(header) },
{ const_cast<void *>(payload), payload_length },
};
SendMessage(socket.GetSocket(),
MessageHeader(ConstBuffer<struct iovec>(v, std::size(v)))
.SetAddress(address),
MSG_DONTWAIT|MSG_NOSIGNAL);
}
<commit_msg>control/Server: throw instead of invoking OnControlError()<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* 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 "Server.hxx"
#include "net/SocketConfig.hxx"
#include "net/SocketAddress.hxx"
#include "net/SendMessage.hxx"
#include "util/ByteOrder.hxx"
#include "util/ConstBuffer.hxx"
#include "util/RuntimeError.hxx"
#include "util/WritableBuffer.hxx"
#include <stdexcept>
#include <assert.h>
#include <string.h>
#include <alloca.h>
ControlServer::ControlServer(EventLoop &event_loop, UniqueSocketDescriptor s,
ControlHandler &_handler) noexcept
:handler(_handler), socket(event_loop, std::move(s), *this)
{
}
ControlServer::ControlServer(EventLoop &event_loop, ControlHandler &_handler,
const SocketConfig &config)
:ControlServer(event_loop, config.Create(SOCK_DGRAM), _handler)
{
}
static void
control_server_decode(ControlServer &control_server,
const void *data, size_t length,
WritableBuffer<UniqueFileDescriptor> fds,
SocketAddress address, int uid,
ControlHandler &handler)
{
/* verify the magic number */
const uint32_t *magic = (const uint32_t *)data;
if (length < sizeof(*magic) || FromBE32(*magic) != BengProxy::control_magic)
throw std::runtime_error("wrong magic");
data = magic + 1;
length -= sizeof(*magic);
if (length % 4 != 0)
throw FormatRuntimeError("odd control packet (length=%zu)", length);
/* now decode all commands */
while (length > 0) {
const auto *header = (const BengProxy::ControlHeader *)data;
if (length < sizeof(*header))
throw FormatRuntimeError("partial header (length=%zu)",
length);
size_t payload_length = FromBE16(header->length);
const auto command = (BengProxy::ControlCommand)
FromBE16(header->command);
data = header + 1;
length -= sizeof(*header);
const char *payload = (const char *)data;
if (length < payload_length)
throw FormatRuntimeError("partial payload (length=%zu, expected=%zu)",
length, payload_length);
/* this command is ok, pass it to the callback */
handler.OnControlPacket(control_server, command,
{payload_length > 0 ? payload : nullptr, payload_length},
fds,
address, uid);
payload_length = ((payload_length + 3) | 3) - 3; /* apply padding */
data = payload + payload_length;
length -= payload_length;
}
}
bool
ControlServer::OnUdpDatagram(ConstBuffer<void> payload,
WritableBuffer<UniqueFileDescriptor> fds,
SocketAddress address, int uid)
{
if (!handler.OnControlRaw(payload, address, uid))
/* discard datagram if raw() returns false */
return true;
control_server_decode(*this, payload.data, payload.size,
fds, address, uid, handler);
return true;
}
void
ControlServer::OnUdpError(std::exception_ptr ep) noexcept
{
handler.OnControlError(ep);
}
void
ControlServer::Reply(SocketAddress address,
BengProxy::ControlCommand command,
const void *payload, size_t payload_length)
{
const struct BengProxy::ControlHeader header{ToBE16(payload_length), ToBE16(uint16_t(command))};
struct iovec v[] = {
{ const_cast<BengProxy::ControlHeader *>(&header), sizeof(header) },
{ const_cast<void *>(payload), payload_length },
};
SendMessage(socket.GetSocket(),
MessageHeader(ConstBuffer<struct iovec>(v, std::size(v)))
.SetAddress(address),
MSG_DONTWAIT|MSG_NOSIGNAL);
}
<|endoftext|> |
<commit_before>#ifndef _C4_TYPES_HPP_
#define _C4_TYPES_HPP_
#include <stdint.h>
#include <stddef.h>
#include <type_traits>
/** @file types.hpp basic types, and utility macros and traits for types.
* @ingroup basic_headers */
C4_BEGIN_NAMESPACE(c4)
using i8 = int8_t;
using u8 = uint8_t;
using i16 = int16_t;
using u16 = uint16_t;
using i32 = int32_t;
using u32 = uint32_t;
using i64 = int64_t;
using u64 = uint64_t;
using f32 = float;
using f64 = double;
using ssize_t = std::make_signed< size_t >::type;
//--------------------------------------------------
// some tag types
/** a tag type for initializing the containers with variadic arguments a la
* initializer_list, minus the initializer_list overload problems.
* @see */
struct aggregate_t {};
/** @see aggregate_t */
constexpr const aggregate_t aggregate{};
/** a tag type for specifying the initial capacity of allocatable contiguous storage */
struct with_capacity_t {};
/** @see with_capacity_t */
constexpr const with_capacity_t with_capacity{};
//--------------------------------------------------
/** whether a value should be used in place of a const-reference in argument passing. */
template< class T >
struct cref_uses_val
{
enum { value = (
std::is_scalar< T >::value
||
(std::is_pod< T >::value && sizeof(T) <= sizeof(size_t))) };
};
/** utility macro to override the default behaviour for c4::fastcref<T>
@see fastcref */
#define C4_CREF_USES_VAL(T) \
template<> \
struct cref_uses_val< T > \
{ \
enum { value = true }; \
};
/** Whether to use pass-by-value or pass-by-const-reference in a function argument
* or return type. */
template< class T >
using fastcref = typename std::conditional< c4::cref_uses_val< T >::value, T, T const& >::type;
//--------------------------------------------------
/** a tag type which can be used to disambiguate in variadic template overloads */
struct varargs_t {};
/** a tag variable which can be used to disambiguate in variadic template overloads */
constexpr const varargs_t varargs{};
/** Just what its name says. Useful sometimes as a default empty policy class. */
struct EmptyStruct
{
template< class... T > EmptyStruct(T && ...){}
};
/** Just what its name says. Useful sometimes as a default policy class to
* be inherited from. */
struct EmptyStructVirtual
{
virtual ~EmptyStructVirtual() = default;
template< class... T > EmptyStructVirtual(T && ...){}
};
/** */
template< class T >
struct inheritfrom : public T {};
//--------------------------------------------------
// Utilities to make a class obey size restrictions (eg, min size or size multiple of).
// DirectX usually makes this restriction with uniform buffers.
// This is also useful for padding to prevent false-sharing.
/** how many bytes must be added to size such that the result is at least minsize? */
C4_ALWAYS_INLINE constexpr size_t min_remainder(size_t size, size_t minsize)
{
return size < minsize ? minsize-size : 0;
}
/** how many bytes must be added to size such that the result is a multiple of multipleof? */
C4_ALWAYS_INLINE constexpr size_t mult_remainder(size_t size, size_t multipleof)
{
return (((size % multipleof) != 0) ? (multipleof-(size % multipleof)) : 0);
}
/** force the following class to be tightly packed.
* @see http://stackoverflow.com/questions/21092415/force-c-structure-to-pack-tightly */
#pragma pack(push, 1)
/** pad a class with more bytes at the end. */
template< class T, size_t BytesToPadAtEnd >
struct Padded : public T
{
using T::T;
public:
char ___c4padspace___[BytesToPadAtEnd];
};
#pragma pack(pop)
/** When the padding argument is 0, we cannot declare the char[] array. */
template< class T >
struct Padded< T, 0 > : public T
{
using T::T;
};
/** make T have a size which is at least Min bytes */
template< class T, size_t Min >
using MinSized = Padded< T, min_remainder(sizeof(T), Min) >;
/** make T have a size which is a multiple of Mult bytes */
template< class T, size_t Mult >
using MultSized = Padded< T, mult_remainder(sizeof(T), Mult) >;
/** make T have a size which is simultaneously:
* -bigger or equal than Min
* -a multiple of Mult */
template< class T, size_t Min, size_t Mult >
using MinMultSized = MultSized< MinSized< T, Min >, Mult >;
/** make T be suitable for use as a uniform buffer. (at least with DirectX). */
template< class T >
using UbufSized = MinMultSized< T, 64, 16 >;
//-----------------------------------------------------------------------------
/** SFINAE. use this macro to enable a template function overload
based on a compile-time condition.
@code
// define an overload for a non-pod type
template< class T, C4_REQUIRE_T(std::is_pod< T >::value) >
void foo() { std::cout << "pod type\n"; }
// define an overload for a non-pod type
template< class T, C4_REQUIRE_T(!std::is_pod< T >::value) >
void foo() { std::cout << "nonpod type\n"; }
struct non_pod
{
non_pod() : name("asdfkjhasdkjh") {}
const char *name;
};
int main()
{
foo< float >(); // prints "pod type"
foo< non_pod >(); // prints "nonpod type"
}
@endcode */
#define C4_REQUIRE_T(cond) typename std::enable_if< cond, bool >::type* = nullptr
/** enable_if for a return type
* @see C4_REQUIRE_T */
#define C4_REQUIRE_R(cond, type_) typename std::enable_if< cond, type_ >::type
//-----------------------------------------------------------------------------
/** declare a traits class telling whether a type provides a member typedef */
#define C4_DEFINE_HAS_TYPEDEF(member_typedef) \
template< typename T > \
struct has_##stype \
{ \
private: \
\
typedef char yes; \
typedef struct { char array[2]; } no; \
\
template< typename C > \
static yes _test(typename C::member_typedef*); \
\
template< typename C > \
static no _test(...); \
\
public: \
\
enum { value = (sizeof(_test< T >(0)) == sizeof(yes)) }; \
\
}
//-----------------------------------------------------------------------------
/** declare a traits class telling whether a type provides a method */
#define C4_DEFINE_HAS_METHOD(ret_type, method_name, const_qualifier, ...) \
template< typename T > \
struct has_##method_name##_method \
{ \
private: \
\
typedef char &yes; \
typedef struct { char array[2]; } &no; \
\
template< typename C > \
static yes _test \
( \
C const_qualifier* v, \
typename std::enable_if \
< \
std::is_same< decltype(v->method_name(__VA_ARGS__)), ret_type >::value \
, \
void /* this is defined only if the bool above is true. */ \
/* so when it fails, SFINAE is triggered */ \
> \
::type* \
); \
\
template< typename C > \
static no _test(...); \
\
public: \
\
enum { value = (sizeof(_test< T >((typename std::remove_reference< T >::type*)0, 0)) == sizeof(yes)) }; \
\
};
//-----------------------------------------------------------------------------
#define _c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I) \
\
using value_type = T; \
using size_type = I; \
using ssize_type = typename std::make_signed<I>::type; \
\
using pointer = T*; \
using const_pointer = T const*; \
\
using reference = T&; \
using const_reference = T const&; \
\
using difference_type = ptrdiff_t;
#define _c4_DEFINE_ARRAY_TYPES(T, I) \
\
_c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I); \
\
using iterator = T*; \
using const_iterator = T const*; \
\
using reverse_iterator = std::reverse_iterator< T* >; \
using const_reverse_iterator = std::reverse_iterator< T const* >;
//-----------------------------------------------------------------------------
// http://stackoverflow.com/questions/10821380/is-t-an-instance-of-a-template-in-c
template< template < typename... > class X, typename T > struct is_instance_of_tpl : std::false_type {};
template< template < typename... > class X, typename... Y > struct is_instance_of_tpl<X, X<Y...>> : std::true_type {};
//-----------------------------------------------------------------------------
// A template parameter pack is mass-forwardable if
// all of its types are mass-forwardable...
template< class T, class ...Args >
struct is_mass_forwardable : public std::conditional<
is_mass_forwardable< T >::value && is_mass_forwardable< Args... >::value,
std::true_type, std::false_type
>::type
{};
// ... and a type is mass-forwardable if:
template< class T >
struct is_mass_forwardable<T> : public std::conditional<
(
!std::is_rvalue_reference<T>::value ||
(
std::is_trivially_move_constructible<typename std::remove_reference<T>::type>::value &&
std::is_trivially_move_assignable<typename std::remove_reference<T>::type>::value
)
),
std::true_type,
std::false_type
>::type
{};
C4_END_NAMESPACE(c4)
#endif /* _C4_TYPES_HPP_ */
<commit_msg>types: join tag types<commit_after>#ifndef _C4_TYPES_HPP_
#define _C4_TYPES_HPP_
#include <stdint.h>
#include <stddef.h>
#include <type_traits>
/** @file types.hpp basic types, and utility macros and traits for types.
* @ingroup basic_headers */
C4_BEGIN_NAMESPACE(c4)
using i8 = int8_t;
using u8 = uint8_t;
using i16 = int16_t;
using u16 = uint16_t;
using i32 = int32_t;
using u32 = uint32_t;
using i64 = int64_t;
using u64 = uint64_t;
using f32 = float;
using f64 = double;
using ssize_t = std::make_signed< size_t >::type;
//--------------------------------------------------
// some tag types
/** a tag type for initializing the containers with variadic arguments a la
* initializer_list, minus the initializer_list overload problems.
* @see */
struct aggregate_t {};
/** @see aggregate_t */
constexpr const aggregate_t aggregate{};
/** a tag type for specifying the initial capacity of allocatable contiguous storage */
struct with_capacity_t {};
/** @see with_capacity_t */
constexpr const with_capacity_t with_capacity{};
/** a tag type which can be used to disambiguate in variadic template overloads */
struct varargs_t {};
/** a tag variable which can be used to disambiguate in variadic template overloads */
constexpr const varargs_t varargs{};
//--------------------------------------------------
/** whether a value should be used in place of a const-reference in argument passing. */
template< class T >
struct cref_uses_val
{
enum { value = (
std::is_scalar< T >::value
||
(std::is_pod< T >::value && sizeof(T) <= sizeof(size_t))) };
};
/** utility macro to override the default behaviour for c4::fastcref<T>
@see fastcref */
#define C4_CREF_USES_VAL(T) \
template<> \
struct cref_uses_val< T > \
{ \
enum { value = true }; \
};
/** Whether to use pass-by-value or pass-by-const-reference in a function argument
* or return type. */
template< class T >
using fastcref = typename std::conditional< c4::cref_uses_val< T >::value, T, T const& >::type;
//--------------------------------------------------
/** Just what its name says. Useful sometimes as a default empty policy class. */
struct EmptyStruct
{
template< class... T > EmptyStruct(T && ...){}
};
/** Just what its name says. Useful sometimes as a default policy class to
* be inherited from. */
struct EmptyStructVirtual
{
virtual ~EmptyStructVirtual() = default;
template< class... T > EmptyStructVirtual(T && ...){}
};
/** */
template< class T >
struct inheritfrom : public T {};
//--------------------------------------------------
// Utilities to make a class obey size restrictions (eg, min size or size multiple of).
// DirectX usually makes this restriction with uniform buffers.
// This is also useful for padding to prevent false-sharing.
/** how many bytes must be added to size such that the result is at least minsize? */
C4_ALWAYS_INLINE constexpr size_t min_remainder(size_t size, size_t minsize)
{
return size < minsize ? minsize-size : 0;
}
/** how many bytes must be added to size such that the result is a multiple of multipleof? */
C4_ALWAYS_INLINE constexpr size_t mult_remainder(size_t size, size_t multipleof)
{
return (((size % multipleof) != 0) ? (multipleof-(size % multipleof)) : 0);
}
/** force the following class to be tightly packed.
* @see http://stackoverflow.com/questions/21092415/force-c-structure-to-pack-tightly */
#pragma pack(push, 1)
/** pad a class with more bytes at the end. */
template< class T, size_t BytesToPadAtEnd >
struct Padded : public T
{
using T::T;
public:
char ___c4padspace___[BytesToPadAtEnd];
};
#pragma pack(pop)
/** When the padding argument is 0, we cannot declare the char[] array. */
template< class T >
struct Padded< T, 0 > : public T
{
using T::T;
};
/** make T have a size which is at least Min bytes */
template< class T, size_t Min >
using MinSized = Padded< T, min_remainder(sizeof(T), Min) >;
/** make T have a size which is a multiple of Mult bytes */
template< class T, size_t Mult >
using MultSized = Padded< T, mult_remainder(sizeof(T), Mult) >;
/** make T have a size which is simultaneously:
* -bigger or equal than Min
* -a multiple of Mult */
template< class T, size_t Min, size_t Mult >
using MinMultSized = MultSized< MinSized< T, Min >, Mult >;
/** make T be suitable for use as a uniform buffer. (at least with DirectX). */
template< class T >
using UbufSized = MinMultSized< T, 64, 16 >;
//-----------------------------------------------------------------------------
/** SFINAE. use this macro to enable a template function overload
based on a compile-time condition.
@code
// define an overload for a non-pod type
template< class T, C4_REQUIRE_T(std::is_pod< T >::value) >
void foo() { std::cout << "pod type\n"; }
// define an overload for a non-pod type
template< class T, C4_REQUIRE_T(!std::is_pod< T >::value) >
void foo() { std::cout << "nonpod type\n"; }
struct non_pod
{
non_pod() : name("asdfkjhasdkjh") {}
const char *name;
};
int main()
{
foo< float >(); // prints "pod type"
foo< non_pod >(); // prints "nonpod type"
}
@endcode */
#define C4_REQUIRE_T(cond) typename std::enable_if< cond, bool >::type* = nullptr
/** enable_if for a return type
* @see C4_REQUIRE_T */
#define C4_REQUIRE_R(cond, type_) typename std::enable_if< cond, type_ >::type
//-----------------------------------------------------------------------------
/** declare a traits class telling whether a type provides a member typedef */
#define C4_DEFINE_HAS_TYPEDEF(member_typedef) \
template< typename T > \
struct has_##stype \
{ \
private: \
\
typedef char yes; \
typedef struct { char array[2]; } no; \
\
template< typename C > \
static yes _test(typename C::member_typedef*); \
\
template< typename C > \
static no _test(...); \
\
public: \
\
enum { value = (sizeof(_test< T >(0)) == sizeof(yes)) }; \
\
}
//-----------------------------------------------------------------------------
/** declare a traits class telling whether a type provides a method */
#define C4_DEFINE_HAS_METHOD(ret_type, method_name, const_qualifier, ...) \
template< typename T > \
struct has_##method_name##_method \
{ \
private: \
\
typedef char &yes; \
typedef struct { char array[2]; } &no; \
\
template< typename C > \
static yes _test \
( \
C const_qualifier* v, \
typename std::enable_if \
< \
std::is_same< decltype(v->method_name(__VA_ARGS__)), ret_type >::value \
, \
void /* this is defined only if the bool above is true. */ \
/* so when it fails, SFINAE is triggered */ \
> \
::type* \
); \
\
template< typename C > \
static no _test(...); \
\
public: \
\
enum { value = (sizeof(_test< T >((typename std::remove_reference< T >::type*)0, 0)) == sizeof(yes)) }; \
\
};
//-----------------------------------------------------------------------------
#define _c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I) \
\
using value_type = T; \
using size_type = I; \
using ssize_type = typename std::make_signed<I>::type; \
\
using pointer = T*; \
using const_pointer = T const*; \
\
using reference = T&; \
using const_reference = T const&; \
\
using difference_type = ptrdiff_t;
#define _c4_DEFINE_ARRAY_TYPES(T, I) \
\
_c4_DEFINE_ARRAY_TYPES_WITHOUT_ITERATOR(T, I); \
\
using iterator = T*; \
using const_iterator = T const*; \
\
using reverse_iterator = std::reverse_iterator< T* >; \
using const_reverse_iterator = std::reverse_iterator< T const* >;
//-----------------------------------------------------------------------------
// http://stackoverflow.com/questions/10821380/is-t-an-instance-of-a-template-in-c
template< template < typename... > class X, typename T > struct is_instance_of_tpl : std::false_type {};
template< template < typename... > class X, typename... Y > struct is_instance_of_tpl<X, X<Y...>> : std::true_type {};
//-----------------------------------------------------------------------------
// A template parameter pack is mass-forwardable if
// all of its types are mass-forwardable...
template< class T, class ...Args >
struct is_mass_forwardable : public std::conditional<
is_mass_forwardable< T >::value && is_mass_forwardable< Args... >::value,
std::true_type, std::false_type
>::type
{};
// ... and a type is mass-forwardable if:
template< class T >
struct is_mass_forwardable<T> : public std::conditional<
(
!std::is_rvalue_reference<T>::value ||
(
std::is_trivially_move_constructible<typename std::remove_reference<T>::type>::value &&
std::is_trivially_move_assignable<typename std::remove_reference<T>::type>::value
)
),
std::true_type,
std::false_type
>::type
{};
C4_END_NAMESPACE(c4)
#endif /* _C4_TYPES_HPP_ */
<|endoftext|> |
<commit_before>#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
#include <iostream>
#include <string>
using namespace Poco::Net;
using namespace Poco;
using namespace std;
int main(int argc, char **argv) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " <url>" << endl;
cout << " fetch the <url> resource and output the result" << endl;
return -1;
}
try {
URI uri(argv[1]);
HTTPClientSession session(uri.getHost(), uri.getPort());
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
session.sendRequest(req);
HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;
istream &is = session.receiveResponse(res);
StreamCopier::copyStream64(is, cout);
} catch (Poco::Exception &ex) {
cerr << ex.displayText() << endl;
return -1;
}
return 0;
}
<commit_msg>comments for what to do to get POST working in POCO<commit_after>#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
#include <iostream>
#include <string>
using namespace Poco::Net;
using namespace Poco;
using namespace std;
int main(int argc, char **argv) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " <url>" << endl;
cout << " fetch the <url> resource and output the result" << endl;
return -1;
}
try {
URI uri(argv[1]);
HTTPClientSession session(uri.getHost(), uri.getPort());
// http://bsecure/api/v0/session
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
// USE POST
// {"email":"[email protected]","code":"591acbb20a20d8115f7cfd39b218948e"}
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
session.sendRequest(req);
// expect 200 response
HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;
istream &is = session.receiveResponse(res);
StreamCopier::copyStream64(is, cout);
} catch (Poco::Exception &ex) {
cerr << ex.displayText() << endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "widget.h"
#include <QDebug>
#include <QPainter>
#include <QFontMetrics>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
resize(402, 322);
}
Widget::~Widget()
{
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
/*!
* Draw the border
*/
QRect rect = this->geometry();
rect.moveTopLeft(QPoint(0, 0));
rect.adjust(10, 10, -11, -11); /**< set aside for edge. */
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(Qt::white));
painter.drawRoundRect(rect, 10, 10);
/*!
* Draw the Title
*/
painter.setPen(Qt::SolidLine);
painter.setFont(QFont("Microsoft YaHei UI", 12)); /**< Use YaHei Font */
painter.drawText(QRect(rect.left(), rect.top(), rect.width(), 50), Qt::AlignCenter, "Simple barchart example");
/*!
* Set data for test
*/
QStringList monthList;
monthList << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
QStringList valueList;
valueList << "0.0" << "3.2" << "6.5" << "9.8" << "13.0";
/*!
* Calculate the Font's pixel.
*/
QFontMetrics metrics = painter.fontMetrics();
int leftBearing = metrics.width("100.0") + 35; /**< 5 is the scale width. */
const int topBearing = 15;
int coordWidth = rect.width() - 2*leftBearing;
int coordHeight = rect.height() - topBearing - 4*metrics.height();
painter.translate(leftBearing, rect.bottom() - 2*metrics.height()); /**< move center to left bottom */
float deltaX = static_cast<float>(coordWidth)/monthList.size();
float deltaY = static_cast<float>(coordHeight)/(valueList.size()-1);
/*!
* Draw the coordinate
*/
painter.drawLine(0, 0, coordWidth, 0);
for (int i = 0; i != monthList.size(); ++i)
{
int strLen = metrics.width(monthList.at(i));
// scale
painter.drawLine(deltaX*(i+1), 0, deltaX*(i+1), 4);
// text
painter.drawText(deltaX*i + (deltaX-strLen)/2 ,metrics.height(), monthList.at(i));
}
painter.drawLine(0, 0, 0, -coordHeight);
for (int i = 0; i != valueList.size(); ++i)
{
int deviation = metrics.height()/2 - metrics.descent();
painter.drawLine(-4, -deltaY*i, 0, -deltaY*i);
painter.drawText(-metrics.width(valueList.at(i))-4, -deltaY*i+deviation, valueList.at(i));
}
}
<commit_msg>remove warning<commit_after>#include "widget.h"
#include <QDebug>
#include <QPainter>
#include <QFontMetrics>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
resize(402, 322);
}
Widget::~Widget()
{
}
void Widget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
/*!
* Draw the border
*/
QRect rect = this->geometry();
rect.moveTopLeft(QPoint(0, 0));
rect.adjust(10, 10, -11, -11); /**< set aside for edge. */
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(Qt::white));
painter.drawRoundRect(rect, 10, 10);
/*!
* Draw the Title
*/
painter.setPen(Qt::SolidLine);
painter.setFont(QFont("Microsoft YaHei UI", 12)); /**< Use YaHei Font */
painter.drawText(QRect(rect.left(), rect.top(), rect.width(), 50), Qt::AlignCenter, "Simple barchart example");
/*!
* Set data for test
*/
QStringList monthList;
monthList << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
QStringList valueList;
valueList << "0.0" << "3.2" << "6.5" << "9.8" << "13.0";
/*!
* Calculate the Font's pixel.
*/
QFontMetrics metrics = painter.fontMetrics();
int leftBearing = metrics.width("100.0") + 35; /**< 5 is the scale width. */
const int topBearing = 15;
int coordWidth = rect.width() - 2*leftBearing;
int coordHeight = rect.height() - topBearing - 4*metrics.height();
painter.translate(leftBearing, rect.bottom() - 2*metrics.height()); /**< move center to left bottom */
float deltaX = static_cast<float>(coordWidth)/monthList.size();
float deltaY = static_cast<float>(coordHeight)/(valueList.size()-1);
/*!
* Draw the coordinate
*/
painter.drawLine(0, 0, coordWidth, 0);
for (int i = 0; i != monthList.size(); ++i)
{
int strLen = metrics.width(monthList.at(i));
// scale
painter.drawLine(deltaX*(i+1), 0, deltaX*(i+1), 4);
// text
painter.drawText(deltaX*i + (deltaX-strLen)/2 ,metrics.height(), monthList.at(i));
}
painter.drawLine(0, 0, 0, -coordHeight);
for (int i = 0; i != valueList.size(); ++i)
{
int deviation = metrics.height()/2 - metrics.descent();
painter.drawLine(-4, -deltaY*i, 0, -deltaY*i);
painter.drawText(-metrics.width(valueList.at(i))-4, -deltaY*i+deviation, valueList.at(i));
}
}
<|endoftext|> |
<commit_before>/*
* dialer - MeeGo Voice Call Manager
* Copyright (c) 2009, 2010, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
#include "common.h"
#include "callitem.h"
#include "callitemmodel.h"
#include "dialerapplication.h"
#include "seasidesyncmodel.h"
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QDebug>
#include <MTheme>
#include <MWidgetCreator>
#define DEFAULT_RINGTONE "ring-1.wav"
M_REGISTER_WIDGET(CallItem)
CallItem::CallItem(const QString path, MWidget *parent)
: MWidgetController(new CallItemModel, parent),
m_path(path),
m_peopleItem(NULL),
m_ringtone(new QMediaPlayer()),
m_rtKey(new MGConfItem("/apps/dialer/defaultRingtone")),
m_isconnected(FALSE),
m_ringtonefile("")
{
TRACE
m_ringtonefile = QString("%1/%2/stereo/%3")
.arg(SOUNDS_DIR)
.arg(MTheme::instance()->currentTheme())
.arg(DEFAULT_RINGTONE);
m_ringtone->setMedia(QMediaContent(QUrl::fromLocalFile(
m_rtKey->value(QVariant(m_ringtonefile)).toString())));
m_ringtone->setVolume(100);
if (isValid())
init();
}
CallItem::~CallItem()
{
TRACE
if (m_ringtone) {
disconnect(m_ringtone, SIGNAL(positionChanged(qint64)));
m_ringtone->stop();
delete m_ringtone;
m_ringtone = 0;
}
if (m_rtKey)
delete m_rtKey;
m_rtKey = 0;
if (m_peopleItem)
delete m_peopleItem;
m_peopleItem = 0;
// delete the callproxy object
if (callProxy())
delete callProxy();
}
void CallItem::init()
{
TRACE
if (!m_path.isEmpty()) {
CallProxy *call = new CallProxy(m_path);
if (call->isValid()) {
model()->setCall(call);
connect(call,SIGNAL(stateChanged()),this,SLOT(callStateChanged()));
connect(call,SIGNAL(dataChanged()),this,SLOT(callDataChanged()));
} else
qCritical("Invalid CallProxy instance!");
} else
qCritical("Empty call path. Can not create CallProxy!");
populatePeopleItem();
if (state() == CallItemModel::STATE_INCOMING ||
state() == CallItemModel::STATE_WAITING)
{
// Start ringing
if (!m_isconnected && m_ringtone) {
connect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
SLOT(ringtoneStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = TRUE;
m_ringtone->play();
}
}
}
bool CallItem::isValid()
{
TRACE
return (!path().isEmpty());
}
bool CallItem::isValid() const
{
TRACE
return (!path().isEmpty());
}
QString CallItem::path() const
{
TRACE
return m_path;
}
bool CallItem::setPath(QString path)
{
TRACE
if (!m_path.isEmpty()) {
qCritical("Path already set and can not be changed once it is set");
return false;
} else if (path.isEmpty()) {
qCritical("It makes no sense to set Path to an empty string!?!?");
return false;
}
m_path = path;
init();
return true;
}
void CallItem::setDirection(CallItemModel::CallDirection direction)
{
TRACE
model()->setDirection(direction);
}
QString CallItem::lineID() const
{
TRACE
return (isValid())?model()->lineID():QString();
}
QString CallItem::name() const
{
TRACE
return (isValid())?model()->name():QString();
}
CallItemModel::CallState CallItem::state() const
{
TRACE
return model()->stateType();
}
CallItemModel::CallDirection CallItem::direction() const
{
TRACE
return model()->direction();
}
CallItemModel::CallDisconnectReason CallItem::reason() const
{
TRACE
return model()->reasonType();
}
int CallItem::duration() const
{
TRACE
return model()->duration();
}
QDateTime CallItem::startTime() const
{
TRACE
return model()->startTime();
}
PeopleItem * CallItem::peopleItem() const
{
TRACE
return m_peopleItem;
}
CallProxy* CallItem::callProxy() const
{
TRACE
return model()->call();
}
void CallItem::setPeopleItem(PeopleItem *person)
{
TRACE
if (m_peopleItem)
delete m_peopleItem;
m_peopleItem = person;
}
void CallItem::click()
{
TRACE
emit clicked();
}
void CallItem::callStateChanged()
{
TRACE
if (state() == CallItemModel::STATE_INCOMING ||
state() == CallItemModel::STATE_WAITING)
{
// Start ringing
if (!m_isconnected && m_ringtone) {
connect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
SLOT(ringtoneStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = TRUE;
m_ringtone->play();
}
} else {
// Stop ringing
if (m_ringtone) {
disconnect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = FALSE;
m_ringtone->stop();
}
}
emit stateChanged();
}
void CallItem::callDataChanged()
{
// For now we only handle lineid because
// a) that's the only case where the signal is emitted
// b) I haven't read anything about callerid name changing in-call
populatePeopleItem();
}
void CallItem::callDisconnected(const QString &reason)
{
TRACE
Q_UNUSED(reason);
}
QVariant CallItem::itemChange(GraphicsItemChange change, const QVariant &val)
{
TRACE
if (change == QGraphicsItem::ItemSelectedHasChanged)
model()->setSelected(val.toBool());
return QGraphicsItem::itemChange(change, val);
}
void CallItem::populatePeopleItem()
{
TRACE
QModelIndexList matches;
matches.clear();
int role = Seaside::SearchRole;
int hits = -1;
//% "Unknown Caller"
QString pi_name = qtTrId("xx_unknown_caller");
QString pi_photo = "icon-m-content-avatar-placeholder";
//% "Private"
QString pi_lineid = qtTrId("xx_private");
if (!lineID().isEmpty()) {
pi_lineid = stripLineID(lineID());
SeasideSyncModel *contacts = DA_SEASIDEMODEL;
QModelIndex first = contacts->index(0,Seaside::ColumnPhoneNumbers);
matches = contacts->match(first, role, QVariant(pi_lineid), hits);
QString firstName = QString();
QString lastName = QString();
if (!matches.isEmpty()) {
QModelIndex person = matches.at(0); //First match is all we look at
SEASIDE_SHORTCUTS
SEASIDE_SET_MODEL_AND_ROW(person.model(), person.row());
firstName = SEASIDE_FIELD(FirstName, String);
lastName = SEASIDE_FIELD(LastName, String);
pi_photo = SEASIDE_FIELD(Avatar, String);
} else if (!name().isEmpty()) {
// We don't have a contact, but we have a callerid name, let's use it
firstName = name();
}
if (lastName.isEmpty() && !firstName.isEmpty())
// Contacts first (common) name
//% "%1"
pi_name = qtTrId("xx_first_name").arg(firstName);
else if (firstName.isEmpty() && !lastName.isEmpty())
// BMC# 8079 - NW
// Contacts last (sur) name
//% "%1"
pi_name = qtTrId("xx_last_name").arg(lastName);
else if (!firstName.isEmpty() && !lastName.isEmpty())
// Contacts full, sortable name, is "Firstname Lastname"
//% "%1 %2"
pi_name = qtTrId("xx_first_last_name").arg(firstName)
.arg(lastName);
} else {
//% "Unavailable"
pi_lineid = qtTrId("xx_unavailable");
}
if (m_peopleItem != NULL)
delete m_peopleItem;
m_peopleItem = new PeopleItem();
m_peopleItem->setName(pi_name);
m_peopleItem->setPhoto(pi_photo);
m_peopleItem->setPhone(pi_lineid);
}
void CallItem::ringtoneStatusChanged(QMediaPlayer::MediaStatus status)
{
TRACE
if (status == QMediaPlayer::EndOfMedia)
{
m_ringtone->setMedia(QMediaContent(QUrl::fromLocalFile(m_ringtonefile)));
m_ringtone->play();
}
}
<commit_msg>Fixed: For FEA#4419, remove wrong comment and whitespace cleanup<commit_after>/*
* dialer - MeeGo Voice Call Manager
* Copyright (c) 2009, 2010, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
#include "common.h"
#include "callitem.h"
#include "callitemmodel.h"
#include "dialerapplication.h"
#include "seasidesyncmodel.h"
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QDebug>
#include <MTheme>
#include <MWidgetCreator>
#define DEFAULT_RINGTONE "ring-1.wav"
M_REGISTER_WIDGET(CallItem)
CallItem::CallItem(const QString path, MWidget *parent)
: MWidgetController(new CallItemModel, parent),
m_path(path),
m_peopleItem(NULL),
m_ringtone(new QMediaPlayer()),
m_rtKey(new MGConfItem("/apps/dialer/defaultRingtone")),
m_isconnected(FALSE),
m_ringtonefile("")
{
TRACE
m_ringtonefile = QString("%1/%2/stereo/%3")
.arg(SOUNDS_DIR)
.arg(MTheme::instance()->currentTheme())
.arg(DEFAULT_RINGTONE);
m_ringtone->setMedia(QMediaContent(QUrl::fromLocalFile(
m_rtKey->value(QVariant(m_ringtonefile)).toString())));
m_ringtone->setVolume(100);
if (isValid())
init();
}
CallItem::~CallItem()
{
TRACE
if (m_ringtone) {
disconnect(m_ringtone, SIGNAL(positionChanged(qint64)));
m_ringtone->stop();
delete m_ringtone;
m_ringtone = 0;
}
if (m_rtKey)
delete m_rtKey;
m_rtKey = 0;
if (m_peopleItem)
delete m_peopleItem;
m_peopleItem = 0;
// delete the callproxy object
if (callProxy())
delete callProxy();
}
void CallItem::init()
{
TRACE
if (!m_path.isEmpty()) {
CallProxy *call = new CallProxy(m_path);
if (call->isValid()) {
model()->setCall(call);
connect(call,SIGNAL(stateChanged()),this,SLOT(callStateChanged()));
connect(call,SIGNAL(dataChanged()),this,SLOT(callDataChanged()));
} else
qCritical("Invalid CallProxy instance!");
} else
qCritical("Empty call path. Can not create CallProxy!");
populatePeopleItem();
if (state() == CallItemModel::STATE_INCOMING ||
state() == CallItemModel::STATE_WAITING)
{
// Start ringing
if (!m_isconnected && m_ringtone) {
connect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
SLOT(ringtoneStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = TRUE;
m_ringtone->play();
}
}
}
bool CallItem::isValid()
{
TRACE
return (!path().isEmpty());
}
bool CallItem::isValid() const
{
TRACE
return (!path().isEmpty());
}
QString CallItem::path() const
{
TRACE
return m_path;
}
bool CallItem::setPath(QString path)
{
TRACE
if (!m_path.isEmpty()) {
qCritical("Path already set and can not be changed once it is set");
return false;
} else if (path.isEmpty()) {
qCritical("It makes no sense to set Path to an empty string!?!?");
return false;
}
m_path = path;
init();
return true;
}
void CallItem::setDirection(CallItemModel::CallDirection direction)
{
TRACE
model()->setDirection(direction);
}
QString CallItem::lineID() const
{
TRACE
return (isValid())?model()->lineID():QString();
}
QString CallItem::name() const
{
TRACE
return (isValid())?model()->name():QString();
}
CallItemModel::CallState CallItem::state() const
{
TRACE
return model()->stateType();
}
CallItemModel::CallDirection CallItem::direction() const
{
TRACE
return model()->direction();
}
CallItemModel::CallDisconnectReason CallItem::reason() const
{
TRACE
return model()->reasonType();
}
int CallItem::duration() const
{
TRACE
return model()->duration();
}
QDateTime CallItem::startTime() const
{
TRACE
return model()->startTime();
}
PeopleItem * CallItem::peopleItem() const
{
TRACE
return m_peopleItem;
}
CallProxy* CallItem::callProxy() const
{
TRACE
return model()->call();
}
void CallItem::setPeopleItem(PeopleItem *person)
{
TRACE
if (m_peopleItem)
delete m_peopleItem;
m_peopleItem = person;
}
void CallItem::click()
{
TRACE
emit clicked();
}
void CallItem::callStateChanged()
{
TRACE
if (state() == CallItemModel::STATE_INCOMING ||
state() == CallItemModel::STATE_WAITING)
{
// Start ringing
if (!m_isconnected && m_ringtone) {
connect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
SLOT(ringtoneStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = TRUE;
m_ringtone->play();
}
} else {
// Stop ringing
if (m_ringtone) {
disconnect(m_ringtone, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
m_isconnected = FALSE;
m_ringtone->stop();
}
}
emit stateChanged();
}
void CallItem::callDataChanged()
{
populatePeopleItem();
}
void CallItem::callDisconnected(const QString &reason)
{
TRACE
Q_UNUSED(reason);
}
QVariant CallItem::itemChange(GraphicsItemChange change, const QVariant &val)
{
TRACE
if (change == QGraphicsItem::ItemSelectedHasChanged)
model()->setSelected(val.toBool());
return QGraphicsItem::itemChange(change, val);
}
void CallItem::populatePeopleItem()
{
TRACE
QModelIndexList matches;
matches.clear();
int role = Seaside::SearchRole;
int hits = -1;
//% "Unknown Caller"
QString pi_name = qtTrId("xx_unknown_caller");
QString pi_photo = "icon-m-content-avatar-placeholder";
//% "Private"
QString pi_lineid = qtTrId("xx_private");
if (!lineID().isEmpty()) {
pi_lineid = stripLineID(lineID());
SeasideSyncModel *contacts = DA_SEASIDEMODEL;
QModelIndex first = contacts->index(0,Seaside::ColumnPhoneNumbers);
matches = contacts->match(first, role, QVariant(pi_lineid), hits);
QString firstName = QString();
QString lastName = QString();
if (!matches.isEmpty()) {
QModelIndex person = matches.at(0); //First match is all we look at
SEASIDE_SHORTCUTS
SEASIDE_SET_MODEL_AND_ROW(person.model(), person.row());
firstName = SEASIDE_FIELD(FirstName, String);
lastName = SEASIDE_FIELD(LastName, String);
pi_photo = SEASIDE_FIELD(Avatar, String);
} else if (!name().isEmpty()) {
// We don't have a contact, but we have a callerid name, let's use it
firstName = name();
}
if (lastName.isEmpty() && !firstName.isEmpty())
// Contacts first (common) name
//% "%1"
pi_name = qtTrId("xx_first_name").arg(firstName);
else if (firstName.isEmpty() && !lastName.isEmpty())
// BMC# 8079 - NW
// Contacts last (sur) name
//% "%1"
pi_name = qtTrId("xx_last_name").arg(lastName);
else if (!firstName.isEmpty() && !lastName.isEmpty())
// Contacts full, sortable name, is "Firstname Lastname"
//% "%1 %2"
pi_name = qtTrId("xx_first_last_name").arg(firstName)
.arg(lastName);
} else {
//% "Unavailable"
pi_lineid = qtTrId("xx_unavailable");
}
if (m_peopleItem != NULL)
delete m_peopleItem;
m_peopleItem = new PeopleItem();
m_peopleItem->setName(pi_name);
m_peopleItem->setPhoto(pi_photo);
m_peopleItem->setPhone(pi_lineid);
}
void CallItem::ringtoneStatusChanged(QMediaPlayer::MediaStatus status)
{
TRACE
if (status == QMediaPlayer::EndOfMedia)
{
m_ringtone->setMedia(QMediaContent(QUrl::fromLocalFile(m_ringtonefile)));
m_ringtone->play();
}
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
using namespace std;
#include "config.h"
#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"
void usage()
{
cout << " usage: [--create-keyring] [--gen-key] [--name=<name>] [--set-uid=uid] [--caps=<filename>] [--list] [--print-key] <filename>" << std::endl;
exit(1);
}
int main(int argc, const char **argv)
{
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
DEFINE_CONF_VARS(usage);
common_init(args, "osdmaptool", false, false);
const char *me = argv[0];
const char *fn = 0;
bool gen_key = false;
const char *add_key = 0;
bool list = false;
bool print_key = false;
bool create_keyring = false;
const char *caps_fn = NULL;
const char *import_keyring = NULL;
bool set_auid = false;
__u64 auid = CEPH_AUTH_UID_DEFAULT;
const char *name = g_conf.name;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("gen-key", 'g')) {
CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
} else if (CONF_ARG_EQ("add-key", 'a')) {
CONF_SAFE_SET_ARG_VAL(&add_key, OPT_STR);
} else if (CONF_ARG_EQ("list", 'l')) {
CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
} else if (CONF_ARG_EQ("caps", '\0')) {
CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
} else if (CONF_ARG_EQ("print-key", 'p')) {
CONF_SAFE_SET_ARG_VAL(&print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("create-keyring", 'c')) {
CONF_SAFE_SET_ARG_VAL(&create_keyring, OPT_BOOL);
} else if (CONF_ARG_EQ("import-keyring", '\0')) {
CONF_SAFE_SET_ARG_VAL(&import_keyring, OPT_STR);
} else if (CONF_ARG_EQ("set-uid", 'u')) {
CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG);
set_auid = true;
} else if (!fn) {
fn = args[i];
} else
usage();
}
if (!fn) {
cerr << me << ": must specify filename" << std::endl;
usage();
}
if (!(gen_key ||
add_key ||
list ||
caps_fn ||
set_auid ||
print_key ||
create_keyring ||
import_keyring)) {
cerr << "no command specified" << std::endl;
usage();
}
if (gen_key && add_key) {
cerr << "can't both gen_key and add_key" << std::endl;
usage();
}
if (caps_fn || add_key || gen_key || print_key || set_auid) {
if (!name || !(*name)) {
cerr << "must specify entity name" << std::endl;
usage();
}
}
// keyring --------
bool modified = false;
KeyRing keyring;
string s = name;
EntityName ename;
if (name[0] && !ename.from_str(s)) {
cerr << "'" << s << "' is not a valid entity name" << std::endl;
exit(1);
}
bufferlist bl;
int r = 0;
if (create_keyring) {
cout << "creating " << fn << std::endl;
modified = true;
} else {
r = bl.read_file(fn, true);
if (r >= 0) {
try {
bufferlist::iterator iter = bl.begin();
::decode(keyring, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << fn << std::endl;
exit(1);
}
} else {
cerr << "can't open " << fn << ": " << strerror(-r) << std::endl;
exit(1);
}
}
// write commands
if (import_keyring) {
KeyRing other;
bufferlist obl;
int r = obl.read_file(import_keyring);
if (r >= 0) {
try {
bufferlist::iterator iter = obl.begin();
::decode(other, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << import_keyring << std::endl;
exit(1);
}
cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
//other.print(cout);
keyring.import(other);
modified = true;
} else {
cerr << "can't open " << import_keyring << ": " << strerror(-r) << std::endl;
exit(1);
}
}
if (gen_key) {
EntityAuth eauth;
eauth.key.create(CEPH_CRYPTO_AES);
keyring.add(ename, eauth);
modified = true;
}
if (add_key) {
if (!name) {
cerr << "must specify a name to add a key" << std::endl;
exit(1);
}
EntityAuth eauth;
string ekey(add_key);
try {
eauth.key.decode_base64(ekey);
} catch (buffer::error *err) {
cerr << "can't decode key '" << add_key << "'" << std::endl;
exit(1);
}
keyring.add(ename, eauth);
modified = true;
cout << "added entity " << ename << " auth " << eauth << std::endl;
}
if (caps_fn) {
ConfFile *cf = new ConfFile(caps_fn);
if (!cf->parse()) {
cerr << "could not parse caps file " << caps_fn << std::endl;
exit(1);
}
map<string, bufferlist> caps;
const char *key_names[] = { "mon", "osd", "mds", NULL };
for (int i=0; key_names[i]; i++) {
char *val;
cf->read("global", key_names[i], &val, NULL);
if (val) {
bufferlist bl;
::encode(val, bl);
string s(key_names[i]);
caps[s] = bl;
free(val);
}
}
keyring.set_caps(ename, caps);
modified = true;
}
if (set_auid) {
if (!name) {
cerr << "must specify a name to set a uid" << std::endl;
exit(1);
}
keyring.set_uid(ename, auid);
modified = true;
}
// read commands
if (list) {
keyring.print(cout);
}
if (print_key) {
CryptoKey key;
if (keyring.get_secret(ename, key)) {
string a;
key.encode_base64(a);
cout << a << std::endl;
} else {
cerr << "entity " << ename << " not found" << std::endl;
}
}
// write result?
if (modified) {
bufferlist bl;
::encode(keyring, bl);
r = bl.write_file(fn, 0600);
if (r < 0) {
cerr << "could not write " << fn << std::endl;
}
//cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
}
return 0;
}
<commit_msg>auth: cauthtool now identifies itself properly to common_init<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
using namespace std;
#include "config.h"
#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"
void usage()
{
cout << " usage: [--create-keyring] [--gen-key] [--name=<name>] [--set-uid=uid] [--caps=<filename>] [--list] [--print-key] <filename>" << std::endl;
exit(1);
}
int main(int argc, const char **argv)
{
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
DEFINE_CONF_VARS(usage);
common_init(args, "cauthtool", false, false);
const char *me = argv[0];
const char *fn = 0;
bool gen_key = false;
const char *add_key = 0;
bool list = false;
bool print_key = false;
bool create_keyring = false;
const char *caps_fn = NULL;
const char *import_keyring = NULL;
bool set_auid = false;
__u64 auid = CEPH_AUTH_UID_DEFAULT;
const char *name = g_conf.name;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("gen-key", 'g')) {
CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
} else if (CONF_ARG_EQ("add-key", 'a')) {
CONF_SAFE_SET_ARG_VAL(&add_key, OPT_STR);
} else if (CONF_ARG_EQ("list", 'l')) {
CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
} else if (CONF_ARG_EQ("caps", '\0')) {
CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
} else if (CONF_ARG_EQ("print-key", 'p')) {
CONF_SAFE_SET_ARG_VAL(&print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("create-keyring", 'c')) {
CONF_SAFE_SET_ARG_VAL(&create_keyring, OPT_BOOL);
} else if (CONF_ARG_EQ("import-keyring", '\0')) {
CONF_SAFE_SET_ARG_VAL(&import_keyring, OPT_STR);
} else if (CONF_ARG_EQ("set-uid", 'u')) {
CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG);
set_auid = true;
} else if (!fn) {
fn = args[i];
} else
usage();
}
if (!fn) {
cerr << me << ": must specify filename" << std::endl;
usage();
}
if (!(gen_key ||
add_key ||
list ||
caps_fn ||
set_auid ||
print_key ||
create_keyring ||
import_keyring)) {
cerr << "no command specified" << std::endl;
usage();
}
if (gen_key && add_key) {
cerr << "can't both gen_key and add_key" << std::endl;
usage();
}
if (caps_fn || add_key || gen_key || print_key || set_auid) {
if (!name || !(*name)) {
cerr << "must specify entity name" << std::endl;
usage();
}
}
// keyring --------
bool modified = false;
KeyRing keyring;
string s = name;
EntityName ename;
if (name[0] && !ename.from_str(s)) {
cerr << "'" << s << "' is not a valid entity name" << std::endl;
exit(1);
}
bufferlist bl;
int r = 0;
if (create_keyring) {
cout << "creating " << fn << std::endl;
modified = true;
} else {
r = bl.read_file(fn, true);
if (r >= 0) {
try {
bufferlist::iterator iter = bl.begin();
::decode(keyring, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << fn << std::endl;
exit(1);
}
} else {
cerr << "can't open " << fn << ": " << strerror(-r) << std::endl;
exit(1);
}
}
// write commands
if (import_keyring) {
KeyRing other;
bufferlist obl;
int r = obl.read_file(import_keyring);
if (r >= 0) {
try {
bufferlist::iterator iter = obl.begin();
::decode(other, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << import_keyring << std::endl;
exit(1);
}
cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
//other.print(cout);
keyring.import(other);
modified = true;
} else {
cerr << "can't open " << import_keyring << ": " << strerror(-r) << std::endl;
exit(1);
}
}
if (gen_key) {
EntityAuth eauth;
eauth.key.create(CEPH_CRYPTO_AES);
keyring.add(ename, eauth);
modified = true;
}
if (add_key) {
if (!name) {
cerr << "must specify a name to add a key" << std::endl;
exit(1);
}
EntityAuth eauth;
string ekey(add_key);
try {
eauth.key.decode_base64(ekey);
} catch (buffer::error *err) {
cerr << "can't decode key '" << add_key << "'" << std::endl;
exit(1);
}
keyring.add(ename, eauth);
modified = true;
cout << "added entity " << ename << " auth " << eauth << std::endl;
}
if (caps_fn) {
ConfFile *cf = new ConfFile(caps_fn);
if (!cf->parse()) {
cerr << "could not parse caps file " << caps_fn << std::endl;
exit(1);
}
map<string, bufferlist> caps;
const char *key_names[] = { "mon", "osd", "mds", NULL };
for (int i=0; key_names[i]; i++) {
char *val;
cf->read("global", key_names[i], &val, NULL);
if (val) {
bufferlist bl;
::encode(val, bl);
string s(key_names[i]);
caps[s] = bl;
free(val);
}
}
keyring.set_caps(ename, caps);
modified = true;
}
if (set_auid) {
if (!name) {
cerr << "must specify a name to set a uid" << std::endl;
exit(1);
}
keyring.set_uid(ename, auid);
modified = true;
}
// read commands
if (list) {
keyring.print(cout);
}
if (print_key) {
CryptoKey key;
if (keyring.get_secret(ename, key)) {
string a;
key.encode_base64(a);
cout << a << std::endl;
} else {
cerr << "entity " << ename << " not found" << std::endl;
}
}
// write result?
if (modified) {
bufferlist bl;
::encode(keyring, bl);
r = bl.write_file(fn, 0600);
if (r < 0) {
cerr << "could not write " << fn << std::endl;
}
//cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <OpenColorIO/OpenColorIO.h>
OCIO_NAMESPACE_ENTER
{
Exception::Exception(const char * msg) throw()
: std::runtime_error(msg)
{}
Exception::Exception(const Exception& e) throw()
: std::runtime_error(e)
{}
//*** ~Exception
Exception::~Exception() throw()
{
}
ExceptionMissingFile::ExceptionMissingFile(const char * msg) throw()
: Exception(msg)
{}
ExceptionMissingFile::ExceptionMissingFile(const ExceptionMissingFile& e) throw()
: Exception(e)
{}
}
OCIO_NAMESPACE_EXIT
///////////////////////////////////////////////////////////////////////////////
#ifdef OCIO_UNIT_TEST
namespace OCIO = OCIO_NAMESPACE;
#include "UnitTest.h"
OIIO_ADD_TEST(Exception, Basic)
{
static const char* dummyErrorStr = "Dummy error";
// Test 1
try
{
throw OCIO::Exception(dummyErrorStr);
}
catch(const std::exception& ex)
{
OIIO_CHECK_EQUAL(strcmp(ex.what(), dummyErrorStr), 0);
}
catch(...)
{
OIIO_CHECK_EQUAL(0x0, "wrong exception type");
}
// Test 2
try
{
OCIO::Exception ex(dummyErrorStr);
throw OCIO::Exception(ex);
}
catch(const std::exception& ex)
{
OIIO_CHECK_EQUAL(strcmp(ex.what(), dummyErrorStr), 0);
}
catch(...)
{
OIIO_CHECK_EQUAL(0x0, "wrong exception type");
}
}
#endif // OCIO_UNIT_TEST
<commit_msg>Remove the stl string of Exception from the public API, fix *nix build break, part II<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <OpenColorIO/OpenColorIO.h>
OCIO_NAMESPACE_ENTER
{
Exception::Exception(const char * msg) throw()
: std::runtime_error(msg)
{}
Exception::Exception(const Exception& e) throw()
: std::runtime_error(e)
{}
//*** ~Exception
Exception::~Exception() throw()
{
}
ExceptionMissingFile::ExceptionMissingFile(const char * msg) throw()
: Exception(msg)
{}
ExceptionMissingFile::ExceptionMissingFile(const ExceptionMissingFile& e) throw()
: Exception(e)
{}
}
OCIO_NAMESPACE_EXIT
///////////////////////////////////////////////////////////////////////////////
#ifdef OCIO_UNIT_TEST
namespace OCIO = OCIO_NAMESPACE;
#include "UnitTest.h"
#include <string.h>
OIIO_ADD_TEST(Exception, Basic)
{
static const char* dummyErrorStr = "Dummy error";
// Test 1
try
{
throw OCIO::Exception(dummyErrorStr);
}
catch(const std::exception& ex)
{
OIIO_CHECK_EQUAL(strcmp(ex.what(), dummyErrorStr), 0);
}
catch(...)
{
OIIO_CHECK_EQUAL(0x0, "wrong exception type");
}
// Test 2
try
{
OCIO::Exception ex(dummyErrorStr);
throw OCIO::Exception(ex);
}
catch(const std::exception& ex)
{
OIIO_CHECK_EQUAL(strcmp(ex.what(), dummyErrorStr), 0);
}
catch(...)
{
OIIO_CHECK_EQUAL(0x0, "wrong exception type");
}
}
#endif // OCIO_UNIT_TEST
<|endoftext|> |
<commit_before>#include "fmv.hpp"
#include "imgui/imgui.h"
#include "core/audiobuffer.hpp"
#include "gamedata.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif/*__APPLE__*/
class FmvUi
{
private:
char buf[4096];
ImGuiTextFilter mFilter;
int listbox_item_current = 1;
std::vector<const char*> listbox_items;
public:
FmvUi()
{
#ifdef _WIN32
strcpy(buf, "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Oddysee\\");
#else
strcpy(buf, "/home/paul/ae_test/");
#endif
}
void DrawVideoSelectionUi(std::unique_ptr<Oddlib::Masher>& video, FILE*& fp, SDL_Surface*& videoFrame, const std::string& setName, const std::vector<std::string>& allFmvs)
{
std::string name = "Video player (" + setName + ")";
ImGui::Begin(name.c_str(), nullptr, ImVec2(550, 580), 1.0f, ImGuiWindowFlags_NoCollapse);
ImGui::InputText("Video path", buf, sizeof(buf));
mFilter.Draw();
listbox_items.resize(allFmvs.size());
int matchingFilter = 0;
for (size_t i = 0; i < allFmvs.size(); i++)
{
if (mFilter.PassFilter(allFmvs[i].c_str()))
{
listbox_items[matchingFilter] = allFmvs[i].c_str();
matchingFilter++;
}
}
ImGui::PushItemWidth(-1);
ImGui::ListBox("##", &listbox_item_current, listbox_items.data(), matchingFilter, 27);
if (ImGui::Button("Play", ImVec2(ImGui::GetWindowWidth(), 20)))
{
std::string fullPath = std::string(buf) + listbox_items[listbox_item_current];
std::cout << "Play " << listbox_items[listbox_item_current] << std::endl;
try
{
video = std::make_unique<Oddlib::Masher>(fullPath);
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
if (video->HasAudio())
{
AudioBuffer::ChangeAudioSpec(video->SingleAudioFrameSizeBytes(), video->AudioSampleRate());
}
if (video->HasVideo())
{
videoFrame = SDL_CreateRGBSurface(0, video->Width(), video->Height(), 32, 0, 0, 0, 0);
// targetFps = video->FrameRate() * 2;
}
SDL_ShowCursor(0);
}
catch (const Oddlib::Exception& ex)
{
// ImGui::Text(ex.what());
fp = fopen(fullPath.c_str(), "rb");
AudioBuffer::ChangeAudioSpec(8064/4, 37800);
}
}
ImGui::End();
}
};
struct CDXASector
{
/*
uint8_t sync[12];
uint8_t header[4];
struct CDXASubHeader
{
uint8_t file_number;
uint8_t channel;
uint8_t submode;
uint8_t coding_info;
uint8_t file_number_copy;
uint8_t channel_number_copy;
uint8_t submode_copy;
uint8_t coding_info_copy;
} subheader;
uint8_t data[2328];
*/
uint8_t data[2328 + 12 + 4 + 8];
};
// expected 2352
// 2328 + 12 + 4 + 8
// 2352-2304, so + 48
static const uint8_t m_CDXA_STEREO = 3;
struct PsxVideoFrameHeader
{
unsigned short int mNumMdecCodes;
unsigned short int m3800Magic;
unsigned short int mQuantizationLevel;
unsigned short int mVersion;
};
struct MasherVideoHeaderWrapper
{
unsigned int mSectorType; // AKIK
unsigned int mSectorNumber;
// The 4 "unknown" / 0x80010160 in psx data is replaced by "AKIK" in PC data
unsigned int mAkikMagic;
unsigned short int mSectorNumberInFrame;
unsigned short int mNumSectorsInFrame;
unsigned int mFrameNum;
unsigned int mFrameDataLen;
unsigned short int mWidth;
unsigned short int mHeight;
PsxVideoFrameHeader mVideoFrameHeader;
unsigned int mNulls;
unsigned char frame[2016 + 240 + 4 + 4 + 4 + 2 + 2 + 4 + 4 + 2 + 2 + 2 + 2 + 2 + 2 + 4];
// PsxVideoFrameHeader mVideoFrameHeader2;
/*
0000 char {4} "AKIK"
// This is standard STR format data here
0004 uint16 {2} Sector number within frame (zero-based)
0006 uint16 {2} Number of sectors in frame
0008 uint32 {4} Frame number within file (one-based)
000C uint32 {4} Frame data length
0010 uint16 {2} Video Width
0012 uint16 {2} Video Height
0014 uint16 {2} Number of MDEC codes divided by two, and rounded up to a multiple of 32
0016 uint16 {2} Always 0x3800
0018 uint16 {2} Quantization level of the video frame
001A uint16 {2} Version of the video frame (always 2)
001C uint32 {4} Always 0x00000000
*/
//demultiplexing is joining all of the frame data into one buffer without the headers
};
std::vector<Uint32> pixels;
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
std::vector<unsigned char> ReadFrame(FILE* fp, bool& end, PSXMDECDecoder& mdec, PSXADPCMDecoder& adpcm, bool firstFrame, int& frameW, int& frameH)
{
std::vector<unsigned char> r(32768);
std::vector<unsigned char> outPtr(32678);
unsigned int numSectorsToRead = 0;
unsigned int sectorNumber = 0;
const int kDataSize = 2016;
;
for (;;)
{
MasherVideoHeaderWrapper w;
if (fread(&w, 1, sizeof(w), fp) != sizeof(w))
{
end = true;
return r;
}
if (w.mSectorType != 0x52494f4d)
{
// There is probably no way this is correct
CDXASector* xa = (CDXASector*)&w;
/*
std::cout <<
(CHECK_BIT(xa->subheader.coding_info, 0) ? "Mono " : "Stereo ") <<
(CHECK_BIT(xa->subheader.coding_info, 2) ? "37800Hz " : "18900Hz ") <<
(CHECK_BIT(xa->subheader.coding_info, 4) ? "4bit " : "8bit ")
*/
// << std::endl;
// if (xa->subheader.coding_info & 0xA)
{
auto numBytes = adpcm.DecodeFrameToPCM((int8_t *)outPtr.data(), &xa->data[0], true);
//if (CHECK_BIT(xa->subheader.coding_info, 2) && (CHECK_BIT(xa->subheader.coding_info, 0)))
{
AudioBuffer::mPlayedSamples = 0;
AudioBuffer::SendSamples((char*)outPtr.data(), numBytes);
// 8064
while (AudioBuffer::mPlayedSamples < numBytes/4)
{
}
}
//else
{
// std::vector<unsigned char> silence;
// silence.resize(numBytes);
// AudioBuffer::SendSamples((char*)silence.data(), numBytes);
}
}
// Must be VALE
continue;
}
else
{
frameW = w.mWidth;
frameH = w.mHeight;
//std::cout << "sector: " << w.mSectorNumber << std::endl;
//std::cout << "data len: " << w.mFrameDataLen << std::endl;
//std::cout << "frame number: " << w.mFrameNum << std::endl;
//std::cout << "num sectors in frame: " << w.mNumSectorsInFrame << std::endl;
//std::cout << "frame sector number: " << w.mSectorNumberInFrame << std::endl;
// SetSurfaceSize(w.mWidth, w.mHeight);
uint32_t bytes_to_copy = w.mFrameDataLen - w.mSectorNumberInFrame *kDataSize;
if (bytes_to_copy > 0)
{
if (bytes_to_copy > kDataSize)
{
bytes_to_copy = kDataSize;
}
memcpy(r.data() + w.mSectorNumberInFrame * kDataSize, w.frame, bytes_to_copy);
}
if (w.mSectorNumberInFrame == w.mNumSectorsInFrame - 1)
{
break;
}
}
}
if (pixels.empty())
{
pixels.resize(frameW * frameH);
}
mdec.DecodeFrameToABGR32((uint16_t*)pixels.data(), (uint16_t*)r.data(), frameW, frameH, false);
return r;
}
void Fmv::RenderVideoUi()
{
if (!video && !mFp)
{
if (mFmvUis.empty())
{
auto fmvs = mGameData.Fmvs();
for (auto fmvSet : fmvs)
{
mFmvUis.emplace_back(std::make_unique<FmvUi>());
}
}
if (!mFmvUis.empty())
{
int i = 0;
auto fmvs = mGameData.Fmvs();
for (auto fmvSet : fmvs)
{
mFmvUis[i]->DrawVideoSelectionUi(video, mFp, videoFrame, fmvSet.first, fmvSet.second);
i++;
}
}
}
else
{
if (mFp)
{
bool firstFrame = true;
bool end = false;
std::vector<unsigned char> frameData = ReadFrame(mFp, end, mMdec, mAdpcm, firstFrame, frameW, frameH);
firstFrame = false;
if (end)
{
fclose(mFp);
mFp = nullptr;
}
}
else if (video)
{
std::vector<Uint16> decodedFrame(video->SingleAudioFrameSizeBytes() * 2); // *2 if stereo
if (!video->Update((Uint32*)videoFrame->pixels, (Uint8*)decodedFrame.data()))
{
SDL_ShowCursor(1);
video = nullptr;
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
//targetFps = 60;
}
else
{
AudioBuffer::SendSamples((char*)decodedFrame.data(), decodedFrame.size() * 2);
while (AudioBuffer::mPlayedSamples < video->FrameNumber() * video->SingleAudioFrameSizeBytes())
{
}
}
}
}
}
Fmv::Fmv(GameData& gameData)
: mGameData(gameData)
{
}
Fmv::~Fmv()
{
}
void Fmv::Play()
{
}
void Fmv::Stop()
{
SDL_ShowCursor(1);
video = nullptr;
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
if (mFp)
{
fclose(mFp);
mFp = nullptr;
}
}
void Fmv::Update()
{
}
void Fmv::Render()
{
glEnable(GL_TEXTURE_2D);
RenderVideoUi();
if (videoFrame || mFp)
{
// TODO: Optimize - should use VBO's & update 1 texture rather than creating per frame
GLuint TextureID = 0;
glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_2D, TextureID);
int Mode = GL_RGB;
/*
if (videoFrame->format->BytesPerPixel == 4)
{
Mode = GL_RGBA;
}
*/
if (videoFrame)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, videoFrame->w, videoFrame->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, videoFrame->pixels);
}
else if (mFp)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frameW, frameH, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// For Ortho mode, of course
int X = -1;
int Y = -1;
int Width = 2;
int Height = 2;
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(X, Y, 0);
glTexCoord2f(1, 0); glVertex3f(X + Width, Y, 0);
glTexCoord2f(1, -1); glVertex3f(X + Width, Y + Height, 0);
glTexCoord2f(0, -1); glVertex3f(X, Y + Height, 0);
glEnd();
glDeleteTextures(1, &TextureID);
}
}
<commit_msg>fix crash on fmv size change<commit_after>#include "fmv.hpp"
#include "imgui/imgui.h"
#include "core/audiobuffer.hpp"
#include "gamedata.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif/*__APPLE__*/
std::vector<Uint32> pixels;
class FmvUi
{
private:
char buf[4096];
ImGuiTextFilter mFilter;
int listbox_item_current = 1;
std::vector<const char*> listbox_items;
public:
FmvUi()
{
#ifdef _WIN32
strcpy(buf, "C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Oddworld Abes Oddysee\\");
#else
strcpy(buf, "/media/paul/FF7DISC3/Program Files (x86)/Steam/SteamApps/common/Oddworld Abes Oddysee/");
#endif
}
void DrawVideoSelectionUi(std::unique_ptr<Oddlib::Masher>& video, FILE*& fp, SDL_Surface*& videoFrame, const std::string& setName, const std::vector<std::string>& allFmvs)
{
std::string name = "Video player (" + setName + ")";
ImGui::Begin(name.c_str(), nullptr, ImVec2(550, 580), 1.0f, ImGuiWindowFlags_NoCollapse);
ImGui::InputText("Video path", buf, sizeof(buf));
mFilter.Draw();
listbox_items.resize(allFmvs.size());
int matchingFilter = 0;
for (size_t i = 0; i < allFmvs.size(); i++)
{
if (mFilter.PassFilter(allFmvs[i].c_str()))
{
listbox_items[matchingFilter] = allFmvs[i].c_str();
matchingFilter++;
}
}
ImGui::PushItemWidth(-1);
ImGui::ListBox("##", &listbox_item_current, listbox_items.data(), matchingFilter, 27);
if (ImGui::Button("Play", ImVec2(ImGui::GetWindowWidth(), 20)))
{
pixels.clear(); // In case next FMV has a diff resolution
std::string fullPath = std::string(buf) + listbox_items[listbox_item_current];
std::cout << "Play " << listbox_items[listbox_item_current] << std::endl;
try
{
video = std::make_unique<Oddlib::Masher>(fullPath);
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
if (video->HasAudio())
{
AudioBuffer::ChangeAudioSpec(video->SingleAudioFrameSizeBytes(), video->AudioSampleRate());
}
if (video->HasVideo())
{
videoFrame = SDL_CreateRGBSurface(0, video->Width(), video->Height(), 32, 0, 0, 0, 0);
// targetFps = video->FrameRate() * 2;
}
SDL_ShowCursor(0);
}
catch (const Oddlib::Exception& ex)
{
// ImGui::Text(ex.what());
fp = fopen(fullPath.c_str(), "rb");
AudioBuffer::ChangeAudioSpec(8064/4, 37800);
}
}
ImGui::End();
}
};
struct CDXASector
{
/*
uint8_t sync[12];
uint8_t header[4];
struct CDXASubHeader
{
uint8_t file_number;
uint8_t channel;
uint8_t submode;
uint8_t coding_info;
uint8_t file_number_copy;
uint8_t channel_number_copy;
uint8_t submode_copy;
uint8_t coding_info_copy;
} subheader;
uint8_t data[2328];
*/
uint8_t data[2328 + 12 + 4 + 8];
};
// expected 2352
// 2328 + 12 + 4 + 8
// 2352-2304, so + 48
static const uint8_t m_CDXA_STEREO = 3;
struct PsxVideoFrameHeader
{
unsigned short int mNumMdecCodes;
unsigned short int m3800Magic;
unsigned short int mQuantizationLevel;
unsigned short int mVersion;
};
struct MasherVideoHeaderWrapper
{
unsigned int mSectorType; // AKIK
unsigned int mSectorNumber;
// The 4 "unknown" / 0x80010160 in psx data is replaced by "AKIK" in PC data
unsigned int mAkikMagic;
unsigned short int mSectorNumberInFrame;
unsigned short int mNumSectorsInFrame;
unsigned int mFrameNum;
unsigned int mFrameDataLen;
unsigned short int mWidth;
unsigned short int mHeight;
PsxVideoFrameHeader mVideoFrameHeader;
unsigned int mNulls;
unsigned char frame[2016 + 240 + 4 + 4 + 4 + 2 + 2 + 4 + 4 + 2 + 2 + 2 + 2 + 2 + 2 + 4];
// PsxVideoFrameHeader mVideoFrameHeader2;
/*
0000 char {4} "AKIK"
// This is standard STR format data here
0004 uint16 {2} Sector number within frame (zero-based)
0006 uint16 {2} Number of sectors in frame
0008 uint32 {4} Frame number within file (one-based)
000C uint32 {4} Frame data length
0010 uint16 {2} Video Width
0012 uint16 {2} Video Height
0014 uint16 {2} Number of MDEC codes divided by two, and rounded up to a multiple of 32
0016 uint16 {2} Always 0x3800
0018 uint16 {2} Quantization level of the video frame
001A uint16 {2} Version of the video frame (always 2)
001C uint32 {4} Always 0x00000000
*/
//demultiplexing is joining all of the frame data into one buffer without the headers
};
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
std::vector<unsigned char> ReadFrame(FILE* fp, bool& end, PSXMDECDecoder& mdec, PSXADPCMDecoder& adpcm, bool firstFrame, int& frameW, int& frameH)
{
std::vector<unsigned char> r(32768);
std::vector<unsigned char> outPtr(32678);
unsigned int numSectorsToRead = 0;
unsigned int sectorNumber = 0;
const int kDataSize = 2016;
;
for (;;)
{
MasherVideoHeaderWrapper w;
if (fread(&w, 1, sizeof(w), fp) != sizeof(w))
{
end = true;
return r;
}
if (w.mSectorType != 0x52494f4d)
{
// There is probably no way this is correct
CDXASector* xa = (CDXASector*)&w;
/*
std::cout <<
(CHECK_BIT(xa->subheader.coding_info, 0) ? "Mono " : "Stereo ") <<
(CHECK_BIT(xa->subheader.coding_info, 2) ? "37800Hz " : "18900Hz ") <<
(CHECK_BIT(xa->subheader.coding_info, 4) ? "4bit " : "8bit ")
*/
// << std::endl;
// if (xa->subheader.coding_info & 0xA)
{
auto numBytes = adpcm.DecodeFrameToPCM((int8_t *)outPtr.data(), &xa->data[0], true);
//if (CHECK_BIT(xa->subheader.coding_info, 2) && (CHECK_BIT(xa->subheader.coding_info, 0)))
{
AudioBuffer::mPlayedSamples = 0;
AudioBuffer::SendSamples((char*)outPtr.data(), numBytes);
// 8064
while (AudioBuffer::mPlayedSamples < numBytes/4)
{
}
}
//else
{
// std::vector<unsigned char> silence;
// silence.resize(numBytes);
// AudioBuffer::SendSamples((char*)silence.data(), numBytes);
}
}
// Must be VALE
continue;
}
else
{
frameW = w.mWidth;
frameH = w.mHeight;
//std::cout << "sector: " << w.mSectorNumber << std::endl;
//std::cout << "data len: " << w.mFrameDataLen << std::endl;
//std::cout << "frame number: " << w.mFrameNum << std::endl;
//std::cout << "num sectors in frame: " << w.mNumSectorsInFrame << std::endl;
//std::cout << "frame sector number: " << w.mSectorNumberInFrame << std::endl;
// SetSurfaceSize(w.mWidth, w.mHeight);
uint32_t bytes_to_copy = w.mFrameDataLen - w.mSectorNumberInFrame *kDataSize;
if (bytes_to_copy > 0)
{
if (bytes_to_copy > kDataSize)
{
bytes_to_copy = kDataSize;
}
memcpy(r.data() + w.mSectorNumberInFrame * kDataSize, w.frame, bytes_to_copy);
}
if (w.mSectorNumberInFrame == w.mNumSectorsInFrame - 1)
{
break;
}
}
}
if (pixels.empty())
{
pixels.resize(frameW * frameH);
}
mdec.DecodeFrameToABGR32((uint16_t*)pixels.data(), (uint16_t*)r.data(), frameW, frameH, false);
return r;
}
void Fmv::RenderVideoUi()
{
if (!video && !mFp)
{
if (mFmvUis.empty())
{
auto fmvs = mGameData.Fmvs();
for (auto fmvSet : fmvs)
{
mFmvUis.emplace_back(std::make_unique<FmvUi>());
}
}
if (!mFmvUis.empty())
{
int i = 0;
auto fmvs = mGameData.Fmvs();
for (auto fmvSet : fmvs)
{
mFmvUis[i]->DrawVideoSelectionUi(video, mFp, videoFrame, fmvSet.first, fmvSet.second);
i++;
}
}
}
else
{
if (mFp)
{
bool firstFrame = true;
bool end = false;
std::vector<unsigned char> frameData = ReadFrame(mFp, end, mMdec, mAdpcm, firstFrame, frameW, frameH);
firstFrame = false;
if (end)
{
fclose(mFp);
mFp = nullptr;
}
}
else if (video)
{
std::vector<Uint16> decodedFrame(video->SingleAudioFrameSizeBytes() * 2); // *2 if stereo
if (!video->Update((Uint32*)videoFrame->pixels, (Uint8*)decodedFrame.data()))
{
SDL_ShowCursor(1);
video = nullptr;
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
//targetFps = 60;
}
else
{
AudioBuffer::SendSamples((char*)decodedFrame.data(), decodedFrame.size() * 2);
while (AudioBuffer::mPlayedSamples < video->FrameNumber() * video->SingleAudioFrameSizeBytes())
{
}
}
}
}
}
Fmv::Fmv(GameData& gameData)
: mGameData(gameData)
{
}
Fmv::~Fmv()
{
}
void Fmv::Play()
{
}
void Fmv::Stop()
{
SDL_ShowCursor(1);
video = nullptr;
if (videoFrame)
{
SDL_FreeSurface(videoFrame);
videoFrame = nullptr;
}
if (mFp)
{
fclose(mFp);
mFp = nullptr;
}
}
void Fmv::Update()
{
}
void Fmv::Render()
{
glEnable(GL_TEXTURE_2D);
RenderVideoUi();
if (videoFrame || mFp)
{
// TODO: Optimize - should use VBO's & update 1 texture rather than creating per frame
GLuint TextureID = 0;
glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_2D, TextureID);
int Mode = GL_RGB;
/*
if (videoFrame->format->BytesPerPixel == 4)
{
Mode = GL_RGBA;
}
*/
if (videoFrame)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, videoFrame->w, videoFrame->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, videoFrame->pixels);
}
else if (mFp)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frameW, frameH, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// For Ortho mode, of course
int X = -1;
int Y = -1;
int Width = 2;
int Height = 2;
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(X, Y, 0);
glTexCoord2f(1, 0); glVertex3f(X + Width, Y, 0);
glTexCoord2f(1, -1); glVertex3f(X + Width, Y + Height, 0);
glTexCoord2f(0, -1); glVertex3f(X, Y + Height, 0);
glEnd();
glDeleteTextures(1, &TextureID);
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "AnalyzeCallDepth.h"
AnalyzeCallDepth::FunctionNode::FunctionNode(TIntermAggregate *node) : node(node)
{
visit = PreVisit;
callDepth = 0;
}
const TString &AnalyzeCallDepth::FunctionNode::getName() const
{
return node->getName();
}
void AnalyzeCallDepth::FunctionNode::addCallee(AnalyzeCallDepth::FunctionNode *callee)
{
for(size_t i = 0; i < callees.size(); i++)
{
if(callees[i] == callee)
{
return;
}
}
callees.push_back(callee);
}
unsigned int AnalyzeCallDepth::FunctionNode::analyzeCallDepth(AnalyzeCallDepth *analyzeCallDepth)
{
ASSERT(visit == PreVisit);
ASSERT(analyzeCallDepth);
callDepth = 0;
visit = InVisit;
for(size_t i = 0; i < callees.size(); i++)
{
switch(callees[i]->visit)
{
case InVisit:
// Cycle detected (recursion)
return UINT_MAX;
case PostVisit:
callDepth = std::max(callDepth, 1 + callees[i]->getLastDepth());
break;
case PreVisit:
callDepth = std::max(callDepth, 1 + callees[i]->analyzeCallDepth(analyzeCallDepth));
break;
default:
UNREACHABLE(callees[i]->visit);
break;
}
}
visit = PostVisit;
return callDepth;
}
unsigned int AnalyzeCallDepth::FunctionNode::getLastDepth() const
{
return callDepth;
}
void AnalyzeCallDepth::FunctionNode::removeIfUnreachable()
{
if(visit == PreVisit)
{
node->setOp(EOpPrototype);
node->getSequence().resize(1); // Remove function body
}
}
AnalyzeCallDepth::AnalyzeCallDepth(TIntermNode *root)
: TIntermTraverser(true, false, true, false),
currentFunction(0)
{
root->traverse(this);
}
AnalyzeCallDepth::~AnalyzeCallDepth()
{
for(size_t i = 0; i < functions.size(); i++)
{
delete functions[i];
}
}
bool AnalyzeCallDepth::visitAggregate(Visit visit, TIntermAggregate *node)
{
switch(node->getOp())
{
case EOpFunction: // Function definition
{
if(visit == PreVisit)
{
currentFunction = findFunctionByName(node->getName());
if(!currentFunction)
{
currentFunction = new FunctionNode(node);
functions.push_back(currentFunction);
}
}
else if(visit == PostVisit)
{
currentFunction = 0;
}
}
break;
case EOpFunctionCall:
{
if(!node->isUserDefined())
{
return true; // Check the arguments for function calls
}
if(visit == PreVisit)
{
FunctionNode *function = findFunctionByName(node->getName());
if(!function)
{
function = new FunctionNode(node);
functions.push_back(function);
}
if(currentFunction)
{
currentFunction->addCallee(function);
}
else
{
globalFunctionCalls.insert(function);
}
}
}
break;
default:
break;
}
return true;
}
unsigned int AnalyzeCallDepth::analyzeCallDepth()
{
FunctionNode *main = findFunctionByName("main(");
if(!main)
{
return 0;
}
unsigned int depth = 1 + main->analyzeCallDepth(this);
for(FunctionSet::iterator globalCall = globalFunctionCalls.begin(); globalCall != globalFunctionCalls.end(); globalCall++)
{
unsigned int globalDepth = 1 + (*globalCall)->analyzeCallDepth(this);
if(globalDepth > depth)
{
depth = globalDepth;
}
}
for(size_t i = 0; i < functions.size(); i++)
{
functions[i]->removeIfUnreachable();
}
return depth;
}
AnalyzeCallDepth::FunctionNode *AnalyzeCallDepth::findFunctionByName(const TString &name)
{
for(size_t i = 0; i < functions.size(); i++)
{
if(functions[i]->getName() == name)
{
return functions[i];
}
}
return 0;
}
<commit_msg>Fixed recursion analysis<commit_after>//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "AnalyzeCallDepth.h"
AnalyzeCallDepth::FunctionNode::FunctionNode(TIntermAggregate *node) : node(node)
{
visit = PreVisit;
callDepth = 0;
}
const TString &AnalyzeCallDepth::FunctionNode::getName() const
{
return node->getName();
}
void AnalyzeCallDepth::FunctionNode::addCallee(AnalyzeCallDepth::FunctionNode *callee)
{
for(size_t i = 0; i < callees.size(); i++)
{
if(callees[i] == callee)
{
return;
}
}
callees.push_back(callee);
}
unsigned int AnalyzeCallDepth::FunctionNode::analyzeCallDepth(AnalyzeCallDepth *analyzeCallDepth)
{
ASSERT(visit == PreVisit);
ASSERT(analyzeCallDepth);
callDepth = 0;
visit = InVisit;
for(size_t i = 0; i < callees.size(); i++)
{
unsigned int calleeDepth = 0;
switch(callees[i]->visit)
{
case InVisit:
// Cycle detected (recursion)
return UINT_MAX;
case PostVisit:
calleeDepth = callees[i]->getLastDepth();
break;
case PreVisit:
calleeDepth = callees[i]->analyzeCallDepth(analyzeCallDepth);
break;
default:
UNREACHABLE(callees[i]->visit);
break;
}
if(calleeDepth != UINT_MAX) ++calleeDepth;
callDepth = std::max(callDepth, calleeDepth);
}
visit = PostVisit;
return callDepth;
}
unsigned int AnalyzeCallDepth::FunctionNode::getLastDepth() const
{
return callDepth;
}
void AnalyzeCallDepth::FunctionNode::removeIfUnreachable()
{
if(visit == PreVisit)
{
node->setOp(EOpPrototype);
node->getSequence().resize(1); // Remove function body
}
}
AnalyzeCallDepth::AnalyzeCallDepth(TIntermNode *root)
: TIntermTraverser(true, false, true, false),
currentFunction(0)
{
root->traverse(this);
}
AnalyzeCallDepth::~AnalyzeCallDepth()
{
for(size_t i = 0; i < functions.size(); i++)
{
delete functions[i];
}
}
bool AnalyzeCallDepth::visitAggregate(Visit visit, TIntermAggregate *node)
{
switch(node->getOp())
{
case EOpFunction: // Function definition
{
if(visit == PreVisit)
{
currentFunction = findFunctionByName(node->getName());
if(!currentFunction)
{
currentFunction = new FunctionNode(node);
functions.push_back(currentFunction);
}
}
else if(visit == PostVisit)
{
currentFunction = 0;
}
}
break;
case EOpFunctionCall:
{
if(!node->isUserDefined())
{
return true; // Check the arguments for function calls
}
if(visit == PreVisit)
{
FunctionNode *function = findFunctionByName(node->getName());
if(!function)
{
function = new FunctionNode(node);
functions.push_back(function);
}
if(currentFunction)
{
currentFunction->addCallee(function);
}
else
{
globalFunctionCalls.insert(function);
}
}
}
break;
default:
break;
}
return true;
}
unsigned int AnalyzeCallDepth::analyzeCallDepth()
{
FunctionNode *main = findFunctionByName("main(");
if(!main)
{
return 0;
}
unsigned int depth = main->analyzeCallDepth(this);
if(depth != UINT_MAX) ++depth;
for(FunctionSet::iterator globalCall = globalFunctionCalls.begin(); globalCall != globalFunctionCalls.end(); globalCall++)
{
unsigned int globalDepth = (*globalCall)->analyzeCallDepth(this);
if(globalDepth != UINT_MAX) ++globalDepth;
if(globalDepth > depth)
{
depth = globalDepth;
}
}
for(size_t i = 0; i < functions.size(); i++)
{
functions[i]->removeIfUnreachable();
}
return depth;
}
AnalyzeCallDepth::FunctionNode *AnalyzeCallDepth::findFunctionByName(const TString &name)
{
for(size_t i = 0; i < functions.size(); i++)
{
if(functions[i]->getName() == name)
{
return functions[i];
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
*Copyright (c) 2013-2013, yinqiwen <[email protected]>
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* * 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 Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
*THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "db.hpp"
#include "ardb_server.hpp"
#include "geo/geohash_helper.hpp"
#include <algorithm>
namespace ardb
{
/*
* GEOADD key MERCATOR|WGS84 x y value [attr_name attr_value ...]
*/
int ArdbServer::GeoAdd(ArdbConnContext& ctx, RedisCommandFrame& cmd)
{
GeoAddOptions options;
std::string err;
if (0 != options.Parse(cmd.GetArguments(), err, 1))
{
fill_error_reply(ctx.reply, "%s", err.c_str());
return 0;
}
int ret = m_db->GeoAdd(ctx.currentDB, cmd.GetArguments()[0], options);
if (ret >= 0)
{
fill_status_reply(ctx.reply, "OK");
}
else
{
fill_error_reply(ctx.reply, "Failed to %s", cmd.ToString().c_str());
}
return 0;
}
/*
* GEOSEARCH key MERCATOR|WGS84 x y <GeoOptions>
* GEOSEARCH key MEMBER m
*
* <GeoOptions> = IN N m0 m1 m2 RADIUS r
* [ASC|DESC] [WITHCOORDINATES] [WITHDISTANCES]
* [GET pattern [GET pattern ...]]
* [INCLUDE key_pattern value_pattern [INCLUDE key_pattern value_pattern ...]]
* [EXCLUDE key_pattern value_pattern [EXCLUDE key_pattern value_pattern ...]]
* [LIMIT offset count]
*
* For 'GET pattern' in GEOSEARCH:
* If 'pattern' is '#.<attr>', return actual point's attribute stored by 'GeoAdd'
* Other pattern would processed the same as 'sort' command (Use same C++ function),
* The patterns like '#', "*->field" are valid.
*/
int ArdbServer::GeoSearch(ArdbConnContext& ctx, RedisCommandFrame& cmd)
{
GeoSearchOptions options;
std::string err;
if (0 != options.Parse(cmd.GetArguments(), err, 1))
{
fill_error_reply(ctx.reply, "%s", err.c_str());
return 0;
}
ValueDataDeque res;
m_db->GeoSearch(ctx.currentDB, cmd.GetArguments()[0], options, res);
fill_array_reply(ctx.reply, res);
return 0;
}
int Ardb::GeoAdd(const DBID& db, const Slice& key, const GeoAddOptions& options)
{
GeoHashRange lat_range, lon_range;
GeoHashHelper::GetCoordRange(options.coord_type, lat_range, lon_range);
if (options.x < lon_range.min || options.x > lon_range.max || options.y < lat_range.min
|| options.y > lat_range.max)
{
return ERR_INVALID_ARGS;
}
GeoPoint point;
point.x = options.x;
point.y = options.y;
if (options.coord_type == GEO_WGS84_TYPE)
{
point.x = GeoHashHelper::GetMercatorX(options.x);
point.y = GeoHashHelper::GetMercatorY(options.y);
GeoHashHelper::GetCoordRange(GEO_MERCATOR_TYPE, lat_range, lon_range);
}
point.attrs = options.attrs;
GeoHashBits hash;
geohash_encode(&lat_range, &lon_range, point.y, point.x, 26, &hash);
GeoHashFix52Bits score = hash.bits;
ValueData score_value;
score_value.SetIntValue((int64) score);
Buffer content;
point.Encode(content);
Slice content_value(content.GetRawReadBuffer(), content.ReadableBytes());
return ZAdd(db, key, score_value, options.value, content_value);
}
static bool less_by_distance(const GeoPoint& v1, const GeoPoint& v2)
{
return v1.distance < v2.distance;
}
static bool great_by_distance(const GeoPoint& v1, const GeoPoint& v2)
{
return v1.distance > v2.distance;
}
static int ZSetValueStoreCallback(const ValueData& value, int cursor, void* cb)
{
ValueDataArray* s = (ValueDataArray*) cb;
s->push_back(value);
return 0;
}
int Ardb::GeoSearch(const DBID& db, const Slice& key, const GeoSearchOptions& options, ValueDataDeque& results)
{
uint64 start_time = get_current_epoch_micros();
GeoHashBitsSet ress;
double x = options.x, y = options.y;
if (options.coord_type == GEO_WGS84_TYPE)
{
x = GeoHashHelper::GetMercatorX(options.x);
y = GeoHashHelper::GetMercatorY(options.y);
}
if (options.by_member)
{
ValueData score, attr;
int err = ZGetNodeValue(db, key, options.member, score, attr);
if (0 != err)
{
return err;
}
Buffer attr_content(const_cast<char*>(attr.bytes_value.data()), 0, attr.bytes_value.size());
GeoPoint point;
point.Decode(attr_content);
x = point.x;
y = point.y;
}
ZSetCacheElementSet subset;
if (options.in_members)
{
StringSet::const_iterator sit = options.submembers.begin();
while (sit != options.submembers.end())
{
ZSetCaheElement ele;
ele.value = *sit;
ValueData score, attr;
if (0 == ZGetNodeValue(db, key, ele.value, score, attr))
{
ele.score = score.NumberValue();
Buffer buf2;
attr.Encode(buf2);
ele.attr.assign(buf2.GetRawReadBuffer(), buf2.ReadableBytes());
subset.insert(ele);
}
sit++;
}
}
GeoHashHelper::GetAreasByRadius(GEO_MERCATOR_TYPE, y, x, options.radius, ress);
/*
* Merge areas if possible to avoid disk search
*/
std::vector<ZRangeSpec> range_array;
GeoHashBitsSet::iterator rit = ress.begin();
GeoHashBitsSet::iterator next_it = ress.begin();
next_it++;
while (rit != ress.end())
{
GeoHashBits& hash = *rit;
GeoHashBits next = hash;
next.bits++;
while (next_it != ress.end() && next.bits == next_it->bits)
{
next.bits++;
next_it++;
rit++;
}
ZRangeSpec range;
range.contain_min = true;
range.contain_max = false;
range.min.SetIntValue(GeoHashHelper::Allign52Bits(hash));
range.max.SetIntValue(GeoHashHelper::Allign52Bits(next));
range_array.push_back(range);
rit++;
next_it++;
}
DEBUG_LOG("After areas merging, reduce searching area size from %u to %u", ress.size(), range_array.size());
GeoPointArray points;
std::vector<ZRangeSpec>::iterator hit = range_array.begin();
Iterator* iter = NULL;
while (hit != range_array.end())
{
ZSetQueryOptions z_options;
z_options.withscores = false;
z_options.withattr = true;
ValueDataArray values;
if (options.in_members)
{
ZSetCache::GetRangeInZSetCache(subset, *hit, z_options.withscores, z_options.withattr,
ZSetValueStoreCallback, &values);
}
else
{
ZRangeByScoreRange(db, key, *hit, iter, z_options, true, ZSetValueStoreCallback, &values);
}
ValueDataArray::iterator vit = values.begin();
while (vit != values.end())
{
GeoPoint point;
vit->ToString(point.value);
//attributes
vit++;
Buffer content(const_cast<char*>(vit->bytes_value.data()), 0, vit->bytes_value.size());
if (point.Decode(content))
{
if (GeoHashHelper::GetDistanceSquareIfInRadius(GEO_MERCATOR_TYPE, x, y, point.x, point.y,
options.radius, point.distance))
{
/*
* filter by exclude/include
*/
if (!options.includes.empty() || !options.excludes.empty())
{
ValueData subst;
subst.SetValue(point.value, false);
bool matched = options.includes.empty() ? true : false;
if (!options.includes.empty())
{
StringStringMap::const_iterator sit = options.includes.begin();
while (sit != options.includes.end())
{
ValueData mv;
if (0 != MatchValueByPattern(db, sit->first, sit->second, subst, mv))
{
matched = false;
break;
}
else
{
matched = true;
}
sit++;
}
}
if (matched && !options.excludes.empty())
{
StringStringMap::const_iterator sit = options.excludes.begin();
while (sit != options.excludes.end())
{
ValueData mv;
if (0 == MatchValueByPattern(db, sit->first, sit->second, subst, mv))
{
matched = false;
break;
}
else
{
matched = true;
}
sit++;
}
}
if (matched)
{
points.push_back(point);
}
}
else
{
points.push_back(point);
}
}
else
{
//DEBUG_LOG("%s is not in radius:%.2fm", point.value.c_str(), options.radius);
}
}
else
{
WARN_LOG("Failed to decode geo point.");
}
vit++;
}
hit++;
}
DELETE(iter);
if (!options.nosort)
{
std::sort(points.begin(), points.end(), options.asc ? less_by_distance : great_by_distance);
}
if (options.offset > 0)
{
if ((uint32) options.offset > points.size())
{
points.clear();
}
else
{
GeoPointArray::iterator start = points.begin() + options.offset;
points.erase(points.begin(), start);
}
}
if (options.limit > 0)
{
if ((uint32) options.limit < points.size())
{
GeoPointArray::iterator end = points.begin() + options.limit;
points.erase(end, points.end());
}
}
GeoPointArray::iterator pit = points.begin();
while (pit != points.end())
{
ValueData v;
v.SetValue(pit->value, false);
results.push_back(v);
GeoGetOptionDeque::const_iterator ait = options.get_patterns.begin();
while (ait != options.get_patterns.end())
{
ValueData attr;
if (ait->get_distances)
{
attr.SetDoubleValue(sqrt(pit->distance));
results.push_back(attr);
}
else if (ait->get_coodinates)
{
if (options.coord_type == GEO_WGS84_TYPE)
{
pit->x = GeoHashHelper::GetWGS84X(pit->x);
pit->y = GeoHashHelper::GetWGS84Y(pit->y);
}
attr.SetDoubleValue(pit->x);
results.push_back(attr);
attr.SetDoubleValue(pit->y);
results.push_back(attr);
}
else if (ait->get_attr)
{
StringStringMap::iterator found = pit->attrs.find(ait->get_pattern);
if (found != pit->attrs.end())
{
attr.SetValue(found->second, false);
}
results.push_back(attr);
}
else
{
GetValueByPattern(db, ait->get_pattern, v, attr);
results.push_back(attr);
}
ait++;
}
pit++;
}
uint64 end_time = get_current_epoch_micros();
DEBUG_LOG("Cost %llu microseconds to search.", end_time - start_time);
return 0;
}
}
<commit_msg>fix for geosearch<commit_after>/*
*Copyright (c) 2013-2013, yinqiwen <[email protected]>
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* * 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 Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
*THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "db.hpp"
#include "ardb_server.hpp"
#include "geo/geohash_helper.hpp"
#include <algorithm>
namespace ardb
{
/*
* GEOADD key MERCATOR|WGS84 x y value [attr_name attr_value ...]
*/
int ArdbServer::GeoAdd(ArdbConnContext& ctx, RedisCommandFrame& cmd)
{
GeoAddOptions options;
std::string err;
if (0 != options.Parse(cmd.GetArguments(), err, 1))
{
fill_error_reply(ctx.reply, "%s", err.c_str());
return 0;
}
int ret = m_db->GeoAdd(ctx.currentDB, cmd.GetArguments()[0], options);
if (ret >= 0)
{
fill_status_reply(ctx.reply, "OK");
}
else
{
fill_error_reply(ctx.reply, "Failed to %s", cmd.ToString().c_str());
}
return 0;
}
/*
* GEOSEARCH key MERCATOR|WGS84 x y <GeoOptions>
* GEOSEARCH key MEMBER m
*
* <GeoOptions> = IN N m0 m1 m2 RADIUS r
* [ASC|DESC] [WITHCOORDINATES] [WITHDISTANCES]
* [GET pattern [GET pattern ...]]
* [INCLUDE key_pattern value_pattern [INCLUDE key_pattern value_pattern ...]]
* [EXCLUDE key_pattern value_pattern [EXCLUDE key_pattern value_pattern ...]]
* [LIMIT offset count]
*
* For 'GET pattern' in GEOSEARCH:
* If 'pattern' is '#.<attr>', return actual point's attribute stored by 'GeoAdd'
* Other pattern would processed the same as 'sort' command (Use same C++ function),
* The patterns like '#', "*->field" are valid.
*/
int ArdbServer::GeoSearch(ArdbConnContext& ctx, RedisCommandFrame& cmd)
{
GeoSearchOptions options;
std::string err;
if (0 != options.Parse(cmd.GetArguments(), err, 1))
{
fill_error_reply(ctx.reply, "%s", err.c_str());
return 0;
}
ValueDataDeque res;
m_db->GeoSearch(ctx.currentDB, cmd.GetArguments()[0], options, res);
fill_array_reply(ctx.reply, res);
return 0;
}
int Ardb::GeoAdd(const DBID& db, const Slice& key, const GeoAddOptions& options)
{
GeoHashRange lat_range, lon_range;
GeoHashHelper::GetCoordRange(options.coord_type, lat_range, lon_range);
if (options.x < lon_range.min || options.x > lon_range.max || options.y < lat_range.min
|| options.y > lat_range.max)
{
return ERR_INVALID_ARGS;
}
GeoPoint point;
point.x = options.x;
point.y = options.y;
if (options.coord_type == GEO_WGS84_TYPE)
{
point.x = GeoHashHelper::GetMercatorX(options.x);
point.y = GeoHashHelper::GetMercatorY(options.y);
GeoHashHelper::GetCoordRange(GEO_MERCATOR_TYPE, lat_range, lon_range);
}
point.attrs = options.attrs;
GeoHashBits hash;
geohash_encode(&lat_range, &lon_range, point.y, point.x, 26, &hash);
GeoHashFix52Bits score = hash.bits;
ValueData score_value;
score_value.SetIntValue((int64) score);
Buffer content;
point.Encode(content);
Slice content_value(content.GetRawReadBuffer(), content.ReadableBytes());
return ZAdd(db, key, score_value, options.value, content_value);
}
static bool less_by_distance(const GeoPoint& v1, const GeoPoint& v2)
{
return v1.distance < v2.distance;
}
static bool great_by_distance(const GeoPoint& v1, const GeoPoint& v2)
{
return v1.distance > v2.distance;
}
static int ZSetValueStoreCallback(const ValueData& value, int cursor, void* cb)
{
ValueDataArray* s = (ValueDataArray*) cb;
s->push_back(value);
return 0;
}
int Ardb::GeoSearch(const DBID& db, const Slice& key, const GeoSearchOptions& options, ValueDataDeque& results)
{
uint64 start_time = get_current_epoch_micros();
GeoHashBitsSet ress;
double x = options.x, y = options.y;
if (options.coord_type == GEO_WGS84_TYPE)
{
x = GeoHashHelper::GetMercatorX(options.x);
y = GeoHashHelper::GetMercatorY(options.y);
}
if (options.by_member)
{
ValueData score, attr;
int err = ZGetNodeValue(db, key, options.member, score, attr);
if (0 != err)
{
return err;
}
Buffer attr_content(const_cast<char*>(attr.bytes_value.data()), 0, attr.bytes_value.size());
GeoPoint point;
point.Decode(attr_content);
x = point.x;
y = point.y;
}
ZSetCacheElementSet subset;
if (options.in_members)
{
StringSet::const_iterator sit = options.submembers.begin();
while (sit != options.submembers.end())
{
ZSetCaheElement ele;
ValueData score, attr;
if (0 == ZGetNodeValue(db, key, *sit, score, attr))
{
ele.score = score.NumberValue();
Buffer buf1, buf2;
ValueData vv;
vv.SetValue(*sit, true);
vv.Encode(buf1);
attr.Encode(buf2);
ele.value.assign(buf1.GetRawReadBuffer(), buf1.ReadableBytes());
ele.attr.assign(buf2.GetRawReadBuffer(), buf2.ReadableBytes());
subset.insert(ele);
}
sit++;
}
}
GeoHashHelper::GetAreasByRadius(GEO_MERCATOR_TYPE, y, x, options.radius, ress);
/*
* Merge areas if possible to avoid disk search
*/
std::vector<ZRangeSpec> range_array;
GeoHashBitsSet::iterator rit = ress.begin();
GeoHashBitsSet::iterator next_it = ress.begin();
next_it++;
while (rit != ress.end())
{
GeoHashBits& hash = *rit;
GeoHashBits next = hash;
next.bits++;
while (next_it != ress.end() && next.bits == next_it->bits)
{
next.bits++;
next_it++;
rit++;
}
ZRangeSpec range;
range.contain_min = true;
range.contain_max = false;
range.min.SetIntValue(GeoHashHelper::Allign52Bits(hash));
range.max.SetIntValue(GeoHashHelper::Allign52Bits(next));
range_array.push_back(range);
rit++;
next_it++;
}
DEBUG_LOG("After areas merging, reduce searching area size from %u to %u", ress.size(), range_array.size());
GeoPointArray points;
std::vector<ZRangeSpec>::iterator hit = range_array.begin();
Iterator* iter = NULL;
while (hit != range_array.end())
{
ZSetQueryOptions z_options;
z_options.withscores = false;
z_options.withattr = true;
ValueDataArray values;
if (options.in_members)
{
ZSetCache::GetRangeInZSetCache(subset, *hit, z_options.withscores, z_options.withattr,
ZSetValueStoreCallback, &values);
}
else
{
ZRangeByScoreRange(db, key, *hit, iter, z_options, true, ZSetValueStoreCallback, &values);
}
ValueDataArray::iterator vit = values.begin();
while (vit != values.end())
{
GeoPoint point;
vit->ToString(point.value);
//attributes
vit++;
Buffer content(const_cast<char*>(vit->bytes_value.data()), 0, vit->bytes_value.size());
if (point.Decode(content))
{
if (GeoHashHelper::GetDistanceSquareIfInRadius(GEO_MERCATOR_TYPE, x, y, point.x, point.y,
options.radius, point.distance))
{
/*
* filter by exclude/include
*/
if (!options.includes.empty() || !options.excludes.empty())
{
ValueData subst;
subst.SetValue(point.value, false);
bool matched = options.includes.empty() ? true : false;
if (!options.includes.empty())
{
StringStringMap::const_iterator sit = options.includes.begin();
while (sit != options.includes.end())
{
ValueData mv;
if (0 != MatchValueByPattern(db, sit->first, sit->second, subst, mv))
{
matched = false;
break;
}
else
{
matched = true;
}
sit++;
}
}
if (matched && !options.excludes.empty())
{
StringStringMap::const_iterator sit = options.excludes.begin();
while (sit != options.excludes.end())
{
ValueData mv;
if (0 == MatchValueByPattern(db, sit->first, sit->second, subst, mv))
{
matched = false;
break;
}
else
{
matched = true;
}
sit++;
}
}
if (matched)
{
points.push_back(point);
}
}
else
{
points.push_back(point);
}
}
else
{
//DEBUG_LOG("%s is not in radius:%.2fm", point.value.c_str(), options.radius);
}
}
else
{
WARN_LOG("Failed to decode geo point.");
}
vit++;
}
hit++;
}
DELETE(iter);
if (!options.nosort)
{
std::sort(points.begin(), points.end(), options.asc ? less_by_distance : great_by_distance);
}
if (options.offset > 0)
{
if ((uint32) options.offset > points.size())
{
points.clear();
}
else
{
GeoPointArray::iterator start = points.begin() + options.offset;
points.erase(points.begin(), start);
}
}
if (options.limit > 0)
{
if ((uint32) options.limit < points.size())
{
GeoPointArray::iterator end = points.begin() + options.limit;
points.erase(end, points.end());
}
}
GeoPointArray::iterator pit = points.begin();
while (pit != points.end())
{
ValueData v;
v.SetValue(pit->value, false);
results.push_back(v);
GeoGetOptionDeque::const_iterator ait = options.get_patterns.begin();
while (ait != options.get_patterns.end())
{
ValueData attr;
if (ait->get_distances)
{
attr.SetDoubleValue(sqrt(pit->distance));
results.push_back(attr);
}
else if (ait->get_coodinates)
{
if (options.coord_type == GEO_WGS84_TYPE)
{
pit->x = GeoHashHelper::GetWGS84X(pit->x);
pit->y = GeoHashHelper::GetWGS84Y(pit->y);
}
attr.SetDoubleValue(pit->x);
results.push_back(attr);
attr.SetDoubleValue(pit->y);
results.push_back(attr);
}
else if (ait->get_attr)
{
StringStringMap::iterator found = pit->attrs.find(ait->get_pattern);
if (found != pit->attrs.end())
{
attr.SetValue(found->second, false);
}
results.push_back(attr);
}
else
{
GetValueByPattern(db, ait->get_pattern, v, attr);
results.push_back(attr);
}
ait++;
}
pit++;
}
uint64 end_time = get_current_epoch_micros();
DEBUG_LOG("Cost %llu microseconds to search.", end_time - start_time);
return 0;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/eula_view.h"
#include <signal.h>
#include <sys/types.h>
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/customization_document.h"
#include "chrome/browser/chromeos/login/network_screen_delegate.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/button/native_button.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/layout_manager.h"
#include "views/standard_layout.h"
namespace {
const int kBorderSize = 10;
const int kMargin = 20;
const int kLastButtonHorizontalMargin = 10;
const int kCheckBowWidth = 22;
const int kTextMargin = 10;
// TODO(glotov): this URL should be changed to actual Google ChromeOS EULA.
// See crbug.com/4647
const char kGoogleEulaUrl[] = "about:terms";
enum kLayoutColumnsets {
SINGLE_CONTROL_ROW,
SINGLE_CONTROL_WITH_SHIFT_ROW,
SINGLE_LINK_WITH_SHIFT_ROW,
LAST_ROW
};
// A simple LayoutManager that causes the associated view's one child to be
// sized to match the bounds of its parent except the bounds, if set.
struct FillLayoutWithBorder : public views::LayoutManager {
// Overridden from LayoutManager:
virtual void Layout(views::View* host) {
DCHECK(host->GetChildViewCount());
host->GetChildViewAt(0)->SetBounds(host->GetLocalBounds(false));
}
virtual gfx::Size GetPreferredSize(views::View* host) {
return gfx::Size(host->width(), host->height());
}
};
} // namespace
namespace chromeos {
EulaView::EulaView(chromeos::ScreenObserver* observer)
: google_eula_label_(NULL),
google_eula_view_(NULL),
usage_statistics_checkbox_(NULL),
learn_more_link_(NULL),
oem_eula_label_(NULL),
oem_eula_view_(NULL),
system_security_settings_link_(NULL),
cancel_button_(NULL),
continue_button_(NULL),
observer_(observer) {
}
EulaView::~EulaView() {
}
// Convenience function to set layout's columnsets for this screen.
static void SetUpGridLayout(views::GridLayout* layout) {
static const int kPadding = kBorderSize + kMargin;
views::ColumnSet* column_set = layout->AddColumnSet(SINGLE_CONTROL_ROW);
column_set->AddPaddingColumn(0, kPadding);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(SINGLE_CONTROL_WITH_SHIFT_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(SINGLE_LINK_WITH_SHIFT_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin + kCheckBowWidth);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(LAST_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kLastButtonHorizontalMargin + kBorderSize);
}
// Convenience function. Returns URL of the OEM EULA page that should be
// displayed using current locale and manifest. Returns empty URL otherwise.
static GURL GetOemEulaPagePath() {
const StartupCustomizationDocument *customization =
WizardController::default_controller()->GetCustomization();
if (customization) {
std::string locale = g_browser_process->GetApplicationLocale();
FilePath eula_page_path = customization->GetEULAPagePath(locale);
if (eula_page_path.empty()) {
LOG(INFO) << "No eula found for locale: " << locale;
locale = customization->initial_locale();
eula_page_path = customization->GetEULAPagePath(locale);
}
if (!eula_page_path.empty()) {
const std::string page_path = std::string(chrome::kFileScheme) +
chrome::kStandardSchemeSeparator + eula_page_path.value();
return GURL(page_path);
} else {
LOG(INFO) << "No eula found for locale: " << locale;
}
} else {
LOG(ERROR) << "No manifest found.";
}
return GURL();
}
void EulaView::Init() {
// Use rounded rect background.
views::Painter* painter = CreateWizardPainter(
&BorderDefinition::kScreenBorder);
set_background(
views::Background::CreateBackgroundPainter(true, painter));
// Layout created controls.
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
SetUpGridLayout(layout);
static const int kPadding = kBorderSize + kMargin;
layout->AddPaddingRow(0, kPadding);
layout->StartRow(0, SINGLE_CONTROL_ROW);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gfx::Font label_font =
rb.GetFont(ResourceBundle::MediumFont).DeriveFont(0, gfx::Font::NORMAL);
google_eula_label_ = new views::Label(std::wstring(), label_font);
layout->AddView(google_eula_label_, 1, 1,
views::GridLayout::LEADING, views::GridLayout::FILL);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, SINGLE_CONTROL_ROW);
views::View* box_view = new views::View();
box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));
box_view->SetLayoutManager(new FillLayoutWithBorder());
layout->AddView(box_view);
google_eula_view_ = new DOMView();
box_view->AddChildView(google_eula_view_);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, SINGLE_CONTROL_WITH_SHIFT_ROW);
usage_statistics_checkbox_ = new views::Checkbox();
usage_statistics_checkbox_->SetMultiLine(true);
usage_statistics_checkbox_->SetChecked(
GoogleUpdateSettings::GetCollectStatsConsent());
layout->AddView(usage_statistics_checkbox_);
layout->StartRow(0, SINGLE_LINK_WITH_SHIFT_ROW);
learn_more_link_ = new views::Link();
learn_more_link_->SetController(this);
layout->AddView(learn_more_link_);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, SINGLE_CONTROL_ROW);
oem_eula_label_ = new views::Label(std::wstring(), label_font);
layout->AddView(oem_eula_label_, 1, 1,
views::GridLayout::LEADING, views::GridLayout::FILL);
oem_eula_page_ = GetOemEulaPagePath();
if (!oem_eula_page_.is_empty()) {
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, SINGLE_CONTROL_ROW);
box_view = new views::View();
box_view->SetLayoutManager(new FillLayoutWithBorder());
box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));
layout->AddView(box_view);
oem_eula_view_ = new DOMView();
box_view->AddChildView(oem_eula_view_);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, LAST_ROW);
system_security_settings_link_ = new views::Link();
system_security_settings_link_->SetController(this);
layout->AddView(system_security_settings_link_);
cancel_button_ = new views::NativeButton(this, std::wstring());
cancel_button_->SetEnabled(false);
layout->AddView(cancel_button_);
continue_button_ = new views::NativeButton(this, std::wstring());
layout->AddView(continue_button_);
layout->AddPaddingRow(0, kPadding);
UpdateLocalizedStrings();
}
void EulaView::LoadEulaView(DOMView* eula_view,
views::Label* eula_label,
const GURL& eula_url) {
Profile* profile = ProfileManager::GetDefaultProfile();
eula_view->Init(profile,
SiteInstance::CreateSiteInstanceForURL(profile, eula_url));
eula_view->LoadURL(eula_url);
eula_view->tab_contents()->set_delegate(this);
}
void EulaView::UpdateLocalizedStrings() {
// Load Google EULA and its title.
LoadEulaView(google_eula_view_, google_eula_label_, GURL(kGoogleEulaUrl));
// Load OEM EULA and its title.
if (!oem_eula_page_.is_empty())
LoadEulaView(oem_eula_view_, oem_eula_label_, oem_eula_page_);
// Load other labels from resources.
usage_statistics_checkbox_->SetLabel(
l10n_util::GetString(IDS_EULA_CHECKBOX_ENABLE_LOGGING));
learn_more_link_->SetText(
l10n_util::GetString(IDS_LEARN_MORE));
system_security_settings_link_->SetText(
l10n_util::GetString(IDS_EULA_SYSTEM_SECURITY_SETTINGS_LINK));
continue_button_->SetLabel(
l10n_util::GetString(IDS_EULA_ACCEPT_AND_CONTINUE_BUTTON));
cancel_button_->SetLabel(
l10n_util::GetString(IDS_CANCEL));
}
////////////////////////////////////////////////////////////////////////////////
// views::View: implementation:
void EulaView::OnLocaleChanged() {
UpdateLocalizedStrings();
Layout();
}
////////////////////////////////////////////////////////////////////////////////
// views::ButtonListener implementation:
void EulaView::ButtonPressed(views::Button* sender, const views::Event& event) {
if (sender == continue_button_) {
if (usage_statistics_checkbox_) {
GoogleUpdateSettings::SetCollectStatsConsent(
usage_statistics_checkbox_->checked());
}
observer_->OnExit(ScreenObserver::EULA_ACCEPTED);
}
// TODO(glotov): handle cancel button.
}
////////////////////////////////////////////////////////////////////////////////
// views::LinkController implementation:
void EulaView::LinkActivated(views::Link* source, int event_flags) {
// TODO(glotov): handle link clicks.
}
////////////////////////////////////////////////////////////////////////////////
// TabContentsDelegate implementation:
// Convenience function. Queries |eula_view| for HTML title and, if it
// is ready, assigns it to |eula_label| and returns true so the caller
// view calls Layout().
static bool PublishTitleIfReady(const TabContents* contents,
DOMView* eula_view,
views::Label* eula_label) {
if (contents != eula_view->tab_contents())
return false;
eula_label->SetText(UTF16ToWide(eula_view->tab_contents()->GetTitle()));
return true;
}
void EulaView::NavigationStateChanged(const TabContents* contents,
unsigned changed_flags) {
if (changed_flags & TabContents::INVALIDATE_TITLE) {
if (PublishTitleIfReady(contents, google_eula_view_, google_eula_label_) ||
PublishTitleIfReady(contents, oem_eula_view_, oem_eula_label_)) {
Layout();
}
}
}
} // namespace chromeos
<commit_msg>EULA screen enabling/disabling crash/metrics reporting renovated.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/eula_view.h"
#include <signal.h>
#include <sys/types.h>
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/customization_document.h"
#include "chrome/browser/chromeos/login/network_screen_delegate.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/options_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/button/native_button.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/layout_manager.h"
#include "views/standard_layout.h"
#if defined(USE_LINUX_BREAKPAD)
#include "chrome/app/breakpad_linux.h"
#endif
namespace {
const int kBorderSize = 10;
const int kMargin = 20;
const int kLastButtonHorizontalMargin = 10;
const int kCheckBowWidth = 22;
const int kTextMargin = 10;
// TODO(glotov): this URL should be changed to actual Google ChromeOS EULA.
// See crbug.com/4647
const char kGoogleEulaUrl[] = "about:terms";
enum kLayoutColumnsets {
SINGLE_CONTROL_ROW,
SINGLE_CONTROL_WITH_SHIFT_ROW,
SINGLE_LINK_WITH_SHIFT_ROW,
LAST_ROW
};
// A simple LayoutManager that causes the associated view's one child to be
// sized to match the bounds of its parent except the bounds, if set.
struct FillLayoutWithBorder : public views::LayoutManager {
// Overridden from LayoutManager:
virtual void Layout(views::View* host) {
DCHECK(host->GetChildViewCount());
host->GetChildViewAt(0)->SetBounds(host->GetLocalBounds(false));
}
virtual gfx::Size GetPreferredSize(views::View* host) {
return gfx::Size(host->width(), host->height());
}
};
} // namespace
namespace chromeos {
EulaView::EulaView(chromeos::ScreenObserver* observer)
: google_eula_label_(NULL),
google_eula_view_(NULL),
usage_statistics_checkbox_(NULL),
learn_more_link_(NULL),
oem_eula_label_(NULL),
oem_eula_view_(NULL),
system_security_settings_link_(NULL),
cancel_button_(NULL),
continue_button_(NULL),
observer_(observer) {
}
EulaView::~EulaView() {
}
// Convenience function to set layout's columnsets for this screen.
static void SetUpGridLayout(views::GridLayout* layout) {
static const int kPadding = kBorderSize + kMargin;
views::ColumnSet* column_set = layout->AddColumnSet(SINGLE_CONTROL_ROW);
column_set->AddPaddingColumn(0, kPadding);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(SINGLE_CONTROL_WITH_SHIFT_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(SINGLE_LINK_WITH_SHIFT_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin + kCheckBowWidth);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kPadding);
column_set = layout->AddColumnSet(LAST_ROW);
column_set->AddPaddingColumn(0, kPadding + kTextMargin);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kLastButtonHorizontalMargin + kBorderSize);
}
// Convenience function. Returns URL of the OEM EULA page that should be
// displayed using current locale and manifest. Returns empty URL otherwise.
static GURL GetOemEulaPagePath() {
const StartupCustomizationDocument *customization =
WizardController::default_controller()->GetCustomization();
if (customization) {
std::string locale = g_browser_process->GetApplicationLocale();
FilePath eula_page_path = customization->GetEULAPagePath(locale);
if (eula_page_path.empty()) {
LOG(INFO) << "No eula found for locale: " << locale;
locale = customization->initial_locale();
eula_page_path = customization->GetEULAPagePath(locale);
}
if (!eula_page_path.empty()) {
const std::string page_path = std::string(chrome::kFileScheme) +
chrome::kStandardSchemeSeparator + eula_page_path.value();
return GURL(page_path);
} else {
LOG(INFO) << "No eula found for locale: " << locale;
}
} else {
LOG(ERROR) << "No manifest found.";
}
return GURL();
}
void EulaView::Init() {
// Use rounded rect background.
views::Painter* painter = CreateWizardPainter(
&BorderDefinition::kScreenBorder);
set_background(
views::Background::CreateBackgroundPainter(true, painter));
// Layout created controls.
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
SetUpGridLayout(layout);
static const int kPadding = kBorderSize + kMargin;
layout->AddPaddingRow(0, kPadding);
layout->StartRow(0, SINGLE_CONTROL_ROW);
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gfx::Font label_font =
rb.GetFont(ResourceBundle::MediumFont).DeriveFont(0, gfx::Font::NORMAL);
google_eula_label_ = new views::Label(std::wstring(), label_font);
layout->AddView(google_eula_label_, 1, 1,
views::GridLayout::LEADING, views::GridLayout::FILL);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, SINGLE_CONTROL_ROW);
views::View* box_view = new views::View();
box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));
box_view->SetLayoutManager(new FillLayoutWithBorder());
layout->AddView(box_view);
google_eula_view_ = new DOMView();
box_view->AddChildView(google_eula_view_);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, SINGLE_CONTROL_WITH_SHIFT_ROW);
usage_statistics_checkbox_ = new views::Checkbox();
usage_statistics_checkbox_->SetMultiLine(true);
usage_statistics_checkbox_->SetChecked(
g_browser_process->local_state()->GetBoolean(
prefs::kMetricsReportingEnabled));
layout->AddView(usage_statistics_checkbox_);
layout->StartRow(0, SINGLE_LINK_WITH_SHIFT_ROW);
learn_more_link_ = new views::Link();
learn_more_link_->SetController(this);
layout->AddView(learn_more_link_);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(0, SINGLE_CONTROL_ROW);
oem_eula_label_ = new views::Label(std::wstring(), label_font);
layout->AddView(oem_eula_label_, 1, 1,
views::GridLayout::LEADING, views::GridLayout::FILL);
oem_eula_page_ = GetOemEulaPagePath();
if (!oem_eula_page_.is_empty()) {
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
layout->StartRow(1, SINGLE_CONTROL_ROW);
box_view = new views::View();
box_view->SetLayoutManager(new FillLayoutWithBorder());
box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));
layout->AddView(box_view);
oem_eula_view_ = new DOMView();
box_view->AddChildView(oem_eula_view_);
}
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(0, LAST_ROW);
system_security_settings_link_ = new views::Link();
system_security_settings_link_->SetController(this);
layout->AddView(system_security_settings_link_);
cancel_button_ = new views::NativeButton(this, std::wstring());
cancel_button_->SetEnabled(false);
layout->AddView(cancel_button_);
continue_button_ = new views::NativeButton(this, std::wstring());
layout->AddView(continue_button_);
layout->AddPaddingRow(0, kPadding);
UpdateLocalizedStrings();
}
void EulaView::LoadEulaView(DOMView* eula_view,
views::Label* eula_label,
const GURL& eula_url) {
Profile* profile = ProfileManager::GetDefaultProfile();
eula_view->Init(profile,
SiteInstance::CreateSiteInstanceForURL(profile, eula_url));
eula_view->LoadURL(eula_url);
eula_view->tab_contents()->set_delegate(this);
}
void EulaView::UpdateLocalizedStrings() {
// Load Google EULA and its title.
LoadEulaView(google_eula_view_, google_eula_label_, GURL(kGoogleEulaUrl));
// Load OEM EULA and its title.
if (!oem_eula_page_.is_empty())
LoadEulaView(oem_eula_view_, oem_eula_label_, oem_eula_page_);
// Load other labels from resources.
usage_statistics_checkbox_->SetLabel(
l10n_util::GetString(IDS_EULA_CHECKBOX_ENABLE_LOGGING));
learn_more_link_->SetText(
l10n_util::GetString(IDS_LEARN_MORE));
system_security_settings_link_->SetText(
l10n_util::GetString(IDS_EULA_SYSTEM_SECURITY_SETTINGS_LINK));
continue_button_->SetLabel(
l10n_util::GetString(IDS_EULA_ACCEPT_AND_CONTINUE_BUTTON));
cancel_button_->SetLabel(
l10n_util::GetString(IDS_CANCEL));
}
////////////////////////////////////////////////////////////////////////////////
// views::View: implementation:
void EulaView::OnLocaleChanged() {
UpdateLocalizedStrings();
Layout();
}
////////////////////////////////////////////////////////////////////////////////
// views::ButtonListener implementation:
void EulaView::ButtonPressed(views::Button* sender, const views::Event& event) {
if (sender == continue_button_) {
if (usage_statistics_checkbox_) {
const bool enable_reporting = usage_statistics_checkbox_->checked();
PrefService* prefs = g_browser_process->local_state();
if (prefs->GetBoolean(prefs::kMetricsReportingEnabled) !=
enable_reporting) {
prefs->SetBoolean(prefs::kMetricsReportingEnabled, enable_reporting);
prefs->SavePersistentPrefs();
OptionsUtil::ResolveMetricsReportingEnabled(enable_reporting);
#if defined(USE_LINUX_BREAKPAD)
if (enable_reporting)
InitCrashReporter();
#endif
}
}
observer_->OnExit(ScreenObserver::EULA_ACCEPTED);
}
// TODO(glotov): handle cancel button.
}
////////////////////////////////////////////////////////////////////////////////
// views::LinkController implementation:
void EulaView::LinkActivated(views::Link* source, int event_flags) {
// TODO(glotov): handle link clicks.
}
////////////////////////////////////////////////////////////////////////////////
// TabContentsDelegate implementation:
// Convenience function. Queries |eula_view| for HTML title and, if it
// is ready, assigns it to |eula_label| and returns true so the caller
// view calls Layout().
static bool PublishTitleIfReady(const TabContents* contents,
DOMView* eula_view,
views::Label* eula_label) {
if (contents != eula_view->tab_contents())
return false;
eula_label->SetText(UTF16ToWide(eula_view->tab_contents()->GetTitle()));
return true;
}
void EulaView::NavigationStateChanged(const TabContents* contents,
unsigned changed_flags) {
if (changed_flags & TabContents::INVALIDATE_TITLE) {
if (PublishTitleIfReady(contents, google_eula_view_, google_eula_label_) ||
PublishTitleIfReady(contents, oem_eula_view_, oem_eula_label_)) {
Layout();
}
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/**
* @file SimpleMotionBehaviorControl.cpp
*
* @author <a href="mailto:[email protected]">Heinrich Mellmann</a>
* @author <a href="mailto:[email protected]">Daniel Goehring</a>
* Implementation of class SimpleMotionBehaviorControl
*/
#include "SimpleMotionBehaviorControl.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugModify.h"
SimpleMotionBehaviorControl::SimpleMotionBehaviorControl()
{
// test head control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Search", "Set the HeadMotion-Request to 'search'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:reverseSearchDirection", "Set the head search direction to counterclockwise.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_image", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_field", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Stabilize", "Set the HeadMotion-Request to 'stabilize'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:SwitchToBottomCamera", "Switch to bottom camera", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_ball_modell", "Search for ball if not seen", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_straight_ahead", "look straight ahead", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_attention_point", "look at attention point", false);
// test motion control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:standard_stand", "stand as standard or not", true);
// walk
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_backward", "Walk backward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_left", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_right", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_left", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_right", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stepping", "walk with zero speed", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:step_control", "test step control", false);
// key frame motion
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_front", "Set the motion request to 'stand_up_from_front'", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_back", "Set the motion request to 'stand_up_from_back'", false);
// other motions
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dead", "Set the robot dead.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand", "The default motion, otherwise do nothing", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:sit", "sit down, has a rest", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:init", "Set the robot init.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dance", "Let's dance", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:protect_falling", "Don't hurt me!", false);
}
void SimpleMotionBehaviorControl::execute()
{
// reset some stuff by default
getMotionRequest().forced = false;
getMotionRequest().standHeight = -1; // sit in a stable position
testHead();
testMotion();
}//end execute
void SimpleMotionBehaviorControl::testHead()
{
getHeadMotionRequest().cameraID = CameraInfo::Top;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:SwitchToBottomCamera",
getHeadMotionRequest().cameraID = CameraInfo::Bottom;
);
// keep the head as forced by default
getHeadMotionRequest().id = HeadMotionRequest::hold;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Search",
getHeadMotionRequest().id = HeadMotionRequest::search;
getHeadMotionRequest().searchCenter = Vector3<double>(2000, 0, 0);
getHeadMotionRequest().searchSize = Vector3<double>(1500, 2000, 0);
);
getHeadMotionRequest().searchDirection = true;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:reverseSearchDirection",
getHeadMotionRequest().searchDirection = false;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Stabilize",
getHeadMotionRequest().id = HeadMotionRequest::stabilize;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_image",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_point;
getHeadMotionRequest().targetPointInImage = getBallPercept().centerInImage;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_field",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_world_point;
getHeadMotionRequest().targetPointInTheWorld.x = getBallPercept().bearingBasedOffsetOnField.x;
getHeadMotionRequest().targetPointInTheWorld.y = getBallPercept().bearingBasedOffsetOnField.y;
getHeadMotionRequest().targetPointInTheWorld.z = getFieldInfo().ballRadius;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_straight_ahead",
getHeadMotionRequest().id = HeadMotionRequest::look_straight_ahead;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_at_attention_point",
getHeadMotionRequest().id = HeadMotionRequest::look_at_point_on_the_ground;
getHeadMotionRequest().targetPointOnTheGround = getAttentionModel().mostInterestingPoint;
);
}//end testHead
void SimpleMotionBehaviorControl::testMotion()
{
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.character = 0.5;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand",
getMotionRequest().id = motion::stand;
);
getMotionRequest().standardStand = false;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:standard_stand",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = -1; // minus means the same value as walk
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:sit",
getMotionRequest().id = motion::sit;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_forward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_backward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(-60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stepping",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:step_control",
if ( getMotionStatus().stepControl.stepID % 5 == 0)
{
getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID;
switch(getMotionStatus().stepControl.moveableFoot)
{
case MotionStatus::StepControlStatus::LEFT:
case MotionStatus::StepControlStatus::BOTH:
{
getMotionRequest().walkRequest.stepControl.moveLeftFoot = true;
getMotionRequest().walkRequest.coordinate = WalkRequest::LFoot;
break;
}
case MotionStatus::StepControlStatus::RIGHT:
{
getMotionRequest().walkRequest.stepControl.moveLeftFoot = false;
getMotionRequest().walkRequest.coordinate = WalkRequest::RFoot;
break;
}
default: ASSERT(false);
break;
}
double stepTime = 1000;
double speedDirection = 0;
MODIFY("StepControl.time",stepTime);
MODIFY("StepControl.speedDirection",speedDirection);
getMotionRequest().walkRequest.stepControl.target = Pose2D(0, 100, 0);
getMotionRequest().walkRequest.stepControl.time = stepTime;
getMotionRequest().walkRequest.stepControl.speedDirection = Math::fromDegrees(speedDirection);
getMotionRequest().walkRequest.character = 1;
}
);
double offsetR = 0;
MODIFY("walk.offset.r", offsetR);
getMotionRequest().walkRequest.offset.rotation = Math::fromDegrees(offsetR);
MODIFY("walk.offset.x", getMotionRequest().walkRequest.offset.translation.x);
MODIFY("walk.offset.y", getMotionRequest().walkRequest.offset.translation.y);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_front",
getMotionRequest().id = motion::stand_up_from_front;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_back",
getMotionRequest().id = motion::stand_up_from_back;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dead",
getMotionRequest().id = motion::dead;
getMotionRequest().forced = true;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:init",
getMotionRequest().id = motion::init;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dance",
getMotionRequest().id = motion::dance;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:protect_falling",
getMotionRequest().id = motion::protect_falling;
);
}//end testMotion
<commit_msg>modify walk character directly<commit_after>/**
* @file SimpleMotionBehaviorControl.cpp
*
* @author <a href="mailto:[email protected]">Heinrich Mellmann</a>
* @author <a href="mailto:[email protected]">Daniel Goehring</a>
* Implementation of class SimpleMotionBehaviorControl
*/
#include "SimpleMotionBehaviorControl.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugModify.h"
SimpleMotionBehaviorControl::SimpleMotionBehaviorControl()
{
// test head control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Search", "Set the HeadMotion-Request to 'search'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:reverseSearchDirection", "Set the head search direction to counterclockwise.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_image", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_field", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Stabilize", "Set the HeadMotion-Request to 'stabilize'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:SwitchToBottomCamera", "Switch to bottom camera", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_ball_modell", "Search for ball if not seen", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_straight_ahead", "look straight ahead", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_attention_point", "look at attention point", false);
// test motion control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:standard_stand", "stand as standard or not", true);
// walk
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_backward", "Walk backward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_left", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_right", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_left", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_right", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stepping", "walk with zero speed", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:step_control", "test step control", false);
// key frame motion
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_front", "Set the motion request to 'stand_up_from_front'", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_back", "Set the motion request to 'stand_up_from_back'", false);
// other motions
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dead", "Set the robot dead.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand", "The default motion, otherwise do nothing", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:sit", "sit down, has a rest", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:init", "Set the robot init.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dance", "Let's dance", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:protect_falling", "Don't hurt me!", false);
}
void SimpleMotionBehaviorControl::execute()
{
// reset some stuff by default
getMotionRequest().forced = false;
getMotionRequest().standHeight = -1; // sit in a stable position
testHead();
testMotion();
}//end execute
void SimpleMotionBehaviorControl::testHead()
{
getHeadMotionRequest().cameraID = CameraInfo::Top;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:SwitchToBottomCamera",
getHeadMotionRequest().cameraID = CameraInfo::Bottom;
);
// keep the head as forced by default
getHeadMotionRequest().id = HeadMotionRequest::hold;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Search",
getHeadMotionRequest().id = HeadMotionRequest::search;
getHeadMotionRequest().searchCenter = Vector3<double>(2000, 0, 0);
getHeadMotionRequest().searchSize = Vector3<double>(1500, 2000, 0);
);
getHeadMotionRequest().searchDirection = true;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:reverseSearchDirection",
getHeadMotionRequest().searchDirection = false;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Stabilize",
getHeadMotionRequest().id = HeadMotionRequest::stabilize;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_image",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_point;
getHeadMotionRequest().targetPointInImage = getBallPercept().centerInImage;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_field",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_world_point;
getHeadMotionRequest().targetPointInTheWorld.x = getBallPercept().bearingBasedOffsetOnField.x;
getHeadMotionRequest().targetPointInTheWorld.y = getBallPercept().bearingBasedOffsetOnField.y;
getHeadMotionRequest().targetPointInTheWorld.z = getFieldInfo().ballRadius;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_straight_ahead",
getHeadMotionRequest().id = HeadMotionRequest::look_straight_ahead;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_at_attention_point",
getHeadMotionRequest().id = HeadMotionRequest::look_at_point_on_the_ground;
getHeadMotionRequest().targetPointOnTheGround = getAttentionModel().mostInterestingPoint;
);
}//end testHead
void SimpleMotionBehaviorControl::testMotion()
{
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.character = 0.5;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand",
getMotionRequest().id = motion::stand;
);
getMotionRequest().standardStand = false;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:standard_stand",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = -1; // minus means the same value as walk
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:sit",
getMotionRequest().id = motion::sit;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_forward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_backward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(-60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stepping",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:step_control",
if ( getMotionStatus().stepControl.stepID % 5 == 0)
{
getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID;
switch(getMotionStatus().stepControl.moveableFoot)
{
case MotionStatus::StepControlStatus::LEFT:
case MotionStatus::StepControlStatus::BOTH:
{
getMotionRequest().walkRequest.stepControl.moveLeftFoot = true;
getMotionRequest().walkRequest.coordinate = WalkRequest::LFoot;
break;
}
case MotionStatus::StepControlStatus::RIGHT:
{
getMotionRequest().walkRequest.stepControl.moveLeftFoot = false;
getMotionRequest().walkRequest.coordinate = WalkRequest::RFoot;
break;
}
default: ASSERT(false);
break;
}
double stepTime = 1000;
double speedDirection = 0;
MODIFY("StepControl.time",stepTime);
MODIFY("StepControl.speedDirection",speedDirection);
getMotionRequest().walkRequest.stepControl.target = Pose2D(0, 100, 0);
getMotionRequest().walkRequest.stepControl.time = stepTime;
getMotionRequest().walkRequest.stepControl.speedDirection = Math::fromDegrees(speedDirection);
}
);
double offsetR = 0;
MODIFY("walk.offset.r", offsetR);
getMotionRequest().walkRequest.offset.rotation = Math::fromDegrees(offsetR);
MODIFY("walk.offset.x", getMotionRequest().walkRequest.offset.translation.x);
MODIFY("walk.offset.y", getMotionRequest().walkRequest.offset.translation.y);
MODIFY("walk.character", getMotionRequest().walkRequest.character);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_front",
getMotionRequest().id = motion::stand_up_from_front;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_back",
getMotionRequest().id = motion::stand_up_from_back;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dead",
getMotionRequest().id = motion::dead;
getMotionRequest().forced = true;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:init",
getMotionRequest().id = motion::init;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dance",
getMotionRequest().id = motion::dance;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:protect_falling",
getMotionRequest().id = motion::protect_falling;
);
}//end testMotion
<|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/extensions/crx_installer.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_file_util.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/chromium_strings.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/image_decoder.h"
namespace {
// Helper function to delete files. This is used to avoid ugly casts which
// would be necessary with PostMessage since file_util::Delete is overloaded.
static void DeleteFileHelper(const FilePath& path, bool recursive) {
file_util::Delete(path, recursive);
}
}
void CrxInstaller::Start(const FilePath& crx_path,
const FilePath& install_directory,
Extension::Location install_source,
const std::string& expected_id,
bool delete_crx,
bool allow_privilege_increase,
MessageLoop* file_loop,
ExtensionsService* frontend,
ExtensionInstallUI* client) {
// Note: We don't keep a reference because this object manages its own
// lifetime.
new CrxInstaller(crx_path, install_directory, install_source, expected_id,
delete_crx, allow_privilege_increase, file_loop, frontend,
client);
}
CrxInstaller::CrxInstaller(const FilePath& crx_path,
const FilePath& install_directory,
Extension::Location install_source,
const std::string& expected_id,
bool delete_crx,
bool allow_privilege_increase,
MessageLoop* file_loop,
ExtensionsService* frontend,
ExtensionInstallUI* client)
: crx_path_(crx_path),
install_directory_(install_directory),
install_source_(install_source),
expected_id_(expected_id),
delete_crx_(delete_crx),
allow_privilege_increase_(allow_privilege_increase),
file_loop_(file_loop),
ui_loop_(MessageLoop::current()),
frontend_(frontend),
client_(client) {
extensions_enabled_ = frontend_->extensions_enabled();
unpacker_ = new SandboxedExtensionUnpacker(
crx_path, g_browser_process->resource_dispatcher_host(), this);
file_loop->PostTask(FROM_HERE, NewRunnableMethod(unpacker_,
&SandboxedExtensionUnpacker::Start));
}
CrxInstaller::~CrxInstaller() {
// Delete the temp directory and crx file as necessary. Note that the
// destructor might be called on any thread, so we post a task to the file
// thread to make sure the delete happens there.
if (!temp_dir_.value().empty()) {
file_loop_->PostTask(FROM_HERE, NewRunnableFunction(&DeleteFileHelper,
temp_dir_, true)); // recursive delete
}
if (delete_crx_) {
file_loop_->PostTask(FROM_HERE, NewRunnableFunction(&DeleteFileHelper,
crx_path_, false)); // non-recursive delete
}
}
void CrxInstaller::OnUnpackFailure(const std::string& error_message) {
DCHECK(MessageLoop::current() == file_loop_);
ReportFailureFromFileThread(error_message);
}
void CrxInstaller::OnUnpackSuccess(const FilePath& temp_dir,
const FilePath& extension_dir,
Extension* extension) {
DCHECK(MessageLoop::current() == file_loop_);
// Note: We take ownership of |extension| and |temp_dir|.
extension_.reset(extension);
temp_dir_ = temp_dir;
// The unpack dir we don't have to delete explicity since it is a child of
// the temp dir.
unpacked_extension_root_ = extension_dir;
DCHECK(file_util::ContainsPath(temp_dir_, unpacked_extension_root_));
// Determine whether to allow installation. We always allow themes and
// external installs.
if (!extensions_enabled_ && !extension->IsTheme() &&
!Extension::IsExternalLocation(install_source_)) {
ReportFailureFromFileThread("Extensions are not enabled.");
return;
}
// Make sure the expected id matches.
// TODO(aa): Also support expected version?
if (!expected_id_.empty() && expected_id_ != extension->id()) {
ReportFailureFromFileThread(StringPrintf(
"ID in new extension manifest (%s) does not match expected id (%s)",
extension->id().c_str(),
expected_id_.c_str()));
return;
}
if (client_.get()) {
DecodeInstallIcon(extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE),
&install_icon_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ConfirmInstall));
}
// static
void CrxInstaller::DecodeInstallIcon(const FilePath& large_icon_path,
scoped_ptr<SkBitmap>* result) {
if (large_icon_path.empty())
return;
std::string file_contents;
if (!file_util::ReadFileToString(large_icon_path, &file_contents)) {
LOG(ERROR) << "Could not read icon file: "
<< WideToUTF8(large_icon_path.ToWStringHack());
return;
}
// Decode the image using WebKit's image decoder.
const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data());
webkit_glue::ImageDecoder decoder;
scoped_ptr<SkBitmap> decoded(new SkBitmap());
*decoded = decoder.Decode(data, file_contents.length());
if (decoded->empty()) {
LOG(ERROR) << "Could not decode icon file: "
<< WideToUTF8(large_icon_path.ToWStringHack());
return;
}
if (decoded->width() != 128 || decoded->height() != 128) {
LOG(ERROR) << "Icon file has unexpected size: "
<< IntToString(decoded->width()) << "x"
<< IntToString(decoded->height());
return;
}
result->swap(decoded);
}
void CrxInstaller::ConfirmInstall() {
DCHECK(MessageLoop::current() == ui_loop_);
if (frontend_->extension_prefs()->IsExtensionBlacklisted(extension_->id())) {
LOG(INFO) << "This extension: " << extension_->id()
<< " is blacklisted. Install failed.";
if (client_.get()) {
client_->OnInstallFailure("This extension is blacklisted.");
}
return;
}
current_version_ =
frontend_->extension_prefs()->GetVersionString(extension_->id());
if (client_.get()) {
AddRef(); // balanced in ContinueInstall() and AbortInstall().
client_->ConfirmInstall(this, extension_.get(), install_icon_.get());
} else {
file_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::CompleteInstall));
}
return;
}
void CrxInstaller::ContinueInstall() {
file_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::CompleteInstall));
Release(); // balanced in ConfirmInstall().
}
void CrxInstaller::AbortInstall() {
Release(); // balanced in ConfirmInstall().
// We're done. Since we don't post any more tasks to ourself, our ref count
// should go to zero and we die. The destructor will clean up the temp dir.
}
void CrxInstaller::CompleteInstall() {
DCHECK(MessageLoop::current() == file_loop_);
FilePath version_dir;
Extension::InstallType install_type =
extension_file_util::CompareToInstalledVersion(
install_directory_, extension_->id(), current_version_,
extension_->VersionString(), &version_dir);
if (install_type == Extension::DOWNGRADE) {
ReportFailureFromFileThread("Attempted to downgrade extension.");
return;
}
if (install_type == Extension::REINSTALL) {
// We use this as a signal to switch themes.
ReportOverinstallFromFileThread();
return;
}
std::string error_msg;
if (!extension_file_util::InstallExtension(unpacked_extension_root_,
version_dir, &error_msg)) {
ReportFailureFromFileThread(error_msg);
return;
}
// This is lame, but we must reload the extension because absolute paths
// inside the content scripts are established inside InitFromValue() and we
// just moved the extension.
// TODO(aa): All paths to resources inside extensions should be created
// lazily and based on the Extension's root path at that moment.
std::string error;
extension_.reset(extension_file_util::LoadExtension(version_dir, true,
&error));
DCHECK(error.empty());
extension_->set_location(install_source_);
ReportSuccessFromFileThread();
}
void CrxInstaller::ReportFailureFromFileThread(const std::string& error) {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportFailureFromUIThread, error));
}
void CrxInstaller::ReportFailureFromUIThread(const std::string& error) {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::NO_THEME_DETECTED,
Source<CrxInstaller>(this),
NotificationService::NoDetails());
// This isn't really necessary, it is only used because unit tests expect to
// see errors get reported via this interface.
//
// TODO(aa): Need to go through unit tests and clean them up too, probably get
// rid of this line.
ExtensionErrorReporter::GetInstance()->ReportError(error, false); // quiet
if (client_.get())
client_->OnInstallFailure(error);
}
void CrxInstaller::ReportOverinstallFromFileThread() {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportOverinstallFromUIThread));
}
void CrxInstaller::ReportOverinstallFromUIThread() {
DCHECK(MessageLoop::current() == ui_loop_);
if (client_.get())
client_->OnOverinstallAttempted(extension_.get());
frontend_->OnExtensionOverinstallAttempted(extension_->id());
}
void CrxInstaller::ReportSuccessFromFileThread() {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportSuccessFromUIThread));
}
void CrxInstaller::ReportSuccessFromUIThread() {
DCHECK(MessageLoop::current() == ui_loop_);
// If there is a client, tell the client about installation.
if (client_.get())
client_->OnInstallSuccess(extension_.get());
// Tell the frontend about the installation and hand off ownership of
// extension_ to it.
frontend_->OnExtensionInstalled(extension_.release(),
allow_privilege_increase_);
// We're done. We don't post any more tasks to ourselves so we are deleted
// soon.
}
<commit_msg>Make sure theme loading bubble is cancelled when extension install is cancelled.<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/extensions/crx_installer.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_file_util.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/chromium_strings.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/image_decoder.h"
namespace {
// Helper function to delete files. This is used to avoid ugly casts which
// would be necessary with PostMessage since file_util::Delete is overloaded.
static void DeleteFileHelper(const FilePath& path, bool recursive) {
file_util::Delete(path, recursive);
}
}
void CrxInstaller::Start(const FilePath& crx_path,
const FilePath& install_directory,
Extension::Location install_source,
const std::string& expected_id,
bool delete_crx,
bool allow_privilege_increase,
MessageLoop* file_loop,
ExtensionsService* frontend,
ExtensionInstallUI* client) {
// Note: We don't keep a reference because this object manages its own
// lifetime.
new CrxInstaller(crx_path, install_directory, install_source, expected_id,
delete_crx, allow_privilege_increase, file_loop, frontend,
client);
}
CrxInstaller::CrxInstaller(const FilePath& crx_path,
const FilePath& install_directory,
Extension::Location install_source,
const std::string& expected_id,
bool delete_crx,
bool allow_privilege_increase,
MessageLoop* file_loop,
ExtensionsService* frontend,
ExtensionInstallUI* client)
: crx_path_(crx_path),
install_directory_(install_directory),
install_source_(install_source),
expected_id_(expected_id),
delete_crx_(delete_crx),
allow_privilege_increase_(allow_privilege_increase),
file_loop_(file_loop),
ui_loop_(MessageLoop::current()),
frontend_(frontend),
client_(client) {
extensions_enabled_ = frontend_->extensions_enabled();
unpacker_ = new SandboxedExtensionUnpacker(
crx_path, g_browser_process->resource_dispatcher_host(), this);
file_loop->PostTask(FROM_HERE, NewRunnableMethod(unpacker_,
&SandboxedExtensionUnpacker::Start));
}
CrxInstaller::~CrxInstaller() {
// Delete the temp directory and crx file as necessary. Note that the
// destructor might be called on any thread, so we post a task to the file
// thread to make sure the delete happens there.
if (!temp_dir_.value().empty()) {
file_loop_->PostTask(FROM_HERE, NewRunnableFunction(&DeleteFileHelper,
temp_dir_, true)); // recursive delete
}
if (delete_crx_) {
file_loop_->PostTask(FROM_HERE, NewRunnableFunction(&DeleteFileHelper,
crx_path_, false)); // non-recursive delete
}
}
void CrxInstaller::OnUnpackFailure(const std::string& error_message) {
DCHECK(MessageLoop::current() == file_loop_);
ReportFailureFromFileThread(error_message);
}
void CrxInstaller::OnUnpackSuccess(const FilePath& temp_dir,
const FilePath& extension_dir,
Extension* extension) {
DCHECK(MessageLoop::current() == file_loop_);
// Note: We take ownership of |extension| and |temp_dir|.
extension_.reset(extension);
temp_dir_ = temp_dir;
// The unpack dir we don't have to delete explicity since it is a child of
// the temp dir.
unpacked_extension_root_ = extension_dir;
DCHECK(file_util::ContainsPath(temp_dir_, unpacked_extension_root_));
// Determine whether to allow installation. We always allow themes and
// external installs.
if (!extensions_enabled_ && !extension->IsTheme() &&
!Extension::IsExternalLocation(install_source_)) {
ReportFailureFromFileThread("Extensions are not enabled.");
return;
}
// Make sure the expected id matches.
// TODO(aa): Also support expected version?
if (!expected_id_.empty() && expected_id_ != extension->id()) {
ReportFailureFromFileThread(StringPrintf(
"ID in new extension manifest (%s) does not match expected id (%s)",
extension->id().c_str(),
expected_id_.c_str()));
return;
}
if (client_.get()) {
DecodeInstallIcon(extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE),
&install_icon_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ConfirmInstall));
}
// static
void CrxInstaller::DecodeInstallIcon(const FilePath& large_icon_path,
scoped_ptr<SkBitmap>* result) {
if (large_icon_path.empty())
return;
std::string file_contents;
if (!file_util::ReadFileToString(large_icon_path, &file_contents)) {
LOG(ERROR) << "Could not read icon file: "
<< WideToUTF8(large_icon_path.ToWStringHack());
return;
}
// Decode the image using WebKit's image decoder.
const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data());
webkit_glue::ImageDecoder decoder;
scoped_ptr<SkBitmap> decoded(new SkBitmap());
*decoded = decoder.Decode(data, file_contents.length());
if (decoded->empty()) {
LOG(ERROR) << "Could not decode icon file: "
<< WideToUTF8(large_icon_path.ToWStringHack());
return;
}
if (decoded->width() != 128 || decoded->height() != 128) {
LOG(ERROR) << "Icon file has unexpected size: "
<< IntToString(decoded->width()) << "x"
<< IntToString(decoded->height());
return;
}
result->swap(decoded);
}
void CrxInstaller::ConfirmInstall() {
DCHECK(MessageLoop::current() == ui_loop_);
if (frontend_->extension_prefs()->IsExtensionBlacklisted(extension_->id())) {
LOG(INFO) << "This extension: " << extension_->id()
<< " is blacklisted. Install failed.";
if (client_.get()) {
client_->OnInstallFailure("This extension is blacklisted.");
}
return;
}
current_version_ =
frontend_->extension_prefs()->GetVersionString(extension_->id());
if (client_.get()) {
AddRef(); // balanced in ContinueInstall() and AbortInstall().
client_->ConfirmInstall(this, extension_.get(), install_icon_.get());
} else {
file_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::CompleteInstall));
}
return;
}
void CrxInstaller::ContinueInstall() {
file_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::CompleteInstall));
Release(); // balanced in ConfirmInstall().
}
void CrxInstaller::AbortInstall() {
// Kill the theme loading bubble.
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::NO_THEME_DETECTED,
Source<CrxInstaller>(this),
NotificationService::NoDetails());
Release(); // balanced in ConfirmInstall().
// We're done. Since we don't post any more tasks to ourself, our ref count
// should go to zero and we die. The destructor will clean up the temp dir.
}
void CrxInstaller::CompleteInstall() {
DCHECK(MessageLoop::current() == file_loop_);
FilePath version_dir;
Extension::InstallType install_type =
extension_file_util::CompareToInstalledVersion(
install_directory_, extension_->id(), current_version_,
extension_->VersionString(), &version_dir);
if (install_type == Extension::DOWNGRADE) {
ReportFailureFromFileThread("Attempted to downgrade extension.");
return;
}
if (install_type == Extension::REINSTALL) {
// We use this as a signal to switch themes.
ReportOverinstallFromFileThread();
return;
}
std::string error_msg;
if (!extension_file_util::InstallExtension(unpacked_extension_root_,
version_dir, &error_msg)) {
ReportFailureFromFileThread(error_msg);
return;
}
// This is lame, but we must reload the extension because absolute paths
// inside the content scripts are established inside InitFromValue() and we
// just moved the extension.
// TODO(aa): All paths to resources inside extensions should be created
// lazily and based on the Extension's root path at that moment.
std::string error;
extension_.reset(extension_file_util::LoadExtension(version_dir, true,
&error));
DCHECK(error.empty());
extension_->set_location(install_source_);
ReportSuccessFromFileThread();
}
void CrxInstaller::ReportFailureFromFileThread(const std::string& error) {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportFailureFromUIThread, error));
}
void CrxInstaller::ReportFailureFromUIThread(const std::string& error) {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::NO_THEME_DETECTED,
Source<CrxInstaller>(this),
NotificationService::NoDetails());
// This isn't really necessary, it is only used because unit tests expect to
// see errors get reported via this interface.
//
// TODO(aa): Need to go through unit tests and clean them up too, probably get
// rid of this line.
ExtensionErrorReporter::GetInstance()->ReportError(error, false); // quiet
if (client_.get())
client_->OnInstallFailure(error);
}
void CrxInstaller::ReportOverinstallFromFileThread() {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportOverinstallFromUIThread));
}
void CrxInstaller::ReportOverinstallFromUIThread() {
DCHECK(MessageLoop::current() == ui_loop_);
if (client_.get())
client_->OnOverinstallAttempted(extension_.get());
frontend_->OnExtensionOverinstallAttempted(extension_->id());
}
void CrxInstaller::ReportSuccessFromFileThread() {
DCHECK(MessageLoop::current() == file_loop_);
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this,
&CrxInstaller::ReportSuccessFromUIThread));
}
void CrxInstaller::ReportSuccessFromUIThread() {
DCHECK(MessageLoop::current() == ui_loop_);
// If there is a client, tell the client about installation.
if (client_.get())
client_->OnInstallSuccess(extension_.get());
// Tell the frontend about the installation and hand off ownership of
// extension_ to it.
frontend_->OnExtensionInstalled(extension_.release(),
allow_privilege_increase_);
// We're done. We don't post any more tasks to ourselves so we are deleted
// soon.
}
<|endoftext|> |
<commit_before>#include "doofit/plotting/Plot/Plot.h"
// STL
#include <string>
#include <sstream>
#include <vector>
// boost
#include <boost/regex.hpp>
// ROOT
#include "TIterator.h"
// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"
// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"
using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;
namespace doofit {
namespace plotting {
Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
dimension_(dimension),
datasets_(),
plot_name_(plot_name)
{
datasets_.push_back(&dataset);
pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());
if (&dimension_ == NULL) {
serr << "Plot::Plot(): Dimension is invalid." << endmsg;
throw 1;
}
if (datasets_.front() == NULL) {
serr << "Plot::Plot(): Dataset is invalid." << endmsg;
throw 1;
}
if (plot_name_ == "") {
plot_name_ = dimension_.GetName();
}
for (int i=1; i<pdfs.getSize(); ++i) {
RooAbsArg* sub_arg = pdfs.at(i);
const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);
if (sub_pdf != NULL) {
components_.push_back(RooArgSet(*sub_pdf));
}
}
}
Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
dimension_(dimension),
datasets_(),
plot_name_(plot_name)
{
datasets_.push_back(&dataset);
pdf_ = &pdf;
if (pdf_ == NULL) {
serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
throw 1;
}
if (&dimension_ == NULL) {
serr << "Plot::Plot(): Dimension is invalid." << endmsg;
throw 1;
}
if (datasets_.front() == NULL) {
serr << "Plot::Plot(): Dataset is invalid." << endmsg;
throw 1;
}
if (plot_name_ == "") {
plot_name_ = dimension_.GetName();
}
// iterate over sub PDFs and match supplied regular expressions
RooArgSet nodes;
pdf.branchNodeServerList(&nodes);
for (std::vector<std::string>::const_iterator it = components.begin();
it != components.end(); ++it) {
boost::regex r(*it);
components_.push_back(RooArgSet());
TIterator* it_nodes = nodes.createIterator();
RooAbsArg* node = NULL;
while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
if (pdf_node != NULL) {
std::string pdf_name = pdf_node->GetName();
// exclude resolution models generated by RooFit and match the rest
if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
components_.back().add(*pdf_node);
}
}
}
delete it_nodes;
}
}
void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
if (suffix == "") suffix = "_log";
std::string plot_name = plot_name_;
std::stringstream log_plot_name_sstr;
log_plot_name_sstr << plot_name << suffix;
std::string log_plot_name = log_plot_name_sstr.str();
std::stringstream pull_plot_sstr;
pull_plot_sstr << plot_name << "_pull";
std::string pull_plot_name = pull_plot_sstr.str();
std::stringstream log_pull_plot_sstr;
log_pull_plot_sstr << plot_name << "_pull" << suffix;
std::string log_pull_plot_name = log_pull_plot_sstr.str();
sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;
doocore::lutils::setStyle("LHCb");
RooCmdArg range_arg;
// x range
if (!dimension_.hasMin() && !dimension_.hasMax()) {
double min, max;
// ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
datasets_.front()->getRange(*dimension_non_const, min, max);
double min_t, max_t;
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
it != datasets_.end(); ++it) {
(*it)->getRange(*dimension_non_const, min_t, max_t);
if (min_t < min) min = min_t;
if (max_t > max) max = max_t;
}
range_arg = Range(min, max);
}
RooPlot* plot_frame = dimension_.frame(range_arg);
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
it != datasets_.end(); ++it) {
(*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/);
}
// y range adaptively for log scale
RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
double x,y;
data->GetPoint(0,x,y);
double min_data_entry = y;
for (unsigned int i = 1; i < data->GetN(); ++i) {
data->GetPoint(0,x,y);
if (min_data_entry > y) min_data_entry = y;
}
double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);
sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
sdebug << "minimum for plot range: " << min_plot << endmsg;
TLatex label(0.65,0.85,"LHCb");
config_plot_.OnDemandOpenPlotStack();
if (pdf_ != NULL) {
RooPlot* plot_frame_pull = dimension_.frame(range_arg);
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
it != datasets_.end(); ++it) {
(*it)->plotOn(plot_frame_pull);
}
// I feel so stupid doing this but apparently RooFit leaves me no other way...
RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
if (plot_args_.size() > 0) arg1 = plot_args_[0];
if (plot_args_.size() > 1) arg2 = plot_args_[1];
if (plot_args_.size() > 2) arg3 = plot_args_[2];
if (plot_args_.size() > 3) arg4 = plot_args_[3];
if (plot_args_.size() > 4) arg5 = plot_args_[4];
if (plot_args_.size() > 5) arg6 = plot_args_[5];
if (plot_args_.size() > 6) arg7 = plot_args_[6];
int i=1;
for (std::vector<RooArgSet>::const_iterator it = components_.begin();
it != components_.end(); ++it) {
if (it->getSize() > 0) {
sinfo << "Plotting component " << it->first()->GetName() << endmsg;
pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
++i;
}
}
pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
// =10^(ln(11)/ln(10)-0.5)
//plot_frame_pull->SetMinimum(0.5);
plot_frame_pull->SetMinimum(0.5);
plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
if (sc_y == kLinear || sc_y == kBoth) {
doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
}
plot_frame_pull->SetMinimum(min_plot);
if (sc_y == kLogarithmic || sc_y == kBoth) {
doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
}
delete plot_frame_pull;
}
plot_frame->SetMinimum(0.0);
plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
if (sc_y == kLinear || sc_y == kBoth) {
doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
}
plot_frame->SetMinimum(min_plot);
if (sc_y == kLogarithmic || sc_y == kBoth) {
doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
}
delete plot_frame;
}
Plot::~Plot() {}
} // namespace plotting
} // namespace doofit
<commit_msg>Plotting: fixing other bugs in automated y range estimator<commit_after>#include "doofit/plotting/Plot/Plot.h"
// STL
#include <string>
#include <sstream>
#include <vector>
// boost
#include <boost/regex.hpp>
// ROOT
#include "TIterator.h"
// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"
// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"
using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;
namespace doofit {
namespace plotting {
Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
dimension_(dimension),
datasets_(),
plot_name_(plot_name)
{
datasets_.push_back(&dataset);
pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());
if (&dimension_ == NULL) {
serr << "Plot::Plot(): Dimension is invalid." << endmsg;
throw 1;
}
if (datasets_.front() == NULL) {
serr << "Plot::Plot(): Dataset is invalid." << endmsg;
throw 1;
}
if (plot_name_ == "") {
plot_name_ = dimension_.GetName();
}
for (int i=1; i<pdfs.getSize(); ++i) {
RooAbsArg* sub_arg = pdfs.at(i);
const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);
if (sub_pdf != NULL) {
components_.push_back(RooArgSet(*sub_pdf));
}
}
}
Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
dimension_(dimension),
datasets_(),
plot_name_(plot_name)
{
datasets_.push_back(&dataset);
pdf_ = &pdf;
if (pdf_ == NULL) {
serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
throw 1;
}
if (&dimension_ == NULL) {
serr << "Plot::Plot(): Dimension is invalid." << endmsg;
throw 1;
}
if (datasets_.front() == NULL) {
serr << "Plot::Plot(): Dataset is invalid." << endmsg;
throw 1;
}
if (plot_name_ == "") {
plot_name_ = dimension_.GetName();
}
// iterate over sub PDFs and match supplied regular expressions
RooArgSet nodes;
pdf.branchNodeServerList(&nodes);
for (std::vector<std::string>::const_iterator it = components.begin();
it != components.end(); ++it) {
boost::regex r(*it);
components_.push_back(RooArgSet());
TIterator* it_nodes = nodes.createIterator();
RooAbsArg* node = NULL;
while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
if (pdf_node != NULL) {
std::string pdf_name = pdf_node->GetName();
// exclude resolution models generated by RooFit and match the rest
if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
components_.back().add(*pdf_node);
}
}
}
delete it_nodes;
}
}
void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
if (suffix == "") suffix = "_log";
std::string plot_name = plot_name_;
std::stringstream log_plot_name_sstr;
log_plot_name_sstr << plot_name << suffix;
std::string log_plot_name = log_plot_name_sstr.str();
std::stringstream pull_plot_sstr;
pull_plot_sstr << plot_name << "_pull";
std::string pull_plot_name = pull_plot_sstr.str();
std::stringstream log_pull_plot_sstr;
log_pull_plot_sstr << plot_name << "_pull" << suffix;
std::string log_pull_plot_name = log_pull_plot_sstr.str();
sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;
doocore::lutils::setStyle("LHCb");
RooCmdArg range_arg;
// x range
if (!dimension_.hasMin() && !dimension_.hasMax()) {
double min, max;
// ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
datasets_.front()->getRange(*dimension_non_const, min, max);
double min_t, max_t;
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
it != datasets_.end(); ++it) {
(*it)->getRange(*dimension_non_const, min_t, max_t);
if (min_t < min) min = min_t;
if (max_t > max) max = max_t;
}
range_arg = Range(min, max);
}
RooPlot* plot_frame = dimension_.frame(range_arg);
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
it != datasets_.end(); ++it) {
(*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/);
}
// y range adaptively for log scale
RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
double x,y;
data->GetPoint(0,x,y);
double min_data_entry = y;
for (unsigned int i = 1; i < data->GetN(); ++i) {
data->GetPoint(i,x,y);
sdebug << y << endmsg;
if (min_data_entry > y) min_data_entry = y;
}
double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);
sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
sdebug << "minimum for plot range: " << min_plot << endmsg;
TLatex label(0.65,0.85,"LHCb");
config_plot_.OnDemandOpenPlotStack();
if (pdf_ != NULL) {
RooPlot* plot_frame_pull = dimension_.frame(range_arg);
for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
it != datasets_.end(); ++it) {
(*it)->plotOn(plot_frame_pull);
}
// I feel so stupid doing this but apparently RooFit leaves me no other way...
RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
if (plot_args_.size() > 0) arg1 = plot_args_[0];
if (plot_args_.size() > 1) arg2 = plot_args_[1];
if (plot_args_.size() > 2) arg3 = plot_args_[2];
if (plot_args_.size() > 3) arg4 = plot_args_[3];
if (plot_args_.size() > 4) arg5 = plot_args_[4];
if (plot_args_.size() > 5) arg6 = plot_args_[5];
if (plot_args_.size() > 6) arg7 = plot_args_[6];
int i=1;
for (std::vector<RooArgSet>::const_iterator it = components_.begin();
it != components_.end(); ++it) {
if (it->getSize() > 0) {
sinfo << "Plotting component " << it->first()->GetName() << endmsg;
pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
++i;
}
}
pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
// =10^(ln(11)/ln(10)-0.5)
//plot_frame_pull->SetMinimum(0.5);
plot_frame_pull->SetMinimum(0.5);
plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
if (sc_y == kLinear || sc_y == kBoth) {
doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
}
plot_frame_pull->SetMinimum(min_plot);
if (sc_y == kLogarithmic || sc_y == kBoth) {
doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
}
delete plot_frame_pull;
}
plot_frame->SetMinimum(0.0);
plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
if (sc_y == kLinear || sc_y == kBoth) {
doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
}
plot_frame->SetMinimum(min_plot);
if (sc_y == kLogarithmic || sc_y == kBoth) {
doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
}
delete plot_frame;
}
Plot::~Plot() {}
} // namespace plotting
} // namespace doofit
<|endoftext|> |
<commit_before>#include "country.hpp"
#include "../version/version.hpp"
#include "../platform/platform.hpp"
#include "../indexer/data_header.hpp"
#include "../coding/streams_sink.hpp"
#include "../coding/file_reader.hpp"
#include "../coding/file_writer.hpp"
#include "../coding/file_container.hpp"
#include "../base/logging.hpp"
#include "../base/std_serialization.hpp"
#include "../base/string_utils.hpp"
#include "../std/fstream.hpp"
#include "../std/ctime.hpp"
namespace storage
{
/// Simple check - compare url size with real file size on disk
bool IsTileDownloaded(TTile const & tile)
{
uint64_t size = 0;
if (!GetPlatform().GetFileSize(GetPlatform().WritablePathForFile(tile.first), size))
return false;
return true;//tile.second == size;
}
struct CountryBoundsCalculator
{
m2::RectD & m_bounds;
CountryBoundsCalculator(m2::RectD & bounds) : m_bounds(bounds) {}
void operator()(TTile const & tile)
{
feature::DataHeader header;
FilesContainerR reader(GetPlatform().WritablePathForFile(tile.first));
header.Load(reader.GetReader(HEADER_FILE_TAG));
m_bounds.Add(header.GetBounds());
}
};
m2::RectD Country::Bounds() const
{
m2::RectD bounds;
std::for_each(m_tiles.begin(), m_tiles.end(), CountryBoundsCalculator(bounds));
return bounds;
}
struct SizeCalculator
{
uint64_t & m_localSize;
uint64_t & m_remoteSize;
SizeCalculator(uint64_t & localSize, uint64_t & remoteSize)
: m_localSize(localSize), m_remoteSize(remoteSize) {}
void operator()(TTile const & tile)
{
if (IsTileDownloaded(tile))
m_localSize += tile.second;
m_remoteSize += tile.second;
}
};
TLocalAndRemoteSize Country::Size() const
{
uint64_t localSize = 0;
uint64_t remoteSize = 0;
std::for_each(m_tiles.begin(), m_tiles.end(), SizeCalculator(localSize, remoteSize));
return TLocalAndRemoteSize(localSize, remoteSize);
}
void Country::AddTile(TTile const & tile)
{
m_tiles.push_back(tile);
}
////////////////////////////////////////////////////////////////////////
// template <class TArchive> TArchive & operator << (TArchive & ar, storage::Country const & country)
// {
// ar << country.m_name;
// ar << country.m_tiles;
// return ar;
// }
inline bool IsCellId(string const & cellId)
{
size_t const size = cellId.size();
if (size == 0)
return false;
for (size_t i = 0; i < size; ++i)
{
if (cellId[i] < '0' || cellId[i] > '3')
return false;
}
return true;
}
bool LoadCountries(file_t const & file, TTilesContainer const & sortedTiles,
TCountriesContainer & countries)
{
countries.Clear();
string buffer;
file.ReadAsString(buffer);
istringstream stream(buffer);
std::string line;
Country * currentCountry = &countries.Value();
while (stream.good())
{
std::getline(stream, line);
if (line.empty())
continue;
// calculate spaces - depth inside the tree
int spaces = 0;
for (size_t i = 0; i < line.size(); ++i)
{
if (line[i] == ' ')
++spaces;
else
break;
}
switch (spaces)
{
case 0:
CHECK(false, ("We should never be here"));
break;
case 1: // country group
case 2: // country name
case 3: // region
{
line = line.substr(spaces);
strings::SimpleTokenizer tokIt(line, "|");
// first string is country name, not always equal to country file name
currentCountry = &countries.AddAtDepth(spaces - 1, Country(*tokIt));
// skip if > 1 names in the list - first name never corresponds to tile file
if (!tokIt.IsLast())
++tokIt;
while (tokIt)
{
TTilesContainer::const_iterator const first = sortedTiles.begin();
TTilesContainer::const_iterator const last = sortedTiles.end();
string const nameWithExt = *tokIt + DATA_FILE_EXTENSION;
TTilesContainer::const_iterator found = lower_bound(
first, last, TTile(nameWithExt, 0));
if (found != last && !(nameWithExt < found->first))
currentCountry->AddTile(*found);
++tokIt;
}
}
break;
default:
return false;
}
}
return countries.SiblingsCount() > 0;
}
void SaveTiles(string const & file, int32_t level, TDataFiles const & cellFiles, TCommonFiles const & commonFiles)
{
FileWriter writer(file);
stream::SinkWriterStream<Writer> wStream(writer);
// save version - it's equal to current date in GMT
time_t rawTime = time(NULL);
tm * pTm = gmtime(&rawTime);
uint32_t const version = (pTm->tm_year - 100) * 10000 + (pTm->tm_mon + 1) * 100 + pTm->tm_mday;
wStream << static_cast<uint32_t>(version);
wStream << level;
wStream << cellFiles;
wStream << commonFiles;
}
bool LoadTiles(file_t const & file, TTilesContainer & tiles, uint32_t & dataVersion)
{
tiles.clear();
try
{
ReaderSource<file_t> source(file);
stream::SinkReaderStream<ReaderSource<file_t> > stream(source);
TDataFiles dataFiles;
TCommonFiles commonFiles;
int32_t level = -1;
stream >> dataVersion;
stream >> level;
stream >> dataFiles;
stream >> commonFiles;
tiles.reserve(dataFiles.size() + commonFiles.size());
for (TDataFiles::iterator it = dataFiles.begin(); it != dataFiles.end(); ++it)
tiles.push_back(TTile(CountryCellId::FromBitsAndLevel(it->first, level).ToString(), it->second));
for (TCommonFiles::iterator it = commonFiles.begin(); it != commonFiles.end(); ++it)
tiles.push_back(TTile(it->first, it->second));
sort(tiles.begin(), tiles.end());
}
catch (RootException const & e)
{
LOG(LWARNING, ("Can't read tiles file", e.what()));
return false;
}
return true;
}
// void SaveCountries(TCountriesContainer const & countries, Writer & writer)
// {
// stream::SinkWriterStream<Writer> wStream(writer);
// wStream << MAPS_MAJOR_VERSION_BINARY_FORMAT;
// wStream << countries;
// }
}
<commit_msg>Added const qualifier<commit_after>#include "country.hpp"
#include "../version/version.hpp"
#include "../platform/platform.hpp"
#include "../indexer/data_header.hpp"
#include "../coding/streams_sink.hpp"
#include "../coding/file_reader.hpp"
#include "../coding/file_writer.hpp"
#include "../coding/file_container.hpp"
#include "../base/logging.hpp"
#include "../base/std_serialization.hpp"
#include "../base/string_utils.hpp"
#include "../std/fstream.hpp"
#include "../std/ctime.hpp"
namespace storage
{
/// Simple check - compare url size with real file size on disk
bool IsTileDownloaded(TTile const & tile)
{
uint64_t size = 0;
if (!GetPlatform().GetFileSize(GetPlatform().WritablePathForFile(tile.first), size))
return false;
return true;//tile.second == size;
}
struct CountryBoundsCalculator
{
m2::RectD & m_bounds;
CountryBoundsCalculator(m2::RectD & bounds) : m_bounds(bounds) {}
void operator()(TTile const & tile)
{
feature::DataHeader header;
FilesContainerR reader(GetPlatform().WritablePathForFile(tile.first));
header.Load(reader.GetReader(HEADER_FILE_TAG));
m_bounds.Add(header.GetBounds());
}
};
m2::RectD Country::Bounds() const
{
m2::RectD bounds;
std::for_each(m_tiles.begin(), m_tiles.end(), CountryBoundsCalculator(bounds));
return bounds;
}
struct SizeCalculator
{
uint64_t & m_localSize;
uint64_t & m_remoteSize;
SizeCalculator(uint64_t & localSize, uint64_t & remoteSize)
: m_localSize(localSize), m_remoteSize(remoteSize) {}
void operator()(TTile const & tile)
{
if (IsTileDownloaded(tile))
m_localSize += tile.second;
m_remoteSize += tile.second;
}
};
TLocalAndRemoteSize Country::Size() const
{
uint64_t localSize = 0;
uint64_t remoteSize = 0;
std::for_each(m_tiles.begin(), m_tiles.end(), SizeCalculator(localSize, remoteSize));
return TLocalAndRemoteSize(localSize, remoteSize);
}
void Country::AddTile(TTile const & tile)
{
m_tiles.push_back(tile);
}
////////////////////////////////////////////////////////////////////////
// template <class TArchive> TArchive & operator << (TArchive & ar, storage::Country const & country)
// {
// ar << country.m_name;
// ar << country.m_tiles;
// return ar;
// }
inline bool IsCellId(string const & cellId)
{
size_t const size = cellId.size();
if (size == 0)
return false;
for (size_t i = 0; i < size; ++i)
{
if (cellId[i] < '0' || cellId[i] > '3')
return false;
}
return true;
}
bool LoadCountries(file_t const & file, TTilesContainer const & sortedTiles,
TCountriesContainer & countries)
{
countries.Clear();
string buffer;
file.ReadAsString(buffer);
istringstream stream(buffer);
std::string line;
Country * currentCountry = &countries.Value();
while (stream.good())
{
std::getline(stream, line);
if (line.empty())
continue;
// calculate spaces - depth inside the tree
int spaces = 0;
for (size_t i = 0; i < line.size(); ++i)
{
if (line[i] == ' ')
++spaces;
else
break;
}
switch (spaces)
{
case 0:
CHECK(false, ("We should never be here"));
break;
case 1: // country group
case 2: // country name
case 3: // region
{
line = line.substr(spaces);
strings::SimpleTokenizer tokIt(line, "|");
// first string is country name, not always equal to country file name
currentCountry = &countries.AddAtDepth(spaces - 1, Country(*tokIt));
// skip if > 1 names in the list - first name never corresponds to tile file
if (!tokIt.IsLast())
++tokIt;
while (tokIt)
{
TTilesContainer::const_iterator const first = sortedTiles.begin();
TTilesContainer::const_iterator const last = sortedTiles.end();
string const nameWithExt = *tokIt + DATA_FILE_EXTENSION;
TTilesContainer::const_iterator const found = lower_bound(
first, last, TTile(nameWithExt, 0));
if (found != last && !(nameWithExt < found->first))
currentCountry->AddTile(*found);
++tokIt;
}
}
break;
default:
return false;
}
}
return countries.SiblingsCount() > 0;
}
void SaveTiles(string const & file, int32_t level, TDataFiles const & cellFiles, TCommonFiles const & commonFiles)
{
FileWriter writer(file);
stream::SinkWriterStream<Writer> wStream(writer);
// save version - it's equal to current date in GMT
time_t rawTime = time(NULL);
tm * pTm = gmtime(&rawTime);
uint32_t const version = (pTm->tm_year - 100) * 10000 + (pTm->tm_mon + 1) * 100 + pTm->tm_mday;
wStream << static_cast<uint32_t>(version);
wStream << level;
wStream << cellFiles;
wStream << commonFiles;
}
bool LoadTiles(file_t const & file, TTilesContainer & tiles, uint32_t & dataVersion)
{
tiles.clear();
try
{
ReaderSource<file_t> source(file);
stream::SinkReaderStream<ReaderSource<file_t> > stream(source);
TDataFiles dataFiles;
TCommonFiles commonFiles;
int32_t level = -1;
stream >> dataVersion;
stream >> level;
stream >> dataFiles;
stream >> commonFiles;
tiles.reserve(dataFiles.size() + commonFiles.size());
for (TDataFiles::iterator it = dataFiles.begin(); it != dataFiles.end(); ++it)
tiles.push_back(TTile(CountryCellId::FromBitsAndLevel(it->first, level).ToString(), it->second));
for (TCommonFiles::iterator it = commonFiles.begin(); it != commonFiles.end(); ++it)
tiles.push_back(TTile(it->first, it->second));
sort(tiles.begin(), tiles.end());
}
catch (RootException const & e)
{
LOG(LWARNING, ("Can't read tiles file", e.what()));
return false;
}
return true;
}
// void SaveCountries(TCountriesContainer const & countries, Writer & writer)
// {
// stream::SinkWriterStream<Writer> wStream(writer);
// wStream << MAPS_MAJOR_VERSION_BINARY_FORMAT;
// wStream << countries;
// }
}
<|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/net/load_timing_observer.h"
#include "base/time.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
using base::Time;
using base::TimeTicks;
using webkit_glue::ResourceLoaderBridge;
using webkit_glue::ResourceLoadTimingInfo;
const size_t kMaxNumEntries = 1000;
namespace {
// We know that this conversion is not solid and suffers from world clock
// changes, but it should be good enough for the load timing info.
static Time TimeTicksToTime(const TimeTicks& time_ticks) {
static int64 tick_to_time_offset;
static bool tick_to_time_offset_available = false;
if (!tick_to_time_offset_available) {
int64 cur_time = (Time::Now() - Time()).InMicroseconds();
int64 cur_time_ticks = (TimeTicks::Now() - TimeTicks()).InMicroseconds();
// If we add this number to a time tick value, it gives the timestamp.
tick_to_time_offset = cur_time - cur_time_ticks;
tick_to_time_offset_available = true;
}
return Time::FromInternalValue(time_ticks.ToInternalValue() +
tick_to_time_offset);
}
static int32 TimeTicksToOffset(
const TimeTicks& time_ticks,
LoadTimingObserver::URLRequestRecord* record) {
return static_cast<int32>(
(time_ticks - record->base_ticks).InMillisecondsRoundedUp());
}
} // namespace
LoadTimingObserver::URLRequestRecord::URLRequestRecord()
: connect_job_id(net::NetLog::Source::kInvalidId),
socket_log_id(net::NetLog::Source::kInvalidId),
socket_reused(false) {
}
LoadTimingObserver::LoadTimingObserver()
: ThreadSafeObserver(net::NetLog::LOG_BASIC),
last_connect_job_id_(net::NetLog::Source::kInvalidId) {
}
LoadTimingObserver::~LoadTimingObserver() {
}
LoadTimingObserver::URLRequestRecord*
LoadTimingObserver::GetURLRequestRecord(uint32 source_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
URLRequestToRecordMap::iterator it = url_request_to_record_.find(source_id);
if (it != url_request_to_record_.end())
return &it->second;
return NULL;
}
void LoadTimingObserver::OnAddEntry(net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
// The events that the Observer is interested in only occur on the IO thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
return;
if (source.type == net::NetLog::SOURCE_URL_REQUEST)
OnAddURLRequestEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_CONNECT_JOB)
OnAddConnectJobEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_SOCKET)
OnAddSocketEntry(type, time, source, phase, params);
}
// static
void LoadTimingObserver::PopulateTimingInfo(net::URLRequest* request,
ResourceResponse* response) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))
return;
ChromeNetLog* chrome_net_log = static_cast<ChromeNetLog*>(
request->net_log().net_log());
if (chrome_net_log == NULL)
return;
uint32 source_id = request->net_log().source().id;
LoadTimingObserver* observer = chrome_net_log->load_timing_observer();
LoadTimingObserver::URLRequestRecord* record =
observer->GetURLRequestRecord(source_id);
if (record) {
response->response_head.connection_id = record->socket_log_id;
response->response_head.connection_reused = record->socket_reused;
response->response_head.load_timing = record->timing;
}
}
void LoadTimingObserver::OnAddURLRequestEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
if (is_begin) {
// Only record timing for entries with corresponding flag.
int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
load_flags();
if (!(load_flags & net::LOAD_ENABLE_LOAD_TIMING))
return;
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (url_request_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer url request count has grown "
"larger than expected, resetting";
url_request_to_record_.clear();
}
URLRequestRecord& record = url_request_to_record_[source.id];
record.base_ticks = time;
record.timing.base_time = TimeTicksToTime(time);
}
return;
} else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
// Cleanup records based on the TYPE_REQUEST_ALIVE entry.
if (is_end)
url_request_to_record_.erase(source.id);
return;
}
URLRequestRecord* record = GetURLRequestRecord(source.id);
if (!record)
return;
ResourceLoadTimingInfo& timing = record->timing;
switch (type) {
case net::NetLog::TYPE_PROXY_SERVICE:
if (is_begin)
timing.proxy_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.proxy_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL:
if (is_begin)
timing.connect_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.connect_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB:
{
uint32 connect_job_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (last_connect_job_id_ == connect_job_id &&
!last_connect_job_record_.dns_start.is_null()) {
timing.dns_start =
TimeTicksToOffset(last_connect_job_record_.dns_start, record);
timing.dns_end =
TimeTicksToOffset(last_connect_job_record_.dns_end, record);
}
}
break;
case net::NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET:
record->socket_reused = true;
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET:
record->socket_log_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (!record->socket_reused) {
SocketToRecordMap::iterator it =
socket_to_record_.find(record->socket_log_id);
if (it != socket_to_record_.end() && !it->second.ssl_start.is_null()) {
timing.ssl_start = TimeTicksToOffset(it->second.ssl_start, record);
timing.ssl_end = TimeTicksToOffset(it->second.ssl_end, record);
}
}
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST:
if (is_begin)
timing.send_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.send_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS:
if (is_begin)
timing.receive_headers_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.receive_headers_end = TimeTicksToOffset(time, record);
break;
default:
break;
}
}
void LoadTimingObserver::OnAddConnectJobEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_POOL_CONNECT_JOB entry.
if (type == net::NetLog::TYPE_SOCKET_POOL_CONNECT_JOB) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (connect_job_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer connect job count has grown "
"larger than expected, resetting";
connect_job_to_record_.clear();
}
connect_job_to_record_.insert(
std::make_pair(source.id, ConnectJobRecord()));
} else if (is_end) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
last_connect_job_id_ = it->first;
last_connect_job_record_ = it->second;
connect_job_to_record_.erase(it);
}
}
} else if (type == net::NetLog::TYPE_HOST_RESOLVER_IMPL) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
if (is_begin)
it->second.dns_start = time;
else if (is_end)
it->second.dns_end = time;
}
}
}
void LoadTimingObserver::OnAddSocketEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_ALIVE entry.
if (type == net::NetLog::TYPE_SOCKET_ALIVE) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (socket_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer socket count has grown "
"larger than expected, resetting";
socket_to_record_.clear();
}
socket_to_record_.insert(
std::make_pair(source.id, SocketRecord()));
} else if (is_end) {
socket_to_record_.erase(source.id);
}
return;
}
SocketToRecordMap::iterator it = socket_to_record_.find(source.id);
if (it == socket_to_record_.end())
return;
if (type == net::NetLog::TYPE_SSL_CONNECT) {
if (is_begin)
it->second.ssl_start = time;
else if (is_end)
it->second.ssl_end = time;
}
}
<commit_msg>DevTools: Network requests are timed with 1.6 days.<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/net/load_timing_observer.h"
#include "base/time.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
using base::Time;
using base::TimeTicks;
using webkit_glue::ResourceLoaderBridge;
using webkit_glue::ResourceLoadTimingInfo;
const size_t kMaxNumEntries = 1000;
namespace {
const int64 kSyncPeriodMicroseconds = 1000 * 1000 * 10;
// We know that this conversion is not solid and suffers from world clock
// changes, but given that we sync clock every 10 seconds, it should be good
// enough for the load timing info.
static Time TimeTicksToTime(const TimeTicks& time_ticks) {
static int64 tick_to_time_offset;
static int64 last_sync_ticks = 0;
if (time_ticks.ToInternalValue() - last_sync_ticks >
kSyncPeriodMicroseconds) {
int64 cur_time = (Time::Now() - Time()).InMicroseconds();
int64 cur_time_ticks = (TimeTicks::Now() - TimeTicks()).InMicroseconds();
// If we add this number to a time tick value, it gives the timestamp.
tick_to_time_offset = cur_time - cur_time_ticks;
last_sync_ticks = time_ticks.ToInternalValue();
}
return Time::FromInternalValue(time_ticks.ToInternalValue() +
tick_to_time_offset);
}
static int32 TimeTicksToOffset(
const TimeTicks& time_ticks,
LoadTimingObserver::URLRequestRecord* record) {
return static_cast<int32>(
(time_ticks - record->base_ticks).InMillisecondsRoundedUp());
}
} // namespace
LoadTimingObserver::URLRequestRecord::URLRequestRecord()
: connect_job_id(net::NetLog::Source::kInvalidId),
socket_log_id(net::NetLog::Source::kInvalidId),
socket_reused(false) {
}
LoadTimingObserver::LoadTimingObserver()
: ThreadSafeObserver(net::NetLog::LOG_BASIC),
last_connect_job_id_(net::NetLog::Source::kInvalidId) {
}
LoadTimingObserver::~LoadTimingObserver() {
}
LoadTimingObserver::URLRequestRecord*
LoadTimingObserver::GetURLRequestRecord(uint32 source_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
URLRequestToRecordMap::iterator it = url_request_to_record_.find(source_id);
if (it != url_request_to_record_.end())
return &it->second;
return NULL;
}
void LoadTimingObserver::OnAddEntry(net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
// The events that the Observer is interested in only occur on the IO thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
return;
if (source.type == net::NetLog::SOURCE_URL_REQUEST)
OnAddURLRequestEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_CONNECT_JOB)
OnAddConnectJobEntry(type, time, source, phase, params);
else if (source.type == net::NetLog::SOURCE_SOCKET)
OnAddSocketEntry(type, time, source, phase, params);
}
// static
void LoadTimingObserver::PopulateTimingInfo(net::URLRequest* request,
ResourceResponse* response) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!(request->load_flags() & net::LOAD_ENABLE_LOAD_TIMING))
return;
ChromeNetLog* chrome_net_log = static_cast<ChromeNetLog*>(
request->net_log().net_log());
if (chrome_net_log == NULL)
return;
uint32 source_id = request->net_log().source().id;
LoadTimingObserver* observer = chrome_net_log->load_timing_observer();
LoadTimingObserver::URLRequestRecord* record =
observer->GetURLRequestRecord(source_id);
if (record) {
response->response_head.connection_id = record->socket_log_id;
response->response_head.connection_reused = record->socket_reused;
response->response_head.load_timing = record->timing;
}
}
void LoadTimingObserver::OnAddURLRequestEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
if (is_begin) {
// Only record timing for entries with corresponding flag.
int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
load_flags();
if (!(load_flags & net::LOAD_ENABLE_LOAD_TIMING))
return;
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (url_request_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer url request count has grown "
"larger than expected, resetting";
url_request_to_record_.clear();
}
URLRequestRecord& record = url_request_to_record_[source.id];
record.base_ticks = time;
record.timing.base_time = TimeTicksToTime(time);
}
return;
} else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
// Cleanup records based on the TYPE_REQUEST_ALIVE entry.
if (is_end)
url_request_to_record_.erase(source.id);
return;
}
URLRequestRecord* record = GetURLRequestRecord(source.id);
if (!record)
return;
ResourceLoadTimingInfo& timing = record->timing;
switch (type) {
case net::NetLog::TYPE_PROXY_SERVICE:
if (is_begin)
timing.proxy_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.proxy_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL:
if (is_begin)
timing.connect_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.connect_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB:
{
uint32 connect_job_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (last_connect_job_id_ == connect_job_id &&
!last_connect_job_record_.dns_start.is_null()) {
timing.dns_start =
TimeTicksToOffset(last_connect_job_record_.dns_start, record);
timing.dns_end =
TimeTicksToOffset(last_connect_job_record_.dns_end, record);
}
}
break;
case net::NetLog::TYPE_SOCKET_POOL_REUSED_AN_EXISTING_SOCKET:
record->socket_reused = true;
break;
case net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET:
record->socket_log_id = static_cast<net::NetLogSourceParameter*>(
params)->value().id;
if (!record->socket_reused) {
SocketToRecordMap::iterator it =
socket_to_record_.find(record->socket_log_id);
if (it != socket_to_record_.end() && !it->second.ssl_start.is_null()) {
timing.ssl_start = TimeTicksToOffset(it->second.ssl_start, record);
timing.ssl_end = TimeTicksToOffset(it->second.ssl_end, record);
}
}
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST:
if (is_begin)
timing.send_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.send_end = TimeTicksToOffset(time, record);
break;
case net::NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS:
if (is_begin)
timing.receive_headers_start = TimeTicksToOffset(time, record);
else if (is_end)
timing.receive_headers_end = TimeTicksToOffset(time, record);
break;
default:
break;
}
}
void LoadTimingObserver::OnAddConnectJobEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_POOL_CONNECT_JOB entry.
if (type == net::NetLog::TYPE_SOCKET_POOL_CONNECT_JOB) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (connect_job_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer connect job count has grown "
"larger than expected, resetting";
connect_job_to_record_.clear();
}
connect_job_to_record_.insert(
std::make_pair(source.id, ConnectJobRecord()));
} else if (is_end) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
last_connect_job_id_ = it->first;
last_connect_job_record_ = it->second;
connect_job_to_record_.erase(it);
}
}
} else if (type == net::NetLog::TYPE_HOST_RESOLVER_IMPL) {
ConnectJobToRecordMap::iterator it =
connect_job_to_record_.find(source.id);
if (it != connect_job_to_record_.end()) {
if (is_begin)
it->second.dns_start = time;
else if (is_end)
it->second.dns_end = time;
}
}
}
void LoadTimingObserver::OnAddSocketEntry(
net::NetLog::EventType type,
const base::TimeTicks& time,
const net::NetLog::Source& source,
net::NetLog::EventPhase phase,
net::NetLog::EventParameters* params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool is_begin = phase == net::NetLog::PHASE_BEGIN;
bool is_end = phase == net::NetLog::PHASE_END;
// Manage record lifetime based on the SOCKET_ALIVE entry.
if (type == net::NetLog::TYPE_SOCKET_ALIVE) {
if (is_begin) {
// Prevents us from passively growing the memory memory unbounded in case
// something went wrong. Should not happen.
if (socket_to_record_.size() > kMaxNumEntries) {
LOG(WARNING) << "The load timing observer socket count has grown "
"larger than expected, resetting";
socket_to_record_.clear();
}
socket_to_record_.insert(
std::make_pair(source.id, SocketRecord()));
} else if (is_end) {
socket_to_record_.erase(source.id);
}
return;
}
SocketToRecordMap::iterator it = socket_to_record_.find(source.id);
if (it == socket_to_record_.end())
return;
if (type == net::NetLog::TYPE_SSL_CONNECT) {
if (is_begin)
it->second.ssl_start = time;
else if (is_end)
it->second.ssl_end = time;
}
}
<|endoftext|> |
<commit_before>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <exception>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include "anh/logger.h"
#include "swganh/app/swganh_app.h"
#include "swganh/scripting/utilities.h"
#include "version.h"
using namespace boost;
using namespace swganh;
using namespace std;
int main(int argc, char* argv[])
{
Py_Initialize();
PyEval_InitThreads();
// Step 2: Release the GIL from the main thread so that other threads can use it
PyEval_ReleaseThread(PyGILState_GetThisThreadState());
try {
app::SwganhApp app;
app.Initialize(argc, argv);
app.Start();
for (;;) {
string cmd;
cin >> cmd;
if (cmd.compare("exit") == 0 || cmd.compare("quit") == 0 || cmd.compare("q") == 0) {
LOG(info) << "Exit command received from command line. Shutting down.";
// Stop the application and join the thread until it's finished.
app.Stop();
break;
} else if(cmd.compare("console") == 0) {
anh::Logger::getInstance().DisableConsoleLogging();
std::system("cls");
std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl;
swganh::scripting::ScopedGilLock lock;
PyRun_InteractiveLoop(stdin, "<stdin>");
anh::Logger::getInstance().EnableConsoleLogging();
} else {
LOG(warning) << "Invalid command received: " << cmd;
std::cout << "Type exit or (q)uit to quit" << std::endl;
}
}
} catch(std::exception& e) {
LOG(fatal) << "Unhandled application exception occurred: " << e.what();
}
// Step 4: Lock the GIL before calling finalize
PyGILState_Ensure();
Py_Finalize();
return 0;
}
<commit_msg>Add the kernel to the dictionary<commit_after>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2011 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <exception>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/python.hpp>
#include "anh/logger.h"
#include "swganh/app/swganh_app.h"
#include "swganh/scripting/utilities.h"
#include "version.h"
using namespace boost;
using namespace swganh;
using namespace std;
int main(int argc, char* argv[])
{
Py_Initialize();
PyEval_InitThreads();
// Step 2: Release the GIL from the main thread so that other threads can use it
PyEval_ReleaseThread(PyGILState_GetThisThreadState());
try {
app::SwganhApp app;
app.Initialize(argc, argv);
app.Start();
for (;;) {
string cmd;
cin >> cmd;
if (cmd.compare("exit") == 0 || cmd.compare("quit") == 0 || cmd.compare("q") == 0) {
LOG(info) << "Exit command received from command line. Shutting down.";
// Stop the application and join the thread until it's finished.
app.Stop();
break;
} else if(cmd.compare("console") == 0) {
swganh::scripting::ScopedGilLock lock;
anh::Logger::getInstance().DisableConsoleLogging();
std::system("cls");
std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl;
boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
PyImport_AddModule("__main__")
)));
auto global_dict = main.attr("__dict__");
global_dict["kernel"] = boost::python::ptr(app.GetAppKernel());
PyRun_InteractiveLoop(stdin, "<stdin>");
anh::Logger::getInstance().EnableConsoleLogging();
} else {
LOG(warning) << "Invalid command received: " << cmd;
std::cout << "Type exit or (q)uit to quit" << std::endl;
}
}
} catch(std::exception& e) {
LOG(fatal) << "Unhandled application exception occurred: " << e.what();
}
// Step 4: Lock the GIL before calling finalize
PyGILState_Ensure();
Py_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include "storage.hpp"
#include "../base/logging.hpp"
#include "../base/string_utils.hpp"
#include "../indexer/data_header.hpp"
#include "../coding/file_writer.hpp"
#include "../coding/file_reader.hpp"
#include "../coding/file_container.hpp"
#include "../coding/strutil.hpp"
#include "../version/version.hpp"
#include "../std/set.hpp"
#include "../std/algorithm.hpp"
#include "../std/target_os.hpp"
#include <boost/bind.hpp>
#include "../base/start_mem_debug.hpp"
namespace storage
{
const int TIndex::INVALID = -1;
static string ErrorString(DownloadResult res)
{
switch (res)
{
case EHttpDownloadCantCreateFile:
return "File can't be created. Probably, you have no disk space available or "
"using read-only file system.";
case EHttpDownloadFailed:
return "Download failed due to missing or poor connection. "
"Please, try again later.";
case EHttpDownloadFileIsLocked:
return "Download can't be finished because file is locked. "
"Please, try again after restarting application.";
case EHttpDownloadFileNotFound:
return "Requested file is absent on the server.";
case EHttpDownloadNoConnectionAvailable:
return "No network connection is available.";
case EHttpDownloadOk:
return "Download finished successfully.";
}
return "Unknown error";
}
////////////////////////////////////////////////////////////////////////////
void Storage::Init(TAddMapFunction addFunc, TRemoveMapFunction removeFunc, TUpdateRectFunction updateRectFunc)
{
m_currentVersion = static_cast<uint32_t>(Version::BUILD);
m_addMap = addFunc;
m_removeMap = removeFunc;
m_updateRect = updateRectFunc;
// activate all downloaded maps
Platform & p = GetPlatform();
Platform::FilesList filesList;
string const dataPath = p.WritableDir();
p.GetFilesInDir(dataPath, "*" DATA_FILE_EXTENSION, filesList);
for (Platform::FilesList::iterator it = filesList.begin(); it != filesList.end(); ++it)
{ // simple way to avoid continuous crashes with invalid data files
try {
m_addMap(dataPath + *it);
} catch (std::exception const & e)
{
FileWriter::DeleteFileX(dataPath + *it);
LOG(LWARNING, (e.what(), "while adding file", *it, "so this file is deleted"));
}
}
}
string Storage::UpdateBaseUrl() const
{
return UPDATE_BASE_URL OMIM_OS_NAME "/" + utils::to_string(m_currentVersion) + "/";
}
TCountriesContainer const & NodeFromIndex(TCountriesContainer const & root, TIndex const & index)
{
// complex logic to avoid [] out_of_bounds exceptions
if (index.m_group == TIndex::INVALID || index.m_group >= static_cast<int>(root.SiblingsCount()))
return root;
else
{
if (index.m_country == TIndex::INVALID || index.m_country >= static_cast<int>(root[index.m_group].SiblingsCount()))
return root[index.m_group];
if (index.m_region == TIndex::INVALID || index.m_region >= static_cast<int>(root[index.m_group][index.m_country].SiblingsCount()))
return root[index.m_group][index.m_country];
return root[index.m_group][index.m_country][index.m_region];
}
}
Country const & Storage::CountryByIndex(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).Value();
}
size_t Storage::CountriesCount(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).SiblingsCount();
}
string Storage::CountryName(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).Value().Name();
}
TLocalAndRemoteSize Storage::CountrySizeInBytes(TIndex const & index) const
{
return CountryByIndex(index).Size();
}
TStatus Storage::CountryStatus(TIndex const & index) const
{
// first, check if we already downloading this country or have in in the queue
TQueue::const_iterator found = std::find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{
if (found == m_queue.begin())
return EDownloading;
else
return EInQueue;
}
// second, check if this country has failed while downloading
if (m_failedCountries.find(index) != m_failedCountries.end())
return EDownloadFailed;
TLocalAndRemoteSize size = CountryByIndex(index).Size();
if (size.first == size.second)
{
if (size.second == 0)
return EUnknown;
else
return EOnDisk;
}
return ENotDownloaded;
}
void Storage::DownloadCountry(TIndex const & index)
{
// check if we already downloading this country
TQueue::const_iterator found = find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{ // do nothing
return;
}
// remove it from failed list
m_failedCountries.erase(index);
// add it into the queue
m_queue.push_back(index);
// and start download if necessary
if (m_queue.size() == 1)
{
// reset total country's download progress
TLocalAndRemoteSize size = CountryByIndex(index).Size();
m_countryProgress = TDownloadProgress(0, size.second);
DownloadNextCountryFromQueue();
}
else
{ // notify about "In Queue" status
if (m_observerChange)
m_observerChange(index);
}
}
template <class TRemoveFn>
class DeactivateMap
{
string m_workingDir;
TRemoveFn & m_removeFn;
public:
DeactivateMap(TRemoveFn & removeFn) : m_removeFn(removeFn)
{
m_workingDir = GetPlatform().WritableDir();
}
void operator()(TTile const & tile)
{
string const file = m_workingDir + tile.first;
m_removeFn(file);
}
};
void Storage::DownloadNextCountryFromQueue()
{
while (!m_queue.empty())
{
TIndex index = m_queue.front();
TTilesContainer const & tiles = CountryByIndex(index).Tiles();
for (TTilesContainer::const_iterator it = tiles.begin(); it != tiles.end(); ++it)
{
if (!IsTileDownloaded(*it))
{
GetDownloadManager().DownloadFile(
(UpdateBaseUrl() + UrlEncode(it->first)).c_str(),
(GetPlatform().WritablePathForFile(it->first).c_str()),
bind(&Storage::OnMapDownloadFinished, this, _1, _2),
bind(&Storage::OnMapDownloadProgress, this, _1, _2),
true); // enabled resume support by default
// notify GUI - new status for country, "Downloading"
if (m_observerChange)
m_observerChange(index);
return;
}
}
// continue with next country
m_queue.pop_front();
// reset total country's download progress
if (!m_queue.empty())
m_countryProgress = TDownloadProgress(0, CountryByIndex(m_queue.front()).Size().second);
// and notify GUI - new status for country, "OnDisk"
if (m_observerChange)
m_observerChange(index);
}
}
struct CancelDownloading
{
string const m_baseUrl;
CancelDownloading(string const & baseUrl) : m_baseUrl(baseUrl) {}
void operator()(TTile const & tile)
{
GetDownloadManager().CancelDownload((m_baseUrl + UrlEncode(tile.first)).c_str());
}
};
class DeleteMap
{
string m_workingDir;
public:
DeleteMap()
{
m_workingDir = GetPlatform().WritableDir();
}
/// @TODO do not delete other countries cells
void operator()(TTile const & tile)
{
FileWriter::DeleteFileX(m_workingDir + tile.first);
}
};
template <typename TRemoveFunc>
void DeactivateAndDeleteCountry(Country const & country, TRemoveFunc removeFunc)
{
// deactivate from multiindex
for_each(country.Tiles().begin(), country.Tiles().end(), DeactivateMap<TRemoveFunc>(removeFunc));
// delete from disk
for_each(country.Tiles().begin(), country.Tiles().end(), DeleteMap());
}
void Storage::DeleteCountry(TIndex const & index)
{
Country const & country = CountryByIndex(index);
m2::RectD bounds;
// check if we already downloading this country
TQueue::iterator found = find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{
if (found == m_queue.begin())
{ // stop download
for_each(country.Tiles().begin(), country.Tiles().end(), CancelDownloading(UpdateBaseUrl()));
// remove from the queue
m_queue.erase(found);
// start another download if the queue is not empty
DownloadNextCountryFromQueue();
}
else
{ // remove from the queue
m_queue.erase(found);
}
}
else
{
// bounds are only updated if country was already activated before
bounds = country.Bounds();
}
DeactivateAndDeleteCountry(country, m_removeMap);
if (m_observerChange)
m_observerChange(index);
if (bounds != m2::RectD::GetEmptyRect())
m_updateRect(bounds);
}
void Storage::ReInitCountries(bool forceReload)
{
if (forceReload)
m_countries.Clear();
if (m_countries.SiblingsCount() == 0)
{
TTilesContainer tiles;
if (LoadTiles(tiles, GetPlatform().ReadPathForFile(DATA_UPDATE_FILE), m_currentVersion))
{
if (!LoadCountries(GetPlatform().ReadPathForFile(COUNTRIES_FILE), tiles, m_countries))
{
LOG(LWARNING, ("Can't load countries file", COUNTRIES_FILE));
}
}
else
{
LOG(LWARNING, ("Can't load update file", DATA_UPDATE_FILE));
}
}
}
void Storage::Subscribe(TObserverChangeCountryFunction change, TObserverProgressFunction progress,
TUpdateRequestFunction updateRequest)
{
m_observerChange = change;
m_observerProgress = progress;
m_observerUpdateRequest = updateRequest;
ReInitCountries(false);
}
void Storage::Unsubscribe()
{
m_observerChange.clear();
m_observerProgress.clear();
m_observerUpdateRequest.clear();
}
string FileFromUrl(string const & url)
{
return UrlDecode(url.substr(url.find_last_of('/') + 1, string::npos));
}
void Storage::OnMapDownloadFinished(char const * url, DownloadResult result)
{
if (m_queue.empty())
{
ASSERT(false, ("Invalid url?", url));
return;
}
if (result != EHttpDownloadOk)
{
// remove failed country from the queue
TIndex failedIndex = m_queue.front();
m_queue.pop_front();
m_failedCountries.insert(failedIndex);
// notify GUI about failed country
if (m_observerChange)
m_observerChange(failedIndex);
}
else
{
TLocalAndRemoteSize size = CountryByIndex(m_queue.front()).Size();
if (size.second != 0)
m_countryProgress.first = size.first;
// activate downloaded map piece
string const datFile = GetPlatform().ReadPathForFile(FileFromUrl(url));
m_addMap(datFile);
feature::DataHeader header;
header.Load(FilesContainerR(datFile).GetReader(HEADER_FILE_TAG));
m_updateRect(header.GetBounds());
}
DownloadNextCountryFromQueue();
}
void Storage::OnMapDownloadProgress(char const * /*url*/, TDownloadProgress progress)
{
if (m_queue.empty())
{
ASSERT(false, ("queue can't be empty"));
return;
}
if (m_observerProgress)
m_observerProgress(m_queue.front(),
TDownloadProgress(m_countryProgress.first + progress.first, m_countryProgress.second));
}
void Storage::CheckForUpdate()
{
// at this moment we support only binary update checks
string const update = UpdateBaseUrl() + BINARY_UPDATE_FILE/*DATA_UPDATE_FILE*/;
GetDownloadManager().CancelDownload(update.c_str());
GetDownloadManager().DownloadFile(
update.c_str(),
(GetPlatform().WritablePathForFile(DATA_UPDATE_FILE)).c_str(),
bind(&Storage::OnBinaryUpdateCheckFinished, this, _1, _2),
TDownloadProgressFunction(), false);
}
void Storage::OnDataUpdateCheckFinished(char const * url, DownloadResult result)
{
if (result != EHttpDownloadOk)
{
LOG(LWARNING, ("Update check failed for url:", url));
if (m_observerUpdateRequest)
m_observerUpdateRequest(EDataCheckFailed, ErrorString(result));
}
else
{ // @TODO parse update file and notify GUI
}
// parse update file
// TCountriesContainer tempCountries;
// if (!LoadCountries(tempCountries, GetPlatform().WritablePathForFile(DATA_UPDATE_FILE)))
// {
// LOG(LWARNING, ("New application version should be downloaded, "
// "update file format can't be parsed"));
// // @TODO: report to GUI
// return;
// }
// // stop any active download, clear the queue, replace countries and notify GUI
// if (!m_queue.empty())
// {
// CancelCountryDownload(CountryByIndex(m_queue.front()));
// m_queue.clear();
// }
// m_countries.swap(tempCountries);
// // @TODO report to GUI about reloading all countries
// LOG(LINFO, ("Update check complete"));
}
void Storage::OnBinaryUpdateCheckFinished(char const * url, DownloadResult result)
{
if (result == EHttpDownloadFileNotFound)
{ // no binary update is available
if (m_observerUpdateRequest)
m_observerUpdateRequest(ENoAnyUpdateAvailable, "No update is available");
}
else if (result == EHttpDownloadOk)
{ // update is available!
try
{
if (m_observerUpdateRequest)
{
string const updateTextFilePath = GetPlatform().ReadPathForFile(FileFromUrl(url));
FileReader file(updateTextFilePath);
m_observerUpdateRequest(ENewBinaryAvailable, file.ReadAsText());
}
}
catch (std::exception const & e)
{
if (m_observerUpdateRequest)
m_observerUpdateRequest(EBinaryCheckFailed,
string("Error loading b-update text file ") + e.what());
}
}
else
{ // connection error
if (m_observerUpdateRequest)
m_observerUpdateRequest(EBinaryCheckFailed, ErrorString(result));
}
}
}
<commit_msg>Fixed World activation from resources<commit_after>#include "storage.hpp"
#include "../base/logging.hpp"
#include "../base/string_utils.hpp"
#include "../indexer/data_header.hpp"
#include "../coding/file_writer.hpp"
#include "../coding/file_reader.hpp"
#include "../coding/file_container.hpp"
#include "../coding/strutil.hpp"
#include "../version/version.hpp"
#include "../std/set.hpp"
#include "../std/algorithm.hpp"
#include "../std/target_os.hpp"
#include <boost/bind.hpp>
#include "../base/start_mem_debug.hpp"
namespace storage
{
const int TIndex::INVALID = -1;
static string ErrorString(DownloadResult res)
{
switch (res)
{
case EHttpDownloadCantCreateFile:
return "File can't be created. Probably, you have no disk space available or "
"using read-only file system.";
case EHttpDownloadFailed:
return "Download failed due to missing or poor connection. "
"Please, try again later.";
case EHttpDownloadFileIsLocked:
return "Download can't be finished because file is locked. "
"Please, try again after restarting application.";
case EHttpDownloadFileNotFound:
return "Requested file is absent on the server.";
case EHttpDownloadNoConnectionAvailable:
return "No network connection is available.";
case EHttpDownloadOk:
return "Download finished successfully.";
}
return "Unknown error";
}
////////////////////////////////////////////////////////////////////////////
void Storage::Init(TAddMapFunction addFunc, TRemoveMapFunction removeFunc, TUpdateRectFunction updateRectFunc)
{
m_currentVersion = static_cast<uint32_t>(Version::BUILD);
m_addMap = addFunc;
m_removeMap = removeFunc;
m_updateRect = updateRectFunc;
// activate all downloaded maps
Platform & p = GetPlatform();
Platform::FilesList filesList;
string const dataPath = p.WritableDir();
p.GetFilesInDir(dataPath, "*" DATA_FILE_EXTENSION, filesList);
for (Platform::FilesList::iterator it = filesList.begin(); it != filesList.end(); ++it)
{ // simple way to avoid continuous crashes with invalid data files
try {
m_addMap(dataPath + *it);
} catch (std::exception const & e)
{
FileWriter::DeleteFileX(dataPath + *it);
LOG(LWARNING, (e.what(), "while adding file", *it, "so this file is deleted"));
}
}
// separate code to activate world data file from resources
// if it's not found in writable data dir
Platform::FilesList::iterator found = std::find(filesList.begin(), filesList.end(),
string(WORLD_FILE_NAME DATA_FILE_EXTENSION));
if (found == filesList.end())
{
try {
m_addMap(p.ReadPathForFile(WORLD_FILE_NAME DATA_FILE_EXTENSION));
} catch (std::exception const & e)
{
LOG(LWARNING, (e.what(), "while adding world data file"));
}
}
}
string Storage::UpdateBaseUrl() const
{
return UPDATE_BASE_URL OMIM_OS_NAME "/" + utils::to_string(m_currentVersion) + "/";
}
TCountriesContainer const & NodeFromIndex(TCountriesContainer const & root, TIndex const & index)
{
// complex logic to avoid [] out_of_bounds exceptions
if (index.m_group == TIndex::INVALID || index.m_group >= static_cast<int>(root.SiblingsCount()))
return root;
else
{
if (index.m_country == TIndex::INVALID || index.m_country >= static_cast<int>(root[index.m_group].SiblingsCount()))
return root[index.m_group];
if (index.m_region == TIndex::INVALID || index.m_region >= static_cast<int>(root[index.m_group][index.m_country].SiblingsCount()))
return root[index.m_group][index.m_country];
return root[index.m_group][index.m_country][index.m_region];
}
}
Country const & Storage::CountryByIndex(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).Value();
}
size_t Storage::CountriesCount(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).SiblingsCount();
}
string Storage::CountryName(TIndex const & index) const
{
return NodeFromIndex(m_countries, index).Value().Name();
}
TLocalAndRemoteSize Storage::CountrySizeInBytes(TIndex const & index) const
{
return CountryByIndex(index).Size();
}
TStatus Storage::CountryStatus(TIndex const & index) const
{
// first, check if we already downloading this country or have in in the queue
TQueue::const_iterator found = std::find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{
if (found == m_queue.begin())
return EDownloading;
else
return EInQueue;
}
// second, check if this country has failed while downloading
if (m_failedCountries.find(index) != m_failedCountries.end())
return EDownloadFailed;
TLocalAndRemoteSize size = CountryByIndex(index).Size();
if (size.first == size.second)
{
if (size.second == 0)
return EUnknown;
else
return EOnDisk;
}
return ENotDownloaded;
}
void Storage::DownloadCountry(TIndex const & index)
{
// check if we already downloading this country
TQueue::const_iterator found = find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{ // do nothing
return;
}
// remove it from failed list
m_failedCountries.erase(index);
// add it into the queue
m_queue.push_back(index);
// and start download if necessary
if (m_queue.size() == 1)
{
// reset total country's download progress
TLocalAndRemoteSize size = CountryByIndex(index).Size();
m_countryProgress = TDownloadProgress(0, size.second);
DownloadNextCountryFromQueue();
}
else
{ // notify about "In Queue" status
if (m_observerChange)
m_observerChange(index);
}
}
template <class TRemoveFn>
class DeactivateMap
{
string m_workingDir;
TRemoveFn & m_removeFn;
public:
DeactivateMap(TRemoveFn & removeFn) : m_removeFn(removeFn)
{
m_workingDir = GetPlatform().WritableDir();
}
void operator()(TTile const & tile)
{
string const file = m_workingDir + tile.first;
m_removeFn(file);
}
};
void Storage::DownloadNextCountryFromQueue()
{
while (!m_queue.empty())
{
TIndex index = m_queue.front();
TTilesContainer const & tiles = CountryByIndex(index).Tiles();
for (TTilesContainer::const_iterator it = tiles.begin(); it != tiles.end(); ++it)
{
if (!IsTileDownloaded(*it))
{
GetDownloadManager().DownloadFile(
(UpdateBaseUrl() + UrlEncode(it->first)).c_str(),
(GetPlatform().WritablePathForFile(it->first).c_str()),
bind(&Storage::OnMapDownloadFinished, this, _1, _2),
bind(&Storage::OnMapDownloadProgress, this, _1, _2),
true); // enabled resume support by default
// notify GUI - new status for country, "Downloading"
if (m_observerChange)
m_observerChange(index);
return;
}
}
// continue with next country
m_queue.pop_front();
// reset total country's download progress
if (!m_queue.empty())
m_countryProgress = TDownloadProgress(0, CountryByIndex(m_queue.front()).Size().second);
// and notify GUI - new status for country, "OnDisk"
if (m_observerChange)
m_observerChange(index);
}
}
struct CancelDownloading
{
string const m_baseUrl;
CancelDownloading(string const & baseUrl) : m_baseUrl(baseUrl) {}
void operator()(TTile const & tile)
{
GetDownloadManager().CancelDownload((m_baseUrl + UrlEncode(tile.first)).c_str());
}
};
class DeleteMap
{
string m_workingDir;
public:
DeleteMap()
{
m_workingDir = GetPlatform().WritableDir();
}
/// @TODO do not delete other countries cells
void operator()(TTile const & tile)
{
FileWriter::DeleteFileX(m_workingDir + tile.first);
}
};
template <typename TRemoveFunc>
void DeactivateAndDeleteCountry(Country const & country, TRemoveFunc removeFunc)
{
// deactivate from multiindex
for_each(country.Tiles().begin(), country.Tiles().end(), DeactivateMap<TRemoveFunc>(removeFunc));
// delete from disk
for_each(country.Tiles().begin(), country.Tiles().end(), DeleteMap());
}
void Storage::DeleteCountry(TIndex const & index)
{
Country const & country = CountryByIndex(index);
m2::RectD bounds;
// check if we already downloading this country
TQueue::iterator found = find(m_queue.begin(), m_queue.end(), index);
if (found != m_queue.end())
{
if (found == m_queue.begin())
{ // stop download
for_each(country.Tiles().begin(), country.Tiles().end(), CancelDownloading(UpdateBaseUrl()));
// remove from the queue
m_queue.erase(found);
// start another download if the queue is not empty
DownloadNextCountryFromQueue();
}
else
{ // remove from the queue
m_queue.erase(found);
}
}
else
{
// bounds are only updated if country was already activated before
bounds = country.Bounds();
}
DeactivateAndDeleteCountry(country, m_removeMap);
if (m_observerChange)
m_observerChange(index);
if (bounds != m2::RectD::GetEmptyRect())
m_updateRect(bounds);
}
void Storage::ReInitCountries(bool forceReload)
{
if (forceReload)
m_countries.Clear();
if (m_countries.SiblingsCount() == 0)
{
TTilesContainer tiles;
if (LoadTiles(tiles, GetPlatform().ReadPathForFile(DATA_UPDATE_FILE), m_currentVersion))
{
if (!LoadCountries(GetPlatform().ReadPathForFile(COUNTRIES_FILE), tiles, m_countries))
{
LOG(LWARNING, ("Can't load countries file", COUNTRIES_FILE));
}
}
else
{
LOG(LWARNING, ("Can't load update file", DATA_UPDATE_FILE));
}
}
}
void Storage::Subscribe(TObserverChangeCountryFunction change, TObserverProgressFunction progress,
TUpdateRequestFunction updateRequest)
{
m_observerChange = change;
m_observerProgress = progress;
m_observerUpdateRequest = updateRequest;
ReInitCountries(false);
}
void Storage::Unsubscribe()
{
m_observerChange.clear();
m_observerProgress.clear();
m_observerUpdateRequest.clear();
}
string FileFromUrl(string const & url)
{
return UrlDecode(url.substr(url.find_last_of('/') + 1, string::npos));
}
void Storage::OnMapDownloadFinished(char const * url, DownloadResult result)
{
if (m_queue.empty())
{
ASSERT(false, ("Invalid url?", url));
return;
}
if (result != EHttpDownloadOk)
{
// remove failed country from the queue
TIndex failedIndex = m_queue.front();
m_queue.pop_front();
m_failedCountries.insert(failedIndex);
// notify GUI about failed country
if (m_observerChange)
m_observerChange(failedIndex);
}
else
{
TLocalAndRemoteSize size = CountryByIndex(m_queue.front()).Size();
if (size.second != 0)
m_countryProgress.first = size.first;
// activate downloaded map piece
string const datFile = GetPlatform().ReadPathForFile(FileFromUrl(url));
m_addMap(datFile);
feature::DataHeader header;
header.Load(FilesContainerR(datFile).GetReader(HEADER_FILE_TAG));
m_updateRect(header.GetBounds());
}
DownloadNextCountryFromQueue();
}
void Storage::OnMapDownloadProgress(char const * /*url*/, TDownloadProgress progress)
{
if (m_queue.empty())
{
ASSERT(false, ("queue can't be empty"));
return;
}
if (m_observerProgress)
m_observerProgress(m_queue.front(),
TDownloadProgress(m_countryProgress.first + progress.first, m_countryProgress.second));
}
void Storage::CheckForUpdate()
{
// at this moment we support only binary update checks
string const update = UpdateBaseUrl() + BINARY_UPDATE_FILE/*DATA_UPDATE_FILE*/;
GetDownloadManager().CancelDownload(update.c_str());
GetDownloadManager().DownloadFile(
update.c_str(),
(GetPlatform().WritablePathForFile(DATA_UPDATE_FILE)).c_str(),
bind(&Storage::OnBinaryUpdateCheckFinished, this, _1, _2),
TDownloadProgressFunction(), false);
}
void Storage::OnDataUpdateCheckFinished(char const * url, DownloadResult result)
{
if (result != EHttpDownloadOk)
{
LOG(LWARNING, ("Update check failed for url:", url));
if (m_observerUpdateRequest)
m_observerUpdateRequest(EDataCheckFailed, ErrorString(result));
}
else
{ // @TODO parse update file and notify GUI
}
// parse update file
// TCountriesContainer tempCountries;
// if (!LoadCountries(tempCountries, GetPlatform().WritablePathForFile(DATA_UPDATE_FILE)))
// {
// LOG(LWARNING, ("New application version should be downloaded, "
// "update file format can't be parsed"));
// // @TODO: report to GUI
// return;
// }
// // stop any active download, clear the queue, replace countries and notify GUI
// if (!m_queue.empty())
// {
// CancelCountryDownload(CountryByIndex(m_queue.front()));
// m_queue.clear();
// }
// m_countries.swap(tempCountries);
// // @TODO report to GUI about reloading all countries
// LOG(LINFO, ("Update check complete"));
}
void Storage::OnBinaryUpdateCheckFinished(char const * url, DownloadResult result)
{
if (result == EHttpDownloadFileNotFound)
{ // no binary update is available
if (m_observerUpdateRequest)
m_observerUpdateRequest(ENoAnyUpdateAvailable, "No update is available");
}
else if (result == EHttpDownloadOk)
{ // update is available!
try
{
if (m_observerUpdateRequest)
{
string const updateTextFilePath = GetPlatform().ReadPathForFile(FileFromUrl(url));
FileReader file(updateTextFilePath);
m_observerUpdateRequest(ENewBinaryAvailable, file.ReadAsText());
}
}
catch (std::exception const & e)
{
if (m_observerUpdateRequest)
m_observerUpdateRequest(EBinaryCheckFailed,
string("Error loading b-update text file ") + e.what());
}
}
else
{ // connection error
if (m_observerUpdateRequest)
m_observerUpdateRequest(EBinaryCheckFailed, ErrorString(result));
}
}
}
<|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/sync/notification_method.h"
#include "base/logging.h"
namespace browser_sync {
const NotificationMethod kDefaultNotificationMethod =
NOTIFICATION_SERVER;
std::string NotificationMethodToString(
NotificationMethod notification_method) {
switch (notification_method) {
case NOTIFICATION_LEGACY:
return "NOTIFICATION_LEGACY";
break;
case NOTIFICATION_TRANSITIONAL:
return "NOTIFICATION_TRANSITIONAL";
break;
case NOTIFICATION_NEW:
return "NOTIFICATION_NEW";
break;
case NOTIFICATION_SERVER:
return "NOTIFICATION_SERVER";
break;
default:
LOG(WARNING) << "Unknown value for notification method: "
<< notification_method;
break;
}
return "<unknown notification method>";
}
NotificationMethod StringToNotificationMethod(const std::string& str) {
if (str == "legacy") {
return NOTIFICATION_LEGACY;
} else if (str == "transitional") {
return NOTIFICATION_TRANSITIONAL;
} else if (str == "new") {
return NOTIFICATION_NEW;
} else if (str == "server") {
return NOTIFICATION_SERVER;
}
LOG(WARNING) << "Unknown notification method \"" << str
<< "\"; using method "
<< NotificationMethodToString(kDefaultNotificationMethod);
return kDefaultNotificationMethod;
}
} // namespace browser_sync
<commit_msg>Revert 51494 - Set default sync notification method to "server".<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/sync/notification_method.h"
#include "base/logging.h"
namespace browser_sync {
// TODO(akalin): Eventually change this to NOTIFICATION_NEW.
const NotificationMethod kDefaultNotificationMethod =
NOTIFICATION_TRANSITIONAL;
std::string NotificationMethodToString(
NotificationMethod notification_method) {
switch (notification_method) {
case NOTIFICATION_LEGACY:
return "NOTIFICATION_LEGACY";
break;
case NOTIFICATION_TRANSITIONAL:
return "NOTIFICATION_TRANSITIONAL";
break;
case NOTIFICATION_NEW:
return "NOTIFICATION_NEW";
break;
case NOTIFICATION_SERVER:
return "NOTIFICATION_SERVER";
break;
default:
LOG(WARNING) << "Unknown value for notification method: "
<< notification_method;
break;
}
return "<unknown notification method>";
}
NotificationMethod StringToNotificationMethod(const std::string& str) {
if (str == "legacy") {
return NOTIFICATION_LEGACY;
} else if (str == "transitional") {
return NOTIFICATION_TRANSITIONAL;
} else if (str == "new") {
return NOTIFICATION_NEW;
} else if (str == "server") {
return NOTIFICATION_SERVER;
}
LOG(WARNING) << "Unknown notification method \"" << str
<< "\"; using method "
<< NotificationMethodToString(kDefaultNotificationMethod);
return kDefaultNotificationMethod;
}
} // namespace browser_sync
<|endoftext|> |
<commit_before>#include <assert.h>
#include <float.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "bnet.hpp"
#include "matrix.hpp"
#include "rand.hpp"
#define VERBOSE 1
#define SAVE_NETWORKS 0
double dirichlet_score_family(SMatrix counts, SCPD cpd) {
SMatrix ns = cpd->sizes, prior = cpd->dirichlet;
SMatrix ns_self = ns->extract_indices(ns->rows - 1, ns->rows, 0, ns->cols);
SMatrix pnc = counts + prior;
SMatrix gamma_pnc = pnc->lgammaed(), gamma_prior = prior->lgammaed();
SMatrix lu_mat = gamma_pnc - gamma_prior;
SMatrix LU = lu_mat->sum_n_cols(ns_self->data[0]);
SMatrix alpha_ij = prior->sum_n_cols(ns_self->data[0]);
SMatrix N_ij = counts->sum_n_cols(ns_self->data[0]);
SMatrix alpha_N = N_ij + alpha_ij;
SMatrix LV = alpha_ij->lgammaed() - alpha_N->lgammaed();
SMatrix LU_LV = LU + LV;
double score = LU_LV->sumAllValue();
return score;
}
int count_index(SMatrix sz, SMatrix sample_data, int col) {
SMatrix mat_col = sample_data->extract_indices(0, sample_data->rows, col, col + 1);
int index = 0;
for (int i = 0, m = 1; i < mat_col->rows * mat_col->cols; m *= sz->data[i++]) {
index += ((mat_col->data[i]) - 1) * m;
}
return index;
}
SMatrix compute_counts(SMatrix data, SMatrix sz) {
SMatrix count = std::make_shared<Matrix>(sz->multiplyAllValues(), 1);
for (int i = 0; i < data->cols; ++i) {
count->data[count_index(sz, data, i)] += 1;
}
return count;
}
double log_marg_prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
SMatrix data = pev->concat_rows(self_ev, false);
SMatrix counts = compute_counts(data, cpd->sizes);
return dirichlet_score_family(counts, cpd);
}
SMatrix prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
SMatrix sample_data = pev->concat_rows(self_ev, false);
SMatrix prob = std::make_shared<Matrix>(sample_data->rows, sample_data->cols);
for (int i = 0; i < sample_data->cols; ++i) {
SMatrix mat_col = sample_data->extract_indices(0, sample_data->rows, i, i + 1);
int index = 0;
auto dd = cpd->sizes->data;
for (int j = 0, m = 1; j < mat_col->rows * mat_col->cols; m *= dd[j++]) {
index += ((mat_col->data[j]) - 1) * m;
}
prob->data[i] = cpd->cpt->data[index];
}
return prob;
}
double log_prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
double score = 0;
SMatrix p = prob_node(cpd, self_ev, pev);
for (int i = 0; i < p->rows * p->cols; ++i) {
double d = p->data[i];
score += d <= 0 ? DBL_MIN : log(d);
}
return score;
}
SCPD tabular_CPD(SMatrix dag, SMatrix ns, int self) {
SCPD cpd = std::make_shared<CPD>();
std::vector<int> ps = dag->adjacency_matrix_parents(self);
ps.push_back(self);
SMatrix fam_sz = std::make_shared<Matrix>(ps.size(), 1);
for (int i = 0; i < ps.size(); ++i) {
fam_sz->data[i] = ns->data[ps[i]];
}
cpd->sizes = fam_sz;
SMatrix calc = fam_sz->extract_indices(0, ps.size() - 1, 0, 1);
int psz = calc->multiplyAllValues();
cpd->dirichlet = std::make_shared<Matrix>(
fam_sz->multiplyAllValues(), 1,
(1.0 / psz) * (1.0 / ns->data[self]));
cpd->cpt = nullptr;
return cpd;
}
double score_family(int j, std::vector<int> ps, SMatrix ns, std::vector<int> discrete, SMatrix data,
std::string scoring_fn) {
SMatrix dag = std::make_shared<Matrix>(data->rows, data->rows);
if (ps.size() > 0) {
dag->set_list_index(1, ps, j, j + 1);
// TODO: sort `ps` here.
}
SMatrix data_sub_1 = data->extract_indices(j, j + 1, 0, data->cols),
data_sub_2 = data->extract_list_index(ps, 0, data->cols);
SCPD cpd = tabular_CPD(dag, ns, j);
double score;
if (scoring_fn == "bayesian") {
score = log_marg_prob_node(cpd, data_sub_1, data_sub_2);
} else if (scoring_fn == "bic") {
std::vector<int> fam(ps);
fam.push_back(j);
SMatrix data_sub_3 = data->extract_list_index(fam, 0, data->cols);
SMatrix counts = compute_counts(data_sub_3, cpd->sizes);
cpd->cpt = counts + cpd->dirichlet;
cpd->cpt->mk_stochastic(ns);
double L = log_prob_node(cpd, data_sub_1, data_sub_2);
SMatrix sz = cpd->sizes;
const int len = sz->rows * sz->cols;
const int value = sz->data[len - 1];
sz->set_position(len, value - 1);
score = L - 0.5 * sz->multiplyAllValues() * log(data->cols);
sz->set_position(len, value);
} else {
throw "dead in the water, mate";
}
return score;
}
template <class T>
std::vector<T> set_difference(std::vector<T> &a, std::vector<T> &b) {
std::vector<T> c(a);
for (auto &&v : b) {
auto pos = std::find(c.begin(), c.end(), v);
if (pos != c.end()) c.erase(pos);
}
return std::move(c);
}
SMatrix learn_struct_K2(SMatrix data, SMatrix ns, std::vector<int> order, std::string scoring_fn, int max_parents) {
assert(order.size() == data->rows);
const int n = data->rows;
int max_fan_in = max_parents == 0 ? n : max_parents;
std::vector<int> discrete;
for (int i = 0; i < n; ++i) discrete.push_back(i);
SMatrix dag = std::make_shared<Matrix>(n, n);
int parent_order = 0;
for (int i = 0; i < n; ++i) {
std::vector<int> ps;
const int j = order[i];
double score = score_family(j, ps, ns, discrete, data, scoring_fn);
#if VERBOSE
printf("\nnode %d, empty score %6.4f\n", j, score);
#endif
for (; ps.size() <= max_fan_in;) {
std::vector<int> order_sub(order.begin(), order.begin() + i);
auto pps = set_difference<int>(order_sub, ps);
int nps = pps.size();
SMatrix pscore = std::make_shared<Matrix>(1, nps);
for (int pi = 0; pi < nps; ++pi) {
int p = pps[pi];
ps.push_back(p);
int n_index = ps.size() - 1;
pscore->data[pi] = score_family(j, ps, ns, discrete, data, scoring_fn);
#if VERBOSE
printf("considering adding %d to %d, score %6.4f\n", p, j, pscore->data[pi]);
#endif
ps.erase(ps.begin() + n_index);
}
double best_pscore = -DBL_MAX;
int best_p = -1;
for (int i = 0; i < nps; ++i) {
double d = pscore->data[i];
if (d > best_pscore) {
best_pscore = d;
best_p = i;
}
}
if (best_p == -1) {
break;
}
best_p = pps[best_p];
if (best_pscore > score) {
score = best_pscore;
ps.push_back(best_p);
#if VERBOSE
printf("* adding %d to %d, score %6.4f\n", best_p, j, best_pscore);
#endif
} else {
break;
}
}
if (ps.size() > 0) {
dag->set_list_index(++parent_order, ps, j, j + 1);
}
}
return dag;
}
int exec(int forkIndex, int forkSize, bool data_transposed, std::string f_data,
int topologies, std::string f_output, std::string scoring_fn, int max_parents) {
SMatrix data = load(f_data, !data_transposed),
sz = data->create_sz();
SMatrix orders = std::make_shared<Matrix>(data->rows * topologies, data->rows);
#if SAVE_NETWORKS
SMatrix networks =
std::make_shared<Matrix>(data->rows * topologies, data->rows * data->rows);
#endif
#pragma omp parallel for
for (int r = 0; r < orders->rows; ++r) {
int start = r / topologies;
int *arr = new int[orders->cols];
arr[0] = start;
for (int i = 1; i < orders->cols; ++i) {
arr[i] = i == start ? 0 : i;
}
shuffle_int(orders->cols - 1, arr + 1);
for (int c = 0; c < orders->cols; ++c) {
orders->inplace_set(r, c, arr[c]);
}
delete[] arr;
}
SMatrix consensus_network = std::make_shared<Matrix>(data->rows, data->rows);
int cn_n_elements = consensus_network->rows * consensus_network->cols;
#pragma omp parallel for
for (int o = 0; o < orders->rows; ++o) {
SMatrix m_order = orders->list_elems_by_row_position(o + 1);
std::vector<int> order = m_order->asVector<int>();
SMatrix bnet = learn_struct_K2(data, sz, order, scoring_fn, max_parents);
assert(consensus_network->rows == bnet->rows);
assert(consensus_network->cols == bnet->cols);
#pragma omp critical
for (int i = 0; i < cn_n_elements; ++i) {
consensus_network->data[i] += bnet->data[i] ? 1 : 0;
}
#if SAVE_NETWORKS
for (int i = 0; i < cn_n_elements; ++i) {
networks->data[i + cn_n_elements * o] = bnet->data[i];
}
#endif
}
if (forkIndex == 0) {
consensus_network->save(f_output);
#if SAVE_NETWORKS
networks->save("networks.csv");
orders->save("topologies.csv");
#endif
}
return 0;
}
int main(int argc, char **argv) {
int forkIndex = 0, forkSize = 1;
srand(time(NULL) ^ forkIndex);
int threads = 1, topologies = 1, max_parents = 0;
bool data_transposed = false;
std::string data, output = "consensus.csv";
std::string scoring_fn = "bayesian";
int c;
while ((c = getopt(argc, argv, "Thp:d:t:o:s:")) != -1) {
switch (c) {
case 'T': {
data_transposed = true;
break;
}
case 'p': {
threads = atoi(optarg);
assert(threads > 0);
assert(threads <= omp_get_num_procs());
break;
}
case 'm': {
max_parents = atoi(optarg);
assert(max_parents >= 0);
break;
}
case 'd': {
data = optarg;
break;
}
case 't': {
topologies = atoi(optarg);
break;
}
case 'o': {
output = optarg;
break;
}
case 's': {
scoring_fn = optarg;
break;
}
case 'h':
default: {
puts(
": -p <num_threads> -d <data file> -t <topologies per gene> -o "
"<output file> -m <max parents>");
puts("~ -T (reads matrix transposed)");
return 1;
}
}
}
if (data.size() < 1) {
puts("You must send a data file using -d <file name>.");
return 1;
}
omp_set_num_threads(threads);
int status = exec(forkIndex, forkSize, data_transposed, data, topologies,
output, scoring_fn, max_parents);
return status;
}
<commit_msg>Turn off verbose<commit_after>#include <assert.h>
#include <float.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "bnet.hpp"
#include "matrix.hpp"
#include "rand.hpp"
#define VERBOSE 0
#define SAVE_NETWORKS 0
double dirichlet_score_family(SMatrix counts, SCPD cpd) {
SMatrix ns = cpd->sizes, prior = cpd->dirichlet;
SMatrix ns_self = ns->extract_indices(ns->rows - 1, ns->rows, 0, ns->cols);
SMatrix pnc = counts + prior;
SMatrix gamma_pnc = pnc->lgammaed(), gamma_prior = prior->lgammaed();
SMatrix lu_mat = gamma_pnc - gamma_prior;
SMatrix LU = lu_mat->sum_n_cols(ns_self->data[0]);
SMatrix alpha_ij = prior->sum_n_cols(ns_self->data[0]);
SMatrix N_ij = counts->sum_n_cols(ns_self->data[0]);
SMatrix alpha_N = N_ij + alpha_ij;
SMatrix LV = alpha_ij->lgammaed() - alpha_N->lgammaed();
SMatrix LU_LV = LU + LV;
double score = LU_LV->sumAllValue();
return score;
}
int count_index(SMatrix sz, SMatrix sample_data, int col) {
SMatrix mat_col = sample_data->extract_indices(0, sample_data->rows, col, col + 1);
int index = 0;
for (int i = 0, m = 1; i < mat_col->rows * mat_col->cols; m *= sz->data[i++]) {
index += ((mat_col->data[i]) - 1) * m;
}
return index;
}
SMatrix compute_counts(SMatrix data, SMatrix sz) {
SMatrix count = std::make_shared<Matrix>(sz->multiplyAllValues(), 1);
for (int i = 0; i < data->cols; ++i) {
count->data[count_index(sz, data, i)] += 1;
}
return count;
}
double log_marg_prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
SMatrix data = pev->concat_rows(self_ev, false);
SMatrix counts = compute_counts(data, cpd->sizes);
return dirichlet_score_family(counts, cpd);
}
SMatrix prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
SMatrix sample_data = pev->concat_rows(self_ev, false);
SMatrix prob = std::make_shared<Matrix>(sample_data->rows, sample_data->cols);
for (int i = 0; i < sample_data->cols; ++i) {
SMatrix mat_col = sample_data->extract_indices(0, sample_data->rows, i, i + 1);
int index = 0;
auto dd = cpd->sizes->data;
for (int j = 0, m = 1; j < mat_col->rows * mat_col->cols; m *= dd[j++]) {
index += ((mat_col->data[j]) - 1) * m;
}
prob->data[i] = cpd->cpt->data[index];
}
return prob;
}
double log_prob_node(SCPD cpd, SMatrix self_ev, SMatrix pev) {
double score = 0;
SMatrix p = prob_node(cpd, self_ev, pev);
for (int i = 0; i < p->rows * p->cols; ++i) {
double d = p->data[i];
score += d <= 0 ? DBL_MIN : log(d);
}
return score;
}
SCPD tabular_CPD(SMatrix dag, SMatrix ns, int self) {
SCPD cpd = std::make_shared<CPD>();
std::vector<int> ps = dag->adjacency_matrix_parents(self);
ps.push_back(self);
SMatrix fam_sz = std::make_shared<Matrix>(ps.size(), 1);
for (int i = 0; i < ps.size(); ++i) {
fam_sz->data[i] = ns->data[ps[i]];
}
cpd->sizes = fam_sz;
SMatrix calc = fam_sz->extract_indices(0, ps.size() - 1, 0, 1);
int psz = calc->multiplyAllValues();
cpd->dirichlet = std::make_shared<Matrix>(
fam_sz->multiplyAllValues(), 1,
(1.0 / psz) * (1.0 / ns->data[self]));
cpd->cpt = nullptr;
return cpd;
}
double score_family(int j, std::vector<int> ps, SMatrix ns, std::vector<int> discrete, SMatrix data,
std::string scoring_fn) {
SMatrix dag = std::make_shared<Matrix>(data->rows, data->rows);
if (ps.size() > 0) {
dag->set_list_index(1, ps, j, j + 1);
// TODO: sort `ps` here.
}
SMatrix data_sub_1 = data->extract_indices(j, j + 1, 0, data->cols),
data_sub_2 = data->extract_list_index(ps, 0, data->cols);
SCPD cpd = tabular_CPD(dag, ns, j);
double score;
if (scoring_fn == "bayesian") {
score = log_marg_prob_node(cpd, data_sub_1, data_sub_2);
} else if (scoring_fn == "bic") {
std::vector<int> fam(ps);
fam.push_back(j);
SMatrix data_sub_3 = data->extract_list_index(fam, 0, data->cols);
SMatrix counts = compute_counts(data_sub_3, cpd->sizes);
cpd->cpt = counts + cpd->dirichlet;
cpd->cpt->mk_stochastic(ns);
double L = log_prob_node(cpd, data_sub_1, data_sub_2);
SMatrix sz = cpd->sizes;
const int len = sz->rows * sz->cols;
const int value = sz->data[len - 1];
sz->set_position(len, value - 1);
score = L - 0.5 * sz->multiplyAllValues() * log(data->cols);
sz->set_position(len, value);
} else {
throw "dead in the water, mate";
}
return score;
}
template <class T>
std::vector<T> set_difference(std::vector<T> &a, std::vector<T> &b) {
std::vector<T> c(a);
for (auto &&v : b) {
auto pos = std::find(c.begin(), c.end(), v);
if (pos != c.end()) c.erase(pos);
}
return std::move(c);
}
SMatrix learn_struct_K2(SMatrix data, SMatrix ns, std::vector<int> order, std::string scoring_fn, int max_parents) {
assert(order.size() == data->rows);
const int n = data->rows;
int max_fan_in = max_parents == 0 ? n : max_parents;
std::vector<int> discrete;
for (int i = 0; i < n; ++i) discrete.push_back(i);
SMatrix dag = std::make_shared<Matrix>(n, n);
int parent_order = 0;
for (int i = 0; i < n; ++i) {
std::vector<int> ps;
const int j = order[i];
double score = score_family(j, ps, ns, discrete, data, scoring_fn);
#if VERBOSE
printf("\nnode %d, empty score %6.4f\n", j, score);
#endif
for (; ps.size() <= max_fan_in;) {
std::vector<int> order_sub(order.begin(), order.begin() + i);
auto pps = set_difference<int>(order_sub, ps);
int nps = pps.size();
SMatrix pscore = std::make_shared<Matrix>(1, nps);
for (int pi = 0; pi < nps; ++pi) {
int p = pps[pi];
ps.push_back(p);
int n_index = ps.size() - 1;
pscore->data[pi] = score_family(j, ps, ns, discrete, data, scoring_fn);
#if VERBOSE
printf("considering adding %d to %d, score %6.4f\n", p, j, pscore->data[pi]);
#endif
ps.erase(ps.begin() + n_index);
}
double best_pscore = -DBL_MAX;
int best_p = -1;
for (int i = 0; i < nps; ++i) {
double d = pscore->data[i];
if (d > best_pscore) {
best_pscore = d;
best_p = i;
}
}
if (best_p == -1) {
break;
}
best_p = pps[best_p];
if (best_pscore > score) {
score = best_pscore;
ps.push_back(best_p);
#if VERBOSE
printf("* adding %d to %d, score %6.4f\n", best_p, j, best_pscore);
#endif
} else {
break;
}
}
if (ps.size() > 0) {
dag->set_list_index(++parent_order, ps, j, j + 1);
}
}
return dag;
}
int exec(int forkIndex, int forkSize, bool data_transposed, std::string f_data,
int topologies, std::string f_output, std::string scoring_fn, int max_parents) {
SMatrix data = load(f_data, !data_transposed),
sz = data->create_sz();
SMatrix orders = std::make_shared<Matrix>(data->rows * topologies, data->rows);
#if SAVE_NETWORKS
SMatrix networks =
std::make_shared<Matrix>(data->rows * topologies, data->rows * data->rows);
#endif
#pragma omp parallel for
for (int r = 0; r < orders->rows; ++r) {
int start = r / topologies;
int *arr = new int[orders->cols];
arr[0] = start;
for (int i = 1; i < orders->cols; ++i) {
arr[i] = i == start ? 0 : i;
}
shuffle_int(orders->cols - 1, arr + 1);
for (int c = 0; c < orders->cols; ++c) {
orders->inplace_set(r, c, arr[c]);
}
delete[] arr;
}
SMatrix consensus_network = std::make_shared<Matrix>(data->rows, data->rows);
int cn_n_elements = consensus_network->rows * consensus_network->cols;
#pragma omp parallel for
for (int o = 0; o < orders->rows; ++o) {
SMatrix m_order = orders->list_elems_by_row_position(o + 1);
std::vector<int> order = m_order->asVector<int>();
SMatrix bnet = learn_struct_K2(data, sz, order, scoring_fn, max_parents);
assert(consensus_network->rows == bnet->rows);
assert(consensus_network->cols == bnet->cols);
#pragma omp critical
for (int i = 0; i < cn_n_elements; ++i) {
consensus_network->data[i] += bnet->data[i] ? 1 : 0;
}
#if SAVE_NETWORKS
for (int i = 0; i < cn_n_elements; ++i) {
networks->data[i + cn_n_elements * o] = bnet->data[i];
}
#endif
}
if (forkIndex == 0) {
consensus_network->save(f_output);
#if SAVE_NETWORKS
networks->save("networks.csv");
orders->save("topologies.csv");
#endif
}
return 0;
}
int main(int argc, char **argv) {
int forkIndex = 0, forkSize = 1;
srand(time(NULL) ^ forkIndex);
int threads = 1, topologies = 1, max_parents = 0;
bool data_transposed = false;
std::string data, output = "consensus.csv";
std::string scoring_fn = "bayesian";
int c;
while ((c = getopt(argc, argv, "Thp:d:t:o:s:")) != -1) {
switch (c) {
case 'T': {
data_transposed = true;
break;
}
case 'p': {
threads = atoi(optarg);
assert(threads > 0);
assert(threads <= omp_get_num_procs());
break;
}
case 'm': {
max_parents = atoi(optarg);
assert(max_parents >= 0);
break;
}
case 'd': {
data = optarg;
break;
}
case 't': {
topologies = atoi(optarg);
break;
}
case 'o': {
output = optarg;
break;
}
case 's': {
scoring_fn = optarg;
break;
}
case 'h':
default: {
puts(
": -p <num_threads> -d <data file> -t <topologies per gene> -o "
"<output file> -m <max parents>");
puts("~ -T (reads matrix transposed)");
return 1;
}
}
}
if (data.size() < 1) {
puts("You must send a data file using -d <file name>.");
return 1;
}
omp_set_num_threads(threads);
int status = exec(forkIndex, forkSize, data_transposed, data, topologies,
output, scoring_fn, max_parents);
return status;
}
<|endoftext|> |
<commit_before>/** \file
* Implements safer c++ wrappers for the sysctl() interface.
*/
#ifndef _POWERDXX_SYS_SYSCTL_HPP_
#define _POWERDXX_SYS_SYSCTL_HPP_
#include "error.hpp" /* sys::sc_error */
#include <sys/types.h> /* sysctl() */
#include <sys/sysctl.h> /* sysctl() */
namespace sys {
/**
* This namespace contains safer c++ wrappers for the sysctl() interface.
*
* The template class Sysctl represents a sysctl address and offers
* handles to retrieve or set the stored value.
*/
namespace ctl {
/**
* Management Information Base identifier type (see sysctl(3)).
*/
typedef int mib_t;
/**
* Represents a sysctl MIB address.
*
* @tparam MibDepth
* The maximum allowed MIB depth
*/
template <size_t MibDepth>
class Sysctl {
private:
/**
* Stores the MIB address.
*/
mib_t mib[MibDepth];
public:
/**
* The default constructor.
*
* This is available to defer initialisation to a later moment.
* This might be useful when initialising global or static
* instances by a character string repesented name.
*/
constexpr Sysctl() : mib{} {}
/**
* Initialise the MIB address from a character string.
*
* @param name
* The name of the sysctl
* @throws sc_error
* May throw an exception if the addressed sysct does
* not exist or if the address is too long to store
*/
Sysctl(char const * const name) {
size_t length = MibDepth;
if (::sysctlnametomib(name, this->mib, &length) == -1) {
throw sc_error{errno};
}
}
/**
* Initialise the MIB address directly.
*
* Some important sysctl values have a fixed address that
* can be initialised at compile time with a noexcept guarantee.
*
* Spliting the MIB address into head and tail makes sure
* that `Sysctl(char *)` does not match the template and is
* instead implicitly cast to invoke `Sysctl(char const *)`.
*
* @tparam Tail
* The types of the trailing MIB address values (must
* be mib_t)
* @param head,tail
* The mib
*/
template <typename... Tail>
constexpr Sysctl(mib_t const head, Tail const... tail) noexcept :
mib{head, tail...} {
static_assert(MibDepth >= sizeof...(Tail) + 1,
"The number of MIB addresses must not exceed the MIB depth");
}
/**
* Update the given buffer with a value retrieved from the
* sysctl.
*
* @param buf,bufsize
* The target buffer and its size
* @throws sc_error
* Throws if value retrieval fails or is incomplete,
* e.g. because the value does not fit into the target
* buffer
*/
void update(void * const buf, size_t const bufsize) const {
auto len = bufsize;
if (::sysctl(this->mib, MibDepth, buf, &len, nullptr, 0)
== -1) {
throw sc_error{errno};
}
}
/**
* Update the given value with a value retreived from the
* sysctl.
*
* @tparam T
* The type store the sysctl value in
* @param value
* A reference to the target value
* @throws sc_error
* Throws if value retrieval fails or is incomplete,
* e.g. because the value does not fit into the target
* type
*/
template <typename T>
void update(T & value) const {
update(&value, sizeof(T));
}
/**
* Retrieve an array from the sysctl address.
*
* This is useful to retrieve variable length sysctls, like
* characer strings.
*
* @tparam T
* The type stored in the array
* @return
* And array of T with the right length to store the
* whole sysctl value
* @throws sc_error
* May throw if the size of the sysctl increases after
* the length was queried
*/
template <typename T>
std::unique_ptr<T[]> get() const {
size_t len = 0;
if (::sysctl(this->mib, MibDepth, nullptr, &len, nullptr, 0)
== -1) {
throw sc_error{errno};
}
auto result = std::unique_ptr<T[]>(new T[len / sizeof(T)]);
update(result.get(), len);
return result;
}
/**
* Update the the sysctl value with the given buffer.
*
* @param buf,bufsize
* The source buffer
* @throws sc_error
* If the source buffer cannot be stored in the sysctl
*/
void set(void const * const buf, size_t const bufsize) {
if (::sysctl(this->mib, MibDepth, nullptr, nullptr,
buf, bufsize) == -1) {
throw sc_error{errno};
}
}
/**
* Update the the sysctl value with the given value.
*
* @tparam T
* The value type
* @param value
* The value to set the sysctl to
*/
template <typename T>
void set(T const & value) {
set(&value, sizeof(T));
}
};
template <typename... MibTs>
constexpr Sysctl<sizeof...(MibTs)> make_Sysctl(MibTs const... mib) {
return {mib...};
}
template <size_t MibDepth, typename T>
class SysctlValue {
private:
T value;
Sysctl<MibDepth> sysctl;
public:
template <typename... SysctlArgs>
constexpr SysctlValue(T const & value, SysctlArgs const &... args) :
value{value}, sysctl{args...} {};
SysctlValue & operator =(T const & value) {
this->value = value;
this->sysctl.set(this->value);
return *this;
}
operator T const &() const {
return this->value;
}
void update() {
this->sysctl.update(this->value);
}
};
template <typename T, typename... MibTs>
constexpr SysctlValue<sizeof...(MibTs), T>
make_SysctlValue(T const & value, MibTs const... addr) {
return {value, addr...};
}
} /* namespace ctl */
} /* namespace sys */
#endif /* _POWERDXX_SYS_SYSCTL_HPP_ */
<commit_msg>Replace SysctlValue with Once and Sync<commit_after>/** \file
* Implements safer c++ wrappers for the sysctl() interface.
*/
#ifndef _POWERDXX_SYS_SYSCTL_HPP_
#define _POWERDXX_SYS_SYSCTL_HPP_
#include "error.hpp" /* sys::sc_error */
#include <sys/types.h> /* sysctl() */
#include <sys/sysctl.h> /* sysctl() */
namespace sys {
/**
* This namespace contains safer c++ wrappers for the sysctl() interface.
*
* The template class Sysctl represents a sysctl address and offers
* handles to retrieve or set the stored value.
*/
namespace ctl {
/**
* Management Information Base identifier type (see sysctl(3)).
*/
typedef int mib_t;
/**
* Represents a sysctl MIB address.
*
* @tparam MibDepth
* The maximum allowed MIB depth
*/
template <size_t MibDepth>
class Sysctl {
private:
/**
* Stores the MIB address.
*/
mib_t mib[MibDepth];
public:
/**
* The default constructor.
*
* This is available to defer initialisation to a later moment.
* This might be useful when initialising global or static
* instances by a character string repesented name.
*/
constexpr Sysctl() : mib{} {}
/**
* Initialise the MIB address from a character string.
*
* @param name
* The name of the sysctl
* @throws sc_error
* May throw an exception if the addressed sysct does
* not exist or if the address is too long to store
*/
Sysctl(char const * const name) {
size_t length = MibDepth;
if (::sysctlnametomib(name, this->mib, &length) == -1) {
throw sc_error{errno};
}
}
/**
* Initialise the MIB address directly.
*
* Some important sysctl values have a fixed address that
* can be initialised at compile time with a noexcept guarantee.
*
* Spliting the MIB address into head and tail makes sure
* that `Sysctl(char *)` does not match the template and is
* instead implicitly cast to invoke `Sysctl(char const *)`.
*
* @tparam Tail
* The types of the trailing MIB address values (must
* be mib_t)
* @param head,tail
* The mib
*/
template <typename... Tail>
constexpr Sysctl(mib_t const head, Tail const... tail) noexcept :
mib{head, tail...} {
static_assert(MibDepth >= sizeof...(Tail) + 1,
"The number of MIB addresses must not exceed the MIB depth");
}
/**
* Update the given buffer with a value retrieved from the
* sysctl.
*
* @param buf,bufsize
* The target buffer and its size
* @throws sc_error
* Throws if value retrieval fails or is incomplete,
* e.g. because the value does not fit into the target
* buffer
*/
void update(void * const buf, size_t const bufsize) const {
auto len = bufsize;
if (::sysctl(this->mib, MibDepth, buf, &len, nullptr, 0)
== -1) {
throw sc_error{errno};
}
}
/**
* Update the given value with a value retreived from the
* sysctl.
*
* @tparam T
* The type store the sysctl value in
* @param value
* A reference to the target value
* @throws sc_error
* Throws if value retrieval fails or is incomplete,
* e.g. because the value does not fit into the target
* type
*/
template <typename T>
void update(T & value) const {
update(&value, sizeof(T));
}
/**
* Retrieve an array from the sysctl address.
*
* This is useful to retrieve variable length sysctls, like
* characer strings.
*
* @tparam T
* The type stored in the array
* @return
* And array of T with the right length to store the
* whole sysctl value
* @throws sc_error
* May throw if the size of the sysctl increases after
* the length was queried
*/
template <typename T>
std::unique_ptr<T[]> get() const {
size_t len = 0;
if (::sysctl(this->mib, MibDepth, nullptr, &len, nullptr, 0)
== -1) {
throw sc_error{errno};
}
auto result = std::unique_ptr<T[]>(new T[len / sizeof(T)]);
update(result.get(), len);
return result;
}
/**
* Update the the sysctl value with the given buffer.
*
* @param buf,bufsize
* The source buffer
* @throws sc_error
* If the source buffer cannot be stored in the sysctl
*/
void set(void const * const buf, size_t const bufsize) {
if (::sysctl(this->mib, MibDepth, nullptr, nullptr,
buf, bufsize) == -1) {
throw sc_error{errno};
}
}
/**
* Update the the sysctl value with the given value.
*
* @tparam T
* The value type
* @param value
* The value to set the sysctl to
*/
template <typename T>
void set(T const & value) {
set(&value, sizeof(T));
}
};
template <typename T, class SysctlT>
class Sync {
private:
SysctlT sysctl;
public:
constexpr Sync(SysctlT const & sysctl) noexcept : sysctl{sysctl} {}
Sync & operator =(T const & value) {
this->sysctl.set(value);
return *this;
}
operator T () const {
T value;
this->sysctl.update(value);
return value;
}
};
template <typename T, size_t MibDepth>
using SysctlSync = Sync<T, Sysctl<MibDepth>>;
template <typename T, class SysctlT>
class Once {
private:
T value;
public:
Once(T const & value, SysctlT const & sysctl) noexcept {
try {
sysctl.update(this->value);
} catch (sc_error) {
this->value = value;
}
}
operator T const &() const {
return this->value;
}
};
template <typename T, size_t MibDepth>
using SysctlOnce = Once<T, Sysctl<MibDepth>>;
template <typename T, class SysctlT>
constexpr Once<T, SysctlT> once(T const & value, SysctlT const & sysctl)
noexcept {
return {value, sysctl};
}
} /* namespace ctl */
} /* namespace sys */
#endif /* _POWERDXX_SYS_SYSCTL_HPP_ */
<|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/views/browser_bubble.h"
#include "app/l10n_util_win.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
class BubbleWidget : public views::WidgetWin {
public:
explicit BubbleWidget(BrowserBubble* bubble)
: bubble_(bubble), closed_(false) {
}
void Show(bool activate) {
if (activate)
ShowWindow(SW_SHOW);
else
views::WidgetWin::Show();
}
void Close() {
if (closed_)
return;
closed_ = true;
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Close();
}
void Hide() {
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Hide();
}
void OnActivate(UINT action, BOOL minimized, HWND window) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (!delegate) {
if (action == WA_INACTIVE && !closed_) {
bubble_->DetachFromBrowser();
delete bubble_;
}
return;
}
if (action == WA_INACTIVE && !closed_) {
delegate->BubbleLostFocus(bubble_);
} else if (action == WA_ACTIVE) {
delegate->BubbleGotFocus(bubble_);
}
}
private:
bool closed_;
BrowserBubble* bubble_;
};
void BrowserBubble::InitPopup() {
// popup_ is a Widget, but we need to do some WidgetWin stuff first, then
// we'll assign it into popup_.
views::WidgetWin* pop = new BubbleWidget(this);
pop->set_window_style(WS_POPUP);
pop->Init(frame_native_view_, bounds_);
pop->SetContentsView(view_);
popup_ = pop;
Reposition();
AttachToBrowser();
}
void BrowserBubble::MovePopup(int x, int y, int w, int h) {
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->MoveWindow(x, y, w, h);
}
void BrowserBubble::Show(bool activate) {
if (visible_)
return;
BubbleWidget* pop = static_cast<BubbleWidget*>(popup_);
pop->Show(activate);
visible_ = true;
}
void BrowserBubble::Hide() {
if (!visible_)
return;
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->Hide();
visible_ = false;
}
<commit_msg>Mostly fixes black flashing that happens during popup resize.<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/views/browser_bubble.h"
#include "app/l10n_util_win.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
class BubbleWidget : public views::WidgetWin {
public:
explicit BubbleWidget(BrowserBubble* bubble)
: bubble_(bubble), closed_(false) {
set_window_style(WS_POPUP | WS_CLIPCHILDREN);
set_window_ex_style(WS_EX_TOOLWINDOW);
}
void Show(bool activate) {
if (activate)
ShowWindow(SW_SHOW);
else
views::WidgetWin::Show();
}
void Close() {
if (closed_)
return;
closed_ = true;
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Close();
}
void Hide() {
if (IsActive()) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (delegate)
delegate->BubbleLostFocus(bubble_);
}
views::WidgetWin::Hide();
}
void OnActivate(UINT action, BOOL minimized, HWND window) {
BrowserBubble::Delegate* delegate = bubble_->delegate();
if (!delegate) {
if (action == WA_INACTIVE && !closed_) {
bubble_->DetachFromBrowser();
delete bubble_;
}
return;
}
if (action == WA_INACTIVE && !closed_) {
delegate->BubbleLostFocus(bubble_);
} else if (action == WA_ACTIVE) {
delegate->BubbleGotFocus(bubble_);
}
}
private:
bool closed_;
BrowserBubble* bubble_;
};
void BrowserBubble::InitPopup() {
// popup_ is a Widget, but we need to do some WidgetWin stuff first, then
// we'll assign it into popup_.
views::WidgetWin* pop = new BubbleWidget(this);
pop->Init(frame_native_view_, bounds_);
pop->SetContentsView(view_);
popup_ = pop;
Reposition();
AttachToBrowser();
}
void BrowserBubble::MovePopup(int x, int y, int w, int h) {
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->SetBounds(gfx::Rect(x, y, w, h));
}
void BrowserBubble::Show(bool activate) {
if (visible_)
return;
BubbleWidget* pop = static_cast<BubbleWidget*>(popup_);
pop->Show(activate);
visible_ = true;
}
void BrowserBubble::Hide() {
if (!visible_)
return;
views::WidgetWin* pop = static_cast<views::WidgetWin*>(popup_);
pop->Hide();
visible_ = false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 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: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL), predecoder(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(Quiesce,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst), 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
StaticInstPtr instPtr = NULL;
//Predecode, ie bundle up an ExtMachInst
//This should go away once the constructor can be set up properly
predecoder.setTC(thread->getTC());
//If more fetch data is needed, pass it in.
if(predecoder.needMoreBytes())
predecoder.moreBytes(thread->readPC(), 0, inst);
else
predecoder.process();
//If an instruction is ready, decode it
if (predecoder.extMachInstReady())
instPtr = StaticInst::decode(predecoder.getExtMachInst());
//If we decoded an instruction and it's microcoded, start pulling
//out micro ops
if (instPtr && instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
//If we decoded an instruction this "tick", record information about it.
if(curStaticInst)
{
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n",
curStaticInst->getName(), curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
StaticInstPtr si(inst);
ProfileNode *node = thread->profile->consume(tc, si);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->dump();
delete traceData;
traceData = NULL;
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
curMacroStaticInst = StaticInst::nullStaticInstPtr;
fault->invoke(tc);
thread->setMicroPC(0);
thread->setNextMicroPC(1);
} else if (predecoder.needMoreBytes()) {
//If we're at the last micro op for this instruction
if (curStaticInst && curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<commit_msg>Use a computed mask to mask out the fetch address and not a hard coded one.<commit_after>/*
* Copyright (c) 2002-2005 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: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL), predecoder(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(Quiesce,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
// This will generate a mask which aligns the pc on MachInst size
// boundaries. It won't work for non-power-of-two sized MachInsts, but
// it will work better than a hard coded mask.
const Addr PCMask = ~(sizeof(MachInst) - 1);
req->setVirt(0, thread->readPC() & PCMask, sizeof(MachInst), 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
StaticInstPtr instPtr = NULL;
//Predecode, ie bundle up an ExtMachInst
//This should go away once the constructor can be set up properly
predecoder.setTC(thread->getTC());
//If more fetch data is needed, pass it in.
if(predecoder.needMoreBytes())
predecoder.moreBytes(thread->readPC(), 0, inst);
else
predecoder.process();
//If an instruction is ready, decode it
if (predecoder.extMachInstReady())
instPtr = StaticInst::decode(predecoder.getExtMachInst());
//If we decoded an instruction and it's microcoded, start pulling
//out micro ops
if (instPtr && instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
//If we decoded an instruction this "tick", record information about it.
if(curStaticInst)
{
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n",
curStaticInst->getName(), curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
StaticInstPtr si(inst);
ProfileNode *node = thread->profile->consume(tc, si);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->dump();
delete traceData;
traceData = NULL;
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
curMacroStaticInst = StaticInst::nullStaticInstPtr;
fault->invoke(tc);
thread->setMicroPC(0);
thread->setNextMicroPC(1);
} else if (predecoder.needMoreBytes()) {
//If we're at the last micro op for this instruction
if (curStaticInst && curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<|endoftext|> |
<commit_before>#include "compass_filter.hpp"
#include "location_state.hpp"
#include "../geometry/angles.hpp"
#include "../base/logging.hpp"
#include "../platform/location.hpp"
#define LOW_PASS_FACTOR 0.5
CompassFilter::CompassFilter()
{
m_headingRad = m_smoothedHeadingRad = 0;
// Set hard smoothing treshold constant to 10 degrees.
// We can't assign it from location::CompassInfo::accuracy, because actually it's a
// declination between magnetic and true north in Android
// (and it may be very large in particular places on the Earth).
m_smoothingThreshold = ang::DegreeToRad(10);
}
void CompassFilter::OnCompassUpdate(location::CompassInfo const & info)
{
double const newHeadingRad = ((info.m_trueHeading >= 0.0) ? info.m_trueHeading : info.m_magneticHeading);
double const newHeadingDelta = fabs(newHeadingRad - m_headingRad);
#ifdef OMIM_OS_IPHONE
// On iOS we shouldn't smooth the compass values.
m_headingRad = newHeadingRad;
#else
// if new heading lies outside the twice treshold radius we immediately accept it
if (newHeadingDelta > 2.0 * m_smoothingThreshold)
{
m_headingRad = newHeadingRad;
m_smoothedHeadingRad = newHeadingRad;
}
else
{
// else we smooth the received value with the following formula
// O(n) = O(n-1) + k * (I - O(n - 1));
m_smoothedHeadingRad = m_smoothedHeadingRad + LOW_PASS_FACTOR * (newHeadingRad - m_smoothedHeadingRad);
// if the change is too small we won't change the compass value
if (newHeadingDelta > m_smoothingThreshold)
m_headingRad = m_smoothedHeadingRad;
}
#endif
}
double CompassFilter::GetHeadingRad() const
{
return m_headingRad;
}
double CompassFilter::GetHeadingHalfErrorRad() const
{
return m_smoothingThreshold;
}
<commit_msg>Fix warning.<commit_after>#include "compass_filter.hpp"
#include "location_state.hpp"
#include "../geometry/angles.hpp"
#include "../base/logging.hpp"
#include "../platform/location.hpp"
#define LOW_PASS_FACTOR 0.5
CompassFilter::CompassFilter()
{
m_headingRad = m_smoothedHeadingRad = 0;
// Set hard smoothing treshold constant to 10 degrees.
// We can't assign it from location::CompassInfo::accuracy, because actually it's a
// declination between magnetic and true north in Android
// (and it may be very large in particular places on the Earth).
m_smoothingThreshold = ang::DegreeToRad(10);
}
void CompassFilter::OnCompassUpdate(location::CompassInfo const & info)
{
double const newHeadingRad = ((info.m_trueHeading >= 0.0) ? info.m_trueHeading : info.m_magneticHeading);
#ifdef OMIM_OS_IPHONE
// On iOS we shouldn't smooth the compass values.
m_headingRad = newHeadingRad;
#else
double const newHeadingDelta = fabs(newHeadingRad - m_headingRad);
// if new heading lies outside the twice treshold radius we immediately accept it
if (newHeadingDelta > 2.0 * m_smoothingThreshold)
{
m_headingRad = newHeadingRad;
m_smoothedHeadingRad = newHeadingRad;
}
else
{
// else we smooth the received value with the following formula
// O(n) = O(n-1) + k * (I - O(n - 1));
m_smoothedHeadingRad = m_smoothedHeadingRad + LOW_PASS_FACTOR * (newHeadingRad - m_smoothedHeadingRad);
// if the change is too small we won't change the compass value
if (newHeadingDelta > m_smoothingThreshold)
m_headingRad = m_smoothedHeadingRad;
}
#endif
}
double CompassFilter::GetHeadingRad() const
{
return m_headingRad;
}
double CompassFilter::GetHeadingHalfErrorRad() const
{
return m_smoothingThreshold;
}
<|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/renderer/autofill/autofill_agent.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/autofill_messages.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/renderer/autofill/password_autofill_manager.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormControlElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/password_form.h"
using WebKit::WebFormControlElement;
using WebKit::WebFormElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebKeyboardEvent;
using WebKit::WebNode;
using WebKit::WebString;
namespace {
// The size above which we stop triggering autofill for an input text field
// (so to avoid sending long strings through IPC).
const size_t kMaximumTextSizeForAutoFill = 1000;
} // namespace
namespace autofill {
AutoFillAgent::AutoFillAgent(
RenderView* render_view,
PasswordAutoFillManager* password_autofill_manager)
: RenderViewObserver(render_view),
password_autofill_manager_(password_autofill_manager),
autofill_query_id_(0),
autofill_action_(AUTOFILL_NONE),
display_warning_if_disabled_(false),
was_query_node_autofilled_(false),
suggestions_clear_index_(-1),
suggestions_options_index_(-1),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
}
AutoFillAgent::~AutoFillAgent() {}
bool AutoFillAgent::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(AutoFillAgent, message)
IPC_MESSAGE_HANDLER(AutoFillMsg_SuggestionsReturned, OnSuggestionsReturned)
IPC_MESSAGE_HANDLER(AutoFillMsg_FormDataFilled, OnFormDataFilled)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void AutoFillAgent::DidFinishDocumentLoad(WebKit::WebFrame* frame) {
// The document has now been fully loaded. Scan for forms to be sent up to
// the browser.
form_manager_.ExtractForms(frame);
SendForms(frame);
}
void AutoFillAgent::FrameDetached(WebKit::WebFrame* frame) {
form_manager_.ResetFrame(frame);
}
void AutoFillAgent::FrameWillClose(WebKit::WebFrame* frame) {
form_manager_.ResetFrame(frame);
}
void AutoFillAgent::FrameTranslated(WebKit::WebFrame* frame) {
// The page is translated, so try to extract the form data again.
DidFinishDocumentLoad(frame);
}
bool AutoFillAgent::InputElementClicked(const WebInputElement& element,
bool was_focused,
bool is_focused) {
if (was_focused)
ShowSuggestions(element, true, false, true);
return false;
}
void AutoFillAgent::didAcceptAutoFillSuggestion(const WebKit::WebNode& node,
const WebKit::WebString& value,
const WebKit::WebString& label,
int unique_id,
unsigned index) {
if (suggestions_options_index_ != -1 &&
index == static_cast<unsigned>(suggestions_options_index_)) {
// User selected 'AutoFill Options'.
Send(new AutoFillHostMsg_ShowAutoFillDialog(routing_id()));
} else if (suggestions_clear_index_ != -1 &&
index == static_cast<unsigned>(suggestions_clear_index_)) {
// User selected 'Clear form'.
form_manager_.ClearFormWithNode(node);
} else if (!unique_id) {
// User selected an Autocomplete entry, so we fill directly.
WebInputElement element = node.toConst<WebInputElement>();
string16 substring = value;
substring = substring.substr(0, element.maxLength());
element.setValue(substring);
WebFrame* webframe = node.document().frame();
if (webframe)
webframe->notifiyPasswordListenerOfAutocomplete(element);
} else {
// Fill the values for the whole form.
FillAutoFillFormData(node, unique_id, AUTOFILL_FILL);
}
suggestions_clear_index_ = -1;
suggestions_options_index_ = -1;
}
void AutoFillAgent::didSelectAutoFillSuggestion(const WebKit::WebNode& node,
const WebKit::WebString& value,
const WebKit::WebString& label,
int unique_id) {
DCHECK_GE(unique_id, 0);
if (password_autofill_manager_->DidSelectAutoFillSuggestion(node, value))
return;
didClearAutoFillSelection(node);
FillAutoFillFormData(node, unique_id, AUTOFILL_PREVIEW);
}
void AutoFillAgent::didClearAutoFillSelection(const WebKit::WebNode& node) {
form_manager_.ClearPreviewedFormWithNode(node, was_query_node_autofilled_);
}
void AutoFillAgent::removeAutocompleteSuggestion(
const WebKit::WebString& name,
const WebKit::WebString& value) {
// The index of clear & options will have shifted down.
if (suggestions_clear_index_ != -1)
suggestions_clear_index_--;
if (suggestions_options_index_ != -1)
suggestions_options_index_--;
Send(new AutoFillHostMsg_RemoveAutocompleteEntry(routing_id(), name, value));
}
void AutoFillAgent::textFieldDidEndEditing(
const WebKit::WebInputElement& element) {
password_autofill_manager_->TextFieldDidEndEditing(element);
}
void AutoFillAgent::textFieldDidChange(const WebKit::WebInputElement& element) {
// We post a task for doing the AutoFill as the caret position is not set
// properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
// it is needed to trigger autofill.
method_factory_.RevokeAll();
MessageLoop::current()->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&AutoFillAgent::TextFieldDidChangeImpl, element));
}
void AutoFillAgent::TextFieldDidChangeImpl(
const WebKit::WebInputElement& element) {
if (password_autofill_manager_->TextDidChangeInTextField(element))
return;
ShowSuggestions(element, false, true, false);
}
void AutoFillAgent::textFieldDidReceiveKeyDown(
const WebKit::WebInputElement& element,
const WebKit::WebKeyboardEvent& event) {
if (password_autofill_manager_->TextFieldHandlingKeyDown(element, event))
return;
if (event.windowsKeyCode == ui::VKEY_DOWN ||
event.windowsKeyCode == ui::VKEY_UP)
ShowSuggestions(element, true, true, true);
}
void AutoFillAgent::OnSuggestionsReturned(int query_id,
const std::vector<string16>& values,
const std::vector<string16>& labels,
const std::vector<string16>& icons,
const std::vector<int>& unique_ids) {
WebKit::WebView* web_view = render_view()->webview();
if (!web_view || query_id != autofill_query_id_)
return;
if (values.empty()) {
// No suggestions, any popup currently showing is obsolete.
web_view->hidePopups();
return;
}
std::vector<string16> v(values);
std::vector<string16> l(labels);
std::vector<string16> i(icons);
std::vector<int> ids(unique_ids);
int separator_index = -1;
if (ids[0] < 0 && ids.size() > 1) {
// If we received a warning instead of suggestions from autofill but regular
// suggestions from autocomplete, don't show the autofill warning.
v.erase(v.begin());
l.erase(l.begin());
i.erase(i.begin());
ids.erase(ids.begin());
}
// If we were about to show a warning and we shouldn't, don't.
if (ids[0] < 0 && !display_warning_if_disabled_)
return;
// Only include "AutoFill Options" special menu item if we have AutoFill
// items, identified by |unique_ids| having at least one valid value.
bool has_autofill_item = false;
for (size_t i = 0; i < ids.size(); ++i) {
if (ids[i] > 0) {
has_autofill_item = true;
break;
}
}
// The form has been auto-filled, so give the user the chance to clear the
// form. Append the 'Clear form' menu item.
if (has_autofill_item &&
form_manager_.FormWithNodeIsAutoFilled(autofill_query_node_)) {
v.push_back(l10n_util::GetStringUTF16(IDS_AUTOFILL_CLEAR_FORM_MENU_ITEM));
l.push_back(string16());
i.push_back(string16());
ids.push_back(0);
suggestions_clear_index_ = v.size() - 1;
separator_index = v.size() - 1;
}
if (has_autofill_item) {
// Append the 'Chrome Autofill options' menu item;
v.push_back(l10n_util::GetStringFUTF16(IDS_AUTOFILL_OPTIONS_POPUP,
WideToUTF16(chrome::kBrowserAppName)));
l.push_back(string16());
i.push_back(string16());
ids.push_back(0);
suggestions_options_index_ = v.size() - 1;
separator_index = values.size();
}
// Send to WebKit for display.
if (!v.empty() && autofill_query_node_.hasNonEmptyBoundingBox()) {
web_view->applyAutoFillSuggestions(
autofill_query_node_, v, l, i, ids, separator_index);
}
Send(new AutoFillHostMsg_DidShowAutoFillSuggestions(routing_id()));
}
void AutoFillAgent::OnFormDataFilled(int query_id,
const webkit_glue::FormData& form) {
if (!render_view()->webview() || query_id != autofill_query_id_)
return;
switch (autofill_action_) {
case AUTOFILL_FILL:
form_manager_.FillForm(form, autofill_query_node_);
break;
case AUTOFILL_PREVIEW:
form_manager_.PreviewForm(form, autofill_query_node_);
break;
default:
NOTREACHED();
}
autofill_action_ = AUTOFILL_NONE;
Send(new AutoFillHostMsg_DidFillAutoFillFormData(routing_id()));
}
void AutoFillAgent::ShowSuggestions(const WebInputElement& element,
bool autofill_on_empty_values,
bool requires_caret_at_end,
bool display_warning_if_disabled) {
if (!element.isEnabledFormControl() || !element.isTextField() ||
element.isPasswordField() || element.isReadOnly() ||
!element.autoComplete())
return;
// If the field has no name, then we won't have values.
if (element.nameForAutofill().isEmpty())
return;
// Don't attempt to autofill with values that are too large.
WebString value = element.value();
if (value.length() > kMaximumTextSizeForAutoFill)
return;
if (!autofill_on_empty_values && value.isEmpty())
return;
if (requires_caret_at_end &&
(element.selectionStart() != element.selectionEnd() ||
element.selectionEnd() != static_cast<int>(value.length())))
return;
QueryAutoFillSuggestions(element, display_warning_if_disabled);
}
void AutoFillAgent::QueryAutoFillSuggestions(const WebNode& node,
bool display_warning_if_disabled) {
static int query_counter = 0;
autofill_query_id_ = query_counter++;
autofill_query_node_ = node;
display_warning_if_disabled_ = display_warning_if_disabled;
webkit_glue::FormData form;
webkit_glue::FormField field;
if (!FindFormAndFieldForNode(node, &form, &field)) {
// If we didn't find the cached form, at least let autocomplete have a shot
// at providing suggestions.
FormManager::WebFormControlElementToFormField(
node.toConst<WebFormControlElement>(), FormManager::EXTRACT_VALUE,
&field);
}
Send(new AutoFillHostMsg_QueryFormFieldAutoFill(
routing_id(), autofill_query_id_, form, field));
}
void AutoFillAgent::FillAutoFillFormData(const WebNode& node,
int unique_id,
AutoFillAction action) {
static int query_counter = 0;
autofill_query_id_ = query_counter++;
webkit_glue::FormData form;
webkit_glue::FormField field;
if (!FindFormAndFieldForNode(node, &form, &field))
return;
autofill_action_ = action;
was_query_node_autofilled_ = field.is_autofilled();
Send(new AutoFillHostMsg_FillAutoFillFormData(
routing_id(), autofill_query_id_, form, field, unique_id));
}
void AutoFillAgent::SendForms(WebFrame* frame) {
std::vector<webkit_glue::FormData> forms;
form_manager_.GetFormsInFrame(frame, FormManager::REQUIRE_NONE, &forms);
if (!forms.empty())
Send(new AutoFillHostMsg_FormsSeen(routing_id(), forms));
}
bool AutoFillAgent::FindFormAndFieldForNode(const WebNode& node,
webkit_glue::FormData* form,
webkit_glue::FormField* field) {
const WebInputElement& element = node.toConst<WebInputElement>();
if (!form_manager_.FindFormWithFormControlElement(element,
FormManager::REQUIRE_NONE,
form))
return false;
FormManager::WebFormControlElementToFormField(element,
FormManager::EXTRACT_VALUE,
field);
// WebFormControlElementToFormField does not scrape the DOM for the field
// label, so find the label here.
// TODO(jhawkins): Add form and field identities so we can use the cached form
// data in FormManager.
field->set_label(FormManager::LabelForElement(element));
return true;
}
} // namespace autofill
<commit_msg>Autofill crasher Chrome:+Crash+Report+-+Stack+Signature:+WebCore::Node::renderBoxModelObject()<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/renderer/autofill/autofill_agent.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/autofill_messages.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/renderer/autofill/password_autofill_manager.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormControlElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/form_data.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/password_form.h"
using WebKit::WebFormControlElement;
using WebKit::WebFormElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebKeyboardEvent;
using WebKit::WebNode;
using WebKit::WebString;
namespace {
// The size above which we stop triggering autofill for an input text field
// (so to avoid sending long strings through IPC).
const size_t kMaximumTextSizeForAutoFill = 1000;
} // namespace
namespace autofill {
AutoFillAgent::AutoFillAgent(
RenderView* render_view,
PasswordAutoFillManager* password_autofill_manager)
: RenderViewObserver(render_view),
password_autofill_manager_(password_autofill_manager),
autofill_query_id_(0),
autofill_action_(AUTOFILL_NONE),
display_warning_if_disabled_(false),
was_query_node_autofilled_(false),
suggestions_clear_index_(-1),
suggestions_options_index_(-1),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
}
AutoFillAgent::~AutoFillAgent() {}
bool AutoFillAgent::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(AutoFillAgent, message)
IPC_MESSAGE_HANDLER(AutoFillMsg_SuggestionsReturned, OnSuggestionsReturned)
IPC_MESSAGE_HANDLER(AutoFillMsg_FormDataFilled, OnFormDataFilled)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void AutoFillAgent::DidFinishDocumentLoad(WebKit::WebFrame* frame) {
// The document has now been fully loaded. Scan for forms to be sent up to
// the browser.
form_manager_.ExtractForms(frame);
SendForms(frame);
}
void AutoFillAgent::FrameDetached(WebKit::WebFrame* frame) {
form_manager_.ResetFrame(frame);
}
void AutoFillAgent::FrameWillClose(WebKit::WebFrame* frame) {
form_manager_.ResetFrame(frame);
}
void AutoFillAgent::FrameTranslated(WebKit::WebFrame* frame) {
// The page is translated, so try to extract the form data again.
DidFinishDocumentLoad(frame);
}
bool AutoFillAgent::InputElementClicked(const WebInputElement& element,
bool was_focused,
bool is_focused) {
if (was_focused)
ShowSuggestions(element, true, false, true);
return false;
}
void AutoFillAgent::didAcceptAutoFillSuggestion(const WebKit::WebNode& node,
const WebKit::WebString& value,
const WebKit::WebString& label,
int unique_id,
unsigned index) {
if (suggestions_options_index_ != -1 &&
index == static_cast<unsigned>(suggestions_options_index_)) {
// User selected 'AutoFill Options'.
Send(new AutoFillHostMsg_ShowAutoFillDialog(routing_id()));
} else if (suggestions_clear_index_ != -1 &&
index == static_cast<unsigned>(suggestions_clear_index_)) {
// User selected 'Clear form'.
form_manager_.ClearFormWithNode(node);
} else if (!unique_id) {
// User selected an Autocomplete entry, so we fill directly.
WebInputElement element = node.toConst<WebInputElement>();
string16 substring = value;
substring = substring.substr(0, element.maxLength());
element.setValue(substring);
WebFrame* webframe = node.document().frame();
if (webframe)
webframe->notifiyPasswordListenerOfAutocomplete(element);
} else {
// Fill the values for the whole form.
FillAutoFillFormData(node, unique_id, AUTOFILL_FILL);
}
suggestions_clear_index_ = -1;
suggestions_options_index_ = -1;
}
void AutoFillAgent::didSelectAutoFillSuggestion(const WebKit::WebNode& node,
const WebKit::WebString& value,
const WebKit::WebString& label,
int unique_id) {
DCHECK_GE(unique_id, 0);
if (password_autofill_manager_->DidSelectAutoFillSuggestion(node, value))
return;
didClearAutoFillSelection(node);
FillAutoFillFormData(node, unique_id, AUTOFILL_PREVIEW);
}
void AutoFillAgent::didClearAutoFillSelection(const WebKit::WebNode& node) {
form_manager_.ClearPreviewedFormWithNode(node, was_query_node_autofilled_);
}
void AutoFillAgent::removeAutocompleteSuggestion(
const WebKit::WebString& name,
const WebKit::WebString& value) {
// The index of clear & options will have shifted down.
if (suggestions_clear_index_ != -1)
suggestions_clear_index_--;
if (suggestions_options_index_ != -1)
suggestions_options_index_--;
Send(new AutoFillHostMsg_RemoveAutocompleteEntry(routing_id(), name, value));
}
void AutoFillAgent::textFieldDidEndEditing(
const WebKit::WebInputElement& element) {
password_autofill_manager_->TextFieldDidEndEditing(element);
}
void AutoFillAgent::textFieldDidChange(const WebKit::WebInputElement& element) {
// We post a task for doing the AutoFill as the caret position is not set
// properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
// it is needed to trigger autofill.
method_factory_.RevokeAll();
MessageLoop::current()->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&AutoFillAgent::TextFieldDidChangeImpl, element));
}
void AutoFillAgent::TextFieldDidChangeImpl(
const WebKit::WebInputElement& element) {
if (password_autofill_manager_->TextDidChangeInTextField(element))
return;
ShowSuggestions(element, false, true, false);
}
void AutoFillAgent::textFieldDidReceiveKeyDown(
const WebKit::WebInputElement& element,
const WebKit::WebKeyboardEvent& event) {
if (password_autofill_manager_->TextFieldHandlingKeyDown(element, event))
return;
if (event.windowsKeyCode == ui::VKEY_DOWN ||
event.windowsKeyCode == ui::VKEY_UP)
ShowSuggestions(element, true, true, true);
}
void AutoFillAgent::OnSuggestionsReturned(int query_id,
const std::vector<string16>& values,
const std::vector<string16>& labels,
const std::vector<string16>& icons,
const std::vector<int>& unique_ids) {
WebKit::WebView* web_view = render_view()->webview();
if (!web_view || query_id != autofill_query_id_)
return;
if (values.empty()) {
// No suggestions, any popup currently showing is obsolete.
web_view->hidePopups();
return;
}
std::vector<string16> v(values);
std::vector<string16> l(labels);
std::vector<string16> i(icons);
std::vector<int> ids(unique_ids);
int separator_index = -1;
if (ids[0] < 0 && ids.size() > 1) {
// If we received a warning instead of suggestions from autofill but regular
// suggestions from autocomplete, don't show the autofill warning.
v.erase(v.begin());
l.erase(l.begin());
i.erase(i.begin());
ids.erase(ids.begin());
}
// If we were about to show a warning and we shouldn't, don't.
if (ids[0] < 0 && !display_warning_if_disabled_)
return;
// Only include "AutoFill Options" special menu item if we have AutoFill
// items, identified by |unique_ids| having at least one valid value.
bool has_autofill_item = false;
for (size_t i = 0; i < ids.size(); ++i) {
if (ids[i] > 0) {
has_autofill_item = true;
break;
}
}
// The form has been auto-filled, so give the user the chance to clear the
// form. Append the 'Clear form' menu item.
if (has_autofill_item &&
form_manager_.FormWithNodeIsAutoFilled(autofill_query_node_)) {
v.push_back(l10n_util::GetStringUTF16(IDS_AUTOFILL_CLEAR_FORM_MENU_ITEM));
l.push_back(string16());
i.push_back(string16());
ids.push_back(0);
suggestions_clear_index_ = v.size() - 1;
separator_index = v.size() - 1;
}
if (has_autofill_item) {
// Append the 'Chrome Autofill options' menu item;
v.push_back(l10n_util::GetStringFUTF16(IDS_AUTOFILL_OPTIONS_POPUP,
WideToUTF16(chrome::kBrowserAppName)));
l.push_back(string16());
i.push_back(string16());
ids.push_back(0);
suggestions_options_index_ = v.size() - 1;
separator_index = values.size();
}
// Send to WebKit for display.
if (!v.empty() && !autofill_query_node_.isNull() &&
autofill_query_node_.hasNonEmptyBoundingBox()) {
web_view->applyAutoFillSuggestions(
autofill_query_node_, v, l, i, ids, separator_index);
}
Send(new AutoFillHostMsg_DidShowAutoFillSuggestions(routing_id()));
}
void AutoFillAgent::OnFormDataFilled(int query_id,
const webkit_glue::FormData& form) {
if (!render_view()->webview() || query_id != autofill_query_id_)
return;
switch (autofill_action_) {
case AUTOFILL_FILL:
form_manager_.FillForm(form, autofill_query_node_);
break;
case AUTOFILL_PREVIEW:
form_manager_.PreviewForm(form, autofill_query_node_);
break;
default:
NOTREACHED();
}
autofill_action_ = AUTOFILL_NONE;
Send(new AutoFillHostMsg_DidFillAutoFillFormData(routing_id()));
}
void AutoFillAgent::ShowSuggestions(const WebInputElement& element,
bool autofill_on_empty_values,
bool requires_caret_at_end,
bool display_warning_if_disabled) {
if (!element.isEnabledFormControl() || !element.isTextField() ||
element.isPasswordField() || element.isReadOnly() ||
!element.autoComplete())
return;
// If the field has no name, then we won't have values.
if (element.nameForAutofill().isEmpty())
return;
// Don't attempt to autofill with values that are too large.
WebString value = element.value();
if (value.length() > kMaximumTextSizeForAutoFill)
return;
if (!autofill_on_empty_values && value.isEmpty())
return;
if (requires_caret_at_end &&
(element.selectionStart() != element.selectionEnd() ||
element.selectionEnd() != static_cast<int>(value.length())))
return;
QueryAutoFillSuggestions(element, display_warning_if_disabled);
}
void AutoFillAgent::QueryAutoFillSuggestions(const WebNode& node,
bool display_warning_if_disabled) {
static int query_counter = 0;
autofill_query_id_ = query_counter++;
autofill_query_node_ = node;
display_warning_if_disabled_ = display_warning_if_disabled;
webkit_glue::FormData form;
webkit_glue::FormField field;
if (!FindFormAndFieldForNode(node, &form, &field)) {
// If we didn't find the cached form, at least let autocomplete have a shot
// at providing suggestions.
FormManager::WebFormControlElementToFormField(
node.toConst<WebFormControlElement>(), FormManager::EXTRACT_VALUE,
&field);
}
Send(new AutoFillHostMsg_QueryFormFieldAutoFill(
routing_id(), autofill_query_id_, form, field));
}
void AutoFillAgent::FillAutoFillFormData(const WebNode& node,
int unique_id,
AutoFillAction action) {
static int query_counter = 0;
autofill_query_id_ = query_counter++;
webkit_glue::FormData form;
webkit_glue::FormField field;
if (!FindFormAndFieldForNode(node, &form, &field))
return;
autofill_action_ = action;
was_query_node_autofilled_ = field.is_autofilled();
Send(new AutoFillHostMsg_FillAutoFillFormData(
routing_id(), autofill_query_id_, form, field, unique_id));
}
void AutoFillAgent::SendForms(WebFrame* frame) {
std::vector<webkit_glue::FormData> forms;
form_manager_.GetFormsInFrame(frame, FormManager::REQUIRE_NONE, &forms);
if (!forms.empty())
Send(new AutoFillHostMsg_FormsSeen(routing_id(), forms));
}
bool AutoFillAgent::FindFormAndFieldForNode(const WebNode& node,
webkit_glue::FormData* form,
webkit_glue::FormField* field) {
const WebInputElement& element = node.toConst<WebInputElement>();
if (!form_manager_.FindFormWithFormControlElement(element,
FormManager::REQUIRE_NONE,
form))
return false;
FormManager::WebFormControlElementToFormField(element,
FormManager::EXTRACT_VALUE,
field);
// WebFormControlElementToFormField does not scrape the DOM for the field
// label, so find the label here.
// TODO(jhawkins): Add form and field identities so we can use the cached form
// data in FormManager.
field->set_label(FormManager::LabelForElement(element));
return true;
}
} // namespace autofill
<|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/renderer/pepper_scrollbar_widget.h"
#include "base/basictypes.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/renderer/pepper_devices.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScrollBar.h"
#include "webkit/glue/plugins/plugin_instance.h"
using WebKit::WebInputEvent;
using WebKit::WebKeyboardEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
using WebKit::WebRect;
using WebKit::WebScrollbar;
using WebKit::WebVector;
// Anonymous namespace for functions converting NPAPI to WebInputEvents types.
namespace {
WebKeyboardEvent BuildKeyEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
switch (event.type) {
case NPEventType_RawKeyDown:
key_event.type = WebInputEvent::RawKeyDown;
break;
case NPEventType_KeyDown:
key_event.type = WebInputEvent::KeyDown;
break;
case NPEventType_KeyUp:
key_event.type = WebInputEvent::KeyUp;
break;
}
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.key.modifier;
key_event.windowsKeyCode = event.u.key.normalizedKeyCode;
return key_event;
}
WebKeyboardEvent BuildCharEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
key_event.type = WebInputEvent::Char;
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.character.modifier;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(event.u.character.text) == sizeof(key_event.text));
DCHECK(sizeof(event.u.character.unmodifiedText) ==
sizeof(key_event.unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
key_event.text[i] = event.u.character.text[i];
key_event.unmodifiedText[i] = event.u.character.unmodifiedText[i];
}
return key_event;
}
WebMouseEvent BuildMouseEvent(const NPPepperEvent& event) {
WebMouseEvent mouse_event;
switch (event.type) {
case NPEventType_MouseDown:
mouse_event.type = WebInputEvent::MouseDown;
break;
case NPEventType_MouseUp:
mouse_event.type = WebInputEvent::MouseUp;
break;
case NPEventType_MouseMove:
mouse_event.type = WebInputEvent::MouseMove;
break;
case NPEventType_MouseEnter:
mouse_event.type = WebInputEvent::MouseEnter;
break;
case NPEventType_MouseLeave:
mouse_event.type = WebInputEvent::MouseLeave;
break;
}
mouse_event.timeStampSeconds = event.timeStampSeconds;
mouse_event.modifiers = event.u.mouse.modifier;
mouse_event.button = static_cast<WebMouseEvent::Button>(event.u.mouse.button);
mouse_event.x = event.u.mouse.x;
mouse_event.y = event.u.mouse.y;
mouse_event.clickCount = event.u.mouse.clickCount;
return mouse_event;
}
WebMouseWheelEvent BuildMouseWheelEvent(const NPPepperEvent& event) {
WebMouseWheelEvent mouse_wheel_event;
mouse_wheel_event.type = WebInputEvent::MouseWheel;
mouse_wheel_event.timeStampSeconds = event.timeStampSeconds;
mouse_wheel_event.modifiers = event.u.wheel.modifier;
mouse_wheel_event.deltaX = event.u.wheel.deltaX;
mouse_wheel_event.deltaY = event.u.wheel.deltaY;
mouse_wheel_event.wheelTicksX = event.u.wheel.wheelTicksX;
mouse_wheel_event.wheelTicksY = event.u.wheel.wheelTicksY;
mouse_wheel_event.scrollByPage = event.u.wheel.scrollByPage;
return mouse_wheel_event;
}
} // namespace
PepperScrollbarWidget::PepperScrollbarWidget(
const NPScrollbarCreateParams& params) {
scrollbar_.reset(WebScrollbar::create(
static_cast<WebKit::WebScrollbarClient*>(this),
params.vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));
AddRef();
}
PepperScrollbarWidget::~PepperScrollbarWidget() {
}
void PepperScrollbarWidget::Destroy() {
Release();
}
void PepperScrollbarWidget::Paint(Graphics2DDeviceContext* context,
const NPRect& dirty) {
gfx::Rect rect(dirty.left, dirty.top, dirty.right - dirty.left,
dirty.bottom - dirty.top);
#if defined(OS_WIN) || defined(OS_LINUX)
scrollbar_->paint(context->canvas(), rect);
#elif defined(OS_MACOSX)
// TODO(port)
#endif
dirty_rect_ = dirty_rect_.Subtract(rect);
}
bool PepperScrollbarWidget::HandleEvent(const NPPepperEvent& event) {
bool rv = false;
switch (event.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
rv = scrollbar_->handleInputEvent(BuildMouseEvent(event));
break;
case NPEventType_MouseWheel:
rv = scrollbar_->handleInputEvent(BuildMouseWheelEvent(event));
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
rv = scrollbar_->handleInputEvent(BuildKeyEvent(event));
break;
case NPEventType_Char:
rv = scrollbar_->handleInputEvent(BuildCharEvent(event));
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
return rv;
}
void PepperScrollbarWidget::GetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* rv = static_cast<NPRect*>(value);
rv->left = location_.x();
rv->top = location_.y();
rv->right = location_.right();
rv->bottom = location_.bottom();
break;
}
case NPWidgetPropertyDirtyRect: {
NPRect* rv = reinterpret_cast<NPRect*>(value);
rv->left = dirty_rect_.x();
rv->top = dirty_rect_.y();
rv->right = dirty_rect_.right();
rv->bottom = dirty_rect_.bottom();
break;
}
case NPWidgetPropertyScrollbarThickness: {
int32* rv = static_cast<int32*>(value);
*rv = WebScrollbar::defaultThickness();
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* rv = static_cast<int32*>(value);
*rv = scrollbar_->value();
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::SetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* r = static_cast<NPRect*>(value);
location_ = gfx::Rect(
r->left, r->top, r->right - r->left, r->bottom - r->top);
scrollbar_->setLocation(location_);
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* position = static_cast<int*>(value);
scrollbar_->setValue(*position);
break;
}
case NPWidgetPropertyScrollbarDocumentSize: {
int32* total_length = static_cast<int32*>(value);
scrollbar_->setDocumentSize(*total_length);
break;
}
case NPWidgetPropertyScrollbarTickMarks: {
NPScrollbarTickMarks* tickmarks =
static_cast<NPScrollbarTickMarks*>(value);
tickmarks_.resize(tickmarks->count);
for (uint32 i = 0; i < tickmarks->count; ++i) {
WebRect rect(
tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].top,
tickmarks->tickmarks[i].right - tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].bottom - tickmarks->tickmarks[i].top);
tickmarks_[i] = rect;
}
dirty_rect_ = location_;
NotifyInvalidate();
break;
}
case NPWidgetPropertyScrollbarScrollByLine:
case NPWidgetPropertyScrollbarScrollByPage:
case NPWidgetPropertyScrollbarScrollByDocument:
case NPWidgetPropertyScrollbarScrollByPixels: {
bool forward;
float multiplier = 1.0;
WebScrollbar::ScrollGranularity granularity;
if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByLine;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByPage;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByDocument;
} else {
multiplier = static_cast<float>(*static_cast<int32*>(value));
forward = multiplier >= 0;
if (multiplier < 0)
multiplier *= -1;
granularity = WebScrollbar::ScrollByPixel;
}
scrollbar_->scroll(
forward ? WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward,
granularity, multiplier);
break;
}
}
}
void PepperScrollbarWidget::valueChanged(WebScrollbar*) {
WidgetPropertyChanged(NPWidgetPropertyScrollbarValue);
}
void PepperScrollbarWidget::invalidateScrollbarRect(WebScrollbar*,
const WebRect& rect) {
dirty_rect_ = dirty_rect_.Union(rect);
// Can't call into the client to tell them about the invalidate right away,
// since the Scrollbar code is still in the middle of updating its internal
// state.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &PepperScrollbarWidget::NotifyInvalidate));
}
void PepperScrollbarWidget::getTickmarks(WebKit::WebScrollbar*,
WebVector<WebRect>* tickmarks) const {
if (tickmarks_.empty()) {
WebRect* rects = NULL;
tickmarks->assign(rects, 0);
} else {
tickmarks->assign(&tickmarks_[0], tickmarks_.size());
}
}
void PepperScrollbarWidget::NotifyInvalidate() {
if (!dirty_rect_.IsEmpty())
WidgetPropertyChanged(NPWidgetPropertyDirtyRect);
}
<commit_msg>Fix Mac buildbreak<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/renderer/pepper_scrollbar_widget.h"
#include "base/basictypes.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/renderer/pepper_devices.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScrollBar.h"
#include "webkit/glue/plugins/plugin_instance.h"
using WebKit::WebInputEvent;
using WebKit::WebKeyboardEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
using WebKit::WebRect;
using WebKit::WebScrollbar;
using WebKit::WebVector;
// Anonymous namespace for functions converting NPAPI to WebInputEvents types.
namespace {
WebKeyboardEvent BuildKeyEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
switch (event.type) {
case NPEventType_RawKeyDown:
key_event.type = WebInputEvent::RawKeyDown;
break;
case NPEventType_KeyDown:
key_event.type = WebInputEvent::KeyDown;
break;
case NPEventType_KeyUp:
key_event.type = WebInputEvent::KeyUp;
break;
}
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.key.modifier;
key_event.windowsKeyCode = event.u.key.normalizedKeyCode;
return key_event;
}
WebKeyboardEvent BuildCharEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
key_event.type = WebInputEvent::Char;
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.character.modifier;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(event.u.character.text) == sizeof(key_event.text));
DCHECK(sizeof(event.u.character.unmodifiedText) ==
sizeof(key_event.unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
key_event.text[i] = event.u.character.text[i];
key_event.unmodifiedText[i] = event.u.character.unmodifiedText[i];
}
return key_event;
}
WebMouseEvent BuildMouseEvent(const NPPepperEvent& event) {
WebMouseEvent mouse_event;
switch (event.type) {
case NPEventType_MouseDown:
mouse_event.type = WebInputEvent::MouseDown;
break;
case NPEventType_MouseUp:
mouse_event.type = WebInputEvent::MouseUp;
break;
case NPEventType_MouseMove:
mouse_event.type = WebInputEvent::MouseMove;
break;
case NPEventType_MouseEnter:
mouse_event.type = WebInputEvent::MouseEnter;
break;
case NPEventType_MouseLeave:
mouse_event.type = WebInputEvent::MouseLeave;
break;
}
mouse_event.timeStampSeconds = event.timeStampSeconds;
mouse_event.modifiers = event.u.mouse.modifier;
mouse_event.button = static_cast<WebMouseEvent::Button>(event.u.mouse.button);
mouse_event.x = event.u.mouse.x;
mouse_event.y = event.u.mouse.y;
mouse_event.clickCount = event.u.mouse.clickCount;
return mouse_event;
}
WebMouseWheelEvent BuildMouseWheelEvent(const NPPepperEvent& event) {
WebMouseWheelEvent mouse_wheel_event;
mouse_wheel_event.type = WebInputEvent::MouseWheel;
mouse_wheel_event.timeStampSeconds = event.timeStampSeconds;
mouse_wheel_event.modifiers = event.u.wheel.modifier;
mouse_wheel_event.deltaX = event.u.wheel.deltaX;
mouse_wheel_event.deltaY = event.u.wheel.deltaY;
mouse_wheel_event.wheelTicksX = event.u.wheel.wheelTicksX;
mouse_wheel_event.wheelTicksY = event.u.wheel.wheelTicksY;
mouse_wheel_event.scrollByPage = event.u.wheel.scrollByPage;
return mouse_wheel_event;
}
} // namespace
PepperScrollbarWidget::PepperScrollbarWidget(
const NPScrollbarCreateParams& params) {
scrollbar_.reset(WebScrollbar::create(
static_cast<WebKit::WebScrollbarClient*>(this),
params.vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));
AddRef();
}
PepperScrollbarWidget::~PepperScrollbarWidget() {
}
void PepperScrollbarWidget::Destroy() {
Release();
}
void PepperScrollbarWidget::Paint(Graphics2DDeviceContext* context,
const NPRect& dirty) {
gfx::Rect rect(dirty.left, dirty.top, dirty.right - dirty.left,
dirty.bottom - dirty.top);
#if defined(OS_WIN) || defined(OS_LINUX)
scrollbar_->paint(context->canvas(), rect);
#elif defined(OS_MACOSX)
// TODO(port)
#endif
dirty_rect_ = dirty_rect_.Subtract(rect);
}
bool PepperScrollbarWidget::HandleEvent(const NPPepperEvent& event) {
bool rv = false;
switch (event.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
rv = scrollbar_->handleInputEvent(BuildMouseEvent(event));
break;
case NPEventType_MouseWheel:
rv = scrollbar_->handleInputEvent(BuildMouseWheelEvent(event));
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
rv = scrollbar_->handleInputEvent(BuildKeyEvent(event));
break;
case NPEventType_Char:
rv = scrollbar_->handleInputEvent(BuildCharEvent(event));
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
return rv;
}
void PepperScrollbarWidget::GetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* rv = static_cast<NPRect*>(value);
rv->left = location_.x();
rv->top = location_.y();
rv->right = location_.right();
rv->bottom = location_.bottom();
break;
}
case NPWidgetPropertyDirtyRect: {
NPRect* rv = reinterpret_cast<NPRect*>(value);
rv->left = dirty_rect_.x();
rv->top = dirty_rect_.y();
rv->right = dirty_rect_.right();
rv->bottom = dirty_rect_.bottom();
break;
}
case NPWidgetPropertyScrollbarThickness: {
int32* rv = static_cast<int32*>(value);
*rv = WebScrollbar::defaultThickness();
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* rv = static_cast<int32*>(value);
*rv = scrollbar_->value();
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::SetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* r = static_cast<NPRect*>(value);
location_ = gfx::Rect(
r->left, r->top, r->right - r->left, r->bottom - r->top);
scrollbar_->setLocation(location_);
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* position = static_cast<int*>(value);
scrollbar_->setValue(*position);
break;
}
case NPWidgetPropertyScrollbarDocumentSize: {
int32* total_length = static_cast<int32*>(value);
scrollbar_->setDocumentSize(*total_length);
break;
}
case NPWidgetPropertyScrollbarTickMarks: {
NPScrollbarTickMarks* tickmarks =
static_cast<NPScrollbarTickMarks*>(value);
tickmarks_.resize(tickmarks->count);
for (uint32 i = 0; i < tickmarks->count; ++i) {
WebRect rect(
tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].top,
tickmarks->tickmarks[i].right - tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].bottom - tickmarks->tickmarks[i].top);
tickmarks_[i] = rect;
}
dirty_rect_ = location_;
NotifyInvalidate();
break;
}
case NPWidgetPropertyScrollbarScrollByLine:
case NPWidgetPropertyScrollbarScrollByPage:
case NPWidgetPropertyScrollbarScrollByDocument:
case NPWidgetPropertyScrollbarScrollByPixels: {
bool forward;
float multiplier = 1.0;
WebScrollbar::ScrollGranularity granularity;
if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByLine;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByPage;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByDocument;
} else {
multiplier = static_cast<float>(*static_cast<int32*>(value));
forward = multiplier >= 0;
if (multiplier < 0)
multiplier *= -1;
granularity = WebScrollbar::ScrollByPixel;
}
scrollbar_->scroll(
forward ? WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward,
granularity, multiplier);
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::valueChanged(WebScrollbar*) {
WidgetPropertyChanged(NPWidgetPropertyScrollbarValue);
}
void PepperScrollbarWidget::invalidateScrollbarRect(WebScrollbar*,
const WebRect& rect) {
dirty_rect_ = dirty_rect_.Union(rect);
// Can't call into the client to tell them about the invalidate right away,
// since the Scrollbar code is still in the middle of updating its internal
// state.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &PepperScrollbarWidget::NotifyInvalidate));
}
void PepperScrollbarWidget::getTickmarks(WebKit::WebScrollbar*,
WebVector<WebRect>* tickmarks) const {
if (tickmarks_.empty()) {
WebRect* rects = NULL;
tickmarks->assign(rects, 0);
} else {
tickmarks->assign(&tickmarks_[0], tickmarks_.size());
}
}
void PepperScrollbarWidget::NotifyInvalidate() {
if (!dirty_rect_.IsEmpty())
WidgetPropertyChanged(NPWidgetPropertyDirtyRect);
}
<|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/renderer/speech_input_dispatcher.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSpeechInputListener.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
using WebKit::WebFrame;
SpeechInputDispatcher::SpeechInputDispatcher(
RenderView* render_view, WebKit::WebSpeechInputListener* listener)
: render_view_(render_view),
listener_(listener) {
}
bool SpeechInputDispatcher::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SpeechInputDispatcher, message)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_SetRecognitionResult,
OnSpeechRecognitionResult)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_RecordingComplete,
OnSpeechRecordingComplete)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_RecognitionComplete,
OnSpeechRecognitionComplete)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool SpeechInputDispatcher::startRecognition(
int request_id, const WebKit::WebString& language,
const WebKit::WebRect& element_rect) {
return startRecognition(request_id, element_rect);
}
bool SpeechInputDispatcher::startRecognition(
int request_id, const WebKit::WebRect& element_rect) {
VLOG(1) << "SpeechInputDispatcher::startRecognition enter";
gfx::Size scroll = render_view_->webview()->mainFrame()->scrollOffset();
gfx::Rect rect = element_rect;
rect.Offset(-scroll.width(), -scroll.height());
render_view_->Send(new ViewHostMsg_SpeechInput_StartRecognition(
render_view_->routing_id(), request_id, rect));
VLOG(1) << "SpeechInputDispatcher::startRecognition exit";
return true;
}
void SpeechInputDispatcher::cancelRecognition(int request_id) {
VLOG(1) << "SpeechInputDispatcher::cancelRecognition enter";
render_view_->Send(new ViewHostMsg_SpeechInput_CancelRecognition(
render_view_->routing_id(), request_id));
VLOG(1) << "SpeechInputDispatcher::cancelRecognition exit";
}
void SpeechInputDispatcher::stopRecording(int request_id) {
VLOG(1) << "SpeechInputDispatcher::stopRecording enter";
render_view_->Send(new ViewHostMsg_SpeechInput_StopRecording(
render_view_->routing_id(), request_id));
VLOG(1) << "SpeechInputDispatcher::stopRecording exit";
}
void SpeechInputDispatcher::OnSpeechRecognitionResult(
int request_id, const string16& result) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionResult enter";
listener_->setRecognitionResult(request_id, result);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionResult exit";
}
void SpeechInputDispatcher::OnSpeechRecordingComplete(int request_id) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecordingComplete enter";
listener_->didCompleteRecording(request_id);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecordingComplete exit";
}
void SpeechInputDispatcher::OnSpeechRecognitionComplete(int request_id) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionComplete enter";
listener_->didCompleteRecognition(request_id);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionComplete exit";
}
<commit_msg>Construct a WebString explicitly and pass to a WebKit method. This is to prevent build errors when https://bugs.webkit.org/show_bug.cgi?id=48068 lands.<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/renderer/speech_input_dispatcher.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSpeechInputListener.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
using WebKit::WebFrame;
SpeechInputDispatcher::SpeechInputDispatcher(
RenderView* render_view, WebKit::WebSpeechInputListener* listener)
: render_view_(render_view),
listener_(listener) {
}
bool SpeechInputDispatcher::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SpeechInputDispatcher, message)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_SetRecognitionResult,
OnSpeechRecognitionResult)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_RecordingComplete,
OnSpeechRecordingComplete)
IPC_MESSAGE_HANDLER(ViewMsg_SpeechInput_RecognitionComplete,
OnSpeechRecognitionComplete)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool SpeechInputDispatcher::startRecognition(
int request_id, const WebKit::WebString& language,
const WebKit::WebRect& element_rect) {
return startRecognition(request_id, element_rect);
}
bool SpeechInputDispatcher::startRecognition(
int request_id, const WebKit::WebRect& element_rect) {
VLOG(1) << "SpeechInputDispatcher::startRecognition enter";
gfx::Size scroll = render_view_->webview()->mainFrame()->scrollOffset();
gfx::Rect rect = element_rect;
rect.Offset(-scroll.width(), -scroll.height());
render_view_->Send(new ViewHostMsg_SpeechInput_StartRecognition(
render_view_->routing_id(), request_id, rect));
VLOG(1) << "SpeechInputDispatcher::startRecognition exit";
return true;
}
void SpeechInputDispatcher::cancelRecognition(int request_id) {
VLOG(1) << "SpeechInputDispatcher::cancelRecognition enter";
render_view_->Send(new ViewHostMsg_SpeechInput_CancelRecognition(
render_view_->routing_id(), request_id));
VLOG(1) << "SpeechInputDispatcher::cancelRecognition exit";
}
void SpeechInputDispatcher::stopRecording(int request_id) {
VLOG(1) << "SpeechInputDispatcher::stopRecording enter";
render_view_->Send(new ViewHostMsg_SpeechInput_StopRecording(
render_view_->routing_id(), request_id));
VLOG(1) << "SpeechInputDispatcher::stopRecording exit";
}
void SpeechInputDispatcher::OnSpeechRecognitionResult(
int request_id, const string16& result) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionResult enter";
WebKit::WebString webkit_result(result);
listener_->setRecognitionResult(request_id, webkit_result);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionResult exit";
}
void SpeechInputDispatcher::OnSpeechRecordingComplete(int request_id) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecordingComplete enter";
listener_->didCompleteRecording(request_id);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecordingComplete exit";
}
void SpeechInputDispatcher::OnSpeechRecognitionComplete(int request_id) {
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionComplete enter";
listener_->didCompleteRecognition(request_id);
VLOG(1) << "SpeechInputDispatcher::OnSpeechRecognitionComplete exit";
}
<|endoftext|> |
<commit_before>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "storage/persistenttable.h"
#include "storage/ElasticScanner.h"
namespace voltdb
{
namespace elastic
{
/**
* Constructor.
*/
Scanner::Scanner(PersistentTable &table) :
m_table(table),
m_blockMap(table.m_data),
m_tupleSize(table.getTupleLength()),
m_blockIterator(m_blockMap.begin()),
m_blockEnd(m_blockMap.end()),
m_currentBlockPtr(NULL),
m_tuplePtr(NULL),
m_tupleIndex(0)
{
}
/**
* Internal method that handles transitions between blocks and
* returns true as long as tuples are available.
*/
bool Scanner::continueScan() {
bool hasMore = true;
// First block or end of block?
if (m_currentBlockPtr == NULL || m_tupleIndex >= m_currentBlockPtr->unusedTupleBoundry()) {
// No more blocks?
hasMore = (m_blockIterator != m_blockEnd);
// Shift to the next block?
if (hasMore) {
m_tuplePtr = m_blockIterator.key();
m_currentBlockPtr = m_blockIterator.data();
assert(m_currentBlockPtr->address() == m_tuplePtr);
m_blockIterator.data() = TBPtr();
m_tupleIndex = 0;
m_blockIterator++;
}
}
return hasMore;
}
/**
* Get the next tuple or return false if none is available.
*/
bool Scanner::next(TableTuple &out)
{
bool found = false;
while (!found && continueScan()) {
assert(m_currentBlockPtr != NULL);
// Sanity checks.
assert(m_tuplePtr < m_currentBlockPtr.get()->address() + m_table.getTableAllocationSize());
assert(m_tuplePtr < m_currentBlockPtr.get()->address() + (m_tupleSize * m_table.getTuplesPerBlock()));
assert (out.sizeInValues() == m_table.columnCount());
// Grab the tuple pointer.
out.move(m_tuplePtr);
// Shift to the next tuple in block.
// continueScan() will check if it's the last one in the block.
m_tupleIndex++;
m_tuplePtr += m_tupleSize;
// The next active/non-dirty tuple is return-worthy.
found = out.isActive() && !out.isDirty();
}
return found;
}
/**
* Block compaction hook.
*/
void Scanner::notifyBlockWasCompactedAway(TBPtr block) {
if (m_blockIterator != m_blockEnd) {
TBPtr nextBlock = m_blockIterator.data();
if (nextBlock == block) {
// The next block was compacted away.
m_blockIterator++;
if (m_blockIterator != m_blockEnd) {
// There is a block to skip to.
TBPtr newNextBlock = m_blockIterator.data();
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.find(newNextBlock->address());
m_blockEnd = m_blockMap.end();
assert(m_blockIterator != m_blockMap.end());
}
else {
// There isn't a block to skip to, so we're done.
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.end();
m_blockEnd = m_blockMap.end();
}
} else {
// Some random block was compacted away.
// Remove it and regenerate the iterator.
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.find(nextBlock->address());
m_blockEnd = m_blockMap.end();
assert(m_blockIterator != m_blockMap.end());
}
}
}
/**
* Tuple insert hook.
*/
void Scanner::notifyTupleInsert(TableTuple &tuple) {
// Nothing to do for insert. The caller will deal with it.
}
/**
* Tuple update hook.
*/
void Scanner::notifyTupleUpdate(TableTuple &tuple) {
// Nothing to do for update. The caller will deal with it.
}
} // namespace elastic
} // namespace voltdb<commit_msg>ENG-4536 Fixed missing EOL at EOF.<commit_after>/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include "storage/persistenttable.h"
#include "storage/ElasticScanner.h"
namespace voltdb
{
namespace elastic
{
/**
* Constructor.
*/
Scanner::Scanner(PersistentTable &table) :
m_table(table),
m_blockMap(table.m_data),
m_tupleSize(table.getTupleLength()),
m_blockIterator(m_blockMap.begin()),
m_blockEnd(m_blockMap.end()),
m_currentBlockPtr(NULL),
m_tuplePtr(NULL),
m_tupleIndex(0)
{
}
/**
* Internal method that handles transitions between blocks and
* returns true as long as tuples are available.
*/
bool Scanner::continueScan() {
bool hasMore = true;
// First block or end of block?
if (m_currentBlockPtr == NULL || m_tupleIndex >= m_currentBlockPtr->unusedTupleBoundry()) {
// No more blocks?
hasMore = (m_blockIterator != m_blockEnd);
// Shift to the next block?
if (hasMore) {
m_tuplePtr = m_blockIterator.key();
m_currentBlockPtr = m_blockIterator.data();
assert(m_currentBlockPtr->address() == m_tuplePtr);
m_blockIterator.data() = TBPtr();
m_tupleIndex = 0;
m_blockIterator++;
}
}
return hasMore;
}
/**
* Get the next tuple or return false if none is available.
*/
bool Scanner::next(TableTuple &out)
{
bool found = false;
while (!found && continueScan()) {
assert(m_currentBlockPtr != NULL);
// Sanity checks.
assert(m_tuplePtr < m_currentBlockPtr.get()->address() + m_table.getTableAllocationSize());
assert(m_tuplePtr < m_currentBlockPtr.get()->address() + (m_tupleSize * m_table.getTuplesPerBlock()));
assert (out.sizeInValues() == m_table.columnCount());
// Grab the tuple pointer.
out.move(m_tuplePtr);
// Shift to the next tuple in block.
// continueScan() will check if it's the last one in the block.
m_tupleIndex++;
m_tuplePtr += m_tupleSize;
// The next active/non-dirty tuple is return-worthy.
found = out.isActive() && !out.isDirty();
}
return found;
}
/**
* Block compaction hook.
*/
void Scanner::notifyBlockWasCompactedAway(TBPtr block) {
if (m_blockIterator != m_blockEnd) {
TBPtr nextBlock = m_blockIterator.data();
if (nextBlock == block) {
// The next block was compacted away.
m_blockIterator++;
if (m_blockIterator != m_blockEnd) {
// There is a block to skip to.
TBPtr newNextBlock = m_blockIterator.data();
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.find(newNextBlock->address());
m_blockEnd = m_blockMap.end();
assert(m_blockIterator != m_blockMap.end());
}
else {
// There isn't a block to skip to, so we're done.
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.end();
m_blockEnd = m_blockMap.end();
}
} else {
// Some random block was compacted away.
// Remove it and regenerate the iterator.
m_blockMap.erase(block->address());
m_blockIterator = m_blockMap.find(nextBlock->address());
m_blockEnd = m_blockMap.end();
assert(m_blockIterator != m_blockMap.end());
}
}
}
/**
* Tuple insert hook.
*/
void Scanner::notifyTupleInsert(TableTuple &tuple) {
// Nothing to do for insert. The caller will deal with it.
}
/**
* Tuple update hook.
*/
void Scanner::notifyTupleUpdate(TableTuple &tuple) {
// Nothing to do for update. The caller will deal with it.
}
} // namespace elastic
} // namespace voltdb
<|endoftext|> |
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method
) {
// range errors: test all combinations of
// "wrong" (outside of correct range) arguments
// Max_index: 0; min_index: 0
for (int arg1 = -1; arg1 <= 1; arg1++) {
for (int arg2 = -1; arg2 <= 1; arg2++) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
}
}
// "dead" error
// (attempt to do something with dead bacterium)
model->kill(0, 0);
BOOST_REQUIRE_THROW(
((*model).*model_method)(0, 0), Exception
);
}
#define CREATE_NEW \
model->createNewByCoordinates( \
coordinates, \
DEFAULT_MASS, \
0, \
0, \
0 \
);
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
CREATE_NEW
return coordinates;
}
static void createByCoordinates(
Implementation::Model* model,
Abstract::Point coordinates
) {
CREATE_NEW
}
#undef CREATE_NEW
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(model, &Implementation::Model::getMass);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
// error handling checks
createInBaseCoordinates(model);
// FIXME test doesn't work correctly without this function call.
// The solution is to use set instead of vector in model.
model->clearBeforeMove(0);
checkErrorHandling(model, &Implementation::Model::kill);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
delete model;
}
<commit_msg>Implement checkModelMethodForThrow <TwoArgsMethod><commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<>
void checkModelMethodForThrow<TwoArgsMethod>(
Implementation::Model* model,
TwoArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates, 0), Exception
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method
) {
// range errors: test all combinations of
// "wrong" (outside of correct range) arguments
// Max_index: 0; min_index: 0
for (int arg1 = -1; arg1 <= 1; arg1++) {
for (int arg2 = -1; arg2 <= 1; arg2++) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
}
}
// "dead" error
// (attempt to do something with dead bacterium)
model->kill(0, 0);
BOOST_REQUIRE_THROW(
((*model).*model_method)(0, 0), Exception
);
}
#define CREATE_NEW \
model->createNewByCoordinates( \
coordinates, \
DEFAULT_MASS, \
0, \
0, \
0 \
);
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
CREATE_NEW
return coordinates;
}
static void createByCoordinates(
Implementation::Model* model,
Abstract::Point coordinates
) {
CREATE_NEW
}
#undef CREATE_NEW
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(model, &Implementation::Model::getMass);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
// error handling checks
createInBaseCoordinates(model);
// FIXME test doesn't work correctly without this function call.
// The solution is to use set instead of vector in model.
model->clearBeforeMove(0);
checkErrorHandling(model, &Implementation::Model::kill);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
delete model;
}
<|endoftext|> |
<commit_before>#include "AmsFont.h"
#include "constants.h"
const int CHAR_SIZE = 24;
const int MAX_COLUMN = SCREEN_W / CHAR_SIZE;
const int MAX_LINE = SCREEN_H / CHAR_SIZE;
AmsFont::AmsFont(char* fileName) {
font = SDL_LoadBMP(fileName);
SDL_Surface* surface = SDL_CreateRGBSurface(0, SCREEN_W, SCREEN_H, 32, 0, 0, 0, 0);
ctx = new RenderingContext(surface);
_x = 0;
_y = 0;
_clearRect = SDL_CreateRGBSurface(SDL_HWSURFACE, CHAR_SIZE, CHAR_SIZE, 32, 0, 0, 0, 0);
}
AmsFont::~AmsFont() {
delete ctx;
SDL_FreeSurface(_clearRect);
}
SDL_Surface* AmsFont::get() {
SDL_SetColorKey(ctx->getContext(), SDL_SRCCOLORKEY, SDL_MapRGB(ctx->getContext()->format, 0, 0, 0));
return ctx->getContext();
};
void AmsFont::locate(int x, int y) {
_x = x;
_y = y;
}
void AmsFont::print(char* text) {
while (*text) {
int c = *text;
text++;
if (c == '\n') {
_x = 0;
_y++;
continue;
}
int sourceX = (c % 16) * CHAR_SIZE;
int sourceY = (c / 16) * CHAR_SIZE;
int destX = _x * CHAR_SIZE;
int destY = _y * CHAR_SIZE;
// clear character background
_clearPos.x = destX;
_clearPos.y = destY;
SDL_BlitSurface(_clearRect, NULL, ctx->getContext(), &_clearPos);
ctx->drawImage(font, sourceX, sourceY, CHAR_SIZE, CHAR_SIZE, destX, destY);
if (++_x >= MAX_COLUMN) {
_x = 0;
if (++_y > MAX_LINE) {
_y--;
scroll(1);
}
}
}
}
void AmsFont::scroll(int) {
// save current
// TODO
}
<commit_msg>colored paper<commit_after>#include "AmsFont.h"
#include "constants.h"
const int CHAR_SIZE = 24;
const int MAX_COLUMN = SCREEN_W / CHAR_SIZE;
const int MAX_LINE = SCREEN_H / CHAR_SIZE;
AmsFont::AmsFont(char* fileName) {
font = SDL_LoadBMP(fileName);
SDL_Surface* surface = SDL_CreateRGBSurface(0, SCREEN_W, SCREEN_H, 32, 0, 0, 0, 0);
ctx = new RenderingContext(surface);
_x = 0;
_y = 0;
_clearRect = SDL_CreateRGBSurface(SDL_HWSURFACE, CHAR_SIZE, CHAR_SIZE, 32, 0, 0, 0, 0);
}
AmsFont::~AmsFont() {
delete ctx;
SDL_FreeSurface(_clearRect);
}
SDL_Surface* AmsFont::get() {
SDL_SetColorKey(ctx->getContext(), SDL_SRCCOLORKEY, SDL_MapRGB(ctx->getContext()->format, 0, 0, 0));
return ctx->getContext();
};
void AmsFont::locate(int x, int y) {
_x = x;
_y = y;
}
void AmsFont::print(char* text) {
while (*text) {
int c = *text;
text++;
if (c == '\n') {
_x = 0;
_y++;
continue;
}
int sourceX = (c % 16) * CHAR_SIZE;
int sourceY = (c / 16) * CHAR_SIZE;
int destX = _x * CHAR_SIZE;
int destY = _y * CHAR_SIZE;
// clear character background
_clearPos.x = destX;
_clearPos.y = destY;
SDL_FillRect(_clearRect, NULL, SDL_MapRGB(ctx->getContext()->format, 255, 5, 5));
SDL_BlitSurface(_clearRect, NULL, ctx->getContext(), &_clearPos);
ctx->drawImage(font, sourceX, sourceY, CHAR_SIZE, CHAR_SIZE, destX, destY);
if (++_x >= MAX_COLUMN) {
_x = 0;
if (++_y > MAX_LINE) {
_y--;
scroll(1);
}
}
}
}
void AmsFont::scroll(int) {
// save current
// TODO
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2015 Stefan Tröger <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
#include <QMenu>
#endif
#include "ViewProviderPipe.h"
//#include "TaskPipeParameters.h"
#include "TaskPipeParameters.h"
#include <Mod/PartDesign/App/Body.h>
#include <Mod/PartDesign/App/FeaturePipe.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <TopExp.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderPipe,PartDesignGui::ViewProvider)
ViewProviderPipe::ViewProviderPipe()
{
}
ViewProviderPipe::~ViewProviderPipe()
{
}
std::vector<App::DocumentObject*> ViewProviderPipe::claimChildren(void)const
{
std::vector<App::DocumentObject*> temp;
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
App::DocumentObject* sketch = pcPipe->getVerifiedSketch(true);
if (sketch != NULL)
temp.push_back(sketch);
App::DocumentObject* spine = pcPipe->Spine.getValue();
if (spine != NULL)
temp.push_back(spine);
App::DocumentObject* auxspine = pcPipe->AuxillerySpine.getValue();
if (auxspine != NULL)
temp.push_back(auxspine);
return temp;
}
void ViewProviderPipe::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
QAction* act;
act = menu->addAction(QObject::tr("Edit pipe"), receiver, member);
act->setData(QVariant((int)ViewProvider::Default));
}
bool ViewProviderPipe::doubleClicked(void)
{
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",this->pcObject->getNameInDocument());
return true;
}
bool ViewProviderPipe::setEdit(int ModNum) {
if (ModNum == ViewProvider::Default )
setPreviewDisplayMode(true);
return PartDesignGui::ViewProvider::setEdit(ModNum);
}
void ViewProviderPipe::unsetEdit(int ModNum) {
setPreviewDisplayMode(false);
PartDesignGui::ViewProvider::unsetEdit(ModNum);
}
TaskDlgFeatureParameters* ViewProviderPipe::getEditDialog() {
return new TaskDlgPipeParameters(this, false);
}
bool ViewProviderPipe::onDelete(const std::vector<std::string> &s)
{/*
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
// get the Sketch
Sketcher::SketchObject *pcSketch = 0;
if (pcPipe->Sketch.getValue())
pcSketch = static_cast<Sketcher::SketchObject*>(pcPipe->Sketch.getValue());
// if abort command deleted the object the sketch is visible again
if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
Gui::Application::Instance->getViewProvider(pcSketch)->show();
*/
return ViewProvider::onDelete(s);
}
void ViewProviderPipe::highlightReferences(const bool on, bool auxillery)
{
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
Part::Feature* base;
if(!auxillery)
base = static_cast<Part::Feature*>(pcPipe->Spine.getValue());
else
base = static_cast<Part::Feature*>(pcPipe->AuxillerySpine.getValue());
if (base == NULL) return;
PartGui::ViewProviderPart* svp = dynamic_cast<PartGui::ViewProviderPart*>(
Gui::Application::Instance->getViewProvider(base));
if (svp == NULL) return;
std::vector<std::string> edges;
if(!auxillery)
edges = pcPipe->Spine.getSubValuesStartsWith("Edge");
else
edges = pcPipe->AuxillerySpine.getSubValuesStartsWith("Edge");
if (on) {
if (!edges.empty() && originalLineColors.empty()) {
TopTools_IndexedMapOfShape eMap;
TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap);
originalLineColors = svp->LineColorArray.getValues();
std::vector<App::Color> colors = originalLineColors;
colors.resize(eMap.Extent(), svp->LineColor.getValue());
for (std::string e : edges) {
int idx = std::stoi(e.substr(4)) - 1;
assert ( idx >= 0 );
if ( idx < (ssize_t) colors.size() )
colors[idx] = App::Color(1.0,0.0,1.0); // magenta
}
svp->LineColorArray.setValues(colors);
}
} else {
if (!edges.empty() && !originalLineColors.empty()) {
svp->LineColorArray.setValues(originalLineColors);
originalLineColors.clear();
}
}
}
QIcon ViewProviderPipe::getIcon(void) const {
QString str = QString::fromLatin1("PartDesign_");
auto* prim = static_cast<PartDesign::Pipe*>(getObject());
if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive)
str += QString::fromLatin1("Additive_");
else
str += QString::fromLatin1("Subtractive_");
str += QString::fromLatin1("Pipe.svg");
return Gui::BitmapFactory().pixmap(str.toStdString().c_str());
}
<commit_msg>PDN: Fix Pipe claimChildren to only grab sketches<commit_after>/***************************************************************************
* Copyright (c) 2015 Stefan Tröger <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMessageBox>
#include <QMenu>
#endif
#include "ViewProviderPipe.h"
//#include "TaskPipeParameters.h"
#include "TaskPipeParameters.h"
#include <Mod/PartDesign/App/Body.h>
#include <Mod/PartDesign/App/FeaturePipe.h>
#include <Mod/Sketcher/App/SketchObject.h>
#include <Gui/Control.h>
#include <Gui/Command.h>
#include <Gui/Application.h>
#include <Gui/BitmapFactory.h>
#include <TopExp.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderPipe,PartDesignGui::ViewProvider)
ViewProviderPipe::ViewProviderPipe()
{
}
ViewProviderPipe::~ViewProviderPipe()
{
}
std::vector<App::DocumentObject*> ViewProviderPipe::claimChildren(void)const
{
std::vector<App::DocumentObject*> temp;
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
App::DocumentObject* sketch = pcPipe->getVerifiedSketch(true);
if (sketch != NULL)
temp.push_back(sketch);
App::DocumentObject* spine = pcPipe->Spine.getValue();
if (spine != NULL && spine->isDerivedFrom(Part::Part2DObject::getClassTypeId()))
temp.push_back(spine);
App::DocumentObject* auxspine = pcPipe->AuxillerySpine.getValue();
if (auxspine != NULL && auxspine->isDerivedFrom(Part::Part2DObject::getClassTypeId()))
temp.push_back(auxspine);
return temp;
}
void ViewProviderPipe::setupContextMenu(QMenu* menu, QObject* receiver, const char* member)
{
QAction* act;
act = menu->addAction(QObject::tr("Edit pipe"), receiver, member);
act->setData(QVariant((int)ViewProvider::Default));
}
bool ViewProviderPipe::doubleClicked(void)
{
Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",this->pcObject->getNameInDocument());
return true;
}
bool ViewProviderPipe::setEdit(int ModNum) {
if (ModNum == ViewProvider::Default )
setPreviewDisplayMode(true);
return PartDesignGui::ViewProvider::setEdit(ModNum);
}
void ViewProviderPipe::unsetEdit(int ModNum) {
setPreviewDisplayMode(false);
PartDesignGui::ViewProvider::unsetEdit(ModNum);
}
TaskDlgFeatureParameters* ViewProviderPipe::getEditDialog() {
return new TaskDlgPipeParameters(this, false);
}
bool ViewProviderPipe::onDelete(const std::vector<std::string> &s)
{/*
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
// get the Sketch
Sketcher::SketchObject *pcSketch = 0;
if (pcPipe->Sketch.getValue())
pcSketch = static_cast<Sketcher::SketchObject*>(pcPipe->Sketch.getValue());
// if abort command deleted the object the sketch is visible again
if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch))
Gui::Application::Instance->getViewProvider(pcSketch)->show();
*/
return ViewProvider::onDelete(s);
}
void ViewProviderPipe::highlightReferences(const bool on, bool auxillery)
{
PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getObject());
Part::Feature* base;
if(!auxillery)
base = static_cast<Part::Feature*>(pcPipe->Spine.getValue());
else
base = static_cast<Part::Feature*>(pcPipe->AuxillerySpine.getValue());
if (base == NULL) return;
PartGui::ViewProviderPart* svp = dynamic_cast<PartGui::ViewProviderPart*>(
Gui::Application::Instance->getViewProvider(base));
if (svp == NULL) return;
std::vector<std::string> edges;
if(!auxillery)
edges = pcPipe->Spine.getSubValuesStartsWith("Edge");
else
edges = pcPipe->AuxillerySpine.getSubValuesStartsWith("Edge");
if (on) {
if (!edges.empty() && originalLineColors.empty()) {
TopTools_IndexedMapOfShape eMap;
TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap);
originalLineColors = svp->LineColorArray.getValues();
std::vector<App::Color> colors = originalLineColors;
colors.resize(eMap.Extent(), svp->LineColor.getValue());
for (std::string e : edges) {
int idx = std::stoi(e.substr(4)) - 1;
assert ( idx >= 0 );
if ( idx < (ssize_t) colors.size() )
colors[idx] = App::Color(1.0,0.0,1.0); // magenta
}
svp->LineColorArray.setValues(colors);
}
} else {
if (!edges.empty() && !originalLineColors.empty()) {
svp->LineColorArray.setValues(originalLineColors);
originalLineColors.clear();
}
}
}
QIcon ViewProviderPipe::getIcon(void) const {
QString str = QString::fromLatin1("PartDesign_");
auto* prim = static_cast<PartDesign::Pipe*>(getObject());
if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive)
str += QString::fromLatin1("Additive_");
else
str += QString::fromLatin1("Subtractive_");
str += QString::fromLatin1("Pipe.svg");
return Gui::BitmapFactory().pixmap(str.toStdString().c_str());
}
<|endoftext|> |
<commit_before>//
// Copyright 2016 Giovanni Mels
//
// 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 "NTriplesWriter.hh"
#include <utility> // std::move
namespace turtle {
std::unique_ptr<BlankNode> NTriplesWriter::triples(const RDFList &list)
{
std::string id = m_idgen.generate();
std::unique_ptr<BlankNode> head(new BlankNode(id));
for (std::size_t i = 0; i < list.size(); i++) {
const N3Node *node = list[i];
std::unique_ptr<BlankNode> nestedList;
if (const RDFList *rl = dynamic_cast<const RDFList *>(node)) {
nestedList = triples(*rl);
node = nestedList.get();
}
rawTriple(*head, RDF::first, *node);
if (i == list.size() - 1) {
rawTriple(*head, RDF::rest, RDF::nil);
} else {
std::unique_ptr<BlankNode> rest(new BlankNode(m_idgen.generate()));
rawTriple(*head, RDF::rest, *rest);
head = std::move(rest);
}
}
return std::unique_ptr<BlankNode>(new BlankNode(id));
}
void NTriplesWriter::triple(const Resource &subject, const URIResource &property, const N3Node &object)
{
std::unique_ptr<BlankNode> sp; // prevent sp.get() getting deleted
const Resource *s = &subject;
if (const RDFList *list = dynamic_cast<const RDFList *>(s)) {
if (list->empty()) {
s = &RDF::nil;
} else {
sp = triples(*list);
s = sp.get();
}
}
std::unique_ptr<BlankNode> op; // prevent op.get() getting deleted
const N3Node *o = &object;
if (const RDFList *list = dynamic_cast<const RDFList *>(o)) {
if (list->empty()) {
o = &RDF::nil;
} else {
op = triples(*list);
o = op.get();
}
}
rawTriple(*s, property, *o);
}
inline void NTriplesWriter::rawTriple(const Resource &subject, const URIResource &property, const N3Node &object)
{
m_count++;
subject.visit(m_formatter);
m_outbuf->sputc(' ');
property.visit(m_formatter);
m_outbuf->sputc(' ');
object.visit(m_formatter);
m_outbuf->sputc(' ');
m_outbuf->sputc('.');
#ifdef CTURTLE_CRLF
m_outbuf->sputc('\r');
#endif
m_outbuf->sputc('\n');
}
}
<commit_msg>Fix for issue #5.<commit_after>//
// Copyright 2016 Giovanni Mels
//
// 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 "NTriplesWriter.hh"
#include <utility> // std::move
namespace turtle {
std::unique_ptr<BlankNode> NTriplesWriter::triples(const RDFList &list)
{
std::string id = m_idgen.generate();
std::unique_ptr<BlankNode> head(new BlankNode(id));
for (std::size_t i = 0; i < list.size(); i++) {
const N3Node *node = list[i];
std::unique_ptr<BlankNode> nestedList;
if (const RDFList *rl = dynamic_cast<const RDFList *>(node)) {
if (rl->empty()) {
node = &RDF::nil;
} else {
nestedList = triples(*rl);
node = nestedList.get();
}
}
rawTriple(*head, RDF::first, *node);
if (i == list.size() - 1) {
rawTriple(*head, RDF::rest, RDF::nil);
} else {
std::unique_ptr<BlankNode> rest(new BlankNode(m_idgen.generate()));
rawTriple(*head, RDF::rest, *rest);
head = std::move(rest);
}
}
return std::unique_ptr<BlankNode>(new BlankNode(id));
}
void NTriplesWriter::triple(const Resource &subject, const URIResource &property, const N3Node &object)
{
std::unique_ptr<BlankNode> sp; // prevent sp.get() getting deleted
const Resource *s = &subject;
if (const RDFList *list = dynamic_cast<const RDFList *>(s)) {
if (list->empty()) {
s = &RDF::nil;
} else {
sp = triples(*list);
s = sp.get();
}
}
std::unique_ptr<BlankNode> op; // prevent op.get() getting deleted
const N3Node *o = &object;
if (const RDFList *list = dynamic_cast<const RDFList *>(o)) {
if (list->empty()) {
o = &RDF::nil;
} else {
op = triples(*list);
o = op.get();
}
}
rawTriple(*s, property, *o);
}
inline void NTriplesWriter::rawTriple(const Resource &subject, const URIResource &property, const N3Node &object)
{
m_count++;
subject.visit(m_formatter);
m_outbuf->sputc(' ');
property.visit(m_formatter);
m_outbuf->sputc(' ');
object.visit(m_formatter);
m_outbuf->sputc(' ');
m_outbuf->sputc('.');
#ifdef CTURTLE_CRLF
m_outbuf->sputc('\r');
#endif
m_outbuf->sputc('\n');
}
}
<|endoftext|> |
<commit_before>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiSocket.h"
#include "nuiNetworkHost.h"
#ifdef WIN32
#include <Ws2tcpip.h>
#undef GetAddrInfo
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
nuiSocket::nuiSocket(nuiSocket::SocketType Socket)
: mSocket(Socket)
{
#if (!defined _LINUX_)
int n = 0;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof(n));
#endif
mNonBlocking = false;
}
bool nuiSocket::Init(int domain, int type, int protocol)
{
mSocket = socket(domain, type, protocol);
#if (!defined _LINUX_)
int n = 0;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof(n));
#endif
return mSocket >= 0;
}
nuiSocket::~nuiSocket()
{
#ifdef WIN32
//DisconnectEx(mSocket, NULL, 0, 0);
closesocket(mSocket);
#else
close(mSocket);
#endif
}
nuiSocket::SocketType nuiSocket::GetSocket() const
{
return mSocket;
}
bool nuiSocket::GetLocalHost(nuiNetworkHost& rHost) const
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int res = getsockname(mSocket, (struct sockaddr*)&addr, &addrlen);
if (res != 0)
return false;
nuiNetworkHost h(addr.sin_addr.s_addr, addr.sin_port, rHost.mProtocol);
rHost = h;
return true;
}
bool nuiSocket::GetDistantHost(nuiNetworkHost& rHost) const
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int res = getpeername(mSocket, (struct sockaddr*)&addr, &addrlen);
if (res != 0)
return false;
nuiNetworkHost h(ntohl(addr.sin_addr.s_addr), addr.sin_port, rHost.mProtocol);
rHost = h;
return true;
}
bool nuiSocket::IsValid() const
{
return mSocket != -1;
}
struct addrinfo* nuiSocket::GetAddrInfo(const nuiNetworkHost& rHost) const
{
return rHost.GetAddrInfo();
}
void nuiSocket::SetNonBlocking(bool set)
{
if (mNonBlocking == set)
return;
int flags;
mNonBlocking = set;
/* If they have O_NONBLOCK, use the Posix way to do it */
#if defined(O_NONBLOCK)
/* Fixme: O_NONBLOCK is defined but broken on SunOS 4.1.x and AIX 3.2.5. */
if (-1 == (flags = fcntl(mSocket, F_GETFL, 0)))
flags = 0;
if (set)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
fcntl(mSocket, F_SETFL, flags);
#else
/* Otherwise, use the old way of doing it */
flags = set ? 1 : 0;
ioctl(mSocket, FIOBIO, &flags);
#endif
}
bool nuiSocket::IsNonBlocking() const
{
return mNonBlocking;
}
void nuiSocket::SetCanReadDelegate(const EventDelegate& rDelegate)
{
mReadDelegate = rDelegate;
}
void nuiSocket::SetCanWriteDelegate(const EventDelegate& rDelegate)
{
mWriteDelegate = rDelegate;
}
void nuiSocket::SetReadClosedDelegate(const EventDelegate& rDelegate)
{
mReadCloseDelegate = rDelegate;
}
void nuiSocket::SetWriteClosedDelegate(const EventDelegate& rDelegate)
{
mWriteCloseDelegate = rDelegate;
}
void nuiSocket::OnCanRead()
{
if (mReadDelegate)
mReadDelegate(*this);
}
void nuiSocket::OnCanWrite()
{
if (mWriteDelegate)
mWriteDelegate(*this);
}
void nuiSocket::OnReadClosed()
{
if (mReadCloseDelegate)
mReadCloseDelegate(*this);
}
void nuiSocket::OnWriteClosed()
{
if (mWriteCloseDelegate)
mWriteCloseDelegate(*this);
}
#ifdef WIN32
#define W(X) WSA##X
#else
#define W(X) X
#endif
void nuiSocket::DumpError(int err) const
{
if (!err)
return;
nglString error;
switch (err)
{
case EACCES: error = "The destination address is a broadcast address and the socket option SO_BROADCAST is not set."; break;
case W(EADDRINUSE): error = "The address is already in use."; break;
case W(EADDRNOTAVAIL): error = "The specified address is not available on this machine."; break;
case W(EAFNOSUPPORT): error = "Addresses in the specified address family cannot be used with this socket."; break;
case W(EALREADY): error = "The socket is non-blocking and a previous connection attempt has not yet been completed."; break;
case W(EBADF): error = "socket is not a valid descriptor."; break;
case W(ECONNREFUSED): error = "The attempt to connect was ignored (because the target is not listening for connections) or explicitly rejected."; break;
case W(EFAULT): error = "The address parameter specifies an area outside the process address space."; break;
case W(EHOSTUNREACH): error = "The target host cannot be reached (e.g., down, disconnected)."; break;
case W(EINPROGRESS): error = "The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) for completion by selecting the socket for writing."; break;
case W(EINTR): error = "Its execution was interrupted by a signal."; break;
case W(EINVAL): error = "An invalid argument was detected (e.g., address_len is not valid for the address family, the specified address family is invalid)."; break;
case W(EISCONN): error = "The socket is already connected."; break;
case W(ENETDOWN): error = "The local network interface is not functioning."; break;
case W(ENETUNREACH): error = "The network isn't reachable from this host."; break;
case W(ENOBUFS): error = "The system call was unable to allocate a needed memory buffer."; break;
case W(ENOTSOCK): error = "socket is not a file descriptor for a socket."; break;
case W(EOPNOTSUPP): error = "Because socket is listening, no connection is allowed."; break;
case W(EPROTOTYPE): error = "address has a different type than the socket that is bound to the specified peer address."; break;
case W(ETIMEDOUT): error = " Connection establishment timed out without establishing a connection."; break;
case W(ECONNRESET): error = "Remote host reset the connection request."; break;
default: error = "Unknown error "; error.Add(err); break;
}
NGL_OUT(_T("Socket Error: %s\n"), error.GetChars());
}
//////////////////////////////////////////////////////////////////
//class nuiSocketPool
#ifdef NGL_KQUEUE
nuiSocketPool::nuiSocketPool()
{
mQueue = kqueue();
}
nuiSocketPool::~nuiSocketPool()
{
///
}
void nuiSocketPool::Add(nuiSocket* pSocket, TriggerMode ReadMode, TriggerMode WriteMode)
{
struct kevent ev;
memset(&ev, 0, sizeof(struct kevent));
ev.ident = pSocket->GetSocket();
ev.filter = EVFILT_READ;
ev.flags = EV_ADD | EV_ENABLE | EV_CLEAR;
ev.udata = pSocket;
mChangeset.push_back(ev);
ev.filter = EVFILT_WRITE;
mChangeset.push_back(ev);
mEvents.resize(mEvents.size() + 2);
}
void nuiSocketPool::Del(nuiSocket* pSocket)
{
struct kevent ev;
memset(&ev, 0, sizeof(struct kevent));
ev.ident = pSocket->GetSocket();
ev.filter = EVFILT_READ;
ev.flags = EV_DELETE;
ev.udata = pSocket;
mChangeset.push_back(ev);
ev.filter = EVFILT_WRITE;
mChangeset.push_back(ev);
mEvents.resize(mEvents.size() - 2);
}
int nuiSocketPool::DispatchEvents(int timeout_millisec)
{
struct timespec to;
if (timeout_millisec >= 0)
{
to.tv_sec = timeout_millisec / 1000;
to.tv_nsec = (timeout_millisec % 1000) * 1000000; // nanosec
}
int res = kevent(mQueue, &mChangeset[0], mChangeset.size(), &mEvents[0], mEvents.size(), (timeout_millisec >= 0) ? &to : (struct timespec *) 0);
mChangeset.clear();
if(res == -1)
{
int err = errno;
NGL_LOG("socket", NGL_LOG_ERROR, "kqueue::waitForEvents : kevent : %s (errno %d)\n", strerror(err), err);
return err;
}
if (res == 0)
return EWOULDBLOCK;
for (int i = 0; i < res; i++)
{
nuiSocket* pSocket = (nuiSocket*)mEvents[i].udata;
// dispatch events:
switch (mEvents[i].filter)
{
case EVFILT_READ:
if (mEvents[i].flags == EV_EOF)
pSocket->OnReadClosed();
else
pSocket->OnCanRead();
break;
case EVFILT_WRITE:
if (mEvents[i].flags == EV_EOF)
pSocket->OnWriteClosed();
else
pSocket->OnCanWrite();
break;
};
}
return 0;
}
#endif //NGL_KQUEUE
#ifdef NGL_EPOLL
nuiSocketPool::nuiSocketPool()
{
mEPoll = epoll_create(100);
}
nuiSocketPool::~nuiSocketPool()
{
///
}
void nuiSocketPool::Add(nuiSocket* pSocket, TriggerMode ReadMode, TriggerMode WriteMode)
{
struct epoll_event ev;
ev.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP;
ev.data.ptr = pSocket;
ev.data.fd = pSocket->GetSocket();
ev.data.u32 = 0;
ev.data.u64 = 0;
epoll_ctl(mEPoll, EPOLL_CTL_ADD, pSocket->GetSocket(), &ev);
mEvents.resize(mEvents.size() + 2);
}
void nuiSocketPool::Del(nuiSocket* pSocket)
{
epoll_ctl(mEPoll, EPOLL_CTL_DEL, pSocket->GetSocket(), NULL);
mEvents.resize(mEvents.size() - 2);
}
int nuiSocketPool::DispatchEvents(int timeout_millisec)
{
int res = epoll_wait(mEPoll, &mEvents[0], mEvents.size(), timeout_millisec);
if(res == -1)
{
int err = errno;
NGL_LOG("socket", NGL_LOG_ERROR, "epoll::WaitForEvents : %s (errno %d)\n", strerror(err), err);
return err;
}
if (res == 0)
return EWOULDBLOCK;
for (int i = 0; i < res; i++)
{
nuiSocket* pSocket = (nuiSocket*)mEvents[i].data.ptr;
// dispatch events:
switch (mEvents[i].events)
{
case EPOLLIN:
pSocket->OnCanRead();
break;
case EPOLLOUT:
pSocket->OnCanWrite();
break;
case EPOLLRDHUP:
default:
pSocket->OnReadClosed();
pSocket->OnWriteClosed();
break;
};
}
return 0;
}
#endif //NGL_EPOLL
<commit_msg>fixed ntohl missing<commit_after>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiSocket.h"
#include "nuiNetworkHost.h"
#ifdef WIN32
#include <Ws2tcpip.h>
#undef GetAddrInfo
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
nuiSocket::nuiSocket(nuiSocket::SocketType Socket)
: mSocket(Socket)
{
#if (!defined _LINUX_)
int n = 0;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof(n));
#endif
mNonBlocking = false;
}
bool nuiSocket::Init(int domain, int type, int protocol)
{
mSocket = socket(domain, type, protocol);
#if (!defined _LINUX_)
int n = 0;
setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof(n));
#endif
return mSocket >= 0;
}
nuiSocket::~nuiSocket()
{
#ifdef WIN32
//DisconnectEx(mSocket, NULL, 0, 0);
closesocket(mSocket);
#else
close(mSocket);
#endif
}
nuiSocket::SocketType nuiSocket::GetSocket() const
{
return mSocket;
}
bool nuiSocket::GetLocalHost(nuiNetworkHost& rHost) const
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int res = getsockname(mSocket, (struct sockaddr*)&addr, &addrlen);
if (res != 0)
return false;
nuiNetworkHost h(ntohl(addr.sin_addr.s_addr), addr.sin_port, rHost.mProtocol);
rHost = h;
return true;
}
bool nuiSocket::GetDistantHost(nuiNetworkHost& rHost) const
{
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int res = getpeername(mSocket, (struct sockaddr*)&addr, &addrlen);
if (res != 0)
return false;
nuiNetworkHost h(ntohl(addr.sin_addr.s_addr), addr.sin_port, rHost.mProtocol);
rHost = h;
return true;
}
bool nuiSocket::IsValid() const
{
return mSocket != -1;
}
struct addrinfo* nuiSocket::GetAddrInfo(const nuiNetworkHost& rHost) const
{
return rHost.GetAddrInfo();
}
void nuiSocket::SetNonBlocking(bool set)
{
if (mNonBlocking == set)
return;
int flags;
mNonBlocking = set;
/* If they have O_NONBLOCK, use the Posix way to do it */
#if defined(O_NONBLOCK)
/* Fixme: O_NONBLOCK is defined but broken on SunOS 4.1.x and AIX 3.2.5. */
if (-1 == (flags = fcntl(mSocket, F_GETFL, 0)))
flags = 0;
if (set)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
fcntl(mSocket, F_SETFL, flags);
#else
/* Otherwise, use the old way of doing it */
flags = set ? 1 : 0;
ioctl(mSocket, FIOBIO, &flags);
#endif
}
bool nuiSocket::IsNonBlocking() const
{
return mNonBlocking;
}
void nuiSocket::SetCanReadDelegate(const EventDelegate& rDelegate)
{
mReadDelegate = rDelegate;
}
void nuiSocket::SetCanWriteDelegate(const EventDelegate& rDelegate)
{
mWriteDelegate = rDelegate;
}
void nuiSocket::SetReadClosedDelegate(const EventDelegate& rDelegate)
{
mReadCloseDelegate = rDelegate;
}
void nuiSocket::SetWriteClosedDelegate(const EventDelegate& rDelegate)
{
mWriteCloseDelegate = rDelegate;
}
void nuiSocket::OnCanRead()
{
if (mReadDelegate)
mReadDelegate(*this);
}
void nuiSocket::OnCanWrite()
{
if (mWriteDelegate)
mWriteDelegate(*this);
}
void nuiSocket::OnReadClosed()
{
if (mReadCloseDelegate)
mReadCloseDelegate(*this);
}
void nuiSocket::OnWriteClosed()
{
if (mWriteCloseDelegate)
mWriteCloseDelegate(*this);
}
#ifdef WIN32
#define W(X) WSA##X
#else
#define W(X) X
#endif
void nuiSocket::DumpError(int err) const
{
if (!err)
return;
nglString error;
switch (err)
{
case EACCES: error = "The destination address is a broadcast address and the socket option SO_BROADCAST is not set."; break;
case W(EADDRINUSE): error = "The address is already in use."; break;
case W(EADDRNOTAVAIL): error = "The specified address is not available on this machine."; break;
case W(EAFNOSUPPORT): error = "Addresses in the specified address family cannot be used with this socket."; break;
case W(EALREADY): error = "The socket is non-blocking and a previous connection attempt has not yet been completed."; break;
case W(EBADF): error = "socket is not a valid descriptor."; break;
case W(ECONNREFUSED): error = "The attempt to connect was ignored (because the target is not listening for connections) or explicitly rejected."; break;
case W(EFAULT): error = "The address parameter specifies an area outside the process address space."; break;
case W(EHOSTUNREACH): error = "The target host cannot be reached (e.g., down, disconnected)."; break;
case W(EINPROGRESS): error = "The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) for completion by selecting the socket for writing."; break;
case W(EINTR): error = "Its execution was interrupted by a signal."; break;
case W(EINVAL): error = "An invalid argument was detected (e.g., address_len is not valid for the address family, the specified address family is invalid)."; break;
case W(EISCONN): error = "The socket is already connected."; break;
case W(ENETDOWN): error = "The local network interface is not functioning."; break;
case W(ENETUNREACH): error = "The network isn't reachable from this host."; break;
case W(ENOBUFS): error = "The system call was unable to allocate a needed memory buffer."; break;
case W(ENOTSOCK): error = "socket is not a file descriptor for a socket."; break;
case W(EOPNOTSUPP): error = "Because socket is listening, no connection is allowed."; break;
case W(EPROTOTYPE): error = "address has a different type than the socket that is bound to the specified peer address."; break;
case W(ETIMEDOUT): error = " Connection establishment timed out without establishing a connection."; break;
case W(ECONNRESET): error = "Remote host reset the connection request."; break;
default: error = "Unknown error "; error.Add(err); break;
}
NGL_OUT(_T("Socket Error: %s\n"), error.GetChars());
}
//////////////////////////////////////////////////////////////////
//class nuiSocketPool
#ifdef NGL_KQUEUE
nuiSocketPool::nuiSocketPool()
{
mQueue = kqueue();
}
nuiSocketPool::~nuiSocketPool()
{
///
}
void nuiSocketPool::Add(nuiSocket* pSocket, TriggerMode ReadMode, TriggerMode WriteMode)
{
struct kevent ev;
memset(&ev, 0, sizeof(struct kevent));
ev.ident = pSocket->GetSocket();
ev.filter = EVFILT_READ;
ev.flags = EV_ADD | EV_ENABLE | EV_CLEAR;
ev.udata = pSocket;
mChangeset.push_back(ev);
ev.filter = EVFILT_WRITE;
mChangeset.push_back(ev);
mEvents.resize(mEvents.size() + 2);
}
void nuiSocketPool::Del(nuiSocket* pSocket)
{
struct kevent ev;
memset(&ev, 0, sizeof(struct kevent));
ev.ident = pSocket->GetSocket();
ev.filter = EVFILT_READ;
ev.flags = EV_DELETE;
ev.udata = pSocket;
mChangeset.push_back(ev);
ev.filter = EVFILT_WRITE;
mChangeset.push_back(ev);
mEvents.resize(mEvents.size() - 2);
}
int nuiSocketPool::DispatchEvents(int timeout_millisec)
{
struct timespec to;
if (timeout_millisec >= 0)
{
to.tv_sec = timeout_millisec / 1000;
to.tv_nsec = (timeout_millisec % 1000) * 1000000; // nanosec
}
int res = kevent(mQueue, &mChangeset[0], mChangeset.size(), &mEvents[0], mEvents.size(), (timeout_millisec >= 0) ? &to : (struct timespec *) 0);
mChangeset.clear();
if(res == -1)
{
int err = errno;
NGL_LOG("socket", NGL_LOG_ERROR, "kqueue::waitForEvents : kevent : %s (errno %d)\n", strerror(err), err);
return err;
}
if (res == 0)
return EWOULDBLOCK;
for (int i = 0; i < res; i++)
{
nuiSocket* pSocket = (nuiSocket*)mEvents[i].udata;
// dispatch events:
switch (mEvents[i].filter)
{
case EVFILT_READ:
if (mEvents[i].flags == EV_EOF)
pSocket->OnReadClosed();
else
pSocket->OnCanRead();
break;
case EVFILT_WRITE:
if (mEvents[i].flags == EV_EOF)
pSocket->OnWriteClosed();
else
pSocket->OnCanWrite();
break;
};
}
return 0;
}
#endif //NGL_KQUEUE
#ifdef NGL_EPOLL
nuiSocketPool::nuiSocketPool()
{
mEPoll = epoll_create(100);
}
nuiSocketPool::~nuiSocketPool()
{
///
}
void nuiSocketPool::Add(nuiSocket* pSocket, TriggerMode ReadMode, TriggerMode WriteMode)
{
struct epoll_event ev;
ev.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP;
ev.data.ptr = pSocket;
ev.data.fd = pSocket->GetSocket();
ev.data.u32 = 0;
ev.data.u64 = 0;
epoll_ctl(mEPoll, EPOLL_CTL_ADD, pSocket->GetSocket(), &ev);
mEvents.resize(mEvents.size() + 2);
}
void nuiSocketPool::Del(nuiSocket* pSocket)
{
epoll_ctl(mEPoll, EPOLL_CTL_DEL, pSocket->GetSocket(), NULL);
mEvents.resize(mEvents.size() - 2);
}
int nuiSocketPool::DispatchEvents(int timeout_millisec)
{
int res = epoll_wait(mEPoll, &mEvents[0], mEvents.size(), timeout_millisec);
if(res == -1)
{
int err = errno;
NGL_LOG("socket", NGL_LOG_ERROR, "epoll::WaitForEvents : %s (errno %d)\n", strerror(err), err);
return err;
}
if (res == 0)
return EWOULDBLOCK;
for (int i = 0; i < res; i++)
{
nuiSocket* pSocket = (nuiSocket*)mEvents[i].data.ptr;
// dispatch events:
switch (mEvents[i].events)
{
case EPOLLIN:
pSocket->OnCanRead();
break;
case EPOLLOUT:
pSocket->OnCanWrite();
break;
case EPOLLRDHUP:
default:
pSocket->OnReadClosed();
pSocket->OnWriteClosed();
break;
};
}
return 0;
}
#endif //NGL_EPOLL
<|endoftext|> |
<commit_before>// Copyright 2010-2012 UT-Battelle, LLC. See LICENSE.txt for more information.
#include "eavlVTKExporter.h"
#include <iostream>
void
eavlVTKExporter::Export(ostream &out)
{
out<<"# vtk DataFile Version 3.0"<<endl;
out<<"vtk output"<<endl;
out<<"ASCII"<<endl;
ExportUnstructured(out);
}
void
eavlVTKExporter::ExportUnstructured(ostream &out)
{
out<<"DATASET UNSTRUCTURED_GRID"<<endl;
ExportPoints(out);
ExportCells(out);
ExportFields(out);
}
void
eavlVTKExporter::ExportCells(ostream &out)
{
if (data->GetNumCellSets() == 0)
return;
int nCells = data->GetCellSet(cellSetIndex)->GetNumCells();
int sz = 0;
for (int i = 0; i < nCells; i++)
{
sz += data->GetCellSet(cellSetIndex)->GetCellNodes(i).numIndices;
sz += 1;
}
out<<"CELLS "<<nCells<<" "<<sz<<endl;
for (int i = 0; i < nCells; i++)
{
int nVerts = data->GetCellSet(cellSetIndex)->GetCellNodes(i).numIndices;
eavlCell cell = data->GetCellSet(cellSetIndex)->GetCellNodes(i);
out<<nVerts<<" ";
for (int j = 0; j < nVerts; j++)
out<<cell.indices[j]<<" ";
out<<endl;
}
out<<"CELL_TYPES "<<nCells<<endl;
for (int i = 0; i < nCells; i++)
{
eavlCell cell = data->GetCellSet(cellSetIndex)->GetCellNodes(i);
out<<CellTypeToVTK(cell.type)<<endl;
}
}
void
eavlVTKExporter::ExportFields(ostream &out)
{
// do point data
bool wrote_point_header = false;
for (unsigned int f = 0; f < data->GetNumFields(); f++)
{
int ntuples = data->GetField(f)->GetArray()->GetNumberOfTuples();
int ncomp = data->GetField(f)->GetArray()->GetNumberOfComponents();
if (ncomp > 4)
continue;
if (data->GetField(f)->GetAssociation() == eavlField::ASSOC_POINTS)
{
if (!wrote_point_header)
out<<"POINT_DATA "<<ntuples<<endl;
wrote_point_header = true;
out<<"SCALARS "<<data->GetField(f)->GetArray()->GetName()<<" float "<< ncomp<<endl;
out<<"LOOKUP_TABLE default"<<endl;
for (int i = 0; i < ntuples; i++)
{
for (int j = 0; j < ncomp; j++)
out<<data->GetField(f)->GetArray()->GetComponentAsDouble(i,j)<<endl;
}
}
}
// do cell data
bool wrote_cell_header = false;
for (unsigned int f = 0; f < data->GetNumFields(); f++)
{
int ntuples = data->GetField(f)->GetArray()->GetNumberOfTuples();
int ncomp = data->GetField(f)->GetArray()->GetNumberOfComponents();
if (ncomp > 4)
continue;
if (data->GetField(f)->GetAssociation() == eavlField::ASSOC_CELL_SET &&
data->GetField(f)->GetAssocCellSet() == cellSetIndex)
{
if (!wrote_cell_header)
out<<"CELL_DATA "<<ntuples<<endl;
wrote_cell_header = true;
out<<"SCALARS "<<data->GetField(f)->GetArray()->GetName()<<" float "<< ncomp<<endl;
out<<"LOOKUP_TABLE default"<<endl;
for (int i = 0; i < ntuples; i++)
{
for (int j = 0; j < ncomp; j++)
out<<data->GetField(f)->GetArray()->GetComponentAsDouble(i,j)<<endl;
}
}
}
}
void
eavlVTKExporter::ExportPoints(ostream &out)
{
out<<"POINTS "<<data->GetNumPoints()<<" float"<<endl;
int dim = data->GetCoordinateSystem(0)->GetDimension();
int npts = data->GetNumPoints();
for (int i = 0; i < npts; i++)
{
out<<(float)data->GetPoint(i, 0)<<" ";
out<<(dim >=2 ? (float)data->GetPoint(i, 1) : 0.0)<<" ";
out<<(dim >=3 ? (float)data->GetPoint(i, 2) : 0.0)<<endl;
}
}
#define VTK_EMPTY_CELL 0
#define VTK_VERTEX 1
#define VTK_POLY_VERTEX 2
#define VTK_LINE 3
#define VTK_POLY_LINE 4
#define VTK_TRIANGLE 5
#define VTK_TRIANGLE_STRIP 6
#define VTK_POLYGON 7
#define VTK_PIXEL 8
#define VTK_QUAD 9
#define VTK_TETRA 10
#define VTK_VOXEL 11
#define VTK_HEXAHEDRON 12
#define VTK_WEDGE 13
#define VTK_PYRAMID 14
#define VTK_PENTAGONAL_PRISM 15
#define VTK_HEXAGONAL_PRISM 16
int
eavlVTKExporter::CellTypeToVTK(eavlCellShape &type)
{
int vtkType = -1;
switch(type)
{
case EAVL_POINT:
vtkType = VTK_VERTEX;
break;
case EAVL_BEAM:
vtkType = VTK_LINE;
break;
case EAVL_TRI:
vtkType = VTK_TRIANGLE;
break;
case EAVL_QUAD:
vtkType = VTK_QUAD;
break;
case EAVL_PIXEL:
vtkType = VTK_PIXEL;
break;
case EAVL_TET:
vtkType = VTK_TETRA;
break;
case EAVL_PYRAMID:
vtkType = VTK_PYRAMID;
break;
case EAVL_WEDGE:
vtkType = VTK_WEDGE;
break;
case EAVL_HEX:
vtkType = VTK_HEXAHEDRON;
break;
case EAVL_VOXEL:
vtkType = VTK_VOXEL;
break;
case EAVL_TRISTRIP:
vtkType = VTK_TRIANGLE_STRIP;
break;
case EAVL_POLYGON:
vtkType = VTK_POLYGON;
break;
case EAVL_OTHER:
break;
}
return vtkType;
}
<commit_msg>fixing bug exporting rgrids to vtk.<commit_after>// Copyright 2010-2012 UT-Battelle, LLC. See LICENSE.txt for more information.
#include "eavlVTKExporter.h"
#include <iostream>
void
eavlVTKExporter::Export(ostream &out)
{
out<<"# vtk DataFile Version 3.0"<<endl;
out<<"vtk output"<<endl;
out<<"ASCII"<<endl;
ExportUnstructured(out);
}
void
eavlVTKExporter::ExportUnstructured(ostream &out)
{
out<<"DATASET UNSTRUCTURED_GRID"<<endl;
ExportPoints(out);
ExportCells(out);
ExportFields(out);
}
void
eavlVTKExporter::ExportCells(ostream &out)
{
if (data->GetNumCellSets() == 0)
return;
int nCells = data->GetCellSet(cellSetIndex)->GetNumCells();
int sz = 0;
for (int i = 0; i < nCells; i++)
{
sz += data->GetCellSet(cellSetIndex)->GetCellNodes(i).numIndices;
sz += 1;
}
out<<"CELLS "<<nCells<<" "<<sz<<endl;
for (int i = 0; i < nCells; i++)
{
int nVerts = data->GetCellSet(cellSetIndex)->GetCellNodes(i).numIndices;
eavlCell cell = data->GetCellSet(cellSetIndex)->GetCellNodes(i);
out<<nVerts<<" ";
for (int j = 0; j < nVerts; j++)
out<<cell.indices[j]<<" ";
out<<endl;
}
out<<"CELL_TYPES "<<nCells<<endl;
for (int i = 0; i < nCells; i++)
{
eavlCell cell = data->GetCellSet(cellSetIndex)->GetCellNodes(i);
out<<CellTypeToVTK(cell.type)<<endl;
}
}
void
eavlVTKExporter::ExportFields(ostream &out)
{
// do point data
bool wrote_point_header = false;
for (unsigned int f = 0; f < data->GetNumFields(); f++)
{
int ntuples = data->GetField(f)->GetArray()->GetNumberOfTuples();
int ncomp = data->GetField(f)->GetArray()->GetNumberOfComponents();
if (ncomp > 4)
continue;
if (data->GetField(f)->GetAssociation() == eavlField::ASSOC_POINTS)
{
if (!wrote_point_header)
out<<"POINT_DATA "<<ntuples<<endl;
wrote_point_header = true;
out<<"SCALARS "<<data->GetField(f)->GetArray()->GetName()<<" float "<< ncomp<<endl;
out<<"LOOKUP_TABLE default"<<endl;
for (int i = 0; i < ntuples; i++)
{
for (int j = 0; j < ncomp; j++)
out<<data->GetField(f)->GetArray()->GetComponentAsDouble(i,j)<<endl;
}
}
}
// do cell data
bool wrote_cell_header = false;
for (unsigned int f = 0; f < data->GetNumFields(); f++)
{
int ntuples = data->GetField(f)->GetArray()->GetNumberOfTuples();
int ncomp = data->GetField(f)->GetArray()->GetNumberOfComponents();
if (ncomp > 4)
continue;
if (data->GetField(f)->GetAssociation() == eavlField::ASSOC_CELL_SET &&
data->GetField(f)->GetAssocCellSet() == cellSetIndex)
{
if (!wrote_cell_header)
out<<"CELL_DATA "<<ntuples<<endl;
wrote_cell_header = true;
out<<"SCALARS "<<data->GetField(f)->GetArray()->GetName()<<" float "<< ncomp<<endl;
out<<"LOOKUP_TABLE default"<<endl;
for (int i = 0; i < ntuples; i++)
{
for (int j = 0; j < ncomp; j++)
out<<data->GetField(f)->GetArray()->GetComponentAsDouble(i,j)<<endl;
}
}
}
}
void
eavlVTKExporter::ExportPoints(ostream &out)
{
out<<"POINTS "<<data->GetNumPoints()<<" float"<<endl;
int dim = data->GetCoordinateSystem(0)->GetDimension();
int npts = data->GetNumPoints();
for (int i = 0; i < npts; i++)
{
out<<(float)data->GetPoint(i, 0)<<" ";
out<<(float)data->GetPoint(i, 1)<<" ";
out<<(float)data->GetPoint(i, 2)<<endl;
}
}
#define VTK_EMPTY_CELL 0
#define VTK_VERTEX 1
#define VTK_POLY_VERTEX 2
#define VTK_LINE 3
#define VTK_POLY_LINE 4
#define VTK_TRIANGLE 5
#define VTK_TRIANGLE_STRIP 6
#define VTK_POLYGON 7
#define VTK_PIXEL 8
#define VTK_QUAD 9
#define VTK_TETRA 10
#define VTK_VOXEL 11
#define VTK_HEXAHEDRON 12
#define VTK_WEDGE 13
#define VTK_PYRAMID 14
#define VTK_PENTAGONAL_PRISM 15
#define VTK_HEXAGONAL_PRISM 16
int
eavlVTKExporter::CellTypeToVTK(eavlCellShape &type)
{
int vtkType = -1;
switch(type)
{
case EAVL_POINT:
vtkType = VTK_VERTEX;
break;
case EAVL_BEAM:
vtkType = VTK_LINE;
break;
case EAVL_TRI:
vtkType = VTK_TRIANGLE;
break;
case EAVL_QUAD:
vtkType = VTK_QUAD;
break;
case EAVL_PIXEL:
vtkType = VTK_PIXEL;
break;
case EAVL_TET:
vtkType = VTK_TETRA;
break;
case EAVL_PYRAMID:
vtkType = VTK_PYRAMID;
break;
case EAVL_WEDGE:
vtkType = VTK_WEDGE;
break;
case EAVL_HEX:
vtkType = VTK_HEXAHEDRON;
break;
case EAVL_VOXEL:
vtkType = VTK_VOXEL;
break;
case EAVL_TRISTRIP:
vtkType = VTK_TRIANGLE_STRIP;
break;
case EAVL_POLYGON:
vtkType = VTK_POLYGON;
break;
case EAVL_OTHER:
break;
}
return vtkType;
}
<|endoftext|> |
<commit_before>#ifndef RESULT_BENCHMARK_HPP_
#define RESULT_BENCHMARK_HPP_
#include <math.h>
#include <iostream>
#include <array>
#include <vector>
#include <assert.h>
#include <regex>
namespace gearshifft
{
/** Result data generated after a benchmark has completed the runs
*/
template<int T_NumberRuns, int T_NumberValues>
class ResultBenchmark {
public:
using ValuesT = std::array<std::array<double, T_NumberValues >, T_NumberRuns >;
template<bool isComplex, bool isInplace, size_t T_NDim>
void init(const std::array<unsigned, T_NDim>& ce, const char* precision) {
total_ = 1;
for(auto i=0; i<T_NDim; ++i) {
extents_[i] = ce[i];
total_ *= ce[i];
}
dim_ = T_NDim;
dimkind_ = computeDimkind();
run_ = 0;
isInplace_ = isInplace;
isComplex_ = isComplex;
precision_.assign(precision);
error_.clear();
errorRun_ = -1;
}
/**
* @retval 1 arbitrary extents
* @retval 2 power-of-two extents
* @retval 3 last dim: combination of powers of (3,5,7) {3^r * 5^s * 7^t}
*/
size_t computeDimkind() {
bool p2=true;
for( unsigned k=0; k<dim_; ++k)
p2 &= powerOf(extents_[k], 2.0);
if(p2)
return 2;
unsigned e = extents_[dim_-1];
unsigned sqr = static_cast<unsigned>(sqrt(e));
for( unsigned k=2; k<=sqr; k+=1 ) {
while( e%k == 0 ) {
e /= k;
}
}
if(e>7)
return 1;
else
return 3;
}
/* setters */
void setRun(int run) {
run_ = run;
}
template<typename T_Index>
void setValue(T_Index idx_val, double val) {
int idx = static_cast<int>(idx_val);
assert(idx<T_NumberValues);
values_[run_][idx] = val;
}
void setError(int run, const std::string& what) {
assert(errorRun_<T_NumberRuns);
errorRun_ = run;
error_ = what;
// remove path informations of source file location
std::regex e ("([^ ]*/|[^ ]*\\\\)([^/\\\\]*)(hpp|cpp)");
error_ = std::regex_replace(error_,e,"$2$3");
}
/* getters */
template<typename T_Index>
double getValue(T_Index idx_val) const {
int idx = static_cast<int>(idx_val);
assert(idx<T_NumberValues);
return values_[run_][idx];
}
std::string getPrecision() const { return precision_; }
size_t getDim() const { return dim_; }
size_t getDimKind() const { return dimkind_; }
std::array<unsigned,3> getExtents() const { return extents_; }
size_t getExtentsTotal() const { return total_; }
bool isInplace() const { return isInplace_; }
bool isComplex() const { return isComplex_; }
bool hasError() const { return error_.empty()==false; }
const std::string& getError() const { return error_; }
int getErrorRun() const { return errorRun_; }
private:
/// result object id
//size_t id_ = 0;
int run_ = 0;
/// fft dimension
size_t dim_ = 0;
/// extents are 1=Arbitrary, 2=PowerOfTwo, 3=PowerOfOther
size_t dimkind_ = 0;
/// fft extents
std::array<unsigned,3> extents_ = { {1} };
/// all extents multiplied
size_t total_ = 1;
/// each run w values ( data[idx_run][idx_val] )
ValuesT values_ = { {{ {0.0} }} };
/// FFT Kind Inplace
bool isInplace_ = false;
/// FFT Kind Complex
bool isComplex_ = false;
/// Precision as string
std::string precision_;
/// Error message
std::string error_;
/// Run where error occurred
int errorRun_;
private:
bool powerOf(unsigned e, double b) {
if(e==0)
return false;
double a = static_cast<double>(e);
double p = floor(log(a)/log(b)+0.5);
return fabs(pow(b,p)-a)<0.0001;
}
};
}
#endif
<commit_msg>computeDimKind fixed.<commit_after>#ifndef RESULT_BENCHMARK_HPP_
#define RESULT_BENCHMARK_HPP_
#include <math.h>
#include <iostream>
#include <array>
#include <vector>
#include <assert.h>
#include <regex>
namespace gearshifft
{
/** Result data generated after a benchmark has completed the runs
*/
template<int T_NumberRuns, int T_NumberValues>
class ResultBenchmark {
public:
using ValuesT = std::array<std::array<double, T_NumberValues >, T_NumberRuns >;
template<bool isComplex, bool isInplace, size_t T_NDim>
void init(const std::array<unsigned, T_NDim>& ce, const char* precision) {
total_ = 1;
for(auto i=0; i<T_NDim; ++i) {
extents_[i] = ce[i];
total_ *= ce[i];
}
dim_ = T_NDim;
dimkind_ = computeDimkind();
run_ = 0;
isInplace_ = isInplace;
isComplex_ = isComplex;
precision_.assign(precision);
error_.clear();
errorRun_ = -1;
}
/**
* @retval 1 arbitrary extents
* @retval 2 power-of-two extents
* @retval 3 combination of powers of (3,5,7) {3^r * 5^s * 7^t}
*/
size_t computeDimkind() {
bool p2=true;
for( unsigned k=0; k<dim_; ++k)
p2 &= powerOf(extents_[k], 2.0);
if(p2)
return 2;
for(unsigned k=0; k<dim_; ++k) {
unsigned e = extents_[k];
unsigned sqr = static_cast<unsigned>(sqrt(e));
for( unsigned k=2; k<=sqr; k+=1 ) {
while( e%k == 0 ) {
e /= k;
}
}
if(e>7)
return 1;
}
return 3;
}
/* setters */
void setRun(int run) {
run_ = run;
}
template<typename T_Index>
void setValue(T_Index idx_val, double val) {
int idx = static_cast<int>(idx_val);
assert(idx<T_NumberValues);
values_[run_][idx] = val;
}
void setError(int run, const std::string& what) {
assert(errorRun_<T_NumberRuns);
errorRun_ = run;
error_ = what;
// remove path informations of source file location
std::regex e ("([^ ]*/|[^ ]*\\\\)([^/\\\\]*)(hpp|cpp)");
error_ = std::regex_replace(error_,e,"$2$3");
}
/* getters */
template<typename T_Index>
double getValue(T_Index idx_val) const {
int idx = static_cast<int>(idx_val);
assert(idx<T_NumberValues);
return values_[run_][idx];
}
std::string getPrecision() const { return precision_; }
size_t getDim() const { return dim_; }
size_t getDimKind() const { return dimkind_; }
std::array<unsigned,3> getExtents() const { return extents_; }
size_t getExtentsTotal() const { return total_; }
bool isInplace() const { return isInplace_; }
bool isComplex() const { return isComplex_; }
bool hasError() const { return error_.empty()==false; }
const std::string& getError() const { return error_; }
int getErrorRun() const { return errorRun_; }
private:
/// result object id
//size_t id_ = 0;
int run_ = 0;
/// fft dimension
size_t dim_ = 0;
/// extents are 1=Arbitrary, 2=PowerOfTwo, 3=PowerOfOther
size_t dimkind_ = 0;
/// fft extents
std::array<unsigned,3> extents_ = { {1} };
/// all extents multiplied
size_t total_ = 1;
/// each run w values ( data[idx_run][idx_val] )
ValuesT values_ = { {{ {0.0} }} };
/// FFT Kind Inplace
bool isInplace_ = false;
/// FFT Kind Complex
bool isComplex_ = false;
/// Precision as string
std::string precision_;
/// Error message
std::string error_;
/// Run where error occurred
int errorRun_;
private:
bool powerOf(unsigned e, double b) {
if(e==0)
return false;
double a = static_cast<double>(e);
double p = floor(log(a)/log(b)+0.5);
return fabs(pow(b,p)-a)<0.0001;
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <fstream>
#include <windows.h>
#include "simple/string.h"
typedef struct tagHEADER {
WORD idReserved;
WORD idType;
WORD idCount;
} HEADER, *LPHEADER;
typedef struct tagICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
DWORD dwImageOffset;
} ICONDIRENTRY, *LPICONDIRENTRY;
#pragma pack( push )
#pragma pack( 2 )
typedef struct tagGRPICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
} GRPICONDIRENTRY, *LPGRPICONDIRENTRY;;
typedef struct tagGRPICONDIR {
WORD idReserved;
WORD idType;
WORD idCount;
GRPICONDIRENTRY idEntries[1];
} GRPICONDIR, *LPGRPICONDIR;
#pragma pack( pop )
bool Res_ReplaceICO(const char* lpExeName, const char* sResID, const char* lpIconFile) {
LPICONDIRENTRY pIconDirEntry(NULL);
LPGRPICONDIR pGrpIconDir(NULL);
HEADER header;
LPBYTE pIconBytes(NULL);
HANDLE hIconFile(NULL);
DWORD dwRet(0), nSize(0), nGSize(0), dwReserved(0);
HANDLE hUpdate(NULL);
BOOL ret(FALSE);
WORD i(0);
//打开图标文件
hIconFile = CreateFile(lpIconFile, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hIconFile == INVALID_HANDLE_VALUE) {
return false;
}
//读取文件头部信息
ret=ReadFile(hIconFile, &header, sizeof(HEADER), &dwReserved, NULL);
if (!ret) {
CloseHandle(hIconFile);
return false;
}
//建立每一个图标的目录信息存放区域
pIconDirEntry = (LPICONDIRENTRY)new BYTE[header.idCount*sizeof(ICONDIRENTRY)];
if (pIconDirEntry==NULL) {
CloseHandle(hIconFile);
return false;
}
//从Icon文件中读取每一个图标的目录信息
ret = ReadFile(hIconFile, pIconDirEntry, header.idCount*sizeof(ICONDIRENTRY), &dwReserved, NULL);
if (!ret) {
delete[] pIconDirEntry;
CloseHandle(hIconFile);
return false;
}
//建立EXE文件中RT_GROUP_ICON所需的数据结构存放区域
nGSize=sizeof(GRPICONDIR)+header.idCount*sizeof(ICONDIRENTRY);
pGrpIconDir=(LPGRPICONDIR)new BYTE[nGSize];
ZeroMemory(pGrpIconDir, nSize);
//填充信息,这里相当于一个转换的过程
pGrpIconDir->idReserved=header.idReserved;
pGrpIconDir->idType=header.idType;
pGrpIconDir->idCount=header.idCount;
//复制信息并设置每一个图标对应的ID。ID为位置索引号
for(i=0; i<header.idCount; i++) {
pGrpIconDir->idEntries[i].bWidth=pIconDirEntry[i].bWidth;
pGrpIconDir->idEntries[i].bHeight=pIconDirEntry[i].bHeight;
pGrpIconDir->idEntries[i].bColorCount=pIconDirEntry[i].bColorCount;
pGrpIconDir->idEntries[i].bReserved=pIconDirEntry[i].bReserved;
pGrpIconDir->idEntries[i].wPlanes=pIconDirEntry[i].wPlanes;
pGrpIconDir->idEntries[i].wBitCount=pIconDirEntry[i].wBitCount;
pGrpIconDir->idEntries[i].dwBytesInRes=pIconDirEntry[i].dwBytesInRes;
pGrpIconDir->idEntries[i].nID=i+1; //id == 0 是 RT_GROUP_ICON 的id,我这里替换的时候出现问题,所以就 + 1 了。
}
//开始更新EXE中的图标资源,ID定为最小0,如果原来存在0ID的图标信息则被替换为新的。
hUpdate = BeginUpdateResource(lpExeName, false);
if (hUpdate!=NULL) {
//首先更新RT_GROUP_ICON信息
ret = UpdateResource(hUpdate, RT_GROUP_ICON, sResID, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPVOID)pGrpIconDir, nGSize);
if (!ret) {
delete[] pIconDirEntry;
delete[] pGrpIconDir;
CloseHandle(hIconFile);
return false;
}
//接着的是每一个Icon的信息存放
for(i=0; i<header.idCount; i++) {
//Icon的字节数
nSize = pIconDirEntry[i].dwBytesInRes;
//偏移文件的指针到当前图标的开始处
dwRet=SetFilePointer(hIconFile, pIconDirEntry[i].dwImageOffset, NULL, FILE_BEGIN);
if (dwRet==INVALID_SET_FILE_POINTER) {
break;
}
//准备pIconBytes来存放文件里的Byte信息用于更新到EXE中。
delete[] pIconBytes;
pIconBytes = new BYTE[nSize];
ZeroMemory(pIconBytes, nSize);
ret = ReadFile(hIconFile, (LPVOID)pIconBytes, nSize, &dwReserved, NULL);
if(!ret) {
break;
}
//更新每一个ID对应的RT_ICON信息
ret = UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(pGrpIconDir->idEntries[i].nID), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPVOID)pIconBytes, nSize);
if(!ret) {
break;
}
}
//结束EXE资源的更新操作
if (pIconBytes!=NULL) {
delete[] pIconBytes;
}
if(!EndUpdateResource(hUpdate, false)) {
return false;
}
}
//清理资源并关闭Icon文件,到此更新操作结束!
delete []pGrpIconDir;
delete []pIconDirEntry;
CloseHandle(hIconFile);
return true;
}
bool Res_ReplaceString(const char* pszApp, int nResID, const char* pszText) {
std::wstring wText;
string_ansi_to_utf16(pszText, wText);
int SourceId = nResID;
HINSTANCE hInst = ::LoadLibrary(pszApp);
if(hInst == NULL) return false;
std::vector<WCHAR> vStrTable; // 资源数据
int idStr = (SourceId-1)/16 + 1; // 字符串表ID
HRSRC hSrc = ::FindResource(hInst, MAKEINTRESOURCE(idStr), RT_STRING);
if(hSrc != NULL) {
LPVOID lpData = ::LockResource( ::LoadResource(hInst,hSrc) );
DWORD dwSize = ::SizeofResource(hInst,hSrc);
vStrTable.resize((dwSize+1)/sizeof(WCHAR));
::CopyMemory(&vStrTable[0],lpData,dwSize); // 取得数据
}
::FreeLibrary(hInst);
HANDLE hUpdateRes=BeginUpdateResource(pszApp,false);
if(hUpdateRes == NULL) return false; // 不能更新,浪费表情
int nIndex = (SourceId-1)%16; // 字符串表中的位置
UINT nPos = 1;
for (int i = 0; i < nIndex; i++) { // 移到我们要修改的位置
if(vStrTable.size() <= nPos) vStrTable.resize(nPos+1);
nPos += vStrTable[nPos];
nPos++;
}
if(vStrTable.size()<=nPos) vStrTable.resize(nPos+1);
// 删除原先数据
if(vStrTable[nPos]>0) {
std::vector<WCHAR>::iterator itrStart=vStrTable.begin();
std::advance(itrStart,nPos+1);
std::vector<WCHAR>::iterator itrEnd = itrStart;
std::advance(itrEnd,vStrTable[nPos]);
vStrTable.erase(itrStart,itrEnd);
}
int nLen = ::lstrlenW(wText.c_str());
vStrTable[nPos] = (WCHAR)nLen;
// 插入现在的数据
if(nLen>0) {
std::vector<WCHAR>::iterator itrStart=vStrTable.begin();
std::advance(itrStart,nPos+1);
vStrTable.insert(itrStart,wText.c_str(),wText.c_str()+nLen);
}
// 好了,可以替换了
UpdateResource(hUpdateRes,
RT_STRING,
MAKEINTRESOURCE(idStr),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // 注意我这里用的语言不一样:)
&vStrTable[0],
vStrTable.size()*sizeof(WCHAR));
return (FALSE != EndUpdateResource(hUpdateRes,FALSE));
}
//
// 获取资源内容
//
bool Res_LoadResource(
HMODULE hModule,
const char* res_name,
const char* res_type,
void*& res_data,
size_t& res_size
) {
HRSRC hRsrc = FindResourceA(hModule, res_name, res_type);
if(NULL == hRsrc) return false;
DWORD dwSize = SizeofResource(hModule, hRsrc);
if(0 == dwSize) return false;
HGLOBAL hGlobal = LoadResource(hModule, hRsrc);
if(NULL == hGlobal) return false;
LPVOID pBuffer = LockResource(hGlobal);
if(NULL == pBuffer) return false;
res_data = pBuffer;
res_size = dwSize;
return true;
}
//
// 获取文件内容(必须确保空间足够大)
//
bool Res_LoadFile(
const char* file_name,
void* res_data,
size_t& res_size
) {
std::ifstream ifs(file_name, std::ios::binary);
if(!ifs) {
return false;
}
ifs.seekg(0, std::ios::end);
size_t file_size = size_t(ifs.tellg());
if(NULL == res_data) {
res_size = file_size;
return true;
}
if(res_size < file_size) {
return false;
}
res_size = file_size;
ifs.seekg(0, std::ios::beg);
ifs.read((char*)res_data, res_size);
return true;
}
<commit_msg>unicode env errors.<commit_after>#include <string>
#include <vector>
#include <fstream>
#include <windows.h>
#include "simple/string.h"
typedef struct tagHEADER {
WORD idReserved;
WORD idType;
WORD idCount;
} HEADER, *LPHEADER;
typedef struct tagICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
DWORD dwImageOffset;
} ICONDIRENTRY, *LPICONDIRENTRY;
#pragma pack( push )
#pragma pack( 2 )
typedef struct tagGRPICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
} GRPICONDIRENTRY, *LPGRPICONDIRENTRY;;
typedef struct tagGRPICONDIR {
WORD idReserved;
WORD idType;
WORD idCount;
GRPICONDIRENTRY idEntries[1];
} GRPICONDIR, *LPGRPICONDIR;
#pragma pack( pop )
bool Res_ReplaceICO(const char* lpExeName, const char* sResID, const char* lpIconFile) {
LPICONDIRENTRY pIconDirEntry(NULL);
LPGRPICONDIR pGrpIconDir(NULL);
HEADER header;
LPBYTE pIconBytes(NULL);
HANDLE hIconFile(NULL);
DWORD dwRet(0), nSize(0), nGSize(0), dwReserved(0);
HANDLE hUpdate(NULL);
BOOL ret(FALSE);
WORD i(0);
//打开图标文件
hIconFile = CreateFileA(lpIconFile, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hIconFile == INVALID_HANDLE_VALUE) {
return false;
}
//读取文件头部信息
ret=ReadFile(hIconFile, &header, sizeof(HEADER), &dwReserved, NULL);
if (!ret) {
CloseHandle(hIconFile);
return false;
}
//建立每一个图标的目录信息存放区域
pIconDirEntry = (LPICONDIRENTRY)new BYTE[header.idCount*sizeof(ICONDIRENTRY)];
if (pIconDirEntry==NULL) {
CloseHandle(hIconFile);
return false;
}
//从Icon文件中读取每一个图标的目录信息
ret = ReadFile(hIconFile, pIconDirEntry, header.idCount*sizeof(ICONDIRENTRY), &dwReserved, NULL);
if (!ret) {
delete[] pIconDirEntry;
CloseHandle(hIconFile);
return false;
}
//建立EXE文件中RT_GROUP_ICON所需的数据结构存放区域
nGSize=sizeof(GRPICONDIR)+header.idCount*sizeof(ICONDIRENTRY);
pGrpIconDir=(LPGRPICONDIR)new BYTE[nGSize];
ZeroMemory(pGrpIconDir, nSize);
//填充信息,这里相当于一个转换的过程
pGrpIconDir->idReserved=header.idReserved;
pGrpIconDir->idType=header.idType;
pGrpIconDir->idCount=header.idCount;
//复制信息并设置每一个图标对应的ID。ID为位置索引号
for(i=0; i<header.idCount; i++) {
pGrpIconDir->idEntries[i].bWidth=pIconDirEntry[i].bWidth;
pGrpIconDir->idEntries[i].bHeight=pIconDirEntry[i].bHeight;
pGrpIconDir->idEntries[i].bColorCount=pIconDirEntry[i].bColorCount;
pGrpIconDir->idEntries[i].bReserved=pIconDirEntry[i].bReserved;
pGrpIconDir->idEntries[i].wPlanes=pIconDirEntry[i].wPlanes;
pGrpIconDir->idEntries[i].wBitCount=pIconDirEntry[i].wBitCount;
pGrpIconDir->idEntries[i].dwBytesInRes=pIconDirEntry[i].dwBytesInRes;
pGrpIconDir->idEntries[i].nID=i+1; //id == 0 是 RT_GROUP_ICON 的id,我这里替换的时候出现问题,所以就 + 1 了。
}
//开始更新EXE中的图标资源,ID定为最小0,如果原来存在0ID的图标信息则被替换为新的。
hUpdate = BeginUpdateResourceA(lpExeName, false);
if (hUpdate!=NULL) {
//首先更新RT_GROUP_ICON信息
ret = UpdateResourceA(hUpdate, (LPSTR)RT_GROUP_ICON, sResID, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPVOID)pGrpIconDir, nGSize);
if (!ret) {
delete[] pIconDirEntry;
delete[] pGrpIconDir;
CloseHandle(hIconFile);
return false;
}
//接着的是每一个Icon的信息存放
for(i=0; i<header.idCount; i++) {
//Icon的字节数
nSize = pIconDirEntry[i].dwBytesInRes;
//偏移文件的指针到当前图标的开始处
dwRet=SetFilePointer(hIconFile, pIconDirEntry[i].dwImageOffset, NULL, FILE_BEGIN);
if (dwRet==INVALID_SET_FILE_POINTER) {
break;
}
//准备pIconBytes来存放文件里的Byte信息用于更新到EXE中。
delete[] pIconBytes;
pIconBytes = new BYTE[nSize];
ZeroMemory(pIconBytes, nSize);
ret = ReadFile(hIconFile, (LPVOID)pIconBytes, nSize, &dwReserved, NULL);
if(!ret) {
break;
}
//更新每一个ID对应的RT_ICON信息
ret = UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(pGrpIconDir->idEntries[i].nID), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPVOID)pIconBytes, nSize);
if(!ret) {
break;
}
}
//结束EXE资源的更新操作
if (pIconBytes!=NULL) {
delete[] pIconBytes;
}
if(!EndUpdateResource(hUpdate, false)) {
return false;
}
}
//清理资源并关闭Icon文件,到此更新操作结束!
delete []pGrpIconDir;
delete []pIconDirEntry;
CloseHandle(hIconFile);
return true;
}
bool Res_ReplaceString(const char* pszApp, int nResID, const char* pszText) {
std::wstring wText;
string_ansi_to_utf16(pszText, wText);
int SourceId = nResID;
HINSTANCE hInst = ::LoadLibraryA(pszApp);
if(hInst == NULL) return false;
std::vector<WCHAR> vStrTable; // 资源数据
int idStr = (SourceId-1)/16 + 1; // 字符串表ID
HRSRC hSrc = ::FindResource(hInst, MAKEINTRESOURCE(idStr), RT_STRING);
if(hSrc != NULL) {
LPVOID lpData = ::LockResource( ::LoadResource(hInst,hSrc) );
DWORD dwSize = ::SizeofResource(hInst,hSrc);
vStrTable.resize((dwSize+1)/sizeof(WCHAR));
::CopyMemory(&vStrTable[0],lpData,dwSize); // 取得数据
}
::FreeLibrary(hInst);
HANDLE hUpdateRes=BeginUpdateResourceA(pszApp,false);
if(hUpdateRes == NULL) return false; // 不能更新,浪费表情
int nIndex = (SourceId-1)%16; // 字符串表中的位置
UINT nPos = 1;
for (int i = 0; i < nIndex; i++) { // 移到我们要修改的位置
if(vStrTable.size() <= nPos) vStrTable.resize(nPos+1);
nPos += vStrTable[nPos];
nPos++;
}
if(vStrTable.size()<=nPos) vStrTable.resize(nPos+1);
// 删除原先数据
if(vStrTable[nPos]>0) {
std::vector<WCHAR>::iterator itrStart=vStrTable.begin();
std::advance(itrStart,nPos+1);
std::vector<WCHAR>::iterator itrEnd = itrStart;
std::advance(itrEnd,vStrTable[nPos]);
vStrTable.erase(itrStart,itrEnd);
}
int nLen = ::lstrlenW(wText.c_str());
vStrTable[nPos] = (WCHAR)nLen;
// 插入现在的数据
if(nLen>0) {
std::vector<WCHAR>::iterator itrStart=vStrTable.begin();
std::advance(itrStart,nPos+1);
vStrTable.insert(itrStart,wText.c_str(),wText.c_str()+nLen);
}
// 好了,可以替换了
UpdateResource(hUpdateRes,
RT_STRING,
MAKEINTRESOURCE(idStr),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // 注意我这里用的语言不一样:)
&vStrTable[0],
vStrTable.size()*sizeof(WCHAR));
return (FALSE != EndUpdateResource(hUpdateRes,FALSE));
}
//
// 获取资源内容
//
bool Res_LoadResource(
HMODULE hModule,
const char* res_name,
const char* res_type,
void*& res_data,
size_t& res_size
) {
HRSRC hRsrc = FindResourceA(hModule, res_name, res_type);
if(NULL == hRsrc) return false;
DWORD dwSize = SizeofResource(hModule, hRsrc);
if(0 == dwSize) return false;
HGLOBAL hGlobal = LoadResource(hModule, hRsrc);
if(NULL == hGlobal) return false;
LPVOID pBuffer = LockResource(hGlobal);
if(NULL == pBuffer) return false;
res_data = pBuffer;
res_size = dwSize;
return true;
}
//
// 获取文件内容(必须确保空间足够大)
//
bool Res_LoadFile(
const char* file_name,
void* res_data,
size_t& res_size
) {
std::ifstream ifs(file_name, std::ios::binary);
if(!ifs) {
return false;
}
ifs.seekg(0, std::ios::end);
size_t file_size = size_t(ifs.tellg());
if(NULL == res_data) {
res_size = file_size;
return true;
}
if(res_size < file_size) {
return false;
}
res_size = file_size;
ifs.seekg(0, std::ios::beg);
ifs.read((char*)res_data, res_size);
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include "systemMacro.h"
#include <OgreSharedPtr.h>
#include <OgreResourceManager.h>
#include <vector>
#include <algorithm>
#include <sndfile.h>
#include "AnnTypes.h"
namespace Annwvyn
{
class AnnDllExport AnnAudioFile : public Ogre::Resource
{
///Where the data is actually stored, as bytes.
std::vector<byte> data;
///Read bytes from a data stream and stick them inside the "data" re-sizable array
void readFromStream(Ogre::DataStreamPtr &stream);
///Utility class that perform a static_cast<AnnAudioFile*> on the pointer you give it.
inline static AnnAudioFile* cast(void* audioFileRawPtr);
protected:
///Actually load the data
void loadImpl() override;
///Clear the data vector
void unloadImpl() override;
///Return the size of the data vector
size_t calculateSize() const override;
public:
///Create an audio file. This is intended to be called by a resource manager, not by the user.
AnnAudioFile(Ogre::ResourceManager* creator,
const Ogre::String& name,
Ogre::ResourceHandle handle,
const Ogre::String& group,
bool isManual = false,
Ogre::ManualResourceLoader* loader = nullptr);
virtual ~AnnAudioFile();
///Return a raw const pointer to the data, in bytes
const byte* getData() const;
///Return the size
size_t getSize() const override;
//Virtual IO interface
///Structure that will contain function pointers to all the functions defined below
static std::unique_ptr<SF_VIRTUAL_IO> sfVioStruct;
///Get the length of the file. Give that function pointer to libsndfile.
static sf_count_t sfVioGetFileLen(void* audioFileRawPtr);
///Seek (move reading cursor) inside virtual file Give that function pointer to libsndfile.
static sf_count_t sfVioSeek(sf_count_t offset, int whence, void* audioFileRawPtr);
///REad "count" bytes from cursor to ptr. Will return number of bytes actually read. Will not read past the end of data but do not check writing to the pointer. Give that function pointer to libsndfile.
static sf_count_t sfVioRead(void* ptr, sf_count_t count, void* audiFileRawPtr);
///Do nothing. Dummy function just to fill up the interface. Give that function pointer to libsndfile.
static sf_count_t sfVioWriteDummy(const void *, sf_count_t, void*);
///return current cursor position. Give that function pointer to libsndfile.
static sf_count_t sfVioTell(void* audioFileRawPtr);
///Get the virtual I/O struct. Will initialize it at 1st call. Give that function pointer to libsndfile.
static SF_VIRTUAL_IO* getSndFileVioStruct();
///For cleanup. Will deallocate the VioStruct and set the pointer back to nullptr
static void clearSndFileVioStruct();
///Current cursor position. the only "state" used while reading the file from libsndfile (except for the data itself, that is non mutable)
size_t sf_offset;
};
using AnnAudioFilePtr = Ogre::SharedPtr<AnnAudioFile>;
class AnnAudioFileManager : public Ogre::ResourceManager, public Ogre::Singleton<AnnAudioFileManager>
{
protected:
///Create the audio file resource itself
Ogre::Resource* createImpl(const Ogre::String &name, Ogre::ResourceHandle handle,
const Ogre::String &group, bool isManual, Ogre::ManualResourceLoader *loader,
const Ogre::NameValuePairList *createParams) override;
public:
///Construct an AnnAudioFileManager. Will register itsel to the Ogre ResourceGroupManager.
AnnAudioFileManager();
///Will unregister itself to the Ogre ResourceGroupManager
virtual ~AnnAudioFileManager();
///Load a file via the AudioFileManager
virtual AnnAudioFilePtr load(const Ogre::String& name, const Ogre::String& group);
///Get singleton ref
static AnnAudioFileManager& getSingleton();
///Get singleton pointer
static AnnAudioFileManager* getSingletonPtr();
};
}<commit_msg>Add missing doxygen brief descriptions<commit_after>#pragma once
#include "systemMacro.h"
#include <OgreSharedPtr.h>
#include <OgreResourceManager.h>
#include <vector>
#include <algorithm>
#include <sndfile.h>
#include "AnnTypes.h"
namespace Annwvyn
{
///Ogre resource that contain the data from a binary file for the audio engine importing
class AnnDllExport AnnAudioFile : public Ogre::Resource
{
///Where the data is actually stored, as bytes.
std::vector<byte> data;
///Read bytes from a data stream and stick them inside the "data" re-sizable array
void readFromStream(Ogre::DataStreamPtr &stream);
///Utility class that perform a static_cast<AnnAudioFile*> on the pointer you give it.
inline static AnnAudioFile* cast(void* audioFileRawPtr);
protected:
///Actually load the data
void loadImpl() override;
///Clear the data vector
void unloadImpl() override;
///Return the size of the data vector
size_t calculateSize() const override;
public:
///Create an audio file. This is intended to be called by a resource manager, not by the user.
AnnAudioFile(Ogre::ResourceManager* creator,
const Ogre::String& name,
Ogre::ResourceHandle handle,
const Ogre::String& group,
bool isManual = false,
Ogre::ManualResourceLoader* loader = nullptr);
virtual ~AnnAudioFile();
///Return a raw const pointer to the data, in bytes
const byte* getData() const;
///Return the size
size_t getSize() const override;
//Virtual IO interface
///Structure that will contain function pointers to all the functions defined below
static std::unique_ptr<SF_VIRTUAL_IO> sfVioStruct;
///Get the length of the file. Give that function pointer to libsndfile.
static sf_count_t sfVioGetFileLen(void* audioFileRawPtr);
///Seek (move reading cursor) inside virtual file Give that function pointer to libsndfile.
static sf_count_t sfVioSeek(sf_count_t offset, int whence, void* audioFileRawPtr);
///REad "count" bytes from cursor to ptr. Will return number of bytes actually read. Will not read past the end of data but do not check writing to the pointer. Give that function pointer to libsndfile.
static sf_count_t sfVioRead(void* ptr, sf_count_t count, void* audiFileRawPtr);
///Do nothing. Dummy function just to fill up the interface. Give that function pointer to libsndfile.
static sf_count_t sfVioWriteDummy(const void *, sf_count_t, void*);
///return current cursor position. Give that function pointer to libsndfile.
static sf_count_t sfVioTell(void* audioFileRawPtr);
///Get the virtual I/O struct. Will initialize it at 1st call. Give that function pointer to libsndfile.
static SF_VIRTUAL_IO* getSndFileVioStruct();
///For cleanup. Will deallocate the VioStruct and set the pointer back to nullptr
static void clearSndFileVioStruct();
///Current cursor position. the only "state" used while reading the file from libsndfile (except for the data itself, that is non mutable)
size_t sf_offset;
};
using AnnAudioFilePtr = Ogre::SharedPtr<AnnAudioFile>;
///Audio file ResourceManager
class AnnAudioFileManager : public Ogre::ResourceManager, public Ogre::Singleton<AnnAudioFileManager>
{
protected:
///Create the audio file resource itself
Ogre::Resource* createImpl(const Ogre::String &name, Ogre::ResourceHandle handle,
const Ogre::String &group, bool isManual, Ogre::ManualResourceLoader *loader,
const Ogre::NameValuePairList *createParams) override;
public:
///Construct an AnnAudioFileManager. Will register itsel to the Ogre ResourceGroupManager.
AnnAudioFileManager();
///Will unregister itself to the Ogre ResourceGroupManager
virtual ~AnnAudioFileManager();
///Load a file via the AudioFileManager
virtual AnnAudioFilePtr load(const Ogre::String& name, const Ogre::String& group);
///Get singleton ref
static AnnAudioFileManager& getSingleton();
///Get singleton pointer
static AnnAudioFileManager* getSingletonPtr();
};
}<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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 BASE_RESOURCE_HPP
#define BASE_RESOURCE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
namespace rm
{
///////////////////////////////////////////////////////////
/// \brief An abstract resource class
///
/// This abstract base class needs to be inherited by a
/// ManagedResource class. It contains three pure virtual
/// functions that require a specific body of code for each
/// resource type.
///
///////////////////////////////////////////////////////////
class BaseResource
{
public:
void BaseResource();
void ~BaseResource();
///////////////////////////////////////////////////////////
/// \brief Loads the resource from the file path
///
/// pure virtual function that has a specific load
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void load() = 0;
///////////////////////////////////////////////////////////
/// \brief unloads the resource
///
/// a pure virtual function that has a specific unload
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void unload() = 0;
///////////////////////////////////////////////////////////
/// \brief Reloads the resource from the file path
///
/// a pure virtual function that has a specific reload
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void reload() = 0;
///////////////////////////////////////////////////////////
/// \brief Returns the alias of type string by value
///
///////////////////////////////////////////////////////////
std::string getAlias()const;
///////////////////////////////////////////////////////////
/// \ brief
///
///////////////////////////////////////////////////////////
std::string getResourceType()const;
std::string getFilePath()const;
bool isLoaded()const;
size_t getRamUse()const;
void setAlias();
void setResourceType();
void setFilePath();
void setIsLoaded();
void setRam();
private:
std::string alias, type, filePath;
bool isLoaded;
size_t ramUse;
};
}
#endif //BASE_RESOURCE_HPP
<commit_msg>Finished BaseResource Header<commit_after>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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 BASE_RESOURCE_HPP
#define BASE_RESOURCE_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <string>
namespace rm
{
///////////////////////////////////////////////////////////
/// \brief An abstract resource class
///
/// This abstract base class needs to be inherited by a
/// ManagedResource class. It contains three pure virtual
/// functions that require a specific body of code for each
/// resource type.
///
///////////////////////////////////////////////////////////
class BaseResource
{
public:
////////////////////////////////////////////////////////////
/// \brief Default Constructor
///
/// Standard constructor
///
////////////////////////////////////////////////////////////
void BaseResource();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Standard destructor
///
////////////////////////////////////////////////////////////
void ~BaseResource();
///////////////////////////////////////////////////////////
/// \brief Loads the resource
///
/// pure virtual function that has a specific load
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void load() = 0;
///////////////////////////////////////////////////////////
/// \brief unloads the resource
///
/// a pure virtual function that has a specific unload
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void unload() = 0;
///////////////////////////////////////////////////////////
/// \brief Reloads the resource
///
/// a pure virtual function that has a specific reload
/// function body for each resource type.
///
///////////////////////////////////////////////////////////
virtual void reload() = 0;
///////////////////////////////////////////////////////////
/// \brief Returns the alias of type string by reference
///
///////////////////////////////////////////////////////////
std::string& getAlias()const;
///////////////////////////////////////////////////////////
/// \ brief Returns the resource type string by reference
///
///////////////////////////////////////////////////////////
std::string& getResourceType()const;
///////////////////////////////////////////////////////////
/// \ brief Returns the file path string by reference
///
///////////////////////////////////////////////////////////
std::string& getFilePath()const;
///////////////////////////////////////////////////////////
/// \ brief Returns true if resource is loaded
///
///////////////////////////////////////////////////////////
bool isLoaded()const;
///////////////////////////////////////////////////////////
/// \ brief Returns the RAM use by value
///
///////////////////////////////////////////////////////////
size_t getRamUse()const;
///////////////////////////////////////////////////////////
/// \ brief Sets the alias member
///
///////////////////////////////////////////////////////////
void setAlias();
///////////////////////////////////////////////////////////
/// \ brief Sets the resource type member
///
///////////////////////////////////////////////////////////
void setResourceType();
///////////////////////////////////////////////////////////
/// \ brief Sets the file path member
///
///////////////////////////////////////////////////////////
void setFilePath();
///////////////////////////////////////////////////////////
/// \ brief Sets the isLoaded member
///
///////////////////////////////////////////////////////////
void setIsLoaded();
///////////////////////////////////////////////////////////
/// \ brief Sets the ram use member
///
///////////////////////////////////////////////////////////
void setRam();
private:
std::string alias, type, filePath;
bool isLoaded;
size_t ramUse;
};
}
#endif //BASE_RESOURCE_HPP
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include <map>
#include <Observation.hpp>
#include <utils.hpp>
#ifndef DEDISPERSION_HPP
#define DEDISPERSION_HPP
namespace PulsarSearch {
public DedispersionConf {
public:
DedispersionConf();
~DedispersionConf();
// Get
inline bool getLocalMem() const;
inline unsigned int getNrsamplesPerBlock() const;
inline unsigned int getNrSamplesPerThread() const;
inline unsigned int getNrDMsPerBlock() const;
inline unsigned int getNrDMsPerThread() const;
inline unsigned int getUnroll() const;
// Set
inline void setLocalMem(bool local);
inline void setNrSamplesPerBlock(unsigned int samples);
inline void setNrSamplesPerThread(unsigned int samples);
inline void setNrDMsPerBlock(unsigned int dms);
inline void setNrDMsPerThread(unsigned int dms);
inline void setUnroll(unsigned int unroll);
private:
bool local;
unsigned int nrSamplesPerBlock;
unsigned int nrSamplesPerThread;
unsigned int nrDMsPerBlock;
unsigned int nrDMsPerThread;
unsigned int unroll;
};
// Sequential dedispersion
template< typename T > void dedispersion(AstroData::Observation & observation, const std::vector< T > & input, std::vector< T > & output, const std::vector< float > & shifts);
// OpenCL dedispersion algorithm
std::string * getDedispersionOpenCL(const DedispersionConf & conf, const std::string & dataType, const AstroData::Observation & observation, std::vector< float > & shifts);
} // PulsarSearch
#endif // DEDISPERSION_HPP
<commit_msg>Typo.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include <map>
#include <Observation.hpp>
#include <utils.hpp>
#ifndef DEDISPERSION_HPP
#define DEDISPERSION_HPP
namespace PulsarSearch {
class DedispersionConf {
public:
DedispersionConf();
~DedispersionConf();
// Get
inline bool getLocalMem() const;
inline unsigned int getNrsamplesPerBlock() const;
inline unsigned int getNrSamplesPerThread() const;
inline unsigned int getNrDMsPerBlock() const;
inline unsigned int getNrDMsPerThread() const;
inline unsigned int getUnroll() const;
// Set
inline void setLocalMem(bool local);
inline void setNrSamplesPerBlock(unsigned int samples);
inline void setNrSamplesPerThread(unsigned int samples);
inline void setNrDMsPerBlock(unsigned int dms);
inline void setNrDMsPerThread(unsigned int dms);
inline void setUnroll(unsigned int unroll);
private:
bool local;
unsigned int nrSamplesPerBlock;
unsigned int nrSamplesPerThread;
unsigned int nrDMsPerBlock;
unsigned int nrDMsPerThread;
unsigned int unroll;
};
// Sequential dedispersion
template< typename T > void dedispersion(AstroData::Observation & observation, const std::vector< T > & input, std::vector< T > & output, const std::vector< float > & shifts);
// OpenCL dedispersion algorithm
std::string * getDedispersionOpenCL(const DedispersionConf & conf, const std::string & dataType, const AstroData::Observation & observation, std::vector< float > & shifts);
} // PulsarSearch
#endif // DEDISPERSION_HPP
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.