commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
9d4bc08d6787044cd771f5caa31a790271b61e52
|
src/DBase3File.cpp
|
src/DBase3File.cpp
|
#include "DBase3File.h"
#include "utf8.h"
#ifndef _WIN32
#include "../system/IConv.h"
#endif
#include <cstdio>
#include <cstring>
#include <cassert>
#include <shapefil.h>
using namespace std;
using namespace table;
class table::DBase3Handle {
public:
DBase3Handle() { }
~DBase3Handle() {
if (h) {
DBFClose(h);
}
}
void open(const std::string & fn) {
h = DBFOpen(fn.c_str(), "rb");
}
int readIntegerAttribute(int rec, int field) { return DBFReadIntegerAttribute(h, rec, field); }
double readDoubleAttribute(int rec, int field) { return DBFReadDoubleAttribute(h, rec, field); }
std::string readStringAttribute(int rec, int field) {
const char * tmp = DBFReadStringAttribute(h, rec, field);
if (tmp) {
#ifdef _WIN32
string output;
while (!tmp) {
utf8::append((unsigned char)*tmp, back_inserter(output));
tmp++;
}
return output;
#else
IConv iconv("ISO8859-1", "UTF-8");
string tmp2;
if (iconv.convert(tmp, tmp2)) {
return tmp2;
}
#endif
}
return "";
}
bool readBoolAttribute(int rec, int field) { return DBFReadLogicalAttribute(h, rec, field); }
bool isNull(int rec, int field) { return DBFIsAttributeNULL(h, rec, field); }
unsigned int getRecordCount() { return DBFGetRecordCount(h); }
unsigned int getFieldCount() { return DBFGetFieldCount(h); }
string getFieldName(int field) {
char fieldname[255];
DBFFieldType type = DBFGetFieldInfo(h, field, fieldname, 0, 0);
return fieldname;
}
private:
DBFHandle h = 0;
};
DBase3File::DBase3File(const string & filename) {
record_count = 0;
openDBF(filename);
}
bool
DBase3File::openDBF(const string & filename) {
dbf = std::make_shared<DBase3Handle>();
dbf->open(filename);
record_count = dbf->getRecordCount();
unsigned int field_count = dbf->getFieldCount();
for (unsigned int i = 0; i < field_count; i++) {
string name = dbf->getFieldName(i);
columns.push_back(std::make_shared<ColumnDBase3>(dbf, i, record_count, name));
}
return true;
}
ColumnDBase3::ColumnDBase3(const std::shared_ptr<DBase3Handle> _dbf,
int _column_index,
int _num_rows,
const std::string & _name)
: Column(_name),
dbf(_dbf),
column_index(_column_index),
num_rows(_num_rows)
{
}
long long
ColumnDBase3::getInt64(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
std::string
ColumnDBase3::getText(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readStringAttribute(i, column_index);
} else {
return "";
}
}
double
ColumnDBase3::getDouble(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
int
ColumnDBase3::getInt(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
|
#include "DBase3File.h"
#include "utf8.h"
#ifndef _WIN32
#include "../system/IConv.h"
#endif
#include <cstring>
#include <cassert>
#include <shapefil.h>
using namespace std;
using namespace table;
class table::DBase3Handle {
public:
DBase3Handle() { }
~DBase3Handle() {
if (h) {
DBFClose(h);
}
}
void open(const std::string & fn) {
h = DBFOpen(fn.c_str(), "rb");
}
int readIntegerAttribute(int rec, int field) { return DBFReadIntegerAttribute(h, rec, field); }
double readDoubleAttribute(int rec, int field) { return DBFReadDoubleAttribute(h, rec, field); }
std::string readStringAttribute(int rec, int field) {
const char * tmp = DBFReadStringAttribute(h, rec, field);
if (tmp) {
#ifdef _WIN32
string output;
while (!tmp) {
utf8::append((unsigned char)*tmp, back_inserter(output));
tmp++;
}
return output;
#else
IConv iconv("ISO8859-1", "UTF-8");
string tmp2;
if (iconv.convert(tmp, tmp2)) {
return tmp2;
}
#endif
}
return "";
}
bool readBoolAttribute(int rec, int field) { return DBFReadLogicalAttribute(h, rec, field); }
bool isNull(int rec, int field) { return DBFIsAttributeNULL(h, rec, field); }
unsigned int getRecordCount() { return DBFGetRecordCount(h); }
unsigned int getFieldCount() { return DBFGetFieldCount(h); }
string getFieldName(int field) {
char fieldname[255];
DBFFieldType type = DBFGetFieldInfo(h, field, fieldname, 0, 0);
return fieldname;
}
private:
DBFHandle h = 0;
};
DBase3File::DBase3File(const string & filename) {
record_count = 0;
openDBF(filename);
}
bool
DBase3File::openDBF(const string & filename) {
dbf = std::make_shared<DBase3Handle>();
dbf->open(filename);
record_count = dbf->getRecordCount();
unsigned int field_count = dbf->getFieldCount();
for (unsigned int i = 0; i < field_count; i++) {
string name = dbf->getFieldName(i);
columns.push_back(std::make_shared<ColumnDBase3>(dbf, i, record_count, name));
}
return true;
}
ColumnDBase3::ColumnDBase3(const std::shared_ptr<DBase3Handle> _dbf,
int _column_index,
int _num_rows,
const std::string & _name)
: Column(_name),
dbf(_dbf),
column_index(_column_index),
num_rows(_num_rows)
{
}
long long
ColumnDBase3::getInt64(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
std::string
ColumnDBase3::getText(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readStringAttribute(i, column_index);
} else {
return "";
}
}
double
ColumnDBase3::getDouble(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
int
ColumnDBase3::getInt(int i) const {
if (i >= 0 && i < num_rows) {
return dbf->readIntegerAttribute(i, column_index);
} else {
return 0;
}
}
|
remove cstdio header file
|
remove cstdio header file
|
C++
|
mit
|
Sometrik/graphlib,Sometrik/graphlib
|
abd94fdf50fae6a18c718161b5280da1ace6a62d
|
src/IndexWriter.cc
|
src/IndexWriter.cc
|
/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
doc->debugPrint();
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0",
doc->docID().docid);
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* description~LANG */
if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
/* tags_as_text~LANG */
if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "tags_as_text~","text~");
fts_fields_anal[k] += " ";
fts_fields_anal[k] += f.second;
}
}
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
fts_->updateDocument(del_term, fts_doc);
}
void IndexWriter::rebuildFTS() {
//docs_->listDocuments([this] (const DocID& docid) -> bool {
// rebuildFTS(docid);
// return true;
//});
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
|
/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
doc->debugPrint();
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0",
doc->docID().docid);
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " " + f.second;
}
/* description~LANG */
else if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* size_description~LANG */
else if (StringUtil::beginsWith(f.first, "size_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "size_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* material_description~LANG */
else if (StringUtil::beginsWith(f.first, "material_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "material_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* manufacturing_description~LANG */
else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "manufacturing_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* tags_as_text~LANG */
else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
fts_fields_anal["tags"] += " " + f.second;
}
/* shop_name */
else if (f.first == "shop_name") {
fts_fields_anal["tags"] += " " + f.second;
}
/* cm_clicked_terms */
else if (f.first == "cm_clicked_terms") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_clicked_terms",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
else if (f.first == "cm_ctr_norm_std") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_ctr_norm_std",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED));
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
fts_->updateDocument(del_term, fts_doc);
}
void IndexWriter::rebuildFTS() {
//docs_->listDocuments([this] (const DocID& docid) -> bool {
// rebuildFTS(docid);
// return true;
//});
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
|
index cm_clicked_terms and cm_ctr_norm_std
|
index cm_clicked_terms and cm_ctr_norm_std
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
e2dd45a4dba923ae0157a50420e1dd32fb719861
|
himan-plugins/source/writer.cpp
|
himan-plugins/source/writer.cpp
|
#include "writer.h"
#include "logger.h"
#include "plugin_factory.h"
#include "s3.h"
#include "statistics.h"
#include "timer.h"
#include "util.h"
#include <fstream>
#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "querydata.h"
#include "radon.h"
static std::vector<std::string> pendingWrites;
static std::mutex pendingMutex;
using namespace himan::plugin;
writer::writer() : itsWriteOptions()
{
itsLogger = logger("writer");
}
void writer::AddToPending(const std::vector<std::string>& names)
{
pendingWrites.reserve(pendingWrites.size() + names.size());
std::lock_guard<std::mutex> lock(pendingMutex);
pendingWrites.insert(pendingWrites.end(), names.begin(), names.end());
}
template <typename T>
std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile(
info<T>& theInfo, std::shared_ptr<const plugin_configuration> conf)
{
itsWriteOptions.configuration = conf;
switch (itsWriteOptions.configuration->OutputFileType())
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
auto theGribWriter = GET_PLUGIN(grib);
theGribWriter->WriteOptions(itsWriteOptions);
return theGribWriter->ToFile<T>(theInfo);
}
case kQueryData:
{
if (theInfo.Grid()->Type() == kReducedGaussian)
{
itsLogger.Error("Reduced gaussian grid cannot be written to querydata");
throw kInvalidWriteOptions;
}
auto theWriter = GET_PLUGIN(querydata);
theWriter->WriteOptions(itsWriteOptions);
return theWriter->ToFile<T>(theInfo);
}
case kNetCDF:
break;
case kCSV:
{
auto theWriter = GET_PLUGIN(csv);
theWriter->WriteOptions(itsWriteOptions);
return theWriter->ToFile<T>(theInfo);
}
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " +
HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
break;
}
throw kInvalidWriteOptions;
}
template std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile<double>(
info<double>&, std::shared_ptr<const plugin_configuration>);
template std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile<float>(
info<float>&, std::shared_ptr<const plugin_configuration>);
himan::HPWriteStatus writer::ToFile(std::shared_ptr<info<double>> theInfo,
std::shared_ptr<const plugin_configuration> conf)
{
return ToFile<double>(theInfo, conf);
}
template <typename T>
himan::HPWriteStatus writer::ToFile(std::shared_ptr<info<T>> theInfo, std::shared_ptr<const plugin_configuration> conf)
{
if (!itsWriteOptions.write_empty_grid)
{
if (theInfo->Data().MissingCount() == theInfo->Data().Size())
{
itsLogger.Info("Not writing empty grid for param " + theInfo->Param().Name() + " time " +
theInfo->Time().OriginDateTime().String() + " step " +
static_cast<std::string>(theInfo->Time().Step()) + " level " +
static_cast<std::string>(theInfo->Level()));
return himan::HPWriteStatus::kFailed;
}
}
timer t;
if (conf->StatisticsEnabled())
{
t.Start();
}
HPWriteStatus status = HPWriteStatus::kFinished;
if (conf->WriteMode() != kNoFileWrite)
{
// When writing previ to database, no file is needed. In all other cases we have to create
// a file.
file_information finfo;
if (theInfo->Producer().Class() == kGridClass ||
(theInfo->Producer().Class() == kPreviClass && conf->WriteToDatabase() == false))
{
auto ret = CreateFile<T>(*theInfo, conf);
status = ret.first;
finfo = ret.second;
}
if (status == HPWriteStatus::kFinished)
{
WriteToRadon(conf, finfo, theInfo);
}
}
if (conf->UseCacheForWrites())
{
auto c = GET_PLUGIN(cache);
// Pin those items that are not written to file at all
// so they can't be removed from cache if cache size is limited
c->Insert<T>(theInfo, (conf->WriteMode() == kNoFileWrite));
}
if (conf->StatisticsEnabled())
{
t.Stop();
conf->Statistics()->AddToWritingTime(t.GetTime());
}
return status;
}
template himan::HPWriteStatus writer::ToFile<double>(std::shared_ptr<info<double>>,
std::shared_ptr<const plugin_configuration>);
template himan::HPWriteStatus writer::ToFile<float>(std::shared_ptr<info<float>>,
std::shared_ptr<const plugin_configuration>);
write_options writer::WriteOptions() const
{
return itsWriteOptions;
}
void writer::WriteOptions(const write_options& theWriteOptions)
{
itsWriteOptions = theWriteOptions;
}
void writer::WritePendingInfos(std::shared_ptr<const plugin_configuration> conf)
{
if (conf->WriteStorageType() == kS3ObjectStorageSystem)
{
std::lock_guard<std::mutex> lock(pendingMutex);
itsLogger.Info("Writing " + std::to_string(pendingWrites.size()) + " pending infos to file");
// The only case when we have pending writes is (currently) when
// writing to s3
// First get the infos from cache that match the names given
// to us by the caller
auto c = GET_PLUGIN(cache);
std::vector<std::shared_ptr<himan::info<double>>> infos;
for (const auto& name : pendingWrites)
{
auto ret = c->GetInfo<double>(name);
if (ret.empty())
{
itsLogger.Fatal("Failed to find pending write from cache with key: " + name);
himan::Abort();
}
infos.insert(infos.end(), ret.begin(), ret.end());
}
// Next create a grib message of each info and store them sequentially
// in a buffer. All infos that have the same filename will end up in the
// same buffer.
std::map<std::string, himan::buffer> list;
std::map<std::string, int> count;
std::vector<std::pair<std::shared_ptr<info<double>>, file_information>> finfos;
auto g = GET_PLUGIN(grib);
itsWriteOptions.configuration = conf;
g->WriteOptions(itsWriteOptions);
ASSERT(conf);
for (const auto& info : infos)
{
auto ret = g->CreateGribMessage(*info);
file_information& finfo = ret.first;
NFmiGribMessage& msg = ret.second;
const size_t griblength = msg.GetLongKey("totalLength");
himan::buffer& buff = list[finfo.file_location];
int& message_no = count[finfo.file_location];
buff.data = static_cast<unsigned char*>(realloc(buff.data, buff.length + griblength));
msg.GetMessage(buff.data + buff.length, griblength);
finfo.offset = buff.length;
finfo.length = griblength;
finfo.message_no = message_no;
buff.length += griblength;
message_no++;
finfos.push_back(make_pair(info, finfo));
}
// Write the buffers to s3
for (const auto& p : list)
{
s3::WriteObject(p.first, p.second);
}
// And finally update radon
for (const auto& elem : finfos)
{
WriteToRadon(conf, elem.second, elem.first);
}
}
else
{
itsLogger.Fatal(
"Pending write started with invalid conditions: write_mode=" + HPWriteModeToString.at(conf->WriteMode()) +
", storage_type=" + HPFileStorageTypeToString.at(conf->WriteStorageType()));
himan::Abort();
}
}
template <typename T>
bool writer::WriteToRadon(std::shared_ptr<const plugin_configuration> conf, const file_information& finfo,
std::shared_ptr<info<T>> theInfo)
{
if (conf->WriteToDatabase() == true)
{
HPDatabaseType dbtype = conf->DatabaseType();
if (dbtype == kRadon)
{
auto r = GET_PLUGIN(radon);
// Try to save file information to radon
try
{
if (!r->Save<T>(*theInfo, finfo, conf->TargetGeomName()))
{
itsLogger.Error("Writing to radon failed");
return false;
}
}
catch (const std::exception& e)
{
itsLogger.Error("Writing to radon failed: " + std::string(e.what()));
return false;
}
catch (...)
{
itsLogger.Error("Writing to radon failed: general exception");
return false;
}
}
}
return true;
}
template bool writer::WriteToRadon(std::shared_ptr<const plugin_configuration>, const file_information&,
std::shared_ptr<info<double>>);
|
#include "writer.h"
#include "logger.h"
#include "plugin_factory.h"
#include "s3.h"
#include "statistics.h"
#include "timer.h"
#include "util.h"
#include <fstream>
#include "cache.h"
#include "csv.h"
#include "grib.h"
#include "querydata.h"
#include "radon.h"
static std::vector<std::string> pendingWrites;
static std::mutex pendingMutex;
using namespace himan::plugin;
writer::writer() : itsWriteOptions()
{
itsLogger = logger("writer");
}
void writer::AddToPending(const std::vector<std::string>& names)
{
std::lock_guard<std::mutex> lock(pendingMutex);
pendingWrites.reserve(pendingWrites.size() + names.size());
pendingWrites.insert(pendingWrites.end(), names.begin(), names.end());
}
template <typename T>
std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile(
info<T>& theInfo, std::shared_ptr<const plugin_configuration> conf)
{
itsWriteOptions.configuration = conf;
switch (itsWriteOptions.configuration->OutputFileType())
{
case kGRIB:
case kGRIB1:
case kGRIB2:
{
auto theGribWriter = GET_PLUGIN(grib);
theGribWriter->WriteOptions(itsWriteOptions);
return theGribWriter->ToFile<T>(theInfo);
}
case kQueryData:
{
if (theInfo.Grid()->Type() == kReducedGaussian)
{
itsLogger.Error("Reduced gaussian grid cannot be written to querydata");
throw kInvalidWriteOptions;
}
auto theWriter = GET_PLUGIN(querydata);
theWriter->WriteOptions(itsWriteOptions);
return theWriter->ToFile<T>(theInfo);
}
case kNetCDF:
break;
case kCSV:
{
auto theWriter = GET_PLUGIN(csv);
theWriter->WriteOptions(itsWriteOptions);
return theWriter->ToFile<T>(theInfo);
}
// Must have this or compiler complains
default:
throw std::runtime_error(ClassName() + ": Invalid file type: " +
HPFileTypeToString.at(itsWriteOptions.configuration->OutputFileType()));
break;
}
throw kInvalidWriteOptions;
}
template std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile<double>(
info<double>&, std::shared_ptr<const plugin_configuration>);
template std::pair<himan::HPWriteStatus, himan::file_information> writer::CreateFile<float>(
info<float>&, std::shared_ptr<const plugin_configuration>);
himan::HPWriteStatus writer::ToFile(std::shared_ptr<info<double>> theInfo,
std::shared_ptr<const plugin_configuration> conf)
{
return ToFile<double>(theInfo, conf);
}
template <typename T>
himan::HPWriteStatus writer::ToFile(std::shared_ptr<info<T>> theInfo, std::shared_ptr<const plugin_configuration> conf)
{
if (!itsWriteOptions.write_empty_grid)
{
if (theInfo->Data().MissingCount() == theInfo->Data().Size())
{
itsLogger.Info("Not writing empty grid for param " + theInfo->Param().Name() + " time " +
theInfo->Time().OriginDateTime().String() + " step " +
static_cast<std::string>(theInfo->Time().Step()) + " level " +
static_cast<std::string>(theInfo->Level()));
return himan::HPWriteStatus::kFailed;
}
}
timer t;
if (conf->StatisticsEnabled())
{
t.Start();
}
HPWriteStatus status = HPWriteStatus::kFinished;
if (conf->WriteMode() != kNoFileWrite)
{
// When writing previ to database, no file is needed. In all other cases we have to create
// a file.
file_information finfo;
if (theInfo->Producer().Class() == kGridClass ||
(theInfo->Producer().Class() == kPreviClass && conf->WriteToDatabase() == false))
{
auto ret = CreateFile<T>(*theInfo, conf);
status = ret.first;
finfo = ret.second;
}
if (status == HPWriteStatus::kFinished)
{
WriteToRadon(conf, finfo, theInfo);
}
}
if (conf->UseCacheForWrites())
{
auto c = GET_PLUGIN(cache);
// Pin those items that are not written to file at all
// so they can't be removed from cache if cache size is limited
c->Insert<T>(theInfo, (conf->WriteMode() == kNoFileWrite));
}
if (conf->StatisticsEnabled())
{
t.Stop();
conf->Statistics()->AddToWritingTime(t.GetTime());
}
return status;
}
template himan::HPWriteStatus writer::ToFile<double>(std::shared_ptr<info<double>>,
std::shared_ptr<const plugin_configuration>);
template himan::HPWriteStatus writer::ToFile<float>(std::shared_ptr<info<float>>,
std::shared_ptr<const plugin_configuration>);
write_options writer::WriteOptions() const
{
return itsWriteOptions;
}
void writer::WriteOptions(const write_options& theWriteOptions)
{
itsWriteOptions = theWriteOptions;
}
void writer::WritePendingInfos(std::shared_ptr<const plugin_configuration> conf)
{
if (conf->WriteStorageType() == kS3ObjectStorageSystem)
{
std::lock_guard<std::mutex> lock(pendingMutex);
itsLogger.Info("Writing " + std::to_string(pendingWrites.size()) + " pending infos to file");
// The only case when we have pending writes is (currently) when
// writing to s3
// First get the infos from cache that match the names given
// to us by the caller
auto c = GET_PLUGIN(cache);
std::vector<std::shared_ptr<himan::info<double>>> infos;
for (const auto& name : pendingWrites)
{
auto ret = c->GetInfo<double>(name);
if (ret.empty())
{
itsLogger.Fatal("Failed to find pending write from cache with key: " + name);
himan::Abort();
}
infos.insert(infos.end(), ret.begin(), ret.end());
}
// Next create a grib message of each info and store them sequentially
// in a buffer. All infos that have the same filename will end up in the
// same buffer.
std::map<std::string, himan::buffer> list;
std::map<std::string, int> count;
std::vector<std::pair<std::shared_ptr<info<double>>, file_information>> finfos;
auto g = GET_PLUGIN(grib);
itsWriteOptions.configuration = conf;
g->WriteOptions(itsWriteOptions);
ASSERT(conf);
for (const auto& info : infos)
{
auto ret = g->CreateGribMessage(*info);
file_information& finfo = ret.first;
NFmiGribMessage& msg = ret.second;
const size_t griblength = msg.GetLongKey("totalLength");
himan::buffer& buff = list[finfo.file_location];
int& message_no = count[finfo.file_location];
buff.data = static_cast<unsigned char*>(realloc(buff.data, buff.length + griblength));
msg.GetMessage(buff.data + buff.length, griblength);
finfo.offset = buff.length;
finfo.length = griblength;
finfo.message_no = message_no;
buff.length += griblength;
message_no++;
finfos.push_back(make_pair(info, finfo));
}
// Write the buffers to s3
for (const auto& p : list)
{
s3::WriteObject(p.first, p.second);
}
// And finally update radon
for (const auto& elem : finfos)
{
WriteToRadon(conf, elem.second, elem.first);
}
}
else
{
itsLogger.Fatal(
"Pending write started with invalid conditions: write_mode=" + HPWriteModeToString.at(conf->WriteMode()) +
", storage_type=" + HPFileStorageTypeToString.at(conf->WriteStorageType()));
himan::Abort();
}
}
template <typename T>
bool writer::WriteToRadon(std::shared_ptr<const plugin_configuration> conf, const file_information& finfo,
std::shared_ptr<info<T>> theInfo)
{
if (conf->WriteToDatabase() == true)
{
HPDatabaseType dbtype = conf->DatabaseType();
if (dbtype == kRadon)
{
auto r = GET_PLUGIN(radon);
// Try to save file information to radon
try
{
if (!r->Save<T>(*theInfo, finfo, conf->TargetGeomName()))
{
itsLogger.Error("Writing to radon failed");
return false;
}
}
catch (const std::exception& e)
{
itsLogger.Error("Writing to radon failed: " + std::string(e.what()));
return false;
}
catch (...)
{
itsLogger.Error("Writing to radon failed: general exception");
return false;
}
}
}
return true;
}
template bool writer::WriteToRadon(std::shared_ptr<const plugin_configuration>, const file_information&,
std::shared_ptr<info<double>>);
|
Call reserve() after locking
|
Call reserve() after locking
|
C++
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
9069d0aa108de862a03f2f140ad1424cf5c3fa89
|
src/SearchForm.cpp
|
src/SearchForm.cpp
|
/*
* Copyright 2016-2017 Raefaldhi Amartya Junior <[email protected]>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "SearchForm.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include "tinyxml/tinyxml.h"
#include <LayoutBuilder.h>
#include <TextView.h>
#include <Url.h>
#include <UrlRequest.h>
#include <UrlProtocolRoster.h>
#include <UrlProtocolListener.h>
#include <Window.h>
#include "MapsData.h"
#include "MapsView.h"
class SearchBar : public BTextView {
public:
SearchBar(SearchResultList*);
virtual ~SearchBar();
virtual void KeyDown(const char*, int32);
virtual void MessageReceived(BMessage*);
private:
regex_t* regex0;
regex_t* regex1;
regmatch_t matches[3];
BString current;
SearchResultList* searchResultList;
};
struct SearchResultList_Data {
float longitude;
float latitude;
};
class SearchResultList : public BListView, public BUrlProtocolListener {
public:
SearchResultList();
virtual ~SearchResultList();
virtual void MakeEmpty();
virtual void AttachedToWindow();
virtual void MessageReceived(BMessage*);
virtual void TargetedByScrollView(BScrollView*);
virtual void DataReceived(BUrlRequest*, const char*, off_t, ssize_t);
virtual void RequestCompleted(BUrlRequest*, bool);
private:
static BString baseUrl;
int current;
BMallocIO* result;
thread_id thread;
BUrlRequest* request;
BScrollView *scrollBar;
std::map<int, SearchResultList_Data*> itemList;
};
SearchForm::SearchForm() {
searchResultList = new SearchResultList();
searchBar = new SearchBar(searchResultList);
MapsData::AddHandler(searchBar);
MapsData::AddHandler(searchResultList);
}
SearchForm::~SearchForm() {
}
BTextView* SearchForm::GetSearchBar() {
return searchBar;
}
BListView* SearchForm::GetSearchResultList() {
return searchResultList;
}
SearchBar::SearchBar(SearchResultList* view)
: BTextView("searchForm", B_WILL_DRAW | B_PULSE_NEEDED | B_SUPPORTS_LAYOUT) {
searchResultList = view;
BFont font;
SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, font.Size() * 1.4));
SetMaxBytes(32);
DisallowChar(B_RETURN);
SetAlignment(B_ALIGN_CENTER);
regex0 = (regex_t*)malloc(sizeof(regex_t));;
regex1 = (regex_t*)malloc(sizeof(regex_t));;
regcomp(regex0, "^([0-9]+\\.[0-9]+),([0-9]+\\.[0-9]+)$", REG_EXTENDED);
regcomp(regex1, "^([0-9]+),([0-9]+)$", REG_EXTENDED);
}
SearchBar::~SearchBar() {
regfree(regex0);
regfree(regex1);
}
void SearchBar::KeyDown(const char* bytes, int32 numBytes) {
switch (bytes[0]) {
case B_ENTER: {
MakeFocus(false);
BMessenger messenger(searchResultList);
BMessage* message = new BMessage(M_SEARCHRESULTLIST_SHOW);
BString temp;
BString regxstr(Text());
regxstr.ReplaceAll(" ", "");
if (!regexec(regex0, regxstr.String(), 3, matches, 0)) {
regxstr.CopyInto(temp, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
MapsData::SetLongitude(atof(temp.String()));
regxstr.CopyInto(temp, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
MapsData::SetLatitude(atof(temp.String()));
MapsData::Retrieve();
}
else if (!regexec(regex1, regxstr.String(), 3, matches, 0)){
regxstr.CopyInto(temp, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
MapsData::SetLongitude(atof(temp.String()));
regxstr.CopyInto(temp, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
MapsData::SetLatitude(atof(temp.String()));
MapsData::Retrieve();
}
else {
message->AddString("Text", BUrl::UrlEncode(Text(), false, false));
messenger.SendMessage(message);
}
}break;
default: {
BTextView::KeyDown(bytes, numBytes);
}break;
}
}
void SearchBar::MessageReceived(BMessage* msg) {
switch (msg->what) {
case MAPDATA_UPDATE: {
current.SetTo("");
MapsVector mapsVector = MapsData::GetVector();
current << mapsVector.longitude << ", ";
current << mapsVector.latitude;
SetText(current);
}break;
case M_MAPSVIEW_ON_FOCUS: {
MakeFocus(false);
SetText(current);
}break;
default: {
BTextView::MessageReceived(msg);
}break;
}
}
BString SearchResultList::baseUrl("https://nominatim.openstreetmap.org/search?q=%s&format=xml");
SearchResultList::SearchResultList()
: BListView("resultList") {
request = NULL;
scrollBar = NULL;
Hide();
}
SearchResultList::~SearchResultList() {
if (request != NULL) {
request->Stop();
wait_for_thread(thread, NULL);
delete request;
request = NULL;
}
}
void SearchResultList::MakeEmpty() {
itemList.clear();
BListView::MakeEmpty();
}
void SearchResultList::AttachedToWindow() {
SetSelectionMessage(new BMessage(M_SEARCHRESULTLIST_ON_SELECT));
SetInvocationMessage(new BMessage(M_SEARCHRESULTLIST_ON_INVOKE));
SetTarget(this);
}
void SearchResultList::MessageReceived(BMessage* message) {
switch (message->what) {
case M_SEARCHRESULTLIST_SHOW: {
if (scrollBar != NULL) {
scrollBar->Show();
}
Show();
MakeEmpty();
BString url;
url.SetToFormat(baseUrl.String(), message->GetString("Text"));
if (request != NULL) {
request->Stop();
wait_for_thread(thread, NULL);
delete result;
delete request;
request = NULL;
}
result = new BMallocIO();
request = BUrlProtocolRoster::MakeRequest(BUrl(url.String()), this);
thread = request->Run();
}break;
case M_SEARCHRESULTLIST_ON_SELECT: {
current = CurrentSelection();
}break;
case M_SEARCHRESULTLIST_ON_INVOKE: {
MapsData::SetLongitude(itemList[current]->longitude);
MapsData::SetLatitude(itemList[current]->latitude);
MapsData::Retrieve();
}
case M_MAPSVIEW_ON_FOCUS: {
if (scrollBar != NULL) {
scrollBar->Hide();
}
Hide();
}break;
case M_SEARCHRESULTLIST_ON_RESULT: {
BString xmlData((const char*)result->Buffer());
TiXmlDocument document;
document.Parse(xmlData);
int index = 0;
TiXmlElement* searchresult = document.FirstChildElement("searchresults");
for (TiXmlElement* e = searchresult->FirstChildElement("place"); e != NULL; e = e->NextSiblingElement("place")) {
AddItem(new BStringItem(e->Attribute("display_name")), index);
SearchResultList_Data* itemData = new SearchResultList_Data();
itemData->longitude = atof(e->Attribute("lon"));
itemData->latitude = atof(e->Attribute("lat"));
itemList.insert(std::pair<int, SearchResultList_Data*>(index, itemData));
index++;
}
}break;
default: {
BListView::MessageReceived(message);
}break;
}
}
void SearchResultList::TargetedByScrollView(BScrollView* view) {
scrollBar = view;
view->Hide();
BListView::TargetedByScrollView(view);
}
void SearchResultList::DataReceived(BUrlRequest* caller, const char* data, off_t position, ssize_t size) {
result->WriteAt(position, data, size);
}
void SearchResultList::RequestCompleted(BUrlRequest* caller, bool success) {
if (success) {
Invoke(new BMessage(M_SEARCHRESULTLIST_ON_RESULT));
}
}
|
/*
* Copyright 2016-2017 Raefaldhi Amartya Junior <[email protected]>
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "SearchForm.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include "tinyxml/tinyxml.h"
#include <LayoutBuilder.h>
#include <TextView.h>
#include <Url.h>
#include <UrlRequest.h>
#include <UrlProtocolRoster.h>
#include <UrlProtocolListener.h>
#include <Window.h>
#include "MapsData.h"
#include "MapsView.h"
class SearchBar : public BTextView {
public:
SearchBar(SearchResultList*);
virtual ~SearchBar();
virtual void KeyDown(const char*, int32);
virtual void MessageReceived(BMessage*);
private:
regex_t* regex0;
regex_t* regex1;
regmatch_t matches[3];
BString current;
SearchResultList* searchResultList;
};
struct SearchResultList_Data {
float longitude;
float latitude;
};
class SearchResultList : public BListView, public BUrlProtocolListener {
public:
SearchResultList();
virtual ~SearchResultList();
virtual void MakeEmpty();
virtual void AttachedToWindow();
virtual void MessageReceived(BMessage*);
virtual void TargetedByScrollView(BScrollView*);
virtual void DataReceived(BUrlRequest*, const char*, off_t, ssize_t);
virtual void RequestCompleted(BUrlRequest*, bool);
private:
static BString baseUrl;
int current;
BMallocIO* result;
thread_id thread;
BUrlRequest* request;
BScrollView *scrollBar;
std::map<int, SearchResultList_Data*> itemList;
};
SearchForm::SearchForm() {
searchResultList = new SearchResultList();
searchBar = new SearchBar(searchResultList);
MapsData::AddHandler(searchBar);
MapsData::AddHandler(searchResultList);
}
SearchForm::~SearchForm() {
}
BTextView* SearchForm::GetSearchBar() {
return searchBar;
}
BListView* SearchForm::GetSearchResultList() {
return searchResultList;
}
SearchBar::SearchBar(SearchResultList* view)
: BTextView("searchForm", B_WILL_DRAW | B_PULSE_NEEDED | B_SUPPORTS_LAYOUT) {
searchResultList = view;
BFont font;
SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, font.Size() * 1.4));
SetMaxBytes(32);
DisallowChar(B_RETURN);
SetAlignment(B_ALIGN_CENTER);
regex0 = (regex_t*)malloc(sizeof(regex_t));;
regex1 = (regex_t*)malloc(sizeof(regex_t));;
regcomp(regex0, "^([0-9]+\\.[0-9]+),([0-9]+\\.[0-9]+)$", REG_EXTENDED);
regcomp(regex1, "^([0-9]+),([0-9]+)$", REG_EXTENDED);
}
SearchBar::~SearchBar() {
regfree(regex0);
regfree(regex1);
}
void SearchBar::KeyDown(const char* bytes, int32 numBytes) {
switch (bytes[0]) {
case B_ENTER: {
MakeFocus(false);
BMessenger messenger(searchResultList);
BMessage* message = new BMessage(M_SEARCHRESULTLIST_SHOW);
BString temp;
BString regxstr(Text());
regxstr.ReplaceAll(" ", "");
if (!regexec(regex0, regxstr.String(), 3, matches, 0)) {
regxstr.CopyInto(temp, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
MapsData::SetLongitude(atof(temp.String()));
regxstr.CopyInto(temp, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
MapsData::SetLatitude(atof(temp.String()));
MapsData::Retrieve();
}
else if (!regexec(regex1, regxstr.String(), 3, matches, 0)){
regxstr.CopyInto(temp, matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
MapsData::SetLongitude(atof(temp.String()));
regxstr.CopyInto(temp, matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
MapsData::SetLatitude(atof(temp.String()));
MapsData::Retrieve();
}
else {
message->AddString("Text", BUrl::UrlEncode(Text(), false, false));
messenger.SendMessage(message);
}
}break;
default: {
BTextView::KeyDown(bytes, numBytes);
}break;
}
}
void SearchBar::MessageReceived(BMessage* msg) {
switch (msg->what) {
case MAPDATA_UPDATE: {
current.SetTo("");
MapsVector mapsVector = MapsData::GetVector();
current << mapsVector.longitude << ", ";
current << mapsVector.latitude;
SetText(current);
}break;
case M_MAPSVIEW_ON_FOCUS: {
MakeFocus(false);
SetText(current);
}break;
default: {
BTextView::MessageReceived(msg);
}break;
}
}
BString SearchResultList::baseUrl("https://nominatim.openstreetmap.org/search?q=%s&format=xml");
SearchResultList::SearchResultList()
: BListView("resultList") {
request = NULL;
scrollBar = NULL;
Hide();
}
SearchResultList::~SearchResultList() {
if (request != NULL) {
request->Stop();
wait_for_thread(thread, NULL);
delete request;
request = NULL;
}
}
void SearchResultList::MakeEmpty() {
itemList.clear();
BListView::MakeEmpty();
}
void SearchResultList::AttachedToWindow() {
SetSelectionMessage(new BMessage(M_SEARCHRESULTLIST_ON_SELECT));
SetInvocationMessage(new BMessage(M_SEARCHRESULTLIST_ON_INVOKE));
SetTarget(this);
}
void SearchResultList::MessageReceived(BMessage* message) {
switch (message->what) {
case M_SEARCHRESULTLIST_SHOW: {
MakeEmpty();
BString url;
url.SetToFormat(baseUrl.String(), message->GetString("Text"));
if (request != NULL) {
request->Stop();
wait_for_thread(thread, NULL);
delete result;
delete request;
request = NULL;
}
result = new BMallocIO();
request = BUrlProtocolRoster::MakeRequest(BUrl(url.String()), this);
thread = request->Run();
}break;
case M_SEARCHRESULTLIST_ON_SELECT: {
current = CurrentSelection();
}break;
case M_SEARCHRESULTLIST_ON_INVOKE: {
// We have to make sure that the list is not empty
// when the user clicks it. Otherwise, it throws an error.
if ((itemList.size() > current) && (current >= 0)) {
MapsData::SetLongitude(itemList[current]->longitude);
MapsData::SetLatitude(itemList[current]->latitude);
MapsData::Retrieve();
}
}
case M_MAPSVIEW_ON_FOCUS: {
if (scrollBar != NULL) {
scrollBar->Hide();
}
Hide();
}break;
case M_SEARCHRESULTLIST_ON_RESULT: {
BString xmlData((const char*)result->Buffer());
TiXmlDocument document;
document.Parse(xmlData);
int index = 0;
TiXmlElement* searchresult = document.FirstChildElement("searchresults");
// Also, we would want to tell the user when there are no matches.
TiXmlElement* e = searchresult->FirstChildElement("place");
if (e == NULL) {
SearchResultList_Data* itemData = new SearchResultList_Data();
// Disable the item so the user can't click on it.
BStringItem* item = new BStringItem("No matches found!");
item->SetEnabled(false);
AddItem(item);
// Set long and lat to current/previous location.
MapsVector mapsVector = MapsData::GetVector();
itemData->longitude = mapsVector.longitude;
itemData->latitude = mapsVector.latitude;
itemList.insert(std::pair<int, SearchResultList_Data*>(0, itemData));
}
for (e; e != NULL; e = e->NextSiblingElement("place")) {
AddItem(new BStringItem(e->Attribute("display_name")), index);
SearchResultList_Data* itemData = new SearchResultList_Data();
itemData->longitude = atof(e->Attribute("lon"));
itemData->latitude = atof(e->Attribute("lat"));
itemList.insert(std::pair<int, SearchResultList_Data*>(index, itemData));
index++;
}
// The list will only show AFTER all the data is inserted into the list.
if (scrollBar != NULL) {
scrollBar->Show();
}
Show();
}break;
default: {
BListView::MessageReceived(message);
}break;
}
}
void SearchResultList::TargetedByScrollView(BScrollView* view) {
scrollBar = view;
view->Hide();
BListView::TargetedByScrollView(view);
}
void SearchResultList::DataReceived(BUrlRequest* caller, const char* data, off_t position, ssize_t size) {
result->WriteAt(position, data, size);
}
void SearchResultList::RequestCompleted(BUrlRequest* caller, bool success) {
if (success) {
Invoke(new BMessage(M_SEARCHRESULTLIST_ON_RESULT));
}
}
|
Fix SegFault error when pressing on empty list
|
Fix SegFault error when pressing on empty list
|
C++
|
mit
|
raefaldhia/Maps
|
ffd47f4ff905d4d61e9e8595ad6e0797d247a0ea
|
tests/test_service.cpp
|
tests/test_service.cpp
|
/*
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/
#include <vector>
#include <iostream>
#include <string>
#include <gtest/gtest.h>
#include <qimessaging/session.hpp>
#include <qitype/anyobject.hpp>
#include <qitype/dynamicobjectbuilder.hpp>
#include <qitype/dynamicobject.hpp>
#include <qitype/objecttypebuilder.hpp>
#include <qimessaging/gateway.hpp>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <testsession/testsessionpair.hpp>
qiLogCategory("test");
static std::string reply(const std::string &msg)
{
return msg;
}
/* For asynchronous things where no synchronisation mechanism
* is possible, loop the check and wait a small delay,
* instead of one big sleep that will slow us down
*
*/
#define PERSIST_CHECK(code, cond, what, msdelay) \
do \
{ \
code; \
for(unsigned i=0; i<50 && !(cond); ++i) \
{ \
qi::os::msleep(1 + msdelay / 50); \
code; \
} \
what(cond); \
} while(0)
#define PERSIST_ASSERT(code, cond, msdelay) \
PERSIST_CHECK(code, cond, ASSERT_TRUE, msdelay)
#define PERSIST_EXPECT(code, cond, msdelay) \
PERSIST_CHECK(code, cond, EXPECT_TRUE, msdelay)
#define PERSIST(code, cond, msdelay) \
PERSIST_CHECK(code, cond, (void),msdelay)
//check for server closed
//check for socket disconnected
//check for service unregistered
//check for service unregistered, then readded
TEST(QiService, RemoteObjectCacheServerClose)
{
TestSessionPair p;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->close();
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
}
TEST(QiService, RemoteObjectCacheUnregister)
{
TestSessionPair p;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->unregisterService(idx);
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
}
TEST(QiService, RemoteObjectCacheABAUnregister)
{
TestSessionPair p;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->unregisterService(idx);
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
unsigned int idx2 = p.server()->registerService("serviceTest", obj);
//new service should not have a previoulsy registered ID
EXPECT_NE(idx2, idx);
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi");
if (fret.hasError()) {
std::cout << "Error returned:" << fret.error();
}
EXPECT_FALSE(fret.hasError());
EXPECT_EQ(std::string("titi"), fret.value());
}
TEST(QiService, RemoteObjectCacheABANewServer)
{
TestSessionPair p;
qi::Session ses;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->close();
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
qi::Future<void> f = ses.connect(p.client()->url().str());
f.wait(8000);
EXPECT_FALSE(f.hasError());
ses.listen("tcp://0.0.0.0:0");
unsigned int idx2 = ses.registerService("serviceTest", obj);
//new service should not have a previoulsy registered ID
EXPECT_NE(idx2, idx);
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi");
if (fret.hasError()) {
std::cout << "Error returned:" << fret.error();
}
EXPECT_FALSE(fret.hasError());
EXPECT_EQ(std::string("titi"), fret.value());
}
TEST(QiService, RemoteObjectNackTransactionWhenServerClosed)
{
TestSessionPair p;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("msleep", &qi::os::msleep);
qi::AnyObject obj(ob.object());
p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<void> fret = fut.value().call<void>("msleep", 2000);
qi::Future<void> fclose = p.server()->close();
fclose.wait(1000);
EXPECT_TRUE(fclose.isFinished());
EXPECT_FALSE(fclose.hasError(1));
fret.wait(1000);
//once the server is close, the answer should be ready.
EXPECT_TRUE(fret.isFinished());
//the service is closed, so it can't send an answer.
EXPECT_TRUE(fret.hasError(1000));
}
class Foo
{
public:
int ping(int i) { return i + prop.get();}
qi::Property<int> prop;
};
void inc (qi::Atomic<int>* daInt, int unused)
{
++(*daInt);
}
TEST(QiService, ClassProperty)
{
Foo f; // foo is registered as service, so must survive the session
TestSessionPair p;
qi::ObjectTypeBuilder<Foo> builder;
builder.advertiseMethod("ping", &Foo::ping);
ASSERT_TRUE(builder.advertiseProperty("offset", &Foo::prop) > 0);
qi::AnyObject obj = builder.object(&f, &qi::AnyObject::deleteGenericObjectOnly);
p.server()->registerService("foo", obj);
qi::AnyObject client = p.client()->service("foo");
qi::details::printMetaObject(std::cerr, obj.metaObject());
std::cerr <<"--" << std::endl;
qi::details::printMetaObject(std::cerr, client.metaObject());
qiLogDebug() << "setProp";
client.setProperty<int>("offset", 1).value();
qiLogDebug() << "setProp done";
ASSERT_EQ(1, f.prop.get());
ASSERT_EQ(2, client.call<int>("ping", 1));
f.prop.set(2);
ASSERT_EQ(3, client.call<int>("ping", 1));
ASSERT_EQ(2, client.property<int>("offset"));
// test event
qi::Atomic<int> hit = 0;
f.prop.connect(boost::bind(&inc, &hit, _1));
obj.connect("offset", boost::bind(&inc, &hit,_1));
client.connect("offset", boost::bind(&inc, &hit,_1));
f.prop.set(1);
PERSIST_ASSERT(, (*hit) == 3, 500);
client.setProperty("offset", 2);
PERSIST_ASSERT(, (*hit) == 6, 500);
// test error handling
EXPECT_TRUE(client.setProperty("canard", 5).hasError());
EXPECT_TRUE(client.setProperty("offset", "astring").hasError());
}
int prop_ping(qi::PropertyBase* &p, int v)
{
return p->value().toInt() + v;
}
TEST(QiService, GenericProperty)
{
TestSessionPair p;
qi::DynamicObject* dobj = new qi::DynamicObject();
qi::DynamicObjectBuilder builder(dobj);
unsigned int propId = builder.advertiseProperty<int>("offset");
qi::PropertyBase* prop;
builder.advertiseMethod("ping",
(boost::function<int (int)>)boost::bind(&prop_ping, boost::ref(prop), _1));
qi::AnyObject obj = builder.object();
prop = dobj->property(propId);
prop->setValue(0);
p.server()->registerService("foo", obj);
qi::AnyObject client = p.client()->service("foo");
client.setProperty("offset", 1);
ASSERT_EQ(1, prop->value().toInt());
ASSERT_EQ(2, client.call<int>("ping", 1));
prop->setValue(2);
ASSERT_EQ(3, client.call<int>("ping", 1));
ASSERT_EQ(2, client.property<int>("offset"));
// test event
qi::Atomic<int> hit;
qiLogVerbose() << "Connecting to signal";
ASSERT_NE(qi::SignalBase::invalidSignalLink, prop->signal()->connect((boost::function<void(int)>)boost::bind(&inc, &hit, _1)));
ASSERT_NE(qi::SignalBase::invalidSignalLink, obj.connect("offset", boost::bind(&inc, &hit, _1)));
ASSERT_NE(qi::SignalBase::invalidSignalLink, client.connect("offset", boost::bind(&inc, &hit, _1)));
qiLogVerbose() << "Triggering prop set";
prop->setValue(1);
PERSIST(, (*hit) == 3, 500);
qi::os::msleep(500);
EXPECT_EQ(3, *hit);
client.setProperty<int>("offset", 2);
PERSIST(, (*hit) == 6, 500);
qi::os::msleep(500);
EXPECT_EQ(6, *hit);
if (client != obj)
{
client.call<void>("setProperty", "offset", 3);
EXPECT_EQ(3, prop->value().toInt());
}
// test error handling
EXPECT_TRUE(client.setProperty("canard", 5).hasError());
EXPECT_TRUE(client.setProperty("offset", "astring").hasError());
}
class Bar
{
public:
void ping() { }
};
QI_REGISTER_OBJECT(Bar, ping)
TEST(QiService, RemoteServiceRegistrationAfterDisconnection)
{
TestSessionPair p;
// Create an object
boost::shared_ptr<Bar> bar(new Bar());
qi::AnyObject barAsObject = qi::AnyValue::from(bar).to<qi::AnyObject>();
// Register the object with the provider, find it back from the client
p.server()->registerService("Bar", barAsObject);
qi::AnyObject barAsRemoteService = p.client()->service("Bar");
ASSERT_TRUE(barAsRemoteService != NULL);
// Disconnect the provider, it should unregister any related services
p.server()->close();
qiLogVerbose() << "close finished";
qi::Future<void> fc = p.server()->connect(p.serviceDirectoryEndpoints()[0]);
fc.wait(3000);
if (fc.hasError())
qiLogError() << fc.error();
ASSERT_TRUE(fc.hasValue());
qiLogVerbose() << "Connect finished";
// Register the object again with the provider, find it back from the client
ASSERT_NO_THROW(p.server()->registerService("Bar", barAsObject));
qi::Future<qi::AnyObject> f = p.client()->service("Bar");
f.wait(3000);
ASSERT_TRUE(f.hasValue());
barAsRemoteService = f.value();
ASSERT_TRUE(barAsRemoteService != NULL);
}
int main(int argc, char **argv)
{
qi::Application app(argc, argv);
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
TestMode::initTestMode(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2010, 2012 Aldebaran Robotics
*/
#include <vector>
#include <iostream>
#include <string>
#include <gtest/gtest.h>
#include <qimessaging/session.hpp>
#include <qitype/anyobject.hpp>
#include <qitype/dynamicobjectbuilder.hpp>
#include <qitype/dynamicobject.hpp>
#include <qitype/objecttypebuilder.hpp>
#include <qimessaging/gateway.hpp>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <testsession/testsessionpair.hpp>
qiLogCategory("test");
static std::string reply(const std::string &msg)
{
return msg;
}
/* For asynchronous things where no synchronisation mechanism
* is possible, loop the check and wait a small delay,
* instead of one big sleep that will slow us down
*
*/
#define PERSIST_CHECK(code, cond, what, msdelay) \
do \
{ \
code; \
for(unsigned i=0; i<50 && !(cond); ++i) \
{ \
qi::os::msleep(1 + msdelay / 50); \
code; \
} \
what(cond); \
} while(0)
#define PERSIST_ASSERT(code, cond, msdelay) \
PERSIST_CHECK(code, cond, ASSERT_TRUE, msdelay)
#define PERSIST_EXPECT(code, cond, msdelay) \
PERSIST_CHECK(code, cond, EXPECT_TRUE, msdelay)
#define PERSIST(code, cond, msdelay) \
PERSIST_CHECK(code, cond, (void),msdelay)
//check for server closed
//check for socket disconnected
//check for service unregistered
//check for service unregistered, then readded
TEST(QiService, RemoteObjectCacheServerClose)
{
TestSessionPair p;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->close();
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
}
TEST(QiService, RemoteObjectCacheUnregister)
{
TestSessionPair p;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->unregisterService(idx);
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
}
TEST(QiService, RemoteObjectCacheABAUnregister)
{
TestSessionPair p;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->unregisterService(idx);
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
unsigned int idx2 = p.server()->registerService("serviceTest", obj);
//new service should not have a previoulsy registered ID
EXPECT_NE(idx2, idx);
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi");
if (fret.hasError()) {
std::cout << "Error returned:" << fret.error();
}
EXPECT_FALSE(fret.hasError());
EXPECT_EQ(std::string("titi"), fret.value());
}
TEST(QiService, RemoteObjectCacheABANewServer)
{
TestSessionPair p;
qi::Session ses;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("reply", &reply);
qi::AnyObject obj(ob.object());
unsigned int idx = p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
EXPECT_EQ(std::string("titi"), fut.value().call<std::string>("reply", "titi").value());
p.server()->close();
PERSIST_ASSERT(fut = p.client()->service("serviceTest"), fut.hasError(), 1000);
qi::Future<void> f = ses.connect(p.client()->url().str());
f.wait(8000);
EXPECT_FALSE(f.hasError());
ses.listen("tcp://0.0.0.0:0");
unsigned int idx2 = ses.registerService("serviceTest", obj);
//new service should not have a previoulsy registered ID
EXPECT_NE(idx2, idx);
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<std::string> fret = fut.value().call<std::string>("reply", "titi");
if (fret.hasError()) {
std::cout << "Error returned:" << fret.error();
}
EXPECT_FALSE(fret.hasError());
EXPECT_EQ(std::string("titi"), fret.value());
}
TEST(QiService, RemoteObjectNackTransactionWhenServerClosed)
{
TestSessionPair p;
if (p.server() == p.client()) // we close and not unregister, so does not work in direct mode
return;
qi::DynamicObjectBuilder ob;
ob.advertiseMethod("msleep", &qi::os::msleep);
qi::AnyObject obj(ob.object());
p.server()->registerService("serviceTest", obj);
qi::Future<qi::AnyObject> fut;
fut = p.client()->service("serviceTest");
EXPECT_FALSE(fut.hasError());
qi::Future<void> fret = fut.value().call<void>("msleep", 2000);
qi::Future<void> fclose = p.server()->close();
fclose.wait(1000);
EXPECT_TRUE(fclose.isFinished());
EXPECT_FALSE(fclose.hasError(1));
fret.wait(1000);
//once the server is close, the answer should be ready.
EXPECT_TRUE(fret.isFinished());
//the service is closed, so it can't send an answer.
EXPECT_TRUE(fret.hasError(1000));
}
class Foo
{
public:
int ping(int i) { return i + prop.get();}
qi::Property<int> prop;
};
void inc (qi::Atomic<int>* daInt, int unused)
{
++(*daInt);
}
TEST(QiService, ClassProperty)
{
Foo f; // foo is registered as service, so must survive the session
TestSessionPair p;
qi::ObjectTypeBuilder<Foo> builder;
builder.advertiseMethod("ping", &Foo::ping);
ASSERT_TRUE(builder.advertiseProperty("offset", &Foo::prop) > 0);
qi::AnyObject obj = builder.object(&f, &qi::AnyObject::deleteGenericObjectOnly);
p.server()->registerService("foo", obj);
qi::AnyObject client = p.client()->service("foo");
qi::details::printMetaObject(std::cerr, obj.metaObject());
std::cerr <<"--" << std::endl;
qi::details::printMetaObject(std::cerr, client.metaObject());
qiLogDebug() << "setProp";
client.setProperty<int>("offset", 1).value();
qiLogDebug() << "setProp done";
ASSERT_EQ(1, f.prop.get());
ASSERT_EQ(2, client.call<int>("ping", 1));
f.prop.set(2);
ASSERT_EQ(3, client.call<int>("ping", 1));
ASSERT_EQ(2, client.property<int>("offset"));
// test event
qi::Atomic<int> hit = 0;
f.prop.connect(boost::bind(&inc, &hit, _1));
obj.connect("offset", boost::bind(&inc, &hit,_1));
client.connect("offset", boost::bind(&inc, &hit,_1));
f.prop.set(1);
PERSIST_ASSERT(, (*hit) == 3, 500);
client.setProperty("offset", 2);
PERSIST_ASSERT(, (*hit) == 6, 500);
// test error handling
EXPECT_TRUE(client.setProperty("canard", 5).hasError());
EXPECT_TRUE(client.setProperty("offset", "astring").hasError());
}
int prop_ping(qi::PropertyBase* &p, int v)
{
return p->value().toInt() + v;
}
TEST(QiService, GenericProperty)
{
TestSessionPair p;
qi::DynamicObject* dobj = new qi::DynamicObject();
qi::DynamicObjectBuilder builder(dobj);
unsigned int propId = builder.advertiseProperty<int>("offset");
qi::PropertyBase* prop;
builder.advertiseMethod("ping",
(boost::function<int (int)>)boost::bind(&prop_ping, boost::ref(prop), _1));
qi::AnyObject obj = builder.object();
prop = dobj->property(propId);
prop->setValue(0);
p.server()->registerService("foo", obj);
qi::AnyObject client = p.client()->service("foo");
client.setProperty("offset", 1);
ASSERT_EQ(1, prop->value().toInt());
ASSERT_EQ(2, client.call<int>("ping", 1));
prop->setValue(2);
ASSERT_EQ(3, client.call<int>("ping", 1));
ASSERT_EQ(2, client.property<int>("offset"));
// test event
qi::Atomic<int> hit;
qiLogVerbose() << "Connecting to signal";
ASSERT_NE(qi::SignalBase::invalidSignalLink, prop->signal()->connect((boost::function<void(int)>)boost::bind(&inc, &hit, _1)));
ASSERT_NE(qi::SignalBase::invalidSignalLink, obj.connect("offset", boost::bind(&inc, &hit, _1)));
ASSERT_NE(qi::SignalBase::invalidSignalLink, client.connect("offset", boost::bind(&inc, &hit, _1)));
qiLogVerbose() << "Triggering prop set";
prop->setValue(1);
PERSIST(, (*hit) == 3, 500);
qi::os::msleep(500);
EXPECT_EQ(3, *hit);
client.setProperty<int>("offset", 2);
PERSIST(, (*hit) == 6, 500);
qi::os::msleep(500);
EXPECT_EQ(6, *hit);
if (client != obj)
{
client.call<void>("setProperty", "offset", 3);
EXPECT_EQ(3, prop->value().toInt());
}
// test error handling
EXPECT_TRUE(client.setProperty("canard", 5).hasError());
EXPECT_TRUE(client.setProperty("offset", "astring").hasError());
}
class Bar
{
public:
void ping() { }
};
QI_REGISTER_OBJECT(Bar, ping)
TEST(QiService, RemoteServiceRegistrationAfterDisconnection)
{
TestSessionPair p;
// Create an object
boost::shared_ptr<Bar> bar(new Bar());
qi::AnyObject barAsObject = qi::AnyValue::from(bar).to<qi::AnyObject>();
// Register the object with the provider, find it back from the client
p.server()->registerService("Bar", barAsObject);
qi::AnyObject barAsRemoteService = p.client()->service("Bar");
ASSERT_TRUE(barAsRemoteService);
// Disconnect the provider, it should unregister any related services
p.server()->close();
qiLogVerbose() << "close finished";
qi::Future<void> fc = p.server()->connect(p.serviceDirectoryEndpoints()[0]);
fc.wait(3000);
if (fc.hasError())
qiLogError() << fc.error();
ASSERT_TRUE(fc.hasValue());
qiLogVerbose() << "Connect finished";
// Register the object again with the provider, find it back from the client
ASSERT_NO_THROW(p.server()->registerService("Bar", barAsObject));
qi::Future<qi::AnyObject> f = p.client()->service("Bar");
f.wait(3000);
ASSERT_TRUE(f.hasValue());
barAsRemoteService = f.value();
ASSERT_TRUE(barAsRemoteService);
}
int main(int argc, char **argv)
{
qi::Application app(argc, argv);
#if defined(__APPLE__) || defined(__linux__)
setsid();
#endif
TestMode::initTestMode(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
fix warnings
|
Test: fix warnings
Change-Id: I13484079d3dfd43c496decda1308f9ad97d0be52
Reviewed-on: http://gerrit.aldebaran.lan/38248
Reviewed-by: pdaouadi <[email protected]>
Tested-by: pdaouadi <[email protected]>
|
C++
|
bsd-3-clause
|
aldebaran/libqi,aldebaran/libqi,vbarbaresi/libqi,bsautron/libqi,aldebaran/libqi
|
af72c898095e91132e0569315561dd59def50da9
|
ext/pdfium_ext/page.cc
|
ext/pdfium_ext/page.cc
|
#include "page.h"
#include "page_wrapper.h"
#include "pdfium.h"
#include <FreeImage.h>
#include "fpdfview.h"
#include <limits.h>
#include <algorithm>
#include <string>
extern "C" {
#include "ruby/encoding.h"
}
static VALUE rb_sym_height;
static VALUE rb_sym_width;
//static VALUE RB_Document;
/////////////////////////////////////////////////////////////////////////
// The Page class //
/////////////////////////////////////////////////////////////////////////
/*
* Document-class: PDFium::Page
* A Page on a PDFium::Document
*/
static void
page_gc_free(PageWrapper* page)
{
DEBUG_MSG("GC Free Page: " << page);
// The page's destructor will remove itself from the Document, and perform all cleanup
page->markUnused();
}
/*
* call-seq:
* Page.new -> raises RuntimeError
*
* Pages cannot be created by using Page.new, instead Page.open or Page.create
* should be used
*/
static VALUE
page_new(VALUE klass)
{
rb_raise(rb_eRuntimeError, "Use Page.open or Page.create");
}
/*
* call-seq:
* Page.open(PDFIum::Document, page_index) -> Page
*
* Opens a given page on a document
*/
static VALUE
page_open(VALUE klass, VALUE rb_document, VALUE rb_page_number)
{
DocumentWrapper *doc_wrapper;
Data_Get_Struct(rb_document, DocumentWrapper, doc_wrapper);
int pg = FIX2INT(rb_page_number);
if ( pg < 0 || pg >= doc_wrapper->document->GetPageCount() ){
rb_raise(rb_eRangeError, "%d is out of range: 0...%d",
pg, doc_wrapper->document->GetPageCount() );
}
PageWrapper *page_wrapper = new PageWrapper(doc_wrapper, FIX2INT(rb_page_number));
return Data_Wrap_Struct(klass, NULL, page_gc_free, page_wrapper);
}
/*
* call-seq:
* Page.create(PDFIum::Document, page_number=document.page_count) -> Page
*
* Creates a new page on a document. The page_number defaults to the
* Document#page_count, causing pages to be appended to the back of the document
* by default if no page_number is given.
*/
static VALUE
page_create(int argc, VALUE *argv, VALUE klass)
{
VALUE rb_document, rb_page_number, options;
rb_scan_args(argc, argv, "11:", &rb_document, &rb_page_number, &options);
if (NIL_P(options)){
options=rb_hash_new();
rb_hash_aset(options, ID2SYM(rb_intern("size")),
rb_const_get(RB::PDFium(), rb_intern("LETTER")) );
}
VALUE size, rb_width, rb_height;
if ( !NIL_P(size = RB::get_option(options,"size")) ){
rb_width = rb_ary_entry(size, 0);
rb_height = rb_ary_entry(size, 1);
} else {
rb_width = RB::get_option(options,"width");
rb_height = RB::get_option(options,"height");
}
if ( NIL_P(rb_width) || NIL_P(rb_height) ){
rb_raise(rb_eArgError, ":height or :width must be given");
}
DocumentWrapper *doc_wrapper;
Data_Get_Struct(rb_document, DocumentWrapper, doc_wrapper);
int page_number;
if (NIL_P(rb_page_number)){
page_number = doc_wrapper->document->GetPageCount();
} else {
page_number = FIX2INT(rb_page_number);
}
if ( page_number < 0 || page_number > doc_wrapper->document->GetPageCount() ){
rb_raise(rb_eRangeError, "%d is out of range: 0...%d",
page_number, doc_wrapper->document->GetPageCount() );
}
CPDF_Page* newpage = (CPDF_Page*)FPDFPage_New(doc_wrapper->document, page_number,
FIX2INT(rb_width), FIX2INT(rb_height) );
PageWrapper *page_wrapper = new PageWrapper(doc_wrapper, rb_page_number);
page_wrapper->setPage(newpage);
VALUE i=Data_Wrap_Struct(klass, NULL, page_gc_free, page_wrapper);
return i;
}
/*
* call-seq:
* width -> Float
*
* Returns the width of the page.
* The width is given in terms of points, which are set to 72 per inch. (DPI)
*/
static VALUE
page_width(VALUE self)
{
return rb_float_new( FPDF_GetPageWidth(RB2PG(self)) );
}
/*
* call-seq:
* height -> Float
*
* Returns the height of the page.
* The height is given in terms of points, which are set to 72 per inch. (DPI)
*/
static VALUE
page_height(VALUE self)
{
return rb_float_new( FPDF_GetPageHeight(RB2PG(self)) );
}
/*
* call-seq:
* text -> String
*
* Returns the text that is contained on the page as a UTF-16LE encoded string
*/
static VALUE
page_text(VALUE self)
{
static rb_encoding *enc = rb_enc_find("UTF-16LE");
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
CPDF_Page *page = pw->page();
IPDF_TextPage *text_page = (IPDF_TextPage*)FPDFText_LoadPage(page);
//
unsigned int buff_size = text_page->CountChars()*2 + 1; // 16 bit per char, plus terminator
char *buffer = ALLOC_N(char, buff_size );
FPDFText_GetText((FPDF_TEXTPAGE)text_page, 0, text_page->CountChars(), (unsigned short*)buffer);
VALUE ret = rb_enc_str_new(buffer, buff_size-1, enc);
xfree(buffer);
return ret;
}
/*
* call-seq:
* number -> Fixnum
*
* Returns the page number that the page represents on the document.
* It is *NOT* zero based, meaning that the first page#number will be 1.
*
* *Warning:* if pages are added/removed after the page is loaded, this value will be inaccurate.
*/
static VALUE
page_number(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
return INT2FIX(pw->_page_number+1);
}
/*
call-seq:
images -> ImageList
Returns ImageList which contains all the images on the page. Images are lazily loaded only when requested.
=== Example
pdf = PDFium::Document.new( "test.pdf" )
page = pdf.pages.first
page.images.each do | image |
image.save("pg-#{page.number}-#{image.index}.png")
end
*/
static VALUE
page_images(VALUE self)
{
VALUE args[1];
args[0] = self;
return rb_class_new_instance( 1, args, RB::ImageList() );
}
/*
call-seq:
as_image(width:nil, height:nil) -> Image
Render a page as an image of width and height to the given file. The image type
will be auto-detected from the file_path's extension, and can be any of the
formats supported by the FreeImage library http://freeimage.sourceforge.net/features.html
If neither the height or width are given, it will be calculated to retain the
approprate page scale.
Returns an Image instance.
=== Example
pdf = PDFium::Document.new( "test.pdf" )
page = pdf.pages[0]
page.as_image(height: 100, width: 75).save("pg-#{page.number}-sm.png")
page.as_image(height: 500).save("pg-#{page.number}-md.png")
page.as_image(width: 1000).save("pg-#{page.number}-lg.png")
If the above page's #dimensions were 1000x1500, then the following images would be generated:
pg-1-sm.png -> 100x75
pg-1-md.png -> 500x750
pg-1-lg.png -> 750x1000
*/
static VALUE
page_as_image(int argc, VALUE *argv, VALUE self)
{
CPDF_Page *page = RB2PG(self);
VALUE rb_options;
rb_scan_args(argc,argv,":", &rb_options);
if (NIL_P(rb_options)){
rb_options=rb_hash_new();
}
if ( TYPE(rb_options) != T_HASH ){
rb_raise(rb_eTypeError, "wrong argument type %s (expected Hash)", rb_obj_classname(rb_options));
}
VALUE width_option = rb_hash_aref(rb_options, rb_sym_width);
VALUE height_option = rb_hash_aref(rb_options, rb_sym_height);
int width = NIL_P(width_option) ? 0 : FIX2INT(width_option);
int height = NIL_P(height_option) ? 0 : FIX2INT(height_option);
if (!width && !height){
width = FPDF_GetPageWidth(page) * 2;
}
if (!width)
width = FPDF_GetPageWidth(page) * ( (double)height / FPDF_GetPageHeight(page) );
if (!height)
height = FPDF_GetPageHeight(page) * ( (double)width / FPDF_GetPageWidth(page) );
VALUE args[2];
args[0] = self;
VALUE img_options = args[1] = rb_hash_new();
rb_hash_aset(img_options, rb_sym_width, INT2FIX(width));
rb_hash_aset(img_options, rb_sym_height, INT2FIX(height));
VALUE bounds_args[4];
bounds_args[0] = rb_float_new( 0 );
bounds_args[1] = rb_float_new( FPDF_GetPageWidth(page) );
bounds_args[2] = rb_float_new( 0 );
bounds_args[3] = rb_float_new( FPDF_GetPageHeight(page) );
VALUE bounds = rb_class_new_instance( 4, bounds_args, RB::BoundingBox() );
rb_hash_aset(img_options, ID2SYM(rb_intern("bounds")), bounds);
return rb_class_new_instance( 2, args, RB::Image() );
}
/*
* call-seq:
* unload -> Page
*
* Frees a large portion of the internal memory allocated to the page.
* When a page is parsed by the PDFIum engine, various elements are cached in memory
* While Ruby will eventually garbage collect the Page instance once it's no longer
* in use, this method will free the memory immediatly. Page#unload is safe to use
* since the Page will re-load itself as needed, but calling it while the page
* is still in use will cause additional work by the engine since it will have to
* repeatedly re-parse the page when it re-loads itself.
*
* PageList#each will call this method on each page after it yields.
*/
static VALUE
page_unload(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
pw->unload();
return self;
}
// creates and yeilds an image. Not documented since all access
// should got through the ImageList interface via the Page#images method
/* :nodoc: */
static VALUE
page_each_image(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
auto count = pw->page()->CountObjects();
int image_index=0;
for (int index=0; index < count; index++){
CPDF_PageObject *object = pw->page()->GetObjectByIndex(index);
if ( PDFPAGE_IMAGE == object->m_Type ){
VALUE args[2];
args[0] = self;
VALUE img_options = args[1] = rb_hash_new();
rb_hash_aset(img_options, ID2SYM(rb_intern("object_index")), INT2FIX(index));
rb_hash_aset(img_options, ID2SYM(rb_intern("index")), INT2FIX(image_index));
VALUE img = rb_class_new_instance( 2, args, RB::Image() );
rb_yield( img );
image_index++;
}
}
return self;
}
void
define_page_class()
{
rb_sym_width = ID2SYM(rb_intern("width"));
rb_sym_height = ID2SYM(rb_intern("height"));
VALUE PDFium = RB::PDFium();
/*
The Page class definition and methods
*/
VALUE RB_Page = rb_define_class_under( PDFium, "Page", rb_cObject);
rb_define_singleton_method(RB_Page, "new", RUBY_METHOD_FUNC(page_new), 0);
rb_define_singleton_method(RB_Page, "open", RUBY_METHOD_FUNC(page_open), 2);
rb_define_singleton_method(RB_Page, "create", RUBY_METHOD_FUNC(page_create), -1);
rb_define_method (RB_Page, "text", RUBY_METHOD_FUNC(page_text), 0);
rb_define_method (RB_Page, "width", RUBY_METHOD_FUNC(page_width), 0);
rb_define_method (RB_Page, "height", RUBY_METHOD_FUNC(page_height), 0);
rb_define_method (RB_Page, "as_image", RUBY_METHOD_FUNC(page_as_image), -1);
rb_define_method (RB_Page, "unload", RUBY_METHOD_FUNC(page_unload), 0);
rb_define_method (RB_Page, "number", RUBY_METHOD_FUNC(page_number), 0);
rb_define_method (RB_Page, "images", RUBY_METHOD_FUNC(page_images), 0);
rb_define_method (RB_Page, "each_image", RUBY_METHOD_FUNC(page_each_image), 0);
}
|
#include "page.h"
#include "page_wrapper.h"
#include "pdfium.h"
#include <FreeImage.h>
#include "fpdfview.h"
#include <limits.h>
#include <algorithm>
#include <string>
extern "C" {
#include "ruby/encoding.h"
}
static VALUE rb_sym_height;
static VALUE rb_sym_width;
//static VALUE RB_Document;
/////////////////////////////////////////////////////////////////////////
// The Page class //
/////////////////////////////////////////////////////////////////////////
/*
* Document-class: PDFium::Page
* A Page on a PDFium::Document
*/
static void
page_gc_free(PageWrapper* page)
{
DEBUG_MSG("GC Free Page: " << page);
// The page's destructor will remove itself from the Document, and perform all cleanup
page->markUnused();
}
/*
* call-seq:
* Page.new -> raises RuntimeError
*
* Pages cannot be created by using Page.new, instead Page.open or Page.create
* should be used
*/
static VALUE
page_new(VALUE klass)
{
rb_raise(rb_eRuntimeError, "Use Page.open or Page.create");
}
/*
* call-seq:
* Page.open(PDFIum::Document, page_index) -> Page
*
* Opens a given page on a document
*/
static VALUE
page_open(VALUE klass, VALUE rb_document, VALUE rb_page_number)
{
DocumentWrapper *doc_wrapper;
Data_Get_Struct(rb_document, DocumentWrapper, doc_wrapper);
int pg = FIX2INT(rb_page_number);
if ( pg < 0 || pg >= doc_wrapper->document->GetPageCount() ){
rb_raise(rb_eRangeError, "%d is out of range: 0...%d",
pg, doc_wrapper->document->GetPageCount() );
}
PageWrapper *page_wrapper = new PageWrapper(doc_wrapper, FIX2INT(rb_page_number));
return Data_Wrap_Struct(klass, NULL, page_gc_free, page_wrapper);
}
/*
* call-seq:
* Page.create(PDFIum::Document, page_number=document.page_count) -> Page
*
* Creates a new page on a document. The page_number defaults to the
* Document#page_count, causing pages to be appended to the back of the document
* by default if no page_number is given.
*/
static VALUE
page_create(int argc, VALUE *argv, VALUE klass)
{
VALUE rb_document, rb_page_number, options;
rb_scan_args(argc, argv, "11:", &rb_document, &rb_page_number, &options);
if (NIL_P(options)){
options=rb_hash_new();
rb_hash_aset(options, ID2SYM(rb_intern("size")),
rb_const_get(RB::PDFium(), rb_intern("LETTER")) );
}
VALUE size, rb_width, rb_height;
if ( !NIL_P(size = RB::get_option(options,"size")) ){
rb_width = rb_ary_entry(size, 0);
rb_height = rb_ary_entry(size, 1);
} else {
rb_width = RB::get_option(options,"width");
rb_height = RB::get_option(options,"height");
}
if ( NIL_P(rb_width) || NIL_P(rb_height) ){
rb_raise(rb_eArgError, ":height or :width must be given");
}
DocumentWrapper *doc_wrapper;
Data_Get_Struct(rb_document, DocumentWrapper, doc_wrapper);
int page_number;
if (NIL_P(rb_page_number)){
page_number = doc_wrapper->document->GetPageCount();
} else {
page_number = FIX2INT(rb_page_number);
}
if ( page_number < 0 || page_number > doc_wrapper->document->GetPageCount() ){
rb_raise(rb_eRangeError, "%d is out of range: 0...%d",
page_number, doc_wrapper->document->GetPageCount() );
}
CPDF_Page* newpage = (CPDF_Page*)FPDFPage_New(doc_wrapper->document, page_number,
FIX2INT(rb_width), FIX2INT(rb_height) );
PageWrapper *page_wrapper = new PageWrapper(doc_wrapper, rb_page_number);
page_wrapper->setPage(newpage);
VALUE i=Data_Wrap_Struct(klass, NULL, page_gc_free, page_wrapper);
return i;
}
/*
* call-seq:
* width -> Float
*
* Returns the width of the page.
* The width is given in terms of points, which are set to 72 per inch. (DPI)
*/
static VALUE
page_width(VALUE self)
{
return rb_float_new( FPDF_GetPageWidth(RB2PG(self)) );
}
/*
* call-seq:
* height -> Float
*
* Returns the height of the page.
* The height is given in terms of points, which are set to 72 per inch. (DPI)
*/
static VALUE
page_height(VALUE self)
{
return rb_float_new( FPDF_GetPageHeight(RB2PG(self)) );
}
/*
* call-seq:
* text -> String
*
* Returns the text that is contained on the page as a UTF-16LE encoded string
*/
static VALUE
page_text(VALUE self)
{
static rb_encoding *enc = rb_enc_find("UTF-16LE");
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
CPDF_Page *page = pw->page();
IPDF_TextPage *text_page = (IPDF_TextPage*)FPDFText_LoadPage(page);
//
unsigned int buff_size = text_page->CountChars()*2 + 1; // 16 bit per char, plus terminator
char *buffer = ALLOC_N(char, buff_size );
FPDFText_GetText((FPDF_TEXTPAGE)text_page, 0, text_page->CountChars(), (unsigned short*)buffer);
VALUE ret = rb_enc_str_new(buffer, buff_size-1, enc);
xfree(buffer);
return ret;
}
/*
* call-seq:
* number -> Fixnum
*
* Returns the page number that the page represents on the document.
* It is *NOT* zero based, meaning that the first page#number will be 1.
*
* *Warning:* if pages are added/removed after the page is loaded, this value will be inaccurate.
*/
static VALUE
page_number(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
return INT2FIX(pw->_page_number+1);
}
/*
call-seq:
images -> ImageList
Returns ImageList which contains all the images on the page. Images are lazily loaded only when requested.
=== Example
pdf = PDFium::Document.new( "test.pdf" )
page = pdf.pages.first
page.images.each do | image |
image.save("pg-#{page.number}-#{image.index}.png")
end
*/
static VALUE
page_images(VALUE self)
{
VALUE args[1];
args[0] = self;
return rb_class_new_instance( 1, args, RB::ImageList() );
}
/*
call-seq:
as_image(width:nil, height:nil) -> Image
Render a page as an image of width and height to the given file. The image type
will be auto-detected from the file_path's extension, and can be any of the
formats supported by the FreeImage library http://freeimage.sourceforge.net/features.html
If neither the height or width are given, it will be calculated to retain the
approprate page scale.
Returns an Image instance.
=== Example
pdf = PDFium::Document.new( "test.pdf" )
page = pdf.pages[0]
page.as_image(height: 100, width: 75).save("pg-#{page.number}-sm.png")
page.as_image(height: 500).save("pg-#{page.number}-md.png")
page.as_image(width: 1000).save("pg-#{page.number}-lg.png")
If the above page's #dimensions were 1000x1500, then the following images would be generated:
pg-1-sm.png -> 100x75
pg-1-md.png -> 500x750
pg-1-lg.png -> 750x1000
*/
static VALUE
page_as_image(int argc, VALUE *argv, VALUE self)
{
CPDF_Page *page = RB2PG(self);
VALUE rb_options;
rb_scan_args(argc,argv,":", &rb_options);
if (NIL_P(rb_options)){
rb_options=rb_hash_new();
}
if ( TYPE(rb_options) != T_HASH ){
rb_raise(rb_eTypeError, "wrong argument type %s (expected Hash)", rb_obj_classname(rb_options));
}
VALUE width_option = rb_hash_aref(rb_options, rb_sym_width);
VALUE height_option = rb_hash_aref(rb_options, rb_sym_height);
int width = NIL_P(width_option) ? 0 : FIX2INT(width_option);
int height = NIL_P(height_option) ? 0 : FIX2INT(height_option);
if (!width && !height){
width = FPDF_GetPageWidth(page) * 2;
}
if (!width)
width = FPDF_GetPageWidth(page) * ( (double)height / FPDF_GetPageHeight(page) );
if (!height)
height = FPDF_GetPageHeight(page) * ( (double)width / FPDF_GetPageWidth(page) );
VALUE args[2];
args[0] = self;
VALUE img_options = args[1] = rb_hash_new();
rb_hash_aset(img_options, rb_sym_width, INT2FIX(width));
rb_hash_aset(img_options, rb_sym_height, INT2FIX(height));
VALUE bounds_args[4];
bounds_args[0] = rb_float_new( 0 );
bounds_args[1] = rb_float_new( FPDF_GetPageWidth(page) );
bounds_args[2] = rb_float_new( 0 );
bounds_args[3] = rb_float_new( FPDF_GetPageHeight(page) );
VALUE bounds = rb_class_new_instance( 4, bounds_args, RB::BoundingBox() );
rb_hash_aset(img_options, ID2SYM(rb_intern("bounds")), bounds);
return rb_class_new_instance( 2, args, RB::Image() );
}
/*
* call-seq:
* unload -> Page
*
* Frees a large portion of the internal memory allocated to the page.
* When a page is parsed by the PDFIum engine, various elements are cached in memory
* While Ruby will eventually garbage collect the Page instance once it's no longer
* in use, this method will free the memory immediatly. Page#unload is safe to use
* since the Page will re-load itself as needed, but calling it while the page
* is still in use will cause additional work by the engine since it will have to
* repeatedly re-parse the page when it re-loads itself.
*
* PageList#each will call this method on each page after it yields.
*/
static VALUE
page_unload(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
pw->unload();
return self;
}
// creates and yeilds an image. Not documented since all access
// should got through the ImageList interface via the Page#images method
/* :nodoc: */
static VALUE
page_each_image(VALUE self)
{
PageWrapper *pw;
Data_Get_Struct(self, PageWrapper, pw);
unsigned int count = pw->page()->CountObjects();
int image_index=0;
for (unsigned int index=0; index < count; index++){
CPDF_PageObject *object = pw->page()->GetObjectByIndex(index);
if ( PDFPAGE_IMAGE == object->m_Type ){
VALUE args[2];
args[0] = self;
VALUE img_options = args[1] = rb_hash_new();
rb_hash_aset(img_options, ID2SYM(rb_intern("object_index")), INT2FIX(index));
rb_hash_aset(img_options, ID2SYM(rb_intern("index")), INT2FIX(image_index));
VALUE img = rb_class_new_instance( 2, args, RB::Image() );
rb_yield( img );
image_index++;
}
}
return self;
}
void
define_page_class()
{
rb_sym_width = ID2SYM(rb_intern("width"));
rb_sym_height = ID2SYM(rb_intern("height"));
VALUE PDFium = RB::PDFium();
/*
The Page class definition and methods
*/
VALUE RB_Page = rb_define_class_under( PDFium, "Page", rb_cObject);
rb_define_singleton_method(RB_Page, "new", RUBY_METHOD_FUNC(page_new), 0);
rb_define_singleton_method(RB_Page, "open", RUBY_METHOD_FUNC(page_open), 2);
rb_define_singleton_method(RB_Page, "create", RUBY_METHOD_FUNC(page_create), -1);
rb_define_method (RB_Page, "text", RUBY_METHOD_FUNC(page_text), 0);
rb_define_method (RB_Page, "width", RUBY_METHOD_FUNC(page_width), 0);
rb_define_method (RB_Page, "height", RUBY_METHOD_FUNC(page_height), 0);
rb_define_method (RB_Page, "as_image", RUBY_METHOD_FUNC(page_as_image), -1);
rb_define_method (RB_Page, "unload", RUBY_METHOD_FUNC(page_unload), 0);
rb_define_method (RB_Page, "number", RUBY_METHOD_FUNC(page_number), 0);
rb_define_method (RB_Page, "images", RUBY_METHOD_FUNC(page_images), 0);
rb_define_method (RB_Page, "each_image", RUBY_METHOD_FUNC(page_each_image), 0);
}
|
Fix unsigned/signed comparision warning
|
Fix unsigned/signed comparision warning
|
C++
|
mit
|
openresearch/pdfium-ruby,openresearch/pdfium-ruby,openresearch/pdfium-ruby,nathanstitt/pdfium-ruby,nathanstitt/pdfium-ruby,nathanstitt/pdfium-ruby
|
ddedeab5ddd41affe948f09c6ea5dbf28a7dfc62
|
src/tools/davix_taskqueue.cpp
|
src/tools/davix_taskqueue.cpp
|
/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2013
* Author: Kwong Tat Cheung <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "davix_taskqueue.hpp"
#include <davix_internal.hpp>
#include <utils/davix_logger_internal.hpp>
namespace Davix{
DavixTaskQueue::DavixTaskQueue(){
pthread_mutex_init(&tq_mutex, NULL);
pthread_cond_init(&popOpConvar, NULL);
pthread_cond_init(&pushOpConvar, NULL);
_shutdown = false;
}
int DavixTaskQueue::pushOp(DavixOp* op){
//struct timespec to;
DavixMutex mutex(tq_mutex);
/*
to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
to.tv_nsec = 0;
*/
while(taskQueue.size() >= DAVIX_DEFAULT_TASKQUEUE_SIZE)
pthread_cond_wait(&pushOpConvar, mutex.getMutex());
/*
while(taskQueue.size() >= DAVIX_DEFAULT_TASKQUEUE_SIZE){
int rc = pthread_cond_timedwait(&pushOpConvar, mutex.getMutex(), &to);
if(rc == ETIMEDOUT)
{
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "PushOp() timed out. Task Queue size is {}", taskQueue.size());
to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
}
}
*/
taskQueue.push_back(op);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) {} Op pushed to taskQueue, target is {}, queue size is now: {}", op->getOpType(), op->getTargetUrl(), taskQueue.size());
mutex.unlock();
pthread_cond_signal(&popOpConvar);
return 0;
}
DavixOp* DavixTaskQueue::popOp(){
//struct timespec to;
DavixMutex mutex(tq_mutex);
while(taskQueue.empty() && !_shutdown){
/*
to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
to.tv_nsec = 0;
int rc = pthread_cond_timedwait(&popOpConvar, mutex.getMutex(), &to);
if(rc == ETIMEDOUT)
{
std::cerr << std::endl << "(DavixTaskQueue) PopOp() timed out." << std::endl;
return NULL;
}
}
*/
pthread_cond_wait(&popOpConvar, mutex.getMutex());
if(_shutdown){
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) Shutting down task queue, queue size is: {}", taskQueue.size());
return NULL;
}
}
if(taskQueue.size() > 0){
DavixOp* op = taskQueue.front();
taskQueue.pop_front();
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) Op popped from taskQueue, queue size is now: {}", taskQueue.size());
mutex.unlock();
pthread_cond_signal(&pushOpConvar);
return op;
}
else
return NULL;
}
int DavixTaskQueue::getSize(){
DavixMutex mutex(tq_mutex);
return taskQueue.size();
}
bool DavixTaskQueue::isEmpty(){
DavixMutex mutex(tq_mutex);
return taskQueue.empty();
}
void DavixTaskQueue::shutdown(){
_shutdown = true;
pthread_cond_broadcast(&pushOpConvar);
pthread_cond_broadcast(&popOpConvar);
}
bool DavixTaskQueue::isStopped(){
return _shutdown;
}
}
|
/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2013
* Author: Kwong Tat Cheung <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "davix_taskqueue.hpp"
#include <davix_internal.hpp>
#include <utils/davix_logger_internal.hpp>
namespace Davix{
DavixTaskQueue::DavixTaskQueue(){
pthread_mutex_init(&tq_mutex, NULL);
pthread_cond_init(&popOpConvar, NULL);
pthread_cond_init(&pushOpConvar, NULL);
_shutdown = false;
}
int DavixTaskQueue::pushOp(DavixOp* op){
{
DavixMutex mutex(tq_mutex);
/*
* to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
* to.tv_nsec = 0;
*/
while(taskQueue.size() >= DAVIX_DEFAULT_TASKQUEUE_SIZE)
pthread_cond_wait(&pushOpConvar, mutex.getMutex());
/*
* while(taskQueue.size() >= DAVIX_DEFAULT_TASKQUEUE_SIZE){
* int rc = pthread_cond_timedwait(&pushOpConvar, mutex.getMutex(), &to);
* if(rc == ETIMEDOUT)
* {
* DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "PushOp() timed out. Task Queue size is {}", taskQueue.size());
* to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
}
}
*/
taskQueue.push_back(op);
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) {} Op pushed to taskQueue, target is {}, queue size is now: {}", op->getOpType(), op->getTargetUrl(), taskQueue.size());
pthread_cond_signal(&popOpConvar);
return 0;
}
DavixOp* DavixTaskQueue::popOp(){
bool dosig = false;
DavixOp* op;
//struct timespec to;
{
DavixMutex mutex(tq_mutex);
while(taskQueue.empty() && !_shutdown){
/*
* to.tv_sec = time(NULL) + DEFAULT_WAIT_TIME;
* to.tv_nsec = 0;
* int rc = pthread_cond_timedwait(&popOpConvar, mutex.getMutex(), &to);
*
* if(rc == ETIMEDOUT)
* {
* std::cerr << std::endl << "(DavixTaskQueue) PopOp() timed out." << std::endl;
* return NULL;
}
}
*/
pthread_cond_wait(&popOpConvar, mutex.getMutex());
if(_shutdown){
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) Shutting down task queue, queue size is: {}", taskQueue.size());
return NULL;
}
}
if(taskQueue.size() > 0){
op = taskQueue.front();
taskQueue.pop_front();
dosig = true;
}
}
if (dosig) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CORE, "(DavixTaskQueue) Op popped from taskQueue, queue size is now: {}", taskQueue.size());
pthread_cond_signal(&pushOpConvar);
return op;
}
return NULL;
}
int DavixTaskQueue::getSize(){
DavixMutex mutex(tq_mutex);
return taskQueue.size();
}
bool DavixTaskQueue::isEmpty(){
DavixMutex mutex(tq_mutex);
return taskQueue.empty();
}
void DavixTaskQueue::shutdown(){
_shutdown = true;
pthread_cond_broadcast(&pushOpConvar);
pthread_cond_broadcast(&popOpConvar);
}
bool DavixTaskQueue::isStopped(){
return _shutdown;
}
}
|
Fix thread synchronization
|
Fix thread synchronization
|
C++
|
lgpl-2.1
|
cern-it-sdc-id/davix,cern-it-sdc-id/davix,cern-it-sdc-id/davix,cern-it-sdc-id/davix
|
6cef992c54fd4c05f3939f68e5eba97ee5f552c0
|
src/auth/Crypto.cc
|
src/auth/Crypto.cc
|
// 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.
*
*/
#include "Crypto.h"
#include <cryptopp/modes.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include "include/ceph_fs.h"
#include "common/config.h"
#include "common/debug.h"
#include "common/armor.h"
#include "common/Clock.h"
#include "common/hex.h"
#include "common/safe_io.h"
#include <errno.h>
using namespace CryptoPP;
int get_random_bytes(char *buf, int len)
{
int fd = TEMP_FAILURE_RETRY(::open("/dev/urandom", O_RDONLY));
if (fd < 0)
return -errno;
int ret = safe_read_exact(fd, buf, len);
if (ret)
return ret;
TEMP_FAILURE_RETRY(::close(fd));
return 0;
}
static int get_random_bytes(int len, bufferlist& bl)
{
char buf[len];
get_random_bytes(buf, len);
bl.append(buf, len);
return 0;
}
// ---------------------------------------------------
class CryptoNone : public CryptoHandler {
public:
CryptoNone() {}
~CryptoNone() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
int CryptoNone::create(bufferptr& secret)
{
return 0;
}
int CryptoNone::validate_secret(bufferptr& secret)
{
return 0;
}
int CryptoNone::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
int CryptoNone::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
// ---------------------------------------------------
#define AES_KEY_LEN ((size_t)AES::DEFAULT_KEYLENGTH)
#define AES_BLOCK_LEN ((size_t)AES::BLOCKSIZE)
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = (const unsigned char *)CEPH_AES_IV;
int CryptoAES::create(bufferptr& secret)
{
bufferlist bl;
int r = get_random_bytes(AES_KEY_LEN, bl);
if (r < 0)
return r;
secret = buffer::ptr(bl.c_str(), bl.length());
return 0;
}
int CryptoAES::validate_secret(bufferptr& secret)
{
if (secret.length() < (size_t)AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return -EINVAL;
}
return 0;
}
int CryptoAES::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
const unsigned char *in_buf;
if (secret.length() < AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return false;
}
string ciphertext;
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, aes_iv );
CryptoPP::StringSink *sink = new CryptoPP::StringSink(ciphertext);
if (!sink)
return false;
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, sink);
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
in_buf = (const unsigned char *)it->c_str();
stfEncryptor.Put(in_buf, it->length());
}
try {
stfEncryptor.MessageEnd();
} catch (CryptoPP::Exception& e) {
dout(0) << "encryptor.MessageEnd::Exception: " << e.GetWhat() << dendl;
return false;
}
out.append((const char *)ciphertext.c_str(), ciphertext.length());
return true;
}
int CryptoAES::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, aes_iv );
string decryptedtext;
CryptoPP::StringSink *sink = new CryptoPP::StringSink(decryptedtext);
if (!sink)
return -ENOMEM;
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, sink);
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
const unsigned char *in_buf = (const unsigned char *)it->c_str();
stfDecryptor.Put(in_buf, it->length());
}
try {
stfDecryptor.MessageEnd();
} catch (CryptoPP::Exception& e) {
dout(0) << "decryptor.MessageEnd::Exception: " << e.GetWhat() << dendl;
return -EINVAL;
}
out.append((const char *)decryptedtext.c_str(), decryptedtext.length());
return decryptedtext.length();
}
// ---------------------------------------------------
static CryptoNone crypto_none;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_NONE:
return &crypto_none;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
// ---------------------------------------------------
int CryptoKey::set_secret(int type, bufferptr& s)
{
this->type = type;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
int ret = h->validate_secret(s);
if (ret < 0)
return ret;
secret = s;
return 0;
}
int CryptoKey::create(int t)
{
type = t;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->create(secret);
}
int CryptoKey::encrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->encrypt(this->secret, in, out);
}
int CryptoKey::decrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->decrypt(this->secret, in, out);
}
void CryptoKey::print(ostream &out) const
{
string a;
encode_base64(a);
out << a;
}
void CryptoKey::to_str(string& s)
{
int len = secret.length() * 4;
char buf[len];
hex2str(secret.c_str(), secret.length(), buf, len);
s = buf;
}
|
// 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.
*
*/
#include "Crypto.h"
#include <cryptopp/modes.h>
#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include "include/ceph_fs.h"
#include "common/config.h"
#include "common/debug.h"
#include "common/armor.h"
#include "common/Clock.h"
#include "common/hex.h"
#include "common/safe_io.h"
#include <errno.h>
int get_random_bytes(char *buf, int len)
{
int fd = TEMP_FAILURE_RETRY(::open("/dev/urandom", O_RDONLY));
if (fd < 0)
return -errno;
int ret = safe_read_exact(fd, buf, len);
if (ret)
return ret;
TEMP_FAILURE_RETRY(::close(fd));
return 0;
}
static int get_random_bytes(int len, bufferlist& bl)
{
char buf[len];
get_random_bytes(buf, len);
bl.append(buf, len);
return 0;
}
// ---------------------------------------------------
class CryptoNone : public CryptoHandler {
public:
CryptoNone() {}
~CryptoNone() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
int CryptoNone::create(bufferptr& secret)
{
return 0;
}
int CryptoNone::validate_secret(bufferptr& secret)
{
return 0;
}
int CryptoNone::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
int CryptoNone::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
// ---------------------------------------------------
#define AES_KEY_LEN ((size_t)CryptoPP::AES::DEFAULT_KEYLENGTH)
#define AES_BLOCK_LEN ((size_t)CryptoPP::AES::BLOCKSIZE)
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = (const unsigned char *)CEPH_AES_IV;
int CryptoAES::create(bufferptr& secret)
{
bufferlist bl;
int r = get_random_bytes(AES_KEY_LEN, bl);
if (r < 0)
return r;
secret = buffer::ptr(bl.c_str(), bl.length());
return 0;
}
int CryptoAES::validate_secret(bufferptr& secret)
{
if (secret.length() < (size_t)AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return -EINVAL;
}
return 0;
}
int CryptoAES::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
const unsigned char *in_buf;
if (secret.length() < AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return false;
}
string ciphertext;
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, aes_iv );
CryptoPP::StringSink *sink = new CryptoPP::StringSink(ciphertext);
if (!sink)
return false;
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, sink);
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
in_buf = (const unsigned char *)it->c_str();
stfEncryptor.Put(in_buf, it->length());
}
try {
stfEncryptor.MessageEnd();
} catch (CryptoPP::Exception& e) {
dout(0) << "encryptor.MessageEnd::Exception: " << e.GetWhat() << dendl;
return false;
}
out.append((const char *)ciphertext.c_str(), ciphertext.length());
return true;
}
int CryptoAES::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, aes_iv );
string decryptedtext;
CryptoPP::StringSink *sink = new CryptoPP::StringSink(decryptedtext);
if (!sink)
return -ENOMEM;
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, sink);
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
const unsigned char *in_buf = (const unsigned char *)it->c_str();
stfDecryptor.Put(in_buf, it->length());
}
try {
stfDecryptor.MessageEnd();
} catch (CryptoPP::Exception& e) {
dout(0) << "decryptor.MessageEnd::Exception: " << e.GetWhat() << dendl;
return -EINVAL;
}
out.append((const char *)decryptedtext.c_str(), decryptedtext.length());
return decryptedtext.length();
}
// ---------------------------------------------------
static CryptoNone crypto_none;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_NONE:
return &crypto_none;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
// ---------------------------------------------------
int CryptoKey::set_secret(int type, bufferptr& s)
{
this->type = type;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
int ret = h->validate_secret(s);
if (ret < 0)
return ret;
secret = s;
return 0;
}
int CryptoKey::create(int t)
{
type = t;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->create(secret);
}
int CryptoKey::encrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->encrypt(this->secret, in, out);
}
int CryptoKey::decrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->decrypt(this->secret, in, out);
}
void CryptoKey::print(ostream &out) const
{
string a;
encode_base64(a);
out << a;
}
void CryptoKey::to_str(string& s)
{
int len = secret.length() * 4;
char buf[len];
hex2str(secret.c_str(), secret.length(), buf, len);
s = buf;
}
|
Drop "using namespace", it's almost always used explicitly anyway.
|
auth: Drop "using namespace", it's almost always used explicitly anyway.
This helps us be agnostic about what crypto library is in use.
Signed-off-by: Tommi Virtanen <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
b08814e8d26ca9670fed019a7f290814e47d56a7
|
src/transportserverasio_p.cpp
|
src/transportserverasio_p.cpp
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <qi/log.hpp>
#include <cerrno>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include "transportserver.hpp"
#include "transportsocket.hpp"
#include "tcptransportsocket.hpp"
#include <qi/eventloop.hpp>
#include "transportserverasio_p.hpp"
qiLogCategory("qimessaging.transportserver");
namespace qi
{
const int ifsMonitoringTimeout = 5 * 1000 * 1000; // in usec
void _onAccept(TransportServerImplPtr p,
const boost::system::error_code& erc,
#ifdef WITH_SSL
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s
#else
boost::asio::ip::tcp::socket* s
#endif
)
{
boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p);
ts->onAccept(erc, s);
}
void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc,
#ifdef WITH_SSL
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s
#else
boost::asio::ip::tcp::socket* s
#endif
)
{
qiLogDebug() << this << " onAccept";
if (!_live)
{
delete s;
return;
}
if (erc)
{
qiLogDebug() << "accept error " << erc.message();
delete s;
self->acceptError(erc.value());
return;
}
qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(context, _ssl, s));
self->newConnection(socket);
#ifdef WITH_SSL
_s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext);
#else
_s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service());
#endif
_acceptor.async_accept(_s->lowest_layer(),
boost::bind(_onAccept, shared_from_this(), _1, _s));
}
void TransportServerAsioPrivate::close() {
qiLogDebug() << this << " close";
try
{
_asyncEndpoints.cancel();
}
catch (const std::runtime_error& e)
{
qiLogDebug() << e.what();
}
_live = false;
_acceptor.close();
}
/*
* This asynchronous call will keep a shared ptr on the object to prevent
* its destruction.
*/
void _updateEndpoints(TransportServerImplPtr p)
{
boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p);
ts->updateEndpoints();
}
/*
* This function is used to detect and update endpoints when the transport
* server is listening on 0.0.0.0.
*/
void TransportServerAsioPrivate::updateEndpoints()
{
if (!_live)
{
return;
}
// TODO: implement OS networking notifications
qiLogDebug() << "Checking endpoints...";
std::vector<qi::Url> currentEndpoints;
std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs();
if (ifsMap.empty())
{
const char* s = "Cannot get host addresses";
qiLogWarning() << s;
}
std::string protocol = _ssl ? "tcps://" : "tcp://";
{
for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin();
interfaceIt != ifsMap.end();
++interfaceIt)
{
for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin();
addressIt != (*interfaceIt).second.end();
++addressIt)
{
std::stringstream ss;
ss << protocol << (*addressIt) << ":" << _port;
currentEndpoints.push_back(ss.str());
}
}
}
{
boost::mutex::scoped_lock(_endpointsMutex);
if (_endpoints.size() != currentEndpoints.size() ||
!std::equal(_endpoints.begin(), _endpoints.end(), currentEndpoints.begin()))
{
qiLogVerbose() << "Updating endpoints...";
_endpoints = currentEndpoints;
_self->endpointsChanged();
}
}
_asyncEndpoints = context->async(boost::bind(_updateEndpoints, shared_from_this()),
ifsMonitoringTimeout);
}
qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url)
{
qi::Url listenUrl = url;
_ssl = listenUrl.protocol() == "tcps";
using namespace boost::asio;
// resolve endpoint
ip::tcp::resolver r(_acceptor.get_io_service());
ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port()),
boost::asio::ip::tcp::resolver::query::all_matching);
ip::tcp::resolver::iterator it = r.resolve(q);
if (it == ip::tcp::resolver::iterator())
{
const char* s = "Listen error: no endpoint.";
qiLogError() << s;
return qi::makeFutureError<void>(s);
}
ip::tcp::endpoint ep = *it;
qiLogDebug() <<"Will listen on " << ep.address().to_string() << ' ' << ep.port();
_acceptor.open(ep.protocol());
#ifdef _WIN32
boost::asio::socket_base::reuse_address option(false);
#else
boost::asio::socket_base::reuse_address option(true);
fcntl(_acceptor.native(), F_SETFD, FD_CLOEXEC);
#endif
_acceptor.set_option(option);
_acceptor.bind(ep);
boost::system::error_code ec;
_acceptor.listen(socket_base::max_connections, ec);
if (ec)
{
qiLogError("qimessaging.server.listen") << ec.message();
return qi::makeFutureError<void>(ec.message());
}
_port = _acceptor.local_endpoint().port();// already in host byte orde
qiLogDebug() << "Effective port io_service" << _port;
if (listenUrl.port() == 0)
{
listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":"
+ boost::lexical_cast<std::string>(_port));
}
/* Set endpoints */
if (listenUrl.host() != "0.0.0.0")
{
boost::mutex::scoped_lock(_endpointsMutex);
_endpoints.push_back(listenUrl.str());
}
else
{
updateEndpoints();
}
{
boost::mutex::scoped_lock(_endpointsMutex);
for (std::vector<qi::Url>::const_iterator it = _endpoints.begin();
it != _endpoints.end();
it++)
{
qiLogInfo() << "TransportServer will listen on: " << it->str();
}
}
#ifdef WITH_SSL
if (_ssl)
{
if (self->_p->_identityCertificate.empty() || self->_p->_identityKey.empty())
{
const char* s = "SSL certificates missing, please call Session::setIdentity first";
qiLogError("qimessaging.server.listen") << s;
return qi::makeFutureError<void>(s);
}
_sslContext.set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2);
_sslContext.use_certificate_chain_file(self->_p->_identityCertificate.c_str());
_sslContext.use_private_key_file(self->_p->_identityKey.c_str(), boost::asio::ssl::context::pem);
}
_s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext);
#else
_s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service());
#endif
_acceptor.async_accept(_s->lowest_layer(),
boost::bind(_onAccept, shared_from_this(), _1, _s));
_connectionPromise.setValue(0);
return _connectionPromise.future();
}
TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self,
EventLoop* ctx)
: TransportServerImpl(self, ctx)
, _self(self)
, _acceptor(*(boost::asio::io_service*)ctx->nativeHandle())
, _live(true)
#ifdef WITH_SSL
, _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23)
#endif
, _ssl(false)
{
}
TransportServerAsioPrivate::~TransportServerAsioPrivate()
{
}
}
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <qi/log.hpp>
#include <cerrno>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include "transportserver.hpp"
#include "transportsocket.hpp"
#include "tcptransportsocket.hpp"
#include <qi/eventloop.hpp>
#include "transportserverasio_p.hpp"
qiLogCategory("qimessaging.transportserver");
namespace qi
{
const int ifsMonitoringTimeout = 5 * 1000 * 1000; // in usec
void _onAccept(TransportServerImplPtr p,
const boost::system::error_code& erc,
#ifdef WITH_SSL
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s
#else
boost::asio::ip::tcp::socket* s
#endif
)
{
boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p);
ts->onAccept(erc, s);
}
void TransportServerAsioPrivate::onAccept(const boost::system::error_code& erc,
#ifdef WITH_SSL
boost::asio::ssl::stream<boost::asio::ip::tcp::socket>* s
#else
boost::asio::ip::tcp::socket* s
#endif
)
{
qiLogDebug() << this << " onAccept";
if (!_live)
{
delete s;
return;
}
if (erc)
{
qiLogDebug() << "accept error " << erc.message();
delete s;
self->acceptError(erc.value());
return;
}
qi::TransportSocketPtr socket = qi::TcpTransportSocketPtr(new TcpTransportSocket(context, _ssl, s));
self->newConnection(socket);
#ifdef WITH_SSL
_s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext);
#else
_s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service());
#endif
_acceptor.async_accept(_s->lowest_layer(),
boost::bind(_onAccept, shared_from_this(), _1, _s));
}
void TransportServerAsioPrivate::close() {
qiLogDebug() << this << " close";
try
{
_asyncEndpoints.cancel();
}
catch (const std::runtime_error& e)
{
qiLogDebug() << e.what();
}
_live = false;
_acceptor.close();
}
/*
* This asynchronous call will keep a shared ptr on the object to prevent
* its destruction.
*/
void _updateEndpoints(TransportServerImplPtr p)
{
boost::shared_ptr<TransportServerAsioPrivate> ts = boost::dynamic_pointer_cast<TransportServerAsioPrivate>(p);
ts->updateEndpoints();
}
/*
* This function is used to detect and update endpoints when the transport
* server is listening on 0.0.0.0.
*/
void TransportServerAsioPrivate::updateEndpoints()
{
if (!_live)
{
return;
}
// TODO: implement OS networking notifications
qiLogDebug() << "Checking endpoints...";
std::vector<qi::Url> currentEndpoints;
std::map<std::string, std::vector<std::string> > ifsMap = qi::os::hostIPAddrs();
if (ifsMap.empty())
{
const char* s = "Cannot get host addresses";
qiLogWarning() << s;
}
std::string protocol = _ssl ? "tcps://" : "tcp://";
{
for (std::map<std::string, std::vector<std::string> >::iterator interfaceIt = ifsMap.begin();
interfaceIt != ifsMap.end();
++interfaceIt)
{
for (std::vector<std::string>::iterator addressIt = (*interfaceIt).second.begin();
addressIt != (*interfaceIt).second.end();
++addressIt)
{
std::stringstream ss;
ss << protocol << (*addressIt) << ":" << _port;
currentEndpoints.push_back(ss.str());
}
}
}
{
boost::mutex::scoped_lock(_endpointsMutex);
if (_endpoints.size() != currentEndpoints.size() ||
!std::equal(_endpoints.begin(), _endpoints.end(), currentEndpoints.begin()))
{
qiLogVerbose() << "Updating endpoints...";
_endpoints = currentEndpoints;
_self->endpointsChanged();
}
}
_asyncEndpoints = context->async(boost::bind(_updateEndpoints, shared_from_this()),
ifsMonitoringTimeout);
}
qi::Future<void> TransportServerAsioPrivate::listen(const qi::Url& url)
{
qi::Url listenUrl = url;
_ssl = listenUrl.protocol() == "tcps";
using namespace boost::asio;
// resolve endpoint
ip::tcp::resolver r(_acceptor.get_io_service());
ip::tcp::resolver::query q(listenUrl.host(), boost::lexical_cast<std::string>(listenUrl.port()),
boost::asio::ip::tcp::resolver::query::all_matching);
ip::tcp::resolver::iterator it = r.resolve(q);
if (it == ip::tcp::resolver::iterator())
{
const char* s = "Listen error: no endpoint.";
qiLogError() << s;
return qi::makeFutureError<void>(s);
}
ip::tcp::endpoint ep = *it;
qiLogDebug() <<"Will listen on " << ep.address().to_string() << ' ' << ep.port();
_acceptor.open(ep.protocol());
#ifdef _WIN32
boost::asio::socket_base::reuse_address option(false);
#else
boost::asio::socket_base::reuse_address option(true);
fcntl(_acceptor.native(), F_SETFD, FD_CLOEXEC);
#endif
_acceptor.set_option(option);
_acceptor.bind(ep);
boost::system::error_code ec;
_acceptor.listen(socket_base::max_connections, ec);
if (ec)
{
qiLogError("qimessaging.server.listen") << ec.message();
return qi::makeFutureError<void>(ec.message());
}
_port = _acceptor.local_endpoint().port();// already in host byte orde
qiLogDebug() << "Effective port io_service" << _port;
if (listenUrl.port() == 0)
{
listenUrl = Url(listenUrl.protocol() + "://" + listenUrl.host() + ":"
+ boost::lexical_cast<std::string>(_port));
}
/* Set endpoints */
if (listenUrl.host() != "0.0.0.0")
{
boost::mutex::scoped_lock(_endpointsMutex);
_endpoints.push_back(listenUrl.str());
}
else
{
updateEndpoints();
}
{
boost::mutex::scoped_lock(_endpointsMutex);
for (std::vector<qi::Url>::const_iterator it = _endpoints.begin();
it != _endpoints.end();
it++)
{
qiLogInfo() << "TransportServer will listen on: " << it->str();
}
}
#ifdef WITH_SSL
if (_ssl)
{
if (self->_identityCertificate.empty() || self->_identityKey.empty())
{
const char* s = "SSL certificates missing, please call Session::setIdentity first";
qiLogError("qimessaging.server.listen") << s;
return qi::makeFutureError<void>(s);
}
_sslContext.set_options(
boost::asio::ssl::context::default_workarounds
| boost::asio::ssl::context::no_sslv2);
_sslContext.use_certificate_chain_file(self->_identityCertificate.c_str());
_sslContext.use_private_key_file(self->_identityKey.c_str(), boost::asio::ssl::context::pem);
}
_s = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(_acceptor.get_io_service(), _sslContext);
#else
_s = new boost::asio::ip::tcp::socket(_acceptor.get_io_service());
#endif
_acceptor.async_accept(_s->lowest_layer(),
boost::bind(_onAccept, shared_from_this(), _1, _s));
_connectionPromise.setValue(0);
return _connectionPromise.future();
}
TransportServerAsioPrivate::TransportServerAsioPrivate(TransportServer* self,
EventLoop* ctx)
: TransportServerImpl(self, ctx)
, _self(self)
, _acceptor(*(boost::asio::io_service*)ctx->nativeHandle())
, _live(true)
#ifdef WITH_SSL
, _sslContext(*(boost::asio::io_service*)ctx->nativeHandle(), boost::asio::ssl::context::sslv23)
#endif
, _ssl(false)
{
}
TransportServerAsioPrivate::~TransportServerAsioPrivate()
{
}
}
|
Fix SSL compilation
|
Fix SSL compilation
Change-Id: Ic896e87332d2a0a5cb69b554c946fb8d21242b9c
Reviewed-on: http://gerrit.aldebaran.lan:8080/16244
Reviewed-by: llec <[email protected]>
Tested-by: llec <[email protected]>
|
C++
|
bsd-3-clause
|
aldebaran/libqi,aldebaran/libqi,aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi-java,aldebaran/libqi-java,bsautron/libqi,aldebaran/libqi-java
|
87bfd40fb79067c2070e30b43d2b12f47985e97b
|
chrome/browser/net/preconnect.cc
|
chrome/browser/net/preconnect.cc
|
// 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/preconnect.h"
#include "base/logging.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/http/http_network_session.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
namespace chrome_browser_net {
// We will deliberately leak this singular instance, which is used only for
// callbacks.
// static
Preconnect* Preconnect::callback_instance_;
// static
bool Preconnect::PreconnectOnUIThread(const GURL& url) {
// Try to do connection warming for this search provider.
URLRequestContextGetter* getter = Profile::GetDefaultRequestContext();
if (!getter)
return false;
// Prewarm connection to Search URL.
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableFunction(Preconnect::PreconnectOnIOThread, url));
return true;
}
// static
void Preconnect::PreconnectOnIOThread(const GURL& url) {
URLRequestContextGetter* getter = Profile::GetDefaultRequestContext();
if (!getter)
return;
if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
LOG(DFATAL) << "This must be run only on the IO thread.";
return;
}
URLRequestContext* context = getter->GetURLRequestContext();
net::HttpTransactionFactory* factory = context->http_transaction_factory();
net::HttpNetworkSession* session = factory->GetSession();
scoped_refptr<net::TCPClientSocketPool> pool = session->tcp_socket_pool();
net::TCPSocketParams params(url.host(), url.EffectiveIntPort(), net::LOW,
GURL(), false);
net::ClientSocketHandle handle;
if (!callback_instance_)
callback_instance_ = new Preconnect;
// TODO(jar): This does not handle proxies currently.
handle.Init(url.spec(), params, net::LOWEST,
callback_instance_, pool, net::BoundNetLog());
handle.Reset();
}
void Preconnect::RunWithParams(const Tuple1<int>& params) {
// This will rarely be called, as we reset the connection just after creating.
NOTREACHED();
}
} // chrome_browser_net
|
// 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/preconnect.h"
#include "base/logging.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/base/host_port_pair.h"
#include "net/http/http_network_session.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
namespace chrome_browser_net {
// We will deliberately leak this singular instance, which is used only for
// callbacks.
// static
Preconnect* Preconnect::callback_instance_;
// static
bool Preconnect::PreconnectOnUIThread(const GURL& url) {
// Try to do connection warming for this search provider.
URLRequestContextGetter* getter = Profile::GetDefaultRequestContext();
if (!getter)
return false;
// Prewarm connection to Search URL.
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableFunction(Preconnect::PreconnectOnIOThread, url));
return true;
}
// static
void Preconnect::PreconnectOnIOThread(const GURL& url) {
URLRequestContextGetter* getter = Profile::GetDefaultRequestContext();
if (!getter)
return;
if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) {
LOG(DFATAL) << "This must be run only on the IO thread.";
return;
}
URLRequestContext* context = getter->GetURLRequestContext();
net::HttpTransactionFactory* factory = context->http_transaction_factory();
net::HttpNetworkSession* session = factory->GetSession();
scoped_refptr<net::TCPClientSocketPool> pool = session->tcp_socket_pool();
net::TCPSocketParams params(url.host(), url.EffectiveIntPort(), net::LOW,
GURL(), false);
net::ClientSocketHandle handle;
if (!callback_instance_)
callback_instance_ = new Preconnect;
net::HostPortPair endpoint(url.host(), url.EffectiveIntPort());
std::string group_name = endpoint.ToString();
if (url.SchemeIs("https"))
group_name = StringPrintf("ssl/%s", group_name.c_str());
// TODO(jar): This does not handle proxies currently.
handle.Init(group_name, params, net::LOWEST,
callback_instance_, pool, net::BoundNetLog());
handle.Reset();
}
void Preconnect::RunWithParams(const Tuple1<int>& params) {
// This will rarely be called, as we reset the connection just after creating.
NOTREACHED();
}
} // chrome_browser_net
|
Fix the construction of the pool names for preconnect.
|
Fix the construction of the pool names for preconnect.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2842033
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@51163 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
ae9856b1dc7808dbd266def84a889644b5d049ca
|
chrome_frame/test/http_server.cc
|
chrome_frame/test/http_server.cc
|
// 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_frame/test/http_server.h"
#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
const wchar_t kDocRoot[] = L"chrome_frame\\test\\data";
ChromeFrameHTTPServer::ChromeFrameHTTPServer()
: test_server_(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)) {
}
void ChromeFrameHTTPServer::SetUp() {
ASSERT_TRUE(test_server_.Start());
// copy CFInstance.js into the test directory
FilePath cf_source_path;
PathService::Get(base::DIR_SOURCE_ROOT, &cf_source_path);
cf_source_path = cf_source_path.Append(FILE_PATH_LITERAL("chrome_frame"));
file_util::CopyFile(cf_source_path.Append(FILE_PATH_LITERAL("CFInstance.js")),
cf_source_path.Append(
FILE_PATH_LITERAL("test")).Append(
FILE_PATH_LITERAL("data")).Append(
FILE_PATH_LITERAL("CFInstance.js"))); // NOLINT
file_util::CopyFile(cf_source_path.Append(FILE_PATH_LITERAL("CFInstall.js")),
cf_source_path.Append(
FILE_PATH_LITERAL("test")).Append(
FILE_PATH_LITERAL("data")).Append(
FILE_PATH_LITERAL("CFInstall.js"))); // NOLINT
}
void ChromeFrameHTTPServer::TearDown() {
test_server_.Stop();
// clobber CFInstance.js
FilePath cfi_path;
PathService::Get(base::DIR_SOURCE_ROOT, &cfi_path);
cfi_path = cfi_path
.Append(FILE_PATH_LITERAL("chrome_frame"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("CFInstance.js"));
file_util::Delete(cfi_path, false);
cfi_path.empty();
PathService::Get(base::DIR_SOURCE_ROOT, &cfi_path);
cfi_path = cfi_path
.Append(FILE_PATH_LITERAL("chrome_frame"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("CFInstall.js"));
file_util::Delete(cfi_path, false);
}
bool ChromeFrameHTTPServer::WaitToFinish(int milliseconds) {
bool ret = test_server_.WaitToFinish(milliseconds);
if (!ret) {
LOG(ERROR) << "WaitToFinish failed with error:" << ::GetLastError();
} else {
ret = test_server_.Stop();
}
return ret;
}
// TODO(phajdan.jr): Change wchar_t* to std::string& and fix callers.
GURL ChromeFrameHTTPServer::Resolve(const wchar_t* relative_url) {
return test_server_.GetURL(WideToUTF8(relative_url));
}
FilePath ChromeFrameHTTPServer::GetDataDir() {
return test_server_.document_root();
}
|
// 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_frame/test/http_server.h"
#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
const wchar_t kDocRoot[] = L"chrome_frame\\test\\data";
ChromeFrameHTTPServer::ChromeFrameHTTPServer()
: test_server_(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)) {
}
void ChromeFrameHTTPServer::SetUp() {
ASSERT_TRUE(test_server_.Start());
// copy CFInstance.js into the test directory
FilePath cf_source_path;
PathService::Get(base::DIR_SOURCE_ROOT, &cf_source_path);
cf_source_path = cf_source_path.Append(FILE_PATH_LITERAL("chrome_frame"));
file_util::CopyFile(cf_source_path.Append(FILE_PATH_LITERAL("CFInstance.js")),
cf_source_path.Append(
FILE_PATH_LITERAL("test")).Append(
FILE_PATH_LITERAL("data")).Append(
FILE_PATH_LITERAL("CFInstance.js"))); // NOLINT
file_util::CopyFile(cf_source_path.Append(FILE_PATH_LITERAL("CFInstall.js")),
cf_source_path.Append(
FILE_PATH_LITERAL("test")).Append(
FILE_PATH_LITERAL("data")).Append(
FILE_PATH_LITERAL("CFInstall.js"))); // NOLINT
}
void ChromeFrameHTTPServer::TearDown() {
test_server_.Stop();
// clobber CFInstance.js
FilePath cfi_path;
PathService::Get(base::DIR_SOURCE_ROOT, &cfi_path);
cfi_path = cfi_path
.Append(FILE_PATH_LITERAL("chrome_frame"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("CFInstance.js"));
file_util::Delete(cfi_path, false);
cfi_path.empty();
PathService::Get(base::DIR_SOURCE_ROOT, &cfi_path);
cfi_path = cfi_path
.Append(FILE_PATH_LITERAL("chrome_frame"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("CFInstall.js"));
file_util::Delete(cfi_path, false);
}
bool ChromeFrameHTTPServer::WaitToFinish(int milliseconds) {
bool ret = test_server_.WaitToFinish(milliseconds);
if (!ret) {
LOG(ERROR) << "WaitToFinish failed with error:" << ::GetLastError();
ret = test_server_.Stop();
}
return ret;
}
// TODO(phajdan.jr): Change wchar_t* to std::string& and fix callers.
GURL ChromeFrameHTTPServer::Resolve(const wchar_t* relative_url) {
return test_server_.GetURL(WideToUTF8(relative_url));
}
FilePath ChromeFrameHTTPServer::GetDataDir() {
return test_server_.document_root();
}
|
Fix a dumb error introduced earlier. We need to call Stop only when the wait on the python server returns an error
|
Fix a dumb error introduced earlier. We need to call Stop only when the wait on the python server
returns an error
TBR=amit
Review URL: http://codereview.chromium.org/3162028
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@56901 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,robclark/chromium,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,rogerwang/chromium,Just-D/chromium-1,M4sse/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,patrickm/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,Just-D/chromium-1,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,ltilve/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,keishi/chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,rogerwang/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,robclark/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,patrickm/chromium.src,Just-D/chromium-1,jaruba/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,keishi/chromium,robclark/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,zcbenz/cefode-chromium,keishi/chromium,ltilve/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,Chilledheart/chromium,patrickm/chromium.src,Chilledheart/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,rogerwang/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,rogerwang/chromium,keishi/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,Jonekee/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,dushu1203/chromium.src,axinging/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,patrickm/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,markYoungH/chromium.src,jaruba/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,ltilve/chromium,zcbenz/cefode-chromium,M4sse/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,robclark/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,anirudhSK/chromium,keishi/chromium,hujiajie/pa-chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,robclark/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,ltilve/chromium,Just-D/chromium-1,Jonekee/chromium.src,ChromiumWebApps/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk
|
fe8ffb63005accbbe9b86c2bf673bce7f73efd84
|
tensorflow/cc/gradients/resource_variable_grad_test.cc
|
tensorflow/cc/gradients/resource_variable_grad_test.cc
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/gradient_checker.h"
#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/gradients/grad_testutil.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace ops {
namespace {
TEST(ResourceVariableGradTest, ReadVariableOpGrad) {
TensorShape shape({});
auto scope_ = Scope::NewRootScope();
auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
auto var = VarHandleOp(scope_, DT_FLOAT, shape);
auto init = AssignVariableOp(scope_, var, Const(scope_, (float) 2, shape));
auto temp = ReadVariableOp(scope_, var, DT_FLOAT);
auto y = Mul(scope_, temp, x);
auto dy = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
OutputList dxs;
TF_ASSERT_OK(AddSymbolicGradients(scope_, {y}, {var}, {dy}, &dxs));
ClientSession::FeedType feed_list;
feed_list.insert({x, (float) 5});
feed_list.insert({dy, (float) 1});
std::vector<Tensor> dxout;
ClientSession session(scope_);
TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));
auto grad = dxout[0].scalar<float>()();
EXPECT_EQ(grad, 5);
}
} // namespace
} // namespace ops
} // namespace tensorflow
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/gradient_checker.h"
#include "tensorflow/cc/framework/gradients.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/gradients/grad_testutil.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace ops {
namespace {
TEST(ResourceVariableGradTest, ReadVariableOpGrad) {
TensorShape shape({});
auto scope = Scope::NewRootScope();
auto x = Placeholder(scope, DT_FLOAT, Placeholder::Shape(shape));
auto var = VarHandleOp(scope, DT_FLOAT, shape);
auto init = AssignVariableOp(scope, var, Const(scope, (float) 2, shape));
auto temp = ReadVariableOp(scope, var, DT_FLOAT);
auto y = Mul(scope, temp, x);
auto dy = Placeholder(scope, DT_FLOAT, Placeholder::Shape(shape));
OutputList dxs;
TF_ASSERT_OK(AddSymbolicGradients(scope, {y}, {var}, {dy}, &dxs));
ClientSession::FeedType feed_list;
feed_list.insert({x, (float) 5});
feed_list.insert({dy, (float) 1});
std::vector<Tensor> dxout;
ClientSession session(scope);
TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));
auto grad = dxout[0].scalar<float>()();
EXPECT_EQ(grad, 5);
}
} // namespace
} // namespace ops
} // namespace tensorflow
|
Rename scope_
|
Rename scope_
|
C++
|
apache-2.0
|
gautam1858/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,yongtang/tensorflow,yongtang/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,karllessard/tensorflow,yongtang/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,yongtang/tensorflow
|
b055b9c474cd376259dde8779908f9eeaf097d93
|
tensorflow/core/kernels/ragged_tensor_to_variant_op.cc
|
tensorflow/core/kernels/ragged_tensor_to_variant_op.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <utility>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_encode_decode.h"
#include "tensorflow/core/framework/variant_op_registry.h"
#include "tensorflow/core/kernels/concat_lib.h"
#include "tensorflow/core/kernels/ragged_tensor_variant.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/util/tensor_ops_util.h"
namespace tensorflow {
namespace {
template <typename VALUE_TYPE, typename SPLIT_TYPE>
Status UnbatchRaggedZerothDim(
const RaggedTensorVariant& batched_ragged,
std::vector<RaggedTensorVariant>* ragged_components) {
// Set up the component Ragged Tensors.
int ragged_rank = batched_ragged.ragged_rank();
auto batched_splits_top_vec = batched_ragged.splits(0).vec<SPLIT_TYPE>();
int num_components = batched_splits_top_vec.size() - 1;
int num_splits = ragged_rank - 1;
ragged_components->resize(num_components);
for (RaggedTensorVariant& ragged_component : *ragged_components) {
ragged_component.mutable_nested_splits()->reserve(num_splits);
}
const auto& batched_flat = batched_ragged.values().flat<VALUE_TYPE>();
int num_inner_elems = batched_ragged.values().NumElements();
if (batched_ragged.values().dim_size(0) > 1) {
num_inner_elems /= batched_ragged.values().dim_size(0);
}
TensorShape values_shape = batched_ragged.values().shape();
// Corner case: ragged_rank == 1, e.g. [[1, 2, 3], [4, 5]]
if (num_splits == 0) {
for (int i = 0; i < num_components; i++) {
int start = batched_splits_top_vec(i);
int limit = batched_splits_top_vec(i + 1);
int num_values = limit - start;
values_shape.set_dim(0, num_values);
(*ragged_components)[i].set_values(
Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));
auto ragged_component_values_flat =
(*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();
for (int j = 0; j < num_values * num_inner_elems; j++) {
ragged_component_values_flat(j) =
batched_flat(j + start * num_inner_elems);
}
}
return Status::OK();
}
// Unbatch nested splits.
std::vector<typename TTypes<SPLIT_TYPE>::ConstVec> batched_splits_vec;
batched_splits_vec.reserve(ragged_rank);
for (int i = 0; i < ragged_rank; i++) {
batched_splits_vec.push_back(batched_ragged.splits(i).vec<SPLIT_TYPE>());
}
std::vector<int> index(num_splits, 1);
std::vector<int> ragged_component_values_size(num_components, 0);
for (int i = 0; i < num_components; i++) {
std::vector<typename TTypes<SPLIT_TYPE>::Vec> ragged_component_splits_vec;
ragged_component_splits_vec.reserve(num_splits);
int split_size = -1;
for (int j = 0; j < num_splits; j++) {
if (j == 0) {
split_size =
batched_splits_top_vec(i + 1) - batched_splits_top_vec(i) + 1;
} else {
// Update split size based on previous split.
int last_index = ragged_component_splits_vec[j - 1].size() - 1;
split_size = ragged_component_splits_vec[j - 1](last_index) + 1;
}
(*ragged_components)[i].append_splits(
Tensor(DataTypeToEnum<SPLIT_TYPE>::value, TensorShape({split_size})));
ragged_component_splits_vec.push_back(
(*ragged_components)[i].mutable_splits(j)->vec<SPLIT_TYPE>());
SPLIT_TYPE last_split_value = batched_splits_vec[j + 1](index[j] - 1);
ragged_component_splits_vec[j](0) = 0;
for (int k = 1; k < split_size; k++, index[j]++) {
ragged_component_splits_vec[j](k) =
batched_splits_vec[j + 1](index[j]) - last_split_value;
}
}
int last_split_size = ragged_component_splits_vec[num_splits - 1].size();
ragged_component_values_size[i] =
ragged_component_splits_vec[num_splits - 1](last_split_size - 1);
}
// Unbatch values.
int value_index = 0;
for (int i = 0; i < num_components; i++) {
int num_values = ragged_component_values_size[i];
values_shape.set_dim(0, num_values);
(*ragged_components)[i].set_values(
Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));
auto ragged_component_values_flat =
(*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();
for (int j = 0; j < num_values * num_inner_elems; j++, value_index++) {
ragged_component_values_flat(j) = batched_flat(value_index);
}
}
return Status::OK();
}
} // namespace
template <typename VALUE_TYPE, typename SPLIT_TYPE>
class RaggedTensorToVariantOp : public OpKernel {
public:
explicit RaggedTensorToVariantOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("batched_input", &batched_input_));
}
void Compute(OpKernelContext* context) override {
// Read ragged_splits inputs.
OpInputList ragged_nested_splits_in;
OP_REQUIRES_OK(context, context->input_list("rt_nested_splits",
&ragged_nested_splits_in));
const int ragged_nested_splits_len = ragged_nested_splits_in.size();
RaggedTensorVariant batched_ragged_input;
// Read ragged_values input.
batched_ragged_input.set_values(context->input(ragged_nested_splits_len));
batched_ragged_input.mutable_nested_splits()->reserve(
ragged_nested_splits_len);
for (int i = 0; i < ragged_nested_splits_len; i++) {
batched_ragged_input.append_splits(ragged_nested_splits_in[i]);
}
if (!batched_input_) {
// Encode as a Scalar Variant Tensor.
Tensor* encoded_scalar;
OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),
&encoded_scalar));
encoded_scalar->scalar<Variant>()() = std::move(batched_ragged_input);
return;
}
// Unbatch the Ragged Tensor and encode the components.
std::vector<RaggedTensorVariant> unbatched_ragged_input;
OP_REQUIRES_OK(context, UnbatchRaggedZerothDim<VALUE_TYPE, SPLIT_TYPE>(
batched_ragged_input, &unbatched_ragged_input));
// Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.
Tensor* encoded_vector;
int output_size = unbatched_ragged_input.size();
OP_REQUIRES_OK(context,
context->allocate_output(0, TensorShape({output_size}),
&encoded_vector));
auto encoded_vector_t = encoded_vector->vec<Variant>();
for (int i = 0; i < output_size; i++) {
encoded_vector_t(i) = unbatched_ragged_input[i];
}
}
private:
bool batched_input_;
};
template <typename VALUE_TYPE, typename SPLIT_TYPE>
class RaggedTensorToVariantGradientOp : public OpKernel {
public:
using OpKernel::OpKernel;
void Compute(OpKernelContext* context) override {
// Read inputs.
Tensor encoded_variant = context->input(0);
Tensor row_splits = context->input(1);
auto flat_row_splits = row_splits.flat<SPLIT_TYPE>();
TensorShape dense_values_shape;
OP_REQUIRES_OK(context,
TensorShapeUtils::MakeShape(context->input(2).vec<int32>(),
&dense_values_shape));
const auto& flat_variants = encoded_variant.flat<Variant>();
// Get a Tensor containing the flat_values for each variant.
std::vector<Tensor> values;
for (int i = 0; i < flat_variants.size(); ++i) {
if (const auto* encoded = flat_variants(i).get<RaggedTensorVariant>()) {
values.push_back(encoded->values());
} else {
// Missing value: this happens if only some of the variant values
// generated by ragged_tensor_to_variant impacted the value that we're
// calculating the gradient for. In this case, we will see a
// default-constructed variant; so treat it as a zero tensor with the
// appropriate shape.
const auto value_dtype = DataTypeToEnum<VALUE_TYPE>::v();
int piece_size = flat_row_splits(i + 1) - flat_row_splits(i);
TensorShape zeros_shape = dense_values_shape;
zeros_shape.set_dim(0, piece_size);
Tensor zero(value_dtype, zeros_shape);
zero.flat<VALUE_TYPE>() =
zero.flat<VALUE_TYPE>().constant(VALUE_TYPE());
values.push_back(zero);
}
}
if (values.size() == 1) {
// Just one flat_value tensor: return as-is.
context->set_output(0, values[0]);
} else {
// Multiple flat_values tensors: concatenate them together.
using Piece = typename TTypes<VALUE_TYPE, 2>::Matrix;
using ConstPiece = typename TTypes<VALUE_TYPE, 2>::ConstMatrix;
std::vector<std::unique_ptr<ConstPiece>> pieces;
pieces.reserve(values.size());
for (const Tensor& t : values) {
pieces.emplace_back(
new ConstPiece(t.shaped<VALUE_TYPE, 2>({1, t.NumElements()})));
}
Tensor* out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, dense_values_shape, &out));
Piece out_flat =
out->shaped<VALUE_TYPE, 2>({1, dense_values_shape.num_elements()});
ConcatCPU<VALUE_TYPE>(context->device(), pieces, &out_flat);
}
}
};
#define REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, split_type) \
REGISTER_KERNEL_BUILDER(Name("RaggedTensorToVariant") \
.Device(DEVICE_CPU) \
.TypeConstraint<value_type>("Tvalues") \
.TypeConstraint<split_type>("Tsplits"), \
RaggedTensorToVariantOp<value_type, split_type>); \
REGISTER_KERNEL_BUILDER( \
Name("RaggedTensorToVariantGradient") \
.Device(DEVICE_CPU) \
.TypeConstraint<value_type>("Tvalues") \
.TypeConstraint<split_type>("Tsplits"), \
RaggedTensorToVariantGradientOp<value_type, split_type>);
#define REGISTER_KERNELS(value_type) \
REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int32) \
REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int64)
TF_CALL_POD_TYPES(REGISTER_KERNELS);
TF_CALL_tstring(REGISTER_KERNELS);
TF_CALL_QUANTIZED_TYPES(REGISTER_KERNELS);
TF_CALL_quint16(REGISTER_KERNELS);
TF_CALL_qint16(REGISTER_KERNELS);
#undef REGISTER_KERNELS
#undef REGISTER_KERNELS_WITH_SPLIT_TYPE
} // namespace tensorflow
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <utility>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_encode_decode.h"
#include "tensorflow/core/framework/variant_op_registry.h"
#include "tensorflow/core/kernels/concat_lib.h"
#include "tensorflow/core/kernels/ragged_tensor_variant.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/util/tensor_ops_util.h"
namespace tensorflow {
namespace {
template <typename VALUE_TYPE, typename SPLIT_TYPE>
Status UnbatchRaggedZerothDim(
const RaggedTensorVariant& batched_ragged,
std::vector<RaggedTensorVariant>* ragged_components) {
// Set up the component Ragged Tensors.
int ragged_rank = batched_ragged.ragged_rank();
auto batched_splits_top_vec = batched_ragged.splits(0).vec<SPLIT_TYPE>();
int num_components = batched_splits_top_vec.size() - 1;
int num_splits = ragged_rank - 1;
ragged_components->resize(num_components);
for (RaggedTensorVariant& ragged_component : *ragged_components) {
ragged_component.mutable_nested_splits()->reserve(num_splits);
}
const auto& batched_flat = batched_ragged.values().flat<VALUE_TYPE>();
int num_inner_elems = batched_ragged.values().NumElements();
if (batched_ragged.values().dim_size(0) > 1) {
num_inner_elems /= batched_ragged.values().dim_size(0);
}
TensorShape values_shape = batched_ragged.values().shape();
// Corner case: ragged_rank == 1, e.g. [[1, 2, 3], [4, 5]]
if (num_splits == 0) {
for (int i = 0; i < num_components; i++) {
int start = batched_splits_top_vec(i);
int limit = batched_splits_top_vec(i + 1);
int num_values = limit - start;
values_shape.set_dim(0, num_values);
(*ragged_components)[i].set_values(
Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));
auto ragged_component_values_flat =
(*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();
for (int j = 0; j < num_values * num_inner_elems; j++) {
ragged_component_values_flat(j) =
batched_flat(j + start * num_inner_elems);
}
}
return Status::OK();
}
// Unbatch nested splits.
std::vector<typename TTypes<SPLIT_TYPE>::ConstVec> batched_splits_vec;
batched_splits_vec.reserve(ragged_rank);
for (int i = 0; i < ragged_rank; i++) {
batched_splits_vec.push_back(batched_ragged.splits(i).vec<SPLIT_TYPE>());
}
std::vector<int> index(num_splits, 1);
std::vector<int> ragged_component_values_size(num_components, 0);
for (int i = 0; i < num_components; i++) {
std::vector<typename TTypes<SPLIT_TYPE>::Vec> ragged_component_splits_vec;
ragged_component_splits_vec.reserve(num_splits);
int split_size = -1;
for (int j = 0; j < num_splits; j++) {
if (j == 0) {
split_size =
batched_splits_top_vec(i + 1) - batched_splits_top_vec(i) + 1;
} else {
// Update split size based on previous split.
int last_index = ragged_component_splits_vec[j - 1].size() - 1;
split_size = ragged_component_splits_vec[j - 1](last_index) + 1;
}
(*ragged_components)[i].append_splits(
Tensor(DataTypeToEnum<SPLIT_TYPE>::value, TensorShape({split_size})));
ragged_component_splits_vec.push_back(
(*ragged_components)[i].mutable_splits(j)->vec<SPLIT_TYPE>());
SPLIT_TYPE last_split_value = batched_splits_vec[j + 1](index[j] - 1);
ragged_component_splits_vec[j](0) = 0;
for (int k = 1; k < split_size; k++, index[j]++) {
ragged_component_splits_vec[j](k) =
batched_splits_vec[j + 1](index[j]) - last_split_value;
}
}
int last_split_size = ragged_component_splits_vec[num_splits - 1].size();
ragged_component_values_size[i] =
ragged_component_splits_vec[num_splits - 1](last_split_size - 1);
}
// Unbatch values.
int value_index = 0;
for (int i = 0; i < num_components; i++) {
int num_values = ragged_component_values_size[i];
values_shape.set_dim(0, num_values);
(*ragged_components)[i].set_values(
Tensor(DataTypeToEnum<VALUE_TYPE>::value, values_shape));
auto ragged_component_values_flat =
(*ragged_components)[i].mutable_values()->flat<VALUE_TYPE>();
for (int j = 0; j < num_values * num_inner_elems; j++, value_index++) {
ragged_component_values_flat(j) = batched_flat(value_index);
}
}
return Status::OK();
}
} // namespace
template <typename VALUE_TYPE, typename SPLIT_TYPE>
class RaggedTensorToVariantOp : public OpKernel {
public:
explicit RaggedTensorToVariantOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("batched_input", &batched_input_));
}
void Compute(OpKernelContext* context) override {
// Read ragged_splits inputs.
OpInputList ragged_nested_splits_in;
OP_REQUIRES_OK(context, context->input_list("rt_nested_splits",
&ragged_nested_splits_in));
const int ragged_nested_splits_len = ragged_nested_splits_in.size();
RaggedTensorVariant batched_ragged_input;
// Read ragged_values input.
batched_ragged_input.set_values(context->input(ragged_nested_splits_len));
batched_ragged_input.mutable_nested_splits()->reserve(
ragged_nested_splits_len);
for (int i = 0; i < ragged_nested_splits_len; i++) {
batched_ragged_input.append_splits(ragged_nested_splits_in[i]);
}
if (!batched_input_) {
// Encode as a Scalar Variant Tensor.
Tensor* encoded_scalar;
OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),
&encoded_scalar));
encoded_scalar->scalar<Variant>()() = std::move(batched_ragged_input);
return;
}
// Unbatch the Ragged Tensor and encode the components.
std::vector<RaggedTensorVariant> unbatched_ragged_input;
auto batched_splits_top_vec =
batched_ragged_input.splits(0).vec<SPLIT_TYPE>();
int num_components = batched_splits_top_vec.size() - 1;
OP_REQUIRES(context, num_components >= 0,
errors::Internal("Invalid split argument."));
OP_REQUIRES_OK(context, UnbatchRaggedZerothDim<VALUE_TYPE, SPLIT_TYPE>(
batched_ragged_input, &unbatched_ragged_input));
// Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.
Tensor* encoded_vector;
int output_size = unbatched_ragged_input.size();
OP_REQUIRES_OK(context,
context->allocate_output(0, TensorShape({output_size}),
&encoded_vector));
auto encoded_vector_t = encoded_vector->vec<Variant>();
for (int i = 0; i < output_size; i++) {
encoded_vector_t(i) = unbatched_ragged_input[i];
}
}
private:
bool batched_input_;
};
template <typename VALUE_TYPE, typename SPLIT_TYPE>
class RaggedTensorToVariantGradientOp : public OpKernel {
public:
using OpKernel::OpKernel;
void Compute(OpKernelContext* context) override {
// Read inputs.
Tensor encoded_variant = context->input(0);
Tensor row_splits = context->input(1);
auto flat_row_splits = row_splits.flat<SPLIT_TYPE>();
TensorShape dense_values_shape;
OP_REQUIRES_OK(context,
TensorShapeUtils::MakeShape(context->input(2).vec<int32>(),
&dense_values_shape));
const auto& flat_variants = encoded_variant.flat<Variant>();
// Get a Tensor containing the flat_values for each variant.
std::vector<Tensor> values;
for (int i = 0; i < flat_variants.size(); ++i) {
if (const auto* encoded = flat_variants(i).get<RaggedTensorVariant>()) {
values.push_back(encoded->values());
} else {
// Missing value: this happens if only some of the variant values
// generated by ragged_tensor_to_variant impacted the value that we're
// calculating the gradient for. In this case, we will see a
// default-constructed variant; so treat it as a zero tensor with the
// appropriate shape.
const auto value_dtype = DataTypeToEnum<VALUE_TYPE>::v();
int piece_size = flat_row_splits(i + 1) - flat_row_splits(i);
TensorShape zeros_shape = dense_values_shape;
zeros_shape.set_dim(0, piece_size);
Tensor zero(value_dtype, zeros_shape);
zero.flat<VALUE_TYPE>() =
zero.flat<VALUE_TYPE>().constant(VALUE_TYPE());
values.push_back(zero);
}
}
if (values.size() == 1) {
// Just one flat_value tensor: return as-is.
context->set_output(0, values[0]);
} else {
// Multiple flat_values tensors: concatenate them together.
using Piece = typename TTypes<VALUE_TYPE, 2>::Matrix;
using ConstPiece = typename TTypes<VALUE_TYPE, 2>::ConstMatrix;
std::vector<std::unique_ptr<ConstPiece>> pieces;
pieces.reserve(values.size());
for (const Tensor& t : values) {
pieces.emplace_back(
new ConstPiece(t.shaped<VALUE_TYPE, 2>({1, t.NumElements()})));
}
Tensor* out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, dense_values_shape, &out));
Piece out_flat =
out->shaped<VALUE_TYPE, 2>({1, dense_values_shape.num_elements()});
ConcatCPU<VALUE_TYPE>(context->device(), pieces, &out_flat);
}
}
};
#define REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, split_type) \
REGISTER_KERNEL_BUILDER(Name("RaggedTensorToVariant") \
.Device(DEVICE_CPU) \
.TypeConstraint<value_type>("Tvalues") \
.TypeConstraint<split_type>("Tsplits"), \
RaggedTensorToVariantOp<value_type, split_type>); \
REGISTER_KERNEL_BUILDER( \
Name("RaggedTensorToVariantGradient") \
.Device(DEVICE_CPU) \
.TypeConstraint<value_type>("Tvalues") \
.TypeConstraint<split_type>("Tsplits"), \
RaggedTensorToVariantGradientOp<value_type, split_type>);
#define REGISTER_KERNELS(value_type) \
REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int32) \
REGISTER_KERNELS_WITH_SPLIT_TYPE(value_type, int64)
TF_CALL_POD_TYPES(REGISTER_KERNELS);
TF_CALL_tstring(REGISTER_KERNELS);
TF_CALL_QUANTIZED_TYPES(REGISTER_KERNELS);
TF_CALL_quint16(REGISTER_KERNELS);
TF_CALL_qint16(REGISTER_KERNELS);
#undef REGISTER_KERNELS
#undef REGISTER_KERNELS_WITH_SPLIT_TYPE
} // namespace tensorflow
|
Fix `tf.raw_ops.RaggedTensorToVariant` invalid resize.
|
Fix `tf.raw_ops.RaggedTensorToVariant` invalid resize.
PiperOrigin-RevId: 368299574
Change-Id: I751c186325aa0bab397928845e790e60c2d90918
|
C++
|
apache-2.0
|
frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,karllessard/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,frreiss/tensorflow-fred,gautam1858/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,karllessard/tensorflow,sarvex/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,sarvex/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow
|
b05909987cda772230915def4fa389dc8ef495da
|
trunk/extension/sample/report/appl.cpp
|
trunk/extension/sample/report/appl.cpp
|
/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxExRep
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/stdpaths.h> // for wxStandardPaths
#include "appl.h"
#ifndef __WXMSW__
#include "appl.xpm"
#endif
enum
{
ID_PROCESS_DIALOG,
ID_PROCESS_RUN,
ID_RECENTFILE_MENU,
};
BEGIN_EVENT_TABLE(wxExRepSampleFrame, wxExFrameWithHistory)
EVT_MENU(wxID_STOP, wxExRepSampleFrame::OnCommand)
EVT_MENU(ID_PROCESS_DIALOG, wxExRepSampleFrame::OnCommand)
EVT_MENU(ID_PROCESS_RUN, wxExRepSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, wxExRepSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, wxExRepSampleFrame::OnCommand)
EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExRepSampleFrame::OnTree)
END_EVENT_TABLE()
IMPLEMENT_APP(wxExRepSampleApp)
bool wxExRepSampleApp::OnInit()
{
SetAppName("wxExRepSample");
if (!wxExApp::OnInit())
{
return false;
}
SetLogging();
wxExRepSampleFrame *frame = new wxExRepSampleFrame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
wxExRepSampleFrame::wxExRepSampleFrame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
{
SetIcon(wxICON(appl));
wxExMenu *menuFile = new wxExMenu;
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu *menuProcess = new wxExMenu;
menuProcess->Append(ID_PROCESS_DIALOG, wxExEllipsed(_("Dialog")));
menuProcess->Append(ID_PROCESS_RUN, _("Run"));
menuProcess->AppendSeparator();
menuProcess->Append(wxID_STOP);
wxExMenu* menuHelp = new wxExMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->Realize();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50));
panes.push_back(wxExPane("PaneLines", 100));
panes.push_back(wxExPane("PaneLexer", 60));
panes.push_back(wxExPane("PaneItems", 60));
SetupStatusBar(panes);
#endif
const wxExLexer lexer = wxExApp::GetLexers()->FindByName("cpp");
m_DirCtrl = new wxGenericDirCtrl(this, wxID_ANY, wxStandardPaths::Get().GetDocumentsDir());
m_NotebookWithLists = new wxExNotebook(
this, this,
wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxAUI_NB_DEFAULT_STYLE |
wxAUI_NB_WINDOWLIST_BUTTON);
m_STC = new wxExSTCWithFrame(this); // use all flags (default)
for (
int i = wxExListViewWithFrame::LIST_BEFORE_FIRST + 1;
i < wxExListViewWithFrame::LIST_AFTER_LAST;
i++)
{
wxExListViewWithFrame* vw = new wxExListViewWithFrame(
this,
(wxExListViewWithFrame::ListType)i,
wxID_ANY,
0xFF,
&lexer); // set all flags
m_NotebookWithLists->AddPage(vw, vw->GetTypeDescription(), vw->GetTypeDescription(), true);
}
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true));
GetManager().AddPane(m_NotebookWithLists, wxAuiPaneInfo().CloseButton(false).Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_DirCtrl, wxAuiPaneInfo().Caption(_("DirCtrl")).Left().MinSize(wxSize(250, 250)));
GetManager().AddPane(new wxExFindToolBar(this, this),
wxAuiPaneInfo().ToolbarPane().Bottom().Name("FINDBAR").Caption(_("Findbar")));
GetManager().Update();
wxExDirWithListView dir(
(wxExListViewWithFrame*)m_NotebookWithLists->GetPageByKey(
wxExListViewWithFrame::GetTypeDescription(wxExListViewWithFrame::LIST_PROJECT)),
wxGetCwd(),
"*.cpp;*.h");
dir.FindFiles();
wxExListItemWithFileName item(
(wxExListViewWithFrame*)m_NotebookWithLists->GetPageByKey(
wxExListViewWithFrame::GetTypeDescription(wxExListViewWithFrame::LIST_PROJECT)),
"NOT EXISTING ITEM");
item.Insert();
}
wxExListViewWithFrame* wxExRepSampleFrame::Activate(
wxExListViewWithFrame::ListType type,
const wxExLexer* lexer)
{
for (
size_t i = 0;
i < m_NotebookWithLists->GetPageCount();
i++)
{
wxExListViewWithFrame* vw = (wxExListViewWithFrame*)m_NotebookWithLists->GetPage(i);
if (vw->GetType() == type)
{
if (type == wxExListViewWithFrame::LIST_KEYWORD)
{
if (lexer != NULL)
{
if (lexer->GetScintillaLexer() != "cpp")
{
wxLogMessage(lexer->GetScintillaLexer() + ", only cpp for the sample");
return NULL;
}
}
}
return vw;
}
}
return NULL;
}
void wxExRepSampleFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(wxEX_VERSION_STRING);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
event.Skip();
break;
case wxID_PREVIEW:
if (m_STC->HasCapture())
{
m_STC->PrintPreview();
}
else
{
wxExListViewWithFrame* lv = GetFocusedListView();
if (lv != NULL)
{
lv->PrintPreview();
}
}
break;
case wxID_PRINT:
{
wxExListViewWithFrame* lv = GetFocusedListView();
if (lv != NULL)
{
lv->Print();
}
}
break;
case wxID_PRINT_SETUP: wxExApp::GetPrinter()->PageSetup();
break;
case wxID_STOP:
if (ProcessIsRunning())
{
ProcessStop();
}
break;
case ID_PROCESS_DIALOG:
wxExProcessWithListView::ConfigDialog(this);
break;
case ID_PROCESS_RUN:
ProcessRun();
break;
default:
wxFAIL;
break;
}
}
void wxExRepSampleFrame::OnTree(wxTreeEvent& /* event */)
{
const wxString selection = m_DirCtrl->GetFilePath();
if (!selection.empty())
{
OpenFile(wxExFileName(selection));
}
}
bool wxExRepSampleFrame::OpenFile(const wxExFileName& file,
int line_number,
const wxString& match,
long flags)
{
// We cannot use the wxExFrameWithHistory::OpenFile, as that uses the focused STC.
// Prevent recursion.
if ((flags & wxExSTC::STC_OPEN_FROM_LINK) |
(flags & wxExSTC::STC_OPEN_FROM_STATISTICS))
{
flags = 0;
}
bool result = m_STC->Open(file, line_number, match, flags);
if (result)
{
m_STC->PropertiesMessage();
}
return result;
}
|
/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxExRep
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/stdpaths.h> // for wxStandardPaths
#include "appl.h"
#ifndef __WXMSW__
#include "appl.xpm"
#endif
enum
{
ID_PROCESS_DIALOG,
ID_PROCESS_RUN,
ID_RECENTFILE_MENU,
};
BEGIN_EVENT_TABLE(wxExRepSampleFrame, wxExFrameWithHistory)
EVT_MENU(wxID_STOP, wxExRepSampleFrame::OnCommand)
EVT_MENU(ID_PROCESS_DIALOG, wxExRepSampleFrame::OnCommand)
EVT_MENU(ID_PROCESS_RUN, wxExRepSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, wxExRepSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, wxExRepSampleFrame::OnCommand)
EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExRepSampleFrame::OnTree)
END_EVENT_TABLE()
IMPLEMENT_APP(wxExRepSampleApp)
bool wxExRepSampleApp::OnInit()
{
SetAppName("wxExRepSample");
if (!wxExApp::OnInit())
{
return false;
}
SetLogging();
wxExRepSampleFrame *frame = new wxExRepSampleFrame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
wxExRepSampleFrame::wxExRepSampleFrame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
{
SetIcon(wxICON(appl));
wxExMenu *menuFile = new wxExMenu;
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu *menuProcess = new wxExMenu;
menuProcess->Append(ID_PROCESS_DIALOG, wxExEllipsed(_("Dialog")));
menuProcess->Append(ID_PROCESS_RUN, _("Run"));
menuProcess->AppendSeparator();
menuProcess->Append(wxID_STOP);
wxExMenu* menuHelp = new wxExMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->Realize();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50));
panes.push_back(wxExPane("PaneLines", 100));
panes.push_back(wxExPane("PaneLexer", 60));
panes.push_back(wxExPane("PaneItems", 60));
SetupStatusBar(panes);
#endif
const wxExLexer lexer = wxExApp::GetLexers()->FindByName("cpp");
m_DirCtrl = new wxGenericDirCtrl(this, wxID_ANY, wxStandardPaths::Get().GetDocumentsDir());
m_NotebookWithLists = new wxExNotebook(
this, this,
wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxAUI_NB_DEFAULT_STYLE |
wxAUI_NB_WINDOWLIST_BUTTON);
m_STC = new wxExSTCWithFrame(this); // use all flags (default)
for (
int i = wxExListViewWithFrame::LIST_BEFORE_FIRST + 1;
i < wxExListViewWithFrame::LIST_AFTER_LAST;
i++)
{
wxExListViewWithFrame* vw = new wxExListViewWithFrame(
this,
(wxExListViewWithFrame::ListType)i,
wxID_ANY,
0xFF,
&lexer); // set all flags
m_NotebookWithLists->AddPage(vw, vw->GetTypeDescription(), vw->GetTypeDescription(), true);
}
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true));
GetManager().AddPane(m_NotebookWithLists, wxAuiPaneInfo().CloseButton(false).Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_DirCtrl, wxAuiPaneInfo().Caption(_("DirCtrl")).Left().MinSize(wxSize(250, 250)));
GetManager().AddPane(new wxExFindToolBar(this, this),
wxAuiPaneInfo().ToolbarPane().Bottom().Name("FINDBAR").Caption(_("Findbar")));
GetManager().Update();
wxExDirWithListView dir(
(wxExListViewWithFrame*)m_NotebookWithLists->GetPageByKey(
wxExListViewWithFrame::GetTypeDescription(wxExListViewWithFrame::LIST_PROJECT)),
wxGetCwd(),
"*.cpp;*.h");
dir.FindFiles();
wxExListItemWithFileName item(
(wxExListViewWithFrame*)m_NotebookWithLists->GetPageByKey(
wxExListViewWithFrame::GetTypeDescription(wxExListViewWithFrame::LIST_PROJECT)),
"NOT EXISTING ITEM");
item.Insert();
}
wxExListViewWithFrame* wxExRepSampleFrame::Activate(
wxExListViewWithFrame::ListType type,
const wxExLexer* lexer)
{
for (
size_t i = 0;
i < m_NotebookWithLists->GetPageCount();
i++)
{
wxExListViewWithFrame* vw = (wxExListViewWithFrame*)m_NotebookWithLists->GetPage(i);
if (vw->GetType() == type)
{
if (type == wxExListViewWithFrame::LIST_KEYWORD)
{
if (lexer != NULL)
{
if (lexer->GetScintillaLexer() != "cpp")
{
wxLogMessage(lexer->GetScintillaLexer() + ", only cpp for the sample");
return NULL;
}
}
}
return vw;
}
}
return NULL;
}
void wxExRepSampleFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(wxEX_VERSION_STRING);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
event.Skip();
break;
case wxID_PREVIEW:
if (m_STC->HasCapture())
{
m_STC->PrintPreview();
}
else
{
wxExListView* lv = GetFocusedListView();
if (lv != NULL)
{
lv->PrintPreview();
}
}
break;
case wxID_PRINT:
{
wxExListView* lv = GetFocusedListView();
if (lv != NULL)
{
lv->Print();
}
}
break;
case wxID_PRINT_SETUP: wxExApp::GetPrinter()->PageSetup();
break;
case wxID_STOP:
if (ProcessIsRunning())
{
ProcessStop();
}
break;
case ID_PROCESS_DIALOG:
wxExProcessWithListView::ConfigDialog(this);
break;
case ID_PROCESS_RUN:
ProcessRun();
break;
default:
wxFAIL;
break;
}
}
void wxExRepSampleFrame::OnTree(wxTreeEvent& /* event */)
{
const wxString selection = m_DirCtrl->GetFilePath();
if (!selection.empty())
{
OpenFile(wxExFileName(selection));
}
}
bool wxExRepSampleFrame::OpenFile(const wxExFileName& file,
int line_number,
const wxString& match,
long flags)
{
// We cannot use the wxExFrameWithHistory::OpenFile, as that uses the focused STC.
// Prevent recursion.
if ((flags & wxExSTC::STC_OPEN_FROM_LINK) |
(flags & wxExSTC::STC_OPEN_FROM_STATISTICS))
{
flags = 0;
}
bool result = m_STC->Open(file, line_number, match, flags);
if (result)
{
m_STC->PropertiesMessage();
}
return result;
}
|
fix compile error
|
fix compile error
git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@1770 f22100f3-aa73-48fe-a4fb-fd497bb32605
|
C++
|
mit
|
antonvw/wxExtension,antonvw/wxExtension,antonvw/wxExtension
|
1e5631a62992f147dae73f5146c11b0bf51cec4d
|
src/vector_tile_load_tile.hpp
|
src/vector_tile_load_tile.hpp
|
#ifndef __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
#define __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
// mapnik-vector-tile
#include "vector_tile_config.hpp"
#include "vector_tile_compression.hpp"
#include "vector_tile_tile.hpp"
#include "vector_tile_datasource_pbf.hpp"
#include "vector_tile_is_valid.hpp"
#include "vector_tile_processor.hpp"
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/make_unique.hpp>
//protozero
#include <protozero/pbf_reader.hpp>
#include <protozero/pbf_writer.hpp>
// std
#include <set>
#include <string>
#include <memory>
namespace mapnik
{
namespace vector_tile_impl
{
std::pair<std::string,std::uint32_t> get_layer_name_and_version(protozero::pbf_reader & layer_msg)
{
std::string name;
std::uint32_t version = 1;
while (layer_msg.next())
{
switch (layer_msg.tag())
{
case Layer_Encoding::NAME:
name = layer_msg.get_string();
break;
case Layer_Encoding::VERSION:
version = layer_msg.get_uint32();;
break;
default:
layer_msg.skip();
break;
}
}
return std::make_pair(name,version);
}
void merge_from_buffer(merc_tile & t, const char * data, std::size_t size, bool validate = false, bool upgrade = false)
{
using ds_ptr = std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf>;
protozero::pbf_reader tile_msg(data, size);
std::vector<ds_ptr> ds_vec;
while (tile_msg.next())
{
switch (tile_msg.tag())
{
case Tile_Encoding::LAYERS:
{
auto layer_data = tile_msg.get_data();
protozero::pbf_reader layer_props_msg(layer_data);
auto layer_info = get_layer_name_and_version(layer_props_msg);
std::string const& layer_name = layer_info.first;
std::uint32_t version = layer_info.second;
if (validate)
{
std::set<validity_error> errors;
if (version < 1 || version > 2)
{
errors.insert(LAYER_HAS_UNSUPPORTED_VERSION);
}
if (t.has_layer(layer_name))
{
errors.insert(TILE_REPEATED_LAYER_NAMES);
}
protozero::pbf_reader layer_valid_msg(layer_data);
layer_is_valid(layer_valid_msg, errors);
if (!errors.empty())
{
std::string layer_errors;
validity_error_to_string(errors, layer_errors);
throw std::runtime_error(layer_errors);
}
}
else if (layer_name.empty() || t.has_layer(layer_name))
{
continue;
}
if (upgrade && version == 1)
{
// v1 tiles will be converted to v2
protozero::pbf_reader layer_msg(layer_data);
ds_vec.push_back(std::make_shared<mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
t.x(),
t.y(),
t.z(),
true));
}
else if (validate && version != 1)
{
std::ostringstream s;
s << "Unable to upgrade version '" << version << "' data, only version 1 is upgradeable";
throw std::runtime_error(s.str());
}
else
{
t.append_layer_buffer(layer_data.first, layer_data.second, layer_name);
}
}
break;
default:
throw std::runtime_error("Vector Tile Buffer contains invalid tag");
break;
}
}
if (ds_vec.empty())
{
return;
}
// Convert v1 tiles to v2
std::int32_t prev_buffer_size = t.buffer_size();
t.buffer_size(4096); // very large buffer so we don't miss any buffered points
mapnik::Map map(t.tile_size(), t.tile_size(), "+init=epsg:3857");
for (auto const& ds : ds_vec)
{
ds->set_envelope(t.get_buffered_extent());
mapnik::layer lyr(ds->get_name(), "+init=epsg:3857");
lyr.set_datasource(ds);
map.add_layer(std::move(lyr));
}
mapnik::vector_tile_impl::processor ren(map);
ren.set_multi_polygon_union(true);
ren.set_fill_type(mapnik::vector_tile_impl::even_odd_fill);
ren.set_process_all_rings(true);
//ren.set_simplify_distance(4.0);
ren.update_tile(t);
t.buffer_size(prev_buffer_size);
}
void merge_from_compressed_buffer(merc_tile & t, const char * data, std::size_t size, bool validate = false, bool upgrade = false)
{
if (mapnik::vector_tile_impl::is_gzip_compressed(data,size) ||
mapnik::vector_tile_impl::is_zlib_compressed(data,size))
{
std::string decompressed;
mapnik::vector_tile_impl::zlib_decompress(data, size, decompressed);
return merge_from_buffer(t, decompressed.data(), decompressed.size(), validate, upgrade);
}
else
{
return merge_from_buffer(t, data, size, validate, upgrade);
}
}
void add_image_buffer_as_tile_layer(merc_tile & t, std::string const& layer_name, const char * data, std::size_t size)
{
std::string layer_buffer;
protozero::pbf_writer layer_writer(layer_buffer);
layer_writer.add_uint32(Layer_Encoding::VERSION, 2);
layer_writer.add_string(Layer_Encoding::NAME, layer_name);
layer_writer.add_uint32(Layer_Encoding::EXTENT, 4096);
{
protozero::pbf_writer feature_writer(layer_writer, Layer_Encoding::FEATURES);
feature_writer.add_bytes(Feature_Encoding::RASTER, data, size);
}
t.append_layer_buffer(layer_buffer.data(), layer_buffer.size(), layer_name);
}
} // end ns vector_tile_impl
} // end ns mapnik
#endif // __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
|
#ifndef __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
#define __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
// mapnik-vector-tile
#include "vector_tile_config.hpp"
#include "vector_tile_compression.hpp"
#include "vector_tile_tile.hpp"
#include "vector_tile_datasource_pbf.hpp"
#include "vector_tile_is_valid.hpp"
#include "vector_tile_processor.hpp"
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/make_unique.hpp>
//protozero
#include <protozero/pbf_reader.hpp>
#include <protozero/pbf_writer.hpp>
// std
#include <set>
#include <string>
#include <memory>
namespace mapnik
{
namespace vector_tile_impl
{
std::pair<std::string,std::uint32_t> get_layer_name_and_version(protozero::pbf_reader & layer_msg)
{
std::string name;
std::uint32_t version = 1;
while (layer_msg.next())
{
switch (layer_msg.tag())
{
case Layer_Encoding::NAME:
name = layer_msg.get_string();
break;
case Layer_Encoding::VERSION:
version = layer_msg.get_uint32();;
break;
default:
layer_msg.skip();
break;
}
}
return std::make_pair(name,version);
}
void merge_from_buffer(merc_tile & t, const char * data, std::size_t size, bool validate = false, bool upgrade = false)
{
using ds_ptr = std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf>;
protozero::pbf_reader tile_msg(data, size);
std::vector<ds_ptr> ds_vec;
while (tile_msg.next())
{
switch (tile_msg.tag())
{
case Tile_Encoding::LAYERS:
{
auto layer_data = tile_msg.get_data();
protozero::pbf_reader layer_props_msg(layer_data);
auto layer_info = get_layer_name_and_version(layer_props_msg);
std::string const& layer_name = layer_info.first;
std::uint32_t version = layer_info.second;
if (validate)
{
std::set<validity_error> errors;
if (version < 1 || version > 2)
{
errors.insert(LAYER_HAS_UNSUPPORTED_VERSION);
}
if (t.has_layer(layer_name))
{
errors.insert(TILE_REPEATED_LAYER_NAMES);
}
protozero::pbf_reader layer_valid_msg(layer_data);
layer_is_valid(layer_valid_msg, errors);
if (!errors.empty())
{
std::string layer_errors;
validity_error_to_string(errors, layer_errors);
throw std::runtime_error(layer_errors);
}
}
else if (layer_name.empty() || t.has_layer(layer_name))
{
continue;
}
if (upgrade && version == 1)
{
// v1 tiles will be converted to v2
protozero::pbf_reader layer_msg(layer_data);
ds_vec.push_back(std::make_shared<mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
t.x(),
t.y(),
t.z(),
true));
}
else
{
t.append_layer_buffer(layer_data.first, layer_data.second, layer_name);
}
}
break;
default:
throw std::runtime_error("Vector Tile Buffer contains invalid tag");
break;
}
}
if (ds_vec.empty())
{
return;
}
// Convert v1 tiles to v2
std::int32_t prev_buffer_size = t.buffer_size();
t.buffer_size(4096); // very large buffer so we don't miss any buffered points
mapnik::Map map(t.tile_size(), t.tile_size(), "+init=epsg:3857");
for (auto const& ds : ds_vec)
{
ds->set_envelope(t.get_buffered_extent());
mapnik::layer lyr(ds->get_name(), "+init=epsg:3857");
lyr.set_datasource(ds);
map.add_layer(std::move(lyr));
}
mapnik::vector_tile_impl::processor ren(map);
ren.set_multi_polygon_union(true);
ren.set_fill_type(mapnik::vector_tile_impl::even_odd_fill);
ren.set_process_all_rings(true);
//ren.set_simplify_distance(4.0);
ren.update_tile(t);
t.buffer_size(prev_buffer_size);
}
void merge_from_compressed_buffer(merc_tile & t, const char * data, std::size_t size, bool validate = false, bool upgrade = false)
{
if (mapnik::vector_tile_impl::is_gzip_compressed(data,size) ||
mapnik::vector_tile_impl::is_zlib_compressed(data,size))
{
std::string decompressed;
mapnik::vector_tile_impl::zlib_decompress(data, size, decompressed);
return merge_from_buffer(t, decompressed.data(), decompressed.size(), validate, upgrade);
}
else
{
return merge_from_buffer(t, data, size, validate, upgrade);
}
}
void add_image_buffer_as_tile_layer(merc_tile & t, std::string const& layer_name, const char * data, std::size_t size)
{
std::string layer_buffer;
protozero::pbf_writer layer_writer(layer_buffer);
layer_writer.add_uint32(Layer_Encoding::VERSION, 2);
layer_writer.add_string(Layer_Encoding::NAME, layer_name);
layer_writer.add_uint32(Layer_Encoding::EXTENT, 4096);
{
protozero::pbf_writer feature_writer(layer_writer, Layer_Encoding::FEATURES);
feature_writer.add_bytes(Feature_Encoding::RASTER, data, size);
}
t.append_layer_buffer(layer_buffer.data(), layer_buffer.size(), layer_name);
}
} // end ns vector_tile_impl
} // end ns mapnik
#endif // __MAPNIK_VECTOR_TILE_LOAD_TILE_H__
|
simplify code: don't throw in case of upgrading non v1 tiles
|
simplify code: don't throw in case of upgrading non v1 tiles
|
C++
|
bsd-3-clause
|
mapbox/mapnik-vector-tile,mapbox/mapnik-vector-tile,tomhughes/mapnik-vector-tile,tomhughes/mapnik-vector-tile,mapbox/mapnik-vector-tile,mapbox/mapnik-vector-tile,tomhughes/mapnik-vector-tile,tomhughes/mapnik-vector-tile
|
03813a9674a9908e04507041ea54ae0ef88322c7
|
test_conformance/device_execution/host_queue_order.cpp
|
test_conformance/device_execution/host_queue_order.cpp
|
//
// Copyright (c) 2017 The Khronos Group 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 <stdio.h>
#include <string.h>
#include "../../test_common/harness/testHarness.h"
#include "../../test_common/harness/typeWrappers.h"
#include <vector>
#include "procs.h"
#include "utils.h"
#include <time.h>
extern int gWimpyMode;
#ifdef CL_VERSION_2_0
static const char* enqueue_block_first_kernel[] =
{
NL, "void block_fn(uint num, __global int* res)"
NL, "{"
NL, " size_t tid = get_global_id(0);"
NL, ""
NL, " for(int i = 1 ; i < tid ; i++)"
NL, " {"
NL, " for(int j = 0 ; j < num ; j++)"
NL, " atomic_add(res+tid, convert_int_rte(sqrt((float)i*i) / i));"
NL, " }"
NL, "}"
NL, ""
NL, "kernel void enqueue_block_first_kernel(uint num, __global int* res)"
NL, "{"
NL, " void (^kernelBlock)(void) = ^{ block_fn(num, res); };"
NL, ""
NL, " ndrange_t ndrange = ndrange_1D(num, 1);"
NL, ""
NL, " int enq_res = enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_NO_WAIT, ndrange, kernelBlock);"
NL, " if(enq_res != CLK_SUCCESS) { res[0] = -1; return; }"
NL, ""
NL, "}"
NL
};
static const char* enqueue_block_second_kernel[] =
{
NL, "void block_fn(uint num, __global int* res)"
NL, "{"
NL, " for(int i = 2 ; i < num ; i++)"
NL, " {"
NL, " res[i] = res[i]/num - (i-1);"
NL, " }"
NL, "}"
NL, ""
NL, "kernel void enqueue_block_second_kernel(uint num, __global int* res)"
NL, "{"
NL, " void (^kernelBlock)(void) = ^{ block_fn(num, res); };"
NL, ""
NL, " ndrange_t ndrange = ndrange_1D(1);"
NL, ""
NL, " int enq_res = enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange, kernelBlock);"
NL, " if(enq_res != CLK_SUCCESS) { res[0] = -1; return; }"
NL, ""
NL, "}"
NL
};
static int check_kernel_results(cl_int* results, cl_int len)
{
for(cl_int i = 0; i < len; ++i)
{
if(results[i] != 0) return i;
}
return -1;
}
/*
Test checks kernel block execution order in case of two different kernels with enqueue block submitted to one ordered host queue.
*/
int test_host_queue_order(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements)
{
cl_int k, err_ret, res = 0;
clCommandQueueWrapper dev_queue;
cl_int kernel_results[MAX_GWS] = {0};
size_t ret_len;
cl_uint max_queues = 1;
cl_uint maxQueueSize = 0;
err_ret = clGetDeviceInfo(device, CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE, sizeof(maxQueueSize), &maxQueueSize, 0);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE) failed");
err_ret = clGetDeviceInfo(device, CL_DEVICE_MAX_ON_DEVICE_QUEUES, sizeof(max_queues), &max_queues, &ret_len);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_MAX_ON_DEVICE_QUEUES) failed");
size_t max_local_size = 1;
err_ret = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(max_local_size), &max_local_size, &ret_len);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE) failed");
cl_queue_properties queue_prop_def[] =
{
CL_QUEUE_PROPERTIES, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE|CL_QUEUE_ON_DEVICE|CL_QUEUE_ON_DEVICE_DEFAULT,
CL_QUEUE_SIZE, maxQueueSize,
0
};
dev_queue = clCreateCommandQueueWithProperties(context, device, queue_prop_def, &err_ret);
test_error(err_ret, "clCreateCommandQueueWithProperties(CL_QUEUE_DEVICE|CL_QUEUE_DEFAULT) failed");
cl_int status;
size_t size = 1;
cl_int result[MAX_GWS] = { 0 };
cl_uint num = arr_size(result);
if( gWimpyMode )
{
num = MAX(num / 16, 4);
}
clMemWrapper res_mem;
clProgramWrapper program1, program2;
clKernelWrapper kernel1, kernel2;
cl_event kernel_event;
err_ret = create_single_kernel_helper_with_build_options(context, &program1, &kernel1, arr_size(enqueue_block_first_kernel), enqueue_block_first_kernel, "enqueue_block_first_kernel", "-cl-std=CL2.0");
if(check_error(err_ret, "Create single kernel failed")) return -1;
err_ret = create_single_kernel_helper_with_build_options(context, &program2, &kernel2, arr_size(enqueue_block_second_kernel), enqueue_block_second_kernel, "enqueue_block_second_kernel", "-cl-std=CL2.0");
if(check_error(err_ret, "Create single kernel failed")) return -1;
res_mem = clCreateBuffer(context, CL_MEM_READ_WRITE|CL_MEM_COPY_HOST_PTR, sizeof(kernel_results), kernel_results, &err_ret);
test_error(err_ret, "clCreateBuffer() failed");
// Enqueue first kernel
err_ret = clSetKernelArg(kernel1, 0, sizeof(num), &num);
test_error(err_ret, "clSetKernelArg(0) failed");
err_ret = clSetKernelArg(kernel1, 1, sizeof(cl_mem), &res_mem);
test_error(err_ret, "clSetKernelArg(1) failed");
cl_event event1 = clCreateUserEvent(context, &err_ret);
if(check_error(err_ret, "Create user event failed")) return -1;
err_ret = clEnqueueNDRangeKernel(queue, kernel1, 1, NULL, &size, &size, 1, &event1, NULL);
test_error(err_ret, "clEnqueueNDRangeKernel('enqueue_block_first_kernel') failed");
// Enqueue second kernel
err_ret = clSetKernelArg(kernel2, 0, sizeof(num), &num);
test_error(err_ret, "clSetKernelArg(0) failed");
err_ret = clSetKernelArg(kernel2, 1, sizeof(cl_mem), &res_mem);
test_error(err_ret, "clSetKernelArg(1) failed");
err_ret = clEnqueueNDRangeKernel(queue, kernel2, 1, NULL, &size, &size, 0, NULL, &kernel_event);
test_error(err_ret, "clEnqueueNDRangeKernel('enqueue_block_second_kernel') failed");
//Triger execution of first kernel
err_ret = clSetUserEventStatus(event1, CL_COMPLETE);
test_error(err_ret, "clSetUserEventStatus() failed");
// Collect resulsts
err_ret = clEnqueueReadBuffer(queue, res_mem, CL_TRUE, 0, sizeof(result), result, 0, NULL, NULL);
test_error(err_ret, "clEnqueueReadBuffer() failed");
err_ret = clGetEventInfo(kernel_event, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status), &status, &ret_len);
test_error(err_ret, "clGetEventInfo() failed");
if(check_error(status, "Kernel execution status %d", status)) return status;
if((k = check_kernel_results(result, num)) >= 0 && check_error(-1, "'%s' results validation failed: [%d] returned %d expected 0", "test_host_queue_order", k, result[k])) res = -1;
return res;
}
#endif
|
//
// Copyright (c) 2017 The Khronos Group 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 <stdio.h>
#include <string.h>
#include "../../test_common/harness/testHarness.h"
#include "../../test_common/harness/typeWrappers.h"
#include <vector>
#include "procs.h"
#include "utils.h"
#include <time.h>
extern int gWimpyMode;
#ifdef CL_VERSION_2_0
static const char* enqueue_block_first_kernel[] =
{
NL, "void block_fn(uint num, __global int* res)"
NL, "{"
NL, " size_t tid = get_global_id(0);"
NL, ""
NL, " for(int i = 1 ; i < tid ; i++)"
NL, " {"
NL, " for(int j = 0 ; j < num ; j++)"
NL, " atomic_add(res+tid, 1);"
NL, " }"
NL, "}"
NL, ""
NL, "kernel void enqueue_block_first_kernel(uint num, __global int* res)"
NL, "{"
NL, " void (^kernelBlock)(void) = ^{ block_fn(num, res); };"
NL, ""
NL, " ndrange_t ndrange = ndrange_1D(num, 1);"
NL, ""
NL, " int enq_res = enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_NO_WAIT, ndrange, kernelBlock);"
NL, " if(enq_res != CLK_SUCCESS) { res[0] = -1; return; }"
NL, ""
NL, "}"
NL
};
static const char* enqueue_block_second_kernel[] =
{
NL, "void block_fn(uint num, __global int* res)"
NL, "{"
NL, " for(int i = 2 ; i < num ; i++)"
NL, " {"
NL, " res[i] = res[i]/num - (i-1);"
NL, " }"
NL, "}"
NL, ""
NL, "kernel void enqueue_block_second_kernel(uint num, __global int* res)"
NL, "{"
NL, " void (^kernelBlock)(void) = ^{ block_fn(num, res); };"
NL, ""
NL, " ndrange_t ndrange = ndrange_1D(1);"
NL, ""
NL, " int enq_res = enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange, kernelBlock);"
NL, " if(enq_res != CLK_SUCCESS) { res[0] = -1; return; }"
NL, ""
NL, "}"
NL
};
static int check_kernel_results(cl_int* results, cl_int len)
{
for(cl_int i = 0; i < len; ++i)
{
if(results[i] != 0) return i;
}
return -1;
}
/*
Test checks kernel block execution order in case of two different kernels with enqueue block submitted to one ordered host queue.
*/
int test_host_queue_order(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements)
{
cl_int k, err_ret, res = 0;
clCommandQueueWrapper dev_queue;
cl_int kernel_results[MAX_GWS] = {0};
size_t ret_len;
cl_uint max_queues = 1;
cl_uint maxQueueSize = 0;
err_ret = clGetDeviceInfo(device, CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE, sizeof(maxQueueSize), &maxQueueSize, 0);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE) failed");
err_ret = clGetDeviceInfo(device, CL_DEVICE_MAX_ON_DEVICE_QUEUES, sizeof(max_queues), &max_queues, &ret_len);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_MAX_ON_DEVICE_QUEUES) failed");
size_t max_local_size = 1;
err_ret = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(max_local_size), &max_local_size, &ret_len);
test_error(err_ret, "clGetDeviceInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE) failed");
cl_queue_properties queue_prop_def[] =
{
CL_QUEUE_PROPERTIES, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE|CL_QUEUE_ON_DEVICE|CL_QUEUE_ON_DEVICE_DEFAULT,
CL_QUEUE_SIZE, maxQueueSize,
0
};
dev_queue = clCreateCommandQueueWithProperties(context, device, queue_prop_def, &err_ret);
test_error(err_ret, "clCreateCommandQueueWithProperties(CL_QUEUE_DEVICE|CL_QUEUE_DEFAULT) failed");
cl_int status;
size_t size = 1;
cl_int result[MAX_GWS] = { 0 };
cl_uint num = arr_size(result);
if( gWimpyMode )
{
num = MAX(num / 16, 4);
}
clMemWrapper res_mem;
clProgramWrapper program1, program2;
clKernelWrapper kernel1, kernel2;
cl_event kernel_event;
err_ret = create_single_kernel_helper_with_build_options(context, &program1, &kernel1, arr_size(enqueue_block_first_kernel), enqueue_block_first_kernel, "enqueue_block_first_kernel", "-cl-std=CL2.0");
if(check_error(err_ret, "Create single kernel failed")) return -1;
err_ret = create_single_kernel_helper_with_build_options(context, &program2, &kernel2, arr_size(enqueue_block_second_kernel), enqueue_block_second_kernel, "enqueue_block_second_kernel", "-cl-std=CL2.0");
if(check_error(err_ret, "Create single kernel failed")) return -1;
res_mem = clCreateBuffer(context, CL_MEM_READ_WRITE|CL_MEM_COPY_HOST_PTR, sizeof(kernel_results), kernel_results, &err_ret);
test_error(err_ret, "clCreateBuffer() failed");
// Enqueue first kernel
err_ret = clSetKernelArg(kernel1, 0, sizeof(num), &num);
test_error(err_ret, "clSetKernelArg(0) failed");
err_ret = clSetKernelArg(kernel1, 1, sizeof(cl_mem), &res_mem);
test_error(err_ret, "clSetKernelArg(1) failed");
cl_event event1 = clCreateUserEvent(context, &err_ret);
if(check_error(err_ret, "Create user event failed")) return -1;
err_ret = clEnqueueNDRangeKernel(queue, kernel1, 1, NULL, &size, &size, 1, &event1, NULL);
test_error(err_ret, "clEnqueueNDRangeKernel('enqueue_block_first_kernel') failed");
// Enqueue second kernel
err_ret = clSetKernelArg(kernel2, 0, sizeof(num), &num);
test_error(err_ret, "clSetKernelArg(0) failed");
err_ret = clSetKernelArg(kernel2, 1, sizeof(cl_mem), &res_mem);
test_error(err_ret, "clSetKernelArg(1) failed");
err_ret = clEnqueueNDRangeKernel(queue, kernel2, 1, NULL, &size, &size, 0, NULL, &kernel_event);
test_error(err_ret, "clEnqueueNDRangeKernel('enqueue_block_second_kernel') failed");
//Triger execution of first kernel
err_ret = clSetUserEventStatus(event1, CL_COMPLETE);
test_error(err_ret, "clSetUserEventStatus() failed");
// Collect resulsts
err_ret = clEnqueueReadBuffer(queue, res_mem, CL_TRUE, 0, sizeof(result), result, 0, NULL, NULL);
test_error(err_ret, "clEnqueueReadBuffer() failed");
err_ret = clGetEventInfo(kernel_event, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status), &status, &ret_len);
test_error(err_ret, "clGetEventInfo() failed");
if(check_error(status, "Kernel execution status %d", status)) return status;
if((k = check_kernel_results(result, num)) >= 0 && check_error(-1, "'%s' results validation failed: [%d] returned %d expected 0", "test_host_queue_order", k, result[k])) res = -1;
return res;
}
#endif
|
Fix test_host_queue_order not to rely on bit accurate float ops (#294)
|
Fix test_host_queue_order not to rely on bit accurate float ops (#294)
Currently, test_host_queue_order relies on bit accurate float ops.
It expects expects that sqrt((float)i * i) == i.
This is not always true due to floating point precision limitations.
The test does not really need the sqrt operation and it can be removed
instead of trying to correct the floating point check.
Replace problematic float operation with constant value of 1.
|
C++
|
apache-2.0
|
KhronosGroup/OpenCL-CTS,KhronosGroup/OpenCL-CTS,KhronosGroup/OpenCL-CTS,KhronosGroup/OpenCL-CTS
|
93ec63dab294d49a1eea29cc03a0045f3e28b4e0
|
filtersjb/FGFilter.cpp
|
filtersjb/FGFilter.cpp
|
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGFilter.cpp
Author: Jon S. Berndt
Date started: 11/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGFilter.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGFilter.cpp,v 1.37 2004/01/12 00:48:06 jberndt Exp $";
static const char *IdHdr = ID_FILTER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGFilter::FGFilter(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double denom;
string sOutputIdx;
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
dt = fcs->GetState()->Getdt();
Trigger = 0;
C1 = C2 = C3 = C4 = C5 = C6 = 0.0;
if (Type == "LAG_FILTER") FilterType = eLag ;
else if (Type == "LEAD_LAG_FILTER") FilterType = eLeadLag ;
else if (Type == "SECOND_ORDER_FILTER") FilterType = eOrder2 ;
else if (Type == "WASHOUT_FILTER") FilterType = eWashout ;
else if (Type == "INTEGRATOR") FilterType = eIntegrator ;
else FilterType = eUnknown ;
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "C1") *AC_cfg >> C1;
else if (token == "C2") *AC_cfg >> C2;
else if (token == "C3") *AC_cfg >> C3;
else if (token == "C4") *AC_cfg >> C4;
else if (token == "C5") *AC_cfg >> C5;
else if (token == "C6") *AC_cfg >> C6;
else if (token == "TRIGGER")
{
token = AC_cfg->GetValue("TRIGGER");
*AC_cfg >> token;
Trigger = resolveSymbol(token);
}
else if (token == "INPUT")
{
token = AC_cfg->GetValue("INPUT");
if( InputNodes.size() > 0 ) {
cerr << "Filters can only accept one input" << endl;
} else {
*AC_cfg >> token;
InputNodes.push_back( resolveSymbol(token) );
}
}
else if (token == "OUTPUT")
{
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputNode = PropertyManager->GetNode( sOutputIdx );
}
else cerr << "Unknown filter type: " << token << endl;
}
Initialize = true;
switch (FilterType) {
case eLag:
denom = 2.00 + dt*C1;
ca = dt*C1 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eLeadLag:
denom = 2.00*C3 + dt*C4;
ca = (2.00*C1 + dt*C2) / denom;
cb = (dt*C2 - 2.00*C1) / denom;
cc = (2.00*C3 - dt*C2) / denom;
break;
case eOrder2:
denom = 4.0*C3 + 2.0*C5*dt + C6*dt*dt;
ca = 4.0*C1 + 2.0*C2*dt + C3*dt*dt / denom;
cb = 2.0*C3*dt*dt - 8.0*C1 / denom;
cc = 4.0*C1 - 2.0*C2*dt + C3*dt*dt / denom;
cd = 2.0*C6*dt*dt - 8.0*C4 / denom;
ce = 4.0*C3 - 2.0*C5*dt + C6*dt*dt / denom;
break;
case eWashout:
denom = 2.00 + dt*C1;
ca = 2.00 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eIntegrator:
ca = dt*C1 / 2.00;
break;
case eUnknown:
cerr << "Unknown filter type" << endl;
break;
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGFilter::~FGFilter()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGFilter::Run(void)
{
int test = 0;
FGFCSComponent::Run(); // call the base class for initialization of Input
if (Initialize) {
PreviousOutput1 = PreviousInput1 = Output = Input;
Initialize = false;
} else if (Trigger != 0) {
test = Trigger->getIntValue();
if (test < 0) {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
Input = PreviousInput1 = PreviousInput2 = 0.0;
} else {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
}
} else {
Input = InputNodes[0]->getDoubleValue();
switch (FilterType) {
case eLag:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eLeadLag:
Output = Input * ca + PreviousInput1 * cb + PreviousOutput1 * cc;
break;
case eOrder2:
Output = Input * ca + PreviousInput1 * cb + PreviousInput2 * cc
- PreviousOutput1 * cd - PreviousOutput2 * ce;
break;
case eWashout:
Output = Input * ca - PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eIntegrator:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1;
break;
case eUnknown:
break;
}
}
PreviousOutput2 = PreviousOutput1;
PreviousOutput1 = Output;
PreviousInput2 = PreviousInput1;
PreviousInput1 = Input;
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGFilter::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " INPUT: " << InputNodes[0]->getName() << endl;
cout << " C1: " << C1 << endl;
cout << " C2: " << C2 << endl;
cout << " C3: " << C3 << endl;
cout << " C4: " << C4 << endl;
cout << " C5: " << C5 << endl;
cout << " C6: " << C6 << endl;
if (IsOutput) cout << " OUTPUT: " << OutputNode->getName() << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGFilter" << endl;
if (from == 1) cout << "Destroyed: FGFilter" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
|
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGFilter.cpp
Author: Jon S. Berndt
Date started: 11/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGFilter.h"
namespace JSBSim {
static const char *IdSrc = "$Id: FGFilter.cpp,v 1.38 2004/02/05 02:24:22 jberndt Exp $";
static const char *IdHdr = ID_FILTER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGFilter::FGFilter(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs),
AC_cfg(AC_cfg)
{
string token;
double denom;
string sOutputIdx;
Type = AC_cfg->GetValue("TYPE");
Name = AC_cfg->GetValue("NAME");
AC_cfg->GetNextConfigLine();
dt = fcs->GetState()->Getdt();
Trigger = 0;
C1 = C2 = C3 = C4 = C5 = C6 = 0.0;
if (Type == "LAG_FILTER") FilterType = eLag ;
else if (Type == "LEAD_LAG_FILTER") FilterType = eLeadLag ;
else if (Type == "SECOND_ORDER_FILTER") FilterType = eOrder2 ;
else if (Type == "WASHOUT_FILTER") FilterType = eWashout ;
else if (Type == "INTEGRATOR") FilterType = eIntegrator ;
else FilterType = eUnknown ;
while ((token = AC_cfg->GetValue()) != string("/COMPONENT")) {
*AC_cfg >> token;
if (token == "C1") *AC_cfg >> C1;
else if (token == "C2") *AC_cfg >> C2;
else if (token == "C3") *AC_cfg >> C3;
else if (token == "C4") *AC_cfg >> C4;
else if (token == "C5") *AC_cfg >> C5;
else if (token == "C6") *AC_cfg >> C6;
else if (token == "TRIGGER")
{
token = AC_cfg->GetValue("TRIGGER");
*AC_cfg >> token;
Trigger = resolveSymbol(token);
}
else if (token == "INPUT")
{
token = AC_cfg->GetValue("INPUT");
if( InputNodes.size() > 0 ) {
cerr << "Filters can only accept one input" << endl;
} else {
*AC_cfg >> token;
InputNodes.push_back( resolveSymbol(token) );
}
}
else if (token == "OUTPUT")
{
IsOutput = true;
*AC_cfg >> sOutputIdx;
OutputNode = PropertyManager->GetNode( sOutputIdx );
}
else cerr << "Unknown filter type: " << token << endl;
}
Initialize = true;
switch (FilterType) {
case eLag:
denom = 2.00 + dt*C1;
ca = dt*C1 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eLeadLag:
denom = 2.00*C3 + dt*C4;
ca = (2.00*C1 + dt*C2) / denom;
cb = (dt*C2 - 2.00*C1) / denom;
cc = (2.00*C3 - dt*C2) / denom;
break;
case eOrder2:
denom = 4.0*C4 + 2.0*C5*dt + C6*dt*dt;
ca = (4.0*C1 + 2.0*C2*dt + C3*dt*dt) / denom;
cb = (2.0*C3*dt*dt - 8.0*C1) / denom;
cc = (4.0*C1 - 2.0*C2*dt + C3*dt*dt) / denom;
cd = (2.0*C6*dt*dt - 8.0*C4) / denom;
ce = (4.0*C4 - 2.0*C5*dt + C6*dt*dt) / denom;
break;
case eWashout:
denom = 2.00 + dt*C1;
ca = 2.00 / denom;
cb = (2.00 - dt*C1) / denom;
break;
case eIntegrator:
ca = dt*C1 / 2.00;
break;
case eUnknown:
cerr << "Unknown filter type" << endl;
break;
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGFilter::~FGFilter()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGFilter::Run(void)
{
int test = 0;
FGFCSComponent::Run(); // call the base class for initialization of Input
if (Initialize) {
PreviousOutput1 = PreviousInput1 = Output = Input;
Initialize = false;
} else if (Trigger != 0) {
test = Trigger->getIntValue();
if (test < 0) {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
Input = PreviousInput1 = PreviousInput2 = 0.0;
} else {
Output = PreviousOutput1 = PreviousOutput2 = 0.0;
}
} else {
Input = InputNodes[0]->getDoubleValue();
switch (FilterType) {
case eLag:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eLeadLag:
Output = Input * ca + PreviousInput1 * cb + PreviousOutput1 * cc;
break;
case eOrder2:
Output = Input * ca + PreviousInput1 * cb + PreviousInput2 * cc
- PreviousOutput1 * cd - PreviousOutput2 * ce;
break;
case eWashout:
Output = Input * ca - PreviousInput1 * ca + PreviousOutput1 * cb;
break;
case eIntegrator:
Output = Input * ca + PreviousInput1 * ca + PreviousOutput1;
break;
case eUnknown:
break;
}
}
PreviousOutput2 = PreviousOutput1;
PreviousOutput1 = Output;
PreviousInput2 = PreviousInput1;
PreviousInput1 = Input;
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGFilter::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
cout << " INPUT: " << InputNodes[0]->getName() << endl;
cout << " C1: " << C1 << endl;
cout << " C2: " << C2 << endl;
cout << " C3: " << C3 << endl;
cout << " C4: " << C4 << endl;
cout << " C5: " << C5 << endl;
cout << " C6: " << C6 << endl;
if (IsOutput) cout << " OUTPUT: " << OutputNode->getName() << endl;
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGFilter" << endl;
if (from == 1) cout << "Destroyed: FGFilter" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
|
Fix for second order filter
|
Fix for second order filter
|
C++
|
lgpl-2.1
|
adrcad/jsbsim,AEgisTG/jsbsim,DolanP/jsbsim-dll,AEgisTG/jsbsim,airware/jsbsim,adrcad/jsbsim,DolanP/jsbsim-dll,Stonelinks/jsbsim,airware/jsbsim,esden/jsbsim,tridge/jsbsim,tridge/jsbsim,Stonelinks/jsbsim,hrabcak/jsbsim,airware/jsbsim,airware/jsbsim,Stonelinks/jsbsim,adrcad/jsbsim,hrabcak/jsbsim,airware/jsbsim,esden/jsbsim,cs8425/jsbsim,AEgisTG/jsbsim,hrabcak/jsbsim,airware/jsbsim,pmatigakis/jsbsim,pmatigakis/jsbsim,cs8425/jsbsim,adrcad/jsbsim,pmatigakis/jsbsim,tridge/jsbsim,Stonelinks/jsbsim,cs8425/jsbsim,hrabcak/jsbsim,esden/jsbsim,esden/jsbsim,AEgisTG/jsbsim,pmatigakis/jsbsim,pmatigakis/jsbsim,hrabcak/jsbsim,Stonelinks/jsbsim,AEgisTG/jsbsim,airware/jsbsim,pmatigakis/jsbsim,DolanP/jsbsim-dll,adrcad/jsbsim,esden/jsbsim,tridge/jsbsim,Stonelinks/jsbsim,DolanP/jsbsim-dll,tridge/jsbsim,hrabcak/jsbsim,cs8425/jsbsim,DolanP/jsbsim-dll,tridge/jsbsim,AEgisTG/jsbsim,cs8425/jsbsim,cs8425/jsbsim,hrabcak/jsbsim,tridge/jsbsim,AEgisTG/jsbsim,pmatigakis/jsbsim,adrcad/jsbsim,Stonelinks/jsbsim
|
ac320bb16137e8d5f11a96ac16c6f2a5f3a0e629
|
src/vw/Image/PixelTypeInfo.cc
|
src/vw/Image/PixelTypeInfo.cc
|
// __BEGIN_LICENSE__
// Copyright (C) 2006, 2007 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
/// \file PixelTypeInfo.cc
///
/// Functions that return information about types by ID.
///
#include <vw/Image/PixelTypeInfo.h>
#include <vw/Core/Exception.h>
#include <boost/algorithm/string.hpp>
vw::int32 vw::channel_size( vw::ChannelTypeEnum type ) {
switch( type ) {
case VW_CHANNEL_BOOL:
return sizeof(bool);
case VW_CHANNEL_CHAR:
case VW_CHANNEL_INT8:
case VW_CHANNEL_UINT8:
case VW_CHANNEL_GENERIC_1_BYTE:
return 1;
case VW_CHANNEL_INT16:
case VW_CHANNEL_UINT16:
case VW_CHANNEL_FLOAT16:
case VW_CHANNEL_GENERIC_2_BYTE:
return 2;
case VW_CHANNEL_INT32:
case VW_CHANNEL_UINT32:
case VW_CHANNEL_FLOAT32:
case VW_CHANNEL_GENERIC_4_BYTE:
return 4;
case VW_CHANNEL_INT64:
case VW_CHANNEL_UINT64:
case VW_CHANNEL_FLOAT64:
case VW_CHANNEL_GENERIC_8_BYTE:
return 8;
default:
vw_throw( ArgumentErr() << "Unrecognized or unsupported channel type (" << type << ")." );
return 0; // never reached
}
}
const char *vw::channel_type_name( vw::ChannelTypeEnum format ) {
switch( format ) {
case VW_CHANNEL_BOOL: return "BOOL";
case VW_CHANNEL_CHAR: return "CHAR";
case VW_CHANNEL_INT8: return "INT8";
case VW_CHANNEL_UINT8: return "UINT8";
case VW_CHANNEL_INT16: return "INT16";
case VW_CHANNEL_UINT16: return "UINT16";
case VW_CHANNEL_INT32: return "INT32";
case VW_CHANNEL_UINT32: return "UINT32";
case VW_CHANNEL_FLOAT16: return "FLOAT16";
case VW_CHANNEL_FLOAT32: return "FLOAT32";
case VW_CHANNEL_INT64: return "INT64";
case VW_CHANNEL_UINT64: return "UINT64";
case VW_CHANNEL_FLOAT64: return "FLOAT64";
case VW_CHANNEL_GENERIC_1_BYTE: return "GENERIC_1_BYTE";
case VW_CHANNEL_GENERIC_2_BYTE: return "GENERIC_2_BYTE";
case VW_CHANNEL_GENERIC_4_BYTE: return "GENERIC_3_BYTE";
case VW_CHANNEL_GENERIC_8_BYTE: return "GENERIC_4_BYTE";
default: return "UNKNOWN";
}
}
vw::int32 vw::num_channels( vw::PixelFormatEnum format ) {
switch( format ) {
case VW_PIXEL_SCALAR:
case VW_PIXEL_GRAY:
case VW_PIXEL_GENERIC_1_CHANNEL:
return 1;
case VW_PIXEL_GRAYA:
case VW_PIXEL_SCALAR_MASKED:
case VW_PIXEL_GRAY_MASKED:
case VW_PIXEL_GENERIC_2_CHANNEL:
return 2;
case VW_PIXEL_RGB:
case VW_PIXEL_HSV:
case VW_PIXEL_XYZ:
case VW_PIXEL_LUV:
case VW_PIXEL_LAB:
case VW_PIXEL_GRAYA_MASKED:
case VW_PIXEL_GENERIC_3_CHANNEL:
return 3;
case VW_PIXEL_RGBA:
case VW_PIXEL_RGB_MASKED:
case VW_PIXEL_HSV_MASKED:
case VW_PIXEL_XYZ_MASKED:
case VW_PIXEL_LUV_MASKED:
case VW_PIXEL_LAB_MASKED:
case VW_PIXEL_GENERIC_4_CHANNEL:
return 4;
case VW_PIXEL_RGBA_MASKED:
return 5;
default:
vw_throw( ArgumentErr() << "Unrecognized or unsupported pixel format (" << format << ")." );
return 0; // never reached
}
}
const char *vw::pixel_format_name( vw::PixelFormatEnum format ) {
switch( format ) {
case VW_PIXEL_SCALAR: return "SCALAR";
case VW_PIXEL_GRAY: return "GRAY";
case VW_PIXEL_GRAYA: return "GRAYA";
case VW_PIXEL_RGB: return "RGB";
case VW_PIXEL_RGBA: return "RGBA";
case VW_PIXEL_HSV: return "HSV";
case VW_PIXEL_XYZ: return "XYZ";
case VW_PIXEL_LUV: return "LUV";
case VW_PIXEL_LAB: return "LAB";
case VW_PIXEL_UNKNOWN_MASKED: return "UNKNOWN_MASKED";
case VW_PIXEL_SCALAR_MASKED: return "SCALAR_MASKED";
case VW_PIXEL_GRAY_MASKED: return "GRAY_MASKED";
case VW_PIXEL_GRAYA_MASKED: return "GRAYA_MASKED";
case VW_PIXEL_RGB_MASKED: return "RGB_MASKED";
case VW_PIXEL_RGBA_MASKED: return "RGBA_MASKED";
case VW_PIXEL_HSV_MASKED: return "HSV_MASKED";
case VW_PIXEL_XYZ_MASKED: return "XYZ_MASKED";
case VW_PIXEL_LUV_MASKED: return "LUV_MASKED";
case VW_PIXEL_LAB_MASKED: return "LAB_MASKED";
case VW_PIXEL_GENERIC_1_CHANNEL: return "VW_PIXEL_GENERIC_1_CHANNEL";
case VW_PIXEL_GENERIC_2_CHANNEL: return "VW_PIXEL_GENERIC_2_CHANNEL";
case VW_PIXEL_GENERIC_3_CHANNEL: return "VW_PIXEL_GENERIC_3_CHANNEL";
case VW_PIXEL_GENERIC_4_CHANNEL: return "VW_PIXEL_GENERIC_4_CHANNEL";
default: return "UNKNOWN";
}
}
vw::ChannelTypeEnum vw::channel_name_to_enum( const std::string& name ) {
std::string uname(name);
boost::to_upper(uname);
if (uname.length() < 4 || uname.length() > 15)
return VW_CHANNEL_UNKNOWN;
switch(uname[0]) {
case 'B':
if (uname == "BOOL") return VW_CHANNEL_BOOL;
break;
case 'C':
if (uname == "CHAR") return VW_CHANNEL_CHAR;
break;
case 'D':
if (uname == "DOUBLE") return VW_CHANNEL_FLOAT64;
break;
case 'F':
if (uname == "FLOAT16") return VW_CHANNEL_FLOAT16;
if (uname == "FLOAT64") return VW_CHANNEL_FLOAT64;
if (uname == "FLOAT32" || uname == "FLOAT") return VW_CHANNEL_FLOAT32;
break;
case 'G':
if (uname == "GENERIC_1_BYTE") return VW_CHANNEL_GENERIC_1_BYTE;
if (uname == "GENERIC_2_BYTE") return VW_CHANNEL_GENERIC_2_BYTE;
if (uname == "GENERIC_4_BYTE") return VW_CHANNEL_GENERIC_4_BYTE;
if (uname == "GENERIC_8_BYTE") return VW_CHANNEL_GENERIC_8_BYTE;
break;
case 'I':
if (uname == "INT8") return VW_CHANNEL_INT8;
if (uname == "INT16") return VW_CHANNEL_INT16;
if (uname == "INT32" || uname == "INT") return VW_CHANNEL_INT32;
if (uname == "INT64") return VW_CHANNEL_INT64;
break;
case 'U':
if (uname == "UINT8") return VW_CHANNEL_UINT8;
if (uname == "UINT16") return VW_CHANNEL_UINT16;
if (uname == "UINT32" || uname == "UINT") return VW_CHANNEL_UINT32;
if (uname == "UINT64") return VW_CHANNEL_UINT64;
break;
default:
break;
}
return VW_CHANNEL_UNKNOWN;
}
|
// __BEGIN_LICENSE__
// Copyright (C) 2006, 2007 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
/// \file PixelTypeInfo.cc
///
/// Functions that return information about types by ID.
///
#include <vw/Image/PixelTypeInfo.h>
#include <vw/Core/Exception.h>
#include <boost/algorithm/string.hpp>
vw::int32 vw::channel_size( vw::ChannelTypeEnum type ) {
switch( type ) {
case VW_CHANNEL_BOOL:
return sizeof(bool);
case VW_CHANNEL_CHAR:
case VW_CHANNEL_INT8:
case VW_CHANNEL_UINT8:
case VW_CHANNEL_GENERIC_1_BYTE:
return 1;
case VW_CHANNEL_INT16:
case VW_CHANNEL_UINT16:
case VW_CHANNEL_FLOAT16:
case VW_CHANNEL_GENERIC_2_BYTE:
return 2;
case VW_CHANNEL_INT32:
case VW_CHANNEL_UINT32:
case VW_CHANNEL_FLOAT32:
case VW_CHANNEL_GENERIC_4_BYTE:
return 4;
case VW_CHANNEL_INT64:
case VW_CHANNEL_UINT64:
case VW_CHANNEL_FLOAT64:
case VW_CHANNEL_GENERIC_8_BYTE:
return 8;
default:
vw_throw( ArgumentErr() << "Unrecognized or unsupported channel type (" << type << ")." );
return 0; // never reached
}
}
const char *vw::channel_type_name( vw::ChannelTypeEnum format ) {
switch( format ) {
case VW_CHANNEL_BOOL: return "BOOL";
case VW_CHANNEL_CHAR: return "CHAR";
case VW_CHANNEL_INT8: return "INT8";
case VW_CHANNEL_UINT8: return "UINT8";
case VW_CHANNEL_INT16: return "INT16";
case VW_CHANNEL_UINT16: return "UINT16";
case VW_CHANNEL_INT32: return "INT32";
case VW_CHANNEL_UINT32: return "UINT32";
case VW_CHANNEL_FLOAT16: return "FLOAT16";
case VW_CHANNEL_FLOAT32: return "FLOAT32";
case VW_CHANNEL_INT64: return "INT64";
case VW_CHANNEL_UINT64: return "UINT64";
case VW_CHANNEL_FLOAT64: return "FLOAT64";
case VW_CHANNEL_GENERIC_1_BYTE: return "GENERIC_1_BYTE";
case VW_CHANNEL_GENERIC_2_BYTE: return "GENERIC_2_BYTE";
case VW_CHANNEL_GENERIC_4_BYTE: return "GENERIC_4_BYTE";
case VW_CHANNEL_GENERIC_8_BYTE: return "GENERIC_8_BYTE";
default: return "UNKNOWN";
}
}
vw::int32 vw::num_channels( vw::PixelFormatEnum format ) {
switch( format ) {
case VW_PIXEL_SCALAR:
case VW_PIXEL_GRAY:
case VW_PIXEL_GENERIC_1_CHANNEL:
return 1;
case VW_PIXEL_GRAYA:
case VW_PIXEL_SCALAR_MASKED:
case VW_PIXEL_GRAY_MASKED:
case VW_PIXEL_GENERIC_2_CHANNEL:
return 2;
case VW_PIXEL_RGB:
case VW_PIXEL_HSV:
case VW_PIXEL_XYZ:
case VW_PIXEL_LUV:
case VW_PIXEL_LAB:
case VW_PIXEL_GRAYA_MASKED:
case VW_PIXEL_GENERIC_3_CHANNEL:
return 3;
case VW_PIXEL_RGBA:
case VW_PIXEL_RGB_MASKED:
case VW_PIXEL_HSV_MASKED:
case VW_PIXEL_XYZ_MASKED:
case VW_PIXEL_LUV_MASKED:
case VW_PIXEL_LAB_MASKED:
case VW_PIXEL_GENERIC_4_CHANNEL:
return 4;
case VW_PIXEL_RGBA_MASKED:
return 5;
default:
vw_throw( ArgumentErr() << "Unrecognized or unsupported pixel format (" << format << ")." );
return 0; // never reached
}
}
const char *vw::pixel_format_name( vw::PixelFormatEnum format ) {
switch( format ) {
case VW_PIXEL_SCALAR: return "SCALAR";
case VW_PIXEL_GRAY: return "GRAY";
case VW_PIXEL_GRAYA: return "GRAYA";
case VW_PIXEL_RGB: return "RGB";
case VW_PIXEL_RGBA: return "RGBA";
case VW_PIXEL_HSV: return "HSV";
case VW_PIXEL_XYZ: return "XYZ";
case VW_PIXEL_LUV: return "LUV";
case VW_PIXEL_LAB: return "LAB";
case VW_PIXEL_UNKNOWN_MASKED: return "UNKNOWN_MASKED";
case VW_PIXEL_SCALAR_MASKED: return "SCALAR_MASKED";
case VW_PIXEL_GRAY_MASKED: return "GRAY_MASKED";
case VW_PIXEL_GRAYA_MASKED: return "GRAYA_MASKED";
case VW_PIXEL_RGB_MASKED: return "RGB_MASKED";
case VW_PIXEL_RGBA_MASKED: return "RGBA_MASKED";
case VW_PIXEL_HSV_MASKED: return "HSV_MASKED";
case VW_PIXEL_XYZ_MASKED: return "XYZ_MASKED";
case VW_PIXEL_LUV_MASKED: return "LUV_MASKED";
case VW_PIXEL_LAB_MASKED: return "LAB_MASKED";
case VW_PIXEL_GENERIC_1_CHANNEL: return "VW_PIXEL_GENERIC_1_CHANNEL";
case VW_PIXEL_GENERIC_2_CHANNEL: return "VW_PIXEL_GENERIC_2_CHANNEL";
case VW_PIXEL_GENERIC_3_CHANNEL: return "VW_PIXEL_GENERIC_3_CHANNEL";
case VW_PIXEL_GENERIC_4_CHANNEL: return "VW_PIXEL_GENERIC_4_CHANNEL";
default: return "UNKNOWN";
}
}
vw::ChannelTypeEnum vw::channel_name_to_enum( const std::string& name ) {
std::string uname(name);
boost::to_upper(uname);
if (uname.length() < 4 || uname.length() > 15)
return VW_CHANNEL_UNKNOWN;
switch(uname[0]) {
case 'B':
if (uname == "BOOL") return VW_CHANNEL_BOOL;
break;
case 'C':
if (uname == "CHAR") return VW_CHANNEL_CHAR;
break;
case 'D':
if (uname == "DOUBLE") return VW_CHANNEL_FLOAT64;
break;
case 'F':
if (uname == "FLOAT16") return VW_CHANNEL_FLOAT16;
if (uname == "FLOAT64") return VW_CHANNEL_FLOAT64;
if (uname == "FLOAT32" || uname == "FLOAT") return VW_CHANNEL_FLOAT32;
break;
case 'G':
if (uname == "GENERIC_1_BYTE") return VW_CHANNEL_GENERIC_1_BYTE;
if (uname == "GENERIC_2_BYTE") return VW_CHANNEL_GENERIC_2_BYTE;
if (uname == "GENERIC_4_BYTE") return VW_CHANNEL_GENERIC_4_BYTE;
if (uname == "GENERIC_8_BYTE") return VW_CHANNEL_GENERIC_8_BYTE;
break;
case 'I':
if (uname == "INT8") return VW_CHANNEL_INT8;
if (uname == "INT16") return VW_CHANNEL_INT16;
if (uname == "INT32" || uname == "INT") return VW_CHANNEL_INT32;
if (uname == "INT64") return VW_CHANNEL_INT64;
break;
case 'U':
if (uname == "UINT8") return VW_CHANNEL_UINT8;
if (uname == "UINT16") return VW_CHANNEL_UINT16;
if (uname == "UINT32" || uname == "UINT") return VW_CHANNEL_UINT32;
if (uname == "UINT64") return VW_CHANNEL_UINT64;
break;
default:
break;
}
return VW_CHANNEL_UNKNOWN;
}
|
fix a small bug in channel_type_name
|
fix a small bug in channel_type_name
|
C++
|
apache-2.0
|
AveRapina/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench
|
83e63d9bef02d002cc8fcbf067b4695cff12b8b5
|
tutorial/LoadOscProb.C
|
tutorial/LoadOscProb.C
|
void LoadOscProb(TString logLevel = "info") {
// This macro will try to find the OscProb library
// and load it in your session. You may consider
// running it in your rootlogon.C file to be loaded
// by default when you start ROOT.
bool verbose = logLevel.Contains("v");
bool quiet = logLevel.Contains("q") && !verbose;
// ... may be needed for ROOT 5, if "undefined reference to gsl_*" ...
gSystem->Load("libMathMore"); // automatically loads "gsl" and "cblas"
// The library name
TString s("libOscProb.so");
// Search for the library here or in your library paths
gSystem->FindFile(TString::Format("./:../:%s", gSystem->GetDynamicPath()), s);
// Check if library file was found
if(s.Length() == 0){
if(!quiet) std::cout << "libOscProb not found!" << std::endl;
return;
}
// Try to load the library and complain if failed
int errCode = gSystem->Load(s.Data());
// If loading failed, print message
if(errCode != 0 && !quiet){
switch(errCode){
case 1: // Library already loaded
std::cout << "libOscProb already loaded at: ";
TObjArray* libs = TString(gSystem->GetLibraries()).Tokenize(" ");
for(int i =0; i<libs->GetEntries(); i++){
TString lib = libs->At(i)->GetName();
if(lib.Contains("libOscProb.so")) std::cout << lib << std::endl;
}
break;
default: std::cout << "libOscProb could not be loaded. Error Code: " << errCode << std::endl;
}
}
else if(verbose){
std::cout << "Loaded library " << s << std::endl;
}
}
|
#include <iostream>
#include "TString.h"
#include "TSystem.h"
#include "TInterpreter.h"
void LoadOscProb(TString logLevel = "info") {
// This macro will try to find the OscProb library
// and load it in your session. You may consider
// running it in your rootlogon.C file to be loaded
// by default when you start ROOT.
bool verbose = logLevel.Contains("v");
bool quiet = logLevel.Contains("q") && !verbose;
// The library name
TString s("libOscProb.so");
// Search for the library here or in your library paths
gSystem->FindFile(TString::Format("./:../:%s", gSystem->GetDynamicPath()), s);
// Check if library file was found
if(s.Length() == 0){
if(!quiet) std::cout << "libOscProb not found!" << std::endl;
return;
}
// Try to load the library and complain if failed
int errCode = gSystem->Load(s.Data());
// If loading failed, print message
if(errCode != 0 && !quiet){
switch(errCode){
case 1: { // Library already loaded
std::cout << "libOscProb already loaded at: ";
TObjArray* libs = TString(gSystem->GetLibraries()).Tokenize(" ");
for(int i =0; i<libs->GetEntries(); i++){
TString lib = libs->At(i)->GetName();
if(lib.Contains("libOscProb.so")){
std::cout << lib << std::endl;
s = lib;
}
}
break;
}
default: std::cout << "libOscProb could not be loaded. Error Code: " << errCode << std::endl;
}
}
else if(verbose){
std::cout << "Loaded library " << s << std::endl;
}
if(verbose) std::cout << "Adding " << gSystem->DirName(s) << " to include path" << std::endl;
gInterpreter->AddIncludePath(gSystem->DirName(s));
}
|
Remove libMathMore and add OscProb to include path
|
Remove libMathMore and add OscProb to include path
|
C++
|
mit
|
joaoabcoelho/OscProb,joaoabcoelho/OscProb
|
0cd6efa8f1162f106d2a36cc54c7586070c80671
|
include/Cats/Corecat/Stream.hpp
|
include/Cats/Corecat/Stream.hpp
|
/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* 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 CATS_CORECAT_STREAM_HPP
#define CATS_CORECAT_STREAM_HPP
#include <cstdint>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <system_error>
#include <type_traits>
namespace Cats {
namespace Corecat {
namespace Stream {
template <typename T = char>
struct Stream {
using CharType = T;
enum class SeekOrigin { Begin, Current, End };
virtual bool isReadable() const { return false; };
virtual T read() { T data; return read(&data, 1) ? data : 0; }
virtual std::size_t read(T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual T peek() { T data; return peek(&data, 1) ? data : 0; }
virtual std::size_t peek(T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual bool isWriteable() const { return false; };
virtual void write(T data) { write(&data, 1); }
virtual void write(const T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual void flush() { throw std::runtime_error("not implemented"); }
virtual bool isSeekable() const { return false; };
virtual std::intmax_t seek(std::intmax_t /*offset*/, SeekOrigin /*method*/) { throw std::runtime_error("not implemented"); }
virtual std::intmax_t getPosition() { throw std::runtime_error("not implemented"); }
};
template <typename T>
class BufferedStream : public Stream<T> {
private:
Stream<T>* stream;
public:
BufferedStream(Stream<T>& stream_) : stream(&stream) {}
Stream<T>& getStream() { return *stream; }
void setStream(Stream<T>& stream_) { stream = &stream_; }
};
template <typename T, typename = void>
class WrapperStream;
template <>
class WrapperStream<std::FILE*> : public Stream<> {
private:
std::FILE* file;
public:
WrapperStream(std::FILE* file_) : file(file_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override {
std::size_t ret = std::fread(data, 1, size, file);
return ret;
}
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override {
std::fwrite(data, 1, size, file);
}
void flush() override { std::fflush(file); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
int ori;
switch(origin) {
case SeekOrigin::Begin: ori = SEEK_SET; break;
case SeekOrigin::Current: ori = SEEK_CUR; break;
case SeekOrigin::End: ori = SEEK_END; break;
default: throw std::runtime_error("invalid origin");
}
std::fseek(file, offset, ori);
return getPosition();
}
std::intmax_t getPosition() override {
return std::ftell(file);
}
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::istream, T>::value && !std::is_base_of<std::ostream, T>::value>::type>
: public Stream<> {
private:
std::istream* is;
public:
WrapperStream(std::istream& is_) : is(&is_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override { is->read(data, size); return is->gcount(); }
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
is->seekg(offset, dir);
return getPosition();
}
std::intmax_t getPosition() override { return is->tellg(); }
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::ostream, T>::value && !std::is_base_of<std::istream, T>::value>::type>
: public Stream<> {
private:
std::ostream* os;
public:
WrapperStream(std::ostream& os_) : os(&os_) {}
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override { os->write(data, size); }
void flush() override { os->flush(); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
os->seekp(offset, dir);
return getPosition();
}
std::intmax_t getPosition() override { return os->tellp(); }
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::iostream, T>::value>::type>
: public Stream<> {
private:
std::iostream* ios;
public:
WrapperStream(std::iostream& ios_) : ios(&ios_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override { ios->read(data, size); return ios->gcount(); }
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override { ios->write(data, size); }
void flush() override { ios->flush(); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
return ios->rdbuf()->pubseekoff(static_cast<std::iostream::pos_type>(offset), dir);
}
std::intmax_t getPosition() override { return ios->tellg(); }
};
template <typename T>
inline WrapperStream<T> createWrapperStream(T& t) { return WrapperStream<T>(t); }
}
}
}
#endif
|
/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* 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 CATS_CORECAT_STREAM_HPP
#define CATS_CORECAT_STREAM_HPP
#include <cstdint>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <memory>
#include <system_error>
#include <type_traits>
namespace Cats {
namespace Corecat {
namespace Stream {
template <typename T = char>
struct Stream {
using CharType = T;
enum class SeekOrigin { Begin, Current, End };
virtual bool isReadable() const { return false; };
virtual T read() { T data; return read(&data, 1) ? data : 0; }
virtual std::size_t read(T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual T peek() { T data; return peek(&data, 1) ? data : 0; }
virtual std::size_t peek(T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual bool isWriteable() const { return false; };
virtual void write(T data) { write(&data, 1); }
virtual void write(const T* /*data*/, std::size_t /*size*/) { throw std::runtime_error("not implemented"); }
virtual void flush() { throw std::runtime_error("not implemented"); }
virtual bool isSeekable() const { return false; };
virtual std::intmax_t seek(std::intmax_t /*offset*/, SeekOrigin /*method*/) { throw std::runtime_error("not implemented"); }
virtual std::intmax_t getPosition() { throw std::runtime_error("not implemented"); }
};
template <typename T>
class StreamBuffer {
private:
T* data;
T* start;
T* end;
std::size_t size;
std::size_t avail;
public:
StreamBuffer(std::size_t size_ = 4096) : data(new T[size_]), size(data), end(data), size(size_), avail() {}
void read(T* data_, std::size_t count) noexcept {
if(start - data + count < size) {
std::copy(start, start + count, data_);
start += count;
} else {
auto p = std::copy(start, data + size, data_);
start = data + count - (p - data_);
std::copy(data, start, p);
}
avail -= size;
}
};
template <typename T>
class BufferedStream : public Stream<T> {
private:
Stream<T>* stream;
StreamBuffer<T> readBuffer;
StreamBuffer<T> writeBuffer;
public:
BufferedStream(Stream<T>& stream_) : stream(&stream), readBuffer(), writeBuffer() {}
bool isReadable() const override { return stream->isReadable(); };
bool isWriteable() const override { return stream->isWriteable(); };
bool isSeekable() const override { return stream->isSeekable(); };
Stream<T>& getStream() { return *stream; }
void setStream(Stream<T>& stream_) { stream = &stream_; }
};
template <typename T, typename = void>
class WrapperStream;
template <>
class WrapperStream<std::FILE*> : public Stream<> {
private:
std::FILE* file;
public:
WrapperStream(std::FILE* file_) : file(file_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override {
std::size_t ret = std::fread(data, 1, size, file);
return ret;
}
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override {
std::fwrite(data, 1, size, file);
}
void flush() override { std::fflush(file); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
int ori;
switch(origin) {
case SeekOrigin::Begin: ori = SEEK_SET; break;
case SeekOrigin::Current: ori = SEEK_CUR; break;
case SeekOrigin::End: ori = SEEK_END; break;
default: throw std::runtime_error("invalid origin");
}
std::fseek(file, offset, ori);
return getPosition();
}
std::intmax_t getPosition() override {
return std::ftell(file);
}
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::istream, T>::value && !std::is_base_of<std::ostream, T>::value>::type> :
public Stream<> {
private:
std::istream* is;
public:
WrapperStream(std::istream& is_) : is(&is_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override { is->read(data, size); return is->gcount(); }
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
is->seekg(offset, dir);
return getPosition();
}
std::intmax_t getPosition() override { return is->tellg(); }
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::ostream, T>::value && !std::is_base_of<std::istream, T>::value>::type> :
public Stream<> {
private:
std::ostream* os;
public:
WrapperStream(std::ostream& os_) : os(&os_) {}
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override { os->write(data, size); }
void flush() override { os->flush(); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
os->seekp(offset, dir);
return getPosition();
}
std::intmax_t getPosition() override { return os->tellp(); }
};
template <typename T>
class WrapperStream<T, typename std::enable_if<std::is_base_of<std::iostream, T>::value>::type> :
public Stream<> {
private:
std::iostream* ios;
public:
WrapperStream(std::iostream& ios_) : ios(&ios_) {}
bool isReadable() const override { return true; };
std::size_t read(char* data, std::size_t size) override { ios->read(data, size); return ios->gcount(); }
bool isWriteable() const override { return true; };
void write(const char* data, std::size_t size) override { ios->write(data, size); }
void flush() override { ios->flush(); };
bool isSeekable() const override { return true; };
std::intmax_t seek(std::intmax_t offset, SeekOrigin origin) override {
std::ios_base::seekdir dir;
switch(origin) {
case SeekOrigin::Begin: dir = std::ios_base::beg; break;
case SeekOrigin::Current: dir = std::ios_base::cur; break;
case SeekOrigin::End: dir = std::ios_base::end; break;
default: throw std::runtime_error("invalid origin");
}
return ios->rdbuf()->pubseekoff(static_cast<std::iostream::pos_type>(offset), dir);
}
std::intmax_t getPosition() override { return ios->tellg(); }
};
template <typename T>
inline WrapperStream<T> createWrapperStream(T& t) { return WrapperStream<T>(t); }
}
}
}
#endif
|
Add StreamBuffer
|
Add StreamBuffer
|
C++
|
mit
|
SuperSodaSea/Corecat
|
90bda4a2d65ac924a935acf019cd4b36488cb18e
|
src/bp/Request.cxx
|
src/bp/Request.cxx
|
/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Request.hxx"
#include "Connection.hxx"
#include "http_server/Request.hxx"
#include "args.hxx"
#include "strmap.hxx"
#include "istream/istream.hxx"
Request::Request(BpInstance &_instance, BpConnection &_connection,
HttpServerRequest &_request)
:pool(_request.pool),
instance(_instance),
connection(_connection),
logger(connection.logger),
request(_request)
{
session_id.Clear();
}
bool
Request::IsProcessorEnabled() const
{
return translate.response->views->HasProcessor();
}
void
Request::DiscardRequestBody()
{
if (body != nullptr) {
Istream *old_body = body;
body = nullptr;
old_body->CloseUnused();
}
}
void
Request::ParseArgs()
{
assert(args == nullptr);
if (uri.args.IsEmpty()) {
args = nullptr;
translate.request.param = nullptr;
translate.request.session = nullptr;
return;
}
args = args_parse(&pool, uri.args.data, uri.args.size);
translate.request.param = args->Remove("translate");
translate.request.session = nullptr;
}
|
/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Request.hxx"
#include "Connection.hxx"
#include "http_server/Request.hxx"
#include "args.hxx"
#include "strmap.hxx"
#include "istream/istream.hxx"
Request::Request(BpInstance &_instance, BpConnection &_connection,
HttpServerRequest &_request)
:pool(_request.pool),
instance(_instance),
connection(_connection),
logger(connection.logger),
request(_request)
{
session_id.Clear();
}
bool
Request::IsProcessorEnabled() const
{
return translate.response->views->HasProcessor();
}
void
Request::DiscardRequestBody()
{
if (body != nullptr)
std::exchange(body, nullptr)->CloseUnused();
}
void
Request::ParseArgs()
{
assert(args == nullptr);
if (uri.args.IsEmpty()) {
args = nullptr;
translate.request.param = nullptr;
translate.request.session = nullptr;
return;
}
args = args_parse(&pool, uri.args.data, uri.args.size);
translate.request.param = args->Remove("translate");
translate.request.session = nullptr;
}
|
use std::exchange()
|
bp/Request: use std::exchange()
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
dfdde00ba6266e0b1fcc9ded51abe5dbc67e8840
|
include/Cats/Corecat/String.hpp
|
include/Cats/Corecat/String.hpp
|
/*
*
* MIT License
*
* Copyright (c) 2016 The Cats Project
*
* 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 CATS_CORECAT_STRING_HPP
#define CATS_CORECAT_STRING_HPP
#include <cstdlib>
#include <cstring>
#include <iostream>
namespace Cats {
namespace Corecat {
class StringView {
private:
const char* data;
std::size_t length;
public:
StringView() = default;
StringView(const char* data_) : data(data_), length(std::strlen(data_)) {}
StringView(const char* data_, std::size_t length_) : data(data_), length(length_) {}
StringView(const StringView& src) = default;
~StringView() = default;
StringView& operator =(const StringView& src) = default;
bool operator ==(StringView sv) const noexcept {
if(length != sv.length) return false;
const char* p = data;
const char* q = sv.data;
for(const char* end = data + length; p != end; ++p, ++q) if(*p != *q) return false;
return true;
}
bool operator !=(StringView sv) const noexcept { return !(*this == sv); }
const char* getData() const noexcept { return data; }
std::size_t getLength() const noexcept { return length; }
};
inline std::ostream& operator <<(std::ostream& stream, StringView sv) {
stream.write(sv.getData(), sv.getLength());
return stream;
}
}
}
#endif
|
/*
*
* MIT License
*
* Copyright (c) 2016 The Cats Project
*
* 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 CATS_CORECAT_STRING_HPP
#define CATS_CORECAT_STRING_HPP
#include <cstdlib>
#include <cstring>
#include <iostream>
namespace Cats {
namespace Corecat {
class StringView {
private:
const char* data;
std::size_t length;
public:
StringView() = default;
StringView(const char* data_) : data(data_), length(std::strlen(data_)) {}
StringView(const char* data_, std::size_t length_) : data(data_), length(length_) {}
StringView(const StringView& src) = default;
~StringView() = default;
StringView& operator =(const StringView& src) = default;
const char& operator [](std::size_t index) const noexcept { return data[index]; }
bool operator ==(StringView sv) const noexcept {
if(length != sv.length) return false;
const char* p = data;
const char* q = sv.data;
for(const char* end = data + length; p != end; ++p, ++q) if(*p != *q) return false;
return true;
}
bool operator !=(StringView sv) const noexcept { return !(*this == sv); }
const char* getData() const noexcept { return data; }
void setData(const char* data_) noexcept { data = data_; }
std::size_t getLength() const noexcept { return length; }
void setLength(std::size_t length_) noexcept { length = length_; }
};
inline std::ostream& operator <<(std::ostream& stream, StringView sv) {
stream.write(sv.getData(), sv.getLength());
return stream;
}
}
}
#endif
|
Update StringView
|
Update StringView
|
C++
|
mit
|
SuperSodaSea/Corecat
|
842211c0028c12857c877aba069de598b6f8f569
|
include/VBE/system/Keyboard.hpp
|
include/VBE/system/Keyboard.hpp
|
#ifndef KEYBOARD_HPP
#define KEYBOARD_HPP
///
/// \brief The Keyboard class provides support to read the keyboard.
///
class Keyboard {
public:
///
/// \brief Contains all supported keys.
///
enum Key {
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
A,
AC_BACK,
AC_BOOKMARKS,
AC_FORWARD,
AC_HOME,
AC_REFRESH,
AC_SEARCH,
AC_STOP,
Again,
AltErase,
Quote,
Application,
AudioMute,
AudioNext,
AudioPlay,
AudioPrev,
AuidoStop,
B,
Backslash,
Backspace,
BrightnessDown,
BrightnessUp,
C,
Calculator,
Cancel,
Capslock,
Clear,
ClearAgain,
Comma,
Computer,
Copy,
CrSel,
CurrencySubUnit,
CurrencyUnit,
Cut,
D,
DecimalSeparator,
Delete,
DisplaySwitch,
Down,
E,
Eject,
End,
Equals,
Escape,
Execute,
Exsel,
F,
F1,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F2,
F20,
F21,
F22,
F23,
F24,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
Find,
G,
BackQuote,
H,
Help,
Home,
I,
Insert,
J,
K,
KBDIllumDown,
KBDIllumToggle,
KBDIllumUp,
Keypad0,
Keypad00,
Keypad000,
Keypad1,
Keypad2,
Keypad3,
Keypad4,
Keypad5,
Keypad6,
Keypad7,
Keypad8,
Keypad9,
KeypadA,
KeypadAmpersand,
KeypadAt,
KeypadB,
KeypadBackspace,
KeypadBinary,
KeypadC,
KeypadClear,
KeypadClearEntry,
KeypadColon,
KeypadComma,
KeypadD,
KeypadDoubleAmpersand,
KeypadDoubleVerticalBar,
KeypadDecimal,
KeypadDivide,
KeypadE,
KeypadEnter,
KeypadEquals,
KeypadEqualsAS400,
KeypadExclamation,
KeypadF,
KeypadGreater,
KeypadHash,
KeypadHexadecimal,
KeypadLBrace,
KeypadLParenthesis,
KeypadLess,
KeypadMemAdd,
KeypadMemClear,
KeypadMemDivide,
KeypadMemMultiply,
KeypadMemRecall,
KeypadMemStore,
KeypadMemSubstract,
KeypadMinus,
KeypadMultiply,
KeypadOctal,
KeypadPercent,
KeypadPeriod,
KeypadPlus,
KeypadPlusMinus,
KeypadPower,
KeypadRBrace,
KeypadRParenthesis,
KeypadSpace,
KeypadTab,
KeypadVerticalBar,
KeypadXor,
L,
LAlt,
LControl,
Left,
LBracket,
LGUI,
LShift,
M,
Mail,
MediaSelect,
Menu,
Minus,
Mode,
Mute,
N,
NumLockClear,
O,
Oper,
Out,
P,
PageDown,
PageUp,
Paste,
Pause,
Period,
Power,
PrintScren,
Prior,
Q,
R,
RAlt,
RControl,
Return,
Return2,
RGUI,
Right,
RBracket,
RShift,
S,
ScrollLock,
Select,
Semicolont,
Separator,
Slash,
Sleep,
Space,
Stop,
Sysreq,
T,
Tab,
ThousandsSeparator,
U,
Undo,
Unknown,
UP,
V,
VolumeDown,
VolumeUp,
W,
WWW,
X,
Y,
Z,
Ampersand,
Asterisk,
At,
Caret,
Colon,
Dollar,
Exclamation,
Greater,
Hash,
LParenthesis,
Less,
Percent,
Plus,
Question,
DoubleQuote,
RParenthesis,
Underscore,
KeyCount
};
///
/// \brief Tells whether the given key is pressed (held down)
///
static bool pressed(Key k);
///
/// \brief Tells whether the given key has just been pressed (It was not pressed on the last frame and now it is.)
///
static bool justPressed(Key k);
///
/// \brief Tells whether the given key has just been released (It was pressed on the last frame and it's now released.)
///
static bool justReleased(Key k);
private:
static void init();
static void update();
static bool oldKeyPresses[Keyboard::KeyCount];
friend class Window;
};
///
/// @class Keyboard Keyboard.hpp "enviroment/Keyboard.hpp"
/// @ingroup System
///
/// You can use this class within an init Environment to access the current
/// keyboard device's state. Not all keys are supported in all devices and will
/// never be marked as pressed. The state of this device will be updated to
/// match recieved events whenever Environment::update() is called.
///
/// A Key will just be pressed for one frame (one update()) call. Then held for
/// an indefinite number of frames and released right after. For Example, if the
/// user pressed the A Key on frame 1 and released it on frame 4, this would
/// register (updating the environment every frame of course):
///
/// - Frame 1
/// + Key Keyboard::A is pressed
/// + Key Keyboard::A is held
/// + Key Keyboard::A is not released
/// - Frame 2
/// + Key Keyboard::A is not pressed
/// + Key Keyboard::A is held
/// + Key Keyboard::A is not released
/// - Frame 3
/// + Key Keyboard::A is not pressed
/// + Key Keyboard::A is held
/// + Key Keyboard::A is not released
/// - Frame 4
/// + Key Keyboard::A is not pressed
/// + Key Keyboard::A is not held
/// + Key Keyboard::A is released
///
/// @see Environment
#endif // KEYBOARD_HPP
|
#ifndef KEYBOARD_HPP
#define KEYBOARD_HPP
///
/// \brief The Keyboard class provides support to read the keyboard.
///
class Keyboard {
public:
///
/// \brief Contains all supported keys.
///
enum Key {
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
A,
AC_BACK,
AC_BOOKMARKS,
AC_FORWARD,
AC_HOME,
AC_REFRESH,
AC_SEARCH,
AC_STOP,
Again,
AltErase,
Quote,
Application,
AudioMute,
AudioNext,
AudioPlay,
AudioPrev,
AuidoStop,
B,
Backslash,
Backspace,
BrightnessDown,
BrightnessUp,
C,
Calculator,
Cancel,
Capslock,
Clear,
ClearAgain,
Comma,
Computer,
Copy,
CrSel,
CurrencySubUnit,
CurrencyUnit,
Cut,
D,
DecimalSeparator,
Delete,
DisplaySwitch,
Down,
E,
Eject,
End,
Equals,
Escape,
Execute,
Exsel,
F,
F1,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F2,
F20,
F21,
F22,
F23,
F24,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
Find,
G,
BackQuote,
H,
Help,
Home,
I,
Insert,
J,
K,
KBDIllumDown,
KBDIllumToggle,
KBDIllumUp,
Keypad0,
Keypad00,
Keypad000,
Keypad1,
Keypad2,
Keypad3,
Keypad4,
Keypad5,
Keypad6,
Keypad7,
Keypad8,
Keypad9,
KeypadA,
KeypadAmpersand,
KeypadAt,
KeypadB,
KeypadBackspace,
KeypadBinary,
KeypadC,
KeypadClear,
KeypadClearEntry,
KeypadColon,
KeypadComma,
KeypadD,
KeypadDoubleAmpersand,
KeypadDoubleVerticalBar,
KeypadDecimal,
KeypadDivide,
KeypadE,
KeypadEnter,
KeypadEquals,
KeypadEqualsAS400,
KeypadExclamation,
KeypadF,
KeypadGreater,
KeypadHash,
KeypadHexadecimal,
KeypadLBrace,
KeypadLParenthesis,
KeypadLess,
KeypadMemAdd,
KeypadMemClear,
KeypadMemDivide,
KeypadMemMultiply,
KeypadMemRecall,
KeypadMemStore,
KeypadMemSubstract,
KeypadMinus,
KeypadMultiply,
KeypadOctal,
KeypadPercent,
KeypadPeriod,
KeypadPlus,
KeypadPlusMinus,
KeypadPower,
KeypadRBrace,
KeypadRParenthesis,
KeypadSpace,
KeypadTab,
KeypadVerticalBar,
KeypadXor,
L,
LAlt,
LControl,
Left,
LBracket,
LGUI,
LShift,
M,
Mail,
MediaSelect,
Menu,
Minus,
Mode,
Mute,
N,
NumLockClear,
O,
Oper,
Out,
P,
PageDown,
PageUp,
Paste,
Pause,
Period,
Power,
PrintScren,
Prior,
Q,
R,
RAlt,
RControl,
Return,
Return2,
RGUI,
Right,
RBracket,
RShift,
S,
ScrollLock,
Select,
Semicolont,
Separator,
Slash,
Sleep,
Space,
Stop,
Sysreq,
T,
Tab,
ThousandsSeparator,
U,
Undo,
Unknown,
UP,
V,
VolumeDown,
VolumeUp,
W,
WWW,
X,
Y,
Z,
Ampersand,
Asterisk,
At,
Caret,
Colon,
Dollar,
Exclamation,
Greater,
Hash,
LParenthesis,
Less,
Percent,
Plus,
Question,
DoubleQuote,
RParenthesis,
Underscore,
KeyCount
};
///
/// \brief Tells whether the given key is pressed (held down)
///
static bool pressed(Key k);
///
/// \brief Tells whether the given key has just been pressed (It was not pressed on the last frame and now it is.)
///
static bool justPressed(Key k);
///
/// \brief Tells whether the given key has just been released (It was pressed on the last frame and it's now released.)
///
static bool justReleased(Key k);
private:
static void init();
static void update();
static bool oldKeyPresses[Keyboard::KeyCount];
friend class Window;
};
///
/// @class Keyboard Keyboard.hpp "enviroment/Keyboard.hpp"
/// @ingroup System
///
/// You can use this class within an init Environment to access the current
/// keyboard device's state. Not all keys are supported in all devices and will
/// never be marked as pressed. The state of this device will be updated to
/// match recieved events whenever Environment::update() is called.
///
/// A Key will be 'just pressed' for only one frame (one update()) call. Then held for
/// an indefinite number of frames and released right after. For Example, if the
/// user pressed the A Key on frame 1 and released it on frame 4, this would
/// register (updating the environment every frame of course):
///
/// - Frame 1
/// + Key Keyboard::A is just pressed
/// + Key Keyboard::A is pressed
/// + Key Keyboard::A is not just released
/// - Frame 2
/// + Key Keyboard::A is not just pressed
/// + Key Keyboard::A is held
/// + Key Keyboard::A is not just released
/// - Frame 3
/// + Key Keyboard::A is not just pressed
/// + Key Keyboard::A is held
/// + Key Keyboard::A is not just released
/// - Frame 4
/// + Key Keyboard::A is not just pressed
/// + Key Keyboard::A is not held
/// + Key Keyboard::A is just released
///
/// @see Environment
#endif // KEYBOARD_HPP
|
Update keyboard docs
|
Update keyboard docs
|
C++
|
mit
|
Towerthousand/VBE
|
8ed1daaae035e2473ff101d7ebf0f45068eaa67e
|
include/aleph/topology/Spine.hh
|
include/aleph/topology/Spine.hh
|
#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
namespace aleph
{
namespace topology
{
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
bool principal = true;
for( auto&& t : K )
{
if( s.dimension() < t.dimension() )
{
if( intersect(s,t) == s )
principal = false;
}
}
return principal;
}
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
bool admissible = true;
for( auto&& t : K )
{
}
return admissible;
}
} // namespace topology
} // namespace aleph
#endif
|
#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__
#include <aleph/topology/Intersections.hh>
#include <vector>
namespace aleph
{
namespace topology
{
/**
Checks whether a simplex in a simplicial complex is principal, i.e.
whether it is not a proper face of any other simplex in K.
*/
template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
bool principal = true;
for( auto&& t : K )
{
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ s..
if( s.dimension()+1 == t.dimension() )
{
if( intersect(s,t) == s )
principal = false;
}
}
return principal;
}
/**
Checks whether a simplex in a simplicial complex is admissible, i.e.
the simplex is *principal* and has at least one free face.
*/
template <class SimplicialComplex, class Simplex> bool isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
if( !isPrincipal(s,K) )
return false;
// Check whether a free face exists ----------------------------------
std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
std::vector<bool> admissible( faces.size(), false );
std::size_t i = 0;
for( auto&& face : faces )
{
for( auto&& t : K )
{
// This check assumes that the simplicial complex is valid, so it
// suffices to search faces in one dimension _below_ t.
if( face.dimension()+1 == t.dimension() && t != s )
{
if( intersect(face,t) == face )
{
admissible[i] = false;
break;
}
}
}
++i;
}
return admissible;
}
} // namespace topology
} // namespace aleph
#endif
|
Check for admissible and principal simplices
|
Check for admissible and principal simplices
|
C++
|
mit
|
Submanifold/Aleph,Submanifold/Aleph,Submanifold/Aleph
|
b47cf8a4a1898f5959fb3d79212b4f02470d77c2
|
include/estd/CircularBuffer.hpp
|
include/estd/CircularBuffer.hpp
|
/**
* \file
* \brief CircularBuffer class header
*
* \author Copyright (C) 2020 Kamil Szczygiel https://distortec.com https://freddiechopin.info
*
* \par License
* 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 https://mozilla.org/MPL/2.0/.
*/
#ifndef ESTD_CIRCULARBUFFER_HPP_
#define ESTD_CIRCULARBUFFER_HPP_
#include <memory>
namespace estd
{
/**
* \brief Thread-safe, lock-free circular buffer for single-producer and single-consumer
*
* Distinction between empty and full buffer is possible because most significant bits of read and write positions are
* used as single-bit counters of wrap-arounds. This limits the capacity of buffer to SIZE_MAX / 2 elements, but allows
* full utilization of storage (no free slot is needed).
*
* \tparam T is the type of data in circular buffer
* \tparam Deleter is the templated deleter which will be used for disposing of storage when circular buffer is
* destructed, should be either estd::DummyDeleter for static storage or `std::default_delete` for dynamic storage
*/
template<typename T, template<typename> class Deleter>
class CircularBuffer
{
public:
/// type of uninitialized storage for data
using Storage = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
/// unique_ptr (with deleter) to Storage[]
using StorageUniquePointer = std::unique_ptr<Storage[], Deleter<Storage[]>>;
/// type of data in circular buffer
using ValueType = T;
/**
* \brief CircularBuffer's constructor
*
* \param [in] storageUniquePointer is a rvalue reference to StorageUniquePointer with storage for circular buffer
* elements (sufficiently large for \a capacity elements, each sizeof(T) bytes long) and appropriate deleter
* \param [in] capacity is the number of elements in storage array, should be less than or equal to SIZE_MAX / 2
*/
constexpr CircularBuffer(StorageUniquePointer&& storageUniquePointer, const size_t capacity) :
storageUniquePointer_{std::move(storageUniquePointer)},
capacity_{capacity & positionMask_},
readPosition_{},
writePosition_{}
{
}
/**
* \brief CircularBuffer's destructor
*
* Destructs all elements remaining in the circular buffer.
*/
~CircularBuffer()
{
while (isEmpty() == false)
pop();
}
/**
* \brief Emplaces the element in circular buffer.
*
* \pre Circular buffer is not full.
*
* \tparam Args are types of arguments for constructor of T
*
* \param [in] args are arguments for constructor of T
*/
template<typename... Args>
void emplace(Args&&... args)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{std::forward<Args>(args)...};
writePosition_ = incrementPosition(writePosition);
}
/**
* \pre Circular buffer is not empty.
*
* \return const reference to first element on the list
*/
const T& front() const
{
return *reinterpret_cast<T*>(getStorage(readPosition_));
}
/**
* \return maximum number of elements in circular buffer
*/
size_t getCapacity() const
{
return capacity_;
}
/**
* \return total amount of valid elements in circular buffer
*/
size_t getSize() const
{
const auto readPosition = readPosition_ ;
const auto writePosition = writePosition_;
if (isEmpty(readPosition, writePosition) == true)
return {};
const auto capacity = getCapacity();
if (isFull(readPosition, writePosition) == true)
return capacity;
return (capacity - (readPosition & positionMask_) + (writePosition & positionMask_)) % capacity;
}
/**
* \return true if circular buffer is empty, false otherwise
*/
bool isEmpty() const
{
return isEmpty(readPosition_, writePosition_);
}
/**
* \return true if circular buffer is full, false otherwise
*/
bool isFull() const
{
return isFull(readPosition_, writePosition_);
}
/**
* \brief Pops the oldest (first) element from circular buffer.
*
* \pre Circular buffer is not empty.
*/
void pop()
{
const auto readPosition = readPosition_ ;
reinterpret_cast<T*>(getStorage(readPosition))->~T();
readPosition_ = incrementPosition(readPosition);
}
/**
* \brief Pushes the element to circular buffer.
*
* \pre Circular buffer is not full.
*
* \param [in] value is a reference to object that will be pushed, value in circular buffer's storage is
* copy-constructed
*/
void push(const T& value)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{value};
writePosition_ = incrementPosition(writePosition);
}
/**
* \brief Pushes the element to circular buffer.
*
* \pre Circular buffer is not full.
*
* \param [in] value is a rvalue reference to object that will be pushed, value in circular buffer's storage is
* move-constructed
*/
void push(T&& value)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{std::move(value)};
writePosition_ = incrementPosition(writePosition);
}
CircularBuffer(const CircularBuffer&) = delete;
CircularBuffer(CircularBuffer&&) = default;
const CircularBuffer& operator=(const CircularBuffer&) = delete;
CircularBuffer& operator=(CircularBuffer&&) = delete;
private:
/**
* \brief Gets pointer to storage at \a position.
*
* \param [in] position is the selected position
*
* \return pointer to storage at \a position
*/
Storage* getStorage(const size_t position) const
{
const auto maskedPosition = position & positionMask_;
return &storageUniquePointer_[maskedPosition];
}
/**
* \brief Increments given position by 1.
*
* \param [in] position is the position that will be incremented
*
* \return \a position incremented by 1
*/
size_t incrementPosition(const size_t position)
{
const auto maskedPosition = position & positionMask_;
const auto msb = position & msbMask_;
// in case of wrap-around MSB is inverted and position is 0
return maskedPosition + 1 != getCapacity() ? msb | (maskedPosition + 1) : msb ^ msbMask_;
}
/**
* \brief Tests for empty circular buffer.
*
* The buffer is empty if read and write positions are equal, including their MSBs.
*
* \param [in] readPosition is the value of \a readPosition_
* \param [in] writePosition is the value of \a writePosition_
*
* \return true if circular buffer is empty, false otherwise
*/
constexpr static bool isEmpty(const size_t readPosition, const size_t writePosition)
{
return readPosition == writePosition;
}
/**
* \brief Tests for full circular buffer.
*
* The buffer is full if masked read and write positions are equal, but their MSBs are different.
*
* \param [in] readPosition is the value of \a readPosition_
* \param [in] writePosition is the value of \a writePosition_
*
* \return true if circular buffer is full, false otherwise
*/
constexpr static bool isFull(const size_t readPosition, const size_t writePosition)
{
return (readPosition ^ writePosition) == msbMask_;
}
/// bitmask used to extract position from \a readPosition_ or \a writePosition_
constexpr static size_t positionMask_ {SIZE_MAX >> 1};
/// bitmask used to extract MSB from \a readPosition_ or \a writePosition_
constexpr static size_t msbMask_ {~positionMask_};
/// storage for circular buffer elements
const StorageUniquePointer storageUniquePointer_;
/// capacity of an array pointed by \a storageUniquePointer_
size_t capacity_;
/// current read position
volatile size_t readPosition_;
/// current write position
volatile size_t writePosition_;
};
} // namespace estd
#endif // ESTD_CIRCULARBUFFER_HPP_
|
/**
* \file
* \brief CircularBuffer class header
*
* \author Copyright (C) 2020 Kamil Szczygiel https://distortec.com https://freddiechopin.info
*
* \par License
* 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 https://mozilla.org/MPL/2.0/.
*/
#ifndef ESTD_CIRCULARBUFFER_HPP_
#define ESTD_CIRCULARBUFFER_HPP_
#include <memory>
namespace estd
{
/**
* \brief Thread-safe, lock-free circular buffer for single-producer and single-consumer
*
* Distinction between empty and full buffer is possible because most significant bits of read and write positions are
* used as single-bit counters of wrap-arounds. This limits the capacity of buffer to SIZE_MAX / 2 elements, but allows
* full utilization of storage (no free slot is needed).
*
* \tparam T is the type of data in circular buffer
* \tparam Deleter is the templated deleter which will be used for disposing of storage when circular buffer is
* destructed, should be either estd::DummyDeleter for static storage or `std::default_delete` for dynamic storage
*/
template<typename T, template<typename> class Deleter>
class CircularBuffer
{
public:
/// type of uninitialized storage for data
using Storage = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
/// unique_ptr (with deleter) to Storage[]
using StorageUniquePointer = std::unique_ptr<Storage[], Deleter<Storage[]>>;
/// type of data in circular buffer
using ValueType = T;
/**
* \brief CircularBuffer's constructor
*
* \param [in] storageUniquePointer is a rvalue reference to StorageUniquePointer with storage for circular buffer
* elements (sufficiently large for \a capacity elements, each sizeof(T) bytes long) and appropriate deleter
* \param [in] capacity is the number of elements in storage array, should be less than or equal to SIZE_MAX / 2
*/
constexpr CircularBuffer(StorageUniquePointer&& storageUniquePointer, const size_t capacity) :
storageUniquePointer_{std::move(storageUniquePointer)},
capacity_{capacity & positionMask_},
readPosition_{},
writePosition_{}
{
}
/**
* \brief CircularBuffer's destructor
*
* Destructs all elements remaining in the circular buffer.
*/
~CircularBuffer()
{
while (isEmpty() == false)
pop();
}
/**
* \brief Emplaces the element in circular buffer.
*
* \pre Circular buffer is not full.
*
* \tparam Args are types of arguments for constructor of T
*
* \param [in] args are arguments for constructor of T
*/
template<typename... Args>
void emplace(Args&&... args)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{std::forward<Args>(args)...};
writePosition_ = incrementPosition(writePosition);
}
/**
* \pre Circular buffer is not empty.
*
* \return reference to first element on the list
*/
T& front()
{
return *reinterpret_cast<T*>(getStorage(readPosition_));
}
/**
* \pre Circular buffer is not empty.
*
* \return const reference to first element on the list
*/
const T& front() const
{
return *reinterpret_cast<const T*>(getStorage(readPosition_));
}
/**
* \return maximum number of elements in circular buffer
*/
size_t getCapacity() const
{
return capacity_;
}
/**
* \return total amount of valid elements in circular buffer
*/
size_t getSize() const
{
const auto readPosition = readPosition_ ;
const auto writePosition = writePosition_;
if (isEmpty(readPosition, writePosition) == true)
return {};
const auto capacity = getCapacity();
if (isFull(readPosition, writePosition) == true)
return capacity;
return (capacity - (readPosition & positionMask_) + (writePosition & positionMask_)) % capacity;
}
/**
* \return true if circular buffer is empty, false otherwise
*/
bool isEmpty() const
{
return isEmpty(readPosition_, writePosition_);
}
/**
* \return true if circular buffer is full, false otherwise
*/
bool isFull() const
{
return isFull(readPosition_, writePosition_);
}
/**
* \brief Pops the oldest (first) element from circular buffer.
*
* \pre Circular buffer is not empty.
*/
void pop()
{
const auto readPosition = readPosition_ ;
reinterpret_cast<T*>(getStorage(readPosition))->~T();
readPosition_ = incrementPosition(readPosition);
}
/**
* \brief Pushes the element to circular buffer.
*
* \pre Circular buffer is not full.
*
* \param [in] value is a reference to object that will be pushed, value in circular buffer's storage is
* copy-constructed
*/
void push(const T& value)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{value};
writePosition_ = incrementPosition(writePosition);
}
/**
* \brief Pushes the element to circular buffer.
*
* \pre Circular buffer is not full.
*
* \param [in] value is a rvalue reference to object that will be pushed, value in circular buffer's storage is
* move-constructed
*/
void push(T&& value)
{
const auto writePosition = writePosition_;
const auto storage = getStorage(writePosition);
new (storage) T{std::move(value)};
writePosition_ = incrementPosition(writePosition);
}
CircularBuffer(const CircularBuffer&) = delete;
CircularBuffer(CircularBuffer&&) = default;
const CircularBuffer& operator=(const CircularBuffer&) = delete;
CircularBuffer& operator=(CircularBuffer&&) = delete;
private:
/**
* \brief Gets pointer to storage at \a position.
*
* \param [in] position is the selected position
*
* \return pointer to storage at \a position
*/
Storage* getStorage(const size_t position) const
{
const auto maskedPosition = position & positionMask_;
return &storageUniquePointer_[maskedPosition];
}
/**
* \brief Increments given position by 1.
*
* \param [in] position is the position that will be incremented
*
* \return \a position incremented by 1
*/
size_t incrementPosition(const size_t position)
{
const auto maskedPosition = position & positionMask_;
const auto msb = position & msbMask_;
// in case of wrap-around MSB is inverted and position is 0
return maskedPosition + 1 != getCapacity() ? msb | (maskedPosition + 1) : msb ^ msbMask_;
}
/**
* \brief Tests for empty circular buffer.
*
* The buffer is empty if read and write positions are equal, including their MSBs.
*
* \param [in] readPosition is the value of \a readPosition_
* \param [in] writePosition is the value of \a writePosition_
*
* \return true if circular buffer is empty, false otherwise
*/
constexpr static bool isEmpty(const size_t readPosition, const size_t writePosition)
{
return readPosition == writePosition;
}
/**
* \brief Tests for full circular buffer.
*
* The buffer is full if masked read and write positions are equal, but their MSBs are different.
*
* \param [in] readPosition is the value of \a readPosition_
* \param [in] writePosition is the value of \a writePosition_
*
* \return true if circular buffer is full, false otherwise
*/
constexpr static bool isFull(const size_t readPosition, const size_t writePosition)
{
return (readPosition ^ writePosition) == msbMask_;
}
/// bitmask used to extract position from \a readPosition_ or \a writePosition_
constexpr static size_t positionMask_ {SIZE_MAX >> 1};
/// bitmask used to extract MSB from \a readPosition_ or \a writePosition_
constexpr static size_t msbMask_ {~positionMask_};
/// storage for circular buffer elements
const StorageUniquePointer storageUniquePointer_;
/// capacity of an array pointed by \a storageUniquePointer_
size_t capacity_;
/// current read position
volatile size_t readPosition_;
/// current write position
volatile size_t writePosition_;
};
} // namespace estd
#endif // ESTD_CIRCULARBUFFER_HPP_
|
Add non-const version of estd::CircularBuffer::front()
|
Add non-const version of estd::CircularBuffer::front()
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,DISTORTEC/distortos,DISTORTEC/distortos,DISTORTEC/distortos
|
e75354154cff58b412d591182e2b46d54cab8e74
|
include/generator/SvgWriter.hpp
|
include/generator/SvgWriter.hpp
|
// Copyright 2015 Markus Ilmola
// 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.
#ifndef GENERATOR_SVG_HPP
#define GENERATOR_SVG_HPP
#include <algorithm>
#include <sstream>
#include <memory>
#include <map>
#include <gml/gml.hpp>
#include "Iterator.hpp"
#include "MeshVertex.hpp"
#include "PathVertex.hpp"
#include "ShapeVertex.hpp"
#include "Triangle.hpp"
namespace generator {
/// A simple svg writer class for generating preview and debug images.
class SvgWriter {
private:
class BaseElem {
public:
double z_;
gml::dvec3 color_;
BaseElem(double z, const gml::dvec3& color);
virtual ~BaseElem();
// Writes this svg element to a stream.
virtual void stream(std::ostream&) const = 0;
};
class VertexElem : public BaseElem {
public:
gml::dvec3 p_;
VertexElem(const gml::dvec3& p, const gml::dvec3& color);
virtual void stream(std::ostream& os) const override;
};
class LineElem : public BaseElem {
public:
gml::dvec3 p1_, p2_;
LineElem(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& color
);
virtual void stream(std::ostream& os) const override;
};
class TriangleElem : public BaseElem {
public:
std::array<gml::dvec3, 3> p_;
TriangleElem(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3,
const gml::dvec3& color
);
virtual void stream(std::ostream& os) const override;
};
gml::dvec3 project(const gml::dvec3& p) const;
gml::dvec3 normalToColor(const gml::dvec3& normal) const;
gml::uvec2 size_;
gml::dmat4 viewMatrix_;
gml::dmat4 projMatrix_;
gml::dmat4 viewProjMatrix_;
gml::ivec4 viewport_;
gml::dvec3 lightDir_;
bool cullface_;
mutable std::vector<std::unique_ptr<BaseElem>> elems_;
public:
/// @param width Width of the image in pixels
/// @param height Height of the iamge in pixels
SvgWriter(unsigned width, unsigned height);
/// Sets the model view matrix. Default is the identity matrix.
void modelView(const gml::dmat4& matrix);
/// Sets the projection mode to perspective projection.
/// Default is the orthographic.
/// @param fovy Field of view along the y-axis.
/// @param aspect aspect ratio (should usually match the vieport)
void perspective(double fovy, double aspect, double zNear, double zFar);
/// Sets the projection mode to orthographic projection.
/// This is the default.
/// @param left Coordinate that maps to the left edge.
/// @param right Coordinate that maps to the right edge.
void ortho(double left, double right, double bottom, double top);
/// Sets the viewport. Default fills the whole image.
void viewport(int x, int y, unsigned width, unsigned height);
/// Sets if backfacing triangles should be culled. Default is true.
void cullface(bool cullface);
/// Write one point. Drawn as a circle.
void writePoint(
const gml::dvec3& p, const gml::dvec3& color = {0.0, 0.0, 0.0}
);
/// Write one line.
void writeLine(
const gml::dvec3& p1, const gml::dvec3& p2,
const gml::dvec3& color = {0.0, 0.0, 0.0}
);
/// Write one triangle.
void writeTriangle(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3,
const gml::dvec3& color
);
/// Write one triangle with color automatically calculated from light.
void writeTriangle(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3
);
/// Write all shaped edges and optionally vertices, tangents and normals.
template <typename Shape>
void writeShape(
const Shape& shape, bool writeVertices = false, bool writeAxis = false
) {
std::vector<ShapeVertex> vertices{};
for (const auto& vertex : shape.vertices()) {
vertices.push_back(vertex);
}
for (auto e : shape.edges()) {
auto p1 = gml::dvec3{vertices[e.vertices[0]].position, 0.0};
auto p2 = gml::dvec3{vertices[e.vertices[1]].position, 0.0};
writeLine(p1, p2, {0.5, 0.5, 0.5});
}
if (writeAxis) {
for (auto v : vertices) {
auto p1 = gml::dvec3{v.position, 0.0};
auto p2 = gml::dvec3{v.position + 0.1 * v.tangent, 0.0};
auto p3 = gml::dvec3{v.position + 0.1 * v.normal(), 0.0};
writeLine(p1, p2, {0.0, 1.0, 0.0});
writeLine(p1, p3, {1.0, 0.0, 0.0});
}
}
if (writeVertices) {
for (auto v : shape.vertices()) {
writePoint(gml::dvec3{v.position, 0.0});
}
}
}
/// Write all path edges as lines and optionally vertices, tangents, normals
/// and binormals.
template <typename Path>
void writePath(
const Path& path, bool writeVertices = false, bool writeAxis = false
) {
std::vector<PathVertex> vertices{};
for (const auto& temp : path.vertices()) {
vertices.push_back(temp);
}
if (writeAxis) {
for (const auto & v : path.vertices()) {
writeLine(v.position, v.position + 0.1 * v.tangent, {0.0, 0.0, 1.0});
writeLine(v.position, v.position + 0.1 * v.normal, {1.0, 0.0, 0.0});
writeLine(v.position, v.position + 0.1 * v.binormal(), {0.0, 1.0, 0.0});
}
}
if (writeVertices) {
for (const auto& v : path.vertices()) {
writePoint(v.position + 0.001 * v.normal);
}
}
for (const auto & e : path.edges()) {
writeLine(
vertices[e.vertices[0]].position, vertices[e.vertices[1]].position
);
}
}
/// Write all triangles from a mesh.
template <typename Mesh>
void writeMesh(
const Mesh& mesh, bool writeVertices = false, bool writeNormals = false
) {
std::vector<MeshVertex> vertices{};
for (const MeshVertex& vertex : mesh.vertices()) {
vertices.push_back(vertex);
}
for (Triangle t : mesh.triangles()) {
writeTriangle(
vertices[t.vertices[0]].position,
vertices[t.vertices[1]].position,
vertices[t.vertices[2]].position
);
}
if (writeVertices) {
for (const auto & v : vertices) {
writePoint(v.position + 0.001 * v.normal);
}
}
// Normals
if (writeNormals) {
for (const auto & v : vertices) {
writeLine(v.position, v.position + 0.1 * v.normal, {0.0, 0.0, 1.0});
}
}
}
/// Generates svg xml from the data written so far.
std::string str() const;
};
}
#endif
|
// Copyright 2015 Markus Ilmola
// 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.
#ifndef GENERATOR_SVG_HPP
#define GENERATOR_SVG_HPP
#include <array>
#include <algorithm>
#include <sstream>
#include <memory>
#include <map>
#include <vector>
#include <gml/gml.hpp>
#include "Iterator.hpp"
#include "MeshVertex.hpp"
#include "PathVertex.hpp"
#include "ShapeVertex.hpp"
#include "Triangle.hpp"
namespace generator {
/// A simple svg writer class for generating preview and debug images.
class SvgWriter {
private:
class BaseElem {
public:
double z_;
gml::dvec3 color_;
BaseElem(double z, const gml::dvec3& color);
virtual ~BaseElem();
// Writes this svg element to a stream.
virtual void stream(std::ostream&) const = 0;
};
class VertexElem : public BaseElem {
public:
gml::dvec3 p_;
VertexElem(const gml::dvec3& p, const gml::dvec3& color);
virtual void stream(std::ostream& os) const override;
};
class LineElem : public BaseElem {
public:
gml::dvec3 p1_, p2_;
LineElem(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& color
);
virtual void stream(std::ostream& os) const override;
};
class TriangleElem : public BaseElem {
public:
std::array<gml::dvec3, 3> p_;
TriangleElem(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3,
const gml::dvec3& color
);
virtual void stream(std::ostream& os) const override;
};
gml::dvec3 project(const gml::dvec3& p) const;
gml::dvec3 normalToColor(const gml::dvec3& normal) const;
gml::uvec2 size_;
gml::dmat4 viewMatrix_;
gml::dmat4 projMatrix_;
gml::dmat4 viewProjMatrix_;
gml::ivec4 viewport_;
gml::dvec3 lightDir_;
bool cullface_;
mutable std::vector<std::unique_ptr<BaseElem>> elems_;
public:
/// @param width Width of the image in pixels
/// @param height Height of the iamge in pixels
SvgWriter(unsigned width, unsigned height);
/// Sets the model view matrix. Default is the identity matrix.
void modelView(const gml::dmat4& matrix);
/// Sets the projection mode to perspective projection.
/// Default is the orthographic.
/// @param fovy Field of view along the y-axis.
/// @param aspect aspect ratio (should usually match the vieport)
void perspective(double fovy, double aspect, double zNear, double zFar);
/// Sets the projection mode to orthographic projection.
/// This is the default.
/// @param left Coordinate that maps to the left edge.
/// @param right Coordinate that maps to the right edge.
void ortho(double left, double right, double bottom, double top);
/// Sets the viewport. Default fills the whole image.
void viewport(int x, int y, unsigned width, unsigned height);
/// Sets if backfacing triangles should be culled. Default is true.
void cullface(bool cullface);
/// Write one point. Drawn as a circle.
void writePoint(
const gml::dvec3& p, const gml::dvec3& color = {0.0, 0.0, 0.0}
);
/// Write one line.
void writeLine(
const gml::dvec3& p1, const gml::dvec3& p2,
const gml::dvec3& color = {0.0, 0.0, 0.0}
);
/// Write one triangle.
void writeTriangle(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3,
const gml::dvec3& color
);
/// Write one triangle with color automatically calculated from light.
void writeTriangle(
const gml::dvec3& p1, const gml::dvec3& p2, const gml::dvec3& p3
);
/// Write all shaped edges and optionally vertices, tangents and normals.
template <typename Shape>
void writeShape(
const Shape& shape, bool writeVertices = false, bool writeAxis = false
) {
std::vector<ShapeVertex> vertices{};
for (const auto& vertex : shape.vertices()) {
vertices.push_back(vertex);
}
for (auto e : shape.edges()) {
auto p1 = gml::dvec3{vertices[e.vertices[0]].position, 0.0};
auto p2 = gml::dvec3{vertices[e.vertices[1]].position, 0.0};
writeLine(p1, p2, {0.5, 0.5, 0.5});
}
if (writeAxis) {
for (auto v : vertices) {
auto p1 = gml::dvec3{v.position, 0.0};
auto p2 = gml::dvec3{v.position + 0.1 * v.tangent, 0.0};
auto p3 = gml::dvec3{v.position + 0.1 * v.normal(), 0.0};
writeLine(p1, p2, {0.0, 1.0, 0.0});
writeLine(p1, p3, {1.0, 0.0, 0.0});
}
}
if (writeVertices) {
for (auto v : shape.vertices()) {
writePoint(gml::dvec3{v.position, 0.0});
}
}
}
/// Write all path edges as lines and optionally vertices, tangents, normals
/// and binormals.
template <typename Path>
void writePath(
const Path& path, bool writeVertices = false, bool writeAxis = false
) {
std::vector<PathVertex> vertices{};
for (const auto& temp : path.vertices()) {
vertices.push_back(temp);
}
if (writeAxis) {
for (const auto & v : path.vertices()) {
writeLine(v.position, v.position + 0.1 * v.tangent, {0.0, 0.0, 1.0});
writeLine(v.position, v.position + 0.1 * v.normal, {1.0, 0.0, 0.0});
writeLine(v.position, v.position + 0.1 * v.binormal(), {0.0, 1.0, 0.0});
}
}
if (writeVertices) {
for (const auto& v : path.vertices()) {
writePoint(v.position + 0.001 * v.normal);
}
}
for (const auto & e : path.edges()) {
writeLine(
vertices[e.vertices[0]].position, vertices[e.vertices[1]].position
);
}
}
/// Write all triangles from a mesh.
template <typename Mesh>
void writeMesh(
const Mesh& mesh, bool writeVertices = false, bool writeNormals = false
) {
std::vector<MeshVertex> vertices{};
for (const MeshVertex& vertex : mesh.vertices()) {
vertices.push_back(vertex);
}
for (Triangle t : mesh.triangles()) {
writeTriangle(
vertices[t.vertices[0]].position,
vertices[t.vertices[1]].position,
vertices[t.vertices[2]].position
);
}
if (writeVertices) {
for (const auto & v : vertices) {
writePoint(v.position + 0.001 * v.normal);
}
}
// Normals
if (writeNormals) {
for (const auto & v : vertices) {
writeLine(v.position, v.position + 0.1 * v.normal, {0.0, 0.0, 1.0});
}
}
}
/// Generates svg xml from the data written so far.
std::string str() const;
};
}
#endif
|
Fix some #include errors
|
Fix some #include errors
|
C++
|
lgpl-2.1
|
ilmola/generator
|
f791c2ac76a5a42c02fb019a959fba5c1c2993c1
|
include/mdds/grid_map_types.hpp
|
include/mdds/grid_map_types.hpp
|
/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* 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 __MDDS_GRID_MAP_TYPES_HPP__
#define __MDDS_GRID_MAP_TYPES_HPP__
#include <vector>
namespace mdds { namespace gridmap {
typedef int cell_t;
const cell_t celltype_numeric = 0;
const cell_t celltype_string = 1;
const cell_t celltype_index = 2;
const cell_t celltype_boolean = 3;
const cell_t celltype_user_start = 50;
struct base_cell_block
{
cell_t type;
base_cell_block(cell_t _t) : type(_t) {}
};
inline cell_t get_block_type(const base_cell_block& blk)
{
return blk.type;
}
template<typename _Self, cell_t _TypeId, typename _Data>
struct cell_block : public base_cell_block, public std::vector<_Data>
{
cell_block() : base_cell_block(_TypeId), std::vector<_Data>() {}
cell_block(size_t n) : base_cell_block(_TypeId), std::vector<_Data>(n) {}
static _Self& get(base_cell_block& block)
{
if (block.type != _TypeId)
throw general_error("incorrect block type.");
return static_cast<_Self&>(block);
}
static const _Self& get(const base_cell_block& block)
{
if (block.type != _TypeId)
throw general_error("incorrect block type.");
return static_cast<const _Self&>(block);
}
};
template<cell_t _TypeId, typename _Data>
struct default_cell_block : public cell_block<default_cell_block<_TypeId,_Data>, _TypeId, _Data>
{
typedef cell_block<default_cell_block, _TypeId, _Data> base_type;
default_cell_block() : base_type() {}
default_cell_block(size_t n) : base_type(n) {}
};
template<cell_t _TypeId, typename _Data>
struct managed_cell_block : public cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*>
{
typedef cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*> base_type;
using base_type::begin;
using base_type::end;
using base_type::reserve;
using base_type::push_back;
managed_cell_block() : base_type() {}
managed_cell_block(size_t n) : base_type(n) {}
managed_cell_block(const managed_cell_block& r)
{
reserve(r.size());
typename managed_cell_block::const_iterator it = r.begin(), it_end = r.end();
for (; it != it_end; ++it)
push_back(new _Data(**it));
}
~managed_cell_block()
{
std::for_each(begin(), end(), default_deleter<_Data>());
}
};
}}
#endif
|
/*************************************************************************
*
* Copyright (c) 2012 Kohei Yoshida
*
* 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 __MDDS_GRID_MAP_TYPES_HPP__
#define __MDDS_GRID_MAP_TYPES_HPP__
#include <vector>
namespace mdds { namespace gridmap {
typedef int cell_t;
const cell_t celltype_numeric = 0;
const cell_t celltype_string = 1;
const cell_t celltype_index = 2;
const cell_t celltype_boolean = 3;
const cell_t celltype_user_start = 50;
struct base_cell_block
{
cell_t type;
base_cell_block(cell_t _t) : type(_t) {}
};
inline cell_t get_block_type(const base_cell_block& blk)
{
return blk.type;
}
template<typename _Self, cell_t _TypeId, typename _Data>
class cell_block : public base_cell_block, public std::vector<_Data>
{
protected:
cell_block() : base_cell_block(_TypeId), std::vector<_Data>() {}
cell_block(size_t n) : base_cell_block(_TypeId), std::vector<_Data>(n) {}
public:
static _Self& get(base_cell_block& block)
{
if (block.type != _TypeId)
throw general_error("incorrect block type.");
return static_cast<_Self&>(block);
}
static const _Self& get(const base_cell_block& block)
{
if (block.type != _TypeId)
throw general_error("incorrect block type.");
return static_cast<const _Self&>(block);
}
};
template<cell_t _TypeId, typename _Data>
struct default_cell_block : public cell_block<default_cell_block<_TypeId,_Data>, _TypeId, _Data>
{
typedef cell_block<default_cell_block, _TypeId, _Data> base_type;
default_cell_block() : base_type() {}
default_cell_block(size_t n) : base_type(n) {}
};
template<cell_t _TypeId, typename _Data>
struct managed_cell_block : public cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*>
{
typedef cell_block<managed_cell_block<_TypeId,_Data>, _TypeId, _Data*> base_type;
using base_type::begin;
using base_type::end;
using base_type::reserve;
using base_type::push_back;
managed_cell_block() : base_type() {}
managed_cell_block(size_t n) : base_type(n) {}
managed_cell_block(const managed_cell_block& r)
{
reserve(r.size());
typename managed_cell_block::const_iterator it = r.begin(), it_end = r.end();
for (; it != it_end; ++it)
push_back(new _Data(**it));
}
~managed_cell_block()
{
std::for_each(begin(), end(), default_deleter<_Data>());
}
};
}}
#endif
|
Set proper visibility for constructors of cell_block.
|
Set proper visibility for constructors of cell_block.
To avoid getting instantiated directly in the client code.
|
C++
|
mit
|
Distrotech/mdds,Distrotech/mdds
|
c19c7c56c0ae85b120382525b1547766e4eeac17
|
include/sot/core/robot-utils.hh
|
include/sot/core/robot-utils.hh
|
/*
* Copyright 2017, 2019
* LAAS-CNRS
* A. Del Prete, T. Flayols, O. Stasse, F. Bailly
*
*/
#ifndef __sot_torque_control_common_H__
#define __sot_torque_control_common_H__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#ifdef BOOST_MPL_LIMIT_VECTOR_SIZE
#pragma push_macro("BOOST_MPL_LIMIT_VECTOR_SIZE")
#undef BOOST_MPL_LIMIT_VECTOR_SIZE
#define BOOST_MPL_LIMIT_VECTOR_SIZE_PUSH
#endif
#ifdef BOOST_MPL_LIMIT_LIST_SIZE
#pragma push_macro("BOOST_MPL_LIMIT_LIST_SIZE")
#undef BOOST_MPL_LIMIT_LIST_SIZE
#define BOOST_MPL_LIMIT_LIST_SIZE_PUSH
#endif
#include <boost/property_tree/ptree.hpp>
#ifdef BOOST_MPL_LIMIT_VECTOR_SIZE_PUSH
#pragma pop_macro("BOOST_MPL_LIMIT_VECTOR_SIZE")
#endif
#ifdef BOOST_MPL_LIMIT_LIST_SIZE_PUSH
#pragma pop_macro("BOOST_MPL_LIMIT_LIST_SIZE")
#endif
#include "boost/assign.hpp"
#include <dynamic-graph/linear-algebra.h>
#include <dynamic-graph/logger.h>
#include <dynamic-graph/signal-helper.h>
#include <map>
#include <sot/core/matrix-geometry.hh>
namespace dynamicgraph {
namespace sot {
struct SOT_CORE_EXPORT JointLimits {
double upper;
double lower;
JointLimits() : upper(0.0), lower(0.0) {}
JointLimits(double l, double u) : upper(u), lower(l) {}
};
typedef Eigen::VectorXd::Index Index;
class SOT_CORE_EXPORT ExtractJointMimics {
public:
/// Constructor
ExtractJointMimics(std::string & robot_model);
/// Get mimic joints.
const std::vector<std::string> &get_mimic_joints();
private:
void go_through(boost::property_tree::ptree &pt,int level, int stage);
// Create empty property tree object
boost::property_tree::ptree tree_;
std::vector<std::string> mimic_joints_;
std::string current_joint_name_;
void go_through_full();
};
struct SOT_CORE_EXPORT ForceLimits {
Eigen::VectorXd upper;
Eigen::VectorXd lower;
ForceLimits() : upper(Vector6d::Zero()), lower(Vector6d::Zero()) {}
ForceLimits(const Eigen::VectorXd &l, const Eigen::VectorXd &u)
: upper(u), lower(l) {}
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT ForceUtil {
std::map<Index, ForceLimits> m_force_id_to_limits;
std::map<std::string, Index> m_name_to_force_id;
std::map<Index, std::string> m_force_id_to_name;
Index m_Force_Id_Left_Hand, m_Force_Id_Right_Hand, m_Force_Id_Left_Foot,
m_Force_Id_Right_Foot;
void set_name_to_force_id(const std::string &name, const Index &force_id);
void set_force_id_to_limits(const Index &force_id,
const dynamicgraph::Vector &lf,
const dynamicgraph::Vector &uf);
void create_force_id_to_name_map();
Index get_id_from_name(const std::string &name);
const std::string &get_name_from_id(Index idx);
std::string cp_get_name_from_id(Index idx);
const ForceLimits &get_limits_from_id(Index force_id);
ForceLimits cp_get_limits_from_id(Index force_id);
Index get_force_id_left_hand() { return m_Force_Id_Left_Hand; }
void set_force_id_left_hand(Index anId) { m_Force_Id_Left_Hand = anId; }
Index get_force_id_right_hand() { return m_Force_Id_Right_Hand; }
void set_force_id_right_hand(Index anId) { m_Force_Id_Right_Hand = anId; }
Index get_force_id_left_foot() { return m_Force_Id_Left_Foot; }
void set_force_id_left_foot(Index anId) { m_Force_Id_Left_Foot = anId; }
Index get_force_id_right_foot() { return m_Force_Id_Right_Foot; }
void set_force_id_right_foot(Index anId) { m_Force_Id_Right_Foot = anId; }
void display(std::ostream &out) const;
}; // struct ForceUtil
struct SOT_CORE_EXPORT FootUtil {
/// Position of the foot soles w.r.t. the frame of the foot
dynamicgraph::Vector m_Right_Foot_Sole_XYZ;
/// Position of the force/torque sensors w.r.t. the frame of the hosting link
dynamicgraph::Vector m_Right_Foot_Force_Sensor_XYZ;
std::string m_Left_Foot_Frame_Name;
std::string m_Right_Foot_Frame_Name;
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT HandUtil {
std::string m_Left_Hand_Frame_Name;
std::string m_Right_Hand_Frame_Name;
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT RobotUtil {
public:
RobotUtil();
/// Forces data
ForceUtil m_force_util;
/// Foot information
FootUtil m_foot_util;
/// Hand information
HandUtil m_hand_util;
/// Map from the urdf index to the SoT index.
std::vector<Index> m_urdf_to_sot;
/// Nb of Dofs for the robot.
std::size_t m_nbJoints;
/// Map from the name to the id.
std::map<std::string, Index> m_name_to_id;
/// The map between id and name
std::map<Index, std::string> m_id_to_name;
/// The joint limits map.
std::map<Index, JointLimits> m_limits_map;
/// The name of the joint IMU is attached to
std::string m_imu_joint_name;
/// This method creates the map between id and name.
/// It is called each time a new link between id and name is inserted
/// (i.e. when set_name_to_id is called).
void create_id_to_name_map();
/// URDF file path
std::string m_urdf_filename;
dynamicgraph::Vector m_dgv_urdf_to_sot;
/** Given a joint name it finds the associated joint id.
* If the specified joint name is not found it returns -1;
* @param name Name of the joint to find.
* @return The id of the specified joint, -1 if not found. */
const Index &get_id_from_name(const std::string &name);
/** Given a joint id it finds the associated joint name.
* If the specified joint is not found it returns "Joint name not found";
* @param id Id of the joint to find.
* @return The name of the specified joint, "Joint name not found" if not
* found. */
/// Get the joint name from its index
const std::string &get_name_from_id(Index id);
/// Set relation between the name and the SoT id
void set_name_to_id(const std::string &jointName, const Index &jointId);
/// Set the map between urdf index and sot index
void set_urdf_to_sot(const std::vector<Index> &urdf_to_sot);
void set_urdf_to_sot(const dynamicgraph::Vector &urdf_to_sot);
/// Set the limits (lq,uq) for joint idx
void set_joint_limits_for_id(const Index &idx, const double &lq,
const double &uq);
bool joints_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool joints_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
bool velocity_urdf_to_sot(ConstRefVector q_urdf, ConstRefVector v_urdf,
RefVector v_sot);
bool velocity_sot_to_urdf(ConstRefVector q_urdf, ConstRefVector v_sot,
RefVector v_urdf);
bool config_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool config_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
bool base_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool base_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
/** Given a joint id it finds the associated joint limits.
* If the specified joint is not found it returns JointLimits(0,0).
* @param id Id of the joint to find.
* @return The limits of the specified joint, JointLimits(0,0) if not found.
*/
const JointLimits &get_joint_limits_from_id(Index id);
JointLimits cp_get_joint_limits_from_id(Index id);
/** \name Logger related methods */
/** \{*/
/// \brief Send messages \c msg with level \c t. Add string \c file and \c
/// line to message.
void sendMsg(const std::string &msg, MsgType t = MSG_TYPE_INFO,
const std::string &lineId = "");
/// \brief Specify the verbosity level of the logger.
void setLoggerVerbosityLevel(LoggerVerbosity lv) { logger_.setVerbosity(lv); }
/// \brief Get the logger's verbosity level.
LoggerVerbosity getLoggerVerbosityLevel() { return logger_.getVerbosity(); };
void display(std::ostream &os) const;
/**{ \name Handling general parameters */
/** \brief Set a parameter of type string.
If parameter_name already exists the value is overwritten.
If not it is inserted.
*/
template < typename Type>
void set_parameter(const std::string ¶meter_name,
const Type ¶meter_value)
{
try
{
typedef boost::property_tree::ptree::path_type path;
path apath(parameter_name,'/');
property_tree_.put<Type>(apath,parameter_value);
}
catch(const boost::property_tree::ptree_error &e)
{
DYNAMIC_GRAPH_ENTITY_ERROR(*this) << "Robot utils: parameter path is invalid " << '\n'
<< " for set_parameter("
<< parameter_name << ")\n"
<< e.what() << '\n';
return;
}
}
/** \brief Get a parameter of type string.
If parameter_name already exists the value is overwritten.
If not it is inserted.
@param parameter_name: Name of the parameter
Return false if the parameter is not found.
*/
template <typename Type>
Type get_parameter(const std::string ¶meter_name)
{
try {
boost::property_tree::ptree::path_type apath(parameter_name,'/');
const Type & res= property_tree_.get<Type>(apath);
return res;
}
catch(const boost::property_tree::ptree_error &e)
{
std::ostringstream oss;
oss << "Robot utils: parameter path is invalid " << '\n'
<< " for get_parameter("
<< parameter_name << ")\n"
<< e.what() << std::endl;
sendMsg(oss.str(),
MSG_TYPE_ERROR);
}
}
/** @} */
/** Access to property tree directly */
boost::property_tree::ptree & get_property_tree();
protected:
Logger logger_;
/** \brief Map of the parameters: map of strings. */
std::map<std::string, std::string> parameters_strings_;
/** \brief Property tree */
boost::property_tree::ptree property_tree_;
}; // struct RobotUtil
/// Accessors - This should be changed to RobotUtilPtrShared
typedef std::shared_ptr<RobotUtil> RobotUtilShrPtr;
RobotUtilShrPtr RefVoidRobotUtil();
RobotUtilShrPtr getRobotUtil(std::string &robotName);
bool isNameInRobotUtil(std::string &robotName);
RobotUtilShrPtr createRobotUtil(std::string &robotName);
std::shared_ptr<std::vector<std::string> > getListOfRobots();
bool base_se3_to_sot(ConstRefVector pos, ConstRefMatrix R, RefVector q_sot);
} // namespace sot
} // namespace dynamicgraph
#endif // sot_torque_control_common_h_
|
/*
* Copyright 2017, 2019
* LAAS-CNRS
* A. Del Prete, T. Flayols, O. Stasse, F. Bailly
*
*/
#ifndef __sot_torque_control_common_H__
#define __sot_torque_control_common_H__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#ifdef BOOST_MPL_LIMIT_VECTOR_SIZE
#pragma push_macro("BOOST_MPL_LIMIT_VECTOR_SIZE")
#undef BOOST_MPL_LIMIT_VECTOR_SIZE
#define BOOST_MPL_LIMIT_VECTOR_SIZE_PUSH
#endif
#ifdef BOOST_MPL_LIMIT_LIST_SIZE
#pragma push_macro("BOOST_MPL_LIMIT_LIST_SIZE")
#undef BOOST_MPL_LIMIT_LIST_SIZE
#define BOOST_MPL_LIMIT_LIST_SIZE_PUSH
#endif
#include <boost/property_tree/ptree.hpp>
#ifdef BOOST_MPL_LIMIT_VECTOR_SIZE_PUSH
#pragma pop_macro("BOOST_MPL_LIMIT_VECTOR_SIZE")
#endif
#ifdef BOOST_MPL_LIMIT_LIST_SIZE_PUSH
#pragma pop_macro("BOOST_MPL_LIMIT_LIST_SIZE")
#endif
#include "boost/assign.hpp"
#include <dynamic-graph/linear-algebra.h>
#include <dynamic-graph/logger.h>
#include <dynamic-graph/signal-helper.h>
#include <map>
#include <sot/core/matrix-geometry.hh>
namespace dynamicgraph {
namespace sot {
struct SOT_CORE_EXPORT JointLimits {
double upper;
double lower;
JointLimits() : upper(0.0), lower(0.0) {}
JointLimits(double l, double u) : upper(u), lower(l) {}
};
typedef Eigen::VectorXd::Index Index;
class SOT_CORE_EXPORT ExtractJointMimics {
public:
/// Constructor
ExtractJointMimics(std::string & robot_model);
/// Get mimic joints.
const std::vector<std::string> &get_mimic_joints();
private:
void go_through(boost::property_tree::ptree &pt,int level, int stage);
// Create empty property tree object
boost::property_tree::ptree tree_;
std::vector<std::string> mimic_joints_;
std::string current_joint_name_;
void go_through_full();
};
struct SOT_CORE_EXPORT ForceLimits {
Eigen::VectorXd upper;
Eigen::VectorXd lower;
ForceLimits() : upper(Vector6d::Zero()), lower(Vector6d::Zero()) {}
ForceLimits(const Eigen::VectorXd &l, const Eigen::VectorXd &u)
: upper(u), lower(l) {}
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT ForceUtil {
std::map<Index, ForceLimits> m_force_id_to_limits;
std::map<std::string, Index> m_name_to_force_id;
std::map<Index, std::string> m_force_id_to_name;
Index m_Force_Id_Left_Hand, m_Force_Id_Right_Hand, m_Force_Id_Left_Foot,
m_Force_Id_Right_Foot;
void set_name_to_force_id(const std::string &name, const Index &force_id);
void set_force_id_to_limits(const Index &force_id,
const dynamicgraph::Vector &lf,
const dynamicgraph::Vector &uf);
void create_force_id_to_name_map();
Index get_id_from_name(const std::string &name);
const std::string &get_name_from_id(Index idx);
std::string cp_get_name_from_id(Index idx);
const ForceLimits &get_limits_from_id(Index force_id);
ForceLimits cp_get_limits_from_id(Index force_id);
Index get_force_id_left_hand() { return m_Force_Id_Left_Hand; }
void set_force_id_left_hand(Index anId) { m_Force_Id_Left_Hand = anId; }
Index get_force_id_right_hand() { return m_Force_Id_Right_Hand; }
void set_force_id_right_hand(Index anId) { m_Force_Id_Right_Hand = anId; }
Index get_force_id_left_foot() { return m_Force_Id_Left_Foot; }
void set_force_id_left_foot(Index anId) { m_Force_Id_Left_Foot = anId; }
Index get_force_id_right_foot() { return m_Force_Id_Right_Foot; }
void set_force_id_right_foot(Index anId) { m_Force_Id_Right_Foot = anId; }
void display(std::ostream &out) const;
}; // struct ForceUtil
struct SOT_CORE_EXPORT FootUtil {
/// Position of the foot soles w.r.t. the frame of the foot
dynamicgraph::Vector m_Right_Foot_Sole_XYZ;
/// Position of the force/torque sensors w.r.t. the frame of the hosting link
dynamicgraph::Vector m_Right_Foot_Force_Sensor_XYZ;
std::string m_Left_Foot_Frame_Name;
std::string m_Right_Foot_Frame_Name;
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT HandUtil {
std::string m_Left_Hand_Frame_Name;
std::string m_Right_Hand_Frame_Name;
void display(std::ostream &os) const;
};
struct SOT_CORE_EXPORT RobotUtil {
public:
RobotUtil();
/// Forces data
ForceUtil m_force_util;
/// Foot information
FootUtil m_foot_util;
/// Hand information
HandUtil m_hand_util;
/// Map from the urdf index to the SoT index.
std::vector<Index> m_urdf_to_sot;
/// Nb of Dofs for the robot.
std::size_t m_nbJoints;
/// Map from the name to the id.
std::map<std::string, Index> m_name_to_id;
/// The map between id and name
std::map<Index, std::string> m_id_to_name;
/// The joint limits map.
std::map<Index, JointLimits> m_limits_map;
/// The name of the joint IMU is attached to
std::string m_imu_joint_name;
/// This method creates the map between id and name.
/// It is called each time a new link between id and name is inserted
/// (i.e. when set_name_to_id is called).
void create_id_to_name_map();
/// URDF file path
std::string m_urdf_filename;
dynamicgraph::Vector m_dgv_urdf_to_sot;
/** Given a joint name it finds the associated joint id.
* If the specified joint name is not found it returns -1;
* @param name Name of the joint to find.
* @return The id of the specified joint, -1 if not found. */
const Index &get_id_from_name(const std::string &name);
/** Given a joint id it finds the associated joint name.
* If the specified joint is not found it returns "Joint name not found";
* @param id Id of the joint to find.
* @return The name of the specified joint, "Joint name not found" if not
* found. */
/// Get the joint name from its index
const std::string &get_name_from_id(Index id);
/// Set relation between the name and the SoT id
void set_name_to_id(const std::string &jointName, const Index &jointId);
/// Set the map between urdf index and sot index
void set_urdf_to_sot(const std::vector<Index> &urdf_to_sot);
void set_urdf_to_sot(const dynamicgraph::Vector &urdf_to_sot);
/// Set the limits (lq,uq) for joint idx
void set_joint_limits_for_id(const Index &idx, const double &lq,
const double &uq);
bool joints_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool joints_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
bool velocity_urdf_to_sot(ConstRefVector q_urdf, ConstRefVector v_urdf,
RefVector v_sot);
bool velocity_sot_to_urdf(ConstRefVector q_urdf, ConstRefVector v_sot,
RefVector v_urdf);
bool config_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool config_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
bool base_urdf_to_sot(ConstRefVector q_urdf, RefVector q_sot);
bool base_sot_to_urdf(ConstRefVector q_sot, RefVector q_urdf);
/** Given a joint id it finds the associated joint limits.
* If the specified joint is not found it returns JointLimits(0,0).
* @param id Id of the joint to find.
* @return The limits of the specified joint, JointLimits(0,0) if not found.
*/
const JointLimits &get_joint_limits_from_id(Index id);
JointLimits cp_get_joint_limits_from_id(Index id);
/** \name Logger related methods */
/** \{*/
/// \brief Send messages \c msg with level \c t. Add string \c file and \c
/// line to message.
void sendMsg(const std::string &msg, MsgType t = MSG_TYPE_INFO,
const std::string &lineId = "");
/// \brief Specify the verbosity level of the logger.
void setLoggerVerbosityLevel(LoggerVerbosity lv) { logger_.setVerbosity(lv); }
/// \brief Get the logger's verbosity level.
LoggerVerbosity getLoggerVerbosityLevel() { return logger_.getVerbosity(); };
void display(std::ostream &os) const;
/**{ \name Handling general parameters */
/** \brief Set a parameter of type string.
If parameter_name already exists the value is overwritten.
If not it is inserted.
*/
template < typename Type>
void set_parameter(const std::string ¶meter_name,
const Type ¶meter_value)
{
try
{
typedef boost::property_tree::ptree::path_type path;
path apath(parameter_name,'/');
property_tree_.put<Type>(apath,parameter_value);
}
catch(const boost::property_tree::ptree_error &e)
{
DYNAMIC_GRAPH_ENTITY_ERROR(*this) << "Robot utils: parameter path is invalid " << '\n'
<< " for set_parameter("
<< parameter_name << ")\n"
<< e.what() << '\n';
return;
}
}
/** \brief Get a parameter of type string.
If parameter_name already exists the value is overwritten.
If not it is inserted.
@param parameter_name: Name of the parameter
Return false if the parameter is not found.
*/
template <typename Type>
Type get_parameter(const std::string ¶meter_name)
{
try {
boost::property_tree::ptree::path_type apath(parameter_name,'/');
const Type & res= property_tree_.get<Type>(apath);
return res;
}
catch(const boost::property_tree::ptree_error &e)
{
DYNAMIC_GRAPH_ENTITY_ERROR(*this) << "Robot utils: parameter path is invalid " << '\n'
<< " for get_parameter("
<< parameter_name << ")\n"
<< e.what() << '\n';
}
}
/** @} */
/** Access to property tree directly */
boost::property_tree::ptree & get_property_tree();
protected:
Logger logger_;
/** \brief Map of the parameters: map of strings. */
std::map<std::string, std::string> parameters_strings_;
/** \brief Property tree */
boost::property_tree::ptree property_tree_;
}; // struct RobotUtil
/// Accessors - This should be changed to RobotUtilPtrShared
typedef std::shared_ptr<RobotUtil> RobotUtilShrPtr;
RobotUtilShrPtr RefVoidRobotUtil();
RobotUtilShrPtr getRobotUtil(std::string &robotName);
bool isNameInRobotUtil(std::string &robotName);
RobotUtilShrPtr createRobotUtil(std::string &robotName);
std::shared_ptr<std::vector<std::string> > getListOfRobots();
bool base_se3_to_sot(ConstRefVector pos, ConstRefMatrix R, RefVector q_sot);
} // namespace sot
} // namespace dynamicgraph
#endif // sot_torque_control_common_h_
|
Update include/sot/core/robot-utils.hh
|
Update include/sot/core/robot-utils.hh
Co-authored-by: Joseph Mirabel <[email protected]>
|
C++
|
bsd-2-clause
|
stack-of-tasks/sot-core,stack-of-tasks/sot-core,stack-of-tasks/sot-core
|
41e6936bcefc8827e702daaf154a709ccd4bfeb7
|
unsupported/test/kronecker_product.cpp
|
unsupported/test/kronecker_product.cpp
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Kolja Brix <[email protected]>
// Copyright (C) 2011 Andreas Platen <[email protected]>
// Copyright (C) 2012 Chen-Pang He <[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/.
#include "sparse.h"
#include <Eigen/SparseExtra>
#include <Eigen/KroneckerProduct>
template<typename MatrixType>
void check_dimension(const MatrixType& ab, const unsigned int rows, const unsigned int cols)
{
VERIFY_IS_EQUAL(ab.rows(), rows);
VERIFY_IS_EQUAL(ab.cols(), cols);
}
template<typename MatrixType>
void check_kronecker_product(const MatrixType& ab)
{
VERIFY_IS_EQUAL(ab.rows(), 6);
VERIFY_IS_EQUAL(ab.cols(), 6);
VERIFY_IS_EQUAL(ab.nonZeros(), 36);
VERIFY_IS_APPROX(ab.coeff(0,0), -0.4017367630386106);
VERIFY_IS_APPROX(ab.coeff(0,1), 0.1056863433932735);
VERIFY_IS_APPROX(ab.coeff(0,2), -0.7255206194554212);
VERIFY_IS_APPROX(ab.coeff(0,3), 0.1908653336744706);
VERIFY_IS_APPROX(ab.coeff(0,4), 0.350864567234111);
VERIFY_IS_APPROX(ab.coeff(0,5), -0.0923032108308013);
VERIFY_IS_APPROX(ab.coeff(1,0), 0.415417514804677);
VERIFY_IS_APPROX(ab.coeff(1,1), -0.2369227701722048);
VERIFY_IS_APPROX(ab.coeff(1,2), 0.7502275131458511);
VERIFY_IS_APPROX(ab.coeff(1,3), -0.4278731019742696);
VERIFY_IS_APPROX(ab.coeff(1,4), -0.3628129162264507);
VERIFY_IS_APPROX(ab.coeff(1,5), 0.2069210808481275);
VERIFY_IS_APPROX(ab.coeff(2,0), 0.05465890160863986);
VERIFY_IS_APPROX(ab.coeff(2,1), -0.2634092511419858);
VERIFY_IS_APPROX(ab.coeff(2,2), 0.09871180285793758);
VERIFY_IS_APPROX(ab.coeff(2,3), -0.4757066334017702);
VERIFY_IS_APPROX(ab.coeff(2,4), -0.04773740823058334);
VERIFY_IS_APPROX(ab.coeff(2,5), 0.2300535609645254);
VERIFY_IS_APPROX(ab.coeff(3,0), -0.8172945853260133);
VERIFY_IS_APPROX(ab.coeff(3,1), 0.2150086428359221);
VERIFY_IS_APPROX(ab.coeff(3,2), 0.5825113847292743);
VERIFY_IS_APPROX(ab.coeff(3,3), -0.1532433770097174);
VERIFY_IS_APPROX(ab.coeff(3,4), -0.329383387282399);
VERIFY_IS_APPROX(ab.coeff(3,5), 0.08665207912033064);
VERIFY_IS_APPROX(ab.coeff(4,0), 0.8451267514863225);
VERIFY_IS_APPROX(ab.coeff(4,1), -0.481996458918977);
VERIFY_IS_APPROX(ab.coeff(4,2), -0.6023482390791535);
VERIFY_IS_APPROX(ab.coeff(4,3), 0.3435339347164565);
VERIFY_IS_APPROX(ab.coeff(4,4), 0.3406002157428891);
VERIFY_IS_APPROX(ab.coeff(4,5), -0.1942526344200915);
VERIFY_IS_APPROX(ab.coeff(5,0), 0.1111982482925399);
VERIFY_IS_APPROX(ab.coeff(5,1), -0.5358806424754169);
VERIFY_IS_APPROX(ab.coeff(5,2), -0.07925446559335647);
VERIFY_IS_APPROX(ab.coeff(5,3), 0.3819388757769038);
VERIFY_IS_APPROX(ab.coeff(5,4), 0.04481475387219876);
VERIFY_IS_APPROX(ab.coeff(5,5), -0.2159688616158057);
}
template<typename MatrixType>
void check_sparse_kronecker_product(const MatrixType& ab)
{
VERIFY_IS_EQUAL(ab.rows(), 12);
VERIFY_IS_EQUAL(ab.cols(), 10);
VERIFY_IS_EQUAL(ab.nonZeros(), 3*2);
VERIFY_IS_APPROX(ab.coeff(3,0), -0.04);
VERIFY_IS_APPROX(ab.coeff(5,1), 0.05);
VERIFY_IS_APPROX(ab.coeff(0,6), -0.08);
VERIFY_IS_APPROX(ab.coeff(2,7), 0.10);
VERIFY_IS_APPROX(ab.coeff(6,8), 0.12);
VERIFY_IS_APPROX(ab.coeff(8,9), -0.15);
}
void test_kronecker_product()
{
// DM = dense matrix; SM = sparse matrix
Matrix<double, 2, 3> DM_a;
MatrixXd DM_b(3,2);
SparseMatrix<double> SM_a(2,3);
SparseMatrix<double> SM_b(3,2);
SM_a.insert(0,0) = DM_a.coeffRef(0,0) = -0.4461540300782201;
SM_a.insert(0,1) = DM_a.coeffRef(0,1) = -0.8057364375283049;
SM_a.insert(0,2) = DM_a.coeffRef(0,2) = 0.3896572459516341;
SM_a.insert(1,0) = DM_a.coeffRef(1,0) = -0.9076572187376921;
SM_a.insert(1,1) = DM_a.coeffRef(1,1) = 0.6469156566545853;
SM_a.insert(1,2) = DM_a.coeffRef(1,2) = -0.3658010398782789;
SM_b.insert(0,0) = DM_b.coeffRef(0,0) = 0.9004440976767099;
SM_b.insert(0,1) = DM_b.coeffRef(0,1) = -0.2368830858139832;
SM_b.insert(1,0) = DM_b.coeffRef(1,0) = -0.9311078389941825;
SM_b.insert(1,1) = DM_b.coeffRef(1,1) = 0.5310335762980047;
SM_b.insert(2,0) = DM_b.coeffRef(2,0) = -0.1225112806872035;
SM_b.insert(2,1) = DM_b.coeffRef(2,1) = 0.5903998022741264;
SparseMatrix<double,RowMajor> SM_row_a(SM_a), SM_row_b(SM_b);
// test kroneckerProduct(DM_block,DM,DM_fixedSize)
Matrix<double, 6, 6> DM_fix_ab = kroneckerProduct(DM_a.topLeftCorner<2,3>(),DM_b);
CALL_SUBTEST(check_kronecker_product(DM_fix_ab));
// test kroneckerProduct(DM,DM,DM_block)
MatrixXd DM_block_ab(10,15);
DM_block_ab.block<6,6>(2,5) = kroneckerProduct(DM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(DM_block_ab.block<6,6>(2,5)));
// test kroneckerProduct(DM,DM,DM)
MatrixXd DM_ab = kroneckerProduct(DM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(DM_ab));
// test kroneckerProduct(SM,DM,SM)
SparseMatrix<double> SM_ab = kroneckerProduct(SM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SparseMatrix<double,RowMajor> SM_ab2 = kroneckerProduct(SM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(DM,SM,SM)
SM_ab.setZero();
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(DM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SM_ab2.setZero();
SM_ab2.insert(0,0)=37.0;
SM_ab2 = kroneckerProduct(DM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(SM,SM,SM)
SM_ab.resize(2,33);
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SM_ab2.resize(5,11);
SM_ab2.insert(0,0)=37.0;
SM_ab2 = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(SM,SM,SM) with sparse pattern
SM_a.resize(4,5);
SM_b.resize(3,2);
SM_a.resizeNonZeros(0);
SM_b.resizeNonZeros(0);
SM_a.insert(1,0) = -0.1;
SM_a.insert(0,3) = -0.2;
SM_a.insert(2,4) = 0.3;
SM_a.finalize();
SM_b.insert(0,0) = 0.4;
SM_b.insert(2,1) = -0.5;
SM_b.finalize();
SM_ab.resize(1,1);
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_sparse_kronecker_product(SM_ab));
// test dimension of result of kroneckerProduct(DM,DM,DM)
MatrixXd DM_a2(2,1);
MatrixXd DM_b2(5,4);
MatrixXd DM_ab2 = kroneckerProduct(DM_a2,DM_b2);
CALL_SUBTEST(check_dimension(DM_ab2,2*5,1*4));
DM_a2.resize(10,9);
DM_b2.resize(4,8);
DM_ab2 = kroneckerProduct(DM_a2,DM_b2);
CALL_SUBTEST(check_dimension(DM_ab2,10*4,9*8));
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Kolja Brix <[email protected]>
// Copyright (C) 2011 Andreas Platen <[email protected]>
// Copyright (C) 2012 Chen-Pang He <[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/.
#include "sparse.h"
#include <Eigen/SparseExtra>
#include <Eigen/KroneckerProduct>
template<typename MatrixType>
void check_dimension(const MatrixType& ab, const int rows, const int cols)
{
VERIFY_IS_EQUAL(ab.rows(), rows);
VERIFY_IS_EQUAL(ab.cols(), cols);
}
template<typename MatrixType>
void check_kronecker_product(const MatrixType& ab)
{
VERIFY_IS_EQUAL(ab.rows(), 6);
VERIFY_IS_EQUAL(ab.cols(), 6);
VERIFY_IS_EQUAL(ab.nonZeros(), 36);
VERIFY_IS_APPROX(ab.coeff(0,0), -0.4017367630386106);
VERIFY_IS_APPROX(ab.coeff(0,1), 0.1056863433932735);
VERIFY_IS_APPROX(ab.coeff(0,2), -0.7255206194554212);
VERIFY_IS_APPROX(ab.coeff(0,3), 0.1908653336744706);
VERIFY_IS_APPROX(ab.coeff(0,4), 0.350864567234111);
VERIFY_IS_APPROX(ab.coeff(0,5), -0.0923032108308013);
VERIFY_IS_APPROX(ab.coeff(1,0), 0.415417514804677);
VERIFY_IS_APPROX(ab.coeff(1,1), -0.2369227701722048);
VERIFY_IS_APPROX(ab.coeff(1,2), 0.7502275131458511);
VERIFY_IS_APPROX(ab.coeff(1,3), -0.4278731019742696);
VERIFY_IS_APPROX(ab.coeff(1,4), -0.3628129162264507);
VERIFY_IS_APPROX(ab.coeff(1,5), 0.2069210808481275);
VERIFY_IS_APPROX(ab.coeff(2,0), 0.05465890160863986);
VERIFY_IS_APPROX(ab.coeff(2,1), -0.2634092511419858);
VERIFY_IS_APPROX(ab.coeff(2,2), 0.09871180285793758);
VERIFY_IS_APPROX(ab.coeff(2,3), -0.4757066334017702);
VERIFY_IS_APPROX(ab.coeff(2,4), -0.04773740823058334);
VERIFY_IS_APPROX(ab.coeff(2,5), 0.2300535609645254);
VERIFY_IS_APPROX(ab.coeff(3,0), -0.8172945853260133);
VERIFY_IS_APPROX(ab.coeff(3,1), 0.2150086428359221);
VERIFY_IS_APPROX(ab.coeff(3,2), 0.5825113847292743);
VERIFY_IS_APPROX(ab.coeff(3,3), -0.1532433770097174);
VERIFY_IS_APPROX(ab.coeff(3,4), -0.329383387282399);
VERIFY_IS_APPROX(ab.coeff(3,5), 0.08665207912033064);
VERIFY_IS_APPROX(ab.coeff(4,0), 0.8451267514863225);
VERIFY_IS_APPROX(ab.coeff(4,1), -0.481996458918977);
VERIFY_IS_APPROX(ab.coeff(4,2), -0.6023482390791535);
VERIFY_IS_APPROX(ab.coeff(4,3), 0.3435339347164565);
VERIFY_IS_APPROX(ab.coeff(4,4), 0.3406002157428891);
VERIFY_IS_APPROX(ab.coeff(4,5), -0.1942526344200915);
VERIFY_IS_APPROX(ab.coeff(5,0), 0.1111982482925399);
VERIFY_IS_APPROX(ab.coeff(5,1), -0.5358806424754169);
VERIFY_IS_APPROX(ab.coeff(5,2), -0.07925446559335647);
VERIFY_IS_APPROX(ab.coeff(5,3), 0.3819388757769038);
VERIFY_IS_APPROX(ab.coeff(5,4), 0.04481475387219876);
VERIFY_IS_APPROX(ab.coeff(5,5), -0.2159688616158057);
}
template<typename MatrixType>
void check_sparse_kronecker_product(const MatrixType& ab)
{
VERIFY_IS_EQUAL(ab.rows(), 12);
VERIFY_IS_EQUAL(ab.cols(), 10);
VERIFY_IS_EQUAL(ab.nonZeros(), 3*2);
VERIFY_IS_APPROX(ab.coeff(3,0), -0.04);
VERIFY_IS_APPROX(ab.coeff(5,1), 0.05);
VERIFY_IS_APPROX(ab.coeff(0,6), -0.08);
VERIFY_IS_APPROX(ab.coeff(2,7), 0.10);
VERIFY_IS_APPROX(ab.coeff(6,8), 0.12);
VERIFY_IS_APPROX(ab.coeff(8,9), -0.15);
}
void test_kronecker_product()
{
// DM = dense matrix; SM = sparse matrix
Matrix<double, 2, 3> DM_a;
MatrixXd DM_b(3,2);
SparseMatrix<double> SM_a(2,3);
SparseMatrix<double> SM_b(3,2);
SM_a.insert(0,0) = DM_a.coeffRef(0,0) = -0.4461540300782201;
SM_a.insert(0,1) = DM_a.coeffRef(0,1) = -0.8057364375283049;
SM_a.insert(0,2) = DM_a.coeffRef(0,2) = 0.3896572459516341;
SM_a.insert(1,0) = DM_a.coeffRef(1,0) = -0.9076572187376921;
SM_a.insert(1,1) = DM_a.coeffRef(1,1) = 0.6469156566545853;
SM_a.insert(1,2) = DM_a.coeffRef(1,2) = -0.3658010398782789;
SM_b.insert(0,0) = DM_b.coeffRef(0,0) = 0.9004440976767099;
SM_b.insert(0,1) = DM_b.coeffRef(0,1) = -0.2368830858139832;
SM_b.insert(1,0) = DM_b.coeffRef(1,0) = -0.9311078389941825;
SM_b.insert(1,1) = DM_b.coeffRef(1,1) = 0.5310335762980047;
SM_b.insert(2,0) = DM_b.coeffRef(2,0) = -0.1225112806872035;
SM_b.insert(2,1) = DM_b.coeffRef(2,1) = 0.5903998022741264;
SparseMatrix<double,RowMajor> SM_row_a(SM_a), SM_row_b(SM_b);
// test kroneckerProduct(DM_block,DM,DM_fixedSize)
Matrix<double, 6, 6> DM_fix_ab = kroneckerProduct(DM_a.topLeftCorner<2,3>(),DM_b);
CALL_SUBTEST(check_kronecker_product(DM_fix_ab));
// test kroneckerProduct(DM,DM,DM_block)
MatrixXd DM_block_ab(10,15);
DM_block_ab.block<6,6>(2,5) = kroneckerProduct(DM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(DM_block_ab.block<6,6>(2,5)));
// test kroneckerProduct(DM,DM,DM)
MatrixXd DM_ab = kroneckerProduct(DM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(DM_ab));
// test kroneckerProduct(SM,DM,SM)
SparseMatrix<double> SM_ab = kroneckerProduct(SM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SparseMatrix<double,RowMajor> SM_ab2 = kroneckerProduct(SM_a,DM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(DM,SM,SM)
SM_ab.setZero();
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(DM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SM_ab2.setZero();
SM_ab2.insert(0,0)=37.0;
SM_ab2 = kroneckerProduct(DM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(SM,SM,SM)
SM_ab.resize(2,33);
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab));
SM_ab2.resize(5,11);
SM_ab2.insert(0,0)=37.0;
SM_ab2 = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_kronecker_product(SM_ab2));
// test kroneckerProduct(SM,SM,SM) with sparse pattern
SM_a.resize(4,5);
SM_b.resize(3,2);
SM_a.resizeNonZeros(0);
SM_b.resizeNonZeros(0);
SM_a.insert(1,0) = -0.1;
SM_a.insert(0,3) = -0.2;
SM_a.insert(2,4) = 0.3;
SM_a.finalize();
SM_b.insert(0,0) = 0.4;
SM_b.insert(2,1) = -0.5;
SM_b.finalize();
SM_ab.resize(1,1);
SM_ab.insert(0,0)=37.0;
SM_ab = kroneckerProduct(SM_a,SM_b);
CALL_SUBTEST(check_sparse_kronecker_product(SM_ab));
// test dimension of result of kroneckerProduct(DM,DM,DM)
MatrixXd DM_a2(2,1);
MatrixXd DM_b2(5,4);
MatrixXd DM_ab2 = kroneckerProduct(DM_a2,DM_b2);
CALL_SUBTEST(check_dimension(DM_ab2,2*5,1*4));
DM_a2.resize(10,9);
DM_b2.resize(4,8);
DM_ab2 = kroneckerProduct(DM_a2,DM_b2);
CALL_SUBTEST(check_dimension(DM_ab2,10*4,9*8));
}
|
Fix the following warning: "comparison between signed and unsigned integer expressions"
|
Fix the following warning: "comparison between signed and unsigned integer expressions"
|
C++
|
bsd-3-clause
|
robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen
|
39464ccab377c82480fa092ecf02fcdfd1ba2029
|
core/http_loader_test.cpp
|
core/http_loader_test.cpp
|
#include "dronecore.h"
#include "http_loader.h"
#include "curl_include.h"
#include <fstream>
#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
using namespace dronecore;
class HttpLoaderTest : public testing::Test
{
protected:
const std::string _file_url_1 = "http://subdomain.domain.com/some_folder/some_file";
const std::string _file_url_2 = "http://subdomain.domain.com/some_folder/another_file.txt";
const std::string _file_url_3 = "http://subdomain.domain.com/some_folder/yet_another_file.mp4";
const std::string _file_local_path_1 = "some_file";
const std::string _file_local_path_2 = "another_file.txt";
const std::string _file_local_path_3 = "yet_another_file.mp4";
virtual void SetUp()
{
clean();
}
virtual void TearDown()
{
clean();
}
void clean()
{
remove(_file_local_path_1.c_str());
remove(_file_local_path_2.c_str());
remove(_file_local_path_3.c_str());
}
bool check_file_exists(const std::string &file_path)
{
std::ifstream infile(file_path.c_str());
return infile.good();
}
void write_file(const std::string &path, const std::string &content)
{
std::ofstream file;
file.open(path);
file << content;
file.close();
}
void expect_all_simulated_downloads_to_succeed(const std::shared_ptr<CurlWrapperMock> &curl_wrapper)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(_, _, _))
.WillRepeatedly(Invoke([&](const std::string &/*url*/, const std::string & path,
const progress_callback_t &progress_callback) {
for (size_t i = 0; i <= 100; i++) {
if (progress_callback != nullptr) {
progress_callback(i, Status::Downloading, CURLcode::CURLE_OK);
}
}
write_file(path, "downloaded file content\n");
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(100, Status::Finished, CURLcode::CURLE_OK);
return true;
}));
}
void expect_one_simulated_download_to_fail(const std::shared_ptr<CurlWrapperMock> &curl_wrapper,
const std::string &url, const std::string &path)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(url, path, _))
.WillOnce(Invoke([&](const std::string &/*url*/, const std::string &/*path*/,
const progress_callback_t &progress_callback) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(0, Status::Error, CURLcode::CURLE_COULDNT_RESOLVE_HOST);
return false;
}));
}
void expect_one_simulated_download_to_succeed(const std::shared_ptr<CurlWrapperMock> &curl_wrapper,
const std::string &url, const std::string &path)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(url, path, _))
.WillOnce(Invoke([&](const std::string &/*url*/, const std::string & got_path,
const progress_callback_t &progress_callback) {
for (size_t i = 0; i <= 100; i++) {
if (progress_callback != nullptr) {
progress_callback(i, Status::Downloading, CURLcode::CURLE_OK);
}
}
write_file(got_path, "downloaded file content\n");
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(100, Status::Finished, CURLcode::CURLE_OK);
return true;
}));
}
};
TEST_F(HttpLoaderTest, HttpLoader_DownloadAsync_OneBad)
{
auto curl_wrapper_mock = std::make_shared<CurlWrapperMock>();
auto http_loader = std::make_shared<HttpLoader>(curl_wrapper_mock);
expect_one_simulated_download_to_succeed(curl_wrapper_mock, _file_url_1, _file_local_path_1);
expect_one_simulated_download_to_fail(curl_wrapper_mock, _file_url_2, _file_local_path_2);
expect_one_simulated_download_to_succeed(curl_wrapper_mock, _file_url_3, _file_local_path_3);
std::vector<int> callback_results_progress;
int callback_finished_counter = 0;
int callback_error_counter = 0;
progress_callback_t progress = [&callback_results_progress,
&callback_finished_counter,
&callback_error_counter]
(int got_progress, Status status, CURLcode curl_code) -> int {
if (status == Status::Downloading)
{
callback_results_progress.push_back(got_progress);
} else if (status == Status::Error && curl_code == CURLcode::CURLE_COULDNT_RESOLVE_HOST)
{
callback_error_counter++;
} else if (status == Status::Finished && curl_code == CURLcode::CURLE_OK)
{
callback_finished_counter++;
}
return 0;
};
http_loader->download_async(_file_url_1, _file_local_path_1, progress);
http_loader->download_async(_file_url_2, _file_local_path_2, progress);
http_loader->download_async(_file_url_3, _file_local_path_3, progress);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
EXPECT_EQ(check_file_exists(_file_local_path_1), true);
EXPECT_EQ(check_file_exists(_file_local_path_2), false);
EXPECT_EQ(check_file_exists(_file_local_path_3), true);
int callback_results_sum = std::accumulate(callback_results_progress.begin(),
callback_results_progress.end(), 0);
EXPECT_EQ(callback_results_sum, 2 * 5050);
EXPECT_EQ(callback_results_progress.size(), 2 * 101);
EXPECT_EQ(callback_finished_counter, 2);
EXPECT_EQ(callback_error_counter, 1);
clean();
}
TEST_F(HttpLoaderTest, HttpLoader_DownloadAsync_AllGood)
{
auto curl_wrapper_mock = std::make_shared<CurlWrapperMock>();
auto http_loader = std::make_shared<HttpLoader>(curl_wrapper_mock);
expect_all_simulated_downloads_to_succeed(curl_wrapper_mock);
std::vector<int> callback_results_progress;
int callback_finished_counter = 0;
int callback_error_counter = 0;
progress_callback_t progress = [&callback_results_progress,
&callback_finished_counter,
&callback_error_counter]
(int got_progress, Status status, CURLcode curl_code) -> int {
if (status == Status::Downloading)
{
callback_results_progress.push_back(got_progress);
} else if (status == Status::Error && curl_code == CURLcode::CURLE_COULDNT_RESOLVE_HOST)
{
callback_error_counter++;
} else if (status == Status::Finished && curl_code == CURLcode::CURLE_OK)
{
callback_finished_counter++;
}
return 0;
};
http_loader->download_async(_file_url_1, _file_local_path_1, progress);
http_loader->download_async(_file_url_2, _file_local_path_2, progress);
http_loader->download_async(_file_url_3, _file_local_path_3, progress);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
EXPECT_EQ(check_file_exists(_file_local_path_1), true);
EXPECT_EQ(check_file_exists(_file_local_path_2), true);
EXPECT_EQ(check_file_exists(_file_local_path_3), true);
int callback_results_sum = std::accumulate(callback_results_progress.begin(),
callback_results_progress.end(), 0);
EXPECT_EQ(callback_results_sum, 3 * 5050);
EXPECT_EQ(callback_results_progress.size(), 3 * 101);
EXPECT_EQ(callback_finished_counter, 3);
EXPECT_EQ(callback_error_counter, 0);
clean();
}
|
#include "dronecore.h"
#include "http_loader.h"
#include "curl_include.h"
#include <fstream>
#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
#include <gtest/gtest.h>
using namespace dronecore;
class HttpLoaderTest : public testing::Test
{
protected:
const std::string _file_url_1 = "http://subdomain.domain.com/some_folder/some_file";
const std::string _file_url_2 = "http://subdomain.domain.com/some_folder/another_file.txt";
const std::string _file_url_3 = "http://subdomain.domain.com/some_folder/yet_another_file.mp4";
const std::string _file_local_path_1 = "some_file";
const std::string _file_local_path_2 = "another_file.txt";
const std::string _file_local_path_3 = "yet_another_file.mp4";
virtual void SetUp()
{
clean();
}
virtual void TearDown()
{
clean();
}
void clean()
{
remove(_file_local_path_1.c_str());
remove(_file_local_path_2.c_str());
remove(_file_local_path_3.c_str());
}
bool check_file_exists(const std::string &file_path)
{
std::ifstream infile(file_path.c_str());
return infile.good();
}
void write_file(const std::string &path, const std::string &content)
{
std::ofstream file;
file.open(path);
file << content;
file.close();
}
void expect_all_simulated_downloads_to_succeed(const std::shared_ptr<CurlWrapperMock> &curl_wrapper)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(_, _, _))
.WillRepeatedly(Invoke([&](const std::string &/*url*/, const std::string & path,
const progress_callback_t &progress_callback) {
for (size_t i = 0; i <= 100; i++) {
if (progress_callback != nullptr) {
progress_callback(i, Status::Downloading, CURLcode::CURLE_OK);
}
}
write_file(path, "downloaded file content\n");
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(100, Status::Finished, CURLcode::CURLE_OK);
return true;
}));
}
void expect_one_simulated_download_to_fail(const std::shared_ptr<CurlWrapperMock> &curl_wrapper,
const std::string &url, const std::string &path)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(url, path, _))
.WillOnce(Invoke([&](const std::string &/*url*/, const std::string &/*path*/,
const progress_callback_t &progress_callback) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(0, Status::Error, CURLcode::CURLE_COULDNT_RESOLVE_HOST);
return false;
}));
}
void expect_one_simulated_download_to_succeed(const std::shared_ptr<CurlWrapperMock> &curl_wrapper,
const std::string &url, const std::string &path)
{
EXPECT_CALL(*curl_wrapper, download_file_to_path(url, path, _))
.WillOnce(Invoke([&](const std::string &/*url*/, const std::string & got_path,
const progress_callback_t &progress_callback) {
for (size_t i = 0; i <= 100; i++) {
if (progress_callback != nullptr) {
progress_callback(i, Status::Downloading, CURLcode::CURLE_OK);
}
}
write_file(got_path, "downloaded file content\n");
std::this_thread::sleep_for(std::chrono::milliseconds(20));
progress_callback(100, Status::Finished, CURLcode::CURLE_OK);
return true;
}));
}
};
TEST_F(HttpLoaderTest, HttpLoader_DownloadAsync_OneBad)
{
auto curl_wrapper_mock = std::make_shared<CurlWrapperMock>();
auto http_loader = std::make_shared<HttpLoader>(curl_wrapper_mock);
expect_one_simulated_download_to_succeed(curl_wrapper_mock, _file_url_1, _file_local_path_1);
expect_one_simulated_download_to_fail(curl_wrapper_mock, _file_url_2, _file_local_path_2);
expect_one_simulated_download_to_succeed(curl_wrapper_mock, _file_url_3, _file_local_path_3);
std::vector<int> callback_results_progress;
int callback_finished_counter = 0;
int callback_error_counter = 0;
progress_callback_t progress = [&callback_results_progress,
&callback_finished_counter,
&callback_error_counter]
(int got_progress, Status status, CURLcode curl_code) -> int {
if (status == Status::Downloading)
{
callback_results_progress.push_back(got_progress);
} else if (status == Status::Error && curl_code == CURLcode::CURLE_COULDNT_RESOLVE_HOST)
{
callback_error_counter++;
} else if (status == Status::Finished && curl_code == CURLcode::CURLE_OK)
{
callback_finished_counter++;
}
return 0;
};
http_loader->download_async(_file_url_1, _file_local_path_1, progress);
http_loader->download_async(_file_url_2, _file_local_path_2, progress);
http_loader->download_async(_file_url_3, _file_local_path_3, progress);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
EXPECT_EQ(check_file_exists(_file_local_path_1), true);
EXPECT_EQ(check_file_exists(_file_local_path_2), false);
EXPECT_EQ(check_file_exists(_file_local_path_3), true);
int callback_results_sum = std::accumulate(callback_results_progress.begin(),
callback_results_progress.end(), 0);
EXPECT_EQ(callback_results_sum, 2 * 5050);
EXPECT_EQ(callback_results_progress.size(), 2 * 101);
EXPECT_EQ(callback_finished_counter, 2);
EXPECT_EQ(callback_error_counter, 1);
clean();
}
TEST_F(HttpLoaderTest, HttpLoader_DownloadAsync_AllGood)
{
auto curl_wrapper_mock = std::make_shared<CurlWrapperMock>();
auto http_loader = std::make_shared<HttpLoader>(curl_wrapper_mock);
expect_all_simulated_downloads_to_succeed(curl_wrapper_mock);
std::vector<int> callback_results_progress;
int callback_finished_counter = 0;
int callback_error_counter = 0;
progress_callback_t progress = [&callback_results_progress,
&callback_finished_counter,
&callback_error_counter]
(int got_progress, Status status, CURLcode curl_code) -> int {
if (status == Status::Downloading)
{
callback_results_progress.push_back(got_progress);
} else if (status == Status::Error && curl_code == CURLcode::CURLE_COULDNT_RESOLVE_HOST)
{
callback_error_counter++;
} else if (status == Status::Finished && curl_code == CURLcode::CURLE_OK)
{
callback_finished_counter++;
}
return 0;
};
http_loader->download_async(_file_url_1, _file_local_path_1, progress);
http_loader->download_async(_file_url_2, _file_local_path_2, progress);
http_loader->download_async(_file_url_3, _file_local_path_3, progress);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
EXPECT_EQ(check_file_exists(_file_local_path_1), true);
EXPECT_EQ(check_file_exists(_file_local_path_2), true);
EXPECT_EQ(check_file_exists(_file_local_path_3), true);
int callback_results_sum = std::accumulate(callback_results_progress.begin(),
callback_results_progress.end(), 0);
EXPECT_EQ(callback_results_sum, 3 * 5050);
EXPECT_EQ(callback_results_progress.size(), 3 * 101);
EXPECT_EQ(callback_finished_counter, 3);
EXPECT_EQ(callback_error_counter, 0);
clean();
}
|
add missing gtest include
|
core: add missing gtest include
|
C++
|
bsd-3-clause
|
dronecore/DroneCore,dronecore/DroneCore,dronecore/DroneCore,dronecore/DroneCore
|
ef2ecdab6c1f079cb2f3ef2927be0b1d07456ff3
|
src/client/fuse.cc
|
src/client/fuse.cc
|
// -*- 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-2006 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.
*
*/
/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2005 Miklos Szeredi <[email protected]>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
// fuse crap
#ifdef linux
/* For pread()/pwrite() */
#define _XOPEN_SOURCE 500
#endif
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <sys/statvfs.h>
// ceph stuff
#include "include/types.h"
#include "Client.h"
#include "config.h"
// globals
static Client *client; // the ceph client
// ------
// fuse hooks
static int ceph_getattr(const char *path, struct stat *stbuf)
{
return client->lstat(path, stbuf);
}
static int ceph_readlink(const char *path, char *buf, size_t size)
{
int res;
res = client->readlink(path, buf, size - 1);
if (res < 0) return res;
buf[res] = '\0';
return 0;
}
static int ceph_mknod(const char *path, mode_t mode, dev_t rdev)
{
return client->mknod(path, mode);
}
static int ceph_mkdir(const char *path, mode_t mode)
{
return client->mkdir(path, mode);
}
static int ceph_unlink(const char *path)
{
return client->unlink(path);
}
static int ceph_rmdir(const char *path)
{
return client->rmdir(path);
}
static int ceph_symlink(const char *from, const char *to)
{
return client->symlink(from, to);
}
static int ceph_rename(const char *from, const char *to)
{
return client->rename(from, to);
}
static int ceph_link(const char *from, const char *to)
{
return client->link(from, to);
}
static int ceph_chmod(const char *path, mode_t mode)
{
return client->chmod(path, mode);
}
static int ceph_chown(const char *path, uid_t uid, gid_t gid)
{
return client->chown(path, uid, gid);
}
static int ceph_truncate(const char *path, off_t size)
{
return client->truncate(path, size);
}
static int ceph_utime(const char *path, struct utimbuf *buf)
{
return client->utime(path, buf);
}
// ------------------
// file i/o
static int ceph_open(const char *path, struct fuse_file_info *fi)
{
int res;
res = client->open(path, fi->flags, 0);
if (res < 0) return res;
fi->fh = res;
return 0; // fuse wants 0 onsucess
}
static int ceph_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->read(fd, buf, size, offset);
}
static int ceph_write(const char *path, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->write(fd, buf, size, offset);
}
static int ceph_flush(const char *path, struct fuse_file_info *fi)
{
//int fh = fi->fh;
//return client->flush(fh);
return 0;
}
static int ceph_statfs(const char *path, struct statvfs *stbuf)
{
return client->statfs(path, stbuf);
}
static int ceph_release(const char *path, struct fuse_file_info *fi)
{
int fd = fi->fh;
int r = client->close(fd); // close the file
return r;
}
static int ceph_fsync(const char *path, int isdatasync,
struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->fsync(fd, isdatasync ? true:false);
}
// ---------------------
// directory i/o
static int ceph_opendir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp;
int r = client->opendir(path, &dirp);
if (r < 0) return r;
fi->fh = (uint64_t)(void*)dirp;
return 0;
}
static int ceph_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t off, fuse_file_info *fi)
{
DIR *dirp = (DIR*)fi->fh;
client->seekdir(dirp, off);
int res = 0;
struct dirent de;
struct stat st;
int stmask = 0;
while (res == 0) {
int r = client->readdirplus_r(dirp, &de, &st, &stmask);
if (r != 0) break;
int stneed = CEPH_STAT_CAP_TYPE;
res = filler(buf,
de.d_name,
((stmask & stneed) == stneed) ? &st:0,
client->telldir(dirp));
}
return 0;
}
static int ceph_releasedir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp = (DIR*)fi->fh;
int r = client->closedir(dirp); // close the file
return r;
}
static struct fuse_operations ceph_oper = {
getattr: ceph_getattr,
readlink: ceph_readlink,
getdir: 0,
mknod: ceph_mknod,
mkdir: ceph_mkdir,
unlink: ceph_unlink,
rmdir: ceph_rmdir,
symlink: ceph_symlink,
rename: ceph_rename,
link: ceph_link,
chmod: ceph_chmod,
chown: ceph_chown,
truncate: ceph_truncate,
utime: ceph_utime,
open: ceph_open,
read: ceph_read,
write: ceph_write,
statfs: ceph_statfs,
flush: ceph_flush,
release: ceph_release,
fsync: ceph_fsync,
setxattr: 0,
getxattr: 0,
listxattr: 0,
removexattr: 0,
opendir: ceph_opendir,
readdir: ceph_readdir,
releasedir: ceph_releasedir
};
int ceph_fuse_main(Client *c, int argc, const char *argv[])
{
// init client
client = c;
// set up fuse argc/argv
int newargc = 0;
const char **newargv = (const char **) malloc((argc + 10) * sizeof(char *));
newargv[newargc++] = argv[0];
// allow other (all!) users to see my file system
// NOTE: echo user_allow_other >> /etc/fuse.conf
// NB: seems broken on Darwin
#ifndef DARWIN
newargv[newargc++] = "-o";
newargv[newargc++] = "allow_other";
#endif // DARWIN
// use inos
newargv[newargc++] = "-o";
newargv[newargc++] = "use_ino";
// large reads, direct_io (no kernel cachine)
//newargv[newargc++] = "-o";
//newargv[newargc++] = "large_read";
if (g_conf.fuse_direct_io) {
newargv[newargc++] = "-o";
newargv[newargc++] = "direct_io";
}
// disable stupid fuse unlink hiding thing
newargv[newargc++] = "-o";
newargv[newargc++] = "hard_remove";
// force into foreground
// -> we can watch stdout this way!!
newargv[newargc++] = "-f";
// copy rest of cmdline (hopefully, the mount point!)
for (int argctr = 1; argctr < argc; argctr++) newargv[newargc++] = argv[argctr];
// go fuse go
cout << "ok, calling fuse_main" << std::endl;
int r = fuse_main(newargc, (char**)newargv, &ceph_oper, 0);
return r;
}
|
// -*- 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-2010 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GPL.
*
*/
/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2005 Miklos Szeredi <[email protected]>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
// fuse crap
#ifdef linux
/* For pread()/pwrite() */
#define _XOPEN_SOURCE 500
#endif
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <sys/statvfs.h>
// ceph stuff
#include "include/types.h"
#include "Client.h"
#include "config.h"
// globals
static Client *client; // the ceph client
// ------
// fuse hooks
static int ceph_getattr(const char *path, struct stat *stbuf)
{
return client->lstat(path, stbuf);
}
static int ceph_readlink(const char *path, char *buf, size_t size)
{
int res;
res = client->readlink(path, buf, size - 1);
if (res < 0) return res;
buf[res] = '\0';
return 0;
}
static int ceph_mknod(const char *path, mode_t mode, dev_t rdev)
{
return client->mknod(path, mode);
}
static int ceph_mkdir(const char *path, mode_t mode)
{
return client->mkdir(path, mode);
}
static int ceph_unlink(const char *path)
{
return client->unlink(path);
}
static int ceph_rmdir(const char *path)
{
return client->rmdir(path);
}
static int ceph_symlink(const char *from, const char *to)
{
return client->symlink(from, to);
}
static int ceph_rename(const char *from, const char *to)
{
return client->rename(from, to);
}
static int ceph_link(const char *from, const char *to)
{
return client->link(from, to);
}
static int ceph_chmod(const char *path, mode_t mode)
{
return client->chmod(path, mode);
}
static int ceph_chown(const char *path, uid_t uid, gid_t gid)
{
return client->chown(path, uid, gid);
}
static int ceph_truncate(const char *path, off_t size)
{
return client->truncate(path, size);
}
static int ceph_utime(const char *path, struct utimbuf *buf)
{
return client->utime(path, buf);
}
// ------------------
// file i/o
static int ceph_open(const char *path, struct fuse_file_info *fi)
{
int res;
res = client->open(path, fi->flags, 0);
if (res < 0) return res;
fi->fh = res;
return 0; // fuse wants 0 onsucess
}
static int ceph_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->read(fd, buf, size, offset);
}
static int ceph_write(const char *path, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->write(fd, buf, size, offset);
}
static int ceph_flush(const char *path, struct fuse_file_info *fi)
{
//int fh = fi->fh;
//return client->flush(fh);
return 0;
}
static int ceph_statfs(const char *path, struct statvfs *stbuf)
{
return client->statfs(path, stbuf);
}
static int ceph_release(const char *path, struct fuse_file_info *fi)
{
int fd = fi->fh;
int r = client->close(fd); // close the file
return r;
}
static int ceph_fsync(const char *path, int isdatasync,
struct fuse_file_info *fi)
{
int fd = fi->fh;
return client->fsync(fd, isdatasync ? true:false);
}
// ---------------------
// directory i/o
static int ceph_opendir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp;
int r = client->opendir(path, &dirp);
if (r < 0) return r;
fi->fh = (uint64_t)(void*)dirp;
return 0;
}
static int ceph_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t off, fuse_file_info *fi)
{
DIR *dirp = (DIR*)fi->fh;
client->seekdir(dirp, off);
int res = 0;
struct dirent de;
struct stat st;
int stmask = 0;
while (res == 0) {
int r = client->readdirplus_r(dirp, &de, &st, &stmask);
if (r != 0) break;
int stneed = CEPH_STAT_CAP_TYPE;
res = filler(buf,
de.d_name,
((stmask & stneed) == stneed) ? &st:0,
client->telldir(dirp));
}
return 0;
}
static int ceph_releasedir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp = (DIR*)fi->fh;
int r = client->closedir(dirp); // close the file
return r;
}
static struct fuse_operations ceph_oper = {
getattr: ceph_getattr,
readlink: ceph_readlink,
getdir: 0,
mknod: ceph_mknod,
mkdir: ceph_mkdir,
unlink: ceph_unlink,
rmdir: ceph_rmdir,
symlink: ceph_symlink,
rename: ceph_rename,
link: ceph_link,
chmod: ceph_chmod,
chown: ceph_chown,
truncate: ceph_truncate,
utime: ceph_utime,
open: ceph_open,
read: ceph_read,
write: ceph_write,
statfs: ceph_statfs,
flush: ceph_flush,
release: ceph_release,
fsync: ceph_fsync,
setxattr: 0,
getxattr: 0,
listxattr: 0,
removexattr: 0,
opendir: ceph_opendir,
readdir: ceph_readdir,
releasedir: ceph_releasedir
};
int ceph_fuse_main(Client *c, int argc, const char *argv[])
{
// init client
client = c;
// set up fuse argc/argv
int newargc = 0;
const char **newargv = (const char **) malloc((argc + 10) * sizeof(char *));
newargv[newargc++] = argv[0];
// allow other (all!) users to see my file system
// NOTE: echo user_allow_other >> /etc/fuse.conf
// NB: seems broken on Darwin
#ifndef DARWIN
newargv[newargc++] = "-o";
newargv[newargc++] = "allow_other";
#endif // DARWIN
// use inos
newargv[newargc++] = "-o";
newargv[newargc++] = "use_ino";
// large reads, direct_io (no kernel cachine)
//newargv[newargc++] = "-o";
//newargv[newargc++] = "large_read";
if (g_conf.fuse_direct_io) {
newargv[newargc++] = "-o";
newargv[newargc++] = "direct_io";
}
// disable stupid fuse unlink hiding thing
newargv[newargc++] = "-o";
newargv[newargc++] = "hard_remove";
// force into foreground
// -> we can watch stdout this way!!
newargv[newargc++] = "-f";
// copy rest of cmdline (hopefully, the mount point!)
for (int argctr = 1; argctr < argc; argctr++) newargv[newargc++] = argv[argctr];
// go fuse go
cout << "ok, calling fuse_main" << std::endl;
int r = fuse_main(newargc, (char**)newargv, &ceph_oper, 0);
return r;
}
|
make license GPL
|
fuse.cc: make license GPL
Originally based on Miklos' fusexmp.c, which is GPL. Keep that license.
LGPL makes no sense here anyway.
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
ac0756baf911c7cceefbe99eda3e47d6d188b7cf
|
kpeople/nepomuk-feeder/main.cpp
|
kpeople/nepomuk-feeder/main.cpp
|
/*
* This file is part of telepathy-integration-daemon
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
*
* 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
*/
extern "C"
{
#include <signal.h>
}
#include "telepathyaccountmonitor.h"
#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KUniqueApplication>
#include <Nepomuk/ResourceManager>
namespace
{
static void signal_handler(int signal)
{
if ((signal == SIGTERM) || (signal == SIGINT)) {
QCoreApplication * const app(QCoreApplication::instance());
if (app != 0) {
app->quit();
}
}
}
}
int main(int argc, char *argv[])
{
KAboutData aboutData("telepathy-integration-daemon", 0, ki18n("Telepathy Integration Daemon"), "0.1");
KCmdLineArgs::init(argc, argv, &aboutData);
KUniqueApplication app;
Nepomuk::ResourceManager::instance()->init();
// Create an instance of the Telepathy Account Monitor.
TelepathyAccountMonitor *monitor = new TelepathyAccountMonitor(&app);
// Set up signal handlers.
if (signal(SIGINT, signal_handler) == SIG_ERR) {
kWarning() << "Setting up SIGINT signal handler failed.";
}
if (signal(SIGTERM, signal_handler) == SIG_ERR) {
kWarning() << "Setting up SIGTERM signal handler failed.";
}
// Quite the application when the monitor is destroyed.
QObject::connect(monitor, SIGNAL(destroyed()), &app, SLOT(quit()));
kDebug() << "Let's go...";
// Start event loop.
app.exec();
}
|
/*
* This file is part of telepathy-integration-daemon
*
* Copyright (C) 2009-2010 Collabora Ltd. <[email protected]>
* @author George Goldberg <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*/
extern "C"
{
#include <signal.h>
}
#include "telepathyaccountmonitor.h"
#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KUniqueApplication>
#include <Nepomuk/ResourceManager>
#include <TelepathyQt4/Types>
namespace
{
static void signal_handler(int signal)
{
if ((signal == SIGTERM) || (signal == SIGINT)) {
QCoreApplication * const app(QCoreApplication::instance());
if (app != 0) {
app->quit();
}
}
}
}
int main(int argc, char *argv[])
{
KAboutData aboutData("telepathy-integration-daemon",
0,
ki18n("Telepathy Integration Daemon"),
"0.1");
KCmdLineArgs::init(argc, argv, &aboutData);
KUniqueApplication app;
// Initialise Nepomuk.
Nepomuk::ResourceManager::instance()->init();
// Initialise Telepathy.
Tp::registerTypes();
// Create an instance of the Telepathy Account Monitor.
TelepathyAccountMonitor *monitor = new TelepathyAccountMonitor(&app);
// Set up signal handlers.
if (signal(SIGINT, signal_handler) == SIG_ERR) {
kWarning() << "Setting up SIGINT signal handler failed.";
}
if (signal(SIGTERM, signal_handler) == SIG_ERR) {
kWarning() << "Setting up SIGTERM signal handler failed.";
}
// Quie the application when the monitor is destroyed.
QObject::connect(monitor, SIGNAL(destroyed()), &app, SLOT(quit()));
kDebug() << "Let's go...";
// Start event loop.
return app.exec();
}
|
Tidy up main.cpp
|
Tidy up main.cpp
svn path=/trunk/playground/network/telepathy-integration-daemon/; revision=1088894
|
C++
|
lgpl-2.1
|
KDE/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,leonhandreke/ktp-common-internals
|
4b8b42be6cca9a5aa1103472de2c9da880e2512a
|
util/stdlib/strlcpy.cc
|
util/stdlib/strlcpy.cc
|
// Copyright 2014 The Crashpad 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 "util/stdlib/strlcpy.h"
namespace crashpad {
size_t c16lcpy(base::char16* destination,
const base::char16* source,
size_t length) {
size_t source_length = base::c16len(source);
if (source_length < length) {
base::c16memcpy(destination, source, source_length + 1);
} else if (length != 0) {
base::c16memcpy(destination, source, length - 1);
destination[length - 1] = '\0';
}
return source_length;
}
} // namespace crashpad
|
// Copyright 2014 The Crashpad 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 "util/stdlib/strlcpy.h"
#include "base/logging.h"
#include "build/build_config.h"
#if defined(OS_WIN) && defined(WCHAR_T_IS_UTF16)
#include <strsafe.h>
#endif
namespace crashpad {
#if defined(OS_WIN) && defined(WCHAR_T_IS_UTF16)
size_t c16lcpy(base::char16* destination,
const base::char16* source,
size_t length) {
HRESULT result = StringCchCopyW(destination, length, source);
CHECK(result == S_OK || result == STRSAFE_E_INSUFFICIENT_BUFFER);
return wcslen(source);
}
#elif defined(WCHAR_T_IS_UTF32)
size_t c16lcpy(base::char16* destination,
const base::char16* source,
size_t length) {
size_t source_length = base::c16len(source);
if (source_length < length) {
base::c16memcpy(destination, source, source_length + 1);
} else if (length != 0) {
base::c16memcpy(destination, source, length - 1);
destination[length - 1] = '\0';
}
return source_length;
}
#endif // WCHAR_T_IS_UTF32
} // namespace crashpad
|
Implement c16lcpy without base:c16*
|
win: Implement c16lcpy without base:c16*
Chromium base doesn't have base::c16len, c16memcpy, etc. when
WCHAR_T_IS_UTF16, so implement c16lcpy without using those.
[email protected]
BUG=crashpad:1, chromium:546288
Review URL: https://codereview.chromium.org/1417403004 .
|
C++
|
apache-2.0
|
atom/crashpad,atom/crashpad,chromium/crashpad,atom/crashpad,chromium/crashpad,chromium/crashpad
|
c0a1ad0b77c6aaa7f539dbeb692b2176f6642e9a
|
bytes_ostream.hh
|
bytes_ostream.hh
|
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/range/iterator_range.hpp>
#include "bytes.hh"
#include "core/unaligned.hh"
#include "hashing.hh"
#include "seastar/core/simple-stream.hh"
/**
* Utility for writing data into a buffer when its final size is not known up front.
*
* Internally the data is written into a chain of chunks allocated on-demand.
* No resizing of previously written data happens.
*
*/
class bytes_ostream {
public:
using size_type = bytes::size_type;
using value_type = bytes::value_type;
static constexpr size_type max_chunk_size = 16 * 1024;
private:
static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long");
struct chunk {
// FIXME: group fragment pointers to reduce pointer chasing when packetizing
std::unique_ptr<chunk> next;
~chunk() {
auto p = std::move(next);
while (p) {
// Avoid recursion when freeing chunks
auto p_next = std::move(p->next);
p = std::move(p_next);
}
}
size_type offset; // Also means "size" after chunk is closed
size_type size;
value_type data[0];
void operator delete(void* ptr) { free(ptr); }
};
// FIXME: consider increasing chunk size as the buffer grows
static constexpr size_type chunk_size{512};
static constexpr size_type usable_chunk_size{chunk_size - sizeof(chunk)};
private:
std::unique_ptr<chunk> _begin;
chunk* _current;
size_type _size;
public:
class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> {
chunk* _current;
public:
fragment_iterator(chunk* current) : _current(current) {}
fragment_iterator(const fragment_iterator&) = default;
fragment_iterator& operator=(const fragment_iterator&) = default;
bytes_view operator*() const {
return { _current->data, _current->offset };
}
bytes_view operator->() const {
return *(*this);
}
fragment_iterator& operator++() {
_current = _current->next.get();
return *this;
}
fragment_iterator operator++(int) {
fragment_iterator tmp(*this);
++(*this);
return tmp;
}
bool operator==(const fragment_iterator& other) const {
return _current == other._current;
}
bool operator!=(const fragment_iterator& other) const {
return _current != other._current;
}
};
private:
inline size_type current_space_left() const {
if (!_current) {
return 0;
}
return _current->size - _current->offset;
}
// Makes room for a contiguous region of given size.
// The region is accounted for as already written.
// size must not be zero.
value_type* alloc(size_type size) {
if (size <= current_space_left()) {
auto ret = _current->data + _current->offset;
_current->offset += size;
_size += size;
return ret;
} else {
auto alloc_size = size <= usable_chunk_size ? chunk_size : (size + sizeof(chunk));
auto space = malloc(alloc_size);
if (!space) {
throw std::bad_alloc();
}
auto new_chunk = std::unique_ptr<chunk>(new (space) chunk());
new_chunk->offset = size;
new_chunk->size = alloc_size - sizeof(chunk);
if (_current) {
_current->next = std::move(new_chunk);
_current = _current->next.get();
} else {
_begin = std::move(new_chunk);
_current = _begin.get();
}
_size += size;
return _current->data;
};
}
public:
bytes_ostream() noexcept
: _begin()
, _current(nullptr)
, _size(0)
{ }
bytes_ostream(bytes_ostream&& o) noexcept
: _begin(std::move(o._begin))
, _current(o._current)
, _size(o._size)
{
o._current = nullptr;
o._size = 0;
}
bytes_ostream(const bytes_ostream& o)
: _begin()
, _current(nullptr)
, _size(0)
{
append(o);
}
bytes_ostream& operator=(const bytes_ostream& o) {
if (this != &o) {
auto x = bytes_ostream(o);
*this = std::move(x);
}
return *this;
}
bytes_ostream& operator=(bytes_ostream&& o) noexcept {
if (this != &o) {
this->~bytes_ostream();
new (this) bytes_ostream(std::move(o));
}
return *this;
}
template <typename T>
struct place_holder {
value_type* ptr;
// makes the place_holder looks like a stream
seastar::simple_output_stream get_stream() {
return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T));
}
};
// Returns a place holder for a value to be written later.
template <typename T>
inline
std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>>
write_place_holder() {
return place_holder<T>{alloc(sizeof(T))};
}
value_type* write_place_holder(size_type size) {
return alloc(size);
}
// Writes given sequence of bytes
inline void write(bytes_view v) {
if (v.empty()) {
return;
}
auto this_size = std::min(v.size(), size_t(current_space_left()));
if (this_size) {
memcpy(_current->data + _current->offset, v.begin(), this_size);
_current->offset += this_size;
_size += this_size;
v.remove_prefix(this_size);
}
while (!v.empty()) {
auto this_size = std::min(v.size(), size_t(max_chunk_size));
std::copy_n(v.begin(), this_size, alloc(this_size));
v.remove_prefix(this_size);
}
}
void write(const char* ptr, size_t size) {
write(bytes_view(reinterpret_cast<const signed char*>(ptr), size));
}
bool is_linearized() const {
return !_begin || !_begin->next;
}
// Call only when is_linearized()
bytes_view view() const {
assert(is_linearized());
if (!_current) {
return bytes_view();
}
return bytes_view(_current->data, _size);
}
// Makes the underlying storage contiguous and returns a view to it.
// Invalidates all previously created placeholders.
bytes_view linearize() {
if (is_linearized()) {
return view();
}
auto space = malloc(_size + sizeof(chunk));
if (!space) {
throw std::bad_alloc();
}
auto new_chunk = std::unique_ptr<chunk>(new (space) chunk());
new_chunk->offset = _size;
new_chunk->size = _size;
auto dst = new_chunk->data;
auto r = _begin.get();
while (r) {
auto next = r->next.get();
dst = std::copy_n(r->data, r->offset, dst);
r = next;
}
_current = new_chunk.get();
_begin = std::move(new_chunk);
return bytes_view(_current->data, _size);
}
// Returns the amount of bytes written so far
size_type size() const {
return _size;
}
bool empty() const {
return _size == 0;
}
void reserve(size_t size) {
// FIXME: implement
}
void append(const bytes_ostream& o) {
for (auto&& bv : o.fragments()) {
write(bv);
}
}
// begin() and end() form an input range to bytes_view representing fragments.
// Any modification of this instance invalidates iterators.
fragment_iterator begin() const { return { _begin.get() }; }
fragment_iterator end() const { return { nullptr }; }
boost::iterator_range<fragment_iterator> fragments() const {
return { begin(), end() };
}
struct position {
chunk* _chunk;
size_type _offset;
};
position pos() const {
return { _current, _current ? _current->offset : 0 };
}
// Returns the amount of bytes written since given position.
// "pos" must be valid.
size_type written_since(position pos) {
chunk* c = pos._chunk;
if (!c) {
return _size;
}
size_type total = c->offset - pos._offset;
c = c->next.get();
while (c) {
total += c->offset;
c = c->next.get();
}
return total;
}
// Rollbacks all data written after "pos".
// Invalidates all placeholders and positions created after "pos".
void retract(position pos) {
if (!pos._chunk) {
*this = {};
return;
}
_size -= written_since(pos);
_current = pos._chunk;
_current->next = nullptr;
_current->offset = pos._offset;
}
void reduce_chunk_count() {
// FIXME: This is a simplified version. It linearizes the whole buffer
// if its size is below max_chunk_size. We probably could also gain
// some read performance by doing "real" reduction, i.e. merging
// all chunks until all but the last one is max_chunk_size.
if (size() < max_chunk_size) {
linearize();
}
}
bool operator==(const bytes_ostream& other) const {
auto as = fragments().begin();
auto as_end = fragments().end();
auto bs = other.fragments().begin();
auto bs_end = other.fragments().end();
auto a = *as++;
auto b = *bs++;
while (!a.empty() || !b.empty()) {
auto now = std::min(a.size(), b.size());
if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) {
return false;
}
a.remove_prefix(now);
if (a.empty() && as != as_end) {
a = *as++;
}
b.remove_prefix(now);
if (b.empty() && bs != bs_end) {
b = *bs++;
}
}
return true;
}
bool operator!=(const bytes_ostream& other) const {
return !(*this == other);
}
};
template<>
struct appending_hash<bytes_ostream> {
template<typename Hasher>
void operator()(Hasher& h, const bytes_ostream& b) const {
for (auto&& frag : b.fragments()) {
feed_hash(h, frag);
}
}
};
|
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/range/iterator_range.hpp>
#include "bytes.hh"
#include "core/unaligned.hh"
#include "hashing.hh"
#include "seastar/core/simple-stream.hh"
/**
* Utility for writing data into a buffer when its final size is not known up front.
*
* Internally the data is written into a chain of chunks allocated on-demand.
* No resizing of previously written data happens.
*
*/
class bytes_ostream {
public:
using size_type = bytes::size_type;
using value_type = bytes::value_type;
static constexpr size_type max_chunk_size = 16 * 1024;
private:
static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long");
struct chunk {
// FIXME: group fragment pointers to reduce pointer chasing when packetizing
std::unique_ptr<chunk> next;
~chunk() {
auto p = std::move(next);
while (p) {
// Avoid recursion when freeing chunks
auto p_next = std::move(p->next);
p = std::move(p_next);
}
}
size_type offset; // Also means "size" after chunk is closed
size_type size;
value_type data[0];
void operator delete(void* ptr) { free(ptr); }
};
// FIXME: consider increasing chunk size as the buffer grows
static constexpr size_type chunk_size{512};
private:
std::unique_ptr<chunk> _begin;
chunk* _current;
size_type _size;
public:
class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> {
chunk* _current;
public:
fragment_iterator(chunk* current) : _current(current) {}
fragment_iterator(const fragment_iterator&) = default;
fragment_iterator& operator=(const fragment_iterator&) = default;
bytes_view operator*() const {
return { _current->data, _current->offset };
}
bytes_view operator->() const {
return *(*this);
}
fragment_iterator& operator++() {
_current = _current->next.get();
return *this;
}
fragment_iterator operator++(int) {
fragment_iterator tmp(*this);
++(*this);
return tmp;
}
bool operator==(const fragment_iterator& other) const {
return _current == other._current;
}
bool operator!=(const fragment_iterator& other) const {
return _current != other._current;
}
};
private:
inline size_type current_space_left() const {
if (!_current) {
return 0;
}
return _current->size - _current->offset;
}
// Figure out next chunk size.
// - must be enough for data_size
// - must be at least chunk_size
// - try to double each time to prevent too many allocations
// - do not exceed max_chunk_size
size_type next_alloc_size(size_t data_size) const {
auto next_size = _current
? _current->size * 2
: chunk_size;
next_size = std::min(next_size, max_chunk_size);
// FIXME: check for overflow?
return std::max<size_type>(next_size, data_size + sizeof(chunk));
}
// Makes room for a contiguous region of given size.
// The region is accounted for as already written.
// size must not be zero.
value_type* alloc(size_type size) {
if (size <= current_space_left()) {
auto ret = _current->data + _current->offset;
_current->offset += size;
_size += size;
return ret;
} else {
auto alloc_size = next_alloc_size(size);
auto space = malloc(alloc_size);
if (!space) {
throw std::bad_alloc();
}
auto new_chunk = std::unique_ptr<chunk>(new (space) chunk());
new_chunk->offset = size;
new_chunk->size = alloc_size - sizeof(chunk);
if (_current) {
_current->next = std::move(new_chunk);
_current = _current->next.get();
} else {
_begin = std::move(new_chunk);
_current = _begin.get();
}
_size += size;
return _current->data;
};
}
public:
bytes_ostream() noexcept
: _begin()
, _current(nullptr)
, _size(0)
{ }
bytes_ostream(bytes_ostream&& o) noexcept
: _begin(std::move(o._begin))
, _current(o._current)
, _size(o._size)
{
o._current = nullptr;
o._size = 0;
}
bytes_ostream(const bytes_ostream& o)
: _begin()
, _current(nullptr)
, _size(0)
{
append(o);
}
bytes_ostream& operator=(const bytes_ostream& o) {
if (this != &o) {
auto x = bytes_ostream(o);
*this = std::move(x);
}
return *this;
}
bytes_ostream& operator=(bytes_ostream&& o) noexcept {
if (this != &o) {
this->~bytes_ostream();
new (this) bytes_ostream(std::move(o));
}
return *this;
}
template <typename T>
struct place_holder {
value_type* ptr;
// makes the place_holder looks like a stream
seastar::simple_output_stream get_stream() {
return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T));
}
};
// Returns a place holder for a value to be written later.
template <typename T>
inline
std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>>
write_place_holder() {
return place_holder<T>{alloc(sizeof(T))};
}
value_type* write_place_holder(size_type size) {
return alloc(size);
}
// Writes given sequence of bytes
inline void write(bytes_view v) {
if (v.empty()) {
return;
}
auto this_size = std::min(v.size(), size_t(current_space_left()));
if (this_size) {
memcpy(_current->data + _current->offset, v.begin(), this_size);
_current->offset += this_size;
_size += this_size;
v.remove_prefix(this_size);
}
while (!v.empty()) {
auto this_size = std::min(v.size(), size_t(max_chunk_size));
std::copy_n(v.begin(), this_size, alloc(this_size));
v.remove_prefix(this_size);
}
}
void write(const char* ptr, size_t size) {
write(bytes_view(reinterpret_cast<const signed char*>(ptr), size));
}
bool is_linearized() const {
return !_begin || !_begin->next;
}
// Call only when is_linearized()
bytes_view view() const {
assert(is_linearized());
if (!_current) {
return bytes_view();
}
return bytes_view(_current->data, _size);
}
// Makes the underlying storage contiguous and returns a view to it.
// Invalidates all previously created placeholders.
bytes_view linearize() {
if (is_linearized()) {
return view();
}
auto space = malloc(_size + sizeof(chunk));
if (!space) {
throw std::bad_alloc();
}
auto new_chunk = std::unique_ptr<chunk>(new (space) chunk());
new_chunk->offset = _size;
new_chunk->size = _size;
auto dst = new_chunk->data;
auto r = _begin.get();
while (r) {
auto next = r->next.get();
dst = std::copy_n(r->data, r->offset, dst);
r = next;
}
_current = new_chunk.get();
_begin = std::move(new_chunk);
return bytes_view(_current->data, _size);
}
// Returns the amount of bytes written so far
size_type size() const {
return _size;
}
bool empty() const {
return _size == 0;
}
void reserve(size_t size) {
// FIXME: implement
}
void append(const bytes_ostream& o) {
for (auto&& bv : o.fragments()) {
write(bv);
}
}
// begin() and end() form an input range to bytes_view representing fragments.
// Any modification of this instance invalidates iterators.
fragment_iterator begin() const { return { _begin.get() }; }
fragment_iterator end() const { return { nullptr }; }
boost::iterator_range<fragment_iterator> fragments() const {
return { begin(), end() };
}
struct position {
chunk* _chunk;
size_type _offset;
};
position pos() const {
return { _current, _current ? _current->offset : 0 };
}
// Returns the amount of bytes written since given position.
// "pos" must be valid.
size_type written_since(position pos) {
chunk* c = pos._chunk;
if (!c) {
return _size;
}
size_type total = c->offset - pos._offset;
c = c->next.get();
while (c) {
total += c->offset;
c = c->next.get();
}
return total;
}
// Rollbacks all data written after "pos".
// Invalidates all placeholders and positions created after "pos".
void retract(position pos) {
if (!pos._chunk) {
*this = {};
return;
}
_size -= written_since(pos);
_current = pos._chunk;
_current->next = nullptr;
_current->offset = pos._offset;
}
void reduce_chunk_count() {
// FIXME: This is a simplified version. It linearizes the whole buffer
// if its size is below max_chunk_size. We probably could also gain
// some read performance by doing "real" reduction, i.e. merging
// all chunks until all but the last one is max_chunk_size.
if (size() < max_chunk_size) {
linearize();
}
}
bool operator==(const bytes_ostream& other) const {
auto as = fragments().begin();
auto as_end = fragments().end();
auto bs = other.fragments().begin();
auto bs_end = other.fragments().end();
auto a = *as++;
auto b = *bs++;
while (!a.empty() || !b.empty()) {
auto now = std::min(a.size(), b.size());
if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) {
return false;
}
a.remove_prefix(now);
if (a.empty() && as != as_end) {
a = *as++;
}
b.remove_prefix(now);
if (b.empty() && bs != bs_end) {
b = *bs++;
}
}
return true;
}
bool operator!=(const bytes_ostream& other) const {
return !(*this == other);
}
};
template<>
struct appending_hash<bytes_ostream> {
template<typename Hasher>
void operator()(Hasher& h, const bytes_ostream& b) const {
for (auto&& frag : b.fragments()) {
feed_hash(h, frag);
}
}
};
|
use larger allocations
|
bytes_ostream: use larger allocations
A 1MB response will require 2000 allocations with the current 512-byte
chunk size. Increase it exponentially to reduce allocation count for
larger responses (still respecting the upper limit).
Message-Id: <[email protected]>
|
C++
|
agpl-3.0
|
duarten/scylla,raphaelsc/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla,scylladb/scylla,avikivity/scylla,scylladb/scylla,avikivity/scylla,avikivity/scylla,raphaelsc/scylla,duarten/scylla,raphaelsc/scylla
|
b648401adbb50f7c56f274f5b18500168be8a088
|
util/ldb_cmd.cc
|
util/ldb_cmd.cc
|
// Copyright (c) 2012 Facebook. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "leveldb/write_batch.h"
#include "db/dbformat.h"
#include "db/log_reader.h"
#include "db/write_batch_internal.h"
#include "util/ldb_cmd.h"
namespace leveldb {
const char* LDBCommand::FROM_ARG = "--from=";
const char* LDBCommand::END_ARG = "--to=";
const char* LDBCommand::HEX_ARG = "--hex";
Compactor::Compactor(std::string& db_name, std::vector<std::string>& args) :
LDBCommand(db_name, args), null_from_(true), null_to_(true), hex_(false) {
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(FROM_ARG) == 0) {
null_from_ = false;
from_ = arg.substr(strlen(FROM_ARG));
} else if (arg.find(END_ARG) == 0) {
null_to_ = false;
to_ = arg.substr(strlen(END_ARG));
} else if (arg.find(HEX_ARG) == 0) {
hex_ = true;
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument." + arg);
}
}
if (hex_) {
if (!null_from_) {
from_ = HexToString(from_);
}
if (!null_to_) {
to_ = HexToString(to_);
}
}
}
void Compactor::Help(std::string& ret) {
LDBCommand::Help(ret);
ret.append("[--from=START KEY] ");
ret.append("[--to=START KEY] ");
ret.append("[--hex] ");
}
void Compactor::DoCommand() {
leveldb::Slice* begin = NULL;
leveldb::Slice* end = NULL;
if (!null_from_) {
begin = new leveldb::Slice(from_);
}
if (!null_to_) {
end = new leveldb::Slice(to_);
}
db_->CompactRange(begin, end);
exec_state_ = LDBCommandExecuteResult::SUCCEED("");
delete begin;
delete end;
}
const char* DBDumper::MAX_KEYS_ARG = "--max_keys=";
const char* DBDumper::COUNT_ONLY_ARG = "--count_only";
const char* DBDumper::STATS_ARG = "--stats";
const char* DBDumper::HEX_OUTPUT_ARG = "--output_hex";
DBDumper::DBDumper(std::string& db_name, std::vector<std::string>& args) :
LDBCommand(db_name, args),
null_from_(true),
null_to_(true),
max_keys_(-1),
count_only_(false),
print_stats_(false),
hex_(false),
hex_output_(false) {
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(FROM_ARG) == 0) {
null_from_ = false;
from_ = arg.substr(strlen(FROM_ARG));
} else if (arg.find(END_ARG) == 0) {
null_to_ = false;
to_ = arg.substr(strlen(END_ARG));
} else if (arg.find(HEX_ARG) == 0) {
hex_ = true;
} else if (arg.find(MAX_KEYS_ARG) == 0) {
max_keys_ = atoi(arg.substr(strlen(MAX_KEYS_ARG)).c_str());
} else if (arg.find(STATS_ARG) == 0) {
print_stats_ = true;
} else if (arg.find(COUNT_ONLY_ARG) == 0) {
count_only_ = true;
} else if (arg.find(HEX_OUTPUT_ARG) == 0) {
hex_output_ = true;
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument:" + arg);
}
}
if (hex_) {
if (!null_from_) {
from_ = HexToString(from_);
}
if (!null_to_) {
to_ = HexToString(to_);
}
}
}
void DBDumper::Help(std::string& ret) {
LDBCommand::Help(ret);
ret.append("[--from=START KEY] ");
ret.append("[--to=END Key] ");
ret.append("[--hex] ");
ret.append("[--output_hex] ");
ret.append("[--max_keys=NUM] ");
ret.append("[--count_only] ");
ret.append("[--stats] ");
}
void DBDumper::DoCommand() {
// Parse command line args
uint64_t count = 0;
if (print_stats_) {
std::string stats;
if (db_->GetProperty("leveldb.stats", &stats)) {
fprintf(stdout, "%s\n", stats.c_str());
}
}
// Setup key iterator
leveldb::Iterator* iter = db_->NewIterator(leveldb::ReadOptions());
leveldb::Status st = iter->status();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Iterator error."
+ st.ToString());
}
if (!null_from_) {
iter->Seek(from_);
} else {
iter->SeekToFirst();
}
int max_keys = max_keys_;
for (; iter->Valid(); iter->Next()) {
// If end marker was specified, we stop before it
if (!null_to_ && (iter->key().ToString() >= to_))
break;
// Terminate if maximum number of keys have been dumped
if (max_keys == 0)
break;
if (max_keys > 0) {
--max_keys;
}
++count;
if (!count_only_) {
if (hex_output_) {
std::string str = iter->key().ToString();
for (unsigned int i = 0; i < str.length(); ++i) {
fprintf(stdout, "%X", str[i]);
}
fprintf(stdout, " ==> ");
str = iter->value().ToString();
for (unsigned int i = 0; i < str.length(); ++i) {
fprintf(stdout, "%X", str[i]);
}
fprintf(stdout, "\n");
} else {
fprintf(stdout, "%s ==> %s\n", iter->key().ToString().c_str(),
iter->value().ToString().c_str());
}
}
}
fprintf(stdout, "Keys in range: %lld\n", (long long) count);
// Clean up
delete iter;
}
const char* ReduceDBLevels::NEW_LEVLES_ARG = "--new_levels=";
const char* ReduceDBLevels::PRINT_OLD_LEVELS_ARG = "--print_old_levels";
const char* ReduceDBLevels::COMPRESSION_TYPE_ARG = "--compression=";
const char* ReduceDBLevels::FILE_SIZE_ARG = "--file_size=";
ReduceDBLevels::ReduceDBLevels(std::string& db_name,
std::vector<std::string>& args)
: LDBCommand(db_name, args),
old_levels_(1 << 16),
new_levels_(-1),
print_old_levels_(false) {
file_size_ = leveldb::Options().target_file_size_base;
compression_ = leveldb::Options().compression;
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(NEW_LEVLES_ARG) == 0) {
new_levels_ = atoi(arg.substr(strlen(NEW_LEVLES_ARG)).c_str());
} else if (arg.find(PRINT_OLD_LEVELS_ARG) == 0) {
print_old_levels_ = true;
} else if (arg.find(COMPRESSION_TYPE_ARG) == 0) {
const char* type = arg.substr(strlen(COMPRESSION_TYPE_ARG)).c_str();
if (!strcasecmp(type, "none"))
compression_ = leveldb::kNoCompression;
else if (!strcasecmp(type, "snappy"))
compression_ = leveldb::kSnappyCompression;
else if (!strcasecmp(type, "zlib"))
compression_ = leveldb::kZlibCompression;
else if (!strcasecmp(type, "bzip2"))
compression_ = leveldb::kBZip2Compression;
else
exec_state_ = LDBCommandExecuteResult::FAILED(
"Invalid compression arg : " + arg);
} else if (arg.find(FILE_SIZE_ARG) == 0) {
file_size_ = atoi(arg.substr(strlen(FILE_SIZE_ARG)).c_str());
} else {
exec_state_ = LDBCommandExecuteResult::FAILED(
"Unknown argument." + arg);
}
}
if(new_levels_ <= 0) {
exec_state_ = LDBCommandExecuteResult::FAILED(
" Use --new_levels to specify a new level number\n");
}
}
std::vector<std::string> ReduceDBLevels::PrepareArgs(int new_levels,
bool print_old_level) {
std::vector<std::string> ret;
char arg[100];
sprintf(arg, "%s%d", NEW_LEVLES_ARG, new_levels);
ret.push_back(arg);
if(print_old_level) {
sprintf(arg, "%s", PRINT_OLD_LEVELS_ARG);
ret.push_back(arg);
}
return ret;
}
void ReduceDBLevels::Help(std::string& msg) {
LDBCommand::Help(msg);
msg.append("[--new_levels=New number of levels] ");
msg.append("[--print_old_levels] ");
msg.append("[--compression=none|snappy|zlib|bzip2] ");
msg.append("[--file_size= per-file size] ");
}
leveldb::Options ReduceDBLevels::PrepareOptionsForOpenDB() {
leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
opt.num_levels = old_levels_;
// Disable size compaction
opt.max_bytes_for_level_base = 1UL << 50;
opt.max_bytes_for_level_multiplier = 1;
opt.max_mem_compaction_level = 0;
return opt;
}
Status ReduceDBLevels::GetOldNumOfLevels(leveldb::Options& opt, int* levels) {
TableCache* tc = new TableCache(db_path_, &opt, 10);
const InternalKeyComparator* cmp = new InternalKeyComparator(
opt.comparator);
VersionSet* versions = new VersionSet(db_path_, &opt,
tc, cmp);
// We rely the VersionSet::Recover to tell us the internal data structures
// in the db. And the Recover() should never do any change
// (like LogAndApply) to the manifest file.
Status st = versions->Recover();
if (!st.ok()) {
return st;
}
int max = -1;
for (int i = 0; i < versions->NumberLevels(); i++) {
if (versions->NumLevelFiles(i)) {
max = i;
}
}
*levels = max + 1;
delete versions;
return st;
}
void ReduceDBLevels::DoCommand() {
if (new_levels_ <= 1) {
exec_state_ = LDBCommandExecuteResult::FAILED(
"Invalid number of levels.\n");
return;
}
leveldb::Status st;
leveldb::Options opt = PrepareOptionsForOpenDB();
int old_level_num = -1;
st = GetOldNumOfLevels(opt, &old_level_num);
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
if (print_old_levels_) {
fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
}
if (old_level_num <= new_levels_) {
return;
}
old_levels_ = old_level_num;
OpenDB();
// Compact the whole DB to put all files to the highest level.
fprintf(stdout, "Compacting the db...\n");
db_->CompactRange(NULL, NULL);
CloseDB();
TableCache* tc = new TableCache(db_path_, &opt, 10);
const InternalKeyComparator* cmp = new InternalKeyComparator(
opt.comparator);
VersionSet* versions = new VersionSet(db_path_, &opt,
tc, cmp);
// We rely the VersionSet::Recover to tell us the internal data structures
// in the db. And the Recover() should never do any change (like LogAndApply)
// to the manifest file.
st = versions->Recover();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
port::Mutex mu;
mu.Lock();
st = versions->ReduceNumberOfLevels(new_levels_, &mu);
mu.Unlock();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
}
const char* WALDumper::WAL_FILE_ARG = "--walfile=";
WALDumper::WALDumper(std::vector<std::string>& args) :
LDBCommand(args), print_header_(false) {
wal_file_.clear();
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find("--header") == 0) {
print_header_ = true;
} else if (arg.find(WAL_FILE_ARG) == 0) {
wal_file_ = arg.substr(strlen(WAL_FILE_ARG));
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument " + arg);
}
}
if (wal_file_.empty()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Argument --walfile reqd.");
}
}
void WALDumper::Help(std::string& ret) {
ret.append("--walfile write_ahead_log ");
ret.append("[--header print's a header] ");
}
void WALDumper::DoCommand() {
struct StdErrReporter : public log::Reader::Reporter {
virtual void Corruption(size_t bytes, const Status& s) {
std::cerr<<"Corruption detected in log file "<<s.ToString()<<"\n";
}
};
SequentialFile* file;
Env* env_ = Env::Default();
Status status = env_->NewSequentialFile(wal_file_, &file);
if (!status.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Failed to open WAL file " +
status.ToString());
} else {
StdErrReporter reporter;
log::Reader reader(file, &reporter, true, 0);
std::string scratch;
WriteBatch batch;
Slice record;
std::stringstream row;
if (print_header_) {
std::cout<<"Sequence,Count,ByteSize\n";
}
while(reader.ReadRecord(&record, &scratch)) {
row.clear();
if (record.size() < 12) {
reporter.Corruption(
record.size(), Status::Corruption("log record too small"));
} else {
WriteBatchInternal::SetContents(&batch, record);
row<<WriteBatchInternal::Sequence(&batch)<<",";
row<<WriteBatchInternal::Count(&batch)<<",";
row<<WriteBatchInternal::ByteSize(&batch)<<"\n";
}
std::cout<<row.str();
}
}
}
}
|
// Copyright (c) 2012 Facebook. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "leveldb/write_batch.h"
#include "db/dbformat.h"
#include "db/log_reader.h"
#include "db/write_batch_internal.h"
#include "util/ldb_cmd.h"
namespace leveldb {
const char* LDBCommand::FROM_ARG = "--from=";
const char* LDBCommand::END_ARG = "--to=";
const char* LDBCommand::HEX_ARG = "--hex";
Compactor::Compactor(std::string& db_name, std::vector<std::string>& args) :
LDBCommand(db_name, args), null_from_(true), null_to_(true), hex_(false) {
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(FROM_ARG) == 0) {
null_from_ = false;
from_ = arg.substr(strlen(FROM_ARG));
} else if (arg.find(END_ARG) == 0) {
null_to_ = false;
to_ = arg.substr(strlen(END_ARG));
} else if (arg.find(HEX_ARG) == 0) {
hex_ = true;
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument." + arg);
}
}
if (hex_) {
if (!null_from_) {
from_ = HexToString(from_);
}
if (!null_to_) {
to_ = HexToString(to_);
}
}
}
void Compactor::Help(std::string& ret) {
LDBCommand::Help(ret);
ret.append("[--from=START KEY] ");
ret.append("[--to=START KEY] ");
ret.append("[--hex] ");
}
void Compactor::DoCommand() {
leveldb::Slice* begin = NULL;
leveldb::Slice* end = NULL;
if (!null_from_) {
begin = new leveldb::Slice(from_);
}
if (!null_to_) {
end = new leveldb::Slice(to_);
}
db_->CompactRange(begin, end);
exec_state_ = LDBCommandExecuteResult::SUCCEED("");
delete begin;
delete end;
}
const char* DBDumper::MAX_KEYS_ARG = "--max_keys=";
const char* DBDumper::COUNT_ONLY_ARG = "--count_only";
const char* DBDumper::STATS_ARG = "--stats";
const char* DBDumper::HEX_OUTPUT_ARG = "--output_hex";
DBDumper::DBDumper(std::string& db_name, std::vector<std::string>& args) :
LDBCommand(db_name, args),
null_from_(true),
null_to_(true),
max_keys_(-1),
count_only_(false),
print_stats_(false),
hex_(false),
hex_output_(false) {
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(FROM_ARG) == 0) {
null_from_ = false;
from_ = arg.substr(strlen(FROM_ARG));
} else if (arg.find(END_ARG) == 0) {
null_to_ = false;
to_ = arg.substr(strlen(END_ARG));
} else if (arg.find(HEX_ARG) == 0) {
hex_ = true;
} else if (arg.find(MAX_KEYS_ARG) == 0) {
max_keys_ = atoi(arg.substr(strlen(MAX_KEYS_ARG)).c_str());
} else if (arg.find(STATS_ARG) == 0) {
print_stats_ = true;
} else if (arg.find(COUNT_ONLY_ARG) == 0) {
count_only_ = true;
} else if (arg.find(HEX_OUTPUT_ARG) == 0) {
hex_output_ = true;
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument:" + arg);
}
}
if (hex_) {
if (!null_from_) {
from_ = HexToString(from_);
}
if (!null_to_) {
to_ = HexToString(to_);
}
}
}
void DBDumper::Help(std::string& ret) {
LDBCommand::Help(ret);
ret.append("[--from=START KEY] ");
ret.append("[--to=END Key] ");
ret.append("[--hex] ");
ret.append("[--output_hex] ");
ret.append("[--max_keys=NUM] ");
ret.append("[--count_only] ");
ret.append("[--stats] ");
}
void DBDumper::DoCommand() {
// Parse command line args
uint64_t count = 0;
if (print_stats_) {
std::string stats;
if (db_->GetProperty("leveldb.stats", &stats)) {
fprintf(stdout, "%s\n", stats.c_str());
}
}
// Setup key iterator
leveldb::Iterator* iter = db_->NewIterator(leveldb::ReadOptions());
leveldb::Status st = iter->status();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Iterator error."
+ st.ToString());
}
if (!null_from_) {
iter->Seek(from_);
} else {
iter->SeekToFirst();
}
int max_keys = max_keys_;
for (; iter->Valid(); iter->Next()) {
// If end marker was specified, we stop before it
if (!null_to_ && (iter->key().ToString() >= to_))
break;
// Terminate if maximum number of keys have been dumped
if (max_keys == 0)
break;
if (max_keys > 0) {
--max_keys;
}
++count;
if (!count_only_) {
if (hex_output_) {
std::string str = iter->key().ToString();
for (unsigned int i = 0; i < str.length(); ++i) {
fprintf(stdout, "%X", str[i]);
}
fprintf(stdout, " ==> ");
str = iter->value().ToString();
for (unsigned int i = 0; i < str.length(); ++i) {
fprintf(stdout, "%X", str[i]);
}
fprintf(stdout, "\n");
} else {
fprintf(stdout, "%s ==> %s\n", iter->key().ToString().c_str(),
iter->value().ToString().c_str());
}
}
}
fprintf(stdout, "Keys in range: %lld\n", (long long) count);
// Clean up
delete iter;
}
const char* ReduceDBLevels::NEW_LEVLES_ARG = "--new_levels=";
const char* ReduceDBLevels::PRINT_OLD_LEVELS_ARG = "--print_old_levels";
const char* ReduceDBLevels::COMPRESSION_TYPE_ARG = "--compression=";
const char* ReduceDBLevels::FILE_SIZE_ARG = "--file_size=";
ReduceDBLevels::ReduceDBLevels(std::string& db_name,
std::vector<std::string>& args)
: LDBCommand(db_name, args),
old_levels_(1 << 16),
new_levels_(-1),
print_old_levels_(false) {
file_size_ = leveldb::Options().target_file_size_base;
compression_ = leveldb::Options().compression;
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find(NEW_LEVLES_ARG) == 0) {
new_levels_ = atoi(arg.substr(strlen(NEW_LEVLES_ARG)).c_str());
} else if (arg.find(PRINT_OLD_LEVELS_ARG) == 0) {
print_old_levels_ = true;
} else if (arg.find(COMPRESSION_TYPE_ARG) == 0) {
const char* type = arg.substr(strlen(COMPRESSION_TYPE_ARG)).c_str();
if (!strcasecmp(type, "none"))
compression_ = leveldb::kNoCompression;
else if (!strcasecmp(type, "snappy"))
compression_ = leveldb::kSnappyCompression;
else if (!strcasecmp(type, "zlib"))
compression_ = leveldb::kZlibCompression;
else if (!strcasecmp(type, "bzip2"))
compression_ = leveldb::kBZip2Compression;
else
exec_state_ = LDBCommandExecuteResult::FAILED(
"Invalid compression arg : " + arg);
} else if (arg.find(FILE_SIZE_ARG) == 0) {
file_size_ = atoi(arg.substr(strlen(FILE_SIZE_ARG)).c_str());
} else {
exec_state_ = LDBCommandExecuteResult::FAILED(
"Unknown argument." + arg);
}
}
if(new_levels_ <= 0) {
exec_state_ = LDBCommandExecuteResult::FAILED(
" Use --new_levels to specify a new level number\n");
}
}
std::vector<std::string> ReduceDBLevels::PrepareArgs(int new_levels,
bool print_old_level) {
std::vector<std::string> ret;
char arg[100];
sprintf(arg, "%s%d", NEW_LEVLES_ARG, new_levels);
ret.push_back(arg);
if(print_old_level) {
sprintf(arg, "%s", PRINT_OLD_LEVELS_ARG);
ret.push_back(arg);
}
return ret;
}
void ReduceDBLevels::Help(std::string& msg) {
LDBCommand::Help(msg);
msg.append("[--new_levels=New number of levels] ");
msg.append("[--print_old_levels] ");
msg.append("[--compression=none|snappy|zlib|bzip2] ");
msg.append("[--file_size= per-file size] ");
}
leveldb::Options ReduceDBLevels::PrepareOptionsForOpenDB() {
leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
opt.num_levels = old_levels_;
// Disable size compaction
opt.max_bytes_for_level_base = 1UL << 50;
opt.max_bytes_for_level_multiplier = 1;
opt.max_mem_compaction_level = 0;
return opt;
}
Status ReduceDBLevels::GetOldNumOfLevels(leveldb::Options& opt, int* levels) {
TableCache* tc = new TableCache(db_path_, &opt, 10);
const InternalKeyComparator* cmp = new InternalKeyComparator(
opt.comparator);
VersionSet* versions = new VersionSet(db_path_, &opt,
tc, cmp);
// We rely the VersionSet::Recover to tell us the internal data structures
// in the db. And the Recover() should never do any change
// (like LogAndApply) to the manifest file.
Status st = versions->Recover();
if (!st.ok()) {
return st;
}
int max = -1;
for (int i = 0; i < versions->NumberLevels(); i++) {
if (versions->NumLevelFiles(i)) {
max = i;
}
}
*levels = max + 1;
delete versions;
return st;
}
void ReduceDBLevels::DoCommand() {
if (new_levels_ <= 1) {
exec_state_ = LDBCommandExecuteResult::FAILED(
"Invalid number of levels.\n");
return;
}
leveldb::Status st;
leveldb::Options opt = PrepareOptionsForOpenDB();
int old_level_num = -1;
st = GetOldNumOfLevels(opt, &old_level_num);
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
if (print_old_levels_) {
fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
}
if (old_level_num <= new_levels_) {
return;
}
old_levels_ = old_level_num;
OpenDB();
// Compact the whole DB to put all files to the highest level.
fprintf(stdout, "Compacting the db...\n");
db_->CompactRange(NULL, NULL);
CloseDB();
TableCache* tc = new TableCache(db_path_, &opt, 10);
const InternalKeyComparator* cmp = new InternalKeyComparator(
opt.comparator);
VersionSet* versions = new VersionSet(db_path_, &opt,
tc, cmp);
// We rely the VersionSet::Recover to tell us the internal data structures
// in the db. And the Recover() should never do any change (like LogAndApply)
// to the manifest file.
st = versions->Recover();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
port::Mutex mu;
mu.Lock();
st = versions->ReduceNumberOfLevels(new_levels_, &mu);
mu.Unlock();
if (!st.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
return;
}
}
const char* WALDumper::WAL_FILE_ARG = "--walfile=";
WALDumper::WALDumper(std::vector<std::string>& args) :
LDBCommand(args), print_header_(false) {
wal_file_.clear();
for (unsigned int i = 0; i < args.size(); i++) {
std::string& arg = args.at(i);
if (arg.find("--header") == 0) {
print_header_ = true;
} else if (arg.find(WAL_FILE_ARG) == 0) {
wal_file_ = arg.substr(strlen(WAL_FILE_ARG));
} else {
exec_state_ = LDBCommandExecuteResult::FAILED("Unknown argument " + arg);
}
}
if (wal_file_.empty()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Argument --walfile reqd.");
}
}
void WALDumper::Help(std::string& ret) {
ret.append("--walfile write_ahead_log ");
ret.append("[--header print's a header] ");
}
void WALDumper::DoCommand() {
struct StdErrReporter : public log::Reader::Reporter {
virtual void Corruption(size_t bytes, const Status& s) {
std::cerr<<"Corruption detected in log file "<<s.ToString()<<"\n";
}
};
SequentialFile* file;
Env* env_ = Env::Default();
Status status = env_->NewSequentialFile(wal_file_, &file);
if (!status.ok()) {
exec_state_ = LDBCommandExecuteResult::FAILED("Failed to open WAL file " +
status.ToString());
} else {
StdErrReporter reporter;
log::Reader reader(file, &reporter, true, 0);
std::string scratch;
WriteBatch batch;
Slice record;
std::stringstream row;
if (print_header_) {
std::cout<<"Sequence,Count,ByteSize,Physical Offset\n";
}
while(reader.ReadRecord(&record, &scratch)) {
row.str("");
if (record.size() < 12) {
reporter.Corruption(
record.size(), Status::Corruption("log record too small"));
} else {
WriteBatchInternal::SetContents(&batch, record);
row<<WriteBatchInternal::Sequence(&batch)<<",";
row<<WriteBatchInternal::Count(&batch)<<",";
row<<WriteBatchInternal::ByteSize(&batch)<<",";
row<<reader.LastRecordOffset()<<"\n";
}
std::cout<<row.str();
}
}
}
}
|
Fix LDB dumpwal to print the messages as in the file.
|
Fix LDB dumpwal to print the messages as in the file.
Summary:
StringStream.clear() does not clear the stream. It sets some flags.
Who knew? Fixing that is not printing the stuff again and again.
Test Plan: ran it on a local db
Reviewers: dhruba, emayanke
Reviewed By: dhruba
Differential Revision: https://reviews.facebook.net/D6795
|
C++
|
bsd-3-clause
|
mbarbon/rocksdb,fengshao0907/rocksdb,mbarbon/rocksdb,kaschaeffer/rocksdb,luckywhu/rocksdb,tsheasha/rocksdb,caijieming-baidu/rocksdb,luckywhu/rocksdb,bbiao/rocksdb,facebook/rocksdb,JoeWoo/rocksdb,kaschaeffer/rocksdb,OverlordQ/rocksdb,mbarbon/rocksdb,jalexanderqed/rocksdb,siddhartharay007/rocksdb,RyanTech/rocksdb,msb-at-yahoo/rocksdb,IMCG/RcoksDB,zhangpng/rocksdb,Andymic/rocksdb,Vaisman/rocksdb,alihalabyah/rocksdb,ryneli/rocksdb,alihalabyah/rocksdb,JoeWoo/rocksdb,tschottdorf/rocksdb,RyanTech/rocksdb,kaschaeffer/rocksdb,wlqGit/rocksdb,wenduo/rocksdb,alihalabyah/rocksdb,Applied-Duality/rocksdb,wlqGit/rocksdb,hobinyoon/rocksdb,luckywhu/rocksdb,mbarbon/rocksdb,norton/rocksdb,ryneli/rocksdb,biddyweb/rocksdb,tschottdorf/rocksdb,norton/rocksdb,geraldoandradee/rocksdb,wenduo/rocksdb,zhangpng/rocksdb,luckywhu/rocksdb,msb-at-yahoo/rocksdb,caijieming-baidu/rocksdb,siddhartharay007/rocksdb,bbiao/rocksdb,tsheasha/rocksdb,sorphi/rocksdb,skunkwerks/rocksdb,caijieming-baidu/rocksdb,facebook/rocksdb,wat-ze-hex/rocksdb,tizzybec/rocksdb,fengshao0907/rocksdb,SunguckLee/RocksDB,lgscofield/rocksdb,wenduo/rocksdb,dkorolev/rocksdb,fengshao0907/rocksdb,sorphi/rocksdb,hobinyoon/rocksdb,makelivedotnet/rocksdb,hobinyoon/rocksdb,norton/rocksdb,bbiao/rocksdb,kaschaeffer/rocksdb,Vaisman/rocksdb,facebook/rocksdb,skunkwerks/rocksdb,wenduo/rocksdb,RyanTech/rocksdb,vashstorm/rocksdb,tschottdorf/rocksdb,wskplho/rocksdb,ylong/rocksdb,geraldoandradee/rocksdb,NickCis/rocksdb,Andymic/rocksdb,jalexanderqed/rocksdb,SunguckLee/RocksDB,IMCG/RcoksDB,geraldoandradee/rocksdb,Applied-Duality/rocksdb,virtdb/rocksdb,temicai/rocksdb,alihalabyah/rocksdb,ryneli/rocksdb,siddhartharay007/rocksdb,lgscofield/rocksdb,norton/rocksdb,IMCG/RcoksDB,vashstorm/rocksdb,makelivedotnet/rocksdb,jalexanderqed/rocksdb,IMCG/RcoksDB,virtdb/rocksdb,ryneli/rocksdb,Vaisman/rocksdb,temicai/rocksdb,temicai/rocksdb,virtdb/rocksdb,kaschaeffer/rocksdb,JackLian/rocksdb,SunguckLee/RocksDB,wlqGit/rocksdb,wskplho/rocksdb,wskplho/rocksdb,IMCG/RcoksDB,biddyweb/rocksdb,JoeWoo/rocksdb,wlqGit/rocksdb,tschottdorf/rocksdb,msb-at-yahoo/rocksdb,fengshao0907/rocksdb,rDSN-Projects/rocksdb.replicated,amyvmiwei/rocksdb,JohnPJenkins/rocksdb,fengshao0907/rocksdb,tizzybec/rocksdb,zhangpng/rocksdb,tizzybec/rocksdb,tsheasha/rocksdb,JohnPJenkins/rocksdb,Andymic/rocksdb,JoeWoo/rocksdb,sorphi/rocksdb,Andymic/rocksdb,dkorolev/rocksdb,luckywhu/rocksdb,vashstorm/rocksdb,Andymic/rocksdb,temicai/rocksdb,wat-ze-hex/rocksdb,NickCis/rocksdb,tizzybec/rocksdb,flabby/rocksdb,fengshao0907/rocksdb,makelivedotnet/rocksdb,RyanTech/rocksdb,temicai/rocksdb,norton/rocksdb,dkorolev/rocksdb,jalexanderqed/rocksdb,anagav/rocksdb,skunkwerks/rocksdb,bbiao/rocksdb,hobinyoon/rocksdb,skunkwerks/rocksdb,siddhartharay007/rocksdb,virtdb/rocksdb,jalexanderqed/rocksdb,wlqGit/rocksdb,lgscofield/rocksdb,tschottdorf/rocksdb,dkorolev/rocksdb,ryneli/rocksdb,JoeWoo/rocksdb,tsheasha/rocksdb,rDSN-Projects/rocksdb.replicated,norton/rocksdb,geraldoandradee/rocksdb,anagav/rocksdb,wat-ze-hex/rocksdb,facebook/rocksdb,virtdb/rocksdb,rDSN-Projects/rocksdb.replicated,vashstorm/rocksdb,vmx/rocksdb,dkorolev/rocksdb,tizzybec/rocksdb,msb-at-yahoo/rocksdb,vmx/rocksdb,tschottdorf/rocksdb,kaschaeffer/rocksdb,JohnPJenkins/rocksdb,anagav/rocksdb,Applied-Duality/rocksdb,JackLian/rocksdb,rDSN-Projects/rocksdb.replicated,IMCG/RcoksDB,virtdb/rocksdb,flabby/rocksdb,NickCis/rocksdb,norton/rocksdb,vmx/rocksdb,biddyweb/rocksdb,jalexanderqed/rocksdb,flabby/rocksdb,SunguckLee/RocksDB,JohnPJenkins/rocksdb,NickCis/rocksdb,caijieming-baidu/rocksdb,alihalabyah/rocksdb,vashstorm/rocksdb,wskplho/rocksdb,Vaisman/rocksdb,wskplho/rocksdb,alihalabyah/rocksdb,Vaisman/rocksdb,vmx/rocksdb,mbarbon/rocksdb,fengshao0907/rocksdb,RyanTech/rocksdb,vmx/rocksdb,amyvmiwei/rocksdb,hobinyoon/rocksdb,rDSN-Projects/rocksdb.replicated,wskplho/rocksdb,lgscofield/rocksdb,tsheasha/rocksdb,luckywhu/rocksdb,anagav/rocksdb,jalexanderqed/rocksdb,luckywhu/rocksdb,SunguckLee/RocksDB,dkorolev/rocksdb,JoeWoo/rocksdb,facebook/rocksdb,amyvmiwei/rocksdb,lgscofield/rocksdb,vmx/rocksdb,JohnPJenkins/rocksdb,Applied-Duality/rocksdb,facebook/rocksdb,wlqGit/rocksdb,zhangpng/rocksdb,sorphi/rocksdb,virtdb/rocksdb,hobinyoon/rocksdb,biddyweb/rocksdb,wenduo/rocksdb,amyvmiwei/rocksdb,wat-ze-hex/rocksdb,flabby/rocksdb,JackLian/rocksdb,SunguckLee/RocksDB,makelivedotnet/rocksdb,RyanTech/rocksdb,lgscofield/rocksdb,ylong/rocksdb,OverlordQ/rocksdb,ryneli/rocksdb,Andymic/rocksdb,wat-ze-hex/rocksdb,vmx/rocksdb,JackLian/rocksdb,JoeWoo/rocksdb,mbarbon/rocksdb,SunguckLee/RocksDB,caijieming-baidu/rocksdb,rDSN-Projects/rocksdb.replicated,geraldoandradee/rocksdb,wskplho/rocksdb,tsheasha/rocksdb,mbarbon/rocksdb,tsheasha/rocksdb,bbiao/rocksdb,ylong/rocksdb,sorphi/rocksdb,JackLian/rocksdb,rDSN-Projects/rocksdb.replicated,flabby/rocksdb,bbiao/rocksdb,siddhartharay007/rocksdb,zhangpng/rocksdb,bbiao/rocksdb,hobinyoon/rocksdb,wat-ze-hex/rocksdb,geraldoandradee/rocksdb,kaschaeffer/rocksdb,wenduo/rocksdb,JohnPJenkins/rocksdb,amyvmiwei/rocksdb,Andymic/rocksdb,tizzybec/rocksdb,anagav/rocksdb,OverlordQ/rocksdb,makelivedotnet/rocksdb,amyvmiwei/rocksdb,norton/rocksdb,ylong/rocksdb,anagav/rocksdb,facebook/rocksdb,vashstorm/rocksdb,OverlordQ/rocksdb,alihalabyah/rocksdb,wlqGit/rocksdb,OverlordQ/rocksdb,OverlordQ/rocksdb,facebook/rocksdb,IMCG/RcoksDB,bbiao/rocksdb,tizzybec/rocksdb,NickCis/rocksdb,Vaisman/rocksdb,msb-at-yahoo/rocksdb,ylong/rocksdb,tsheasha/rocksdb,skunkwerks/rocksdb,anagav/rocksdb,ylong/rocksdb,makelivedotnet/rocksdb,dkorolev/rocksdb,vashstorm/rocksdb,wenduo/rocksdb,JackLian/rocksdb,Vaisman/rocksdb,wenduo/rocksdb,sorphi/rocksdb,lgscofield/rocksdb,flabby/rocksdb,flabby/rocksdb,temicai/rocksdb,biddyweb/rocksdb,OverlordQ/rocksdb,Andymic/rocksdb,SunguckLee/RocksDB,JohnPJenkins/rocksdb,skunkwerks/rocksdb,amyvmiwei/rocksdb,siddhartharay007/rocksdb,wat-ze-hex/rocksdb,NickCis/rocksdb,hobinyoon/rocksdb,ylong/rocksdb,Applied-Duality/rocksdb,siddhartharay007/rocksdb,biddyweb/rocksdb,makelivedotnet/rocksdb,msb-at-yahoo/rocksdb,Applied-Duality/rocksdb,RyanTech/rocksdb,vmx/rocksdb,ryneli/rocksdb,sorphi/rocksdb,wat-ze-hex/rocksdb,geraldoandradee/rocksdb,zhangpng/rocksdb,JackLian/rocksdb,caijieming-baidu/rocksdb,caijieming-baidu/rocksdb,zhangpng/rocksdb,NickCis/rocksdb,temicai/rocksdb,Applied-Duality/rocksdb,biddyweb/rocksdb,skunkwerks/rocksdb
|
46ddb18995f08d87d9453a2612688ac9329b67de
|
cppcodec/detail/codec.hpp
|
cppcodec/detail/codec.hpp
|
/**
* Copyright (C) 2015 Topology LP
* All rights reserved.
*
* 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 CPPCODEC_DETAIL_CODEC
#define CPPCODEC_DETAIL_CODEC
#include <assert.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "../data/access.hpp"
#include "../data/raw_result_buffer.hpp"
namespace cppcodec {
namespace detail {
// SFINAE: Templates sometimes beat sensible overloads - make sure we don't call the wrong one.
template <typename T>
struct non_char_array : std::enable_if<
!std::is_same<T, char*>::value && !std::is_same<T, uint8_t*>::value, T>::type
{
using type = T;
};
/**
* Public interface for all the codecs. For API documentation, see README.md.
*/
template <typename CodecImpl>
class codec
{
public:
//
// Encoding
// Convenient version, returns an std::string.
static std::string encode(const uint8_t* binary, size_t binary_size);
static std::string encode(const char* binary, size_t binary_size);
template<typename T> static std::string encode(const T& binary);
// Convenient version with templated result type.
template<typename Result> static Result encode(const uint8_t* binary, size_t binary_size);
template<typename Result> static Result encode(const char* binary, size_t binary_size);
template<typename Result, typename T> static Result encode(const T& binary);
// Reused result container version. Resizes encoded_result before writing to it.
template<typename Result>
static void encode(Result& encoded_result, const uint8_t* binary, size_t binary_size);
template<typename Result>
static void encode(Result& encoded_result, const char* binary, size_t binary_size);
template<typename Result, typename T>
static void encode(typename non_char_array<Result>::type& encoded_result, const T& binary);
// Raw pointer output, assumes pre-allocated memory with size > encoded_size(binary_size).
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const uint8_t* binary, size_t binary_size) noexcept;
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const char* binary, size_t binary_size) noexcept;
template<typename T>
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const T& binary) noexcept;
// Calculate the exact length of the encoded string based on binary size.
static constexpr size_t encoded_size(size_t binary_size) noexcept;
//
// Decoding
// Convenient version, returns an std::vector<uint8_t>.
static std::vector<uint8_t> decode(const char* encoded, size_t encoded_size);
template<typename T> static std::vector<uint8_t> decode(const T& encoded);
// Convenient version with templated result type.
template<typename Result> static Result decode(const char* encoded, size_t encoded_size);
template<typename Result, typename T> static Result decode(const T& encoded);
// Reused result container version. Resizes binary_result before writing to it.
template<typename Result>
static void decode(Result& binary_result, const char* encoded, size_t encoded_size);
template<typename Result, typename T>
static void decode(typename non_char_array<Result>::type& binary_result, const T& encoded);
// Raw pointer output, assumes pre-allocated memory with size > decoded_max_size(encoded_size).
static size_t decode(
uint8_t* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size);
static size_t decode(
char* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size);
template<typename T> static size_t decode(
uint8_t* binary_result, size_t binary_buffer_size, const T& encoded);
template<typename T> static size_t decode(
char* binary_result, size_t binary_buffer_size, const T& encoded);
// Calculate the maximum size of the decoded binary buffer based on the encoded string length.
static constexpr size_t decoded_max_size(size_t encoded_size) noexcept;
};
//
// Inline definitions of the above functions, using CRTP to call into CodecImpl
//
//
// Encoding
template <typename CodecImpl>
inline std::string codec<CodecImpl>::encode(const uint8_t* binary, size_t binary_size)
{
return encode<std::string>(binary, binary_size);
}
template <typename CodecImpl>
inline std::string codec<CodecImpl>::encode(const char* binary, size_t binary_size)
{
return encode<std::string>(reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename T>
inline std::string codec<CodecImpl>::encode(const T& binary)
{
return encode<std::string>(binary);
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::encode(const uint8_t* binary, size_t binary_size)
{
Result encoded_result;
encode(encoded_result, binary, binary_size);
return encoded_result;
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::encode(const char* binary, size_t binary_size)
{
return encode<Result>(reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template<typename Result, typename T>
inline Result codec<CodecImpl>::encode(const T& binary)
{
return encode<Result>(data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::encode(
Result& encoded_result, const uint8_t* binary, size_t binary_size)
{
// This overload is where we reserve buffer capacity and call into CodecImpl.
size_t encoded_buffer_size = encoded_size(binary_size);
auto state = data::create_state(encoded_result, data::specific_t());
data::init(encoded_result, state, encoded_buffer_size);
CodecImpl::encode(encoded_result, state, binary, binary_size);
data::finish(encoded_result, state);
assert(data::size(encoded_result) == encoded_buffer_size);
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::encode(
Result& encoded_result, const char* binary, size_t binary_size)
{
return encode(encoded_result, reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename Result, typename T>
inline void codec<CodecImpl>::encode(typename non_char_array<Result>::type& encoded_result, const T& binary)
{
encode(encoded_result, data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const uint8_t* binary, size_t binary_size) noexcept
{
// This overload is where we wrap the result pointer & size.
data::raw_result_buffer encoded(encoded_result, encoded_buffer_size);
encode(encoded, binary, binary_size);
if (data::size(encoded) < encoded_buffer_size) {
encoded_result[data::size(encoded)] = '\0';
}
return data::size(encoded);
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const char* binary, size_t binary_size) noexcept
{
// This overload is where we wrap the result pointer & size.
return encode(encoded_result, encoded_buffer_size,
reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const T& binary) noexcept
{
return encode(encoded_result, encoded_buffer_size, data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
inline constexpr size_t codec<CodecImpl>::encoded_size(size_t binary_size) noexcept
{
return CodecImpl::encoded_size(binary_size);
}
//
// Decoding
template <typename CodecImpl>
inline std::vector<uint8_t> codec<CodecImpl>::decode(const char* encoded, size_t encoded_size)
{
return decode<std::vector<uint8_t>>(encoded, encoded_size);
}
template <typename CodecImpl>
template <typename T> inline std::vector<uint8_t> codec<CodecImpl>::decode(const T& encoded)
{
return decode<std::vector<uint8_t>>(encoded);
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::decode(const char* encoded, size_t encoded_size)
{
Result result;
decode(result, encoded, encoded_size);
return result;
}
template <typename CodecImpl>
template <typename Result, typename T>
inline Result codec<CodecImpl>::decode(const T& encoded)
{
return decode(data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::decode(Result& binary_result, const char* encoded, size_t encoded_size)
{
// This overload is where we reserve buffer capacity and call into CodecImpl.
size_t binary_buffer_size = decoded_max_size(encoded_size);
auto state = data::create_state(binary_result, data::specific_t());
data::init(binary_result, state, binary_buffer_size);
CodecImpl::decode(binary_result, state, encoded, encoded_size);
data::finish(binary_result, state);
assert(data::size(binary_result) <= binary_buffer_size);
}
template <typename CodecImpl>
template <typename Result, typename T>
inline void codec<CodecImpl>::decode(typename non_char_array<Result>::type& binary_result, const T& encoded)
{
decode(binary_result, data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::decode(
uint8_t* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size)
{
// This overload is where we wrap the result pointer & size.
data::raw_result_buffer binary(binary_result, binary_buffer_size);
decode(binary, encoded, encoded_size);
return data::size(binary);
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::decode(
char* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size)
{
return decode(reinterpret_cast<uint8_t*>(binary_result), binary_buffer_size, encoded, encoded_size);
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::decode(
uint8_t* binary_result, size_t binary_buffer_size, const T& encoded)
{
return decode(binary_result, binary_buffer_size, data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::decode(char* binary_result, size_t binary_buffer_size, const T& encoded)
{
return decode(reinterpret_cast<uint8_t*>(binary_result), binary_buffer_size, encoded);
}
template <typename CodecImpl>
inline constexpr size_t codec<CodecImpl>::decoded_max_size(size_t encoded_size) noexcept
{
return CodecImpl::decoded_max_size(encoded_size);
}
} // namespace detail
} // namespace cppcodec
#endif
|
/**
* Copyright (C) 2015 Topology LP
* All rights reserved.
*
* 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 CPPCODEC_DETAIL_CODEC
#define CPPCODEC_DETAIL_CODEC
#include <assert.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "../data/access.hpp"
#include "../data/raw_result_buffer.hpp"
namespace cppcodec {
namespace detail {
// SFINAE: Templates sometimes beat sensible overloads - make sure we don't call the wrong one.
template <typename T>
struct non_char_ptr : std::enable_if<
!std::is_same<T, char*>::value && !std::is_same<T, uint8_t*>::value, T>::type
{
using type = T;
};
/**
* Public interface for all the codecs. For API documentation, see README.md.
*/
template <typename CodecImpl>
class codec
{
public:
//
// Encoding
// Convenient version, returns an std::string.
static std::string encode(const uint8_t* binary, size_t binary_size);
static std::string encode(const char* binary, size_t binary_size);
template<typename T> static std::string encode(const T& binary);
// Convenient version with templated result type.
template<typename Result> static Result encode(const uint8_t* binary, size_t binary_size);
template<typename Result> static Result encode(const char* binary, size_t binary_size);
template<typename Result, typename T> static Result encode(const T& binary);
// Reused result container version. Resizes encoded_result before writing to it.
template<typename Result>
static void encode(Result& encoded_result, const uint8_t* binary, size_t binary_size);
template<typename Result>
static void encode(Result& encoded_result, const char* binary, size_t binary_size);
template<typename Result, typename T>
static void encode(typename non_char_ptr<Result>::type& encoded_result, const T& binary);
// Raw pointer output, assumes pre-allocated memory with size > encoded_size(binary_size).
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const uint8_t* binary, size_t binary_size) noexcept;
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const char* binary, size_t binary_size) noexcept;
template<typename T>
static size_t encode(
char* encoded_result, size_t encoded_buffer_size,
const T& binary) noexcept;
// Calculate the exact length of the encoded string based on binary size.
static constexpr size_t encoded_size(size_t binary_size) noexcept;
//
// Decoding
// Convenient version, returns an std::vector<uint8_t>.
static std::vector<uint8_t> decode(const char* encoded, size_t encoded_size);
template<typename T> static std::vector<uint8_t> decode(const T& encoded);
// Convenient version with templated result type.
template<typename Result> static Result decode(const char* encoded, size_t encoded_size);
template<typename Result, typename T> static Result decode(const T& encoded);
// Reused result container version. Resizes binary_result before writing to it.
template<typename Result>
static void decode(Result& binary_result, const char* encoded, size_t encoded_size);
template<typename Result, typename T>
static void decode(typename non_char_ptr<Result>::type& binary_result, const T& encoded);
// Raw pointer output, assumes pre-allocated memory with size > decoded_max_size(encoded_size).
static size_t decode(
uint8_t* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size);
static size_t decode(
char* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size);
template<typename T> static size_t decode(
uint8_t* binary_result, size_t binary_buffer_size, const T& encoded);
template<typename T> static size_t decode(
char* binary_result, size_t binary_buffer_size, const T& encoded);
// Calculate the maximum size of the decoded binary buffer based on the encoded string length.
static constexpr size_t decoded_max_size(size_t encoded_size) noexcept;
};
//
// Inline definitions of the above functions, using CRTP to call into CodecImpl
//
//
// Encoding
template <typename CodecImpl>
inline std::string codec<CodecImpl>::encode(const uint8_t* binary, size_t binary_size)
{
return encode<std::string>(binary, binary_size);
}
template <typename CodecImpl>
inline std::string codec<CodecImpl>::encode(const char* binary, size_t binary_size)
{
return encode<std::string>(reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename T>
inline std::string codec<CodecImpl>::encode(const T& binary)
{
return encode<std::string>(binary);
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::encode(const uint8_t* binary, size_t binary_size)
{
Result encoded_result;
encode(encoded_result, binary, binary_size);
return encoded_result;
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::encode(const char* binary, size_t binary_size)
{
return encode<Result>(reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template<typename Result, typename T>
inline Result codec<CodecImpl>::encode(const T& binary)
{
return encode<Result>(data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::encode(
Result& encoded_result, const uint8_t* binary, size_t binary_size)
{
// This overload is where we reserve buffer capacity and call into CodecImpl.
size_t encoded_buffer_size = encoded_size(binary_size);
auto state = data::create_state(encoded_result, data::specific_t());
data::init(encoded_result, state, encoded_buffer_size);
CodecImpl::encode(encoded_result, state, binary, binary_size);
data::finish(encoded_result, state);
assert(data::size(encoded_result) == encoded_buffer_size);
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::encode(
Result& encoded_result, const char* binary, size_t binary_size)
{
return encode(encoded_result, reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename Result, typename T>
inline void codec<CodecImpl>::encode(typename non_char_ptr<Result>::type& encoded_result, const T& binary)
{
encode(encoded_result, data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const uint8_t* binary, size_t binary_size) noexcept
{
// This overload is where we wrap the result pointer & size.
data::raw_result_buffer encoded(encoded_result, encoded_buffer_size);
encode(encoded, binary, binary_size);
if (data::size(encoded) < encoded_buffer_size) {
encoded_result[data::size(encoded)] = '\0';
}
return data::size(encoded);
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const char* binary, size_t binary_size) noexcept
{
// This overload is where we wrap the result pointer & size.
return encode(encoded_result, encoded_buffer_size,
reinterpret_cast<const uint8_t*>(binary), binary_size);
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::encode(
char* encoded_result, size_t encoded_buffer_size,
const T& binary) noexcept
{
return encode(encoded_result, encoded_buffer_size, data::uchar_data(binary), data::size(binary));
}
template <typename CodecImpl>
inline constexpr size_t codec<CodecImpl>::encoded_size(size_t binary_size) noexcept
{
return CodecImpl::encoded_size(binary_size);
}
//
// Decoding
template <typename CodecImpl>
inline std::vector<uint8_t> codec<CodecImpl>::decode(const char* encoded, size_t encoded_size)
{
return decode<std::vector<uint8_t>>(encoded, encoded_size);
}
template <typename CodecImpl>
template <typename T> inline std::vector<uint8_t> codec<CodecImpl>::decode(const T& encoded)
{
return decode<std::vector<uint8_t>>(encoded);
}
template <typename CodecImpl>
template <typename Result>
inline Result codec<CodecImpl>::decode(const char* encoded, size_t encoded_size)
{
Result result;
decode(result, encoded, encoded_size);
return result;
}
template <typename CodecImpl>
template <typename Result, typename T>
inline Result codec<CodecImpl>::decode(const T& encoded)
{
return decode(data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
template <typename Result>
inline void codec<CodecImpl>::decode(Result& binary_result, const char* encoded, size_t encoded_size)
{
// This overload is where we reserve buffer capacity and call into CodecImpl.
size_t binary_buffer_size = decoded_max_size(encoded_size);
auto state = data::create_state(binary_result, data::specific_t());
data::init(binary_result, state, binary_buffer_size);
CodecImpl::decode(binary_result, state, encoded, encoded_size);
data::finish(binary_result, state);
assert(data::size(binary_result) <= binary_buffer_size);
}
template <typename CodecImpl>
template <typename Result, typename T>
inline void codec<CodecImpl>::decode(typename non_char_ptr<Result>::type& binary_result, const T& encoded)
{
decode(binary_result, data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::decode(
uint8_t* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size)
{
// This overload is where we wrap the result pointer & size.
data::raw_result_buffer binary(binary_result, binary_buffer_size);
decode(binary, encoded, encoded_size);
return data::size(binary);
}
template <typename CodecImpl>
inline size_t codec<CodecImpl>::decode(
char* binary_result, size_t binary_buffer_size,
const char* encoded, size_t encoded_size)
{
return decode(reinterpret_cast<uint8_t*>(binary_result), binary_buffer_size, encoded, encoded_size);
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::decode(
uint8_t* binary_result, size_t binary_buffer_size, const T& encoded)
{
return decode(binary_result, binary_buffer_size, data::char_data(encoded), data::size(encoded));
}
template <typename CodecImpl>
template <typename T>
inline size_t codec<CodecImpl>::decode(char* binary_result, size_t binary_buffer_size, const T& encoded)
{
return decode(reinterpret_cast<uint8_t*>(binary_result), binary_buffer_size, encoded);
}
template <typename CodecImpl>
inline constexpr size_t codec<CodecImpl>::decoded_max_size(size_t encoded_size) noexcept
{
return CodecImpl::decoded_max_size(encoded_size);
}
} // namespace detail
} // namespace cppcodec
#endif
|
Rename non_char_array to non_char_ptr.
|
Rename non_char_array to non_char_ptr.
That's what it really is, and that's what out SFINAE is
protecting against to avoid the wrong overload from being called.
We're actually sort of fine with actual char arrays.
See next commit.
|
C++
|
mit
|
jpetso/cppcodec,tplgy/cppcodec
|
fe4b55688808e7b10fd2e3a7ae2fc6682351e82a
|
variables/continuous/BetaPrimeRand.cpp
|
variables/continuous/BetaPrimeRand.cpp
|
#include "BetaPrimeRand.h"
BetaPrimeRand::BetaPrimeRand(double shape1, double shape2)
: BetaRand(shape1, shape2)
{
}
std::string BetaPrimeRand::name()
{
return "Beta Prime(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}
double BetaPrimeRand::f(double x) const
{
if (x <= 0)
return 0;
double alpha = X.getShape();
double beta = Y.getShape();
double rv = std::pow(x, alpha - 1);
rv *= std::pow(1 + x, -alpha - beta);
return pdfCoef * rv;
}
double BetaPrimeRand::F(double x) const
{
if (x <= 0)
return 0;
return RandMath::integral([this] (double t)
{
return f(t);
},
0, x);
}
double BetaPrimeRand::variate() const
{
double x = BetaRand::variate();
return x / (1.0 - x);
}
void BetaPrimeRand::sample(QVector<double> &outputData)
{
BetaRand::sample(outputData);
for (double &var : outputData)
var = var / (1.0 - var);
}
double BetaPrimeRand::E() const
{
return (Y.getShape() > 1) ? X.getShape() / (Y.getShape() - 1) : INFINITY;
}
double BetaPrimeRand::Var() const
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 2)
return INFINITY;
double betaAdj = beta - 1;
double numerator = alpha * (alpha + betaAdj);
double denominator = (betaAdj - 1) * betaAdj * betaAdj;
return numerator / denominator;
}
double BetaPrimeRand::Median()
{
//TODO:
return 1.0;
}
double BetaPrimeRand::Mode()
{
return (X.getShape() < 1) ? 0 : (X.getShape() - 1) / (Y.getShape() + 1);
}
double BetaPrimeRand::Skewness()
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 3)
return INFINITY;
double aux = alpha + beta - 1;
double skewness = (beta - 2) / (alpha * aux);
skewness = std::sqrt(skewness);
aux += alpha;
aux += aux;
return aux * skewness / (beta - 3);
}
double BetaPrimeRand::ExcessKurtosis()
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 4)
return INFINITY;
double betam1 = beta - 1;
double numerator = betam1 * betam1 * (beta - 2) / (alpha * (alpha + betam1));
numerator += 5 * beta - 11;
double denominator = (beta - 3) * (beta - 4);
return 6 * numerator / denominator;
}
|
#include "BetaPrimeRand.h"
BetaPrimeRand::BetaPrimeRand(double shape1, double shape2)
: BetaRand(shape1, shape2)
{
}
std::string BetaPrimeRand::name()
{
return "Beta Prime(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}
double BetaPrimeRand::f(double x) const
{
if (x <= 0)
return 0;
double alpha = X.getShape();
double beta = Y.getShape();
double rv = std::pow(x, alpha - 1);
rv *= std::pow(1 + x, -alpha - beta);
return pdfCoef * rv;
}
double BetaPrimeRand::F(double x) const
{
if (x <= 0)
return 0;
return BetaRand::F(x / (1.0 + x));
}
double BetaPrimeRand::variate() const
{
double x = BetaRand::variate();
return x / (1.0 - x);
}
void BetaPrimeRand::sample(QVector<double> &outputData)
{
BetaRand::sample(outputData);
for (double &var : outputData)
var = var / (1.0 - var);
}
double BetaPrimeRand::E() const
{
return (Y.getShape() > 1) ? X.getShape() / (Y.getShape() - 1) : INFINITY;
}
double BetaPrimeRand::Var() const
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 2)
return INFINITY;
double betaAdj = beta - 1;
double numerator = alpha * (alpha + betaAdj);
double denominator = (betaAdj - 1) * betaAdj * betaAdj;
return numerator / denominator;
}
double BetaPrimeRand::Median()
{
//TODO:
return 1.0;
}
double BetaPrimeRand::Mode()
{
return (X.getShape() < 1) ? 0 : (X.getShape() - 1) / (Y.getShape() + 1);
}
double BetaPrimeRand::Skewness()
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 3)
return INFINITY;
double aux = alpha + beta - 1;
double skewness = (beta - 2) / (alpha * aux);
skewness = std::sqrt(skewness);
aux += alpha;
aux += aux;
return aux * skewness / (beta - 3);
}
double BetaPrimeRand::ExcessKurtosis()
{
double alpha = X.getShape();
double beta = Y.getShape();
if (beta <= 4)
return INFINITY;
double betam1 = beta - 1;
double numerator = betam1 * betam1 * (beta - 2) / (alpha * (alpha + betam1));
numerator += 5 * beta - 11;
double denominator = (beta - 3) * (beta - 4);
return 6 * numerator / denominator;
}
|
Update BetaPrimeRand.cpp
|
Update BetaPrimeRand.cpp
|
C++
|
mit
|
StochasticEngineer/RandLib,Quanteeks/RandLib,Quanteeks/RandLib,StochasticEngineer/RandLib
|
5b652a24e3b3e03fc1380257711b9ed7b0ecc8c7
|
vcl/source/gdi/embeddedfontshelper.cxx
|
vcl/source/gdi/embeddedfontshelper.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <config_folders.h>
#include <vcl/embeddedfontshelper.hxx>
#include <osl/file.hxx>
#include <rtl/bootstrap.hxx>
#include <sft.hxx>
#include <vcl/outdev.hxx>
#include <vcl/svapp.hxx>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <fontsubset.hxx>
#include <outdev.h>
#include <outfont.hxx>
#include <salgdi.hxx>
#include <config_eot.h>
#if ENABLE_EOT
extern "C"
{
namespace libeot
{
#include <libeot.h>
} // namespace libeot
} // extern "C"
#endif
using namespace com::sun::star;
using namespace vcl;
static void clearDir( const OUString& path )
{
osl::Directory dir( path );
if( dir.reset() == osl::Directory::E_None )
{
for(;;)
{
osl::DirectoryItem item;
if( dir.getNextItem( item ) != osl::Directory::E_None )
break;
osl::FileStatus status( osl_FileStatus_Mask_FileURL );
if( item.getFileStatus( status ) == osl::File::E_None )
osl::File::remove( status.getFileURL());
}
}
}
void EmbeddedFontsHelper::clearTemporaryFontFiles()
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/";
clearDir( path + "fromdocs/" );
clearDir( path + "fromsystem/" );
}
bool EmbeddedFontsHelper::addEmbeddedFont( uno::Reference< io::XInputStream > stream, const OUString& fontName,
const char* extra, std::vector< unsigned char > key, bool eot )
{
OUString fileUrl = EmbeddedFontsHelper::fileUrlForTemporaryFont( fontName, extra );
osl::File file( fileUrl );
switch( file.open( osl_File_OpenFlag_Create | osl_File_OpenFlag_Write ))
{
case osl::File::E_None:
break; // ok
case osl::File::E_EXIST:
return true; // Assume it's already been added correctly.
default:
SAL_WARN( "vcl.fonts", "Cannot open file for temporary font" );
return false;
}
size_t keyPos = 0;
std::vector< char > fontData;
fontData.reserve( 1000000 );
for(;;)
{
uno::Sequence< sal_Int8 > buffer;
sal_uInt64 read = stream->readBytes( buffer, 1024 );
for( sal_uInt64 pos = 0;
pos < read && keyPos < key.size();
++pos )
buffer[ pos ] ^= key[ keyPos++ ];
// if eot, don't write the file out yet, since we need to unpack it first.
if( !eot && read > 0 )
{
sal_uInt64 writtenTotal = 0;
while( writtenTotal < read )
{
sal_uInt64 written;
file.write( buffer.getConstArray(), read, written );
writtenTotal += written;
}
}
fontData.insert( fontData.end(), buffer.getConstArray(), buffer.getConstArray() + read );
if( read <= 0 )
break;
}
bool sufficientFontRights(false);
#if ENABLE_EOT
if( eot )
{
unsigned uncompressedFontSize = 0;
unsigned char *nakedPointerToUncompressedFont = NULL;
libeot::EOTMetadata eotMetadata;
libeot::EOTError uncompressError =
libeot::eot2ttf_buffer( (const unsigned char *)&fontData[0], fontData.size(), &eotMetadata, &nakedPointerToUncompressedFont, &uncompressedFontSize ):
boost::shared_ptr<unsigned char> uncompressedFont( nakedPointerToUncompressedFont, libeot::freeEOTBuffer );
if( uncompressError != libeot::EOT_SUCCESS )
{
SAL_WARN( "vcl.fonts", "Failed to uncompress font" );
osl::File::remove( fileUrl );
return false;
}
sal_uInt64 writtenTotal = 0;
while( writtenTotal < uncompressedFontSize )
{
sal_uInt64 written;
if( file.write( uncompressedFont.get() + writtenTotal, uncompressedFontSize - writtenTotal, written ) != osl::File::E_None )
{
SAL_WARN( "vcl.fonts", "Error writing temporary font file" );
osl::File::remove( fileUrl );
return false;
}
writtenTotal += written;
}
sufficientFontRights = libeot::canLegallyEdit( eotMetadata );
libeot::EOTfreeMetadata( &eotMetadata );
}
#endif
if( file.close() != osl::File::E_None )
{
SAL_WARN( "vcl.fonts", "Writing temporary font file failed" );
osl::File::remove( fileUrl );
return false;
}
if( !eot )
{
sufficientFontRights = sufficientTTFRights( &fontData.front(), fontData.size(), EditingAllowed );
}
if( !sufficientFontRights )
{
// It would be actually better to open the document in read-only mode in this case,
// warn the user about this, and provide a button to drop the font(s) in order
// to switch to editing.
SAL_INFO( "vcl.fonts", "Ignoring embedded font that is not usable for editing" );
osl::File::remove( fileUrl );
return false;
}
EmbeddedFontsHelper::activateFont( fontName, fileUrl );
return true;
}
OUString EmbeddedFontsHelper::fileUrlForTemporaryFont( const OUString& fontName, const char* extra )
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/fromdocs/";
osl::Directory::createPath( path );
OUString filename = fontName;
static int uniqueCounter = 0;
if( strcmp( extra, "?" ) == 0 )
filename += OUString::number( uniqueCounter++ );
else
filename += OStringToOUString( extra, RTL_TEXTENCODING_ASCII_US );
filename += ".ttf"; // TODO is it always ttf?
return path + filename;
}
void EmbeddedFontsHelper::activateFont( const OUString& fontName, const OUString& fileUrl )
{
OutputDevice *pDevice = Application::GetDefaultDevice();
pDevice->AddTempDevFont( fileUrl, fontName );
pDevice->ImplUpdateAllFontData( true );
}
// Check if it's (legally) allowed to embed the font file into a document
// (ttf has a flag allowing this). PhysicalFontFace::IsEmbeddable() appears
// to have a different meaning (guessing from code, IsSubsettable() might
// possibly mean it's ttf, while IsEmbeddable() might mean it's type1).
// So just try to open the data as ttf and see.
bool EmbeddedFontsHelper::sufficientTTFRights( const void* data, long size, FontRights rights )
{
TrueTypeFont* font;
if( OpenTTFontBuffer( data, size, 0 /*TODO*/, &font ) == SF_OK )
{
TTGlobalFontInfo info;
GetTTGlobalFontInfo( font, &info );
CloseTTFont( font );
// http://www.microsoft.com/typography/tt/ttf_spec/ttch02.doc
int copyright = info.typeFlags & TYPEFLAG_COPYRIGHT_MASK;
switch( rights )
{
case ViewingAllowed:
// Embedding not restricted completely.
return ( copyright & 0x02 ) != 0x02;
case EditingAllowed:
// Font is installable or editable.
return copyright == 0 || ( copyright & 0x08 );
}
}
return true; // no known restriction
}
OUString EmbeddedFontsHelper::fontFileUrl( const OUString& familyName, FontFamily family, FontItalic italic,
FontWeight weight, FontPitch pitch, rtl_TextEncoding, FontRights rights )
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/fromsystem/";
osl::Directory::createPath( path );
OUString filename = familyName + "_" + OUString::number( family ) + "_" + OUString::number( italic )
+ "_" + OUString::number( weight ) + "_" + OUString::number( pitch );
filename += ".ttf"; // TODO is it always ttf?
OUString url = path + filename;
if( osl::File( url ).open( osl_File_OpenFlag_Read ) == osl::File::E_None ) // = exists()
{
// File with contents of the font file already exists, assume it's been created by a previous call.
return url;
}
bool ok = false;
SalGraphics* graphics = Application::GetDefaultDevice()->ImplGetGraphics();
ImplDevFontList fonts;
graphics->GetDevFontList( &fonts );
boost::scoped_ptr< ImplGetDevFontList > fontInfo( fonts.GetDevFontList());
PhysicalFontFace* selected = NULL;
for( int i = 0;
i < fontInfo->Count();
++i )
{
PhysicalFontFace* f = fontInfo->Get( i );
if( f->GetFamilyName() == familyName )
{
// Ignore comparing text encodings, at least for now. They cannot be trivially compared
// (e.g. UCS2 and UTF8 are technically the same characters, just have different encoding,
// and just having a unicode font doesn't say what glyphs it actually contains).
// It is possible that it still may be needed to do at least some checks here
// for some encodings (can one font have more font files for more encodings?).
if(( family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
&& ( italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
&& ( weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
&& ( pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
{ // Exact match, return it immediately.
selected = f;
break;
}
if(( f->GetFamilyType() == FAMILY_DONTKNOW || family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
&& ( f->GetSlant() == ITALIC_DONTKNOW || italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
&& ( f->GetWeight() == WEIGHT_DONTKNOW || weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
&& ( f->GetPitch() == PITCH_DONTKNOW || pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
{ // Some fonts specify 'DONTKNOW' for some things, still a good match, if we don't find a better one.
selected = f;
}
}
}
if( selected != NULL )
{
sal_Ucs unicodes[ 256 ];
for( int i = 0;
i < 256;
++i )
unicodes[ i ] = 'A'; // Just something, not needed, but GetEmbedFontData() needs it.
sal_Int32 widths[ 256 ];
FontSubsetInfo info;
long size;
if( const void* data = graphics->GetEmbedFontData( selected, unicodes, widths, info, &size ))
{
if( sufficientTTFRights( data, size, rights ))
{
osl::File file( url );
if( file.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Create ) == osl::File::E_None )
{
sal_uInt64 written = 0;
sal_uInt64 totalSize = size;
bool error = false;
while( written < totalSize && !error)
{
sal_uInt64 nowWritten;
switch( file.write( static_cast< const char* >( data ) + written, size - written, nowWritten ))
{
case osl::File::E_None:
written += nowWritten;
break;
case osl::File::E_AGAIN:
case osl::File::E_INTR:
break;
default:
error = true;
break;
}
}
file.close();
if( error )
osl::File::remove( url );
else
ok = true;
}
}
graphics->FreeEmbedFontData( data, size );
}
}
return ok ? url : "";
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <config_folders.h>
#include <vcl/embeddedfontshelper.hxx>
#include <osl/file.hxx>
#include <rtl/bootstrap.hxx>
#include <sft.hxx>
#include <vcl/outdev.hxx>
#include <vcl/svapp.hxx>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <fontsubset.hxx>
#include <outdev.h>
#include <outfont.hxx>
#include <salgdi.hxx>
#include <config_eot.h>
#if ENABLE_EOT
extern "C"
{
namespace libeot
{
#include <libeot.h>
} // namespace libeot
} // extern "C"
#endif
using namespace com::sun::star;
using namespace vcl;
static void clearDir( const OUString& path )
{
osl::Directory dir( path );
if( dir.reset() == osl::Directory::E_None )
{
for(;;)
{
osl::DirectoryItem item;
if( dir.getNextItem( item ) != osl::Directory::E_None )
break;
osl::FileStatus status( osl_FileStatus_Mask_FileURL );
if( item.getFileStatus( status ) == osl::File::E_None )
osl::File::remove( status.getFileURL());
}
}
}
void EmbeddedFontsHelper::clearTemporaryFontFiles()
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/";
clearDir( path + "fromdocs/" );
clearDir( path + "fromsystem/" );
}
bool EmbeddedFontsHelper::addEmbeddedFont( uno::Reference< io::XInputStream > stream, const OUString& fontName,
const char* extra, std::vector< unsigned char > key, bool eot )
{
OUString fileUrl = EmbeddedFontsHelper::fileUrlForTemporaryFont( fontName, extra );
osl::File file( fileUrl );
switch( file.open( osl_File_OpenFlag_Create | osl_File_OpenFlag_Write ))
{
case osl::File::E_None:
break; // ok
case osl::File::E_EXIST:
return true; // Assume it's already been added correctly.
default:
SAL_WARN( "vcl.fonts", "Cannot open file for temporary font" );
return false;
}
size_t keyPos = 0;
std::vector< char > fontData;
fontData.reserve( 1000000 );
for(;;)
{
uno::Sequence< sal_Int8 > buffer;
sal_uInt64 read = stream->readBytes( buffer, 1024 );
for( sal_uInt64 pos = 0;
pos < read && keyPos < key.size();
++pos )
buffer[ pos ] ^= key[ keyPos++ ];
// if eot, don't write the file out yet, since we need to unpack it first.
if( !eot && read > 0 )
{
sal_uInt64 writtenTotal = 0;
while( writtenTotal < read )
{
sal_uInt64 written;
file.write( buffer.getConstArray(), read, written );
writtenTotal += written;
}
}
fontData.insert( fontData.end(), buffer.getConstArray(), buffer.getConstArray() + read );
if( read <= 0 )
break;
}
bool sufficientFontRights(false);
#if ENABLE_EOT
if( eot )
{
unsigned uncompressedFontSize = 0;
unsigned char *nakedPointerToUncompressedFont = NULL;
libeot::EOTMetadata eotMetadata;
libeot::EOTError uncompressError =
libeot::eot2ttf_buffer( (const unsigned char *)&fontData[0], fontData.size(), &eotMetadata, &nakedPointerToUncompressedFont, &uncompressedFontSize );
boost::shared_ptr<unsigned char> uncompressedFont( nakedPointerToUncompressedFont, libeot::freeEOTBuffer );
if( uncompressError != libeot::EOT_SUCCESS )
{
SAL_WARN( "vcl.fonts", "Failed to uncompress font" );
osl::File::remove( fileUrl );
return false;
}
sal_uInt64 writtenTotal = 0;
while( writtenTotal < uncompressedFontSize )
{
sal_uInt64 written;
if( file.write( uncompressedFont.get() + writtenTotal, uncompressedFontSize - writtenTotal, written ) != osl::File::E_None )
{
SAL_WARN( "vcl.fonts", "Error writing temporary font file" );
osl::File::remove( fileUrl );
return false;
}
writtenTotal += written;
}
sufficientFontRights = libeot::canLegallyEdit( &eotMetadata );
libeot::EOTfreeMetadata( &eotMetadata );
}
#endif
if( file.close() != osl::File::E_None )
{
SAL_WARN( "vcl.fonts", "Writing temporary font file failed" );
osl::File::remove( fileUrl );
return false;
}
if( !eot )
{
sufficientFontRights = sufficientTTFRights( &fontData.front(), fontData.size(), EditingAllowed );
}
if( !sufficientFontRights )
{
// It would be actually better to open the document in read-only mode in this case,
// warn the user about this, and provide a button to drop the font(s) in order
// to switch to editing.
SAL_INFO( "vcl.fonts", "Ignoring embedded font that is not usable for editing" );
osl::File::remove( fileUrl );
return false;
}
EmbeddedFontsHelper::activateFont( fontName, fileUrl );
return true;
}
OUString EmbeddedFontsHelper::fileUrlForTemporaryFont( const OUString& fontName, const char* extra )
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/fromdocs/";
osl::Directory::createPath( path );
OUString filename = fontName;
static int uniqueCounter = 0;
if( strcmp( extra, "?" ) == 0 )
filename += OUString::number( uniqueCounter++ );
else
filename += OStringToOUString( extra, RTL_TEXTENCODING_ASCII_US );
filename += ".ttf"; // TODO is it always ttf?
return path + filename;
}
void EmbeddedFontsHelper::activateFont( const OUString& fontName, const OUString& fileUrl )
{
OutputDevice *pDevice = Application::GetDefaultDevice();
pDevice->AddTempDevFont( fileUrl, fontName );
pDevice->ImplUpdateAllFontData( true );
}
// Check if it's (legally) allowed to embed the font file into a document
// (ttf has a flag allowing this). PhysicalFontFace::IsEmbeddable() appears
// to have a different meaning (guessing from code, IsSubsettable() might
// possibly mean it's ttf, while IsEmbeddable() might mean it's type1).
// So just try to open the data as ttf and see.
bool EmbeddedFontsHelper::sufficientTTFRights( const void* data, long size, FontRights rights )
{
TrueTypeFont* font;
if( OpenTTFontBuffer( data, size, 0 /*TODO*/, &font ) == SF_OK )
{
TTGlobalFontInfo info;
GetTTGlobalFontInfo( font, &info );
CloseTTFont( font );
// http://www.microsoft.com/typography/tt/ttf_spec/ttch02.doc
int copyright = info.typeFlags & TYPEFLAG_COPYRIGHT_MASK;
switch( rights )
{
case ViewingAllowed:
// Embedding not restricted completely.
return ( copyright & 0x02 ) != 0x02;
case EditingAllowed:
// Font is installable or editable.
return copyright == 0 || ( copyright & 0x08 );
}
}
return true; // no known restriction
}
OUString EmbeddedFontsHelper::fontFileUrl( const OUString& familyName, FontFamily family, FontItalic italic,
FontWeight weight, FontPitch pitch, rtl_TextEncoding, FontRights rights )
{
OUString path = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
rtl::Bootstrap::expandMacros( path );
path += "/user/temp/embeddedfonts/fromsystem/";
osl::Directory::createPath( path );
OUString filename = familyName + "_" + OUString::number( family ) + "_" + OUString::number( italic )
+ "_" + OUString::number( weight ) + "_" + OUString::number( pitch );
filename += ".ttf"; // TODO is it always ttf?
OUString url = path + filename;
if( osl::File( url ).open( osl_File_OpenFlag_Read ) == osl::File::E_None ) // = exists()
{
// File with contents of the font file already exists, assume it's been created by a previous call.
return url;
}
bool ok = false;
SalGraphics* graphics = Application::GetDefaultDevice()->ImplGetGraphics();
ImplDevFontList fonts;
graphics->GetDevFontList( &fonts );
boost::scoped_ptr< ImplGetDevFontList > fontInfo( fonts.GetDevFontList());
PhysicalFontFace* selected = NULL;
for( int i = 0;
i < fontInfo->Count();
++i )
{
PhysicalFontFace* f = fontInfo->Get( i );
if( f->GetFamilyName() == familyName )
{
// Ignore comparing text encodings, at least for now. They cannot be trivially compared
// (e.g. UCS2 and UTF8 are technically the same characters, just have different encoding,
// and just having a unicode font doesn't say what glyphs it actually contains).
// It is possible that it still may be needed to do at least some checks here
// for some encodings (can one font have more font files for more encodings?).
if(( family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
&& ( italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
&& ( weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
&& ( pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
{ // Exact match, return it immediately.
selected = f;
break;
}
if(( f->GetFamilyType() == FAMILY_DONTKNOW || family == FAMILY_DONTKNOW || f->GetFamilyType() == family )
&& ( f->GetSlant() == ITALIC_DONTKNOW || italic == ITALIC_DONTKNOW || f->GetSlant() == italic )
&& ( f->GetWeight() == WEIGHT_DONTKNOW || weight == WEIGHT_DONTKNOW || f->GetWeight() == weight )
&& ( f->GetPitch() == PITCH_DONTKNOW || pitch == PITCH_DONTKNOW || f->GetPitch() == pitch ))
{ // Some fonts specify 'DONTKNOW' for some things, still a good match, if we don't find a better one.
selected = f;
}
}
}
if( selected != NULL )
{
sal_Ucs unicodes[ 256 ];
for( int i = 0;
i < 256;
++i )
unicodes[ i ] = 'A'; // Just something, not needed, but GetEmbedFontData() needs it.
sal_Int32 widths[ 256 ];
FontSubsetInfo info;
long size;
if( const void* data = graphics->GetEmbedFontData( selected, unicodes, widths, info, &size ))
{
if( sufficientTTFRights( data, size, rights ))
{
osl::File file( url );
if( file.open( osl_File_OpenFlag_Write | osl_File_OpenFlag_Create ) == osl::File::E_None )
{
sal_uInt64 written = 0;
sal_uInt64 totalSize = size;
bool error = false;
while( written < totalSize && !error)
{
sal_uInt64 nowWritten;
switch( file.write( static_cast< const char* >( data ) + written, size - written, nowWritten ))
{
case osl::File::E_None:
written += nowWritten;
break;
case osl::File::E_AGAIN:
case osl::File::E_INTR:
break;
default:
error = true;
break;
}
}
file.close();
if( error )
osl::File::remove( url );
else
ok = true;
}
}
graphics->FreeEmbedFontData( data, size );
}
}
return ok ? url : "";
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
fix build with --enable-eot
|
fix build with --enable-eot
Change-Id: Ia4e5f3d5a47ff88e318d930261efdc90e08cde50
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
7082b0ccd6324f5a2e78822e7ee93466fcab2fac
|
verbose-output/rules/numerals_rule.hpp
|
verbose-output/rules/numerals_rule.hpp
|
#ifndef INC_NUMERALS_RULE_HPP_
#define INC_NUMERALS_RULE_HPP_
#include "./../../../Common/verbose-output/rule.hpp"
#include <boost/static_assert.hpp>
namespace utils { namespace verbose_output {
/// @brief rule for events from integrals state changing
/// @detailed 1. let x be monotonous increasing integral under observation
/// 2. let we want to track x every time if it goes through 100
/// 3. so integrals_rule will raise event if we observe x + y, where y >= 100
template<typename T>
class integrals_rule
: public rule
{
BOOST_STATIC_ASSERT((boost::is_arithmetic<T>::value));
typedef integrals_rule<T> this_class;
typedef rule base_class;
public:
/// @brief default constructor
/// @param state observable
/// @param stride stride we want to log observable through
integrals_rule(T state, T stride)
: m_state(state), m_stride(stride){ };
/// @brief inherited from rule interface
/// @see rule
result_type operator()(args<0>::type);
private:
// logics: we could not adaptively change rule behavior.
// Correctly, it should be done by changing rule
// private setter and getter for observable state
T state() const{ return m_state; }
this_class& state(T val){ m_state = val; return *this; }
// just getter for observations stride
T stride() const{ return m_stride; }
T m_state;
T m_stride;
};
}}
#define _tmpl_head_T_ template<typename T>
#define _cls_name_ integrals_rule<T>
#include "./../../../Common/verbose-output/rules/details/integrals_rule.inl"
#endif
|
#ifndef INC_NUMERALS_RULE_HPP_
#define INC_NUMERALS_RULE_HPP_
#include "./../../../Common/verbose-output/rule.hpp"
#include <boost/static_assert.hpp>
namespace utils { namespace verbose_output {
/// @brief rule for events from integrals state changing
/// @detailed 1. let x be monotonous increasing integral under observation
/// 2. let we want to track x every time if it goes through 100
/// 3. so numerals_rule will raise event if we observe x + y, where y >= 100
template<typename T>
class numerals_rule
: public rule
{
BOOST_STATIC_ASSERT((boost::is_arithmetic<T>::value));
typedef numerals_rule<T> this_class;
typedef rule base_class;
public:
/// @brief default constructor
/// @param state observable
/// @param stride stride we want to log observable through
numerals_rule(T state, T stride)
: m_state(state), m_stride(stride){ };
/// @brief inherited from rule interface
/// @see rule
result_type operator()(args<0>::type);
private:
// logics: we could not adaptively change rule behavior.
// Correctly, it should be done by changing rule
// private setter and getter for observable state
T state() const{ return m_state; }
this_class& state(T val){ m_state = val; return *this; }
// just getter for observations stride
T stride() const{ return m_stride; }
T m_state;
T m_stride;
};
}}
#define _tmpl_head_T_ template<typename T>
#define _cls_name_ numerals_rule<T>
#include "./../../../Common/verbose-output/rules/details/integrals_rule.inl"
#endif
|
refactor from "integrals" to "numerals"
|
numerals_rule.hpp: refactor from "integrals" to "numerals"
|
C++
|
bsd-3-clause
|
piotr-semenov/libq
|
1f91c162659d2dbc1930b83a664f374ad70c7348
|
lib/Interpreter/Transaction.cpp
|
lib/Interpreter/Transaction.cpp
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
delete (*m_NestedTransactions)[i];
}
void Transaction::append(DelayCallInfo DCI) {
if (!DCI.m_DGR.isNull() && getState() == kCommitting) {
// We are committing and getting enw decls in.
// Move them into a sub transaction that will be processed
// recursively at the end of of commitTransaction.
Transaction* subTransactionWhileCommitting = 0;
if (hasNestedTransactions()
&& m_NestedTransactions->back()->getState() == kCollecting)
subTransactionWhileCommitting = m_NestedTransactions->back();
else {
// FIXME: is this correct (Axel says "yes")
CompilationOptions Opts(getCompilationOpts());
Opts.DeclarationExtraction = 0;
Opts.ValuePrinting = CompilationOptions::VPDisabled;
Opts.ResultEvaluation = 0;
Opts.DynamicScoping = 0;
subTransactionWhileCommitting = new Transaction(Opts);
addNestedTransaction(subTransactionWhileCommitting);
}
subTransactionWhileCommitting->append(DCI);
return;
}
assert(DCI.m_DGR.isNull()
|| (getState() == kCollecting || getState() == kCompleted)
|| "Cannot append declarations in current state.");
bool checkForWrapper = !m_WrapperFD;
assert(checkForWrapper = true && "Check for wrappers with asserts");
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl()))
if (utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
// Lazy create the container on first append.
if (!m_DeclQueue)
m_DeclQueue.reset(new DeclQueue());
m_DeclQueue->push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::erase(size_t pos) {
assert(!empty() && "Erasing from an empty transaction.");
m_DeclQueue->erase(decls_begin() + pos);
}
void Transaction::dump() const {
if (!size())
return;
ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
if (!size())
return;
ASTContext* C = 0;
if (m_WrapperFD)
C = &(m_WrapperFD->getASTContext());
if (!getFirstDecl().isNull())
C = &(getFirstDecl().getSingleDecl()->getASTContext());
PrintingPolicy Policy(C->getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
for (DeclGroupRef::const_iterator J = I->m_DGR.begin(),
L = I->m_DGR.end(); J != L; ++J)
if (*J)
(*J)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"Committing",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()] << ", "
<< size() << " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
} // end namespace cling
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/PrettyPrinter.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace cling {
Transaction::~Transaction() {
if (hasNestedTransactions())
for (size_t i = 0; i < m_NestedTransactions->size(); ++i)
delete (*m_NestedTransactions)[i];
}
void Transaction::append(DelayCallInfo DCI) {
assert(!DCI.m_DGR.isNull() && "Appending null DGR?!");
assert(getState() == kCollecting &&
"Cannot append declarations in current state.");
if (!DCI.m_DGR.isNull() && getState() == kCommitting) {
// We are committing and getting new decls in.
// Move them into a sub transaction that will be processed
// recursively at the end of of commitTransaction.
Transaction* subTransactionWhileCommitting = 0;
if (hasNestedTransactions()
&& m_NestedTransactions->back()->getState() == kCollecting)
subTransactionWhileCommitting = m_NestedTransactions->back();
else {
// FIXME: is this correct (Axel says "yes")
CompilationOptions Opts(getCompilationOpts());
Opts.DeclarationExtraction = 0;
Opts.ValuePrinting = CompilationOptions::VPDisabled;
Opts.ResultEvaluation = 0;
Opts.DynamicScoping = 0;
subTransactionWhileCommitting = new Transaction(Opts);
addNestedTransaction(subTransactionWhileCommitting);
}
subTransactionWhileCommitting->append(DCI);
return;
}
bool checkForWrapper = !m_WrapperFD;
assert(checkForWrapper = true && "Check for wrappers with asserts");
// register the wrapper if any.
if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) {
if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl()))
if (utils::Analyze::IsWrapper(FD)) {
assert(!m_WrapperFD && "Two wrappers in one transaction?");
m_WrapperFD = FD;
}
}
// Lazy create the container on first append.
if (!m_DeclQueue)
m_DeclQueue.reset(new DeclQueue());
m_DeclQueue->push_back(DCI);
}
void Transaction::append(clang::DeclGroupRef DGR) {
append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl));
}
void Transaction::append(Decl* D) {
append(DeclGroupRef(D));
}
void Transaction::erase(size_t pos) {
assert(!empty() && "Erasing from an empty transaction.");
m_DeclQueue->erase(decls_begin() + pos);
}
void Transaction::dump() const {
if (!size())
return;
ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext();
PrintingPolicy Policy = C.getPrintingPolicy();
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::dumpPretty() const {
if (!size())
return;
ASTContext* C = 0;
if (m_WrapperFD)
C = &(m_WrapperFD->getASTContext());
if (!getFirstDecl().isNull())
C = &(getFirstDecl().getSingleDecl()->getASTContext());
PrintingPolicy Policy(C->getLangOpts());
print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true);
}
void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy,
unsigned Indent, bool PrintInstantiation) const {
int nestedT = 0;
for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) {
if (I->m_DGR.isNull()) {
assert(hasNestedTransactions() && "DGR is null even if no nesting?");
// print the nested decl
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" Nested Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
(*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent,
PrintInstantiation);
Out<< "\n";
Out<<"+====================================================+\n";
Out<<" End Transaction" << nestedT << " \n";
Out<<"+====================================================+\n";
}
for (DeclGroupRef::const_iterator J = I->m_DGR.begin(),
L = I->m_DGR.end(); J != L; ++J)
if (*J)
(*J)->print(Out, Policy, Indent, PrintInstantiation);
else
Out << "<<NULL DECL>>";
}
}
void Transaction::printStructure(size_t nindent) const {
static const char* const stateNames[kNumStates] = {
"Collecting",
"kCompleted",
"Committing",
"RolledBack",
"RolledBackWithErrors",
"Committed"
};
std::string indent(nindent, ' ');
llvm::errs() << indent << "Transaction @" << this << ": \n";
for (const_nested_iterator I = nested_begin(), E = nested_end();
I != E; ++I) {
(*I)->printStructure(nindent + 3);
}
llvm::errs() << indent << " state: " << stateNames[getState()] << ", "
<< size() << " decl groups, ";
if (hasNestedTransactions())
llvm::errs() << m_NestedTransactions->size();
else
llvm::errs() << "0";
llvm::errs() << " nested transactions\n"
<< indent << " wrapper: " << m_WrapperFD
<< ", parent: " << m_Parent
<< ", next: " << m_Next << "\n";
}
} // end namespace cling
|
Transform to proper assertions.
|
Transform to proper assertions.
|
C++
|
lgpl-2.1
|
perovic/cling,perovic/cling,karies/cling,root-mirror/cling,marsupial/cling,root-mirror/cling,marsupial/cling,root-mirror/cling,karies/cling,perovic/cling,karies/cling,marsupial/cling,root-mirror/cling,karies/cling,root-mirror/cling,karies/cling,marsupial/cling,karies/cling,marsupial/cling,perovic/cling,root-mirror/cling,perovic/cling,marsupial/cling
|
843a1d4a6b0380bf5e02a03c467cba65bcdb3504
|
external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmLoopDepLenTests.cpp
|
external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmLoopDepLenTests.cpp
|
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2017 The Khronos Group 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.
*
*//*!
* \file
* \brief SPIR-V Loop Control for DependencyLength qualifier tests
*//*--------------------------------------------------------------------*/
#include "vkApiVersion.hpp"
#include "vktSpvAsmLoopDepLenTests.hpp"
#include "vktTestCase.hpp"
#include "vktSpvAsmComputeShaderCase.hpp"
#include "deRandom.hpp"
namespace vkt
{
namespace SpirVAssembly
{
using namespace vk;
using std::map;
using std::string;
using std::vector;
// Assembly code used for testing loop control with dependencies is based on GLSL source code:
// #version 430
//
// layout(std140, set = 0, binding = 0) readonly buffer Input {
// float elements[];
// } input_data;
// layout(std140, set = 0, binding = 1) writeonly buffer Output {
// float elements[];
// } output_data;
//
// void main() {
// const uint n = 12;
// float c[n];
// uint x = gl_GlobalInvocationID.x;
//
// for (uint i = 0; i < 6; ++i)
// c[i] = float(i) * input_data.elements[x];
//
// for (uint i = 6; i < n; ++i)
// c[i] = c[i - 4] + c[i - 5] + c[i - 6];
//
// output_data.elements[x] = c[n - 1];
// }
static void getComputeSourceCode (std::string& computeSourceCode)
{
computeSourceCode =
string(getComputeAsmShaderPreamble()) +
"OpSource GLSL 430\n"
"OpName %main \"main\"\n"
"OpName %id \"gl_GlobalInvocationID\"\n"
"OpDecorate %id BuiltIn GlobalInvocationId\n"
+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
"%u32ptr = OpTypePointer Function %u32\n"
"%id = OpVariable %uvec3ptr Input\n"
"%zero = OpConstant %i32 0\n"
"%uzero = OpConstant %u32 0\n"
"%one = OpConstant %i32 1\n"
"%four = OpConstant %u32 4\n"
"%five = OpConstant %u32 5\n"
"%six = OpConstant %u32 6\n"
"%elleven = OpConstant %u32 11\n"
"%twelve = OpConstant %u32 12\n"
"%f32arr12_t = OpTypeArray %f32 %twelve\n"
"%f32arr12ptr_t = OpTypePointer Function %f32arr12_t\n"
"%f32funcptr = OpTypePointer Function %f32\n"
"%main = OpFunction %void None %voidf\n"
"%entry = OpLabel\n"
"%f32arr12 = OpVariable %f32arr12ptr_t Function\n"
"%i1 = OpVariable %u32ptr Function\n"
" OpStore %i1 %uzero\n"
"%i2 = OpVariable %u32ptr Function\n"
" OpStore %i2 %six\n"
"%idval = OpLoad %uvec3 %id\n"
"%x = OpCompositeExtract %u32 %idval 0\n"
"%inloc = OpAccessChain %f32ptr %indata %zero %x\n"
"%inval = OpLoad %f32 %inloc\n"
// for (uint i = 0; i < 6; ++i) c[i] = float(i) * input_data.elements[x];
" OpBranch %loop1_entry\n"
"%loop1_entry = OpLabel\n"
"%i1_val = OpLoad %u32 %i1\n"
"%cmp1_lt = OpULessThan %bool %i1_val %six\n"
" OpLoopMerge %loop1_merge %loop1_body None\n"
" OpBranchConditional %cmp1_lt %loop1_body %loop1_merge\n"
"%loop1_body = OpLabel\n"
"%i1_valf32 = OpConvertUToF %f32 %i1_val\n"
"%mulf1 = OpFMul %f32 %i1_valf32 %inval\n"
"%outloc1 = OpAccessChain %f32funcptr %f32arr12 %i1_val\n"
" OpStore %outloc1 %mulf1\n"
"%new1_i = OpIAdd %u32 %i1_val %one\n"
" OpStore %i1 %new1_i\n"
" OpBranch %loop1_entry\n"
"%loop1_merge = OpLabel\n"
// for (uint i = 6; i < n; ++i) c[i] = c[i - 4] + c[i - 5] + c[i - 6];
" OpBranch %loop2_entry\n"
"%loop2_entry = OpLabel\n"
"%i2_val = OpLoad %u32 %i2\n"
"%cmp2_lt = OpULessThan %bool %i2_val %twelve\n"
" OpLoopMerge %loop2_merge %loop2_body DependencyLength 3\n"
" OpBranchConditional %cmp2_lt %loop2_body %loop2_merge\n"
"%loop2_body = OpLabel\n"
"%i2_m4 = OpISub %u32 %i2_val %four\n"
"%arr1_i2m4loc = OpAccessChain %f32funcptr %f32arr12 %i2_m4\n"
"%arr1_i2m4val = OpLoad %f32 %arr1_i2m4loc\n"
"%i2_m5 = OpISub %u32 %i2_val %five\n"
"%arr1_i2m5loc = OpAccessChain %f32funcptr %f32arr12 %i2_m5\n"
"%arr1_i2m5val = OpLoad %f32 %arr1_i2m5loc\n"
"%f32add1 = OpFAdd %f32 %arr1_i2m4val %arr1_i2m5val\n"
"%i2_m6 = OpISub %u32 %i2_val %six\n"
"%arr1_i2m6loc = OpAccessChain %f32funcptr %f32arr12 %i2_m6\n"
"%arr1_i2m6val = OpLoad %f32 %arr1_i2m6loc\n"
"%f32add2 = OpFAdd %f32 %f32add1 %arr1_i2m6val\n"
"%outloc2 = OpAccessChain %f32funcptr %f32arr12 %i2_val\n"
" OpStore %outloc2 %f32add2\n"
"%new_i2 = OpIAdd %u32 %i2_val %one\n"
" OpStore %i2 %new_i2\n"
" OpBranch %loop2_entry\n"
"%loop2_merge = OpLabel\n"
// output_data.elements[x] = c[n - 1];
"%arr1locq = OpAccessChain %f32funcptr %f32arr12 %elleven\n"
"%arr1valq = OpLoad %f32 %arr1locq\n"
"%outlocq = OpAccessChain %f32ptr %outdata %zero %x\n"
" OpStore %outlocq %arr1valq\n"
" OpReturn\n"
" OpFunctionEnd\n";
}
static ComputeShaderSpec getComputeShaderSpec ()
{
de::Random rnd (0xABC);
const int numElements = 100;
vector<float> inputFloats (numElements, 0);
vector<float> outputFloats (numElements, 0);
ComputeShaderSpec spec;
for (size_t ndx = 0; ndx < numElements; ++ndx)
inputFloats[ndx] = rnd.getFloat(1.0f, 100.0f);
for (size_t ndx = 0; ndx < numElements; ++ndx)
{
const deUint32 n = 12;
float c[n];
for (deUint32 i = 0; i < 6; ++i)
c[i] = float(i) * inputFloats[ndx];
for (deUint32 i = 6; i < n; ++i)
c[i] = c[i - 4] + c[i - 5] + c[i - 6];
outputFloats[ndx] = c[n - 1];
}
// Shader source code can be retrieved to complete definition of ComputeShaderSpec, though it is not required at this stage
// getComputeSourceCode (spec.assembly);
spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
spec.numWorkGroups = tcu::IVec3(numElements, 1, 1);
spec.verifyIO = &verifyOutput;
return spec;
}
class SpvAsmLoopControlDependencyLengthInstance : public ComputeShaderSpec, public SpvAsmComputeShaderInstance
{
public:
SpvAsmLoopControlDependencyLengthInstance (Context& ctx);
};
SpvAsmLoopControlDependencyLengthInstance::SpvAsmLoopControlDependencyLengthInstance (Context& ctx)
: ComputeShaderSpec(getComputeShaderSpec())
, SpvAsmComputeShaderInstance(ctx, *this, COMPUTE_TEST_USES_NONE)
{
}
SpvAsmLoopControlDependencyLengthCase::SpvAsmLoopControlDependencyLengthCase (tcu::TestContext& testCtx, const char* name, const char* description)
: TestCase (testCtx, name, description)
{
}
void SpvAsmLoopControlDependencyLengthCase::initPrograms (SourceCollections& programCollection) const
{
std::string comp;
getComputeSourceCode(comp);
programCollection.spirvAsmSources.add("compute") << SpirVAsmBuildOptions(SPIRV_VERSION_1_3) << comp;
}
TestInstance* SpvAsmLoopControlDependencyLengthCase::createInstance (Context& context) const
{
if (context.contextSupports(vk::ApiVersion(1, 1, 0)))
TCU_THROW(NotSupportedError, "SPIR-V higher than 1.3 is required for this test to run");
return new SpvAsmLoopControlDependencyLengthInstance(context);
}
} // SpirVAssembly
} // vkt
|
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2017 The Khronos Group 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.
*
*//*!
* \file
* \brief SPIR-V Loop Control for DependencyLength qualifier tests
*//*--------------------------------------------------------------------*/
#include "vkApiVersion.hpp"
#include "vktSpvAsmLoopDepLenTests.hpp"
#include "vktTestCase.hpp"
#include "vktSpvAsmComputeShaderCase.hpp"
#include "deRandom.hpp"
namespace vkt
{
namespace SpirVAssembly
{
using namespace vk;
using std::map;
using std::string;
using std::vector;
// Assembly code used for testing loop control with dependencies is based on GLSL source code:
// #version 430
//
// layout(std140, set = 0, binding = 0) readonly buffer Input {
// float elements[];
// } input_data;
// layout(std140, set = 0, binding = 1) writeonly buffer Output {
// float elements[];
// } output_data;
//
// void main() {
// const uint n = 12;
// float c[n];
// uint x = gl_GlobalInvocationID.x;
//
// for (uint i = 0; i < 6; ++i)
// c[i] = float(i) * input_data.elements[x];
//
// for (uint i = 6; i < n; ++i)
// c[i] = c[i - 4] + c[i - 5] + c[i - 6];
//
// output_data.elements[x] = c[n - 1];
// }
static void getComputeSourceCode (std::string& computeSourceCode)
{
computeSourceCode =
string(getComputeAsmShaderPreamble()) +
"OpSource GLSL 430\n"
"OpName %main \"main\"\n"
"OpName %id \"gl_GlobalInvocationID\"\n"
"OpDecorate %id BuiltIn GlobalInvocationId\n"
+ string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
"%u32ptr = OpTypePointer Function %u32\n"
"%id = OpVariable %uvec3ptr Input\n"
"%zero = OpConstant %i32 0\n"
"%uzero = OpConstant %u32 0\n"
"%one = OpConstant %i32 1\n"
"%four = OpConstant %u32 4\n"
"%five = OpConstant %u32 5\n"
"%six = OpConstant %u32 6\n"
"%elleven = OpConstant %u32 11\n"
"%twelve = OpConstant %u32 12\n"
"%f32arr12_t = OpTypeArray %f32 %twelve\n"
"%f32arr12ptr_t = OpTypePointer Function %f32arr12_t\n"
"%f32funcptr = OpTypePointer Function %f32\n"
"%main = OpFunction %void None %voidf\n"
"%entry = OpLabel\n"
"%f32arr12 = OpVariable %f32arr12ptr_t Function\n"
"%i1 = OpVariable %u32ptr Function\n"
" OpStore %i1 %uzero\n"
"%i2 = OpVariable %u32ptr Function\n"
" OpStore %i2 %six\n"
"%idval = OpLoad %uvec3 %id\n"
"%x = OpCompositeExtract %u32 %idval 0\n"
"%inloc = OpAccessChain %f32ptr %indata %zero %x\n"
"%inval = OpLoad %f32 %inloc\n"
// for (uint i = 0; i < 6; ++i) c[i] = float(i) * input_data.elements[x];
" OpBranch %loop1_entry\n"
"%loop1_entry = OpLabel\n"
"%i1_val = OpLoad %u32 %i1\n"
"%cmp1_lt = OpULessThan %bool %i1_val %six\n"
" OpLoopMerge %loop1_merge %loop1_body None\n"
" OpBranchConditional %cmp1_lt %loop1_body %loop1_merge\n"
"%loop1_body = OpLabel\n"
"%i1_valf32 = OpConvertUToF %f32 %i1_val\n"
"%mulf1 = OpFMul %f32 %i1_valf32 %inval\n"
"%outloc1 = OpAccessChain %f32funcptr %f32arr12 %i1_val\n"
" OpStore %outloc1 %mulf1\n"
"%new1_i = OpIAdd %u32 %i1_val %one\n"
" OpStore %i1 %new1_i\n"
" OpBranch %loop1_entry\n"
"%loop1_merge = OpLabel\n"
// for (uint i = 6; i < n; ++i) c[i] = c[i - 4] + c[i - 5] + c[i - 6];
" OpBranch %loop2_entry\n"
"%loop2_entry = OpLabel\n"
"%i2_val = OpLoad %u32 %i2\n"
"%cmp2_lt = OpULessThan %bool %i2_val %twelve\n"
" OpLoopMerge %loop2_merge %loop2_body DependencyLength 3\n"
" OpBranchConditional %cmp2_lt %loop2_body %loop2_merge\n"
"%loop2_body = OpLabel\n"
"%i2_m4 = OpISub %u32 %i2_val %four\n"
"%arr1_i2m4loc = OpAccessChain %f32funcptr %f32arr12 %i2_m4\n"
"%arr1_i2m4val = OpLoad %f32 %arr1_i2m4loc\n"
"%i2_m5 = OpISub %u32 %i2_val %five\n"
"%arr1_i2m5loc = OpAccessChain %f32funcptr %f32arr12 %i2_m5\n"
"%arr1_i2m5val = OpLoad %f32 %arr1_i2m5loc\n"
"%f32add1 = OpFAdd %f32 %arr1_i2m4val %arr1_i2m5val\n"
"%i2_m6 = OpISub %u32 %i2_val %six\n"
"%arr1_i2m6loc = OpAccessChain %f32funcptr %f32arr12 %i2_m6\n"
"%arr1_i2m6val = OpLoad %f32 %arr1_i2m6loc\n"
"%f32add2 = OpFAdd %f32 %f32add1 %arr1_i2m6val\n"
"%outloc2 = OpAccessChain %f32funcptr %f32arr12 %i2_val\n"
" OpStore %outloc2 %f32add2\n"
"%new_i2 = OpIAdd %u32 %i2_val %one\n"
" OpStore %i2 %new_i2\n"
" OpBranch %loop2_entry\n"
"%loop2_merge = OpLabel\n"
// output_data.elements[x] = c[n - 1];
"%arr1locq = OpAccessChain %f32funcptr %f32arr12 %elleven\n"
"%arr1valq = OpLoad %f32 %arr1locq\n"
"%outlocq = OpAccessChain %f32ptr %outdata %zero %x\n"
" OpStore %outlocq %arr1valq\n"
" OpReturn\n"
" OpFunctionEnd\n";
}
static ComputeShaderSpec getComputeShaderSpec ()
{
de::Random rnd (0xABC);
const int numElements = 100;
vector<float> inputFloats (numElements, 0);
vector<float> outputFloats (numElements, 0);
ComputeShaderSpec spec;
for (size_t ndx = 0; ndx < numElements; ++ndx)
inputFloats[ndx] = rnd.getFloat(1.0f, 100.0f);
for (size_t ndx = 0; ndx < numElements; ++ndx)
{
const deUint32 n = 12;
float c[n];
for (deUint32 i = 0; i < 6; ++i)
c[i] = float(i) * inputFloats[ndx];
for (deUint32 i = 6; i < n; ++i)
c[i] = c[i - 4] + c[i - 5] + c[i - 6];
outputFloats[ndx] = c[n - 1];
}
// Shader source code can be retrieved to complete definition of ComputeShaderSpec, though it is not required at this stage
// getComputeSourceCode (spec.assembly);
spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
spec.numWorkGroups = tcu::IVec3(numElements, 1, 1);
spec.verifyIO = &verifyOutput;
return spec;
}
class SpvAsmLoopControlDependencyLengthInstance : public ComputeShaderSpec, public SpvAsmComputeShaderInstance
{
public:
SpvAsmLoopControlDependencyLengthInstance (Context& ctx);
};
SpvAsmLoopControlDependencyLengthInstance::SpvAsmLoopControlDependencyLengthInstance (Context& ctx)
: ComputeShaderSpec(getComputeShaderSpec())
, SpvAsmComputeShaderInstance(ctx, *this, COMPUTE_TEST_USES_NONE)
{
}
SpvAsmLoopControlDependencyLengthCase::SpvAsmLoopControlDependencyLengthCase (tcu::TestContext& testCtx, const char* name, const char* description)
: TestCase (testCtx, name, description)
{
}
void SpvAsmLoopControlDependencyLengthCase::initPrograms (SourceCollections& programCollection) const
{
std::string comp;
getComputeSourceCode(comp);
programCollection.spirvAsmSources.add("compute") << SpirVAsmBuildOptions(SPIRV_VERSION_1_3) << comp;
}
TestInstance* SpvAsmLoopControlDependencyLengthCase::createInstance (Context& context) const
{
if (!context.contextSupports(vk::ApiVersion(1, 1, 0)))
TCU_THROW(NotSupportedError, "SPIR-V higher than 1.3 is required for this test to run");
return new SpvAsmLoopControlDependencyLengthInstance(context);
}
} // SpirVAssembly
} // vkt
|
Fix regression from "Add contextSupports functions"
|
Fix regression from "Add contextSupports functions"
Fixes contextSupports condition for missing VK1.1.
This regression was introduced in 39a3dba450.
Affects:
dEQP-VK.spirv_assembly.instruction.compute.loop_control.dependency_infinite
dEQP-VK.spirv_assembly.instruction.compute.loop_control.dependency_length
Components: Vulkan
VK-GL-CTS issue: 727
Change-Id: I64c0b5fbd40f67ae6cfe314ac66ddc9d7f201dbb
|
C++
|
apache-2.0
|
googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,googlestadia/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS
|
3ba43ac975fae174454f38ec7ae9979ea0eb5964
|
editor/plugins/texture_editor_plugin.cpp
|
editor/plugins/texture_editor_plugin.cpp
|
/*************************************************************************/
/* texture_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture_editor_plugin.h"
#include "editor/editor_settings.h"
#include "io/resource_loader.h"
#include "project_settings.h"
void TextureEditor::_gui_input(Ref<InputEvent> p_event) {
}
void TextureEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_PHYSICS_PROCESS) {
}
if (p_what == NOTIFICATION_READY) {
//get_scene()->connect("node_removed",this,"_node_removed");
}
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> checkerboard = get_icon("Checkerboard", "EditorIcons");
Size2 size = get_size();
draw_texture_rect(checkerboard, Rect2(Point2(), size), true);
int tex_width = texture->get_width() * size.height / texture->get_height();
int tex_height = size.height;
if (tex_width > size.width) {
tex_width = size.width;
tex_height = texture->get_height() * tex_width / texture->get_width();
}
// Prevent the texture from being unpreviewable after the rescale, so that we can still see something
if (tex_height <= 0)
tex_height = 1;
if (tex_width <= 0)
tex_width = 1;
int ofs_x = (size.width - tex_width) / 2;
int ofs_y = (size.height - tex_height) / 2;
if (Object::cast_to<CurveTexture>(*texture)) {
// In the case of CurveTextures we know they are 1 in height, so fill the preview to see the gradient
ofs_y = 0;
tex_height = size.height;
}
draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height));
Ref<Font> font = get_font("font", "Label");
String format;
if (Object::cast_to<ImageTexture>(*texture)) {
format = Image::get_format_name(Object::cast_to<ImageTexture>(*texture)->get_format());
} else if (Object::cast_to<StreamTexture>(*texture)) {
format = Image::get_format_name(Object::cast_to<StreamTexture>(*texture)->get_format());
} else {
format = texture->get_class();
}
String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format;
Size2 rect = font->get_string_size(text);
Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2);
if (draw_from.x < 0)
draw_from.x = 0;
draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width);
}
}
void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) {
if (!is_visible())
return;
update();
}
void TextureEditor::edit(Ref<Texture> p_texture) {
if (!texture.is_null())
texture->remove_change_receptor(this);
texture = p_texture;
if (!texture.is_null()) {
texture->add_change_receptor(this);
update();
} else {
hide();
}
}
void TextureEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_gui_input"), &TextureEditor::_gui_input);
}
TextureEditor::TextureEditor() {
set_custom_minimum_size(Size2(1, 150));
}
void TextureEditorPlugin::edit(Object *p_object) {
Texture *s = Object::cast_to<Texture>(p_object);
if (!s)
return;
texture_editor->edit(Ref<Texture>(s));
}
bool TextureEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("Texture");
}
void TextureEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
texture_editor->show();
//texture_editor->set_process(true);
} else {
texture_editor->hide();
//texture_editor->set_process(false);
}
}
TextureEditorPlugin::TextureEditorPlugin(EditorNode *p_node) {
editor = p_node;
texture_editor = memnew(TextureEditor);
add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM, texture_editor);
texture_editor->hide();
}
TextureEditorPlugin::~TextureEditorPlugin() {
}
|
/*************************************************************************/
/* texture_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture_editor_plugin.h"
#include "editor/editor_settings.h"
#include "io/resource_loader.h"
#include "project_settings.h"
void TextureEditor::_gui_input(Ref<InputEvent> p_event) {
}
void TextureEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_PHYSICS_PROCESS) {
}
if (p_what == NOTIFICATION_READY) {
//get_scene()->connect("node_removed",this,"_node_removed");
}
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> checkerboard = get_icon("Checkerboard", "EditorIcons");
Size2 size = get_size();
draw_texture_rect(checkerboard, Rect2(Point2(), size), true);
int tex_width = texture->get_width() * size.height / texture->get_height();
int tex_height = size.height;
if (tex_width > size.width) {
tex_width = size.width;
tex_height = texture->get_height() * tex_width / texture->get_width();
}
// Prevent the texture from being unpreviewable after the rescale, so that we can still see something
if (tex_height <= 0)
tex_height = 1;
if (tex_width <= 0)
tex_width = 1;
int ofs_x = (size.width - tex_width) / 2;
int ofs_y = (size.height - tex_height) / 2;
if (Object::cast_to<CurveTexture>(*texture)) {
// In the case of CurveTextures we know they are 1 in height, so fill the preview to see the gradient
ofs_y = 0;
tex_height = size.height;
} else if (Object::cast_to<GradientTexture>(*texture)) {
ofs_y = size.height / 4.0;
tex_height = size.height / 2.0;
}
draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height));
Ref<Font> font = get_font("font", "Label");
String format;
if (Object::cast_to<ImageTexture>(*texture)) {
format = Image::get_format_name(Object::cast_to<ImageTexture>(*texture)->get_format());
} else if (Object::cast_to<StreamTexture>(*texture)) {
format = Image::get_format_name(Object::cast_to<StreamTexture>(*texture)->get_format());
} else {
format = texture->get_class();
}
String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format;
Size2 rect = font->get_string_size(text);
Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2);
if (draw_from.x < 0)
draw_from.x = 0;
draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width);
}
}
void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) {
if (!is_visible())
return;
update();
}
void TextureEditor::edit(Ref<Texture> p_texture) {
if (!texture.is_null())
texture->remove_change_receptor(this);
texture = p_texture;
if (!texture.is_null()) {
texture->add_change_receptor(this);
update();
} else {
hide();
}
}
void TextureEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_gui_input"), &TextureEditor::_gui_input);
}
TextureEditor::TextureEditor() {
set_custom_minimum_size(Size2(1, 150));
}
void TextureEditorPlugin::edit(Object *p_object) {
Texture *s = Object::cast_to<Texture>(p_object);
if (!s)
return;
texture_editor->edit(Ref<Texture>(s));
}
bool TextureEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("Texture");
}
void TextureEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
texture_editor->show();
//texture_editor->set_process(true);
} else {
texture_editor->hide();
//texture_editor->set_process(false);
}
}
TextureEditorPlugin::TextureEditorPlugin(EditorNode *p_node) {
editor = p_node;
texture_editor = memnew(TextureEditor);
add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM, texture_editor);
texture_editor->hide();
}
TextureEditorPlugin::~TextureEditorPlugin() {
}
|
Fix gradient texture preview
|
Fix gradient texture preview
|
C++
|
mit
|
sanikoyes/godot,sanikoyes/godot,BastiaanOlij/godot,groud/godot,josempans/godot,vnen/godot,akien-mga/godot,ex/godot,ex/godot,vkbsb/godot,mcanders/godot,honix/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,firefly2442/godot,guilhermefelipecgs/godot,Shockblast/godot,MarianoGnu/godot,vnen/godot,akien-mga/godot,godotengine/godot,DmitriySalnikov/godot,okamstudio/godot,groud/godot,okamstudio/godot,guilhermefelipecgs/godot,godotengine/godot,Shockblast/godot,DmitriySalnikov/godot,Paulloz/godot,Valentactive/godot,BastiaanOlij/godot,pkowal1982/godot,Valentactive/godot,Paulloz/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,MarianoGnu/godot,sanikoyes/godot,Paulloz/godot,ex/godot,okamstudio/godot,okamstudio/godot,mcanders/godot,sanikoyes/godot,firefly2442/godot,Valentactive/godot,NateWardawg/godot,firefly2442/godot,sanikoyes/godot,ZuBsPaCe/godot,ZuBsPaCe/godot,groud/godot,Zylann/godot,RandomShaper/godot,ZuBsPaCe/godot,Shockblast/godot,Zylann/godot,Faless/godot,okamstudio/godot,josempans/godot,Paulloz/godot,Zylann/godot,honix/godot,vnen/godot,BastiaanOlij/godot,groud/godot,BastiaanOlij/godot,firefly2442/godot,ex/godot,vkbsb/godot,vkbsb/godot,honix/godot,Faless/godot,akien-mga/godot,vnen/godot,akien-mga/godot,BastiaanOlij/godot,RandomShaper/godot,okamstudio/godot,BastiaanOlij/godot,honix/godot,NateWardawg/godot,firefly2442/godot,NateWardawg/godot,honix/godot,vkbsb/godot,josempans/godot,vnen/godot,groud/godot,pkowal1982/godot,ex/godot,MarianoGnu/godot,Shockblast/godot,okamstudio/godot,ZuBsPaCe/godot,Shockblast/godot,vkbsb/godot,BastiaanOlij/godot,Zylann/godot,pkowal1982/godot,honix/godot,Valentactive/godot,okamstudio/godot,mcanders/godot,NateWardawg/godot,MarianoGnu/godot,Faless/godot,akien-mga/godot,DmitriySalnikov/godot,Faless/godot,NateWardawg/godot,pkowal1982/godot,godotengine/godot,Faless/godot,vnen/godot,josempans/godot,Zylann/godot,josempans/godot,godotengine/godot,sanikoyes/godot,josempans/godot,ex/godot,Zylann/godot,Valentactive/godot,ex/godot,sanikoyes/godot,mcanders/godot,mcanders/godot,firefly2442/godot,groud/godot,DmitriySalnikov/godot,josempans/godot,guilhermefelipecgs/godot,Faless/godot,pkowal1982/godot,vnen/godot,Shockblast/godot,akien-mga/godot,okamstudio/godot,vkbsb/godot,pkowal1982/godot,NateWardawg/godot,Zylann/godot,Faless/godot,godotengine/godot,RandomShaper/godot,Shockblast/godot,MarianoGnu/godot,pkowal1982/godot,ex/godot,MarianoGnu/godot,ZuBsPaCe/godot,pkowal1982/godot,RandomShaper/godot,josempans/godot,godotengine/godot,ZuBsPaCe/godot,vkbsb/godot,guilhermefelipecgs/godot,akien-mga/godot,RandomShaper/godot,Shockblast/godot,DmitriySalnikov/godot,firefly2442/godot,guilhermefelipecgs/godot,DmitriySalnikov/godot,Faless/godot,MarianoGnu/godot,NateWardawg/godot,guilhermefelipecgs/godot,NateWardawg/godot,Paulloz/godot,NateWardawg/godot,RandomShaper/godot,mcanders/godot,Valentactive/godot,MarianoGnu/godot,Zylann/godot,godotengine/godot,firefly2442/godot,RandomShaper/godot,Paulloz/godot,okamstudio/godot,BastiaanOlij/godot,akien-mga/godot,guilhermefelipecgs/godot,vnen/godot,Valentactive/godot,Valentactive/godot,vkbsb/godot,sanikoyes/godot,Paulloz/godot,godotengine/godot
|
77fa3a9a63b59c02c62247fa1e7261ab5eefab20
|
src/compute_ma.cpp
|
src/compute_ma.cpp
|
// Copyright (c) 2015
// Ravi Peters -- [email protected]
// All rights reserved
// This file is part of masbcpp.
//
// masbcpp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// masbcpp 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 masbcpp. If not, see <http://www.gnu.org/licenses/>.
// #define VERBOSEPRINT 1;
// #define WITH_OPENMP 1;
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
// OpenMP
#ifdef WITH_OPENMP
#include <omp.h>
#endif
// Vrui
#include <vrui/Geometry/ComponentArray.h>
#include <vrui/Math/Math.h>
#ifndef __MINGW32__
#include <vrui/Misc/Timer.h>
#endif
// kdtree2
#include <kdtree2/kdtree2.hpp>
// cnpy
#include <cnpy/cnpy.h>
// tclap
#include <tclap/CmdLine.h>
// typedefs
#include "types.h"
// globals
Scalar initial_radius;
bool nan_for_initr;
double denoise_preserve;
double denoise_planar;
const Scalar delta_convergance = 1E-5;
const unsigned int iteration_limit = 30;
const Point nanPoint( std::numeric_limits<Scalar>::quiet_NaN() );
inline Scalar compute_radius(Point &p, Vector &n, Point &q)
{
// this is basic goniometry
double d = Geometry::mag(p-q);
Scalar cos_theta = ( n * (p-q) ) / d;
return d/(2*cos_theta);
}
inline Scalar cos_angle(Vector p, Vector q)
{
// Calculate the cosine of angle between vector p and q, see http://en.wikipedia.org/wiki/Law_of_cosines#Vector_formulation
Scalar result = p*q / ( Geometry::mag(p) * Geometry::mag(q) );
if( result > 1 ) return 1;
else if( result < -1 ) return -1;
return result;
}
ma_result sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)
{
unsigned int j=0;
Scalar r, r_previous = 0;
Point q, c_next;
int qidx;
Point c = p - n * initial_radius;
while (1)
{
#ifdef VERBOSEPRINT
std::cout << "\nloop iteration: " << j << ", p = (" << p[0] << "," << p[1] << "," << p[2] << ", n = (" << n[0] << "," << n[1] << "," << n[2] << ") \n";
std::cout << "c = (" << c[0] << "," << c[1] << "," << c[2] << ")\n";
#endif
// find closest point to c
kdtree2::KDTreeResultVector result;
kd_tree->n_nearest(c,2,result);
qidx = result[0].idx;
q = kd_tree->the_data[ qidx ];
#ifdef VERBOSEPRINT
std::cout << "q = (" << q[0] << "," << q[1] << "," << q[2] << ")\n";
#endif
// handle case when q==p
if( q == p )
{
// 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball
if( r_previous == initial_radius )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
// 2) otherwise just pick the second closest point
} else {
qidx = result[1].idx;
q = kd_tree->the_data[ qidx ];
}
}
// compute radius
r = compute_radius(p,n,q);
#ifdef VERBOSEPRINT
std::cout << "r = " << r << "\n";
#endif
// if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane
if( r < 0 )
r = initial_radius;
// if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop
else if( r > initial_radius )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
}
// compute next ball center
c_next = p - n * r;
// denoising
if( denoise_preserve or denoise_planar )
{
Scalar a = cos_angle(p-c_next, q-c_next);
Scalar separation_angle = Math::acos(a);
if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )
{
// keep previous radius:
r = r_previous;
break;
}
if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
}
}
// stop iteration if r has converged
if( Math::abs(r_previous-r) < delta_convergance )
break;
// stop iteration if this looks like an infinite loop:
if( j > iteration_limit )
break;
r_previous = r;
c = c_next;
j++;
}
return {c, qidx};
}
void sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, PointList &ma_coords, int* ma_qidx, bool inner=1)
{
Point p;
Vector n;
#pragma omp parallel for private(p, n)
for( unsigned int i=0; i<points.size(); i++ )
{
p = points[i];
if( inner )
n = normals[i];
else
n = -normals[i];
ma_result r = sb_point(p, n, kd_tree);
ma_coords[i] = r.c;
ma_qidx[i] = r.qidx;
}
// return ma_coords;
}
int main(int argc, char **argv)
{
// parse command line arguments
try {
TCLAP::CmdLine cmd("Computes a MAT point approximation, see also https://github.com/tudelft3d/masbcpp", ' ', "0.1");
TCLAP::UnlabeledValueArg<std::string> inputArg( "input", "path to directory with inside it a 'coords.npy' and a 'normals.npy' file. Both should be Nx3 float arrays where N is the number of input points.", true, "", "input dir", cmd);
TCLAP::UnlabeledValueArg<std::string> outputArg( "ouput", "path to output directory. Estimated MAT points are written to the files 'ma_coords_in.npy' and 'ma_coords_out.npy', for interior and exterior MAT respectively.", true, "", "output dir", cmd);
TCLAP::ValueArg<double> denoise_preserveArg("d","preserve","denoise preserve threshold",false,20,"double", cmd);
TCLAP::ValueArg<double> denoise_planarArg("p","planar","denoise planar threshold",false,32,"double", cmd);
TCLAP::ValueArg<double> initial_radiusArg("r","radius","initial ball radius",false,200,"double", cmd);
TCLAP::SwitchArg nan_for_initrSwitch("a","nan","write nan for points with radius equal to initial radius", cmd, false);
TCLAP::SwitchArg reorder_kdtreeSwitch("N","no-kdtree-reorder","Don't reorder kd-tree points: slower computation but lower memory use", cmd, true);
cmd.parse(argc,argv);
initial_radius = initial_radiusArg.getValue();
denoise_preserve = (3.1415/180) * denoise_preserveArg.getValue();
denoise_planar = (3.1415/180) * denoise_planarArg.getValue();
nan_for_initr = nan_for_initrSwitch.getValue();
bool kd_tree_reorder = reorder_kdtreeSwitch.getValue();
// check for proper in-output arguments and set in and output filepath strings
std::string input_coords_path = inputArg.getValue()+"/coords.npy";
std::string input_normals_path = inputArg.getValue()+"/normals.npy";
std::string output_path_ma_in = outputArg.getValue()+"/ma_coords_in.npy";
std::string output_path_ma_out = outputArg.getValue()+"/ma_coords_out.npy";
std::string output_path_ma_q_in = outputArg.getValue()+"/ma_qidx_in.npy";
std::string output_path_ma_q_out = outputArg.getValue()+"/ma_qidx_out.npy";
{
std::ifstream infile(input_coords_path.c_str());
if(!infile)
throw TCLAP::ArgParseException("invalid filepath", inputArg.getValue());
}
{
std::ifstream infile(input_normals_path.c_str());
if(!infile)
throw TCLAP::ArgParseException("invalid filepath", inputArg.getValue());
}
{
std::ofstream outfile(output_path_ma_in.c_str());
if(!outfile)
throw TCLAP::ArgParseException("invalid filepath", outputArg.getValue());
}
std::cout << "Parameters: denoise_preserve="<<denoise_preserveArg.getValue()<<", denoise_planar="<<denoise_planarArg.getValue()<<", initial_radius="<<initial_radius<<"\n";
cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );
float* coords_carray = reinterpret_cast<float*>(coords_npy.data);
unsigned int num_points = coords_npy.shape[0];
unsigned int dim = coords_npy.shape[1];
PointList coords(num_points);
for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);
coords_npy.destruct();
cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );
float* normals_carray = reinterpret_cast<float*>(normals_npy.data);
VectorList normals(normals_npy.shape[0]);
for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);
normals_npy.destruct();
#ifndef __MINGW32__
Misc::Timer t0;
#endif
kdtree2::KDTree* kd_tree;
kd_tree = new kdtree2::KDTree(coords,kd_tree_reorder);
kd_tree->sort_results = true;
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Constructed kd-tree in "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
// omp_set_num_threads(4);
{
PointList ma_coords_in(coords.size());
int* ma_qidx_in = new int[num_points];
sb_points(coords, normals, kd_tree, ma_coords_in, ma_qidx_in, 1);
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Done shrinking interior balls, took "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
Scalar* ma_coords_in_carray = new Scalar[num_points*3];
for (int i=0; i<ma_coords_in.size(); i++)
for (int j=0; j<3; j++)
ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];
const unsigned int c_size = ma_coords_in.size();
const unsigned int shape[] = {c_size,3};
cnpy::npy_save(output_path_ma_in.c_str(), ma_coords_in_carray, shape, 2, "w");
const unsigned int shape_[] = {c_size};
cnpy::npy_save(output_path_ma_q_in.c_str(), ma_qidx_in, shape_, 1, "w");
}
{
PointList ma_coords_out(coords.size());
int* ma_qidx_out = new int[num_points];
sb_points(coords, normals, kd_tree, ma_coords_out, ma_qidx_out, 0);
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Done shrinking exterior balls, took "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
Scalar* ma_coords_out_carray = new Scalar[num_points*3];
for (int i=0; i<ma_coords_out.size(); i++)
for (int j=0; j<3; j++)
ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];
const unsigned int c_size = ma_coords_out.size();
const unsigned int shape[] = {c_size,3};
cnpy::npy_save(output_path_ma_out.c_str(), ma_coords_out_carray, shape, 2, "w");
const unsigned int shape_[] = {c_size};
cnpy::npy_save(output_path_ma_q_out.c_str(), ma_qidx_out, shape_, 1, "w");
}
} catch (TCLAP::ArgException &e) { std::cerr << "Error: " << e.error() << " for " << e.argId() << std::endl; }
return 0;
}
|
// Copyright (c) 2015
// Ravi Peters -- [email protected]
// All rights reserved
// This file is part of masbcpp.
//
// masbcpp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// masbcpp 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 masbcpp. If not, see <http://www.gnu.org/licenses/>.
// #define VERBOSEPRINT 1;
// #define WITH_OPENMP 1;
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
// OpenMP
#ifdef WITH_OPENMP
#include <omp.h>
#endif
// Vrui
#include <vrui/Geometry/ComponentArray.h>
#include <vrui/Math/Math.h>
#ifndef __MINGW32__
#include <vrui/Misc/Timer.h>
#endif
// kdtree2
#include <kdtree2/kdtree2.hpp>
// cnpy
#include <cnpy/cnpy.h>
// tclap
#include <tclap/CmdLine.h>
// typedefs
#include "types.h"
// globals
Scalar initial_radius;
bool nan_for_initr;
double denoise_preserve;
double denoise_planar;
const Scalar delta_convergance = 1E-5;
const unsigned int iteration_limit = 30;
const Point nanPoint( std::numeric_limits<Scalar>::quiet_NaN() );
inline Scalar compute_radius(Point &p, Vector &n, Point &q)
{
// this is basic goniometry
double d = Geometry::mag(p-q);
Scalar cos_theta = ( n * (p-q) ) / d;
return d/(2*cos_theta);
}
inline Scalar cos_angle(Vector p, Vector q)
{
// Calculate the cosine of angle between vector p and q, see http://en.wikipedia.org/wiki/Law_of_cosines#Vector_formulation
Scalar result = p*q / ( Geometry::mag(p) * Geometry::mag(q) );
if( result > 1 ) return 1;
else if( result < -1 ) return -1;
return result;
}
ma_result sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)
{
unsigned int j=0;
Scalar r, r_previous = 0;
Point q, c_next;
int qidx = -1, qidx_next;
Point c = p - n * initial_radius;
while (1)
{
#ifdef VERBOSEPRINT
std::cout << "\nloop iteration: " << j << ", p = (" << p[0] << "," << p[1] << "," << p[2] << ", n = (" << n[0] << "," << n[1] << "," << n[2] << ") \n";
std::cout << "c = (" << c[0] << "," << c[1] << "," << c[2] << ")\n";
#endif
// find closest point to c
kdtree2::KDTreeResultVector result;
kd_tree->n_nearest(c,2,result);
qidx_next = result[0].idx;
q = kd_tree->the_data[ qidx_next ];
#ifdef VERBOSEPRINT
std::cout << "q = (" << q[0] << "," << q[1] << "," << q[2] << ")\n";
#endif
// handle case when q==p
if( q == p )
{
// 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball
if( r_previous == initial_radius )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
// 2) otherwise just pick the second closest point
} else {
qidx_next = result[1].idx;
q = kd_tree->the_data[ qidx_next ];
}
}
// compute radius
r = compute_radius(p,n,q);
#ifdef VERBOSEPRINT
std::cout << "r = " << r << "\n";
#endif
// if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane
if( r < 0 )
r = initial_radius;
// if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop
else if( r > initial_radius )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
}
// compute next ball center
c_next = p - n * r;
// denoising
if( denoise_preserve or denoise_planar )
{
Scalar a = cos_angle(p-c_next, q-c_next);
Scalar separation_angle = Math::acos(a);
if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )
{
// keep previous radius:
r = r_previous;
break;
}
if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )
{
r = initial_radius;
c = nan_for_initr ? nanPoint : p - n * r;
break;
}
}
// stop iteration if r has converged
if( Math::abs(r_previous-r) < delta_convergance )
break;
// stop iteration if this looks like an infinite loop:
if( j > iteration_limit )
break;
r_previous = r;
c = c_next;
qidx = qidx_next;
j++;
}
return {c, qidx};
}
void sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, PointList &ma_coords, int* ma_qidx, bool inner=1)
{
Point p;
Vector n;
#pragma omp parallel for private(p, n)
for( unsigned int i=0; i<points.size(); i++ )
{
p = points[i];
if( inner )
n = normals[i];
else
n = -normals[i];
ma_result r = sb_point(p, n, kd_tree);
ma_coords[i] = r.c;
ma_qidx[i] = r.qidx;
}
// return ma_coords;
}
int main(int argc, char **argv)
{
// parse command line arguments
try {
TCLAP::CmdLine cmd("Computes a MAT point approximation, see also https://github.com/tudelft3d/masbcpp", ' ', "0.1");
TCLAP::UnlabeledValueArg<std::string> inputArg( "input", "path to directory with inside it a 'coords.npy' and a 'normals.npy' file. Both should be Nx3 float arrays where N is the number of input points.", true, "", "input dir", cmd);
TCLAP::UnlabeledValueArg<std::string> outputArg( "ouput", "path to output directory. Estimated MAT points are written to the files 'ma_coords_in.npy' and 'ma_coords_out.npy', for interior and exterior MAT respectively.", true, "", "output dir", cmd);
TCLAP::ValueArg<double> denoise_preserveArg("d","preserve","denoise preserve threshold",false,20,"double", cmd);
TCLAP::ValueArg<double> denoise_planarArg("p","planar","denoise planar threshold",false,32,"double", cmd);
TCLAP::ValueArg<double> initial_radiusArg("r","radius","initial ball radius",false,200,"double", cmd);
TCLAP::SwitchArg nan_for_initrSwitch("a","nan","write nan for points with radius equal to initial radius", cmd, false);
TCLAP::SwitchArg reorder_kdtreeSwitch("N","no-kdtree-reorder","Don't reorder kd-tree points: slower computation but lower memory use", cmd, true);
cmd.parse(argc,argv);
initial_radius = initial_radiusArg.getValue();
denoise_preserve = (3.1415/180) * denoise_preserveArg.getValue();
denoise_planar = (3.1415/180) * denoise_planarArg.getValue();
nan_for_initr = nan_for_initrSwitch.getValue();
bool kd_tree_reorder = reorder_kdtreeSwitch.getValue();
// check for proper in-output arguments and set in and output filepath strings
std::string input_coords_path = inputArg.getValue()+"/coords.npy";
std::string input_normals_path = inputArg.getValue()+"/normals.npy";
std::string output_path_ma_in = outputArg.getValue()+"/ma_coords_in.npy";
std::string output_path_ma_out = outputArg.getValue()+"/ma_coords_out.npy";
std::string output_path_ma_q_in = outputArg.getValue()+"/ma_qidx_in.npy";
std::string output_path_ma_q_out = outputArg.getValue()+"/ma_qidx_out.npy";
{
std::ifstream infile(input_coords_path.c_str());
if(!infile)
throw TCLAP::ArgParseException("invalid filepath", inputArg.getValue());
}
{
std::ifstream infile(input_normals_path.c_str());
if(!infile)
throw TCLAP::ArgParseException("invalid filepath", inputArg.getValue());
}
{
std::ofstream outfile(output_path_ma_in.c_str());
if(!outfile)
throw TCLAP::ArgParseException("invalid filepath", outputArg.getValue());
}
std::cout << "Parameters: denoise_preserve="<<denoise_preserveArg.getValue()<<", denoise_planar="<<denoise_planarArg.getValue()<<", initial_radius="<<initial_radius<<"\n";
cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );
float* coords_carray = reinterpret_cast<float*>(coords_npy.data);
unsigned int num_points = coords_npy.shape[0];
unsigned int dim = coords_npy.shape[1];
PointList coords(num_points);
for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);
coords_npy.destruct();
cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );
float* normals_carray = reinterpret_cast<float*>(normals_npy.data);
VectorList normals(normals_npy.shape[0]);
for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);
normals_npy.destruct();
#ifndef __MINGW32__
Misc::Timer t0;
#endif
kdtree2::KDTree* kd_tree;
kd_tree = new kdtree2::KDTree(coords,kd_tree_reorder);
kd_tree->sort_results = true;
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Constructed kd-tree in "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
// omp_set_num_threads(4);
{
PointList ma_coords_in(coords.size());
int* ma_qidx_in = new int[num_points];
sb_points(coords, normals, kd_tree, ma_coords_in, ma_qidx_in, 1);
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Done shrinking interior balls, took "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
Scalar* ma_coords_in_carray = new Scalar[num_points*3];
for (int i=0; i<ma_coords_in.size(); i++)
for (int j=0; j<3; j++)
ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];
const unsigned int c_size = ma_coords_in.size();
const unsigned int shape[] = {c_size,3};
cnpy::npy_save(output_path_ma_in.c_str(), ma_coords_in_carray, shape, 2, "w");
const unsigned int shape_[] = {c_size};
cnpy::npy_save(output_path_ma_q_in.c_str(), ma_qidx_in, shape_, 1, "w");
}
{
PointList ma_coords_out(coords.size());
int* ma_qidx_out = new int[num_points];
sb_points(coords, normals, kd_tree, ma_coords_out, ma_qidx_out, 0);
#ifndef __MINGW32__
t0.elapse();
std::cout<<"Done shrinking exterior balls, took "<<t0.getTime()*1000.0<<" ms"<<std::endl;
#endif
Scalar* ma_coords_out_carray = new Scalar[num_points*3];
for (int i=0; i<ma_coords_out.size(); i++)
for (int j=0; j<3; j++)
ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];
const unsigned int c_size = ma_coords_out.size();
const unsigned int shape[] = {c_size,3};
cnpy::npy_save(output_path_ma_out.c_str(), ma_coords_out_carray, shape, 2, "w");
const unsigned int shape_[] = {c_size};
cnpy::npy_save(output_path_ma_q_out.c_str(), ma_qidx_out, shape_, 1, "w");
}
} catch (TCLAP::ArgException &e) { std::cerr << "Error: " << e.error() << " for " << e.argId() << std::endl; }
return 0;
}
|
fix bug that caused the feature point of the wrong iteration to be stored
|
fix bug that caused the feature point of the wrong iteration to be stored
|
C++
|
mit
|
KevinWiebe/masbcpp,tudelft3d/masbcpp,KevinWiebe/masbcpp,tudelft3d/masbcpp,jeffcoukell/masbcpp,jeffcoukell/masbcpp
|
17dc0dfe7eed46ec21bca5814c9bc1e23b87befc
|
chrome/browser/ui/touch/frame/touch_browser_frame_view.cc
|
chrome/browser/ui/touch/frame/touch_browser_frame_view.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/gfx/rect.h"
#include "views/controls/button/image_button.h"
#include "views/controls/textfield/textfield.h"
namespace {
const int kKeyboardHeight = 300;
const int kKeyboardSlideDuration = 500; // In milliseconds
PropertyAccessor<bool>* GetFocusedStateAccessor() {
static PropertyAccessor<bool> state;
return &state;
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, public:
TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,
BrowserView* browser_view)
: OpaqueBrowserFrameView(frame, browser_view),
keyboard_showing_(false),
focus_listener_added_(false),
keyboard_(NULL) {
registrar_.Add(this,
NotificationType::NAV_ENTRY_COMMITTED,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::FOCUS_CHANGED_IN_PAGE,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
NotificationService::AllSources());
browser_view->browser()->tabstrip_model()->AddObserver(this);
animation_.reset(new ui::SlideAnimation(this));
animation_->SetTweenType(ui::Tween::LINEAR);
animation_->SetSlideDuration(kKeyboardSlideDuration);
}
TouchBrowserFrameView::~TouchBrowserFrameView() {
browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
}
void TouchBrowserFrameView::Layout() {
OpaqueBrowserFrameView::Layout();
if (!keyboard_)
return;
keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());
gfx::Rect bounds = GetBoundsForReservedArea();
if (animation_->is_animating() && !keyboard_showing_) {
// The keyboard is in the process of hiding. So pretend it still has the
// same bounds as when the keyboard is visible. But
// |GetBoundsForReservedArea| should not take this into account so that the
// render view gets the entire area to relayout itself.
bounds.set_y(bounds.y() - kKeyboardHeight);
bounds.set_height(kKeyboardHeight);
}
keyboard_->SetBoundsRect(bounds);
}
void TouchBrowserFrameView::FocusWillChange(views::View* focused_before,
views::View* focused_now) {
VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
if (before != now) {
// TODO(varunjain): support other types of keyboard.
UpdateKeyboardAndLayout(now == GENERIC);
}
}
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, protected:
int TouchBrowserFrameView::GetReservedHeight() const {
return keyboard_showing_ ? kKeyboardHeight : 0;
}
void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);
if (!GetFocusManager())
return;
if (is_add && !focus_listener_added_) {
// Add focus listener when this view is added to the hierarchy.
GetFocusManager()->AddFocusChangeListener(this);
focus_listener_added_ = true;
} else if (!is_add && focus_listener_added_) {
// Remove focus listener when this view is removed from the hierarchy.
GetFocusManager()->RemoveFocusChangeListener(this);
focus_listener_added_ = false;
}
}
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, private:
void TouchBrowserFrameView::InitVirtualKeyboard() {
if (keyboard_)
return;
Profile* keyboard_profile = browser_view()->browser()->profile();
DCHECK(keyboard_profile) << "Profile required for virtual keyboard.";
keyboard_ = new KeyboardContainerView(keyboard_profile);
keyboard_->SetVisible(false);
AddChildView(keyboard_);
}
void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
if (should_show_keyboard)
InitVirtualKeyboard();
if (should_show_keyboard == keyboard_showing_)
return;
DCHECK(keyboard_);
keyboard_showing_ = should_show_keyboard;
if (keyboard_showing_) {
animation_->Show();
// We don't re-layout the client view until the animation ends (see
// AnimationEnded below) because we want the client view to occupy the
// entire height during the animation.
Layout();
} else {
animation_->Hide();
browser_view()->set_clip_y(ui::Tween::ValueBetween(
animation_->GetCurrentValue(), 0, kKeyboardHeight));
parent()->Layout();
}
}
TouchBrowserFrameView::VirtualKeyboardType
TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {
if (!view)
return NONE;
std::string cname = view->GetClassName();
if (cname == views::Textfield::kViewClassName) {
return GENERIC;
} else if (cname == RenderWidgetHostViewViews::kViewClassName) {
TabContents* contents = browser_view()->browser()->GetSelectedTabContents();
bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
contents->property_bag()) : NULL;
if (editable && *editable)
return GENERIC;
}
return NONE;
}
bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {
if (OpaqueBrowserFrameView::HitTest(point))
return true;
if (close_button()->IsVisible() &&
close_button()->GetMirroredBounds().Contains(point))
return true;
if (restore_button()->IsVisible() &&
restore_button()->GetMirroredBounds().Contains(point))
return true;
if (maximize_button()->IsVisible() &&
maximize_button()->GetMirroredBounds().Contains(point))
return true;
if (minimize_button()->IsVisible() &&
minimize_button()->GetMirroredBounds().Contains(point))
return true;
return false;
}
void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,
TabContentsWrapper* new_contents,
int index,
bool user_gesture) {
if (new_contents == old_contents)
return;
TabContents* contents = new_contents->tab_contents();
bool* editable = GetFocusedStateAccessor()->GetProperty(
contents->property_bag());
UpdateKeyboardAndLayout(editable ? *editable : false);
}
void TouchBrowserFrameView::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Browser* browser = browser_view()->browser();
if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
// Only modify the keyboard state if the currently active tab sent the
// notification.
const TabContents* current_tab = browser->GetSelectedTabContents();
TabContents* source_tab = Source<TabContents>(source).ptr();
const bool editable = *Details<const bool>(details).ptr();
if (current_tab == source_tab) {
UpdateKeyboardAndLayout(editable);
}
// Save the state of the focused field so that the keyboard visibility
// can be determined after tab switching.
GetFocusedStateAccessor()->SetProperty(
source_tab->property_bag(), editable);
} else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
Browser* source_browser = Browser::GetBrowserForController(
Source<NavigationController>(source).ptr(), NULL);
// If the Browser for the keyboard has navigated, hide the keyboard.
if (source_browser == browser)
UpdateKeyboardAndLayout(false);
} else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
GetFocusedStateAccessor()->DeleteProperty(
Source<TabContents>(source).ptr()->property_bag());
}
}
///////////////////////////////////////////////////////////////////////////////
// ui::AnimationDelegate implementation
void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {
keyboard_->SetTranslateY(
ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));
browser_view()->set_clip_y(
ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));
SchedulePaint();
}
void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {
browser_view()->set_clip_y(0);
if (keyboard_showing_) {
// Because the NonClientFrameView is a sibling of the ClientView, we rely on
// the parent to resize the ClientView instead of resizing it directly.
parent()->Layout();
// The keyboard that pops up may end up hiding the text entry. So make sure
// the renderer scrolls when necessary to keep the textfield visible.
RenderViewHost* host =
browser_view()->browser()->GetSelectedTabContents()->render_view_host();
host->ScrollFocusedEditableNodeIntoView();
}
SchedulePaint();
}
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/touch/frame/keyboard_container_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/gfx/rect.h"
#include "views/controls/button/image_button.h"
#include "views/controls/textfield/textfield.h"
#include "views/focus/focus_manager.h"
namespace {
const int kKeyboardHeight = 300;
const int kKeyboardSlideDuration = 500; // In milliseconds
PropertyAccessor<bool>* GetFocusedStateAccessor() {
static PropertyAccessor<bool> state;
return &state;
}
bool TabContentsHasFocus(const TabContents* contents) {
views::View* view = static_cast<TabContentsViewViews*>(contents->view());
return view->Contains(view->GetFocusManager()->GetFocusedView());
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, public:
TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,
BrowserView* browser_view)
: OpaqueBrowserFrameView(frame, browser_view),
keyboard_showing_(false),
focus_listener_added_(false),
keyboard_(NULL) {
registrar_.Add(this,
NotificationType::NAV_ENTRY_COMMITTED,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::FOCUS_CHANGED_IN_PAGE,
NotificationService::AllSources());
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
NotificationService::AllSources());
browser_view->browser()->tabstrip_model()->AddObserver(this);
animation_.reset(new ui::SlideAnimation(this));
animation_->SetTweenType(ui::Tween::LINEAR);
animation_->SetSlideDuration(kKeyboardSlideDuration);
}
TouchBrowserFrameView::~TouchBrowserFrameView() {
browser_view()->browser()->tabstrip_model()->RemoveObserver(this);
}
void TouchBrowserFrameView::Layout() {
OpaqueBrowserFrameView::Layout();
if (!keyboard_)
return;
keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());
gfx::Rect bounds = GetBoundsForReservedArea();
if (animation_->is_animating() && !keyboard_showing_) {
// The keyboard is in the process of hiding. So pretend it still has the
// same bounds as when the keyboard is visible. But
// |GetBoundsForReservedArea| should not take this into account so that the
// render view gets the entire area to relayout itself.
bounds.set_y(bounds.y() - kKeyboardHeight);
bounds.set_height(kKeyboardHeight);
}
keyboard_->SetBoundsRect(bounds);
}
void TouchBrowserFrameView::FocusWillChange(views::View* focused_before,
views::View* focused_now) {
VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);
VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);
if (before != now) {
// TODO(varunjain): support other types of keyboard.
UpdateKeyboardAndLayout(now == GENERIC);
}
}
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, protected:
int TouchBrowserFrameView::GetReservedHeight() const {
return keyboard_showing_ ? kKeyboardHeight : 0;
}
void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);
if (!GetFocusManager())
return;
if (is_add && !focus_listener_added_) {
// Add focus listener when this view is added to the hierarchy.
GetFocusManager()->AddFocusChangeListener(this);
focus_listener_added_ = true;
} else if (!is_add && focus_listener_added_) {
// Remove focus listener when this view is removed from the hierarchy.
GetFocusManager()->RemoveFocusChangeListener(this);
focus_listener_added_ = false;
}
}
///////////////////////////////////////////////////////////////////////////////
// TouchBrowserFrameView, private:
void TouchBrowserFrameView::InitVirtualKeyboard() {
if (keyboard_)
return;
Profile* keyboard_profile = browser_view()->browser()->profile();
DCHECK(keyboard_profile) << "Profile required for virtual keyboard.";
keyboard_ = new KeyboardContainerView(keyboard_profile);
keyboard_->SetVisible(false);
AddChildView(keyboard_);
}
void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {
if (should_show_keyboard)
InitVirtualKeyboard();
if (should_show_keyboard == keyboard_showing_)
return;
DCHECK(keyboard_);
keyboard_showing_ = should_show_keyboard;
if (keyboard_showing_) {
animation_->Show();
// We don't re-layout the client view until the animation ends (see
// AnimationEnded below) because we want the client view to occupy the
// entire height during the animation.
Layout();
} else {
animation_->Hide();
browser_view()->set_clip_y(ui::Tween::ValueBetween(
animation_->GetCurrentValue(), 0, kKeyboardHeight));
parent()->Layout();
}
}
TouchBrowserFrameView::VirtualKeyboardType
TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {
if (!view)
return NONE;
std::string cname = view->GetClassName();
if (cname == views::Textfield::kViewClassName) {
return GENERIC;
} else if (cname == RenderWidgetHostViewViews::kViewClassName) {
TabContents* contents = browser_view()->browser()->GetSelectedTabContents();
bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(
contents->property_bag()) : NULL;
if (editable && *editable)
return GENERIC;
}
return NONE;
}
bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {
if (OpaqueBrowserFrameView::HitTest(point))
return true;
if (close_button()->IsVisible() &&
close_button()->GetMirroredBounds().Contains(point))
return true;
if (restore_button()->IsVisible() &&
restore_button()->GetMirroredBounds().Contains(point))
return true;
if (maximize_button()->IsVisible() &&
maximize_button()->GetMirroredBounds().Contains(point))
return true;
if (minimize_button()->IsVisible() &&
minimize_button()->GetMirroredBounds().Contains(point))
return true;
return false;
}
void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,
TabContentsWrapper* new_contents,
int index,
bool user_gesture) {
if (new_contents == old_contents)
return;
TabContents* contents = new_contents->tab_contents();
if (!TabContentsHasFocus(contents))
return;
bool* editable = GetFocusedStateAccessor()->GetProperty(
contents->property_bag());
UpdateKeyboardAndLayout(editable ? *editable : false);
}
void TouchBrowserFrameView::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Browser* browser = browser_view()->browser();
if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {
// Only modify the keyboard state if the currently active tab sent the
// notification.
const TabContents* current_tab = browser->GetSelectedTabContents();
TabContents* source_tab = Source<TabContents>(source).ptr();
const bool editable = *Details<const bool>(details).ptr();
if (current_tab == source_tab && TabContentsHasFocus(source_tab))
UpdateKeyboardAndLayout(editable);
// Save the state of the focused field so that the keyboard visibility
// can be determined after tab switching.
GetFocusedStateAccessor()->SetProperty(
source_tab->property_bag(), editable);
} else if (type == NotificationType::NAV_ENTRY_COMMITTED) {
Browser* source_browser = Browser::GetBrowserForController(
Source<NavigationController>(source).ptr(), NULL);
// If the Browser for the keyboard has navigated, re-evaluate the visibility
// of the keyboard.
if (source_browser == browser)
UpdateKeyboardAndLayout(DecideKeyboardStateForView(
GetFocusManager()->GetFocusedView()) == GENERIC);
} else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {
GetFocusedStateAccessor()->DeleteProperty(
Source<TabContents>(source).ptr()->property_bag());
}
}
///////////////////////////////////////////////////////////////////////////////
// ui::AnimationDelegate implementation
void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {
keyboard_->SetTranslateY(
ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));
browser_view()->set_clip_y(
ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));
SchedulePaint();
}
void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {
browser_view()->set_clip_y(0);
if (keyboard_showing_) {
// Because the NonClientFrameView is a sibling of the ClientView, we rely on
// the parent to resize the ClientView instead of resizing it directly.
parent()->Layout();
// The keyboard that pops up may end up hiding the text entry. So make sure
// the renderer scrolls when necessary to keep the textfield visible.
RenderViewHost* host =
browser_view()->browser()->GetSelectedTabContents()->render_view_host();
host->ScrollFocusedEditableNodeIntoView();
}
SchedulePaint();
}
|
Update the keyboard visibility more intelligently.
|
touch: Update the keyboard visibility more intelligently.
BUG=76347
TEST=manually
Review URL: http://codereview.chromium.org/6667040
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@78480 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,ltilve/chromium,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,robclark/chromium,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,jaruba/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,Just-D/chromium-1,mogoweb/chromium-crosswalk,keishi/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,keishi/chromium,M4sse/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,timopulkkinen/BubbleFish,keishi/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,Just-D/chromium-1,robclark/chromium,hgl888/chromium-crosswalk-efl,rogerwang/chromium,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,hujiajie/pa-chromium,keishi/chromium,keishi/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,rogerwang/chromium,ltilve/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,robclark/chromium,mogoweb/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,robclark/chromium,ondra-novak/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,anirudhSK/chromium,markYoungH/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,keishi/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,ltilve/chromium,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,anirudhSK/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,Chilledheart/chromium,dednal/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,anirudhSK/chromium,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hujiajie/pa-chromium,jaruba/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,littlstar/chromium.src,patrickm/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,anirudhSK/chromium,Just-D/chromium-1,zcbenz/cefode-chromium,dednal/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail
|
caa23d4baaaf7206f353203ca7b1780d482f4881
|
cvmfs/authz/helper_log.cc
|
cvmfs/authz/helper_log.cc
|
/**
* This file is part of the CernVM File System.
*/
#include "helper_log.h"
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <unistd.h>
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std; // NOLINT
namespace {
int fd_debug = -1;
FILE *file_debug = NULL;
int syslog_facility = LOG_USER;
int syslog_level = LOG_NOTICE;
char *syslog_prefix = NULL;
}
void SetLogAuthzDebug(const string &path) {
assert(!path.empty());
if (fd_debug >= 0)
close(fd_debug);
int fd_debug = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0600);
if (fd_debug < 0) {
syslog(LOG_USER | LOG_ERR, "could not open debug log %s (%d), abort",
path.c_str(), errno);
abort();
}
file_debug = fdopen(fd_debug, "a");
assert(file_debug != NULL);
}
void SetLogAuthzSyslogLevel(const int level) {
switch (level) {
case 1:
syslog_level = LOG_DEBUG;
break;
case 2:
syslog_level = LOG_INFO;
break;
case 3:
syslog_level = LOG_NOTICE;
break;
default:
syslog_level = LOG_NOTICE;
break;
}
}
void SetLogAuthzSyslogFacility(const int local_facility) {
switch (local_facility) {
case 0:
syslog_facility = LOG_LOCAL0;
break;
case 1:
syslog_facility = LOG_LOCAL1;
break;
case 2:
syslog_facility = LOG_LOCAL2;
break;
case 3:
syslog_facility = LOG_LOCAL3;
break;
case 4:
syslog_facility = LOG_LOCAL4;
break;
case 5:
syslog_facility = LOG_LOCAL5;
break;
case 6:
syslog_facility = LOG_LOCAL6;
break;
case 7:
syslog_facility = LOG_LOCAL7;
break;
default:
syslog_facility = LOG_USER;
}
}
void SetLogAuthzSyslogPrefix(const string &prefix) {
if (syslog_prefix)
free(syslog_prefix);
if (prefix == "") {
syslog_prefix = NULL;
} else {
unsigned len = prefix.length() + 1;
syslog_prefix = static_cast<char *>(malloc(len));
assert(syslog_prefix != NULL);
syslog_prefix[len-1] = '\0';
memcpy(syslog_prefix, &prefix[0], prefix.length());
}
}
void LogAuthz(const int flags, const char *format, ...) {
char *msg = NULL;
va_list variadic_list;
va_start(variadic_list, format);
int retval = vasprintf(&msg, format, variadic_list);
assert(retval != -1); // else: out of memory
va_end(variadic_list);
if ((flags & kLogAuthzDebug) && (file_debug != NULL)) {
time_t rawtime;
time(&rawtime);
struct tm now;
localtime_r(&rawtime, &now);
fprintf(file_debug, "%s [%02d-%02d-%04d %02d:%02d:%02d %s]\n", msg,
(now.tm_mon)+1, now.tm_mday, (now.tm_year)+1900, now.tm_hour,
now.tm_min, now.tm_sec, now.tm_zone);
fflush(file_debug);
}
if (flags & (kLogAuthzSyslog | kLogAuthzSyslogWarn | kLogAuthzSyslogErr)) {
int level = syslog_level;
if (flags & kLogAuthzSyslogWarn) level = LOG_WARNING;
if (flags & kLogAuthzSyslogErr) level = LOG_ERR;
if (syslog_prefix) {
syslog(syslog_facility | level, "(%s) %s", syslog_prefix, msg);
} else {
syslog(syslog_facility | level, "%s", msg);
}
}
free(msg);
}
|
/**
* This file is part of the CernVM File System.
*/
#include "helper_log.h"
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <unistd.h>
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std; // NOLINT
namespace {
int fd_debug = -1;
FILE *file_debug = NULL;
int syslog_facility = LOG_USER;
int syslog_level = LOG_NOTICE;
char *syslog_prefix = NULL;
}
void SetLogAuthzDebug(const string &path) {
assert(!path.empty());
if (fd_debug >= 0)
close(fd_debug);
int fd_debug = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0600);
if (fd_debug < 0) {
syslog(LOG_USER | LOG_ERR, "could not open debug log %s (%d), abort",
path.c_str(), errno);
abort();
}
file_debug = fdopen(fd_debug, "a");
assert(file_debug != NULL);
}
void SetLogAuthzSyslogLevel(const int level) {
switch (level) {
case 1:
syslog_level = LOG_DEBUG;
break;
case 2:
syslog_level = LOG_INFO;
break;
case 3:
syslog_level = LOG_NOTICE;
break;
default:
syslog_level = LOG_NOTICE;
break;
}
}
void SetLogAuthzSyslogFacility(const int local_facility) {
switch (local_facility) {
case 0:
syslog_facility = LOG_LOCAL0;
break;
case 1:
syslog_facility = LOG_LOCAL1;
break;
case 2:
syslog_facility = LOG_LOCAL2;
break;
case 3:
syslog_facility = LOG_LOCAL3;
break;
case 4:
syslog_facility = LOG_LOCAL4;
break;
case 5:
syslog_facility = LOG_LOCAL5;
break;
case 6:
syslog_facility = LOG_LOCAL6;
break;
case 7:
syslog_facility = LOG_LOCAL7;
break;
default:
syslog_facility = LOG_USER;
}
}
void SetLogAuthzSyslogPrefix(const string &prefix) {
if (syslog_prefix)
free(syslog_prefix);
if (prefix == "") {
syslog_prefix = NULL;
} else {
unsigned len = prefix.length() + 1;
syslog_prefix = static_cast<char *>(malloc(len));
assert(syslog_prefix != NULL);
syslog_prefix[len-1] = '\0';
memcpy(syslog_prefix, &prefix[0], prefix.length());
}
}
void LogAuthz(const int flags, const char *format, ...) {
char *msg = NULL;
va_list variadic_list;
va_start(variadic_list, format);
int retval = vasprintf(&msg, format, variadic_list);
assert(retval != -1); // else: out of memory
va_end(variadic_list);
if ((flags & kLogAuthzDebug) && (file_debug != NULL)) {
time_t rawtime;
time(&rawtime);
struct tm now;
localtime_r(&rawtime, &now);
fprintf(file_debug, "%s [%02d-%02d-%04d %02d:%02d:%02d %s]\n", msg,
(now.tm_mon)+1, now.tm_mday, (now.tm_year)+1900, now.tm_hour,
now.tm_min, now.tm_sec, now.tm_zone);
fflush(file_debug);
}
if (flags & (kLogAuthzSyslog | kLogAuthzSyslogWarn | kLogAuthzSyslogErr)) {
int level = syslog_level;
if (flags & kLogAuthzSyslogWarn) level = LOG_WARNING;
if (flags & kLogAuthzSyslogErr) level = LOG_ERR;
if (syslog_prefix) {
syslog(syslog_facility | level, "(%s) %s", syslog_prefix, msg);
} else {
syslog(syslog_facility | level, "%s", msg);
}
}
free(msg);
}
|
Fix compile error "'time' was not declared in this scope"
|
Fix compile error "'time' was not declared in this scope"
|
C++
|
bsd-3-clause
|
cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs
|
2874fd68afeb381395ab1138205e680ef8a6dc4a
|
content/gpu/transport_texture.cc
|
content/gpu/transport_texture.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu_messages.h"
#include "content/gpu/gpu_channel.h"
#include "content/gpu/transport_texture.h"
TransportTexture::TransportTexture(GpuChannel* channel,
IPC::Message::Sender* sender,
gpu::gles2::GLES2Decoder* decoder,
int32 host_id,
int32 route_id)
: channel_(channel),
sender_(sender),
decoder_(decoder),
host_id_(host_id),
route_id_(route_id) {
}
TransportTexture::~TransportTexture() {
}
void TransportTexture::CreateTextures(
int n, int width, int height, Format format, std::vector<int>* textures,
Task* done_task) {
output_textures_ = textures;
DCHECK(!create_task_.get());
create_task_.reset(done_task);
bool ret = sender_->Send(new GpuTransportTextureHostMsg_CreateTextures(
host_id_, n, width, height, static_cast<int>(format)));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_CreateTextures failed";
}
}
void TransportTexture::ReleaseTextures() {
texture_map_.clear();
bool ret = sender_->Send(new GpuTransportTextureHostMsg_ReleaseTextures(
host_id_));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_ReleaseTextures failed";
}
}
void TransportTexture::TextureUpdated(int texture_id) {
TextureMap::iterator iter = texture_map_.find(texture_id);
if (iter == texture_map_.end()) {
LOG(ERROR) << "Texture not found: " << texture_id;
return;
}
bool ret = sender_->Send(new GpuTransportTextureHostMsg_TextureUpdated(
host_id_, iter->second));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_TextureUpdated failed";
}
}
void TransportTexture::OnChannelConnected(int32 peer_pid) {
}
void TransportTexture::OnChannelError() {
}
bool TransportTexture::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(TransportTexture, msg)
IPC_MESSAGE_HANDLER(GpuTransportTextureMsg_Destroy,
OnDestroy)
IPC_MESSAGE_HANDLER(GpuTransportTextureMsg_TexturesCreated,
OnTexturesCreated)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled);
return handled;
}
void TransportTexture::OnDestroy() {
channel_->DestroyTransportTexture(route_id_);
}
void TransportTexture::OnTexturesCreated(std::vector<int> textures) {
bool ret = decoder_->MakeCurrent();
if (!ret) {
LOG(ERROR) << "Failed to switch context";
return;
}
output_textures_->clear();
for (size_t i = 0; i < textures.size(); ++i) {
uint32 gl_texture = 0;
// Translate the client texture id to service texture id.
ret = decoder_->GetServiceTextureId(textures[i], &gl_texture);
DCHECK(ret) << "Cannot translate client texture ID to service ID";
output_textures_->push_back(gl_texture);
texture_map_.insert(std::make_pair(gl_texture, textures[i]));
}
// Notify user that textures are ready.
create_task_->Run();
create_task_.reset();
output_textures_ = NULL;
}
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu_messages.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/gpu/transport_texture.h"
TransportTexture::TransportTexture(GpuChannel* channel,
IPC::Message::Sender* sender,
gpu::gles2::GLES2Decoder* decoder,
int32 host_id,
int32 route_id)
: channel_(channel),
sender_(sender),
decoder_(decoder),
host_id_(host_id),
route_id_(route_id) {
}
TransportTexture::~TransportTexture() {
}
void TransportTexture::CreateTextures(
int n, int width, int height, Format format, std::vector<int>* textures,
Task* done_task) {
output_textures_ = textures;
DCHECK(!create_task_.get());
create_task_.reset(done_task);
bool ret = sender_->Send(new GpuTransportTextureHostMsg_CreateTextures(
host_id_, n, width, height, static_cast<int>(format)));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_CreateTextures failed";
}
}
void TransportTexture::ReleaseTextures() {
texture_map_.clear();
bool ret = sender_->Send(new GpuTransportTextureHostMsg_ReleaseTextures(
host_id_));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_ReleaseTextures failed";
}
}
void TransportTexture::TextureUpdated(int texture_id) {
TextureMap::iterator iter = texture_map_.find(texture_id);
if (iter == texture_map_.end()) {
LOG(ERROR) << "Texture not found: " << texture_id;
return;
}
bool ret = sender_->Send(new GpuTransportTextureHostMsg_TextureUpdated(
host_id_, iter->second));
if (!ret) {
LOG(ERROR) << "GpuTransportTexture_TextureUpdated failed";
}
}
void TransportTexture::OnChannelConnected(int32 peer_pid) {
}
void TransportTexture::OnChannelError() {
}
bool TransportTexture::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(TransportTexture, msg)
IPC_MESSAGE_HANDLER(GpuTransportTextureMsg_Destroy,
OnDestroy)
IPC_MESSAGE_HANDLER(GpuTransportTextureMsg_TexturesCreated,
OnTexturesCreated)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled);
return handled;
}
void TransportTexture::OnDestroy() {
channel_->DestroyTransportTexture(route_id_);
}
void TransportTexture::OnTexturesCreated(std::vector<int> textures) {
bool ret = decoder_->MakeCurrent();
if (!ret) {
LOG(ERROR) << "Failed to switch context";
return;
}
output_textures_->clear();
for (size_t i = 0; i < textures.size(); ++i) {
uint32 gl_texture = 0;
// Translate the client texture id to service texture id.
ret = decoder_->GetServiceTextureId(textures[i], &gl_texture);
DCHECK(ret) << "Cannot translate client texture ID to service ID";
output_textures_->push_back(gl_texture);
texture_map_.insert(std::make_pair(gl_texture, textures[i]));
}
// Notify user that textures are ready.
create_task_->Run();
create_task_.reset();
output_textures_ = NULL;
}
|
Fix build
|
Fix build
TEST=compiles
BUG=none
Review URL: http://codereview.chromium.org/6813037
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@80885 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium
|
00c28d75b6dc409b25a3be809b3fa7c6a4bfee9f
|
sdk-remote/src/tests/uobjects/all.uob/all.cc
|
sdk-remote/src/tests/uobjects/all.uob/all.cc
|
#include <iostream>
#include <sstream>
#include <urbi/uobject.hh>
class all: public urbi::UObject
{
public:
all(const std::string& name)
: urbi::UObject(name)
{
UBindFunction(all, init);
UBindFunction(all, setOwned);
UBindFunction(all, setNotifyChange);
UBindFunction(all, setNotifyAccess);
UBindFunction(all, setNotifyChangeByName);
UBindFunction(all, read);
UBindFunction(all, write);
UBindFunction(all, readByName);
UBindFunction(all, writeByName);
UBindFunction(all, writeOwnByName);
UBindFunction(all, urbiWriteOwnByName);
UBindFunction(all, sendString);
UBindFunction(all, sendBuf);
UBindFunction(all, sendPar);
UBindFunction(all, typeOf);
UBindVar(all,a);
UBindVar(all,b);
UBindVar(all,c);
UBindVar(all, initCalled);
initCalled = 0;
UBindVar(all, lastChange);
UBindVar(all, lastAccess);
UBindVar(all, lastChangeVal);
lastChangeVal = -1;
UBindVar(all, lastAccessVal);
UBindFunction(all, readProps);
UBindFunction(all, writeProps);
UBindFunction(all, writeD);
UBindFunction(all, writeS);
UBindFunction(all, writeL);
UBindFunction(all, writeB);
UBindFunction(all, writeBNone);
UBindFunction(all, writeI);
UBindFunction(all, writeSnd);
UBindFunction(all, writeRI);
UBindFunction(all, writeRSnd);
UBindFunction(all, transmitD);
UBindFunction(all, transmitS);
UBindFunction(all, transmitL);
UBindFunction(all, transmitB);
UBindFunction(all, transmitI);
UBindFunction(all, transmitSnd);
UBindFunction(all, yield);
UBindFunction(all, loop_yield);
UBindFunction(all, yield_for);
UBindFunction(all, yield_until_things_changed);
UBindFunction(all, side_effect_free_set);
UBindFunction(all, side_effect_free_get);
vars[0] = &a;
vars[1] = &b;
vars[2] = &c;
}
int writeOwnByName(const std::string& name, int val)
{
urbi::UVar v(__name + "." + name);
v = val;
return 0;
}
int urbiWriteOwnByName(const std::string& name, int val)
{
std::stringstream ss;
ss << __name << "." << name << " = " << val << ";";
send(ss.str());
return 0;
}
int typeOf(const std::string& name)
{
urbi::UVar v(name);
v.syncValue();
return v.type();
}
int init(bool fail)
{
initCalled = 1;
return fail ? 1 : 0;
}
int setOwned(int id)
{
UOwned(*vars[id]);
return 0;
}
int setNotifyChange(int id)
{
UNotifyChange(*vars[id], &all::onChange);
return 0;
}
int setNotifyAccess(int id)
{
UNotifyAccess(*vars[id], &all::onAccess);
return 0;
}
int setNotifyChangeByName(const std::string& name)
{
UNotifyChange(name, &all::onChange);
return 0;
}
int read(int id)
{
int v = *vars[id];
return v;
}
int write(int id, int val)
{
*vars[id] = val;
return val;
}
int readByName(const std::string &name)
{
urbi::UVar v(name);
return v;
}
int writeByName(const std::string& name, int val)
{
urbi::UVar v(name);
v = val;
return val;
}
int onChange(urbi::UVar& v)
{
int val = v;
lastChange = v.get_name();
lastChangeVal = val;
return 0;
}
int onAccess(urbi::UVar& v)
{
static int val = 0;
lastAccess = v.get_name();
val++;
v = val;
lastAccessVal = val;
return 0;
}
urbi::UList readProps(const std::string &name)
{
urbi::UVar v(name);
urbi::UList l;
l.array.push_back(new urbi::UValue((double)v.rangemin));
l.array.push_back(new urbi::UValue((double)v.rangemax));
l.array.push_back(new urbi::UValue((double)v.speedmin));
l.array.push_back(new urbi::UValue((double)v.speedmax));
l.array.push_back(new urbi::UValue((double)v.delta));
urbi::UValue bl = v.blend;
l.array.push_back(new urbi::UValue(bl));
return l;
}
int writeProps(const std::string &name, double val)
{
urbi::UVar v(name);
v.rangemin = val;
v.rangemax = val;
v.speedmin = val;
v.speedmax = val;
v.delta = val;
v.blend = val;
return 0;
}
/** Test write to UVAR. **/
int writeD(const std::string &name, double val)
{
std::cerr << "writeD " << name << std::endl;
urbi::UVar v(name);
v = val;
return 0;
}
int writeS(const std::string &name, const std::string &val)
{
std::cerr << "writeS " << name << std::endl;
urbi::UVar v(name);
v = val;
return 0;
}
int writeL(const std::string &name, const std::string &val)
{
std::cerr << "writeL " << name << std::endl;
urbi::UVar v(name);
urbi::UList l;
l.array.push_back(new urbi::UValue(val));
l.array.push_back(new urbi::UValue(42));
v = l;
return 0;
}
int writeB(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UBinary val;
val.type = urbi::BINARY_UNKNOWN;
val.common.size = content.length();
val.common.data = malloc(content.length());
memcpy(val.common.data, content.c_str(), content.length());
v = val;
return 0;
}
int writeBNone(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UBinary val;
val.common.size = content.length();
val.common.data = malloc(content.length());
memcpy(val.common.data, content.c_str(), content.length());
v = val;
return 0;
}
int writeI(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UImage i;
i.imageFormat = urbi::IMAGE_JPEG;
i.width = i.height = 42;
i.size = content.length();
i.data = (unsigned char*)malloc(content.length());
memcpy(i.data, content.c_str(), content.length());
v = i;
free(i.data);
return 0;
}
int writeSnd(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::USound s;
s.soundFormat = urbi::SOUND_RAW;
s.rate = 42;
s.size = content.length();
s.channels = 1;
s.sampleSize= 8;
s.sampleFormat = urbi::SAMPLE_UNSIGNED;
s.data = (char*)malloc(content.length());
memcpy(s.data, content.c_str(), content.length());
v = s;
free(s.data);
return 0;
}
int writeRI(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UImage i = v;
memcpy(i.data, content.c_str(), content.length());
return 0;
}
int writeRSnd(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::USound i = v;
memcpy(i.data, content.c_str(), content.length());
return 0;
}
/** Test function parameter and return value **/
double transmitD(double v)
{
return -(double)v;
}
urbi::UList transmitL(urbi::UList l)
{
urbi::UList r;
for (unsigned int i=0; i<l.array.size(); i++)
r.array.push_back(new urbi::UValue(*l.array[l.array.size()-i-1]));
return r;
}
std::string transmitS(const std::string &name)
{
return name.substr(1, name.length()-2);
}
urbi::UBinary transmitB(urbi::UBinary b)
{
urbi::UBinary res(b);
unsigned char* data = static_cast<unsigned char*>(res.common.data);
for (size_t i = 0; i < res.common.size; ++i)
data[i] -= 1;
data[res.common.size - 1] = '\n';
return r;
}
urbi::UImage transmitI(urbi::UImage im)
{
for (unsigned int i=0; i<im.size; i++)
im.data[i] -= 1;
return im;
}
urbi::USound transmitSnd(urbi::USound im)
{
for (unsigned int i=0; i<im.size; i++)
im.data[i] -= 1;
return im;
}
int sendString(const std::string& s)
{
urbi::send(s.c_str());
return 0;
}
int sendBuf(const std::string& b, int l)
{
urbi::send(const_cast<void*>(static_cast<const void*>(b.c_str())), l);
return 0;
}
int sendPar()
{
URBI((Object.a = 123,));
return 0;
}
void yield()
{
urbi::yield();
}
void loop_yield(long duration)
{
libport::utime_t end = libport::utime() + duration;
while (libport::utime() < end)
{
urbi::yield();
usleep(1000);
}
}
void yield_for(long duration)
{
urbi::yield_until(libport::utime() + duration);
}
void yield_until_things_changed()
{
urbi::yield_until_things_changed();
}
void side_effect_free_set(bool sef)
{
urbi::side_effect_free_set(sef);
}
bool side_effect_free_get()
{
return urbi::side_effect_free_get();
}
urbi::UVar a,b,c;
urbi::UVar* vars[3];
//name of var that trigerred notifyChange
urbi::UVar lastChange;
//value read on said var
urbi::UVar lastChangeVal;
//name of var that triggered notifyAccess
urbi::UVar lastAccess;
//value written to said var
urbi::UVar lastAccessVal;
//Set to 0 in ctor, 1 in init
urbi::UVar initCalled;
};
::urbi::URBIStarter<all>
starter1(urbi::isPluginMode()?"all":"remall");
::urbi::URBIStarter<all>
starter2(urbi::isPluginMode()?"all2":"remall2");
|
#include <iostream>
#include <sstream>
#include <urbi/uobject.hh>
class all: public urbi::UObject
{
public:
all(const std::string& name)
: urbi::UObject(name)
{
UBindFunction(all, init);
UBindFunction(all, setOwned);
UBindFunction(all, setNotifyChange);
UBindFunction(all, setNotifyAccess);
UBindFunction(all, setNotifyChangeByName);
UBindFunction(all, read);
UBindFunction(all, write);
UBindFunction(all, readByName);
UBindFunction(all, writeByName);
UBindFunction(all, writeOwnByName);
UBindFunction(all, urbiWriteOwnByName);
UBindFunction(all, sendString);
UBindFunction(all, sendBuf);
UBindFunction(all, sendPar);
UBindFunction(all, typeOf);
UBindVar(all,a);
UBindVar(all,b);
UBindVar(all,c);
UBindVar(all, initCalled);
initCalled = 0;
UBindVar(all, lastChange);
UBindVar(all, lastAccess);
UBindVar(all, lastChangeVal);
lastChangeVal = -1;
UBindVar(all, lastAccessVal);
UBindFunction(all, readProps);
UBindFunction(all, writeProps);
UBindFunction(all, writeD);
UBindFunction(all, writeS);
UBindFunction(all, writeL);
UBindFunction(all, writeB);
UBindFunction(all, writeBNone);
UBindFunction(all, writeI);
UBindFunction(all, writeSnd);
UBindFunction(all, writeRI);
UBindFunction(all, writeRSnd);
UBindFunction(all, transmitD);
UBindFunction(all, transmitS);
UBindFunction(all, transmitL);
UBindFunction(all, transmitB);
UBindFunction(all, transmitI);
UBindFunction(all, transmitSnd);
UBindFunction(all, yield);
UBindFunction(all, loop_yield);
UBindFunction(all, yield_for);
UBindFunction(all, yield_until_things_changed);
UBindFunction(all, side_effect_free_set);
UBindFunction(all, side_effect_free_get);
vars[0] = &a;
vars[1] = &b;
vars[2] = &c;
}
int writeOwnByName(const std::string& name, int val)
{
urbi::UVar v(__name + "." + name);
v = val;
return 0;
}
int urbiWriteOwnByName(const std::string& name, int val)
{
std::stringstream ss;
ss << __name << "." << name << " = " << val << ";";
send(ss.str());
return 0;
}
int typeOf(const std::string& name)
{
urbi::UVar v(name);
v.syncValue();
return v.type();
}
int init(bool fail)
{
initCalled = 1;
return fail ? 1 : 0;
}
int setOwned(int id)
{
UOwned(*vars[id]);
return 0;
}
int setNotifyChange(int id)
{
UNotifyChange(*vars[id], &all::onChange);
return 0;
}
int setNotifyAccess(int id)
{
UNotifyAccess(*vars[id], &all::onAccess);
return 0;
}
int setNotifyChangeByName(const std::string& name)
{
UNotifyChange(name, &all::onChange);
return 0;
}
int read(int id)
{
int v = *vars[id];
return v;
}
int write(int id, int val)
{
*vars[id] = val;
return val;
}
int readByName(const std::string &name)
{
urbi::UVar v(name);
return v;
}
int writeByName(const std::string& name, int val)
{
urbi::UVar v(name);
v = val;
return val;
}
int onChange(urbi::UVar& v)
{
int val = v;
lastChange = v.get_name();
lastChangeVal = val;
return 0;
}
int onAccess(urbi::UVar& v)
{
static int val = 0;
lastAccess = v.get_name();
val++;
v = val;
lastAccessVal = val;
return 0;
}
urbi::UList readProps(const std::string &name)
{
urbi::UVar v(name);
urbi::UList l;
l.array.push_back(new urbi::UValue((double)v.rangemin));
l.array.push_back(new urbi::UValue((double)v.rangemax));
l.array.push_back(new urbi::UValue((double)v.speedmin));
l.array.push_back(new urbi::UValue((double)v.speedmax));
l.array.push_back(new urbi::UValue((double)v.delta));
urbi::UValue bl = v.blend;
l.array.push_back(new urbi::UValue(bl));
return l;
}
int writeProps(const std::string &name, double val)
{
urbi::UVar v(name);
v.rangemin = val;
v.rangemax = val;
v.speedmin = val;
v.speedmax = val;
v.delta = val;
v.blend = val;
return 0;
}
/** Test write to UVAR. **/
int writeD(const std::string &name, double val)
{
std::cerr << "writeD " << name << std::endl;
urbi::UVar v(name);
v = val;
return 0;
}
int writeS(const std::string &name, const std::string &val)
{
std::cerr << "writeS " << name << std::endl;
urbi::UVar v(name);
v = val;
return 0;
}
int writeL(const std::string &name, const std::string &val)
{
std::cerr << "writeL " << name << std::endl;
urbi::UVar v(name);
urbi::UList l;
l.array.push_back(new urbi::UValue(val));
l.array.push_back(new urbi::UValue(42));
v = l;
return 0;
}
int writeB(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UBinary val;
val.type = urbi::BINARY_UNKNOWN;
val.common.size = content.length();
val.common.data = malloc(content.length());
memcpy(val.common.data, content.c_str(), content.length());
v = val;
return 0;
}
int writeBNone(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UBinary val;
val.common.size = content.length();
val.common.data = malloc(content.length());
memcpy(val.common.data, content.c_str(), content.length());
v = val;
return 0;
}
int writeI(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UImage i;
i.imageFormat = urbi::IMAGE_JPEG;
i.width = i.height = 42;
i.size = content.length();
i.data = (unsigned char*)malloc(content.length());
memcpy(i.data, content.c_str(), content.length());
v = i;
free(i.data);
return 0;
}
int writeSnd(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::USound s;
s.soundFormat = urbi::SOUND_RAW;
s.rate = 42;
s.size = content.length();
s.channels = 1;
s.sampleSize= 8;
s.sampleFormat = urbi::SAMPLE_UNSIGNED;
s.data = (char*)malloc(content.length());
memcpy(s.data, content.c_str(), content.length());
v = s;
free(s.data);
return 0;
}
int writeRI(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::UImage i = v;
memcpy(i.data, content.c_str(), content.length());
return 0;
}
int writeRSnd(const std::string &name, const std::string &content)
{
urbi::UVar v(name);
urbi::USound i = v;
memcpy(i.data, content.c_str(), content.length());
return 0;
}
/** Test function parameter and return value **/
double transmitD(double v)
{
return -(double)v;
}
urbi::UList transmitL(urbi::UList l)
{
urbi::UList r;
for (unsigned int i=0; i<l.array.size(); i++)
r.array.push_back(new urbi::UValue(*l.array[l.array.size()-i-1]));
return r;
}
std::string transmitS(const std::string &name)
{
return name.substr(1, name.length()-2);
}
urbi::UBinary transmitB(urbi::UBinary b)
{
urbi::UBinary res(b);
unsigned char* data = static_cast<unsigned char*>(res.common.data);
for (size_t i = 0; i < res.common.size; ++i)
data[i] -= 1;
data[res.common.size - 1] = '\n';
return res;
}
urbi::UImage transmitI(urbi::UImage im)
{
for (unsigned int i=0; i<im.size; i++)
im.data[i] -= 1;
return im;
}
urbi::USound transmitSnd(urbi::USound im)
{
for (unsigned int i=0; i<im.size; i++)
im.data[i] -= 1;
return im;
}
int sendString(const std::string& s)
{
urbi::send(s.c_str());
return 0;
}
int sendBuf(const std::string& b, int l)
{
urbi::send(const_cast<void*>(static_cast<const void*>(b.c_str())), l);
return 0;
}
int sendPar()
{
URBI((Object.a = 123,));
return 0;
}
void yield()
{
urbi::yield();
}
void loop_yield(long duration)
{
libport::utime_t end = libport::utime() + duration;
while (libport::utime() < end)
{
urbi::yield();
usleep(1000);
}
}
void yield_for(long duration)
{
urbi::yield_until(libport::utime() + duration);
}
void yield_until_things_changed()
{
urbi::yield_until_things_changed();
}
void side_effect_free_set(bool sef)
{
urbi::side_effect_free_set(sef);
}
bool side_effect_free_get()
{
return urbi::side_effect_free_get();
}
urbi::UVar a,b,c;
urbi::UVar* vars[3];
//name of var that trigerred notifyChange
urbi::UVar lastChange;
//value read on said var
urbi::UVar lastChangeVal;
//name of var that triggered notifyAccess
urbi::UVar lastAccess;
//value written to said var
urbi::UVar lastAccessVal;
//Set to 0 in ctor, 1 in init
urbi::UVar initCalled;
};
::urbi::URBIStarter<all>
starter1(urbi::isPluginMode()?"all":"remall");
::urbi::URBIStarter<all>
starter2(urbi::isPluginMode()?"all2":"remall2");
|
Fix missing rename introduced by fdd8c1b.
|
Fix missing rename introduced by fdd8c1b.
* src/tests/uobjects/all.uob/all.cc (transmitI): Here.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi
|
441192692ced21f2ff672fa53bc737f1db24cff0
|
embedding/word2vec_kernels.cc
|
embedding/word2vec_kernels.cc
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/random/distribution_sampler.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/util/guarded_philox_random.h"
namespace tensorflow {
// Number of examples to precalculate.
const int kPrecalc = 3000;
// Number of words to read into a sentence before processing.
const int kSentenceSize = 1000;
namespace {
bool ScanWord(StringPiece* input, string* word) {
str_util::RemoveLeadingWhitespace(input);
StringPiece tmp;
if (str_util::ConsumeNonWhitespace(input, &tmp)) {
word->assign(tmp.data(), tmp.size());
return true;
} else {
return false;
}
}
} // end namespace
class SkipgramWord2vecOp : public OpKernel {
public:
explicit SkipgramWord2vecOp(OpKernelConstruction* ctx)
: OpKernel(ctx), rng_(&philox_) {
string filename;
OP_REQUIRES_OK(ctx, ctx->GetAttr("filename", &filename));
OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("window_size", &window_size_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("min_count", &min_count_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("subsample", &subsample_));
OP_REQUIRES_OK(ctx, Init(ctx->env(), filename));
mutex_lock l(mu_);
example_pos_ = corpus_size_;
label_pos_ = corpus_size_;
label_limit_ = corpus_size_;
sentence_index_ = kSentenceSize;
for (int i = 0; i < kPrecalc; ++i) {
NextExample(&precalc_examples_[i].input, &precalc_examples_[i].label);
}
}
void Compute(OpKernelContext* ctx) override {
Tensor words_per_epoch(DT_INT64, TensorShape({}));
Tensor current_epoch(DT_INT32, TensorShape({}));
Tensor total_words_processed(DT_INT64, TensorShape({}));
Tensor examples(DT_INT32, TensorShape({batch_size_}));
auto Texamples = examples.flat<int32>();
Tensor labels(DT_INT32, TensorShape({batch_size_}));
auto Tlabels = labels.flat<int32>();
{
mutex_lock l(mu_);
for (int i = 0; i < batch_size_; ++i) {
Texamples(i) = precalc_examples_[precalc_index_].input;
Tlabels(i) = precalc_examples_[precalc_index_].label;
precalc_index_++;
if (precalc_index_ >= kPrecalc) {
precalc_index_ = 0;
for (int j = 0; j < kPrecalc; ++j) {
NextExample(&precalc_examples_[j].input,
&precalc_examples_[j].label);
}
}
}
words_per_epoch.scalar<int64>()() = corpus_size_;
current_epoch.scalar<int32>()() = current_epoch_;
total_words_processed.scalar<int64>()() = total_words_processed_;
}
ctx->set_output(0, word_);
ctx->set_output(1, freq_);
ctx->set_output(2, words_per_epoch);
ctx->set_output(3, current_epoch);
ctx->set_output(4, total_words_processed);
ctx->set_output(5, examples);
ctx->set_output(6, labels);
}
private:
struct Example {
int32 input;
int32 label;
};
int32 batch_size_ = 0;
int32 window_size_ = 5;
float subsample_ = 1e-3;
int min_count_ = 5;
int32 vocab_size_ = 0;
Tensor word_;
Tensor freq_;
int64 corpus_size_ = 0;
std::vector<int32> corpus_;
std::vector<Example> precalc_examples_;
int precalc_index_ = 0;
std::vector<int32> sentence_;
int sentence_index_ = 0;
mutex mu_;
random::PhiloxRandom philox_ GUARDED_BY(mu_);
random::SimplePhilox rng_ GUARDED_BY(mu_);
int32 current_epoch_ GUARDED_BY(mu_) = -1;
int64 total_words_processed_ GUARDED_BY(mu_) = 0;
int64 example_pos_ GUARDED_BY(mu_);
int32 label_pos_ GUARDED_BY(mu_);
int32 label_limit_ GUARDED_BY(mu_);
// {example_pos_, label_pos_} is the cursor for the next example.
// example_pos_ wraps around at the end of corpus_. For each
// example, we randomly generate [label_pos_, label_limit) for
// labels.
void NextExample(int32* example, int32* label) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
while (true) {
if (label_pos_ >= label_limit_) {
++total_words_processed_;
++sentence_index_;
if (sentence_index_ >= kSentenceSize) {
sentence_index_ = 0;
for (int i = 0; i < kSentenceSize; ++i, ++example_pos_) {
if (example_pos_ >= corpus_size_) {
++current_epoch_;
example_pos_ = 0;
}
if (subsample_ > 0) {
int32 word_freq = freq_.flat<int32>()(corpus_[example_pos_]);
// See Eq. 5 in http://arxiv.org/abs/1310.4546
float keep_prob =
(std::sqrt(word_freq / (subsample_ * corpus_size_)) + 1) *
(subsample_ * corpus_size_) / word_freq;
if (rng_.RandFloat() > keep_prob) {
i--;
continue;
}
}
sentence_[i] = corpus_[example_pos_];
}
}
const int32 skip = 1 + rng_.Uniform(window_size_);
label_pos_ = std::max<int32>(0, sentence_index_ - skip);
label_limit_ =
std::min<int32>(kSentenceSize, sentence_index_ + skip + 1);
}
if (sentence_index_ != label_pos_) {
break;
}
++label_pos_;
}
*example = sentence_[sentence_index_];
*label = sentence_[label_pos_++];
}
Status Init(Env* env, const string& filename) {
string data;
TF_RETURN_IF_ERROR(ReadFileToString(env, filename, &data));
StringPiece input = data;
string w;
corpus_size_ = 0;
std::unordered_map<string, int32> word_freq;
while (ScanWord(&input, &w)) {
++(word_freq[w]);
++corpus_size_;
}
if (corpus_size_ < window_size_ * 10) {
return errors::InvalidArgument("The text file ", filename,
" contains too little data: ",
corpus_size_, " words");
}
typedef std::pair<string, int32> WordFreq;
std::vector<WordFreq> ordered;
for (const auto& p : word_freq) {
if (p.second >= min_count_) ordered.push_back(p);
}
LOG(INFO) << "Data file: " << filename << " contains " << data.size()
<< " bytes, " << corpus_size_ << " words, " << word_freq.size()
<< " unique words, " << ordered.size()
<< " unique frequent words.";
word_freq.clear();
std::sort(ordered.begin(), ordered.end(),
[](const WordFreq& x, const WordFreq& y) {
return x.second > y.second;
});
vocab_size_ = static_cast<int32>(1 + ordered.size());
Tensor word(DT_STRING, TensorShape({vocab_size_}));
Tensor freq(DT_INT32, TensorShape({vocab_size_}));
word.flat<string>()(0) = "UNK";
static const int32 kUnkId = 0;
std::unordered_map<string, int32> word_id;
int64 total_counted = 0;
for (std::size_t i = 0; i < ordered.size(); ++i) {
const auto& w = ordered[i].first;
auto id = i + 1;
word.flat<string>()(id) = w;
auto word_count = ordered[i].second;
freq.flat<int32>()(id) = word_count;
total_counted += word_count;
word_id[w] = id;
}
freq.flat<int32>()(kUnkId) = corpus_size_ - total_counted;
word_ = word;
freq_ = freq;
corpus_.reserve(corpus_size_);
input = data;
while (ScanWord(&input, &w)) {
corpus_.push_back(gtl::FindWithDefault(word_id, w, kUnkId));
}
precalc_examples_.resize(kPrecalc);
sentence_.resize(kSentenceSize);
return Status::OK();
}
};
REGISTER_KERNEL_BUILDER(Name("SkipgramWord2vec").Device(DEVICE_CPU), SkipgramWord2vecOp);
class NegTrainWord2vecOp : public OpKernel {
public:
explicit NegTrainWord2vecOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
base_.Init(0, 0);
OP_REQUIRES_OK(ctx, ctx->GetAttr("num_negative_samples", &num_samples_));
std::vector<int32> vocab_count;
OP_REQUIRES_OK(ctx, ctx->GetAttr("vocab_count", &vocab_count));
std::vector<float> vocab_weights;
vocab_weights.reserve(vocab_count.size());
for (const auto& f : vocab_count) {
float r = std::pow(static_cast<float>(f), 0.75f);
vocab_weights.push_back(r);
}
sampler_ = new random::DistributionSampler(vocab_weights);
}
~NegTrainWord2vecOp() { delete sampler_; }
void Compute(OpKernelContext* ctx) override {
Tensor w_in = ctx->mutable_input(0, false);
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(w_in.shape()),
errors::InvalidArgument("Must be a matrix"));
Tensor w_out = ctx->mutable_input(1, false);
OP_REQUIRES(ctx, w_in.shape() == w_out.shape(),
errors::InvalidArgument("w_in.shape == w_out.shape"));
const Tensor& examples = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(examples.shape()),
errors::InvalidArgument("Must be a vector"));
const Tensor& labels = ctx->input(3);
OP_REQUIRES(ctx, examples.shape() == labels.shape(),
errors::InvalidArgument("examples.shape == labels.shape"));
const Tensor& learning_rate = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(learning_rate.shape()),
errors::InvalidArgument("Must be a scalar"));
auto Tw_in = w_in.matrix<float>();
auto Tw_out = w_out.matrix<float>();
auto Texamples = examples.flat<int32>();
auto Tlabels = labels.flat<int32>();
auto lr = learning_rate.scalar<float>()();
const int64 vocab_size = w_in.dim_size(0);
const int64 dims = w_in.dim_size(1);
const int64 batch_size = examples.dim_size(0);
OP_REQUIRES(ctx, vocab_size == sampler_->num(),
errors::InvalidArgument("vocab_size mismatches: ", vocab_size,
" vs. ", sampler_->num()));
// Gradient accumulator for v_in.
Tensor buf(DT_FLOAT, TensorShape({dims}));
auto Tbuf = buf.flat<float>();
// Scalar buffer to hold sigmoid(+/- dot).
Tensor g_buf(DT_FLOAT, TensorShape({}));
auto g = g_buf.scalar<float>();
// The following loop needs 2 random 32-bit values per negative
// sample. We reserve 8 values per sample just in case the
// underlying implementation changes.
auto rnd = base_.ReserveSamples32(batch_size * num_samples_ * 8);
random::SimplePhilox srnd(&rnd);
for (int64 i = 0; i < batch_size; ++i) {
const int32 example = Texamples(i);
DCHECK(0 <= example && example < vocab_size) << example;
const int32 label = Tlabels(i);
DCHECK(0 <= label && label < vocab_size) << label;
auto v_in = Tw_in.chip<0>(example);
// Positive: example predicts label.
// forward: x = v_in' * v_out
// l = log(sigmoid(x))
// backward: dl/dx = g = sigmoid(-x)
// dl/d(v_in) = g * v_out'
// dl/d(v_out) = v_in' * g
{
auto v_out = Tw_out.chip<0>(label);
auto dot = (v_in * v_out).sum();
g = (dot.exp() + 1.f).inverse();
Tbuf = v_out * (g() * lr);
v_out += v_in * (g() * lr);
}
// Negative samples:
// forward: x = v_in' * v_sample
// l = log(sigmoid(-x))
// backward: dl/dx = g = -sigmoid(x)
// dl/d(v_in) = g * v_out'
// dl/d(v_out) = v_in' * g
for (int j = 0; j < num_samples_; ++j) {
const int sample = sampler_->Sample(&srnd);
if (sample == label) continue; // Skip.
auto v_sample = Tw_out.chip<0>(sample);
auto dot = (v_in * v_sample).sum();
g = -((-dot).exp() + 1.f).inverse();
Tbuf += v_sample * (g() * lr);
v_sample += v_in * (g() * lr);
}
// Applies the gradient on v_in.
v_in += Tbuf;
}
}
private:
int32 num_samples_ = 0;
random::DistributionSampler* sampler_ = nullptr;
GuardedPhiloxRandom base_;
};
REGISTER_KERNEL_BUILDER(Name("NegTrainWord2vec").Device(DEVICE_CPU), NegTrainWord2vecOp);
} // end namespace tensorflow
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/random/distribution_sampler.h"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/util/guarded_philox_random.h"
namespace tensorflow {
// Number of examples to precalculate.
const int kPrecalc = 3000;
// Number of words to read into a sentence before processing.
const int kSentenceSize = 1000;
namespace {
bool ScanWord(StringPiece* input, string* word) {
str_util::RemoveLeadingWhitespace(input);
StringPiece tmp;
if (str_util::ConsumeNonWhitespace(input, &tmp)) {
word->assign(tmp.data(), tmp.size());
return true;
} else {
return false;
}
}
} // end namespace
class SkipgramWord2vecOp : public OpKernel {
public:
explicit SkipgramWord2vecOp(OpKernelConstruction* ctx)
: OpKernel(ctx), rng_(&philox_) {
string filename;
OP_REQUIRES_OK(ctx, ctx->GetAttr("filename", &filename));
OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("window_size", &window_size_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("min_count", &min_count_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("subsample", &subsample_));
OP_REQUIRES_OK(ctx, Init(ctx->env(), filename));
mutex_lock l(mu_);
example_pos_ = corpus_size_;
label_pos_ = corpus_size_;
label_limit_ = corpus_size_;
sentence_index_ = kSentenceSize;
for (int i = 0; i < kPrecalc; ++i) {
NextExample(&precalc_examples_[i].input, &precalc_examples_[i].label);
}
}
void Compute(OpKernelContext* ctx) override {
Tensor words_per_epoch(DT_INT64, TensorShape({}));
Tensor current_epoch(DT_INT32, TensorShape({}));
Tensor total_words_processed(DT_INT64, TensorShape({}));
Tensor examples(DT_INT32, TensorShape({batch_size_}));
auto Texamples = examples.flat<int32>();
Tensor labels(DT_INT32, TensorShape({batch_size_}));
auto Tlabels = labels.flat<int32>();
{
mutex_lock l(mu_);
for (int i = 0; i < batch_size_; ++i) {
Texamples(i) = precalc_examples_[precalc_index_].input;
Tlabels(i) = precalc_examples_[precalc_index_].label;
precalc_index_++;
if (precalc_index_ >= kPrecalc) {
precalc_index_ = 0;
for (int j = 0; j < kPrecalc; ++j) {
NextExample(&precalc_examples_[j].input,
&precalc_examples_[j].label);
}
}
}
words_per_epoch.scalar<int64>()() = corpus_size_;
current_epoch.scalar<int32>()() = current_epoch_;
total_words_processed.scalar<int64>()() = total_words_processed_;
}
ctx->set_output(0, word_);
ctx->set_output(1, freq_);
ctx->set_output(2, words_per_epoch);
ctx->set_output(3, current_epoch);
ctx->set_output(4, total_words_processed);
ctx->set_output(5, examples);
ctx->set_output(6, labels);
}
private:
struct Example {
int32 input;
int32 label;
};
int32 batch_size_ = 0;
int32 window_size_ = 5;
float subsample_ = 1e-3;
int min_count_ = 5;
int32 vocab_size_ = 0;
Tensor word_;
Tensor freq_;
int64 corpus_size_ = 0;
std::vector<int32> corpus_;
std::vector<Example> precalc_examples_;
int precalc_index_ = 0;
std::vector<int32> sentence_;
int sentence_index_ = 0;
mutex mu_;
random::PhiloxRandom philox_ GUARDED_BY(mu_);
random::SimplePhilox rng_ GUARDED_BY(mu_);
int32 current_epoch_ GUARDED_BY(mu_) = -1;
int64 total_words_processed_ GUARDED_BY(mu_) = 0;
int64 example_pos_ GUARDED_BY(mu_);
int32 label_pos_ GUARDED_BY(mu_);
int32 label_limit_ GUARDED_BY(mu_);
// {example_pos_, label_pos_} is the cursor for the next example.
// example_pos_ wraps around at the end of corpus_. For each
// example, we randomly generate [label_pos_, label_limit) for
// labels.
void NextExample(int32* example, int32* label) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
while (true) {
if (label_pos_ >= label_limit_) {
++total_words_processed_;
++sentence_index_;
if (sentence_index_ >= kSentenceSize) {
sentence_index_ = 0;
for (int i = 0; i < kSentenceSize; ++i, ++example_pos_) {
if (example_pos_ >= corpus_size_) {
++current_epoch_;
example_pos_ = 0;
}
if (subsample_ > 0) {
int32 word_freq = freq_.flat<int32>()(corpus_[example_pos_]);
// See Eq. 5 in http://arxiv.org/abs/1310.4546
float keep_prob =
(std::sqrt(word_freq / (subsample_ * corpus_size_)) + 1) *
(subsample_ * corpus_size_) / word_freq;
if (rng_.RandFloat() > keep_prob) {
i--;
continue;
}
}
sentence_[i] = corpus_[example_pos_];
}
}
const int32 skip = 1 + rng_.Uniform(window_size_);
label_pos_ = std::max<int32>(0, sentence_index_ - skip);
label_limit_ =
std::min<int32>(kSentenceSize, sentence_index_ + skip + 1);
}
if (sentence_index_ != label_pos_) {
break;
}
++label_pos_;
}
*example = sentence_[sentence_index_];
*label = sentence_[label_pos_++];
}
Status Init(Env* env, const string& filename) {
string data;
TF_RETURN_IF_ERROR(ReadFileToString(env, filename, &data));
StringPiece input = data;
string w;
corpus_size_ = 0;
std::unordered_map<string, int32> word_freq;
while (ScanWord(&input, &w)) {
++(word_freq[w]);
++corpus_size_;
}
if (corpus_size_ < window_size_ * 10) {
return errors::InvalidArgument("The text file ", filename,
" contains too little data: ",
corpus_size_, " words");
}
typedef std::pair<string, int32> WordFreq;
std::vector<WordFreq> ordered;
for (const auto& p : word_freq) {
if (p.second >= min_count_) ordered.push_back(p);
}
LOG(INFO) << "Data file: " << filename << " contains " << data.size()
<< " bytes, " << corpus_size_ << " words, " << word_freq.size()
<< " unique words, " << ordered.size()
<< " unique frequent words.";
word_freq.clear();
std::sort(ordered.begin(), ordered.end(),
[](const WordFreq& x, const WordFreq& y) {
return x.second > y.second;
});
vocab_size_ = static_cast<int32>(1 + ordered.size());
Tensor word(DT_STRING, TensorShape({vocab_size_}));
Tensor freq(DT_INT32, TensorShape({vocab_size_}));
word.flat<tstring>()(0) = "UNK";
static const int32 kUnkId = 0;
std::unordered_map<string, int32> word_id;
int64 total_counted = 0;
for (std::size_t i = 0; i < ordered.size(); ++i) {
const auto& w = ordered[i].first;
auto id = i + 1;
word.flat<tstring>()(id) = w;
auto word_count = ordered[i].second;
freq.flat<int32>()(id) = word_count;
total_counted += word_count;
word_id[w] = id;
}
freq.flat<int32>()(kUnkId) = corpus_size_ - total_counted;
word_ = word;
freq_ = freq;
corpus_.reserve(corpus_size_);
input = data;
while (ScanWord(&input, &w)) {
corpus_.push_back(gtl::FindWithDefault(word_id, w, kUnkId));
}
precalc_examples_.resize(kPrecalc);
sentence_.resize(kSentenceSize);
return Status::OK();
}
};
REGISTER_KERNEL_BUILDER(Name("SkipgramWord2vec").Device(DEVICE_CPU), SkipgramWord2vecOp);
class NegTrainWord2vecOp : public OpKernel {
public:
explicit NegTrainWord2vecOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
base_.Init(0, 0);
OP_REQUIRES_OK(ctx, ctx->GetAttr("num_negative_samples", &num_samples_));
std::vector<int32> vocab_count;
OP_REQUIRES_OK(ctx, ctx->GetAttr("vocab_count", &vocab_count));
std::vector<float> vocab_weights;
vocab_weights.reserve(vocab_count.size());
for (const auto& f : vocab_count) {
float r = std::pow(static_cast<float>(f), 0.75f);
vocab_weights.push_back(r);
}
sampler_ = new random::DistributionSampler(vocab_weights);
}
~NegTrainWord2vecOp() { delete sampler_; }
void Compute(OpKernelContext* ctx) override {
Tensor w_in = ctx->mutable_input(0, false);
OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(w_in.shape()),
errors::InvalidArgument("Must be a matrix"));
Tensor w_out = ctx->mutable_input(1, false);
OP_REQUIRES(ctx, w_in.shape() == w_out.shape(),
errors::InvalidArgument("w_in.shape == w_out.shape"));
const Tensor& examples = ctx->input(2);
OP_REQUIRES(ctx, TensorShapeUtils::IsVector(examples.shape()),
errors::InvalidArgument("Must be a vector"));
const Tensor& labels = ctx->input(3);
OP_REQUIRES(ctx, examples.shape() == labels.shape(),
errors::InvalidArgument("examples.shape == labels.shape"));
const Tensor& learning_rate = ctx->input(4);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(learning_rate.shape()),
errors::InvalidArgument("Must be a scalar"));
auto Tw_in = w_in.matrix<float>();
auto Tw_out = w_out.matrix<float>();
auto Texamples = examples.flat<int32>();
auto Tlabels = labels.flat<int32>();
auto lr = learning_rate.scalar<float>()();
const int64 vocab_size = w_in.dim_size(0);
const int64 dims = w_in.dim_size(1);
const int64 batch_size = examples.dim_size(0);
OP_REQUIRES(ctx, vocab_size == sampler_->num(),
errors::InvalidArgument("vocab_size mismatches: ", vocab_size,
" vs. ", sampler_->num()));
// Gradient accumulator for v_in.
Tensor buf(DT_FLOAT, TensorShape({dims}));
auto Tbuf = buf.flat<float>();
// Scalar buffer to hold sigmoid(+/- dot).
Tensor g_buf(DT_FLOAT, TensorShape({}));
auto g = g_buf.scalar<float>();
// The following loop needs 2 random 32-bit values per negative
// sample. We reserve 8 values per sample just in case the
// underlying implementation changes.
auto rnd = base_.ReserveSamples32(batch_size * num_samples_ * 8);
random::SimplePhilox srnd(&rnd);
for (int64 i = 0; i < batch_size; ++i) {
const int32 example = Texamples(i);
DCHECK(0 <= example && example < vocab_size) << example;
const int32 label = Tlabels(i);
DCHECK(0 <= label && label < vocab_size) << label;
auto v_in = Tw_in.chip<0>(example);
// Positive: example predicts label.
// forward: x = v_in' * v_out
// l = log(sigmoid(x))
// backward: dl/dx = g = sigmoid(-x)
// dl/d(v_in) = g * v_out'
// dl/d(v_out) = v_in' * g
{
auto v_out = Tw_out.chip<0>(label);
auto dot = (v_in * v_out).sum();
g = (dot.exp() + 1.f).inverse();
Tbuf = v_out * (g() * lr);
v_out += v_in * (g() * lr);
}
// Negative samples:
// forward: x = v_in' * v_sample
// l = log(sigmoid(-x))
// backward: dl/dx = g = -sigmoid(x)
// dl/d(v_in) = g * v_out'
// dl/d(v_out) = v_in' * g
for (int j = 0; j < num_samples_; ++j) {
const int sample = sampler_->Sample(&srnd);
if (sample == label) continue; // Skip.
auto v_sample = Tw_out.chip<0>(sample);
auto dot = (v_in * v_sample).sum();
g = -((-dot).exp() + 1.f).inverse();
Tbuf += v_sample * (g() * lr);
v_sample += v_in * (g() * lr);
}
// Applies the gradient on v_in.
v_in += Tbuf;
}
}
private:
int32 num_samples_ = 0;
random::DistributionSampler* sampler_ = nullptr;
GuardedPhiloxRandom base_;
};
REGISTER_KERNEL_BUILDER(Name("NegTrainWord2vec").Device(DEVICE_CPU), NegTrainWord2vecOp);
} // end namespace tensorflow
|
Migrate from std::string to tensorflow::tstring. (#7830)
|
Migrate from std::string to tensorflow::tstring. (#7830)
Note that during the transition period tstring is typedef'ed to
std::string.
See: https://github.com/tensorflow/community/pull/91
|
C++
|
apache-2.0
|
tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples,tensorflow/examples
|
c7c78f7a7bb4b60efc17ced884657314a6fc797c
|
chrome/browser/extensions/extension_proxy_api.cc
|
chrome/browser/extensions/extension_proxy_api.cc
|
// 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/extensions/extension_proxy_api.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_pref_store.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
namespace {
// The scheme for which to use the proxy, not of the proxy URI itself.
typedef enum {
SCHEME_ALL = 0,
SCHEME_HTTP,
SCHEME_HTTPS,
SCHEME_FTP,
SCHEME_SOCKS,
SCHEME_MAX = SCHEME_SOCKS // Keep this value up to date.
};
// The names of the JavaScript properties to extract from the args_.
// These must be kept in sync with the SCHEME_* constants.
static const std::wstring field_name[] = {L"singleProxy",
L"proxyForHttp",
L"proxyForHttps",
L"proxyForFtp",
L"socksProxy"};
// The names of the schemes to be used to build the preference value string.
// These must be kept in sync with the SCHEME_* constants.
static const std::string scheme_name[] = {"*error*",
"http",
"https",
"ftp",
"socks"};
} // namespace
COMPILE_ASSERT(SCHEME_MAX == SCHEME_SOCKS, SCHEME_MAX_must_equal_SCHEME_SOCKS);
COMPILE_ASSERT(arraysize(field_name) == SCHEME_MAX + 1,
field_name_array_is_wrong_size);
COMPILE_ASSERT(arraysize(scheme_name) == SCHEME_MAX + 1,
scheme_name_array_is_wrong_size);
bool UseCustomProxySettingsFunction::RunImpl() {
DictionaryValue* proxy_config;
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &proxy_config));
DictionaryValue* proxy_rules;
EXTENSION_FUNCTION_VALIDATE(proxy_config->GetDictionary(L"rules",
&proxy_rules));
// Local data into which the parameters will be parsed. has_proxy describes
// whether a setting was found for the scheme; proxy_dict holds the
// DictionaryValues which in turn contain proxy server descriptions, and
// proxy_server holds ProxyServer structs containing those descriptions.
bool has_proxy[SCHEME_MAX + 1];
DictionaryValue* proxy_dict[SCHEME_MAX + 1];
ProxyServer proxy_server[SCHEME_MAX + 1];
// Looking for all possible proxy types is inefficient if we have a
// singleProxy that will supersede per-URL proxies, but it's worth it to keep
// the code simple and extensible.
for (size_t i = 0; i <= SCHEME_MAX; ++i) {
has_proxy[i] = proxy_rules->GetDictionary(field_name[i], &proxy_dict[i]);
if (has_proxy[i]) {
if (!GetProxyServer(proxy_dict[i], &proxy_server[i]))
return false;
}
}
// A single proxy supersedes individual HTTP, HTTPS, and FTP proxies.
if (has_proxy[SCHEME_ALL]) {
proxy_server[SCHEME_HTTP] = proxy_server[SCHEME_ALL];
proxy_server[SCHEME_HTTPS] = proxy_server[SCHEME_ALL];
proxy_server[SCHEME_FTP] = proxy_server[SCHEME_ALL];
has_proxy[SCHEME_HTTP] = true;
has_proxy[SCHEME_HTTPS] = true;
has_proxy[SCHEME_FTP] = true;
has_proxy[SCHEME_ALL] = false;
}
// TODO(pamg): Ensure that if a value is empty, that means "don't use a proxy
// for this scheme".
// Build the proxy preference string.
std::string proxy_pref;
for (size_t i = 0; i <= SCHEME_MAX; ++i) {
if (has_proxy[i]) {
// http=foopy:4010;ftp=socks://foopy2:80
if (!proxy_pref.empty())
proxy_pref.append(";");
proxy_pref.append(scheme_name[i]);
proxy_pref.append("=");
proxy_pref.append(proxy_server[i].scheme);
proxy_pref.append("://");
proxy_pref.append(proxy_server[i].host);
if (proxy_server[i].port != ProxyServer::INVALID_PORT) {
proxy_pref.append(":");
proxy_pref.append(StringPrintf("%d", proxy_server[i].port));
}
}
}
ExtensionPrefStore::ExtensionPrefDetails details =
std::make_pair(GetExtension(),
std::make_pair(prefs::kProxyServer,
Value::CreateStringValue(proxy_pref)));
NotificationService::current()->Notify(
NotificationType::EXTENSION_PREF_CHANGED,
Source<Profile>(profile_),
Details<ExtensionPrefStore::ExtensionPrefDetails>(&details));
return true;
}
bool UseCustomProxySettingsFunction::GetProxyServer(
const DictionaryValue* dict, ProxyServer* proxy_server) {
dict->GetString(L"scheme", &proxy_server->scheme);
EXTENSION_FUNCTION_VALIDATE(dict->GetString(L"host", &proxy_server->host));
dict->GetInteger(L"port", &proxy_server->port);
return true;
}
|
// 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/extensions/extension_proxy_api.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_pref_store.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
namespace {
// The scheme for which to use the proxy, not of the proxy URI itself.
enum {
SCHEME_ALL = 0,
SCHEME_HTTP,
SCHEME_HTTPS,
SCHEME_FTP,
SCHEME_SOCKS,
SCHEME_MAX = SCHEME_SOCKS // Keep this value up to date.
};
// The names of the JavaScript properties to extract from the args_.
// These must be kept in sync with the SCHEME_* constants.
static const std::wstring field_name[] = {L"singleProxy",
L"proxyForHttp",
L"proxyForHttps",
L"proxyForFtp",
L"socksProxy"};
// The names of the schemes to be used to build the preference value string.
// These must be kept in sync with the SCHEME_* constants.
static const std::string scheme_name[] = {"*error*",
"http",
"https",
"ftp",
"socks"};
} // namespace
COMPILE_ASSERT(SCHEME_MAX == SCHEME_SOCKS, SCHEME_MAX_must_equal_SCHEME_SOCKS);
COMPILE_ASSERT(arraysize(field_name) == SCHEME_MAX + 1,
field_name_array_is_wrong_size);
COMPILE_ASSERT(arraysize(scheme_name) == SCHEME_MAX + 1,
scheme_name_array_is_wrong_size);
bool UseCustomProxySettingsFunction::RunImpl() {
DictionaryValue* proxy_config;
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &proxy_config));
DictionaryValue* proxy_rules;
EXTENSION_FUNCTION_VALIDATE(proxy_config->GetDictionary(L"rules",
&proxy_rules));
// Local data into which the parameters will be parsed. has_proxy describes
// whether a setting was found for the scheme; proxy_dict holds the
// DictionaryValues which in turn contain proxy server descriptions, and
// proxy_server holds ProxyServer structs containing those descriptions.
bool has_proxy[SCHEME_MAX + 1];
DictionaryValue* proxy_dict[SCHEME_MAX + 1];
ProxyServer proxy_server[SCHEME_MAX + 1];
// Looking for all possible proxy types is inefficient if we have a
// singleProxy that will supersede per-URL proxies, but it's worth it to keep
// the code simple and extensible.
for (size_t i = 0; i <= SCHEME_MAX; ++i) {
has_proxy[i] = proxy_rules->GetDictionary(field_name[i], &proxy_dict[i]);
if (has_proxy[i]) {
if (!GetProxyServer(proxy_dict[i], &proxy_server[i]))
return false;
}
}
// A single proxy supersedes individual HTTP, HTTPS, and FTP proxies.
if (has_proxy[SCHEME_ALL]) {
proxy_server[SCHEME_HTTP] = proxy_server[SCHEME_ALL];
proxy_server[SCHEME_HTTPS] = proxy_server[SCHEME_ALL];
proxy_server[SCHEME_FTP] = proxy_server[SCHEME_ALL];
has_proxy[SCHEME_HTTP] = true;
has_proxy[SCHEME_HTTPS] = true;
has_proxy[SCHEME_FTP] = true;
has_proxy[SCHEME_ALL] = false;
}
// TODO(pamg): Ensure that if a value is empty, that means "don't use a proxy
// for this scheme".
// Build the proxy preference string.
std::string proxy_pref;
for (size_t i = 0; i <= SCHEME_MAX; ++i) {
if (has_proxy[i]) {
// http=foopy:4010;ftp=socks://foopy2:80
if (!proxy_pref.empty())
proxy_pref.append(";");
proxy_pref.append(scheme_name[i]);
proxy_pref.append("=");
proxy_pref.append(proxy_server[i].scheme);
proxy_pref.append("://");
proxy_pref.append(proxy_server[i].host);
if (proxy_server[i].port != ProxyServer::INVALID_PORT) {
proxy_pref.append(":");
proxy_pref.append(StringPrintf("%d", proxy_server[i].port));
}
}
}
ExtensionPrefStore::ExtensionPrefDetails details =
std::make_pair(GetExtension(),
std::make_pair(prefs::kProxyServer,
Value::CreateStringValue(proxy_pref)));
NotificationService::current()->Notify(
NotificationType::EXTENSION_PREF_CHANGED,
Source<Profile>(profile_),
Details<ExtensionPrefStore::ExtensionPrefDetails>(&details));
return true;
}
bool UseCustomProxySettingsFunction::GetProxyServer(
const DictionaryValue* dict, ProxyServer* proxy_server) {
dict->GetString(L"scheme", &proxy_server->scheme);
EXTENSION_FUNCTION_VALIDATE(dict->GetString(L"host", &proxy_server->host));
dict->GetInteger(L"port", &proxy_server->port);
return true;
}
|
Fix compile error by removing "typedef".
|
Fix compile error by removing "typedef".
BUG=48930
TEST=Linux (dbg-shlib) compiles without warnings/errors
git-svn-id: http://src.chromium.org/svn/trunk/src@54883 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 5f04f2ddeec0f41507772e08be84625aba87afc0
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
b1509db625ece1f87d39c9601569e897c70cf23f
|
chrome/browser/tab_contents/web_drag_dest_gtk.cc
|
chrome/browser/tab_contents/web_drag_dest_gtk.cc
|
// 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/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "app/gtk_dnd_util.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationMove;
using WebKit::WebDragOperationNone;
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0, GDK_ACTION_COPY);
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
// TODO(estade): we might want to support other actions besides copy,
// but that would increase the cost of getting our drag success guess
// wrong.
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, is_drop_target_ ? GDK_ACTION_COPY :
static_cast<GdkDragAction>(0),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
is_drop_target_ = false;
static int supported_targets[] = {
gtk_dnd_util::TEXT_PLAIN,
gtk_dnd_util::TEXT_URI_LIST,
gtk_dnd_util::TEXT_HTML,
// TODO(estade): support image drags?
};
data_requests_ = arraysize(supported_targets);
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
gtk_dnd_util::GetAtomForTarget(supported_targets[i]),
time);
}
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
static_cast<WebDragOperation>(
WebDragOperationCopy | WebDragOperationMove));
// TODO(snej): Pass appropriate DragOperation instead of hardcoding
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),
data->length));
g_free(text);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// TODO(estade): Can the filenames have a non-UTF8 encoding?
FilePath file_path;
if (net::FileURLToFilePath(GURL(*uri_iter), &file_path))
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
}
// Also, write the first URI as the URL.
if (uris[0])
drop_data_->url = GURL(uris[0]);
g_strfreev(uris);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
static_cast<WebDragOperation>(
WebDragOperationCopy | WebDragOperationMove));
// TODO(snej): Pass appropriate DragOperation instead of hardcoding
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
// The second parameter is just an educated guess, but at least we will
// get the drag-end animation right sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
|
// 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/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "app/gtk_dnd_util.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationMove;
using WebKit::WebDragOperationNone;
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0, GDK_ACTION_COPY);
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
// TODO(estade): we might want to support other actions besides copy,
// but that would increase the cost of getting our drag success guess
// wrong.
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, is_drop_target_ ? GDK_ACTION_COPY :
static_cast<GdkDragAction>(0),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
is_drop_target_ = false;
static int supported_targets[] = {
gtk_dnd_util::TEXT_PLAIN,
gtk_dnd_util::TEXT_URI_LIST,
gtk_dnd_util::TEXT_HTML,
gtk_dnd_util::NETSCAPE_URL,
gtk_dnd_util::CHROME_NAMED_URL,
// TODO(estade): support image drags?
};
data_requests_ = arraysize(supported_targets);
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
gtk_dnd_util::GetAtomForTarget(supported_targets[i]),
time);
}
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
static_cast<WebDragOperation>(
WebDragOperationCopy | WebDragOperationMove));
// TODO(snej): Pass appropriate DragOperation instead of hardcoding
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),
data->length));
g_free(text);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// TODO(estade): Can the filenames have a non-UTF8 encoding?
FilePath file_path;
if (net::FileURLToFilePath(GURL(*uri_iter), &file_path))
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
}
// Also, write the first URI as the URL.
if (uris[0])
drop_data_->url = GURL(uris[0]);
g_strfreev(uris);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {
std::string netscape_url(reinterpret_cast<char*>(data->data),
data->length);
size_t split = netscape_url.find_first_of('\n');
if (split != std::string::npos) {
drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(0, split));
if (split < netscape_url.size() - 1)
drop_data_->url = GURL(netscape_url.substr(split + 1));
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {
gtk_dnd_util::ExtractNamedURL(data,
&drop_data_->url, &drop_data_->url_title);
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
static_cast<WebDragOperation>(
WebDragOperationCopy | WebDragOperationMove));
// TODO(snej): Pass appropriate DragOperation instead of hardcoding
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
// The second parameter is just an educated guess, but at least we will
// get the drag-end animation right sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
|
Add a couple more drop targets to the render view.
|
Add a couple more drop targets to the render view.
BUG=35063
TEST=see bug
Review URL: http://codereview.chromium.org/1030001
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@41772 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
80f1451534d1c2be8e16313b8194bf458678f321
|
lib/SILPasses/SILCodeMotion.cpp
|
lib/SILPasses/SILCodeMotion.cpp
|
//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "codemotion"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILPasses/PassManager.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/RecyclingAllocator.h"
STATISTIC(NumSunk, "Number of instructions sunk");
STATISTIC(NumDeadStores, "Number of dead stores removed");
STATISTIC(NumDupLoads, "Number of dup loads removed");
using namespace swift;
static const int SinkSearchWindow = 6;
static bool isWriteMemBehavior(SILInstruction::MemoryBehavior B) {
switch (B) {
case SILInstruction::MemoryBehavior::MayWrite:
case SILInstruction::MemoryBehavior::MayReadWrite:
case SILInstruction::MemoryBehavior::MayHaveSideEffects:
return true;
case SILInstruction::MemoryBehavior::None:
case SILInstruction::MemoryBehavior::MayRead:
return false;
}
}
/// \brief Promote stored values to loads, remove dead stores and merge
/// duplicated loads.
void promoteMemoryOperationsInBlock(SILBasicBlock *BB, AliasAnalysis *AA) {
StoreInst *PrevStore = 0;
llvm::SmallPtrSet<LoadInst *, 8> Loads;
auto II = BB->begin(), E = BB->end();
while (II != E) {
SILInstruction *Inst = II++;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
// This is a StoreInst. Let's see if we can remove the previous stores.
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// Invalidate all loads that this store writes to.
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, SILValue(LI))))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
// If we are storing to the previously stored address then delete the old
// store.
if (PrevStore && PrevStore->getDest() == SI->getDest()) {
DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:"
<< *PrevStore);
recursivelyDeleteTriviallyDeadInstructions(PrevStore, true);
PrevStore = SI;
NumDeadStores++;
continue;
}
PrevStore = SI;
continue;
}
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
// If we are loading a value that we just saved then use the saved value.
if (PrevStore && PrevStore->getDest() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore);
SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc());
recursivelyDeleteTriviallyDeadInstructions(LI, true);
NumDupLoads++;
continue;
}
// Search the previous loads and replace the current load with one of the
// previous loads.
for (auto PrevLd : Loads) {
if (PrevLd->getOperand() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Replacing with previous load: "
<< *PrevLd);
SILValue(LI, 0).replaceAllUsesWith(PrevLd);
recursivelyDeleteTriviallyDeadInstructions(LI, true);
LI = 0;
NumDupLoads++;
break;
}
}
if (LI)
Loads.insert(LI);
continue;
}
// Retains write to memory but they don't affect loads and stores.
if (isa<StrongRetainInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and"
" stores.\n");
continue;
}
if (auto *AI = dyn_cast<ApplyInst>(Inst))
if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee()))
if (isReadNone(BI)) {
DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect "
"loads and stores.\n");
continue;
}
// cond_fail does not read/write memory in a manner that we care about.
if (isa<CondFailInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found a cond fail, does not affect "
"loads and stores.\n");
continue;
}
// All other instructions that read from memory invalidate the store.
if (Inst->mayReadFromMemory()) {
DEBUG(llvm::dbgs() << " Found an instruction that reads from memory."
" Invalidating store.\n");
PrevStore = 0;
}
// If we have an instruction that may write to memory and we can not prove
// that it and its operands can not alias a load we have visited, invalidate
// that load.
if (Inst->mayWriteToMemory()) {
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, SILValue(LI))))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
}
}
}
/// \brief Returns True if we can sink this instruction to another basic block.
static bool canSinkInstruction(SILInstruction *Inst) {
return Inst->use_empty() && !isa<TermInst>(Inst);
}
/// \brief Returns true if this instruction is a skip barrier, which means that
/// we can't sink other instructions past it.
static bool isSinkBarrier(SILInstruction *Inst) {
// We know that some calls do not have side effects.
if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst))
if (BuiltinFunctionRefInst *FR =
dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef()))
return !isSideEffectFree(FR);
if (isa<TermInst>(Inst))
return false;
if (Inst->mayHaveSideEffects())
return true;
return false;
}
/// \brief Search for an instruction that is identical to \p Iden by scanning
/// \p BB starting at the end of the block, stopping on sink barriers.
SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) {
int SkipBudget = SinkSearchWindow;
SILBasicBlock::iterator InstToSink = BB->getTerminator();
while (SkipBudget) {
// If we found a sinkable instruction that is identical to our goal
// then return it.
if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) {
DEBUG(llvm::dbgs() << "Found an identical instruction.");
return InstToSink;
}
// If this instruction is a skip-barrier end the scan.
if (isSinkBarrier(InstToSink))
return nullptr;
// If this is the first instruction in the block then we are done.
if (InstToSink == BB->begin())
return nullptr;
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
return nullptr;
}
static void sinkCodeFromPredecessors(SILBasicBlock *BB) {
if (BB->pred_empty())
return;
// This block must be the only successor of all the predecessors.
for (auto P : BB->getPreds())
if (P->getSingleSuccessor() != BB)
return;
SILBasicBlock *FirstPred = *BB->pred_begin();
// The first Pred must have at least one non-terminator.
if (FirstPred->getTerminator() == FirstPred->begin())
return;
DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n");
unsigned SkipBudget = SinkSearchWindow;
// Start scanning backwards from the terminator.
SILBasicBlock::iterator InstToSink = FirstPred->getTerminator();
while (SkipBudget) {
DEBUG(llvm::dbgs() << "Processing: " << *InstToSink);
// Save the duplicated instructions in case we need to remove them.
SmallVector<SILInstruction *, 4> Dups;
if (canSinkInstruction(InstToSink)) {
// For all preds:
for (auto P : BB->getPreds()) {
if (P == FirstPred)
continue;
// Search the duplicated instruction in the predecessor.
if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) {
Dups.push_back(DupInst);
} else {
DEBUG(llvm::dbgs() << "Instruction mismatch.\n");
Dups.clear();
break;
}
}
// If we found duplicated instructions, sink one of the copies and delete
// the rest.
if (Dups.size()) {
DEBUG(llvm::dbgs() << "Moving: " << *InstToSink);
InstToSink->moveBefore(BB->begin());
for (auto I : Dups) {
I->replaceAllUsesWith(InstToSink);
I->eraseFromParent();
NumSunk++;
}
// Restart the scan.
InstToSink = FirstPred->getTerminator();
DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink);
continue;
}
}
// If this instruction was a barrier then we can't sink anything else.
if (isSinkBarrier(InstToSink)) {
DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink);
return;
}
// This is the first instruction, we are done.
if (InstToSink == FirstPred->begin()) {
DEBUG(llvm::dbgs() << "Reached the first instruction.");
return;
}
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
}
class SILCodeMotion : public SILFunctionTransform {
virtual ~SILCodeMotion() {}
/// The entry point to the transformation.
virtual void runOnFunction(SILFunction &F, SILPassManager *PM) {
DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() <<
" *****\n");
AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>();
// Remove dead stores and merge duplicate loads.
for (auto &BB : F)
promoteMemoryOperationsInBlock(&BB, AA);
// Sink duplicated code from predecessors.
for (auto &BB : F)
sinkCodeFromPredecessors(&BB);
PM->invalidateAllAnalysis(&F, SILAnalysis::InvalidationKind::Instructions);
}
};
SILTransform *swift::createCodeMotion() {
return new SILCodeMotion();
}
|
//===- SILCodeMotion.cpp - Code Motion Optimizations ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "codemotion"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SILPasses/PassManager.h"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/RecyclingAllocator.h"
STATISTIC(NumSunk, "Number of instructions sunk");
STATISTIC(NumDeadStores, "Number of dead stores removed");
STATISTIC(NumDupLoads, "Number of dup loads removed");
using namespace swift;
static const int SinkSearchWindow = 6;
static bool isWriteMemBehavior(SILInstruction::MemoryBehavior B) {
switch (B) {
case SILInstruction::MemoryBehavior::MayWrite:
case SILInstruction::MemoryBehavior::MayReadWrite:
case SILInstruction::MemoryBehavior::MayHaveSideEffects:
return true;
case SILInstruction::MemoryBehavior::None:
case SILInstruction::MemoryBehavior::MayRead:
return false;
}
}
/// \brief Promote stored values to loads, remove dead stores and merge
/// duplicated loads.
void promoteMemoryOperationsInBlock(SILBasicBlock *BB, AliasAnalysis *AA) {
StoreInst *PrevStore = 0;
llvm::SmallPtrSet<LoadInst *, 8> Loads;
auto II = BB->begin(), E = BB->end();
while (II != E) {
SILInstruction *Inst = II++;
DEBUG(llvm::dbgs() << "Visiting: " << *Inst);
// This is a StoreInst. Let's see if we can remove the previous stores.
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
// Invalidate all loads that this store writes to.
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, SILValue(LI))))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
// If we are storing to the previously stored address then delete the old
// store.
if (PrevStore && PrevStore->getDest() == SI->getDest()) {
DEBUG(llvm::dbgs() << " Found a dead previous store... Removing...:"
<< *PrevStore);
recursivelyDeleteTriviallyDeadInstructions(PrevStore, true);
PrevStore = SI;
NumDeadStores++;
continue;
}
PrevStore = SI;
continue;
}
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
// If we are loading a value that we just saved then use the saved value.
if (PrevStore && PrevStore->getDest() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Forwarding store from: " << *PrevStore);
SILValue(LI, 0).replaceAllUsesWith(PrevStore->getSrc());
recursivelyDeleteTriviallyDeadInstructions(LI, true);
NumDupLoads++;
continue;
}
// Search the previous loads and replace the current load with one of the
// previous loads.
for (auto PrevLd : Loads) {
if (PrevLd->getOperand() == LI->getOperand()) {
DEBUG(llvm::dbgs() << " Replacing with previous load: "
<< *PrevLd);
SILValue(LI, 0).replaceAllUsesWith(PrevLd);
recursivelyDeleteTriviallyDeadInstructions(LI, true);
LI = 0;
NumDupLoads++;
break;
}
}
if (LI)
Loads.insert(LI);
continue;
}
// Retains write to memory but they don't affect loads and stores.
if (isa<StrongRetainInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found strong retain, does not affect loads and"
" stores.\n");
continue;
}
if (auto *AI = dyn_cast<ApplyInst>(Inst))
if (auto *BI = dyn_cast<BuiltinFunctionRefInst>(&*AI->getCallee()))
if (isReadNone(BI)) {
DEBUG(llvm::dbgs() << " Found readnone builtin, does not affect "
"loads and stores.\n");
continue;
}
// cond_fail does not read/write memory in a manner that we care about.
if (isa<CondFailInst>(Inst)) {
DEBUG(llvm::dbgs() << " Found a cond fail, does not affect "
"loads and stores.\n");
continue;
}
// All other instructions that read from memory invalidate the store.
if (Inst->mayReadFromMemory()) {
DEBUG(llvm::dbgs() << " Found an instruction that reads from memory."
" Invalidating store.\n");
PrevStore = 0;
}
// If we have an instruction that may write to memory and we can not prove
// that it and its operands can not alias a load we have visited, invalidate
// that load.
if (Inst->mayWriteToMemory()) {
llvm::SmallVector<LoadInst *, 4> InvalidatedLoadList;
for (auto *LI : Loads)
if (isWriteMemBehavior(AA->getMemoryBehavior(Inst, SILValue(LI))))
InvalidatedLoadList.push_back(LI);
for (auto *LI : InvalidatedLoadList) {
DEBUG(llvm::dbgs() << " Found an instruction that writes to memory "
"such that a load is invalidated:" << *LI);
Loads.erase(LI);
}
}
}
}
/// \brief Returns True if we can sink this instruction to another basic block.
static bool canSinkInstruction(SILInstruction *Inst) {
return Inst->use_empty() && !isa<TermInst>(Inst);
}
/// \brief Returns true if this instruction is a skip barrier, which means that
/// we can't sink other instructions past it.
static bool isSinkBarrier(SILInstruction *Inst) {
// We know that some calls do not have side effects.
if (const ApplyInst *AI = dyn_cast<ApplyInst>(Inst))
if (BuiltinFunctionRefInst *FR =
dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef()))
return !isSideEffectFree(FR);
if (isa<TermInst>(Inst))
return false;
if (Inst->mayHaveSideEffects())
return true;
return false;
}
/// \brief Search for an instruction that is identical to \p Iden by scanning
/// \p BB starting at the end of the block, stopping on sink barriers.
SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden) {
int SkipBudget = SinkSearchWindow;
SILBasicBlock::iterator InstToSink = BB->getTerminator();
while (SkipBudget) {
// If we found a sinkable instruction that is identical to our goal
// then return it.
if (canSinkInstruction(InstToSink) && Iden->isIdenticalTo(InstToSink)) {
DEBUG(llvm::dbgs() << "Found an identical instruction.");
return InstToSink;
}
// If this instruction is a skip-barrier end the scan.
if (isSinkBarrier(InstToSink))
return nullptr;
// If this is the first instruction in the block then we are done.
if (InstToSink == BB->begin())
return nullptr;
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
return nullptr;
}
static void sinkCodeFromPredecessors(SILBasicBlock *BB) {
if (BB->pred_empty())
return;
// This block must be the only successor of all the predecessors.
for (auto P : BB->getPreds())
if (P->getSingleSuccessor() != BB)
return;
SILBasicBlock *FirstPred = *BB->pred_begin();
// The first Pred must have at least one non-terminator.
if (FirstPred->getTerminator() == FirstPred->begin())
return;
DEBUG(llvm::dbgs() << " Sinking values from predecessors.\n");
unsigned SkipBudget = SinkSearchWindow;
// Start scanning backwards from the terminator.
SILBasicBlock::iterator InstToSink = FirstPred->getTerminator();
while (SkipBudget) {
DEBUG(llvm::dbgs() << "Processing: " << *InstToSink);
// Save the duplicated instructions in case we need to remove them.
SmallVector<SILInstruction *, 4> Dups;
if (canSinkInstruction(InstToSink)) {
// For all preds:
for (auto P : BB->getPreds()) {
if (P == FirstPred)
continue;
// Search the duplicated instruction in the predecessor.
if (SILInstruction *DupInst = findIdenticalInBlock(P, InstToSink)) {
Dups.push_back(DupInst);
} else {
DEBUG(llvm::dbgs() << "Instruction mismatch.\n");
Dups.clear();
break;
}
}
// If we found duplicated instructions, sink one of the copies and delete
// the rest.
if (Dups.size()) {
DEBUG(llvm::dbgs() << "Moving: " << *InstToSink);
InstToSink->moveBefore(BB->begin());
for (auto I : Dups) {
I->replaceAllUsesWith(InstToSink);
I->eraseFromParent();
NumSunk++;
}
// Restart the scan.
InstToSink = FirstPred->getTerminator();
DEBUG(llvm::dbgs() << "Restarting scan. Next inst: " << *InstToSink);
continue;
}
}
// If this instruction was a barrier then we can't sink anything else.
if (isSinkBarrier(InstToSink)) {
DEBUG(llvm::dbgs() << "Aborting on barrier: " << *InstToSink);
return;
}
// This is the first instruction, we are done.
if (InstToSink == FirstPred->begin()) {
DEBUG(llvm::dbgs() << "Reached the first instruction.");
return;
}
SkipBudget--;
InstToSink = std::prev(InstToSink);
DEBUG(llvm::dbgs() << "Continuing scan. Next inst: " << *InstToSink);
}
}
class SILCodeMotion : public SILFunctionTransform {
virtual ~SILCodeMotion() {}
/// The entry point to the transformation.
virtual void runOnFunction(SILFunction &F, SILPassManager *PM) {
DEBUG(llvm::dbgs() << "***** CodeMotion on function: " << F.getName() <<
" *****\n");
AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>();
assert(AA && "We should never get a null alias analysis.");
// Remove dead stores and merge duplicate loads.
for (auto &BB : F)
promoteMemoryOperationsInBlock(&BB, AA);
// Sink duplicated code from predecessors.
for (auto &BB : F)
sinkCodeFromPredecessors(&BB);
PM->invalidateAllAnalysis(&F, SILAnalysis::InvalidationKind::Instructions);
}
};
SILTransform *swift::createCodeMotion() {
return new SILCodeMotion();
}
|
Put in assert to make sure we always get a non-null alias analysis. The only way this can happen is if someone is careless and does not add the alias analysis to the pass manager.
|
[sil-code-motion] Put in assert to make sure we always get a non-null alias analysis. The only way this can happen is if someone is careless and does not add the alias analysis to the pass manager.
Swift SVN r13551
|
C++
|
apache-2.0
|
natecook1000/swift,cbrentharris/swift,amraboelela/swift,LeoShimonaka/swift,hooman/swift,uasys/swift,benlangmuir/swift,jtbandes/swift,lorentey/swift,rudkx/swift,cbrentharris/swift,parkera/swift,devincoughlin/swift,huonw/swift,russbishop/swift,allevato/swift,emilstahl/swift,devincoughlin/swift,arvedviehweger/swift,tkremenek/swift,felix91gr/swift,milseman/swift,ken0nek/swift,stephentyrone/swift,kstaring/swift,karwa/swift,slavapestov/swift,gmilos/swift,apple/swift,emilstahl/swift,shajrawi/swift,OscarSwanros/swift,gribozavr/swift,hughbe/swift,ahoppen/swift,milseman/swift,practicalswift/swift,johnno1962d/swift,tkremenek/swift,stephentyrone/swift,codestergit/swift,adrfer/swift,jckarter/swift,aschwaighofer/swift,return/swift,sdulal/swift,codestergit/swift,xedin/swift,hooman/swift,slavapestov/swift,IngmarStein/swift,austinzheng/swift,MukeshKumarS/Swift,alblue/swift,swiftix/swift,MukeshKumarS/Swift,practicalswift/swift,brentdax/swift,milseman/swift,swiftix/swift,swiftix/swift,LeoShimonaka/swift,sschiau/swift,frootloops/swift,russbishop/swift,hughbe/swift,danielmartin/swift,xedin/swift,ahoppen/swift,khizkhiz/swift,tjw/swift,shahmishal/swift,sschiau/swift,return/swift,practicalswift/swift,KrishMunot/swift,brentdax/swift,brentdax/swift,manavgabhawala/swift,amraboelela/swift,therealbnut/swift,aschwaighofer/swift,dduan/swift,modocache/swift,deyton/swift,cbrentharris/swift,KrishMunot/swift,MukeshKumarS/Swift,jckarter/swift,hughbe/swift,ken0nek/swift,tardieu/swift,jopamer/swift,austinzheng/swift,emilstahl/swift,xwu/swift,xedin/swift,kusl/swift,russbishop/swift,kentya6/swift,hooman/swift,xedin/swift,amraboelela/swift,bitjammer/swift,parkera/swift,tkremenek/swift,calebd/swift,jmgc/swift,swiftix/swift.old,brentdax/swift,CodaFi/swift,dduan/swift,dduan/swift,uasys/swift,deyton/swift,russbishop/swift,karwa/swift,gribozavr/swift,gmilos/swift,kentya6/swift,brentdax/swift,hooman/swift,calebd/swift,gregomni/swift,felix91gr/swift,xwu/swift,roambotics/swift,slavapestov/swift,airspeedswift/swift,sdulal/swift,CodaFi/swift,adrfer/swift,kperryua/swift,johnno1962d/swift,benlangmuir/swift,devincoughlin/swift,parkera/swift,huonw/swift,tinysun212/swift-windows,JGiola/swift,ahoppen/swift,adrfer/swift,IngmarStein/swift,kstaring/swift,khizkhiz/swift,deyton/swift,aschwaighofer/swift,therealbnut/swift,amraboelela/swift,frootloops/swift,kstaring/swift,Jnosh/swift,xwu/swift,Jnosh/swift,ben-ng/swift,djwbrown/swift,harlanhaskins/swift,airspeedswift/swift,CodaFi/swift,arvedviehweger/swift,parkera/swift,lorentey/swift,johnno1962d/swift,felix91gr/swift,ken0nek/swift,atrick/swift,amraboelela/swift,modocache/swift,adrfer/swift,dreamsxin/swift,LeoShimonaka/swift,zisko/swift,lorentey/swift,dduan/swift,ben-ng/swift,tardieu/swift,tinysun212/swift-windows,atrick/swift,JGiola/swift,benlangmuir/swift,djwbrown/swift,shajrawi/swift,atrick/swift,JaSpa/swift,IngmarStein/swift,djwbrown/swift,CodaFi/swift,jtbandes/swift,xwu/swift,practicalswift/swift,Jnosh/swift,hughbe/swift,arvedviehweger/swift,CodaFi/swift,kperryua/swift,JGiola/swift,roambotics/swift,hooman/swift,jmgc/swift,IngmarStein/swift,stephentyrone/swift,kusl/swift,zisko/swift,codestergit/swift,kentya6/swift,tjw/swift,xedin/swift,gribozavr/swift,airspeedswift/swift,jmgc/swift,Jnosh/swift,kperryua/swift,sschiau/swift,shajrawi/swift,austinzheng/swift,practicalswift/swift,sdulal/swift,jtbandes/swift,gottesmm/swift,khizkhiz/swift,swiftix/swift,parkera/swift,hughbe/swift,milseman/swift,MukeshKumarS/Swift,shajrawi/swift,manavgabhawala/swift,therealbnut/swift,kentya6/swift,shajrawi/swift,karwa/swift,Ivacker/swift,felix91gr/swift,practicalswift/swift,kusl/swift,shahmishal/swift,kperryua/swift,jckarter/swift,JGiola/swift,kentya6/swift,zisko/swift,emilstahl/swift,hooman/swift,calebd/swift,gregomni/swift,adrfer/swift,swiftix/swift.old,lorentey/swift,jckarter/swift,hughbe/swift,emilstahl/swift,cbrentharris/swift,parkera/swift,return/swift,djwbrown/swift,jtbandes/swift,benlangmuir/swift,austinzheng/swift,Ivacker/swift,gregomni/swift,felix91gr/swift,nathawes/swift,kstaring/swift,deyton/swift,bitjammer/swift,danielmartin/swift,johnno1962d/swift,kusl/swift,KrishMunot/swift,atrick/swift,tardieu/swift,MukeshKumarS/Swift,JaSpa/swift,airspeedswift/swift,austinzheng/swift,tkremenek/swift,alblue/swift,SwiftAndroid/swift,atrick/swift,therealbnut/swift,allevato/swift,natecook1000/swift,roambotics/swift,alblue/swift,frootloops/swift,return/swift,jopamer/swift,OscarSwanros/swift,huonw/swift,gribozavr/swift,benlangmuir/swift,Ivacker/swift,frootloops/swift,calebd/swift,adrfer/swift,manavgabhawala/swift,SwiftAndroid/swift,sdulal/swift,ken0nek/swift,jtbandes/swift,return/swift,kperryua/swift,practicalswift/swift,felix91gr/swift,arvedviehweger/swift,OscarSwanros/swift,rudkx/swift,felix91gr/swift,CodaFi/swift,zisko/swift,jopamer/swift,gmilos/swift,kentya6/swift,swiftix/swift.old,lorentey/swift,dduan/swift,frootloops/swift,khizkhiz/swift,swiftix/swift.old,deyton/swift,milseman/swift,return/swift,lorentey/swift,JaSpa/swift,SwiftAndroid/swift,gmilos/swift,Ivacker/swift,bitjammer/swift,shahmishal/swift,ahoppen/swift,calebd/swift,rudkx/swift,gribozavr/swift,sdulal/swift,jckarter/swift,bitjammer/swift,SwiftAndroid/swift,tardieu/swift,KrishMunot/swift,johnno1962d/swift,allevato/swift,JGiola/swift,LeoShimonaka/swift,modocache/swift,amraboelela/swift,uasys/swift,LeoShimonaka/swift,slavapestov/swift,milseman/swift,hughbe/swift,kentya6/swift,sdulal/swift,swiftix/swift.old,glessard/swift,bitjammer/swift,sschiau/swift,nathawes/swift,djwbrown/swift,swiftix/swift.old,sdulal/swift,deyton/swift,dduan/swift,lorentey/swift,LeoShimonaka/swift,gregomni/swift,tinysun212/swift-windows,harlanhaskins/swift,aschwaighofer/swift,tjw/swift,sschiau/swift,mightydeveloper/swift,mightydeveloper/swift,johnno1962d/swift,mightydeveloper/swift,roambotics/swift,JaSpa/swift,gottesmm/swift,tinysun212/swift-windows,gregomni/swift,alblue/swift,dreamsxin/swift,devincoughlin/swift,swiftix/swift,xedin/swift,emilstahl/swift,Ivacker/swift,Jnosh/swift,bitjammer/swift,arvedviehweger/swift,huonw/swift,glessard/swift,shahmishal/swift,IngmarStein/swift,frootloops/swift,shajrawi/swift,swiftix/swift,practicalswift/swift,brentdax/swift,gottesmm/swift,alblue/swift,slavapestov/swift,tkremenek/swift,natecook1000/swift,kstaring/swift,LeoShimonaka/swift,jtbandes/swift,gmilos/swift,bitjammer/swift,ben-ng/swift,gottesmm/swift,zisko/swift,kperryua/swift,tardieu/swift,airspeedswift/swift,therealbnut/swift,khizkhiz/swift,glessard/swift,allevato/swift,jmgc/swift,manavgabhawala/swift,stephentyrone/swift,danielmartin/swift,slavapestov/swift,JaSpa/swift,kusl/swift,tinysun212/swift-windows,austinzheng/swift,cbrentharris/swift,swiftix/swift.old,xedin/swift,allevato/swift,modocache/swift,KrishMunot/swift,tjw/swift,uasys/swift,shahmishal/swift,uasys/swift,dduan/swift,codestergit/swift,harlanhaskins/swift,Ivacker/swift,kusl/swift,uasys/swift,airspeedswift/swift,gribozavr/swift,apple/swift,adrfer/swift,SwiftAndroid/swift,mightydeveloper/swift,modocache/swift,shahmishal/swift,danielmartin/swift,huonw/swift,SwiftAndroid/swift,IngmarStein/swift,nathawes/swift,MukeshKumarS/Swift,kusl/swift,shahmishal/swift,danielmartin/swift,slavapestov/swift,JaSpa/swift,OscarSwanros/swift,cbrentharris/swift,cbrentharris/swift,jckarter/swift,shajrawi/swift,rudkx/swift,gottesmm/swift,djwbrown/swift,Ivacker/swift,karwa/swift,tjw/swift,ken0nek/swift,gribozavr/swift,kstaring/swift,aschwaighofer/swift,manavgabhawala/swift,ahoppen/swift,shajrawi/swift,mightydeveloper/swift,modocache/swift,allevato/swift,kstaring/swift,khizkhiz/swift,codestergit/swift,hooman/swift,mightydeveloper/swift,huonw/swift,ben-ng/swift,KrishMunot/swift,tinysun212/swift-windows,nathawes/swift,xwu/swift,manavgabhawala/swift,amraboelela/swift,deyton/swift,xedin/swift,natecook1000/swift,jmgc/swift,karwa/swift,alblue/swift,KrishMunot/swift,swiftix/swift,ben-ng/swift,aschwaighofer/swift,aschwaighofer/swift,mightydeveloper/swift,johnno1962d/swift,tinysun212/swift-windows,parkera/swift,JGiola/swift,khizkhiz/swift,emilstahl/swift,glessard/swift,jmgc/swift,russbishop/swift,russbishop/swift,gribozavr/swift,apple/swift,xwu/swift,rudkx/swift,natecook1000/swift,cbrentharris/swift,therealbnut/swift,natecook1000/swift,zisko/swift,OscarSwanros/swift,OscarSwanros/swift,arvedviehweger/swift,SwiftAndroid/swift,gregomni/swift,OscarSwanros/swift,uasys/swift,jopamer/swift,glessard/swift,stephentyrone/swift,manavgabhawala/swift,glessard/swift,kentya6/swift,tkremenek/swift,karwa/swift,brentdax/swift,apple/swift,alblue/swift,lorentey/swift,CodaFi/swift,kusl/swift,nathawes/swift,danielmartin/swift,MukeshKumarS/Swift,parkera/swift,tardieu/swift,harlanhaskins/swift,IngmarStein/swift,emilstahl/swift,gottesmm/swift,roambotics/swift,milseman/swift,xwu/swift,natecook1000/swift,gmilos/swift,ben-ng/swift,sschiau/swift,jopamer/swift,harlanhaskins/swift,benlangmuir/swift,codestergit/swift,tkremenek/swift,austinzheng/swift,Ivacker/swift,tjw/swift,apple/swift,mightydeveloper/swift,jtbandes/swift,devincoughlin/swift,jopamer/swift,Jnosh/swift,jckarter/swift,swiftix/swift.old,devincoughlin/swift,sschiau/swift,ben-ng/swift,gottesmm/swift,russbishop/swift,frootloops/swift,sschiau/swift,karwa/swift,therealbnut/swift,huonw/swift,rudkx/swift,stephentyrone/swift,ken0nek/swift,ken0nek/swift,stephentyrone/swift,calebd/swift,Jnosh/swift,gmilos/swift,nathawes/swift,allevato/swift,JaSpa/swift,djwbrown/swift,devincoughlin/swift,calebd/swift,zisko/swift,kperryua/swift,danielmartin/swift,harlanhaskins/swift,tjw/swift,tardieu/swift,codestergit/swift,harlanhaskins/swift,karwa/swift,return/swift,roambotics/swift,jmgc/swift,atrick/swift,sdulal/swift,jopamer/swift,airspeedswift/swift,nathawes/swift,ahoppen/swift,apple/swift,arvedviehweger/swift,LeoShimonaka/swift,modocache/swift,devincoughlin/swift,shahmishal/swift
|
af4c5eac92631f045ec34dcd3178ff54d9159b8c
|
header/thread/CLock_unordered_set.hpp
|
header/thread/CLock_unordered_set.hpp
|
#ifndef CLOCK_UNORDERED_SET
#define CLOCK_UNORDERED_SET
#include<functional> //equal_to, hash
#include<memory> //allocator
#include<mutex>
#include<shared_mutex>
#include<unordered_set>
#include<utility> //forward, move
namespace nThread
{
template<class Key,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<Key>>
class CLock_unordered_set
{
std::unordered_set<Key,Hash,KeyEqual,Alloc> set_;
mutable std::shared_mutex mut_;
template<class KeyFwdRef,class ... Args>
bool try_emplace_(KeyFwdRef &&key,Args &&...args)
{
std::lock_guard<std::shared_mutex> lock{mut_};
if(find(key))
return false;
set_.emplace(std::forward<decltype(key)>(key),std::forward<decltype(args)>(args)...);
return true;
}
public:
using size_type=typename std::unordered_set<Key,Hash,KeyEqual,Alloc>::size_type;
CLock_unordered_set()=default;
CLock_unordered_set(const CLock_unordered_set &)=delete;
template<class ... Args>
bool emplace(Args &&...args)
{
std::lock_guard<std::shared_mutex> lock{mut_};
return set_.emplace(std::forward<decltype(args)>(args)...).second;
}
size_type erase(const Key &key)
{
std::lock_guard<std::shared_mutex> lock{mut_};
return set_.erase(key);
}
bool find(const Key &key) const
{
std::shared_lock<std::shared_mutex> lock{mut_};
return set_.find(key)!=set_.end();
}
template<class ... Args>
inline bool try_emplace(const Key &key,Args &&...args)
{
return try_emplace_(key,std::forward<decltype(args)>(args)...);
}
template<class ... Args>
inline bool try_emplace(Key &&key,Args &&...args)
{
return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...);
}
CLock_unordered_set& operator=(const CLock_unordered_set &)=delete;
};
}
#endif
|
#ifndef CLOCK_UNORDERED_SET
#define CLOCK_UNORDERED_SET
#include<functional> //equal_to, hash
#include<memory> //allocator
#include<mutex>
#include<shared_mutex>
#include<unordered_set>
#include<utility> //forward, move
namespace nThread
{
template<class Key,class Hash=std::hash<Key>,class KeyEqual=std::equal_to<Key>,class Alloc=std::allocator<Key>>
class CLock_unordered_set
{
std::unordered_set<Key,Hash,KeyEqual,Alloc> set_;
mutable std::shared_mutex mut_;
template<class KeyFwdRef,class ... Args>
bool try_emplace_(KeyFwdRef &&key,Args &&...args)
{
std::lock_guard<std::shared_mutex> lock{mut_};
if(find_not_ts(key))
return false;
set_.emplace(std::forward<decltype(key)>(key),std::forward<decltype(args)>(args)...);
return true;
}
public:
using size_type=typename std::unordered_set<Key,Hash,KeyEqual,Alloc>::size_type;
CLock_unordered_set()=default;
CLock_unordered_set(const CLock_unordered_set &)=delete;
template<class ... Args>
bool emplace(Args &&...args)
{
std::lock_guard<std::shared_mutex> lock{mut_};
return set_.emplace(std::forward<decltype(args)>(args)...).second;
}
size_type erase(const Key &key)
{
std::lock_guard<std::shared_mutex> lock{mut_};
return set_.erase(key);
}
bool find(const Key &key) const
{
std::shared_lock<std::shared_mutex> lock{mut_};
return find_not_ts(key);
}
inline bool find_not_ts(const Key &key) const
{
return set_.find(key)!=set_.end();
}
template<class ... Args>
inline bool try_emplace(const Key &key,Args &&...args)
{
return try_emplace_(key,std::forward<decltype(args)>(args)...);
}
template<class ... Args>
inline bool try_emplace(Key &&key,Args &&...args)
{
return try_emplace_(std::move(key),std::forward<decltype(args)>(args)...);
}
CLock_unordered_set& operator=(const CLock_unordered_set &)=delete;
};
}
#endif
|
fix double lock
|
fix double lock
|
C++
|
mit
|
Fdhvdu/lib
|
24adc8f60f0a39e45363eef5392fe1a7e27bd12f
|
lib/Target/ARM/ARMSubtarget.cpp
|
lib/Target/ARM/ARMSubtarget.cpp
|
//===-- ARMSubtarget.cpp - ARM Subtarget Information ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ARM specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#include "ARMSubtarget.h"
#include "ARMBaseInstrInfo.h"
#include "ARMBaseRegisterInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetOptions.h"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "ARMGenSubtargetInfo.inc"
using namespace llvm;
static cl::opt<bool>
ReserveR9("arm-reserve-r9", cl::Hidden,
cl::desc("Reserve R9, making it unavailable as GPR"));
static cl::opt<bool>
DarwinUseMOVT("arm-darwin-use-movt", cl::init(true), cl::Hidden);
static cl::opt<bool>
UseFusedMulOps("arm-use-mulops",
cl::init(true), cl::Hidden);
enum AlignMode {
DefaultAlign,
StrictAlign,
NoStrictAlign
};
static cl::opt<AlignMode>
Align(cl::desc("Load/store alignment support"),
cl::Hidden, cl::init(DefaultAlign),
cl::values(
clEnumValN(DefaultAlign, "arm-default-align",
"Generate unaligned accesses only on hardware/OS "
"combinations that are known to support them"),
clEnumValN(StrictAlign, "arm-strict-align",
"Disallow all unaligned memory accesses"),
clEnumValN(NoStrictAlign, "arm-no-strict-align",
"Allow unaligned memory accesses"),
clEnumValEnd));
ARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, const TargetOptions &Options)
: ARMGenSubtargetInfo(TT, CPU, FS)
, ARMProcFamily(Others)
, stackAlignment(4)
, CPUString(CPU)
, TargetTriple(TT)
, Options(Options)
, TargetABI(ARM_ABI_APCS) {
initializeEnvironment();
resetSubtargetFeatures(CPU, FS);
}
void ARMSubtarget::initializeEnvironment() {
HasV4TOps = false;
HasV5TOps = false;
HasV5TEOps = false;
HasV6Ops = false;
HasV6T2Ops = false;
HasV7Ops = false;
HasV8Ops = false;
HasVFPv2 = false;
HasVFPv3 = false;
HasVFPv4 = false;
HasV8FP = false;
HasNEON = false;
UseNEONForSinglePrecisionFP = false;
UseMulOps = UseFusedMulOps;
SlowFPVMLx = false;
HasVMLxForwarding = false;
SlowFPBrcc = false;
InThumbMode = false;
HasThumb2 = false;
IsMClass = false;
NoARM = false;
PostRAScheduler = false;
IsR9Reserved = ReserveR9;
UseMovt = false;
SupportsTailCall = false;
HasFP16 = false;
HasD16 = false;
HasHardwareDivide = false;
HasHardwareDivideInARM = false;
HasT2ExtractPack = false;
HasDataBarrier = false;
Pref32BitThumb = false;
AvoidCPSRPartialUpdate = false;
AvoidMOVsShifterOperand = false;
HasRAS = false;
HasMPExtension = false;
FPOnlySP = false;
HasPerfMon = false;
HasTrustZone = false;
AllowsUnalignedMem = false;
Thumb2DSP = false;
UseNaClTrap = false;
UnsafeFPMath = false;
}
void ARMSubtarget::resetSubtargetFeatures(const MachineFunction *MF) {
AttributeSet FnAttrs = MF->getFunction()->getAttributes();
Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
"target-cpu");
Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
"target-features");
std::string CPU =
!CPUAttr.hasAttribute(Attribute::None) ?CPUAttr.getValueAsString() : "";
std::string FS =
!FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : "";
if (!FS.empty()) {
initializeEnvironment();
resetSubtargetFeatures(CPU, FS);
}
}
void ARMSubtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) {
if (CPUString.empty())
CPUString = "generic";
// Insert the architecture feature derived from the target triple into the
// feature string. This is important for setting features that are implied
// based on the architecture version.
std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),
CPUString);
if (!FS.empty()) {
if (!ArchFS.empty())
ArchFS = ArchFS + "," + FS.str();
else
ArchFS = FS;
}
ParseSubtargetFeatures(CPUString, ArchFS);
// Thumb2 implies at least V6T2. FIXME: Fix tests to explicitly specify a
// ARM version or CPU and then remove this.
if (!HasV6T2Ops && hasThumb2())
HasV4TOps = HasV5TOps = HasV5TEOps = HasV6Ops = HasV6T2Ops = true;
// Keep a pointer to static instruction cost data for the specified CPU.
SchedModel = getSchedModelForCPU(CPUString);
// Initialize scheduling itinerary for the specified CPU.
InstrItins = getInstrItineraryForCPU(CPUString);
if ((TargetTriple.getTriple().find("eabi") != std::string::npos) ||
(isTargetIOS() && isMClass()))
// FIXME: We might want to separate AAPCS and EABI. Some systems, e.g.
// Darwin-EABI conforms to AACPS but not the rest of EABI.
TargetABI = ARM_ABI_AAPCS;
if (isAAPCS_ABI())
stackAlignment = 8;
if (!isTargetIOS())
UseMovt = hasV6T2Ops();
else {
IsR9Reserved = ReserveR9 | !HasV6Ops;
UseMovt = DarwinUseMOVT && hasV6T2Ops();
SupportsTailCall = !getTargetTriple().isOSVersionLT(5, 0);
}
if (!isThumb() || hasThumb2())
PostRAScheduler = true;
switch (Align) {
case DefaultAlign:
// Assume pre-ARMv6 doesn't support unaligned accesses.
//
// ARMv6 may or may not support unaligned accesses depending on the
// SCTLR.U bit, which is architecture-specific. We assume ARMv6
// Darwin targets support unaligned accesses, and others don't.
//
// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
// which raises an alignment fault on unaligned accesses. Linux
// defaults this bit to 0 and handles it as a system-wide (not
// per-process) setting. It is therefore safe to assume that ARMv7+
// Linux targets support unaligned accesses. The same goes for NaCl.
//
// The above behavior is consistent with GCC.
AllowsUnalignedMem = (
(hasV7Ops() && (isTargetLinux() || isTargetNaCl())) ||
(hasV6Ops() && isTargetDarwin()));
break;
case StrictAlign:
AllowsUnalignedMem = false;
break;
case NoStrictAlign:
AllowsUnalignedMem = true;
break;
}
// NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.
uint64_t Bits = getFeatureBits();
if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && // Where this matters
(Options.UnsafeFPMath || isTargetDarwin()))
UseNEONForSinglePrecisionFP = true;
}
/// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.
bool
ARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,
Reloc::Model RelocM) const {
if (RelocM == Reloc::Static)
return false;
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
if (!isTargetDarwin()) {
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return false;
return true;
} else {
if (RelocM == Reloc::PIC_) {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage())
// Hidden $non_lazy_ptr reference.
return true;
return false;
} else {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
}
}
return false;
}
unsigned ARMSubtarget::getMispredictionPenalty() const {
return SchedModel->MispredictPenalty;
}
bool ARMSubtarget::enablePostRAScheduler(
CodeGenOpt::Level OptLevel,
TargetSubtargetInfo::AntiDepBreakMode& Mode,
RegClassVector& CriticalPathRCs) const {
Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL;
CriticalPathRCs.clear();
CriticalPathRCs.push_back(&ARM::GPRRegClass);
return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
}
|
//===-- ARMSubtarget.cpp - ARM Subtarget Information ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ARM specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#include "ARMSubtarget.h"
#include "ARMBaseInstrInfo.h"
#include "ARMBaseRegisterInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetOptions.h"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "ARMGenSubtargetInfo.inc"
using namespace llvm;
static cl::opt<bool>
ReserveR9("arm-reserve-r9", cl::Hidden,
cl::desc("Reserve R9, making it unavailable as GPR"));
static cl::opt<bool>
DarwinUseMOVT("arm-darwin-use-movt", cl::init(true), cl::Hidden);
static cl::opt<bool>
UseFusedMulOps("arm-use-mulops",
cl::init(true), cl::Hidden);
enum AlignMode {
DefaultAlign,
StrictAlign,
NoStrictAlign
};
static cl::opt<AlignMode>
Align(cl::desc("Load/store alignment support"),
cl::Hidden, cl::init(DefaultAlign),
cl::values(
clEnumValN(DefaultAlign, "arm-default-align",
"Generate unaligned accesses only on hardware/OS "
"combinations that are known to support them"),
clEnumValN(StrictAlign, "arm-strict-align",
"Disallow all unaligned memory accesses"),
clEnumValN(NoStrictAlign, "arm-no-strict-align",
"Allow unaligned memory accesses"),
clEnumValEnd));
ARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, const TargetOptions &Options)
: ARMGenSubtargetInfo(TT, CPU, FS)
, ARMProcFamily(Others)
, stackAlignment(4)
, CPUString(CPU)
, TargetTriple(TT)
, Options(Options)
, TargetABI(ARM_ABI_APCS) {
initializeEnvironment();
resetSubtargetFeatures(CPU, FS);
}
void ARMSubtarget::initializeEnvironment() {
HasV4TOps = false;
HasV5TOps = false;
HasV5TEOps = false;
HasV6Ops = false;
HasV6T2Ops = false;
HasV7Ops = false;
HasV8Ops = false;
HasVFPv2 = false;
HasVFPv3 = false;
HasVFPv4 = false;
HasV8FP = false;
HasNEON = false;
UseNEONForSinglePrecisionFP = false;
UseMulOps = UseFusedMulOps;
SlowFPVMLx = false;
HasVMLxForwarding = false;
SlowFPBrcc = false;
InThumbMode = false;
HasThumb2 = false;
IsMClass = false;
NoARM = false;
PostRAScheduler = false;
IsR9Reserved = ReserveR9;
UseMovt = false;
SupportsTailCall = false;
HasFP16 = false;
HasD16 = false;
HasHardwareDivide = false;
HasHardwareDivideInARM = false;
HasT2ExtractPack = false;
HasDataBarrier = false;
Pref32BitThumb = false;
AvoidCPSRPartialUpdate = false;
AvoidMOVsShifterOperand = false;
HasRAS = false;
HasMPExtension = false;
FPOnlySP = false;
HasPerfMon = false;
HasTrustZone = false;
AllowsUnalignedMem = false;
Thumb2DSP = false;
UseNaClTrap = false;
UnsafeFPMath = false;
}
void ARMSubtarget::resetSubtargetFeatures(const MachineFunction *MF) {
AttributeSet FnAttrs = MF->getFunction()->getAttributes();
Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
"target-cpu");
Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
"target-features");
std::string CPU =
!CPUAttr.hasAttribute(Attribute::None) ?CPUAttr.getValueAsString() : "";
std::string FS =
!FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : "";
if (!FS.empty()) {
initializeEnvironment();
resetSubtargetFeatures(CPU, FS);
}
}
void ARMSubtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) {
if (CPUString.empty())
CPUString = "generic";
// Insert the architecture feature derived from the target triple into the
// feature string. This is important for setting features that are implied
// based on the architecture version.
std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),
CPUString);
if (!FS.empty()) {
if (!ArchFS.empty())
ArchFS = ArchFS + "," + FS.str();
else
ArchFS = FS;
}
ParseSubtargetFeatures(CPUString, ArchFS);
// Thumb2 implies at least V6T2. FIXME: Fix tests to explicitly specify a
// ARM version or CPU and then remove this.
if (!HasV6T2Ops && hasThumb2())
HasV4TOps = HasV5TOps = HasV5TEOps = HasV6Ops = HasV6T2Ops = true;
// Keep a pointer to static instruction cost data for the specified CPU.
SchedModel = getSchedModelForCPU(CPUString);
// Initialize scheduling itinerary for the specified CPU.
InstrItins = getInstrItineraryForCPU(CPUString);
if ((TargetTriple.getTriple().find("eabi") != std::string::npos) ||
(isTargetIOS() && isMClass()))
// FIXME: We might want to separate AAPCS and EABI. Some systems, e.g.
// Darwin-EABI conforms to AACPS but not the rest of EABI.
TargetABI = ARM_ABI_AAPCS;
if (isAAPCS_ABI())
stackAlignment = 8;
if (!isTargetIOS()) {
UseMovt = hasV6T2Ops();
IsR9Reserved = ReserveR9;
} else {
IsR9Reserved = ReserveR9 | !HasV6Ops;
UseMovt = DarwinUseMOVT && hasV6T2Ops();
SupportsTailCall = !getTargetTriple().isOSVersionLT(5, 0);
}
if (!isThumb() || hasThumb2())
PostRAScheduler = true;
switch (Align) {
case DefaultAlign:
// Assume pre-ARMv6 doesn't support unaligned accesses.
//
// ARMv6 may or may not support unaligned accesses depending on the
// SCTLR.U bit, which is architecture-specific. We assume ARMv6
// Darwin targets support unaligned accesses, and others don't.
//
// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
// which raises an alignment fault on unaligned accesses. Linux
// defaults this bit to 0 and handles it as a system-wide (not
// per-process) setting. It is therefore safe to assume that ARMv7+
// Linux targets support unaligned accesses. The same goes for NaCl.
//
// The above behavior is consistent with GCC.
AllowsUnalignedMem = (
(hasV7Ops() && (isTargetLinux() || isTargetNaCl())) ||
(hasV6Ops() && isTargetDarwin()));
break;
case StrictAlign:
AllowsUnalignedMem = false;
break;
case NoStrictAlign:
AllowsUnalignedMem = true;
break;
}
// NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.
uint64_t Bits = getFeatureBits();
if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && // Where this matters
(Options.UnsafeFPMath || isTargetDarwin()))
UseNEONForSinglePrecisionFP = true;
}
/// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.
bool
ARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,
Reloc::Model RelocM) const {
if (RelocM == Reloc::Static)
return false;
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
if (!isTargetDarwin()) {
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return false;
return true;
} else {
if (RelocM == Reloc::PIC_) {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage())
// Hidden $non_lazy_ptr reference.
return true;
return false;
} else {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
}
}
return false;
}
unsigned ARMSubtarget::getMispredictionPenalty() const {
return SchedModel->MispredictPenalty;
}
bool ARMSubtarget::enablePostRAScheduler(
CodeGenOpt::Level OptLevel,
TargetSubtargetInfo::AntiDepBreakMode& Mode,
RegClassVector& CriticalPathRCs) const {
Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL;
CriticalPathRCs.clear();
CriticalPathRCs.push_back(&ARM::GPRRegClass);
return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
}
|
make arm-reserve-r9 available for all ARM
|
make arm-reserve-r9 available for all ARM
r9 is defined as a platform-specific register in the ARM EABI.
It can be reserved for a special purpose or be used as a general
purpose register. Add support for reserving r9 for all ARM, while
leaving the IOS usage unchanged.
Patch by Jeroen Hofstee.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@188485 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap
|
5b0040b212d8a5a4951938466d7cfd5eeed2e380
|
src/core/ATDev.cpp
|
src/core/ATDev.cpp
|
#include "ATDev.h"
ATDev::ATDev()
{
m_hwSerial = NULL;
memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE + 1);
memset(m_cmdBuffer, 0x00, ATDEV_BUFF_CMD_SIZE + 1);
memset(m_msgBuffer, 0x00, ATDEV_BUFF_MSG_SIZE + 1);
m_readPtr ^= m_readPtr;
m_timeOut ^= m_timeOut;
m_onModulePin ^= m_onModulePin;
}
uint8_t ATDev::sendATCmd(bool abruptEnd, char* readBuf, uint16_t readBufSize)
{
uint16_t isTimeOut;
uint8_t endSize;
// UART initialize?
if (m_hwSerial == NULL) {
return ATDEV_ERR_INITIALIZE;
}
////
// init buffers
// Set default buffer for internal handling
if (readBuf == NULL) {
readBuf = m_msgBuffer;
}
// init read Buffer
memset(readBuf, 0x00, readBufSize);
// init Counter
m_readPtr ^= m_readPtr;
// is it the default AT end or had his own end?
// set default end of AT communication
if (!abruptEnd) {
memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE);
strncpy_P(m_endBuffer, ATDEV_END_OK, ATDEV_BUFF_END_SIZE);
}
endSize = strlen(m_endBuffer);
////
// Send AT command
if (m_cmdBuffer[0] != 0x00) {
// Clear input Serial buffer
while (m_hwSerial->read() >= 0);
// send command
m_hwSerial->println(m_cmdBuffer);
// clean comand buffer for next use
memset(m_cmdBuffer, 0x00, ATDEV_BUFF_CMD_SIZE);
////
// wait until all data are send
m_hwSerial->flush();
}
////
// Calc Timeout
isTimeOut = millis();
// If millis() overloaded
if (isTimeOut + m_timeOut < isTimeOut) {
isTimeOut = m_timeOut - (0xFFFF - isTimeOut);
}
else {
isTimeOut += m_timeOut;
}
// reset timeout for next function
m_timeOut = ATDEV_DEFAULT_TIMEOUT;
////
// process answer
do {
// if data in serial input buffer
while (m_hwSerial->available()) {
// buffer is full
if (m_readPtr >= readBufSize) {
return ATDEV_ERR_BUFFER_FULL;
}
// read into buffer
readBuf[m_readPtr++] = m_hwSerial->read();
// if abrupt end of communication is set
if (abruptEnd && m_readPtr >= endSize &&
strstr(&readBuf[m_readPtr - endSize], m_endBuffer) != 0) {
return ATDEV_OK;
}
}
////
// check is it the end of AT Command in answer buffer
if (m_readPtr >= endSize && strstr(readBuf, m_endBuffer) != 0) {
return ATDEV_OK;
}
// Error
else if (m_readPtr >= ATDEV_END_ERROR_SIZE &&
strstr_P(readBuf, ATDEV_END_ERROR) != 0) {
return ATDEV_ERR_ERROR_RECEIVED;
}
} while (isTimeOut > millis()); // timeout
return ATDEV_ERR_TIMEOUT;
}
uint8_t ATDev::parseInternalData()
{
bool isString = false;
uint8_t params = 0;
// search hole string
for (uint16_t i = 0; i < ATDEV_BUFF_MSG_SIZE; i++) {
// end
if (m_msgBuffer[i] == 0x00) {
return params;
}
// is string "xy zyx"
else if (m_msgBuffer[i] == ATDEV_CH_IC) {
m_msgBuffer[i] = 0x00;
isString = !isString;
}
// ' ' or ',' or ':' replace with '\0'
else if (!isString && (m_msgBuffer[i] == ATDEV_CH_SP ||
m_msgBuffer[i] == ATDEV_CH_CO ||
m_msgBuffer[i] == ATDEV_CH_DD)) {
m_msgBuffer[i] = 0x00;
}
// count
if (m_msgBuffer[i] == 0x00 && m_msgBuffer[i-1] != 0x00) {
params++;
}
}
return params;
}
char* ATDev::getParseElement(uint8_t indx)
{
uint8_t count = 0;
// search hole string
for (uint16_t i = 0; i < ATDEV_BUFF_MSG_SIZE; i++) {
// find next position
if (m_msgBuffer[i] == 0x00 && i > 0 && m_msgBuffer[i-1] != 0x00) {
count++;
}
// found indx with next character
if (count == indx && m_msgBuffer[i] != 0x00) {
return &m_msgBuffer[i];
}
}
return NULL;
}
uint8_t ATDev::waitDevice(uint8_t ret)
{
if (ret == ATDEV_OK) {
delay(ATDEV_WAIT);
}
return ret;
}
void ATDev::initialize(HardwareSerial *UART, long baudrate, uint8_t onPinMod)
{
m_hwSerial = UART;
m_onModulePin = onPinMod;
// init serial interface
pinMode(m_onModulePin, OUTPUT);
m_hwSerial->begin(baudrate);
}
uint8_t ATDev::onPower()
{
// First AT CMD timeout
m_timeOut = ATDEV_FIRST_ATCMD_TIMEOUT;
// Wait for starting up modul
delay(m_timeOut);
if (this->isReady() != ATDEV_OK) {
digitalWrite(m_onModulePin, HIGH);
delay(3000);
digitalWrite(m_onModulePin, LOW);
delay(1000);
// check is modem response
for (uint8_t i = 0; i < ATDEV_POWER_RETRY; i++) {
if (this->isReady() == ATDEV_OK) {
return this->waitDevice(ATDEV_OK);
}
}
}
// power is allready on
else {
return ATDEV_OK;
}
// timeout
return ATDEV_ERR_TIMEOUT;
}
uint8_t ATDev::isReady()
{
strncpy_P(m_cmdBuffer, ATDEV_CMD_AT, ATDEV_BUFF_CMD_SIZE);
return this->sendATCmd();
}
uint8_t ATDev::setSIMPin(uint16_t pin)
{
snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CPIN, pin);
return this->waitDevice(this->sendATCmd());
}
uint8_t ATDev::getNetworkStatus()
{
strncpy_P(m_cmdBuffer, ATDEV_CMD_CREG, ATDEV_BUFF_CMD_SIZE);
if (this->sendATCmd() == ATDEV_OK) {
// parse answer
this->parseInternalData();
return atoi(this->getParseElement(2));
}
return ATDEV_NETSTAT_UNKNOWN;
}
bool ATDev::isCMSError()
{
// found "+CMS ERROR: %d"
if (strstr_P(m_msgBuffer, ATDEV_END_CMS) != NULL) {
return true;
}
return false;
}
// vim: set sts=4 sw=4 ts=4 et:
|
#include "ATDev.h"
ATDev::ATDev()
{
m_hwSerial = NULL;
memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE + 1);
memset(m_cmdBuffer, 0x00, ATDEV_BUFF_CMD_SIZE + 1);
memset(m_msgBuffer, 0x00, ATDEV_BUFF_MSG_SIZE + 1);
m_readPtr ^= m_readPtr;
m_timeOut ^= m_timeOut;
m_onModulePin ^= m_onModulePin;
}
uint8_t ATDev::sendATCmd(bool abruptEnd, char* readBuf, uint16_t readBufSize)
{
uint32_t isTimeOut;
uint32_t startTime;
uint8_t endSize;
bool over;
// UART initialize?
if (m_hwSerial == NULL) {
return ATDEV_ERR_INITIALIZE;
}
////
// init buffers
// Set default buffer for internal handling
if (readBuf == NULL) {
readBuf = m_msgBuffer;
}
// init read Buffer
memset(readBuf, 0x00, readBufSize);
// init Counter
m_readPtr ^= m_readPtr;
// is it the default AT end or had his own end?
// set default end of AT communication
if (!abruptEnd) {
memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE);
strncpy_P(m_endBuffer, ATDEV_END_OK, ATDEV_BUFF_END_SIZE);
}
endSize = strlen(m_endBuffer);
////
// Send AT command
if (m_cmdBuffer[0] != 0x00) {
// Clear input Serial buffer
while (m_hwSerial->read() >= 0);
// send command
m_hwSerial->println(m_cmdBuffer);
// clean comand buffer for next use
memset(m_cmdBuffer, 0x00, ATDEV_BUFF_CMD_SIZE);
////
// wait until all data are send
m_hwSerial->flush();
}
////
// Calc Timeout
startTime = millis();
isTimeOut = startTime + m_timeOut;
// overloaded
if (isTimeOut < startTime) {
over = true;
}
else {
over = false;
}
// reset timeout for next function
m_timeOut = ATDEV_DEFAULT_TIMEOUT;
////
// process answer
do {
// if data in serial input buffer
while (m_hwSerial->available()) {
// buffer is full
if (m_readPtr >= readBufSize) {
return ATDEV_ERR_BUFFER_FULL;
}
// read into buffer
readBuf[m_readPtr++] = m_hwSerial->read();
// if abrupt end of communication is set
if (abruptEnd && m_readPtr >= endSize &&
strstr(&readBuf[m_readPtr - endSize], m_endBuffer) != 0) {
return ATDEV_OK;
}
}
////
// check is it the end of AT Command in answer buffer
if (m_readPtr >= endSize && strstr(readBuf, m_endBuffer) != 0) {
return ATDEV_OK;
}
// Error
else if (m_readPtr >= ATDEV_END_ERROR_SIZE &&
strstr_P(readBuf, ATDEV_END_ERROR) != 0) {
return ATDEV_ERR_ERROR_RECEIVED;
}
// calc diff timeout
if (over) {
if (startTime > millis()) {
over = false;
}
}
} while ((isTimeOut > millis() && !over) || over); // timeout
return ATDEV_ERR_TIMEOUT;
}
uint8_t ATDev::parseInternalData()
{
bool isString = false;
uint8_t params = 0;
// search hole string
for (uint16_t i = 0; i < ATDEV_BUFF_MSG_SIZE; i++) {
// end
if (m_msgBuffer[i] == 0x00) {
return params;
}
// is string "xy zyx"
else if (m_msgBuffer[i] == ATDEV_CH_IC) {
m_msgBuffer[i] = 0x00;
isString = !isString;
}
// ' ' or ',' or ':' replace with '\0'
else if (!isString && (m_msgBuffer[i] == ATDEV_CH_SP ||
m_msgBuffer[i] == ATDEV_CH_CO ||
m_msgBuffer[i] == ATDEV_CH_DD)) {
m_msgBuffer[i] = 0x00;
}
// count
if (m_msgBuffer[i] == 0x00 && m_msgBuffer[i-1] != 0x00) {
params++;
}
}
return params;
}
char* ATDev::getParseElement(uint8_t indx)
{
uint8_t count = 0;
// search hole string
for (uint16_t i = 0; i < ATDEV_BUFF_MSG_SIZE; i++) {
// find next position
if (m_msgBuffer[i] == 0x00 && i > 0 && m_msgBuffer[i-1] != 0x00) {
count++;
}
// found indx with next character
if (count == indx && m_msgBuffer[i] != 0x00) {
return &m_msgBuffer[i];
}
}
return NULL;
}
uint8_t ATDev::waitDevice(uint8_t ret)
{
if (ret == ATDEV_OK) {
delay(ATDEV_WAIT);
}
return ret;
}
void ATDev::initialize(HardwareSerial *UART, long baudrate, uint8_t onPinMod)
{
m_hwSerial = UART;
m_onModulePin = onPinMod;
// init serial interface
pinMode(m_onModulePin, OUTPUT);
m_hwSerial->begin(baudrate);
}
uint8_t ATDev::onPower()
{
// First AT CMD timeout
m_timeOut = ATDEV_FIRST_ATCMD_TIMEOUT;
// Wait for starting up modul
delay(m_timeOut);
if (this->isReady() != ATDEV_OK) {
digitalWrite(m_onModulePin, HIGH);
delay(3000);
digitalWrite(m_onModulePin, LOW);
delay(1000);
// check is modem response
for (uint8_t i = 0; i < ATDEV_POWER_RETRY; i++) {
if (this->isReady() == ATDEV_OK) {
return this->waitDevice(ATDEV_OK);
}
}
}
// power is allready on
else {
return ATDEV_OK;
}
// timeout
return ATDEV_ERR_TIMEOUT;
}
uint8_t ATDev::isReady()
{
strncpy_P(m_cmdBuffer, ATDEV_CMD_AT, ATDEV_BUFF_CMD_SIZE);
return this->sendATCmd();
}
uint8_t ATDev::setSIMPin(uint16_t pin)
{
snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CPIN, pin);
return this->waitDevice(this->sendATCmd());
}
uint8_t ATDev::getNetworkStatus()
{
strncpy_P(m_cmdBuffer, ATDEV_CMD_CREG, ATDEV_BUFF_CMD_SIZE);
if (this->sendATCmd() == ATDEV_OK) {
// parse answer
this->parseInternalData();
return atoi(this->getParseElement(2));
}
return ATDEV_NETSTAT_UNKNOWN;
}
bool ATDev::isCMSError()
{
// found "+CMS ERROR: %d"
if (strstr_P(m_msgBuffer, ATDEV_END_CMS) != NULL) {
return true;
}
return false;
}
// vim: set sts=4 sw=4 ts=4 et:
|
Fix timeout overloaded trouble
|
Fix timeout overloaded trouble
|
C++
|
bsd-3-clause
|
pvizeli/ATDev,pvizeli/ATDev
|
44ca834f0a9eb5d0dd0e5bd760ce7987e10c0e65
|
modules/solid_mechanics/src/actions/PlenumPressureAction.C
|
modules/solid_mechanics/src/actions/PlenumPressureAction.C
|
#include "PlenumPressureAction.h"
#include "Factory.h"
#include "FEProblem.h"
#include "Parser.h"
template<>
InputParameters validParams<PlenumPressureAction>()
{
InputParameters params = validParams<Action>();
params.addRequiredParam<std::vector<BoundaryName> >("boundary", "The list of boundary IDs from the mesh where the pressure will be applied");
params.addRequiredParam<NonlinearVariableName>("disp_x", "The x displacement");
params.addRequiredParam<NonlinearVariableName>("disp_y", "The y displacement");
params.addParam<NonlinearVariableName>("disp_z", "", "The z displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_x", "The save_in variables for x displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_y", "The save_in variables for y displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_z", "The save_in variables for z displacement");
params.addParam<Real>("initial_pressure", 0, "The initial pressure in the plenum. If not given, a zero initial pressure will be used.");
params.addParam<std::string>("material_input", "", "The name of the postprocessor value that holds the amount of material injected into the plenum.");
params.addRequiredParam<Real>("R", "The universal gas constant for the units used.");
params.addRequiredParam<std::string>("temperature", "The name of the average temperature postprocessor value.");
params.addRequiredParam<std::string>("volume", "The name of the internal volume postprocessor value.");
params.addParam<Real>("startup_time", 0, "The amount of time during which the pressure will ramp from zero to its true value.");
params.addParam<std::string>("output_initial_moles", "", "The reporting postprocessor to use for the initial moles of gas.");
params.addParam<std::string>("output", "", "The reporting postprocessor to use for the plenum pressure value.");
params.addParam<Real>("refab_time", -1, "The time at which the plenum pressure must be reinitialized due to fuel rod refabrication.");
params.addParam<Real>("refab_pressure", -1, "The pressure of fill gas at refabrication.");
params.addParam<Real>("refab_temperature", -1, "The temperature at refabrication.");
params.addParam<Real>("refab_volume", -1, "The gas volume at refabrication.");
return params;
}
PlenumPressureAction::PlenumPressureAction(const std::string & name, InputParameters params) :
Action(name, params),
_boundary(getParam<std::vector<BoundaryName> >("boundary")),
_disp_x(getParam<NonlinearVariableName>("disp_x")),
_disp_y(getParam<NonlinearVariableName>("disp_y")),
_disp_z(getParam<NonlinearVariableName>("disp_z")),
_initial_pressure(getParam<Real>("initial_pressure")),
_material_input(getParam<std::string>("material_input")),
_R(getParam<Real>("R")),
_temperature(getParam<std::string>("temperature")),
_volume(getParam<std::string>("volume")),
_startup_time(getParam<Real>("startup_time")),
_output_initial_moles(getParam<std::string>("output_initial_moles")),
_output(getParam<std::string>("output")),
_refab_time(getParam<Real>("refab_time")),
_refab_pressure(getParam<Real>("refab_pressure")),
_refab_temperature(getParam<Real>("refab_temperature")),
_refab_volume(getParam<Real>("refab_volume")),
_kernel_name("PlenumPressure"),
_use_displaced_mesh(true)
{
if (params.isParamValid("refab_time") &&
!(params.isParamValid("refab_pressure") &&
params.isParamValid("refab_temperature") &&
params.isParamValid("refab_volume")))
{
mooseError("PlenumPressure error: refabrication time given but not complete set of refabrication data");
}
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_x"));
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_y"));
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_z"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_x"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_y"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_z"));
}
void
PlenumPressureAction::act()
{
// Determine number of dimensions
unsigned int dim(2);
if (_disp_z != "")
{
++dim;
}
std::vector<NonlinearVariableName> vars;
vars.push_back(_disp_x);
vars.push_back(_disp_y);
vars.push_back(_disp_z);
std::string short_name(_name);
// Chop off "BCs/PlenumPressure/"
short_name.erase(0, 4+_kernel_name.size());
for (unsigned int i(0); i < dim; ++i)
{
std::stringstream name;
name << "BCs/";
name << short_name;
name << "_";
name << i;
InputParameters params = Factory::instance()->getValidParams(_kernel_name);
params.set<std::vector<BoundaryName> >("boundary") = _boundary;
params.set<Real>("initial_pressure") = _initial_pressure;
params.set<std::string>("material_input") = _material_input;
params.set<Real>("R") = _R;
params.set<std::string>("temperature") = _temperature;
params.set<std::string>("volume") = _volume;
params.set<Real>("startup_time") = _startup_time;
params.set<std::string>("output_initial_moles") = _output_initial_moles;
params.set<std::string>("output") = _output;
params.set<Real>("refab_time") = _refab_time;
params.set<Real>("refab_pressure") = _refab_pressure;
params.set<Real>("refab_temperature") = _refab_temperature;
params.set<Real>("refab_volume") = _refab_volume;
params.set<bool>("use_displaced_mesh") = _use_displaced_mesh;
params.set<int>("component") = i;
params.set<NonlinearVariableName>("variable") = vars[i];
if (_has_save_in_vars[i])
{
std::vector<std::string> siv;
for (unsigned int j(0); j<_save_in_vars[i].size(); ++j)
{
std::string svar=_save_in_vars[i][j];
siv.push_back(svar);
}
params.set<std::vector<std::string> >("save_in") = siv;
//TODO: Why doesn't IntegratedBC accept a vec of AuxVariableNames:
// params.set<std::vector<AuxVariableName> >("save_in") = _save_in_vars[i];
}
_problem->addBoundaryCondition(_kernel_name, name.str(), params);
}
}
|
#include "PlenumPressureAction.h"
#include "Factory.h"
#include "FEProblem.h"
#include "Parser.h"
template<>
InputParameters validParams<PlenumPressureAction>()
{
InputParameters params = validParams<Action>();
params.addRequiredParam<std::vector<BoundaryName> >("boundary", "The list of boundary IDs from the mesh where the pressure will be applied");
params.addRequiredParam<NonlinearVariableName>("disp_x", "The x displacement");
params.addRequiredParam<NonlinearVariableName>("disp_y", "The y displacement");
params.addParam<NonlinearVariableName>("disp_z", "", "The z displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_x", "The save_in variables for x displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_y", "The save_in variables for y displacement");
params.addParam<std::vector<AuxVariableName> >("save_in_disp_z", "The save_in variables for z displacement");
params.addParam<Real>("initial_pressure", 0, "The initial pressure in the plenum. If not given, a zero initial pressure will be used.");
params.addParam<std::string>("material_input", "", "The name of the postprocessor value that holds the amount of material injected into the plenum.");
params.addRequiredParam<Real>("R", "The universal gas constant for the units used.");
params.addRequiredParam<std::string>("temperature", "The name of the average temperature postprocessor value.");
params.addRequiredParam<std::string>("volume", "The name of the internal volume postprocessor value.");
params.addParam<Real>("startup_time", 0, "The amount of time during which the pressure will ramp from zero to its true value.");
params.addParam<std::string>("output_initial_moles", "", "The reporting postprocessor to use for the initial moles of gas.");
params.addParam<std::string>("output", "", "The reporting postprocessor to use for the plenum pressure value.");
params.addParam<Real>("refab_time", -1, "The time at which the plenum pressure must be reinitialized due to fuel rod refabrication.");
params.addParam<Real>("refab_pressure", -1, "The pressure of fill gas at refabrication.");
params.addParam<Real>("refab_temperature", -1, "The temperature at refabrication.");
params.addParam<Real>("refab_volume", -1, "The gas volume at refabrication.");
return params;
}
PlenumPressureAction::PlenumPressureAction(const std::string & name, InputParameters params) :
Action(name, params),
_boundary(getParam<std::vector<BoundaryName> >("boundary")),
_disp_x(getParam<NonlinearVariableName>("disp_x")),
_disp_y(getParam<NonlinearVariableName>("disp_y")),
_disp_z(getParam<NonlinearVariableName>("disp_z")),
_initial_pressure(getParam<Real>("initial_pressure")),
_material_input(getParam<std::string>("material_input")),
_R(getParam<Real>("R")),
_temperature(getParam<std::string>("temperature")),
_volume(getParam<std::string>("volume")),
_startup_time(getParam<Real>("startup_time")),
_output_initial_moles(getParam<std::string>("output_initial_moles")),
_output(getParam<std::string>("output")),
_refab_time(getParam<Real>("refab_time")),
_refab_pressure(getParam<Real>("refab_pressure")),
_refab_temperature(getParam<Real>("refab_temperature")),
_refab_volume(getParam<Real>("refab_volume")),
_kernel_name("PlenumPressure"),
_use_displaced_mesh(true)
{
if (params.isParamValid("refab_time") &&
!(params.isParamValid("refab_pressure") &&
params.isParamValid("refab_temperature") &&
params.isParamValid("refab_volume")))
{
mooseError("PlenumPressure error: refabrication time given but not complete set of refabrication data");
}
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_x"));
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_y"));
_save_in_vars.push_back(getParam<std::vector<AuxVariableName> >("save_in_disp_z"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_x"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_y"));
_has_save_in_vars.push_back(params.isParamValid("save_in_disp_z"));
}
void
PlenumPressureAction::act()
{
// Determine number of dimensions
unsigned int dim(2);
if (_disp_z != "")
{
++dim;
}
std::vector<NonlinearVariableName> vars;
vars.push_back(_disp_x);
vars.push_back(_disp_y);
vars.push_back(_disp_z);
std::string short_name(_name);
// Chop off "BCs/PlenumPressure/"
short_name.erase(0, 4+_kernel_name.size());
for (unsigned int i(0); i < dim; ++i)
{
std::stringstream name;
name << "BCs/";
name << short_name;
name << "_";
name << i;
InputParameters params = Factory::instance()->getValidParams(_kernel_name);
params.set<std::vector<BoundaryName> >("boundary") = _boundary;
params.set<Real>("initial_pressure") = _initial_pressure;
params.set<std::string>("material_input") = _material_input;
params.set<Real>("R") = _R;
params.set<std::string>("temperature") = _temperature;
params.set<std::string>("volume") = _volume;
params.set<Real>("startup_time") = _startup_time;
params.set<std::string>("output_initial_moles") = _output_initial_moles;
params.set<std::string>("output") = _output;
params.set<Real>("refab_time") = _refab_time;
params.set<Real>("refab_pressure") = _refab_pressure;
params.set<Real>("refab_temperature") = _refab_temperature;
params.set<Real>("refab_volume") = _refab_volume;
params.set<bool>("use_displaced_mesh") = _use_displaced_mesh;
params.set<int>("component") = i;
params.set<NonlinearVariableName>("variable") = vars[i];
if (_has_save_in_vars[i])
{
params.set<std::vector<AuxVariableName> >("save_in") = _save_in_vars[i];
}
_problem->addBoundaryCondition(_kernel_name, name.str(), params);
}
}
|
Change type of save_in parameter passed from PlenumPressureAux closes #1421
|
Change type of save_in parameter passed from PlenumPressureAux closes #1421
r13868
|
C++
|
lgpl-2.1
|
laagesen/moose,apc-llc/moose,liuwenf/moose,tonkmr/moose,jessecarterMOOSE/moose,idaholab/moose,stimpsonsg/moose,adamLange/moose,laagesen/moose,liuwenf/moose,tonkmr/moose,harterj/moose,zzyfisherman/moose,harterj/moose,backmari/moose,apc-llc/moose,zzyfisherman/moose,adamLange/moose,mellis13/moose,andrsd/moose,sapitts/moose,nuclear-wizard/moose,andrsd/moose,yipenggao/moose,giopastor/moose,joshua-cogliati-inl/moose,bwspenc/moose,sapitts/moose,harterj/moose,WilkAndy/moose,markr622/moose,jinmm1992/moose,adamLange/moose,jiangwen84/moose,tonkmr/moose,YaqiWang/moose,capitalaslash/moose,liuwenf/moose,roystgnr/moose,bwspenc/moose,roystgnr/moose,katyhuff/moose,jinmm1992/moose,katyhuff/moose,tonkmr/moose,cpritam/moose,Chuban/moose,shanestafford/moose,wgapl/moose,cpritam/moose,raghavaggarwal/moose,waxmanr/moose,stimpsonsg/moose,bwspenc/moose,zzyfisherman/moose,tonkmr/moose,mellis13/moose,kasra83/moose,cpritam/moose,capitalaslash/moose,apc-llc/moose,permcody/moose,jbair34/moose,milljm/moose,SudiptaBiswas/moose,jessecarterMOOSE/moose,WilkAndy/moose,jasondhales/moose,andrsd/moose,jinmm1992/moose,raghavaggarwal/moose,nuclear-wizard/moose,dschwen/moose,liuwenf/moose,wgapl/moose,waxmanr/moose,milljm/moose,idaholab/moose,lindsayad/moose,raghavaggarwal/moose,giopastor/moose,shanestafford/moose,liuwenf/moose,SudiptaBiswas/moose,backmari/moose,jasondhales/moose,jasondhales/moose,roystgnr/moose,backmari/moose,jhbradley/moose,YaqiWang/moose,jiangwen84/moose,markr622/moose,Chuban/moose,laagesen/moose,yipenggao/moose,milljm/moose,stimpsonsg/moose,mellis13/moose,jessecarterMOOSE/moose,harterj/moose,apc-llc/moose,jbair34/moose,lindsayad/moose,andrsd/moose,lindsayad/moose,sapitts/moose,nuclear-wizard/moose,friedmud/moose,giopastor/moose,jessecarterMOOSE/moose,joshua-cogliati-inl/moose,idaholab/moose,SudiptaBiswas/moose,waxmanr/moose,friedmud/moose,WilkAndy/moose,yipenggao/moose,zzyfisherman/moose,katyhuff/moose,YaqiWang/moose,jinmm1992/moose,shanestafford/moose,idaholab/moose,sapitts/moose,kasra83/moose,cpritam/moose,wgapl/moose,bwspenc/moose,friedmud/moose,roystgnr/moose,lindsayad/moose,SudiptaBiswas/moose,xy515258/moose,permcody/moose,capitalaslash/moose,friedmud/moose,mellis13/moose,danielru/moose,joshua-cogliati-inl/moose,waxmanr/moose,shanestafford/moose,cpritam/moose,zzyfisherman/moose,shanestafford/moose,permcody/moose,idaholab/moose,roystgnr/moose,danielru/moose,dschwen/moose,jbair34/moose,permcody/moose,yipenggao/moose,YaqiWang/moose,danielru/moose,jessecarterMOOSE/moose,SudiptaBiswas/moose,kasra83/moose,bwspenc/moose,jhbradley/moose,andrsd/moose,WilkAndy/moose,xy515258/moose,WilkAndy/moose,markr622/moose,dschwen/moose,wgapl/moose,zzyfisherman/moose,roystgnr/moose,laagesen/moose,dschwen/moose,dschwen/moose,jasondhales/moose,backmari/moose,raghavaggarwal/moose,stimpsonsg/moose,giopastor/moose,nuclear-wizard/moose,milljm/moose,markr622/moose,jiangwen84/moose,milljm/moose,jhbradley/moose,jiangwen84/moose,Chuban/moose,xy515258/moose,kasra83/moose,danielru/moose,WilkAndy/moose,roystgnr/moose,liuwenf/moose,harterj/moose,laagesen/moose,katyhuff/moose,lindsayad/moose,jbair34/moose,adamLange/moose,xy515258/moose,tonkmr/moose,sapitts/moose,Chuban/moose,capitalaslash/moose,joshua-cogliati-inl/moose,cpritam/moose,jhbradley/moose,shanestafford/moose
|
3378ee1a25c0b3ecdd8f02c639f06e0d980d03b4
|
server/src/work/DeviceUnpairWorkExecutor.cpp
|
server/src/work/DeviceUnpairWorkExecutor.cpp
|
#include <string>
#include <Poco/Event.h>
#include <Poco/Exception.h>
#include <Poco/Net/NetException.h>
#include "dao/DeviceDao.h"
#include "di/Injectable.h"
#include "work/DeviceUnpairWorkExecutor.h"
BEEEON_OBJECT_BEGIN(BeeeOn, DeviceUnpairWorkExecutor)
BEEEON_OBJECT_CASTABLE(WorkExecutor)
BEEEON_OBJECT_REF("deviceDao", &DeviceUnpairWorkExecutor::setDeviceDao)
BEEEON_OBJECT_REF("gatewayRPC", &DeviceUnpairWorkExecutor::setGatewayRPC)
BEEEON_OBJECT_REF("scheduler", &DeviceUnpairWorkExecutor::setScheduler)
BEEEON_OBJECT_REF("lockManager", &DeviceUnpairWorkExecutor::setLockManager)
BEEEON_OBJECT_END(BeeeOn, DeviceUnpairWorkExecutor)
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
DeviceUnpairWorkExecutor::DeviceUnpairWorkExecutor()
{
}
void DeviceUnpairWorkExecutor::setDeviceDao(DeviceDao::Ptr dao)
{
m_dao = dao;
}
void DeviceUnpairWorkExecutor::setGatewayRPC(GatewayRPC::Ptr rpc)
{
m_rpc = rpc;
}
bool DeviceUnpairWorkExecutor::accepts(const Work::Ptr work) const
{
if (work->content().type().is<DeviceUnpairWork>())
return true;
return false;
}
void DeviceUnpairWorkExecutor::processResult(Work::Ptr work, DeviceUnpairWork &content)
{
Gateway gateway(content.gatewayID());
Device device(content.deviceID());
switch (content.result()) {
case GatewayRPCResult::Status::NOT_CONNECTED:
throw ConnectionAbortedException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::TIMEOUT:
throw TimeoutException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::FAILED:
throw RuntimeException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::SUCCESS:
return;
default:
suspend(work);
break;
}
}
void DeviceUnpairWorkExecutor::execute(Work::Ptr work)
{
DeviceUnpairWork content = work->contentAs<DeviceUnpairWork>();
Device device(content.deviceID());
const Gateway gateway(content.gatewayID());
if (!m_dao->fetch(device, gateway)) {
logger().warning("device "
+ device
+ " on gateway "
+ gateway
+ " not found during unpair",
__FILE__, __LINE__);
return; // treat as success
}
if (content.hasResult()) {
processResult(work, content);
return;
}
WorkScheduler::Ptr scheduler = this->scheduler();
WorkLockManager::Ptr lockManager = this->lockManager();
m_rpc->unpairDevice([=](GatewayRPCResult::Ptr result) mutable
{
{
WorkWriteGuard accessGuard(lockManager->readWrite(work->id()));
// update result of the work
DeviceUnpairWork content = work->contentAs<DeviceUnpairWork>();
content.setResult(result->status());
work->setContent(content);
}
switch (result->status()) {
case GatewayRPCResult::Status::PENDING:
case GatewayRPCResult::Status::ACCEPTED:
// TODO persist
return; // no other action is needed
default:
scheduler->wakeup(work);
break;
}
},
gateway,
device
);
suspend(work);
}
|
#include <string>
#include <Poco/Event.h>
#include <Poco/Exception.h>
#include <Poco/Net/NetException.h>
#include "dao/DeviceDao.h"
#include "di/Injectable.h"
#include "work/DeviceUnpairWorkExecutor.h"
BEEEON_OBJECT_BEGIN(BeeeOn, DeviceUnpairWorkExecutor)
BEEEON_OBJECT_CASTABLE(WorkExecutor)
BEEEON_OBJECT_REF("deviceDao", &DeviceUnpairWorkExecutor::setDeviceDao)
BEEEON_OBJECT_REF("gatewayRPC", &DeviceUnpairWorkExecutor::setGatewayRPC)
BEEEON_OBJECT_REF("scheduler", &DeviceUnpairWorkExecutor::setScheduler)
BEEEON_OBJECT_REF("lockManager", &DeviceUnpairWorkExecutor::setLockManager)
BEEEON_OBJECT_END(BeeeOn, DeviceUnpairWorkExecutor)
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
DeviceUnpairWorkExecutor::DeviceUnpairWorkExecutor()
{
}
void DeviceUnpairWorkExecutor::setDeviceDao(DeviceDao::Ptr dao)
{
m_dao = dao;
}
void DeviceUnpairWorkExecutor::setGatewayRPC(GatewayRPC::Ptr rpc)
{
m_rpc = rpc;
}
bool DeviceUnpairWorkExecutor::accepts(const Work::Ptr work) const
{
if (work->content().type().is<DeviceUnpairWork>())
return true;
return false;
}
void DeviceUnpairWorkExecutor::processResult(Work::Ptr work, DeviceUnpairWork &content)
{
Gateway gateway(content.gatewayID());
Device device(content.deviceID());
switch (content.result()) {
case GatewayRPCResult::Status::NOT_CONNECTED:
throw ConnectionAbortedException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::TIMEOUT:
throw TimeoutException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::FAILED:
throw RuntimeException(
"failed to unpair device " + device + " on gateway " + gateway);
case GatewayRPCResult::Status::SUCCESS:
if (!m_dao->fetch(device, gateway)) {
logger().warning("device " + device + " not found while unpairing",
__FILE__, __LINE__);
return;
}
device.setActiveSince(Nullable<DateTime>{});
if (!m_dao->update(device, gateway)) {
logger().warning("failed to update device " + device,
__FILE__, __LINE__);
}
return;
default:
suspend(work);
break;
}
}
void DeviceUnpairWorkExecutor::execute(Work::Ptr work)
{
DeviceUnpairWork content = work->contentAs<DeviceUnpairWork>();
Device device(content.deviceID());
const Gateway gateway(content.gatewayID());
if (!m_dao->fetch(device, gateway)) {
logger().warning("device "
+ device
+ " on gateway "
+ gateway
+ " not found during unpair",
__FILE__, __LINE__);
return; // treat as success
}
if (content.hasResult()) {
processResult(work, content);
return;
}
WorkScheduler::Ptr scheduler = this->scheduler();
WorkLockManager::Ptr lockManager = this->lockManager();
m_rpc->unpairDevice([=](GatewayRPCResult::Ptr result) mutable
{
{
WorkWriteGuard accessGuard(lockManager->readWrite(work->id()));
// update result of the work
DeviceUnpairWork content = work->contentAs<DeviceUnpairWork>();
content.setResult(result->status());
work->setContent(content);
}
switch (result->status()) {
case GatewayRPCResult::Status::PENDING:
case GatewayRPCResult::Status::ACCEPTED:
// TODO persist
return; // no other action is needed
default:
scheduler->wakeup(work);
break;
}
},
gateway,
device
);
suspend(work);
}
|
update device in database after success
|
DeviceUnpairWorkExecutor: update device in database after success
When the device is successfully unpair on the gateway, update the device
record in databse to reflect the unpaired state.
Signed-off-by: Jan Viktorin <[email protected]>
|
C++
|
bsd-3-clause
|
BeeeOn/server,BeeeOn/server,BeeeOn/server,BeeeOn/server
|
bace2e847e05bb98cbbbeb984b54868096878616
|
unotools/inc/unotools/ucblockbytes.hxx
|
unotools/inc/unotools/ucblockbytes.hxx
|
#ifndef _UNTOOLS_UCBLOCKBYTES_HXX
#define _UNTOOLS_UCBLOCKBYTES_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#include <vos/thread.hxx>
#include <vos/conditn.hxx>
#include <vos/mutex.hxx>
#include <tools/stream.hxx>
#include <tools/link.hxx>
#include <tools/errcode.hxx>
class UCB_Link_Helper : public SvRefBase
{
::vos::OMutex maMutex;
Link maDoneLink;
Link maDataAvailLink;
Link maCancelLink;
BOOL mbSet;
~UCB_Link_Helper(){;}
public:
UCB_Link_Helper()
{ mbSet = FALSE;}
void SetDoneLink( const Link& rLink );
void SetDataAvailLink( const Link& rLink );
void SetCancelLink( const Link& rLink );
void Done( ErrCode nError );
void DataAvail();
void Cancel();
void Clear();
};
SV_DECL_IMPL_REF( UCB_Link_Helper )
#define NS_UNO ::com::sun::star::uno
#define NS_IO ::com::sun::star::io
#define NS_UCB ::com::sun::star::ucb
SV_DECL_REF( UcbLockBytes );
class CommandThread_Impl;
class UcbLockBytes : public virtual SvLockBytes
{
vos::OCondition m_aInitialized;
vos::OCondition m_aTerminated;
vos::OMutex m_aMutex;
NS_UNO::Reference < NS_IO::XInputStream > m_xInputStream;
CommandThread_Impl* m_pCommandThread;
sal_Bool m_bTerminated;
sal_Bool m_bDontClose;
sal_uInt32 m_nRead;
sal_uInt32 m_nSize;
ErrCode m_nError;
UCB_Link_HelperRef m_aLinkList;
DECL_LINK( DataAvailHdl, void * );
protected:
virtual ~UcbLockBytes (void);
public:
static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_UCB::XContent > xContent, UCB_Link_HelperRef xLinkList );
static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream > xContent, UCB_Link_HelperRef xLinkList );
UcbLockBytes( UCB_Link_HelperRef xLink )
: m_xInputStream (NULL)
, m_pCommandThread( NULL )
, m_bTerminated (sal_False)
, m_bDontClose( sal_False )
, m_nRead (0)
, m_nSize (0)
, m_aLinkList( xLink )
, m_nError( ERRCODE_NONE )
{}
// SvLockBytes
virtual void SetSynchronMode (BOOL bSynchron);
virtual ErrCode ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const;
virtual ErrCode WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten);
virtual ErrCode Flush (void) const;
virtual ErrCode SetSize (ULONG);
virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const;
void SetError( ErrCode nError )
{ m_nError = nError; }
ErrCode GetError() const
{ return m_nError; }
void Cancel();
#if __PRIVATE
sal_Bool setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream );
void terminate_Impl (void);
NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const
{
vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
return m_xInputStream;
}
sal_Bool hasInputStream_Impl() const
{
vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
return m_xInputStream.is();
}
void setCommandThread_Impl( CommandThread_Impl* pThread )
{ m_pCommandThread = pThread; }
void setDontClose_Impl()
{ m_bDontClose = sal_True; }
#endif
};
//----------------------------------------------------------------------------
SV_IMPL_REF( UcbLockBytes );
#endif
|
#ifndef _UNTOOLS_UCBLOCKBYTES_HXX
#define _UNTOOLS_UCBLOCKBYTES_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#include <vos/thread.hxx>
#include <vos/conditn.hxx>
#include <vos/mutex.hxx>
#include <tools/stream.hxx>
#include <tools/link.hxx>
#include <tools/errcode.hxx>
namespace utl
{
class UCB_Link_Helper : public SvRefBase
{
::vos::OMutex maMutex;
Link maDoneLink;
Link maDataAvailLink;
Link maCancelLink;
BOOL mbSet;
~UCB_Link_Helper(){;}
public:
UCB_Link_Helper()
{ mbSet = FALSE;}
void SetDoneLink( const Link& rLink );
void SetDataAvailLink( const Link& rLink );
void SetCancelLink( const Link& rLink );
void Done( ErrCode nError );
void DataAvail();
void Cancel();
void Clear();
};
SV_DECL_IMPL_REF( UCB_Link_Helper )
#define NS_UNO ::com::sun::star::uno
#define NS_IO ::com::sun::star::io
#define NS_UCB ::com::sun::star::ucb
SV_DECL_REF( UcbLockBytes );
class CommandThread_Impl;
class UcbLockBytes : public virtual SvLockBytes
{
vos::OCondition m_aInitialized;
vos::OCondition m_aTerminated;
vos::OMutex m_aMutex;
NS_UNO::Reference < NS_IO::XInputStream > m_xInputStream;
CommandThread_Impl* m_pCommandThread;
sal_Bool m_bTerminated;
sal_Bool m_bDontClose;
sal_uInt32 m_nRead;
sal_uInt32 m_nSize;
ErrCode m_nError;
UCB_Link_HelperRef m_aLinkList;
DECL_LINK( DataAvailHdl, void * );
protected:
virtual ~UcbLockBytes (void);
public:
static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_UCB::XContent > xContent, UCB_Link_HelperRef xLinkList );
static UcbLockBytesRef CreateInputLockBytes( const NS_UNO::Reference < NS_IO::XInputStream > xContent, UCB_Link_HelperRef xLinkList );
UcbLockBytes( UCB_Link_HelperRef xLink )
: m_xInputStream (NULL)
, m_pCommandThread( NULL )
, m_bTerminated (sal_False)
, m_bDontClose( sal_False )
, m_nRead (0)
, m_nSize (0)
, m_aLinkList( xLink )
, m_nError( ERRCODE_NONE )
{}
// SvLockBytes
virtual void SetSynchronMode (BOOL bSynchron);
virtual ErrCode ReadAt ( ULONG nPos, void *pBuffer, ULONG nCount, ULONG *pRead) const;
virtual ErrCode WriteAt ( ULONG, const void*, ULONG, ULONG *pWritten);
virtual ErrCode Flush (void) const;
virtual ErrCode SetSize (ULONG);
virtual ErrCode Stat ( SvLockBytesStat *pStat, SvLockBytesStatFlag) const;
void SetError( ErrCode nError )
{ m_nError = nError; }
ErrCode GetError() const
{ return m_nError; }
void Cancel();
#if __PRIVATE
sal_Bool setInputStream_Impl( const NS_UNO::Reference < NS_IO::XInputStream > &rxInputStream );
void terminate_Impl (void);
NS_UNO::Reference < NS_IO::XInputStream > getInputStream_Impl() const
{
vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
return m_xInputStream;
}
sal_Bool hasInputStream_Impl() const
{
vos::OGuard aGuard( SAL_CONST_CAST(UcbLockBytes*, this)->m_aMutex );
return m_xInputStream.is();
}
void setCommandThread_Impl( CommandThread_Impl* pThread )
{ m_pCommandThread = pThread; }
void setDontClose_Impl()
{ m_bDontClose = sal_True; }
#endif
};
};
//----------------------------------------------------------------------------
SV_IMPL_REF( UcbLockBytes );
#endif
|
use namespace utl
|
use namespace utl
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
1f104804bf30f1457e92fa6ee958a618a958b1ad
|
lib/Target/X86/X86Subtarget.cpp
|
lib/Target/X86/X86Subtarget.cpp
|
//===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86 specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "subtarget"
#include "X86Subtarget.h"
#include "X86InstrInfo.h"
#include "llvm/GlobalValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/SmallVector.h"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "X86GenSubtargetInfo.inc"
using namespace llvm;
#if defined(_MSC_VER)
#include <intrin.h>
#endif
/// ClassifyBlockAddressReference - Classify a blockaddress reference for the
/// current subtarget according to how we should reference it in a non-pcrel
/// context.
unsigned char X86Subtarget::
ClassifyBlockAddressReference() const {
if (isPICStyleGOT()) // 32-bit ELF targets.
return X86II::MO_GOTOFF;
if (isPICStyleStubPIC()) // Darwin/32 in PIC mode.
return X86II::MO_PIC_BASE_OFFSET;
// Direct static reference to label.
return X86II::MO_NO_FLAG;
}
/// ClassifyGlobalReference - Classify a global variable reference for the
/// current subtarget according to how we should reference it in a non-pcrel
/// context.
unsigned char X86Subtarget::
ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const {
// DLLImport only exists on windows, it is implemented as a load from a
// DLLIMPORT stub.
if (GV->hasDLLImportLinkage())
return X86II::MO_DLLIMPORT;
// Determine whether this is a reference to a definition or a declaration.
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
// X86-64 in PIC mode.
if (isPICStyleRIPRel()) {
// Large model never uses stubs.
if (TM.getCodeModel() == CodeModel::Large)
return X86II::MO_NO_FLAG;
if (isTargetDarwin()) {
// If symbol visibility is hidden, the extra load is not needed if
// target is x86-64 or the symbol is definitely defined in the current
// translation unit.
if (GV->hasDefaultVisibility() &&
(isDecl || GV->isWeakForLinker()))
return X86II::MO_GOTPCREL;
} else if (!isTargetWin64()) {
assert(isTargetELF() && "Unknown rip-relative target");
// Extra load is needed for all externally visible.
if (!GV->hasLocalLinkage() && GV->hasDefaultVisibility())
return X86II::MO_GOTPCREL;
}
return X86II::MO_NO_FLAG;
}
if (isPICStyleGOT()) { // 32-bit ELF targets.
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return X86II::MO_GOTOFF;
return X86II::MO_GOT;
}
if (isPICStyleStubPIC()) { // Darwin/32 in PIC mode.
// Determine whether we have a stub reference and/or whether the reference
// is relative to the PIC base or not.
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return X86II::MO_PIC_BASE_OFFSET;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage()) {
// Hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE;
}
// Otherwise, no stub.
return X86II::MO_PIC_BASE_OFFSET;
}
if (isPICStyleStubNoDynamic()) { // Darwin/32 in -mdynamic-no-pic mode.
// Determine whether we have a stub reference.
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return X86II::MO_NO_FLAG;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_NONLAZY;
// Otherwise, no stub.
return X86II::MO_NO_FLAG;
}
// Direct static reference to global.
return X86II::MO_NO_FLAG;
}
/// getBZeroEntry - This function returns the name of a function which has an
/// interface like the non-standard bzero function, if such a function exists on
/// the current subtarget and it is considered prefereable over memset with zero
/// passed as the second argument. Otherwise it returns null.
const char *X86Subtarget::getBZeroEntry() const {
// Darwin 10 has a __bzero entry point for this purpose.
if (getTargetTriple().isMacOSX() &&
!getTargetTriple().isMacOSXVersionLT(10, 6))
return "__bzero";
return 0;
}
/// IsLegalToCallImmediateAddr - Return true if the subtarget allows calls
/// to immediate address.
bool X86Subtarget::IsLegalToCallImmediateAddr(const TargetMachine &TM) const {
if (In64BitMode)
return false;
return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
}
/// getSpecialAddressLatency - For targets where it is beneficial to
/// backschedule instructions that compute addresses, return a value
/// indicating the number of scheduling cycles of backscheduling that
/// should be attempted.
unsigned X86Subtarget::getSpecialAddressLatency() const {
// For x86 out-of-order targets, back-schedule address computations so
// that loads and stores aren't blocked.
// This value was chosen arbitrarily.
return 200;
}
void X86Subtarget::AutoDetectSubtargetFeatures() {
unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
union {
unsigned u[3];
char c[12];
} text;
if (X86_MC::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1))
return;
X86_MC::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
if ((EDX >> 15) & 1) HasCMov = true; ToggleFeature(X86::FeatureCMOV);
if ((EDX >> 23) & 1) X86SSELevel = MMX; ToggleFeature(X86::FeatureMMX);
if ((EDX >> 25) & 1) X86SSELevel = SSE1; ToggleFeature(X86::FeatureSSE1);
if ((EDX >> 26) & 1) X86SSELevel = SSE2; ToggleFeature(X86::FeatureSSE2);
if (ECX & 0x1) X86SSELevel = SSE3; ToggleFeature(X86::FeatureSSE3);
if ((ECX >> 9) & 1) X86SSELevel = SSSE3; ToggleFeature(X86::FeatureSSSE3);
if ((ECX >> 19) & 1) X86SSELevel = SSE41; ToggleFeature(X86::FeatureSSE41);
if ((ECX >> 20) & 1) X86SSELevel = SSE42; ToggleFeature(X86::FeatureSSE42);
// FIXME: AVX codegen support is not ready.
//if ((ECX >> 28) & 1) { HasAVX = true; } ToggleFeature(X86::FeatureAVX);
bool IsIntel = memcmp(text.c, "GenuineIntel", 12) == 0;
bool IsAMD = !IsIntel && memcmp(text.c, "AuthenticAMD", 12) == 0;
HasCLMUL = IsIntel && ((ECX >> 1) & 0x1); ToggleFeature(X86::FeatureCLMUL);
HasFMA3 = IsIntel && ((ECX >> 12) & 0x1); ToggleFeature(X86::FeatureFMA3);
HasMOVBE = IsIntel && ((ECX >> 22) & 0x1); ToggleFeature(X86::FeatureMOVBE);
HasPOPCNT = IsIntel && ((ECX >> 23) & 0x1); ToggleFeature(X86::FeaturePOPCNT);
HasAES = IsIntel && ((ECX >> 25) & 0x1); ToggleFeature(X86::FeatureAES);
HasF16C = IsIntel && ((ECX >> 29) & 0x1); ToggleFeature(X86::FeatureF16C);
HasRDRAND = IsIntel && ((ECX >> 30) & 0x1); ToggleFeature(X86::FeatureRDRAND);
HasCmpxchg16b = ((ECX >> 13) & 0x1); ToggleFeature(X86::FeatureCMPXCHG16B);
if (IsIntel || IsAMD) {
// Determine if bit test memory instructions are slow.
unsigned Family = 0;
unsigned Model = 0;
X86_MC::DetectFamilyModel(EAX, Family, Model);
if (IsAMD || (Family == 6 && Model >= 13)) {
IsBTMemSlow = true;
ToggleFeature(X86::FeatureSlowBTMem);
}
// If it's Nehalem, unaligned memory access is fast.
if (Family == 15 && Model == 26) {
IsUAMemFast = true;
ToggleFeature(X86::FeatureFastUAMem);
}
X86_MC::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
if ((EDX >> 29) & 0x1) {
HasX86_64 = true;
ToggleFeature(X86::Feature64Bit);
}
if (IsAMD && ((ECX >> 6) & 0x1)) {
HasSSE4A = true;
ToggleFeature(X86::FeatureSSE4A);
}
if (IsAMD && ((ECX >> 16) & 0x1)) {
HasFMA4 = true;
ToggleFeature(X86::FeatureFMA4);
}
}
}
X86Subtarget::X86Subtarget(const std::string &TT, const std::string &CPU,
const std::string &FS,
unsigned StackAlignOverride, bool is64Bit)
: X86GenSubtargetInfo(TT, CPU, FS)
, PICStyle(PICStyles::None)
, X86SSELevel(NoMMXSSE)
, X863DNowLevel(NoThreeDNow)
, HasCMov(false)
, HasX86_64(false)
, HasPOPCNT(false)
, HasSSE4A(false)
, HasAVX(false)
, HasAES(false)
, HasCLMUL(false)
, HasFMA3(false)
, HasFMA4(false)
, HasMOVBE(false)
, HasRDRAND(false)
, HasF16C(false)
, IsBTMemSlow(false)
, IsUAMemFast(false)
, HasVectorUAMem(false)
, HasCmpxchg16b(false)
, stackAlignment(8)
// FIXME: this is a known good value for Yonah. How about others?
, MaxInlineSizeThreshold(128)
, TargetTriple(TT)
, In64BitMode(is64Bit)
, InNaClMode(false) {
// Determine default and user specified characteristics
if (!FS.empty() || !CPU.empty()) {
std::string CPUName = CPU;
if (CPUName.empty()) {
#if defined (__x86_64__) || defined(__i386__)
CPUName = sys::getHostCPUName();
#else
CPUName = "generic";
#endif
}
// Make sure 64-bit features are available in 64-bit mode. (But make sure
// SSE2 can be turned off explicitly.)
std::string FullFS = FS;
if (In64BitMode) {
if (!FullFS.empty())
FullFS = "+64bit,+sse2," + FullFS;
else
FullFS = "+64bit,+sse2";
}
// If feature string is not empty, parse features string.
ParseSubtargetFeatures(CPUName, FullFS);
} else {
// Otherwise, use CPUID to auto-detect feature set.
AutoDetectSubtargetFeatures();
// Make sure 64-bit features are available in 64-bit mode.
if (In64BitMode) {
HasX86_64 = true; ToggleFeature(X86::Feature64Bit);
HasCMov = true; ToggleFeature(X86::FeatureCMOV);
if (!HasAVX && X86SSELevel < SSE2) {
X86SSELevel = SSE2;
ToggleFeature(X86::FeatureSSE1);
ToggleFeature(X86::FeatureSSE2);
}
}
}
// It's important to keep the MCSubtargetInfo feature bits in sync with
// target data structure which is shared with MC code emitter, etc.
if (In64BitMode)
ToggleFeature(X86::Mode64Bit);
if (isTargetNaCl()) {
InNaClMode = true;
ToggleFeature(X86::ModeNaCl);
}
if (HasAVX)
X86SSELevel = NoMMXSSE;
DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
<< ", 3DNowLevel " << X863DNowLevel
<< ", 64bit " << HasX86_64 << "\n");
assert((!In64BitMode || HasX86_64) &&
"64-bit code requested on a subtarget that doesn't support it!");
if(EnableSegmentedStacks && !isTargetELF())
report_fatal_error("Segmented stacks are only implemented on ELF.");
// Stack alignment is 16 bytes on Darwin, FreeBSD, Linux and Solaris (both
// 32 and 64 bit) and for all 64-bit targets.
if (StackAlignOverride)
stackAlignment = StackAlignOverride;
else if (isTargetDarwin() || isTargetFreeBSD() || isTargetLinux() ||
isTargetSolaris() || In64BitMode)
stackAlignment = 16;
}
|
//===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86 specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "subtarget"
#include "X86Subtarget.h"
#include "X86InstrInfo.h"
#include "llvm/GlobalValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/SmallVector.h"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "X86GenSubtargetInfo.inc"
using namespace llvm;
#if defined(_MSC_VER)
#include <intrin.h>
#endif
/// ClassifyBlockAddressReference - Classify a blockaddress reference for the
/// current subtarget according to how we should reference it in a non-pcrel
/// context.
unsigned char X86Subtarget::
ClassifyBlockAddressReference() const {
if (isPICStyleGOT()) // 32-bit ELF targets.
return X86II::MO_GOTOFF;
if (isPICStyleStubPIC()) // Darwin/32 in PIC mode.
return X86II::MO_PIC_BASE_OFFSET;
// Direct static reference to label.
return X86II::MO_NO_FLAG;
}
/// ClassifyGlobalReference - Classify a global variable reference for the
/// current subtarget according to how we should reference it in a non-pcrel
/// context.
unsigned char X86Subtarget::
ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const {
// DLLImport only exists on windows, it is implemented as a load from a
// DLLIMPORT stub.
if (GV->hasDLLImportLinkage())
return X86II::MO_DLLIMPORT;
// Determine whether this is a reference to a definition or a declaration.
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
// X86-64 in PIC mode.
if (isPICStyleRIPRel()) {
// Large model never uses stubs.
if (TM.getCodeModel() == CodeModel::Large)
return X86II::MO_NO_FLAG;
if (isTargetDarwin()) {
// If symbol visibility is hidden, the extra load is not needed if
// target is x86-64 or the symbol is definitely defined in the current
// translation unit.
if (GV->hasDefaultVisibility() &&
(isDecl || GV->isWeakForLinker()))
return X86II::MO_GOTPCREL;
} else if (!isTargetWin64()) {
assert(isTargetELF() && "Unknown rip-relative target");
// Extra load is needed for all externally visible.
if (!GV->hasLocalLinkage() && GV->hasDefaultVisibility())
return X86II::MO_GOTPCREL;
}
return X86II::MO_NO_FLAG;
}
if (isPICStyleGOT()) { // 32-bit ELF targets.
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return X86II::MO_GOTOFF;
return X86II::MO_GOT;
}
if (isPICStyleStubPIC()) { // Darwin/32 in PIC mode.
// Determine whether we have a stub reference and/or whether the reference
// is relative to the PIC base or not.
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return X86II::MO_PIC_BASE_OFFSET;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage()) {
// Hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE;
}
// Otherwise, no stub.
return X86II::MO_PIC_BASE_OFFSET;
}
if (isPICStyleStubNoDynamic()) { // Darwin/32 in -mdynamic-no-pic mode.
// Determine whether we have a stub reference.
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return X86II::MO_NO_FLAG;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return X86II::MO_DARWIN_NONLAZY;
// Otherwise, no stub.
return X86II::MO_NO_FLAG;
}
// Direct static reference to global.
return X86II::MO_NO_FLAG;
}
/// getBZeroEntry - This function returns the name of a function which has an
/// interface like the non-standard bzero function, if such a function exists on
/// the current subtarget and it is considered prefereable over memset with zero
/// passed as the second argument. Otherwise it returns null.
const char *X86Subtarget::getBZeroEntry() const {
// Darwin 10 has a __bzero entry point for this purpose.
if (getTargetTriple().isMacOSX() &&
!getTargetTriple().isMacOSXVersionLT(10, 6))
return "__bzero";
return 0;
}
/// IsLegalToCallImmediateAddr - Return true if the subtarget allows calls
/// to immediate address.
bool X86Subtarget::IsLegalToCallImmediateAddr(const TargetMachine &TM) const {
if (In64BitMode)
return false;
return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
}
/// getSpecialAddressLatency - For targets where it is beneficial to
/// backschedule instructions that compute addresses, return a value
/// indicating the number of scheduling cycles of backscheduling that
/// should be attempted.
unsigned X86Subtarget::getSpecialAddressLatency() const {
// For x86 out-of-order targets, back-schedule address computations so
// that loads and stores aren't blocked.
// This value was chosen arbitrarily.
return 200;
}
void X86Subtarget::AutoDetectSubtargetFeatures() {
unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
union {
unsigned u[3];
char c[12];
} text;
if (X86_MC::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1))
return;
X86_MC::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
if ((EDX >> 15) & 1) { HasCMov = true; ToggleFeature(X86::FeatureCMOV); }
if ((EDX >> 23) & 1) { X86SSELevel = MMX; ToggleFeature(X86::FeatureMMX); }
if ((EDX >> 25) & 1) { X86SSELevel = SSE1; ToggleFeature(X86::FeatureSSE1); }
if ((EDX >> 26) & 1) { X86SSELevel = SSE2; ToggleFeature(X86::FeatureSSE2); }
if (ECX & 0x1) { X86SSELevel = SSE3; ToggleFeature(X86::FeatureSSE3); }
if ((ECX >> 9) & 1) { X86SSELevel = SSSE3; ToggleFeature(X86::FeatureSSSE3);}
if ((ECX >> 19) & 1) { X86SSELevel = SSE41; ToggleFeature(X86::FeatureSSE41);}
if ((ECX >> 20) & 1) { X86SSELevel = SSE42; ToggleFeature(X86::FeatureSSE42);}
// FIXME: AVX codegen support is not ready.
//if ((ECX >> 28) & 1) { HasAVX = true; ToggleFeature(X86::FeatureAVX); }
bool IsIntel = memcmp(text.c, "GenuineIntel", 12) == 0;
bool IsAMD = !IsIntel && memcmp(text.c, "AuthenticAMD", 12) == 0;
if (IsIntel && ((ECX >> 1) & 0x1)) {
HasCLMUL = true;
ToggleFeature(X86::FeatureCLMUL);
}
if (IsIntel && ((ECX >> 12) & 0x1)) {
HasFMA3 = true;
ToggleFeature(X86::FeatureFMA3);
}
if (IsIntel && ((ECX >> 22) & 0x1)) {
HasMOVBE = true;
ToggleFeature(X86::FeatureMOVBE);
}
if (IsIntel && ((ECX >> 23) & 0x1)) {
HasPOPCNT = true;
ToggleFeature(X86::FeaturePOPCNT);
}
if (IsIntel && ((ECX >> 25) & 0x1)) {
HasAES = true;
ToggleFeature(X86::FeatureAES);
}
if (IsIntel && ((ECX >> 29) & 0x1)) {
HasF16C = true;
ToggleFeature(X86::FeatureF16C);
}
if (IsIntel && ((ECX >> 30) & 0x1)) {
HasRDRAND = true;
ToggleFeature(X86::FeatureRDRAND);
}
if ((ECX >> 13) & 0x1) {
HasCmpxchg16b = true;
ToggleFeature(X86::FeatureCMPXCHG16B);
}
if (IsIntel || IsAMD) {
// Determine if bit test memory instructions are slow.
unsigned Family = 0;
unsigned Model = 0;
X86_MC::DetectFamilyModel(EAX, Family, Model);
if (IsAMD || (Family == 6 && Model >= 13)) {
IsBTMemSlow = true;
ToggleFeature(X86::FeatureSlowBTMem);
}
// If it's Nehalem, unaligned memory access is fast.
if (Family == 15 && Model == 26) {
IsUAMemFast = true;
ToggleFeature(X86::FeatureFastUAMem);
}
X86_MC::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
if ((EDX >> 29) & 0x1) {
HasX86_64 = true;
ToggleFeature(X86::Feature64Bit);
}
if (IsAMD && ((ECX >> 6) & 0x1)) {
HasSSE4A = true;
ToggleFeature(X86::FeatureSSE4A);
}
if (IsAMD && ((ECX >> 16) & 0x1)) {
HasFMA4 = true;
ToggleFeature(X86::FeatureFMA4);
}
}
}
X86Subtarget::X86Subtarget(const std::string &TT, const std::string &CPU,
const std::string &FS,
unsigned StackAlignOverride, bool is64Bit)
: X86GenSubtargetInfo(TT, CPU, FS)
, PICStyle(PICStyles::None)
, X86SSELevel(NoMMXSSE)
, X863DNowLevel(NoThreeDNow)
, HasCMov(false)
, HasX86_64(false)
, HasPOPCNT(false)
, HasSSE4A(false)
, HasAVX(false)
, HasAES(false)
, HasCLMUL(false)
, HasFMA3(false)
, HasFMA4(false)
, HasMOVBE(false)
, HasRDRAND(false)
, HasF16C(false)
, IsBTMemSlow(false)
, IsUAMemFast(false)
, HasVectorUAMem(false)
, HasCmpxchg16b(false)
, stackAlignment(8)
// FIXME: this is a known good value for Yonah. How about others?
, MaxInlineSizeThreshold(128)
, TargetTriple(TT)
, In64BitMode(is64Bit)
, InNaClMode(false) {
// Determine default and user specified characteristics
if (!FS.empty() || !CPU.empty()) {
std::string CPUName = CPU;
if (CPUName.empty()) {
#if defined (__x86_64__) || defined(__i386__)
CPUName = sys::getHostCPUName();
#else
CPUName = "generic";
#endif
}
// Make sure 64-bit features are available in 64-bit mode. (But make sure
// SSE2 can be turned off explicitly.)
std::string FullFS = FS;
if (In64BitMode) {
if (!FullFS.empty())
FullFS = "+64bit,+sse2," + FullFS;
else
FullFS = "+64bit,+sse2";
}
// If feature string is not empty, parse features string.
ParseSubtargetFeatures(CPUName, FullFS);
} else {
// Otherwise, use CPUID to auto-detect feature set.
AutoDetectSubtargetFeatures();
// Make sure 64-bit features are available in 64-bit mode.
if (In64BitMode) {
HasX86_64 = true; ToggleFeature(X86::Feature64Bit);
HasCMov = true; ToggleFeature(X86::FeatureCMOV);
if (!HasAVX && X86SSELevel < SSE2) {
X86SSELevel = SSE2;
ToggleFeature(X86::FeatureSSE1);
ToggleFeature(X86::FeatureSSE2);
}
}
}
// It's important to keep the MCSubtargetInfo feature bits in sync with
// target data structure which is shared with MC code emitter, etc.
if (In64BitMode)
ToggleFeature(X86::Mode64Bit);
if (isTargetNaCl()) {
InNaClMode = true;
ToggleFeature(X86::ModeNaCl);
}
if (HasAVX)
X86SSELevel = NoMMXSSE;
DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
<< ", 3DNowLevel " << X863DNowLevel
<< ", 64bit " << HasX86_64 << "\n");
assert((!In64BitMode || HasX86_64) &&
"64-bit code requested on a subtarget that doesn't support it!");
if(EnableSegmentedStacks && !isTargetELF())
report_fatal_error("Segmented stacks are only implemented on ELF.");
// Stack alignment is 16 bytes on Darwin, FreeBSD, Linux and Solaris (both
// 32 and 64 bit) and for all 64-bit targets.
if (StackAlignOverride)
stackAlignment = StackAlignOverride;
else if (isTargetDarwin() || isTargetFreeBSD() || isTargetLinux() ||
isTargetSolaris() || In64BitMode)
stackAlignment = 16;
}
|
Put a bunch of calls to ToggleFeature behind proper if statements.
|
Put a bunch of calls to ToggleFeature behind proper if statements.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@141527 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm
|
15f11b13896cda0661c61c5b080d18ae6a4913c3
|
Engine/Source/FishEngine/Internal/FMODPlugin.cpp
|
Engine/Source/FishEngine/Internal/FMODPlugin.cpp
|
#include <FishEngine/Internal/FMODPlugin.hpp>
#include <fmod.hpp>
#include <fmod_errors.h>
#include <FishEngine/Debug.hpp>
#include <FishEngine/StringFormat.hpp>
#include <FishEngine/AudioClip.hpp>
using namespace FishEngine;
void FMODPlugin::Update()
{
GetInstance().m_system->update();
}
void FMODPlugin::Stop()
{
}
FMODPlugin::FMODPlugin()
{
FMOD_RESULT result;
result = FMOD::System_Create(&m_system);
CheckFMODError(result);
result = m_system->init(512, FMOD_INIT_NORMAL, 0);
CheckFMODError(result);
}
void FMODPlugin::Cleanup()
{
std::vector<AudioClipPtr> clips;
Object::FindObjectsOfType<AudioClip>(clips);
for (auto & clip : clips)
{
clip->Cleanup();
}
clips.clear();
auto result = m_system->close();
CheckFMODError(result);
result = m_system->release();
CheckFMODError(result);
m_system = nullptr;
LogWarning("Cleanup");
}
|
#include <FishEngine/Internal/FMODPlugin.hpp>
#include <fmod.hpp>
#include <fmod_errors.h>
#include <FishEngine/Debug.hpp>
#include <FishEngine/StringFormat.hpp>
#include <FishEngine/AudioClip.hpp>
using namespace FishEngine;
constexpr int maxChannel = 32;
void FMODPlugin::Update()
{
GetInstance().m_system->update();
}
void FMODPlugin::Stop()
{
for (int i = 0; i < maxChannel; ++i)
{
FMOD::Channel* pChannel = nullptr;
auto res = GetInstance().m_system->getChannel(i, &pChannel);
if (res == FMOD_OK && pChannel) {
pChannel->stop();
}
}
}
FMODPlugin::FMODPlugin()
{
FMOD_RESULT result;
result = FMOD::System_Create(&m_system);
CheckFMODError(result);
result = m_system->init(maxChannel, FMOD_INIT_NORMAL, 0);
CheckFMODError(result);
}
void FMODPlugin::Cleanup()
{
std::vector<AudioClipPtr> clips;
Object::FindObjectsOfType<AudioClip>(clips);
for (auto & clip : clips)
{
clip->Cleanup();
}
clips.clear();
auto result = m_system->close();
CheckFMODError(result);
result = m_system->release();
CheckFMODError(result);
m_system = nullptr;
LogWarning("Cleanup");
}
|
stop AudioSystem
|
stop AudioSystem
|
C++
|
mit
|
yushroom/FishEngine,yushroom/FishEngine,yushroom/FishEngine,yushroom/FishEngine,yushroom/FishEngine
|
7fca23a260b4c0fb4142248d469c564759fd183e
|
src/core/Debug.cpp
|
src/core/Debug.cpp
|
/*
(c) Copyright 2012-2013 DirectFB integrated media GmbH
(c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org)
(c) Copyright 2000-2004 Convergence (integrated media) GmbH
All rights reserved.
Written by Denis Oliver Kropp <[email protected]>,
Andreas Shimokawa <[email protected]>,
Marek Pikarski <[email protected]>,
Sven Neumann <[email protected]>,
Ville Syrjälä <[email protected]> and
Claudio Ciccani <[email protected]>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
//#define DIRECT_ENABLE_DEBUG
#include <config.h>
#include <fusion/Debug.h>
#include "Debug.h"
extern "C" {
#include <directfb_strings.h>
#include <directfb_util.h>
#include <core/core_strings.h>
#include <core/layer_region.h>
#include <core/surface_buffer.h>
}
#include <core/SurfaceTask.h>
/*********************************************************************************************************************/
template<>
ToString<DFBResult>::ToString( const DFBResult &result )
{
PrintF( "%s", DirectResultString( (DirectResult) result ) );
}
// Core enums
template<>
ToString<CoreSurfaceTypeFlags>::ToString( const CoreSurfaceTypeFlags &flags )
{
static const DirectFBCoreSurfaceTypeFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
// DirectFB enums
template<>
ToString<DFBAccelerationMask>::ToString( const DFBAccelerationMask &accel )
{
static const DirectFBAccelerationMaskNames(accelerationmask_names);
for (int i=0, n=0; accelerationmask_names[i].mask; i++) {
if (accel & accelerationmask_names[i].mask)
PrintF( "%s%s", n++ ? "," : "", accelerationmask_names[i].name );
}
}
template<>
ToString<DFBSurfaceBlittingFlags>::ToString( const DFBSurfaceBlittingFlags &flags )
{
static const DirectFBSurfaceBlittingFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfaceCapabilities>::ToString( const DFBSurfaceCapabilities &caps )
{
static const DirectFBSurfaceCapabilitiesNames(caps_names);
for (int i=0, n=0; caps_names[i].capability; i++) {
if (caps & caps_names[i].capability)
PrintF( "%s%s", n++ ? "," : "", caps_names[i].name );
}
}
template<>
ToString<DFBSurfaceDrawingFlags>::ToString( const DFBSurfaceDrawingFlags &flags )
{
static const DirectFBSurfaceDrawingFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfacePixelFormat>::ToString( const DFBSurfacePixelFormat &format )
{
for (int i=0; dfb_pixelformat_names[i].format; i++) {
if (format == dfb_pixelformat_names[i].format) {
PrintF( "%s", dfb_pixelformat_names[i].name );
return;
}
}
PrintF( "_INVALID_<0x%08x>", format );
}
template<>
ToString<DFBSurfaceFlipFlags>::ToString( const DFBSurfaceFlipFlags &flags )
{
static const DirectFBSurfaceFlipFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfacePorterDuffRule>::ToString( const DFBSurfacePorterDuffRule &rule )
{
static const DirectFBPorterDuffRuleNames(rules_names);
for (int i=0; rules_names[i].rule; i++) {
if (rule == rules_names[i].rule) {
PrintF( "%s", rules_names[i].name );
return;
}
}
if (rule == DSPD_NONE)
PrintF( "NONE" );
else
PrintF( "_INVALID_<0x%08x>", rule );
}
// DirectFB types
template<>
ToString<DFBDimension>::ToString( const DFBDimension &v )
{
PrintF( "%dx%d", v.w, v.h );
}
template<>
ToString<DFBDisplayLayerBufferMode>::ToString( const DFBDisplayLayerBufferMode &mode )
{
switch (mode) {
case DLBM_FRONTONLY:
PrintF( "FRONTONLY" );
break;
case DLBM_BACKVIDEO:
PrintF( "BACKVIDEO" );
break;
case DLBM_BACKSYSTEM:
PrintF( "BACKSYSTEM" );
break;
case DLBM_TRIPLE:
PrintF( "TRIPLE" );
break;
default:
PrintF( "invalid 0x%x", mode );
break;
}
}
// CoreSurface types
template<>
ToString<CoreSurfaceConfig>::ToString( const CoreSurfaceConfig &config )
{
int buffers = 0;
if (config.caps & DSCAPS_TRIPLE)
buffers = 3;
else if (config.caps & DSCAPS_DOUBLE)
buffers = 2;
else
buffers = 1;
PrintF( "size:%dx%d format:%s caps:%s bufs:%d",
config.size.w, config.size.h,
ToString<DFBSurfacePixelFormat>(config.format).buffer(),
ToString<DFBSurfaceCapabilities>(config.caps).buffer(),
buffers );
}
template<>
ToString<CoreSurfaceAccessFlags>::ToString( const CoreSurfaceAccessFlags &flags )
{
#define CORE_SURFACE_ACCESS_FLAG_PRINTF( __F ) \
D_FLAG_PRINTFn( n, flags, CSAF_, __F )
if (flags) {
size_t n = 0;
CORE_SURFACE_ACCESS_FLAG_PRINTF( READ );
CORE_SURFACE_ACCESS_FLAG_PRINTF( WRITE );
CORE_SURFACE_ACCESS_FLAG_PRINTF( SHARED );
CORE_SURFACE_ACCESS_FLAG_PRINTF( CACHE_INVALIDATE );
CORE_SURFACE_ACCESS_FLAG_PRINTF( CACHE_FLUSH );
}
else
PrintF( "<NONE>" );
}
// CoreLayer types
template<>
ToString<CoreLayerRegionConfig>::ToString( const CoreLayerRegionConfig &config )
{
PrintF( "size:%dx%d format:%s surface_caps:%s buffermode:%s",
config.width, config.height,
*ToString<DFBSurfacePixelFormat>(config.format),
*ToString<DFBSurfaceCapabilities>(config.surface_caps),
*ToString<DFBDisplayLayerBufferMode>(config.buffermode) );
}
// CoreSurface objects
template<>
ToString<CoreSurfaceAllocation>::ToString( const CoreSurfaceAllocation &allocation )
{
PrintF( "{CoreSurfaceAllocation %s [%d] type:%s resid:%lu %s}",
ToString<FusionObject>(allocation.object).buffer(),
allocation.index,
ToString<CoreSurfaceTypeFlags>(allocation.type).buffer(),
allocation.resource_id,
ToString<CoreSurfaceConfig>(allocation.config).buffer() );
}
template<>
ToString<CoreSurfaceBuffer>::ToString( const CoreSurfaceBuffer &buffer )
{
PrintF( "{CoreSurfaceBuffer %s [%d] allocs:%d type:%s resid:%lu %s}",
ToString<FusionObject>(buffer.object).buffer(),
buffer.index, buffer.allocs.count,
ToString<CoreSurfaceTypeFlags>(buffer.type).buffer(),
buffer.resource_id,
ToString<CoreSurfaceConfig>(buffer.config).buffer() );
}
template<>
ToString<CoreSurface>::ToString( const CoreSurface &surface )
{
PrintF( "{CoreSurface %s [%d] buffers:%d type:%s resid:%lu %s}",
*ToString<FusionObject>(surface.object),
surface.clients.count, surface.num_buffers,
*ToString<CoreSurfaceTypeFlags>(surface.type),
surface.resource_id,
*ToString<CoreSurfaceConfig>(surface.config) );
}
template<>
ToString<CoreSurfaceBufferLock>::ToString( const CoreSurfaceBufferLock &lock )
{
PrintF( "accessor:0x%02x access:%s buffer:%p allocation:%p addr:%p phys:0x%08lx offset:%lu pitch:%u handle:%p",
lock.accessor,
*ToString<CoreSurfaceAccessFlags>(lock.access),
lock.buffer,
lock.allocation,
lock.addr,
lock.phys,
lock.offset,
lock.pitch,
lock.handle );
}
template<>
ToString<DirectFB::Task>::ToString( const DirectFB::Task &task )
{
task.Describe( *this );
}
template<>
ToString<DirectFB::TaskState>::ToString( const DirectFB::TaskState &state )
{
switch (state) {
case DirectFB::TASK_STATE_NONE:
PrintF( "<NONE>" );
break;
case DirectFB::TASK_NEW:
PrintF( "NEW" );
break;
case DirectFB::TASK_FLUSHED:
PrintF( "FLUSHED" );
break;
case DirectFB::TASK_READY:
PrintF( "READY" );
break;
case DirectFB::TASK_RUNNING:
PrintF( "RUNNING" );
break;
case DirectFB::TASK_DONE:
PrintF( "DONE" );
break;
case DirectFB::TASK_FINISH:
PrintF( "FINISH" );
break;
case DirectFB::TASK_DEAD:
PrintF( "DEAD" );
break;
case DirectFB::TASK_INVALID:
PrintF( "INVALID" );
break;
case DirectFB::TASK_STATE_ALL:
PrintF( "<ALL>" );
break;
default:
PrintF( "invalid 0x%x", state );
break;
}
}
template<>
ToString<DirectFB::TaskFlags>::ToString( const DirectFB::TaskFlags &flags )
{
#define TASK_FLAG_PRINTF( __F ) \
D_FLAG_PRINTFn( n, flags, DirectFB::TASK_FLAG_, __F )
if (flags) {
size_t n = 0;
TASK_FLAG_PRINTF( NOSYNC );
TASK_FLAG_PRINTF( EMITNOTIFIES );
TASK_FLAG_PRINTF( CACHE_FLUSH );
TASK_FLAG_PRINTF( CACHE_INVALIDATE );
TASK_FLAG_PRINTF( NEED_SLAVE_PUSH );
TASK_FLAG_PRINTF( LAST_IN_QUEUE );
TASK_FLAG_PRINTF( FOLLOW_READER );
TASK_FLAG_PRINTF( FOLLOW_WRITER );
TASK_FLAG_PRINTF( WAITING_TIMED_EMIT );
}
else
PrintF( "<NONE>" );
}
template<>
ToString<DirectFB::SurfaceAllocationAccess>::ToString( const DirectFB::SurfaceAllocationAccess &access )
{
CORE_SURFACE_ALLOCATION_ASSERT( access.allocation );
PrintF( "allocation:%p task_count:%d access:%s\n",
access.allocation, access.allocation->task_count,
*ToString<CoreSurfaceAccessFlags>(access.flags) );
}
/*********************************************************************************************************************/
extern "C" {
const char *
ToString_CoreSurfaceTypeFlags( CoreSurfaceTypeFlags v )
{
return ToString<CoreSurfaceTypeFlags>( v ).CopyTLS();
}
const char *
ToString_DFBAccelerationMask( DFBAccelerationMask v )
{
return ToString<DFBAccelerationMask>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceBlittingFlags( DFBSurfaceBlittingFlags v )
{
return ToString<DFBSurfaceBlittingFlags>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceCapabilities( DFBSurfaceCapabilities v )
{
return ToString<DFBSurfaceCapabilities>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceDrawingFlags( DFBSurfaceDrawingFlags v )
{
return ToString<DFBSurfaceDrawingFlags>( v ).CopyTLS();
}
const char *
ToString_DFBSurfacePixelFormat( DFBSurfacePixelFormat v )
{
return ToString<DFBSurfacePixelFormat>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceFlipFlags( DFBSurfaceFlipFlags v )
{
return ToString<DFBSurfaceFlipFlags>( v ).CopyTLS();
}
const char *
ToString_DFBDimension( const DFBDimension *v )
{
return ToString<DFBDimension>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceConfig( const CoreSurfaceConfig *v )
{
return ToString<CoreSurfaceConfig>( *v ).CopyTLS();
}
const char *
ToString_CoreLayerRegionConfig( const CoreLayerRegionConfig *v )
{
return ToString<CoreLayerRegionConfig>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceAllocation( const CoreSurfaceAllocation *v )
{
return ToString<CoreSurfaceAllocation>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceBuffer( const CoreSurfaceBuffer *v )
{
return ToString<CoreSurfaceBuffer>( *v ).CopyTLS();
}
const char *
ToString_CoreSurface( const CoreSurface *v )
{
return ToString<CoreSurface>( *v ).CopyTLS();
}
const char *
ToString_Task( const DFB_Task *v )
{
return ToString<DFB_Task>( *v ).CopyTLS();
}
}
|
/*
(c) Copyright 2012-2013 DirectFB integrated media GmbH
(c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org)
(c) Copyright 2000-2004 Convergence (integrated media) GmbH
All rights reserved.
Written by Denis Oliver Kropp <[email protected]>,
Andreas Shimokawa <[email protected]>,
Marek Pikarski <[email protected]>,
Sven Neumann <[email protected]>,
Ville Syrjälä <[email protected]> and
Claudio Ciccani <[email protected]>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
//#define DIRECT_ENABLE_DEBUG
#include <config.h>
#include <fusion/Debug.h>
#include "Debug.h"
extern "C" {
#include <directfb_strings.h>
#include <directfb_util.h>
#include <core/core_strings.h>
#include <core/layer_region.h>
#include <core/surface_buffer.h>
}
#include <core/SurfaceTask.h>
/*********************************************************************************************************************/
template<>
ToString<DFBResult>::ToString( const DFBResult &result )
{
PrintF( "%s", DirectResultString( (DirectResult) result ) );
}
// Core enums
template<>
ToString<CoreSurfaceTypeFlags>::ToString( const CoreSurfaceTypeFlags &flags )
{
static const DirectFBCoreSurfaceTypeFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
// DirectFB enums
template<>
ToString<DFBAccelerationMask>::ToString( const DFBAccelerationMask &accel )
{
static const DirectFBAccelerationMaskNames(accelerationmask_names);
for (int i=0, n=0; accelerationmask_names[i].mask; i++) {
if (accel & accelerationmask_names[i].mask)
PrintF( "%s%s", n++ ? "," : "", accelerationmask_names[i].name );
}
}
template<>
ToString<DFBSurfaceBlittingFlags>::ToString( const DFBSurfaceBlittingFlags &flags )
{
static const DirectFBSurfaceBlittingFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfaceCapabilities>::ToString( const DFBSurfaceCapabilities &caps )
{
static const DirectFBSurfaceCapabilitiesNames(caps_names);
for (int i=0, n=0; caps_names[i].capability; i++) {
if (caps & caps_names[i].capability)
PrintF( "%s%s", n++ ? "," : "", caps_names[i].name );
}
}
template<>
ToString<DFBSurfaceDrawingFlags>::ToString( const DFBSurfaceDrawingFlags &flags )
{
static const DirectFBSurfaceDrawingFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfacePixelFormat>::ToString( const DFBSurfacePixelFormat &format )
{
for (int i=0; dfb_pixelformat_names[i].format; i++) {
if (format == dfb_pixelformat_names[i].format) {
PrintF( "%s", dfb_pixelformat_names[i].name );
return;
}
}
PrintF( "_INVALID_<0x%08x>", format );
}
template<>
ToString<DFBSurfaceFlipFlags>::ToString( const DFBSurfaceFlipFlags &flags )
{
static const DirectFBSurfaceFlipFlagsNames(flags_names);
for (int i=0, n=0; flags_names[i].flag; i++) {
if (flags & flags_names[i].flag)
PrintF( "%s%s", n++ ? "," : "", flags_names[i].name );
}
}
template<>
ToString<DFBSurfacePorterDuffRule>::ToString( const DFBSurfacePorterDuffRule &rule )
{
static const DirectFBPorterDuffRuleNames(rules_names);
for (int i=0; rules_names[i].rule; i++) {
if (rule == rules_names[i].rule) {
PrintF( "%s", rules_names[i].name );
return;
}
}
if (rule == DSPD_NONE)
PrintF( "NONE" );
else
PrintF( "_INVALID_<0x%08x>", rule );
}
// DirectFB types
template<>
ToString<DFBDimension>::ToString( const DFBDimension &v )
{
PrintF( "%dx%d", v.w, v.h );
}
template<>
ToString<DFBRectangle>::ToString( const DFBRectangle &v )
{
PrintF( "%d,%d-%dx%d", v.x, v.y, v.w, v.h );
}
template<>
ToString<DFBDisplayLayerBufferMode>::ToString( const DFBDisplayLayerBufferMode &mode )
{
switch (mode) {
case DLBM_FRONTONLY:
PrintF( "FRONTONLY" );
break;
case DLBM_BACKVIDEO:
PrintF( "BACKVIDEO" );
break;
case DLBM_BACKSYSTEM:
PrintF( "BACKSYSTEM" );
break;
case DLBM_TRIPLE:
PrintF( "TRIPLE" );
break;
default:
PrintF( "invalid 0x%x", mode );
break;
}
}
// CoreSurface types
template<>
ToString<CoreSurfaceConfig>::ToString( const CoreSurfaceConfig &config )
{
int buffers = 0;
if (config.caps & DSCAPS_TRIPLE)
buffers = 3;
else if (config.caps & DSCAPS_DOUBLE)
buffers = 2;
else
buffers = 1;
PrintF( "size:%dx%d format:%s caps:%s bufs:%d",
config.size.w, config.size.h,
ToString<DFBSurfacePixelFormat>(config.format).buffer(),
ToString<DFBSurfaceCapabilities>(config.caps).buffer(),
buffers );
}
template<>
ToString<CoreSurfaceAccessFlags>::ToString( const CoreSurfaceAccessFlags &flags )
{
#define CORE_SURFACE_ACCESS_FLAG_PRINTF( __F ) \
D_FLAG_PRINTFn( n, flags, CSAF_, __F )
if (flags) {
size_t n = 0;
CORE_SURFACE_ACCESS_FLAG_PRINTF( READ );
CORE_SURFACE_ACCESS_FLAG_PRINTF( WRITE );
CORE_SURFACE_ACCESS_FLAG_PRINTF( SHARED );
CORE_SURFACE_ACCESS_FLAG_PRINTF( CACHE_INVALIDATE );
CORE_SURFACE_ACCESS_FLAG_PRINTF( CACHE_FLUSH );
}
else
PrintF( "<NONE>" );
}
// CoreLayer types
template<>
ToString<CoreLayerRegionConfig>::ToString( const CoreLayerRegionConfig &config )
{
PrintF( "size:%dx%d format:%s surface_caps:%s buffermode:%s source:%s dest:%s",
config.width, config.height,
*ToString<DFBSurfacePixelFormat>(config.format),
*ToString<DFBSurfaceCapabilities>(config.surface_caps),
*ToString<DFBDisplayLayerBufferMode>(config.buffermode),
*ToString<DFBRectangle>(config.source),
*ToString<DFBRectangle>(config.dest) );
}
// CoreSurface objects
template<>
ToString<CoreSurfaceAllocation>::ToString( const CoreSurfaceAllocation &allocation )
{
PrintF( "{CoreSurfaceAllocation %s [%d] type:%s resid:%lu %s}",
ToString<FusionObject>(allocation.object).buffer(),
allocation.index,
ToString<CoreSurfaceTypeFlags>(allocation.type).buffer(),
allocation.resource_id,
ToString<CoreSurfaceConfig>(allocation.config).buffer() );
}
template<>
ToString<CoreSurfaceBuffer>::ToString( const CoreSurfaceBuffer &buffer )
{
PrintF( "{CoreSurfaceBuffer %s [%d] allocs:%d type:%s resid:%lu %s}",
ToString<FusionObject>(buffer.object).buffer(),
buffer.index, buffer.allocs.count,
ToString<CoreSurfaceTypeFlags>(buffer.type).buffer(),
buffer.resource_id,
ToString<CoreSurfaceConfig>(buffer.config).buffer() );
}
template<>
ToString<CoreSurface>::ToString( const CoreSurface &surface )
{
PrintF( "{CoreSurface %s [%d] buffers:%d type:%s resid:%lu %s}",
*ToString<FusionObject>(surface.object),
surface.clients.count, surface.num_buffers,
*ToString<CoreSurfaceTypeFlags>(surface.type),
surface.resource_id,
*ToString<CoreSurfaceConfig>(surface.config) );
}
template<>
ToString<CoreSurfaceBufferLock>::ToString( const CoreSurfaceBufferLock &lock )
{
PrintF( "accessor:0x%02x access:%s buffer:%p allocation:%p addr:%p phys:0x%08lx offset:%lu pitch:%u handle:%p",
lock.accessor,
*ToString<CoreSurfaceAccessFlags>(lock.access),
lock.buffer,
lock.allocation,
lock.addr,
lock.phys,
lock.offset,
lock.pitch,
lock.handle );
}
template<>
ToString<DirectFB::Task>::ToString( const DirectFB::Task &task )
{
task.Describe( *this );
}
template<>
ToString<DirectFB::TaskState>::ToString( const DirectFB::TaskState &state )
{
switch (state) {
case DirectFB::TASK_STATE_NONE:
PrintF( "<NONE>" );
break;
case DirectFB::TASK_NEW:
PrintF( "NEW" );
break;
case DirectFB::TASK_FLUSHED:
PrintF( "FLUSHED" );
break;
case DirectFB::TASK_READY:
PrintF( "READY" );
break;
case DirectFB::TASK_RUNNING:
PrintF( "RUNNING" );
break;
case DirectFB::TASK_DONE:
PrintF( "DONE" );
break;
case DirectFB::TASK_FINISH:
PrintF( "FINISH" );
break;
case DirectFB::TASK_DEAD:
PrintF( "DEAD" );
break;
case DirectFB::TASK_INVALID:
PrintF( "INVALID" );
break;
case DirectFB::TASK_STATE_ALL:
PrintF( "<ALL>" );
break;
default:
PrintF( "invalid 0x%x", state );
break;
}
}
template<>
ToString<DirectFB::TaskFlags>::ToString( const DirectFB::TaskFlags &flags )
{
#define TASK_FLAG_PRINTF( __F ) \
D_FLAG_PRINTFn( n, flags, DirectFB::TASK_FLAG_, __F )
if (flags) {
size_t n = 0;
TASK_FLAG_PRINTF( NOSYNC );
TASK_FLAG_PRINTF( EMITNOTIFIES );
TASK_FLAG_PRINTF( CACHE_FLUSH );
TASK_FLAG_PRINTF( CACHE_INVALIDATE );
TASK_FLAG_PRINTF( NEED_SLAVE_PUSH );
TASK_FLAG_PRINTF( LAST_IN_QUEUE );
TASK_FLAG_PRINTF( FOLLOW_READER );
TASK_FLAG_PRINTF( FOLLOW_WRITER );
TASK_FLAG_PRINTF( WAITING_TIMED_EMIT );
}
else
PrintF( "<NONE>" );
}
template<>
ToString<DirectFB::SurfaceAllocationAccess>::ToString( const DirectFB::SurfaceAllocationAccess &access )
{
CORE_SURFACE_ALLOCATION_ASSERT( access.allocation );
PrintF( "allocation:%p task_count:%d access:%s\n",
access.allocation, access.allocation->task_count,
*ToString<CoreSurfaceAccessFlags>(access.flags) );
}
/*********************************************************************************************************************/
extern "C" {
const char *
ToString_CoreSurfaceTypeFlags( CoreSurfaceTypeFlags v )
{
return ToString<CoreSurfaceTypeFlags>( v ).CopyTLS();
}
const char *
ToString_DFBAccelerationMask( DFBAccelerationMask v )
{
return ToString<DFBAccelerationMask>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceBlittingFlags( DFBSurfaceBlittingFlags v )
{
return ToString<DFBSurfaceBlittingFlags>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceCapabilities( DFBSurfaceCapabilities v )
{
return ToString<DFBSurfaceCapabilities>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceDrawingFlags( DFBSurfaceDrawingFlags v )
{
return ToString<DFBSurfaceDrawingFlags>( v ).CopyTLS();
}
const char *
ToString_DFBSurfacePixelFormat( DFBSurfacePixelFormat v )
{
return ToString<DFBSurfacePixelFormat>( v ).CopyTLS();
}
const char *
ToString_DFBSurfaceFlipFlags( DFBSurfaceFlipFlags v )
{
return ToString<DFBSurfaceFlipFlags>( v ).CopyTLS();
}
const char *
ToString_DFBDimension( const DFBDimension *v )
{
return ToString<DFBDimension>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceConfig( const CoreSurfaceConfig *v )
{
return ToString<CoreSurfaceConfig>( *v ).CopyTLS();
}
const char *
ToString_CoreLayerRegionConfig( const CoreLayerRegionConfig *v )
{
return ToString<CoreLayerRegionConfig>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceAllocation( const CoreSurfaceAllocation *v )
{
return ToString<CoreSurfaceAllocation>( *v ).CopyTLS();
}
const char *
ToString_CoreSurfaceBuffer( const CoreSurfaceBuffer *v )
{
return ToString<CoreSurfaceBuffer>( *v ).CopyTLS();
}
const char *
ToString_CoreSurface( const CoreSurface *v )
{
return ToString<CoreSurface>( *v ).CopyTLS();
}
const char *
ToString_Task( const DFB_Task *v )
{
return ToString<DFB_Task>( *v ).CopyTLS();
}
}
|
Add ToString<DFBRectangle>
|
Core: Add ToString<DFBRectangle>
|
C++
|
lgpl-2.1
|
sklnet/DirectFB,djbclark/directfb-core-DirectFB,lancebaiyouview/DirectFB,DirectFB/directfb,deniskropp/DirectFB,deniskropp/DirectFB,kevleyski/directfb,deniskropp/DirectFB,dfbdok/DirectFB1,deniskropp/DirectFB,kaostao/directfb,DirectFB/directfb,mtsekm/test,DirectFB/directfb,dfbdok/DirectFB1,kevleyski/directfb,djbclark/directfb-core-DirectFB,lancebaiyouview/DirectFB,jcdubois/DirectFB,mtsekm/test,kaostao/directfb,lancebaiyouview/DirectFB,kevleyski/directfb,djbclark/directfb-core-DirectFB,sklnet/DirectFB,sklnet/DirectFB,djbclark/directfb-core-DirectFB,jcdubois/DirectFB,dfbdok/DirectFB1,kevleyski/directfb,sklnet/DirectFB,mtsekm/test,lancebaiyouview/DirectFB,kaostao/directfb,jcdubois/DirectFB
|
8a9dedc1ac49b1a51e3a6bf7569d2bf469a1406f
|
source/main.cpp
|
source/main.cpp
|
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
#include <3ds.h>
#include <ctrcommon/app.hpp>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](u64 pos, u64 totalSize) {
std::stringstream details;
details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
details << "Press B to cancel.";
u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
} else {
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
if(fsDelete(path)) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
|
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include <stdio.h>
#include <sstream>
#include <iomanip>
#include <sys/dirent.h>
#include <3ds.h>
#include <ctrcommon/app.hpp>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
if(ninjhax) {
stream << "START - Exit to launcher" << "\n";
}
std::string str = stream.str();
screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);
return breakLoop;
};
auto onProgress = [&](u64 pos, u64 totalSize) {
std::stringstream details;
details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
details << "Press B to cancel.";
u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
inputPoll();
return !inputIsPressed(BUTTON_B);
};
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string fileName = (*it).name;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
}
} else {
if(!fsDelete(path)) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << fileName << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
} else {
if(fsDelete(path)) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError()) << "\n";
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(netInstall && !exit) {
netInstall = false;
screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
if(file.fd == NULL) {
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret) << "\n";
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
fclose(file.fd);
continue;
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
|
Break loop when changing the destination in launch mode.
|
Break loop when changing the destination in launch mode.
|
C++
|
mit
|
Jerry-Shaw/FBI,Possum/LumaLocaleSwitcher,soarqin/FBI,Possum/LumaLocaleSwitcher,Traiver/FBI,Traiver/FBI,masterhou/FBI,Traiver/FBI,Jerry-Shaw/FBI,hippydave/Newquay,leo60228/CTRM,leo60228/CTRM,kot2002/FBI,masterhou/FBI,Jerry-Shaw/FBI,Jerry-Shaw/FBI,hippydave/Newquay,leo60228/CTRM,kot2002/FBI,soarqin/FBI
|
d2ef80164a97319d6e83490fdb029ca894467976
|
History/Depthwise-Separable-Convolution/main.cpp
|
History/Depthwise-Separable-Convolution/main.cpp
|
#include <fstream>
#include <iostream>
#include <omp.h>
#include <random>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 20;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.5;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(0);
NN.Add( 1, 28, 28);
NN.Add(24, 24, 24)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(24, 12, 12);
NN.Add(24, 8, 8);
NN.Add(48, 8, 8)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(48, 4, 4);
NN.Add(512)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W")->Initializer(HeNormal());
NN.Connect(2, 1, "P,max");
NN.Connect(3, 2, "W,depthwise")->Initializer(HeNormal());
NN.Connect(4, 3, "W,pointwise")->Initializer(HeNormal());
NN.Connect(5, 4, "P,max");
NN.Connect(6, 5, "W")->Initializer(HeNormal());
NN.Connect(7, 6, "W")->Initializer(HeNormal());
NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
|
#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 20;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double learning_rate = 0.5;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(0);
NN.Add( 1, 28, 28);
NN.Add(24, 24, 24)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(24, 12, 12);
NN.Add(24, 8, 8);
NN.Add(48, 8, 8)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(48, 4, 4);
NN.Add(512)->Activation(Activation::relu)->Batch_Normalization();
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W")->Initializer(HeNormal());
NN.Connect(2, 1, "P,max");
NN.Connect(3, 2, "W,depthwise")->Initializer(HeNormal());
NN.Connect(4, 3, "W,pointwise")->Initializer(HeNormal());
NN.Connect(5, 4, "P,max");
NN.Connect(6, 5, "W")->Initializer(HeNormal());
NN.Connect(7, 6, "W")->Initializer(HeNormal());
NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
|
Update main.cpp
|
Update main.cpp
|
C++
|
mit
|
paperrune/Neural-Networks,paperrune/Neural-Networks
|
48add58ae8c78fa15183c6d3578bdd903dddc3dc
|
cbits/Engine.cpp
|
cbits/Engine.cpp
|
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickWindow>
#include "Manager.h"
#include "Engine.h"
#include "Object.h"
HsQMLEngine::HsQMLEngine(const HsQMLEngineConfig& config)
: mComponent(&mEngine)
, mStopCb(config.stopCb)
{
// Connect signals
QObject::connect(
&mEngine, SIGNAL(quit()),
this, SLOT(deleteLater()));
QObject::connect(
&mComponent, SIGNAL(statusChanged(QQmlComponent::Status)),
this, SLOT(componentStatus(QQmlComponent::Status)));
// Obtain, re-parent, and set QML global object
if (config.contextObject) {
QObject* ctx = config.contextObject->object(this);
mEngine.rootContext()->setContextObject(ctx);
mObjects << ctx;
}
// Load document
mComponent.loadUrl(QUrl(config.initialURL));
}
HsQMLEngine::~HsQMLEngine()
{
// Call stop callback
mStopCb();
gManager->freeFun(reinterpret_cast<HsFunPtr>(mStopCb));
// Delete owned objects
qDeleteAll(mObjects);
}
bool HsQMLEngine::eventFilter(QObject* obj, QEvent* ev)
{
if (QEvent::Close == ev->type()) {
deleteLater();
}
return false;
}
QQmlEngine* HsQMLEngine::declEngine()
{
return &mEngine;
}
void HsQMLEngine::componentStatus(QQmlComponent::Status status)
{
switch (status) {
case QQmlComponent::Ready: {
QObject* obj = mComponent.create();
mObjects << obj;
QQuickWindow* win = qobject_cast<QQuickWindow*>(obj);
QQuickItem* item = qobject_cast<QQuickItem*>(obj);
if (item) {
win = new QQuickWindow();
mObjects << win;
item->setParentItem(win->contentItem());
int width = item->width();
int height = item->height();
if (width < 1 || height < 1) {
width = item->implicitWidth();
height = item->implicitHeight();
}
win->setWidth(width);
win->setHeight(height);
win->contentItem()->setWidth(width);
win->contentItem()->setHeight(height);
win->setTitle("HsQML Window");
win->show();
}
if (win) {
win->installEventFilter(this);
mEngine.setIncubationController(win->incubationController());
}
break;}
case QQmlComponent::Error: {
QList<QQmlError> errs = mComponent.errors();
for (QList<QQmlError>::iterator it = errs.begin();
it != errs.end(); ++it) {
HSQML_LOG(0, it->toString());
}
break;}
}
}
extern "C" void hsqml_create_engine(
HsQMLObjectHandle* contextObject,
HsQMLStringHandle* initialURL,
HsQMLTrivialCb stopCb)
{
HsQMLEngineConfig config;
config.contextObject = reinterpret_cast<HsQMLObjectProxy*>(contextObject);
config.initialURL = *reinterpret_cast<QString*>(initialURL);
config.stopCb = stopCb;
Q_ASSERT (gManager);
gManager->createEngine(config);
}
|
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickWindow>
#include "Manager.h"
#include "Engine.h"
#include "Object.h"
HsQMLEngine::HsQMLEngine(const HsQMLEngineConfig& config)
: mComponent(&mEngine)
, mStopCb(config.stopCb)
{
// Connect signals
QObject::connect(
&mEngine, SIGNAL(quit()),
this, SLOT(deleteLater()));
QObject::connect(
&mComponent, SIGNAL(statusChanged(QQmlComponent::Status)),
this, SLOT(componentStatus(QQmlComponent::Status)));
// Obtain, re-parent, and set QML global object
if (config.contextObject) {
QObject* ctx = config.contextObject->object(this);
mEngine.rootContext()->setContextObject(ctx);
mObjects << ctx;
}
// Load document
mComponent.loadUrl(QUrl(config.initialURL));
}
HsQMLEngine::~HsQMLEngine()
{
// Call stop callback
mStopCb();
gManager->freeFun(reinterpret_cast<HsFunPtr>(mStopCb));
// Delete owned objects
qDeleteAll(mObjects);
}
bool HsQMLEngine::eventFilter(QObject* obj, QEvent* ev)
{
if (QEvent::Close == ev->type()) {
deleteLater();
}
return false;
}
QQmlEngine* HsQMLEngine::declEngine()
{
return &mEngine;
}
void HsQMLEngine::componentStatus(QQmlComponent::Status status)
{
switch (status) {
case QQmlComponent::Ready: {
QObject* obj = mComponent.create();
mObjects << obj;
QQuickWindow* win = qobject_cast<QQuickWindow*>(obj);
QQuickItem* item = qobject_cast<QQuickItem*>(obj);
if (item) {
win = new QQuickWindow();
mObjects << win;
item->setParentItem(win->contentItem());
int width = item->width();
int height = item->height();
if (width < 1 || height < 1) {
width = item->implicitWidth();
height = item->implicitHeight();
}
win->setWidth(width);
win->setHeight(height);
win->contentItem()->setWidth(width);
win->contentItem()->setHeight(height);
win->setTitle("HsQML Window");
win->show();
}
if (win) {
win->installEventFilter(this);
mEngine.setIncubationController(win->incubationController());
}
break;}
case QQmlComponent::Error: {
QList<QQmlError> errs = mComponent.errors();
for (QList<QQmlError>::iterator it = errs.begin();
it != errs.end(); ++it) {
HSQML_LOG(0, it->toString());
}
deleteLater();
break;}
}
}
extern "C" void hsqml_create_engine(
HsQMLObjectHandle* contextObject,
HsQMLStringHandle* initialURL,
HsQMLTrivialCb stopCb)
{
HsQMLEngineConfig config;
config.contextObject = reinterpret_cast<HsQMLObjectProxy*>(contextObject);
config.initialURL = *reinterpret_cast<QString*>(initialURL);
config.stopCb = stopCb;
Q_ASSERT (gManager);
gManager->createEngine(config);
}
|
Fix engine hanging when error occurs on startup.
|
Fix engine hanging when error occurs on startup.
Ignore-this: 85a91b76e3678eb9f4cdb098e3ee0d9a
darcs-hash:20140501173434-4d2ae-c2fe5c1fa42fc1ac107fac2583817a3e96b3809c
|
C++
|
bsd-3-clause
|
johntyree/HsQML,johntyree/HsQML
|
625e5c88c87614742fce150b2d04fdf55a441765
|
targets/CMSIS-OS/ChibiOS/nanoCLR/nanoFramework.Hardware.Stm32/nf_hardware_stm32_native.cpp
|
targets/CMSIS-OS/ChibiOS/nanoCLR/nanoFramework.Hardware.Stm32/nf_hardware_stm32_native.cpp
|
//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_hardware_stm32_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::ReadBytes___STATIC__VOID__U4__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::WriteBytes___STATIC__VOID__U4__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::GetSize___STATIC__I4,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_RTC::Native_RTC_SetAlarm___STATIC__VOID__U1__U1__U1__U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_RTC::Native_RTC_GetAlarm___STATIC__I8,
NULL,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceUniqueId___STATIC__VOID__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceId___STATIC__U4,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceRevisionId___STATIC__U4,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Stm32 =
{
"nanoFramework.Hardware.Stm32",
0x8D551100,
method_lookup,
{ 1, 0, 2, 4 }
};
|
//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_hardware_stm32_native.h"
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::ReadBytes___STATIC__VOID__U4__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::WriteBytes___STATIC__VOID__U4__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::GetSize___STATIC__I4,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_RTC::Native_RTC_SetAlarm___STATIC__VOID__U1__U1__U1__U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_RTC::Native_RTC_GetAlarm___STATIC__I8,
NULL,
NULL,
NULL,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceUniqueId___STATIC__VOID__SZARRAY_U1,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceId___STATIC__U4,
Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_Utilities::NativeGetDeviceRevisionId___STATIC__U4,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Stm32 =
{
"nanoFramework.Hardware.Stm32",
0x8D551100,
method_lookup,
{ 1, 0, 2, 10 }
};
|
Update nanoFramework.Hardware.Stm32 version to 1.0.2-preview-010 ***NO_CI*** (#998)
|
Update nanoFramework.Hardware.Stm32 version to 1.0.2-preview-010 ***NO_CI*** (#998)
|
C++
|
mit
|
nanoframework/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter
|
cbc6c142c4eedae30bd752ec755b1af0b1a860f6
|
video/screenshare_loopback.cc
|
video/screenshare_loopback.cc
|
/*
* Copyright (c) 2015 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 <stdio.h>
#include <map>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/frame_generator.h"
#include "webrtc/test/frame_generator_capturer.h"
#include "webrtc/test/run_test.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
#include "webrtc/video/video_send_stream.h"
namespace webrtc {
namespace flags {
// Fixed for prerecorded screenshare content.
size_t Width() {
return 1850;
}
size_t Height() {
return 1110;
}
DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
return static_cast<size_t>(FLAGS_min_bitrate);
}
DEFINE_int32(tl0_bitrate, 100, "Temporal layer 0 target bitrate.");
size_t StartBitrate() {
return static_cast<size_t>(FLAGS_tl0_bitrate);
}
DEFINE_int32(tl1_bitrate, 1000, "Temporal layer 1 target bitrate.");
size_t MaxBitrate() {
return static_cast<size_t>(FLAGS_tl1_bitrate);
}
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrate() {
return FLAGS_min_transmit_bitrate;
}
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
} // namespace flags
class ScreenshareLoopback : public test::Loopback {
public:
explicit ScreenshareLoopback(const Config& config) : Loopback(config) {}
virtual ~ScreenshareLoopback() {}
protected:
VideoEncoderConfig CreateEncoderConfig() override {
VideoEncoderConfig encoder_config(test::Loopback::CreateEncoderConfig());
VideoStream* stream = &encoder_config.streams[0];
encoder_config.content_type = VideoEncoderConfig::ContentType::kScreen;
encoder_config.min_transmit_bitrate_bps = flags::MinTransmitBitrate();
VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
vp8_settings.denoisingOn = false;
vp8_settings.frameDroppingOn = false;
vp8_settings.numberOfTemporalLayers = 2;
encoder_config.encoder_specific_settings = &vp8_settings;
stream->temporal_layer_thresholds_bps.clear();
stream->target_bitrate_bps =
static_cast<int>(config_.start_bitrate_kbps) * 1000;
stream->temporal_layer_thresholds_bps.push_back(stream->target_bitrate_bps);
return encoder_config;
}
test::VideoCapturer* CreateCapturer(VideoSendStream* send_stream) override {
std::vector<std::string> slides;
slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));
test::FrameGenerator* frame_generator =
test::FrameGenerator::CreateFromYuvFile(
slides, flags::Width(), flags::Height(), 10 * flags::Fps());
test::FrameGeneratorCapturer* capturer(new test::FrameGeneratorCapturer(
clock_, send_stream->Input(), frame_generator, flags::Fps()));
EXPECT_TRUE(capturer->Init());
return capturer;
}
};
void Loopback() {
test::Loopback::Config config{flags::Width(),
flags::Height(),
flags::Fps(),
flags::MinBitrate(),
flags::StartBitrate(),
flags::MaxBitrate(),
flags::MinTransmitBitrate(),
flags::Codec(),
flags::LossPercent(),
flags::LinkCapacity(),
flags::QueueSize(),
flags::AvgPropagationDelayMs(),
flags::StdPropagationDelayMs(),
flags::FLAGS_logs};
ScreenshareLoopback loopback(config);
loopback.Run();
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
|
/*
* Copyright (c) 2015 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 <stdio.h>
#include <map>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/frame_generator.h"
#include "webrtc/test/frame_generator_capturer.h"
#include "webrtc/test/run_test.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
#include "webrtc/video/video_send_stream.h"
namespace webrtc {
namespace flags {
// Fixed for prerecorded screenshare content.
size_t Width() {
return 1850;
}
size_t Height() {
return 1110;
}
DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
return static_cast<size_t>(FLAGS_min_bitrate);
}
DEFINE_int32(tl0_bitrate, 100, "Temporal layer 0 target bitrate.");
size_t StartBitrate() {
return static_cast<size_t>(FLAGS_tl0_bitrate);
}
DEFINE_int32(tl1_bitrate, 1000, "Temporal layer 1 target bitrate.");
size_t MaxBitrate() {
return static_cast<size_t>(FLAGS_tl1_bitrate);
}
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrate() {
return FLAGS_min_transmit_bitrate;
}
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
} // namespace flags
class ScreenshareLoopback : public test::Loopback {
public:
explicit ScreenshareLoopback(const Config& config) : Loopback(config) {
vp8_settings_ = VideoEncoder::GetDefaultVp8Settings();
vp8_settings_.denoisingOn = false;
vp8_settings_.frameDroppingOn = false;
vp8_settings_.numberOfTemporalLayers = 2;
}
virtual ~ScreenshareLoopback() {}
protected:
VideoEncoderConfig CreateEncoderConfig() override {
VideoEncoderConfig encoder_config(test::Loopback::CreateEncoderConfig());
VideoStream* stream = &encoder_config.streams[0];
encoder_config.content_type = VideoEncoderConfig::ContentType::kScreen;
encoder_config.min_transmit_bitrate_bps = flags::MinTransmitBitrate();
encoder_config.encoder_specific_settings = &vp8_settings_;
stream->temporal_layer_thresholds_bps.clear();
stream->target_bitrate_bps =
static_cast<int>(config_.start_bitrate_kbps) * 1000;
stream->temporal_layer_thresholds_bps.push_back(stream->target_bitrate_bps);
return encoder_config;
}
test::VideoCapturer* CreateCapturer(VideoSendStream* send_stream) override {
std::vector<std::string> slides;
slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));
test::FrameGenerator* frame_generator =
test::FrameGenerator::CreateFromYuvFile(
slides, flags::Width(), flags::Height(), 10 * flags::Fps());
test::FrameGeneratorCapturer* capturer(new test::FrameGeneratorCapturer(
clock_, send_stream->Input(), frame_generator, flags::Fps()));
EXPECT_TRUE(capturer->Init());
return capturer;
}
VideoCodecVP8 vp8_settings_;
};
void Loopback() {
test::Loopback::Config config{flags::Width(),
flags::Height(),
flags::Fps(),
flags::MinBitrate(),
flags::StartBitrate(),
flags::MaxBitrate(),
flags::MinTransmitBitrate(),
flags::Codec(),
flags::LossPercent(),
flags::LinkCapacity(),
flags::QueueSize(),
flags::AvgPropagationDelayMs(),
flags::StdPropagationDelayMs(),
flags::FLAGS_logs};
ScreenshareLoopback loopback(config);
loopback.Run();
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
|
Fix dangling pointer in screenshare_loopback
|
Fix dangling pointer in screenshare_loopback
BUG=
[email protected]
Review URL: https://webrtc-codereview.appspot.com/52369004
Cr-Original-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#9098}
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: 9d657cfd664122541086e5ab7ca19b25f1c4b90e
|
C++
|
bsd-3-clause
|
sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc,sippet/webrtc
|
f2cbf20ada4e4505b0c748e82144e8170bda2fb1
|
ch13/ex13_40.cpp
|
ch13/ex13_40.cpp
|
//
// ex13_40.cpp
// Exercise 13.40
//
// Created by pezy on 2/3/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Add a constructor that takes an initializer_list<string> to your StrVec class.
//
#include "ex13_40.h"
void StrVec::push_back(const std::string &s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*>
StrVec::alloc_n_copy(const std::string *b, const std::string *e)
{
auto data = alloc.allocate(e-b);
return { data, std::uninitialized_copy(b, e, data) };
}
void StrVec::free()
{
if (elements) {
for (auto p = first_free; p != elements;)
alloc.destroy(--p);
alloc.deallocate(elements, cap - elements);
}
}
void StrVec::range_initialize(const std::string *first, const std::string *last)
{
auto newdata = alloc_n_copy(first, last);
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(const StrVec &rhs)
{
range_initialize(rhs.begin(), rhs.end());
}
StrVec::StrVec(std::initializer_list<std::string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator = (const StrVec &rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string &s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count)
alloc.destroy(--first_free);
}
}
int main()
{
return 0;
}
|
//
// ex13_40.cpp
// Exercise 13.40
//
// Created by pezy on 2/3/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Add a constructor that takes an initializer_list<string> to your StrVec class.
//
#include "ex13_40.h"
void StrVec::push_back(const std::string &s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*>
StrVec::alloc_n_copy(const std::string *b, const std::string *e)
{
auto data = alloc.allocate(e - b);
return{ data, std::uninitialized_copy(b, e, data) };
}
void StrVec::free()
{
if (elements) {
for (auto p = first_free; p != elements;)
alloc.destroy(--p);
alloc.deallocate(elements, cap - elements);
}
}
void StrVec::range_initialize(const std::string *first, const std::string *last)
{
auto newdata = alloc_n_copy(first, last);
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(const StrVec &rhs)
{
range_initialize(rhs.begin(), rhs.end());
}
StrVec::StrVec(std::initializer_list<std::string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator = (const StrVec &rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string &s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count)
alloc.destroy(--first_free);
}
}
int main()
{
return 0;
}
|
Update ex13_40.cpp
|
Update ex13_40.cpp
|
C++
|
cc0-1.0
|
MojieBuddhist/Cpp-Primer,tre-pengxu/Cpp-Primer,andersy005/Cpp-Primer,seekertang/Cpp-Primer,Fenolona/Cpp-Primer,seekertang/Cpp-Primer,OlafLee/Cpp-Primer,Soyn/Cpp-Primer,theneversky/Cpp-Primer,Soyn/Cpp-Primer,AndychenCL/Cpp-Primer,wangqc/Cpp-Primer,LiaoPan/Cpp-Primer,Jinpeiqi/Cpp-Primer,XDXX/Cpp-Primer,XDXX/Cpp-Primer,zhuanggengzhen/Cpp-Primer-1,jiutianhuayu/Cpp-Primer,sin-zx/Cpp-Primer,coldmanck/Cpp-Primer,Fenolona/Cpp-Primer,AwesomePH/Cpp-Primer,Mooophy/Cpp-Primer,AndychenCL/Cpp-Primer,ricardousp/Cpp-Primer,andersy005/Cpp-Primer,fzls/Cpp-Primer,Allianzcortex/Cpp-Primer,frank67/Cpp-Primer,zhuanggengzhen/Cpp-Primer-1,buptfb/Cpp-Primer,Squawk09/Cpp-Primer,clearScreenZJ/Cpp-Primer,jasonchenzhou/Cpp-Primer,theneversky/Cpp-Primer,Squawk09/Cpp-Primer,singleman/Cpp-Primer,codetiger7/Cpp-Primer,jiutianhuayu/Cpp-Primer,sunlianqiang/Cpp-Primer,suesai/Cpp-Primer,AwesomePH/Cpp-Primer,kevinzhang2012/Cpp-Primer,honestme/Cpp-Primer,MojieBuddhist/Cpp-Primer,Nwpuer/Cpp-Primer,Mugurell/Cpp-Primer,IBYoung/Cpp-Primer,sunlianqiang/Cpp-Primer,kevinzhang2012/Cpp-Primer,kevinzhang1986/Cpp-Primer,honestme/Cpp-Primer,sanerror/Cpp-Primer,wy7980/Cpp-Primer,coldmanck/Cpp-Primer,suesai/Cpp-Primer,sigma-random/Cpp-Primer,jasonchenzhou/Cpp-Primer,frank67/Cpp-Primer,opensourceDA/Cpp-Primer,Mooophy/Cpp-Primer,kevinzhang1986/Cpp-Primer,sanerror/Cpp-Primer,Jinpeiqi/Cpp-Primer
|
393ec018c46827b1000fa56c9cabe5860927ab33
|
webkit/glue/plugins/pepper_char_set.cc
|
webkit/glue/plugins/pepper_char_set.cc
|
// 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 "webkit/glue/plugins/pepper_char_set.h"
#include <stdlib.h>
#include "base/i18n/icu_string_conversions.h"
#include "third_party/ppapi/c/ppb_char_set.h"
#include "unicode/ucnv.h"
#include "unicode/ucnv_cb.h"
#include "unicode/ucnv_err.h"
#include "unicode/ustring.h"
namespace pepper {
namespace {
// Converts the given PP error handling behavior to the version in base,
// placing the result in |*result| and returning true on success. Returns false
// if the enum is invalid.
bool PPToBaseConversionError(PP_CharSet_ConversionError on_error,
base::OnStringConversionError::Type* result) {
switch (on_error) {
case PP_CHARSET_CONVERSIONERROR_FAIL:
*result = base::OnStringConversionError::FAIL;
return true;
case PP_CHARSET_CONVERSIONERROR_SKIP:
*result = base::OnStringConversionError::SKIP;
return true;
case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE:
*result = base::OnStringConversionError::SUBSTITUTE;
return true;
default:
return false;
}
}
// The "substitution" behavior of this function does not match the
// implementation in base, so we partially duplicate the code from
// icu_string_conversions.cc with the correct error handling setup required
// by this pepper interface.
char* UTF16ToCharSet(const uint16_t* utf16, uint32_t utf16_len,
const char* output_char_set,
PP_CharSet_ConversionError on_error,
uint32_t* output_length) {
*output_length = 0;
UErrorCode status = U_ZERO_ERROR;
UConverter* converter = ucnv_open(output_char_set, &status);
if (!U_SUCCESS(status))
return NULL;
int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(utf16_len,
ucnv_getMaxCharSize(converter));
// Setup our error handler.
switch (on_error) {
case PP_CHARSET_CONVERSIONERROR_FAIL:
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, 0,
NULL, NULL, &status);
break;
case PP_CHARSET_CONVERSIONERROR_SKIP:
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, 0,
NULL, NULL, &status);
break;
case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE: {
// ICU sets the substitution char for some character sets (like latin1)
// to be the ASCII "substitution character" (26). We want to use '?'
// instead for backwards-compat with Windows behavior.
char subst_chars[32];
int8_t subst_chars_len = 32;
ucnv_getSubstChars(converter, subst_chars, &subst_chars_len, &status);
if (subst_chars_len == 1 && subst_chars[0] == 26) {
// Override to the question mark character if possible. When using
// setSubstString, the input is a Unicode character. The function will
// try to convert it to the destination character set and fail if that
// can not be converted to the destination character set.
//
// We just ignore any failure. If the dest char set has no
// representation for '?', then we'll just stick to the ICU default
// substitution character.
UErrorCode subst_status = U_ZERO_ERROR;
UChar question_mark = '?';
ucnv_setSubstString(converter, &question_mark, 1, &subst_status);
}
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0,
NULL, NULL, &status);
break;
}
default:
return NULL;
}
// ucnv_fromUChars returns size not including terminating null.
char* encoded = static_cast<char*>(malloc(encoded_max_length + 1));
int actual_size = ucnv_fromUChars(converter, encoded,
encoded_max_length, utf16, utf16_len, &status);
ucnv_close(converter);
if (!U_SUCCESS(status)) {
free(encoded);
return NULL;
}
encoded[actual_size] = 0;
*output_length = actual_size;
return encoded;
}
uint16_t* CharSetToUTF16(const char* input, uint32_t input_len,
const char* input_char_set,
PP_CharSet_ConversionError on_error,
uint32_t* output_length) {
*output_length = 0;
base::OnStringConversionError::Type base_on_error;
if (!PPToBaseConversionError(on_error, &base_on_error))
return NULL; // Invalid enum value.
// We can convert this call to the implementation in base to avoid code
// duplication, although this does introduce an extra copy of the data.
string16 output;
if (!base::CodepageToUTF16(std::string(input, input_len), input_char_set,
base_on_error, &output))
return NULL;
uint16_t* ret_buf = static_cast<uint16_t*>(
malloc((output.size() + 1) * sizeof(uint16_t)));
if (!ret_buf)
return NULL;
*output_length = static_cast<uint32_t>(output.size());
memcpy(ret_buf, output.c_str(), (output.size() + 1) * sizeof(uint16_t));
return ret_buf;
}
PP_Var GetDefaultCodePageForUILanguage() {
// TODO(brettw) bug 52865: Implement this function.
return PP_MakeVoid();
}
const PPB_CharSetDev ppb_charset = {
&UTF16ToCharSet,
&CharSetToUTF16,
&GetDefaultCodePageForUILanguage
};
} // namespace
// static
const PPB_CharSetDev* CharSet::GetInterface() {
return &ppb_charset;
}
} // namespace pepper
|
// 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 "webkit/glue/plugins/pepper_char_set.h"
#include <stdlib.h>
#include "base/i18n/icu_string_conversions.h"
#include "third_party/ppapi/c/ppb_char_set.h"
#include "unicode/ucnv.h"
#include "unicode/ucnv_cb.h"
#include "unicode/ucnv_err.h"
#include "unicode/ustring.h"
namespace pepper {
namespace {
// Converts the given PP error handling behavior to the version in base,
// placing the result in |*result| and returning true on success. Returns false
// if the enum is invalid.
bool PPToBaseConversionError(PP_CharSet_ConversionError on_error,
base::OnStringConversionError::Type* result) {
switch (on_error) {
case PP_CHARSET_CONVERSIONERROR_FAIL:
*result = base::OnStringConversionError::FAIL;
return true;
case PP_CHARSET_CONVERSIONERROR_SKIP:
*result = base::OnStringConversionError::SKIP;
return true;
case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE:
*result = base::OnStringConversionError::SUBSTITUTE;
return true;
default:
return false;
}
}
// The "substitution" behavior of this function does not match the
// implementation in base, so we partially duplicate the code from
// icu_string_conversions.cc with the correct error handling setup required
// by this pepper interface.
char* UTF16ToCharSet(const uint16_t* utf16, uint32_t utf16_len,
const char* output_char_set,
PP_CharSet_ConversionError on_error,
uint32_t* output_length) {
*output_length = 0;
UErrorCode status = U_ZERO_ERROR;
UConverter* converter = ucnv_open(output_char_set, &status);
if (!U_SUCCESS(status))
return NULL;
int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(utf16_len,
ucnv_getMaxCharSize(converter));
// Setup our error handler.
switch (on_error) {
case PP_CHARSET_CONVERSIONERROR_FAIL:
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, 0,
NULL, NULL, &status);
break;
case PP_CHARSET_CONVERSIONERROR_SKIP:
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, 0,
NULL, NULL, &status);
break;
case PP_CHARSET_CONVERSIONERROR_SUBSTITUTE: {
// ICU sets the substitution char for some character sets (like latin1)
// to be the ASCII "substitution character" (26). We want to use '?'
// instead for backwards-compat with Windows behavior.
char subst_chars[32];
int8_t subst_chars_len = 32;
ucnv_getSubstChars(converter, subst_chars, &subst_chars_len, &status);
if (subst_chars_len == 1 && subst_chars[0] == 26) {
// Override to the question mark character if possible. When using
// setSubstString, the input is a Unicode character. The function will
// try to convert it to the destination character set and fail if that
// can not be converted to the destination character set.
//
// We just ignore any failure. If the dest char set has no
// representation for '?', then we'll just stick to the ICU default
// substitution character.
UErrorCode subst_status = U_ZERO_ERROR;
UChar question_mark = '?';
ucnv_setSubstString(converter, &question_mark, 1, &subst_status);
}
ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SUBSTITUTE, 0,
NULL, NULL, &status);
break;
}
default:
return NULL;
}
// ucnv_fromUChars returns size not including terminating null.
char* encoded = static_cast<char*>(malloc(encoded_max_length + 1));
int actual_size = ucnv_fromUChars(converter, encoded,
encoded_max_length, reinterpret_cast<const UChar*>(utf16), utf16_len,
&status);
ucnv_close(converter);
if (!U_SUCCESS(status)) {
free(encoded);
return NULL;
}
encoded[actual_size] = 0;
*output_length = actual_size;
return encoded;
}
uint16_t* CharSetToUTF16(const char* input, uint32_t input_len,
const char* input_char_set,
PP_CharSet_ConversionError on_error,
uint32_t* output_length) {
*output_length = 0;
base::OnStringConversionError::Type base_on_error;
if (!PPToBaseConversionError(on_error, &base_on_error))
return NULL; // Invalid enum value.
// We can convert this call to the implementation in base to avoid code
// duplication, although this does introduce an extra copy of the data.
string16 output;
if (!base::CodepageToUTF16(std::string(input, input_len), input_char_set,
base_on_error, &output))
return NULL;
uint16_t* ret_buf = static_cast<uint16_t*>(
malloc((output.size() + 1) * sizeof(uint16_t)));
if (!ret_buf)
return NULL;
*output_length = static_cast<uint32_t>(output.size());
memcpy(ret_buf, output.c_str(), (output.size() + 1) * sizeof(uint16_t));
return ret_buf;
}
PP_Var GetDefaultCodePageForUILanguage() {
// TODO(brettw) bug 52865: Implement this function.
return PP_MakeVoid();
}
const PPB_CharSetDev ppb_charset = {
&UTF16ToCharSet,
&CharSetToUTF16,
&GetDefaultCodePageForUILanguage
};
} // namespace
// static
const PPB_CharSetDev* CharSet::GetInterface() {
return &ppb_charset;
}
} // namespace pepper
|
Fix the windows build by casting for ICU.
|
Fix the windows build by casting for ICU.
TEST=none
BUG=none
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@57015 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
88e703b8d14f5dcbe059c04c7c095d6f213055dc
|
src/d8-readline.cc
|
src/d8-readline.cc
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio> // NOLINT
#include <string.h> // NOLINT
#include <readline/readline.h> // NOLINT
#include <readline/history.h> // NOLINT
// The readline includes leaves RETURN defined which breaks V8 compilation.
#undef RETURN
#include "d8.h"
// There are incompatibilities between different versions and different
// implementations of readline. This smooths out one known incompatibility.
#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif
namespace v8 {
class ReadLineEditor: public LineEditor {
public:
ReadLineEditor() : LineEditor(LineEditor::READLINE, "readline") { }
virtual Handle<String> Prompt(const char* prompt);
virtual bool Open(Isolate* isolate);
virtual bool Close();
virtual void AddHistory(const char* str);
static const char* kHistoryFileName;
static const int kMaxHistoryEntries;
private:
#ifndef V8_SHARED
static char** AttemptedCompletion(const char* text, int start, int end);
static char* CompletionGenerator(const char* text, int state);
#endif // V8_SHARED
static char kWordBreakCharacters[];
Isolate* isolate_;
};
static ReadLineEditor read_line_editor;
char ReadLineEditor::kWordBreakCharacters[] = {' ', '\t', '\n', '"',
'\\', '\'', '`', '@', '.', '>', '<', '=', ';', '|', '&', '{', '(',
'\0'};
const char* ReadLineEditor::kHistoryFileName = ".d8_history";
const int ReadLineEditor::kMaxHistoryEntries = 1000;
bool ReadLineEditor::Open(Isolate* isolate) {
isolate_ = isolate;
rl_initialize();
#ifdef V8_SHARED
// Don't do completion on shared library mode
// http://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC24
rl_bind_key('\t', rl_insert);
#else
rl_attempted_completion_function = AttemptedCompletion;
#endif // V8_SHARED
rl_completer_word_break_characters = kWordBreakCharacters;
rl_bind_key('\t', rl_complete);
using_history();
stifle_history(kMaxHistoryEntries);
return read_history(kHistoryFileName) == 0;
}
bool ReadLineEditor::Close() {
return write_history(kHistoryFileName) == 0;
}
Handle<String> ReadLineEditor::Prompt(const char* prompt) {
char* result = NULL;
{ // Release lock for blocking input.
Unlocker unlock(Isolate::GetCurrent());
result = readline(prompt);
}
if (result == NULL) return Handle<String>();
AddHistory(result);
return String::NewFromUtf8(isolate_, result);
}
void ReadLineEditor::AddHistory(const char* str) {
// Do not record empty input.
if (strlen(str) == 0) return;
// Remove duplicate history entry.
history_set_pos(history_length-1);
if (current_history()) {
do {
if (strcmp(current_history()->line, str) == 0) {
remove_history(where_history());
break;
}
} while (previous_history());
}
add_history(str);
}
#ifndef V8_SHARED
char** ReadLineEditor::AttemptedCompletion(const char* text,
int start,
int end) {
char** result = completion_matches(text, CompletionGenerator);
rl_attempted_completion_over = true;
return result;
}
char* ReadLineEditor::CompletionGenerator(const char* text, int state) {
static unsigned current_index;
static Persistent<Array> current_completions;
Isolate* isolate = read_line_editor.isolate_;
Locker lock(isolate);
HandleScope scope(isolate);
Handle<Array> completions;
if (state == 0) {
Local<String> full_text = String::NewFromUtf8(isolate,
rl_line_buffer,
String::kNormalString,
rl_point);
completions = Shell::GetCompletions(isolate,
String::NewFromUtf8(isolate, text),
full_text);
current_completions.Reset(isolate, completions);
current_index = 0;
} else {
completions = Local<Array>::New(isolate, current_completions);
}
if (current_index < completions->Length()) {
Handle<Integer> index = Integer::New(current_index);
Handle<Value> str_obj = completions->Get(index);
current_index++;
String::Utf8Value str(str_obj);
return strdup(*str);
} else {
current_completions.Reset();
return NULL;
}
}
#endif // V8_SHARED
} // namespace v8
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdio> // NOLINT
#include <string.h> // NOLINT
#include <readline/readline.h> // NOLINT
#include <readline/history.h> // NOLINT
// The readline includes leaves RETURN defined which breaks V8 compilation.
#undef RETURN
#include "d8.h"
// There are incompatibilities between different versions and different
// implementations of readline. This smooths out one known incompatibility.
#if RL_READLINE_VERSION >= 0x0500
#define completion_matches rl_completion_matches
#endif
namespace v8 {
class ReadLineEditor: public LineEditor {
public:
ReadLineEditor() : LineEditor(LineEditor::READLINE, "readline") { }
virtual Handle<String> Prompt(const char* prompt);
virtual bool Open(Isolate* isolate);
virtual bool Close();
virtual void AddHistory(const char* str);
static const char* kHistoryFileName;
static const int kMaxHistoryEntries;
private:
#ifndef V8_SHARED
static char** AttemptedCompletion(const char* text, int start, int end);
static char* CompletionGenerator(const char* text, int state);
#endif // V8_SHARED
static char kWordBreakCharacters[];
Isolate* isolate_;
};
static ReadLineEditor read_line_editor;
char ReadLineEditor::kWordBreakCharacters[] = {' ', '\t', '\n', '"',
'\\', '\'', '`', '@', '.', '>', '<', '=', ';', '|', '&', '{', '(',
'\0'};
const char* ReadLineEditor::kHistoryFileName = ".d8_history";
const int ReadLineEditor::kMaxHistoryEntries = 1000;
bool ReadLineEditor::Open(Isolate* isolate) {
isolate_ = isolate;
rl_initialize();
#ifdef V8_SHARED
// Don't do completion on shared library mode
// http://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC24
rl_bind_key('\t', rl_insert);
#else
rl_attempted_completion_function = AttemptedCompletion;
#endif // V8_SHARED
rl_completer_word_break_characters = kWordBreakCharacters;
rl_bind_key('\t', rl_complete);
using_history();
stifle_history(kMaxHistoryEntries);
return read_history(kHistoryFileName) == 0;
}
bool ReadLineEditor::Close() {
return write_history(kHistoryFileName) == 0;
}
Handle<String> ReadLineEditor::Prompt(const char* prompt) {
char* result = NULL;
{ // Release lock for blocking input.
Unlocker unlock(Isolate::GetCurrent());
result = readline(prompt);
}
if (result == NULL) return Handle<String>();
AddHistory(result);
return String::NewFromUtf8(isolate_, result);
}
void ReadLineEditor::AddHistory(const char* str) {
// Do not record empty input.
if (strlen(str) == 0) return;
// Remove duplicate history entry.
history_set_pos(history_length-1);
if (current_history()) {
do {
if (strcmp(current_history()->line, str) == 0) {
remove_history(where_history());
break;
}
} while (previous_history());
}
add_history(str);
}
#ifndef V8_SHARED
char** ReadLineEditor::AttemptedCompletion(const char* text,
int start,
int end) {
char** result = completion_matches(text, CompletionGenerator);
rl_attempted_completion_over = true;
return result;
}
char* ReadLineEditor::CompletionGenerator(const char* text, int state) {
static unsigned current_index;
static Persistent<Array> current_completions;
Isolate* isolate = read_line_editor.isolate_;
Locker lock(isolate);
HandleScope scope(isolate);
Handle<Array> completions;
if (state == 0) {
Local<String> full_text = String::NewFromUtf8(isolate,
rl_line_buffer,
String::kNormalString,
rl_point);
completions = Shell::GetCompletions(isolate,
String::NewFromUtf8(isolate, text),
full_text);
current_completions.Reset(isolate, completions);
current_index = 0;
} else {
completions = Local<Array>::New(isolate, current_completions);
}
if (current_index < completions->Length()) {
Handle<Integer> index = Integer::New(isolate, current_index);
Handle<Value> str_obj = completions->Get(index);
current_index++;
String::Utf8Value str(str_obj);
return strdup(*str);
} else {
current_completions.Reset();
return NULL;
}
}
#endif // V8_SHARED
} // namespace v8
|
Fix building d8 with readline support due to API changes
|
Fix building d8 with readline support due to API changes
After recent API changes, d8 will fail to build when passing
"console=readline". This patch makes d8 work with readline again.
[email protected]
Review URL: https://codereview.chromium.org/125043006
Patch from Adrian Perez de Castro <[email protected]>.
git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@18457 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
|
C++
|
mit
|
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
|
c3f0c037c7f83c42c3dfad4a35cb29cfebe8e740
|
indra/llmessage/llavatarnamecache.cpp
|
indra/llmessage/llavatarnamecache.cpp
|
/**
* @file llavatarnamecache.cpp
* @brief Provides lookup of avatar SLIDs ("bobsmith123") and display names
* ("James Cook") from avatar UUIDs.
*
* $LicenseInfo:firstyear=2010&license=viewergpl$
*
* Copyright (c) 2010, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llavatarnamecache.h"
#include "llcachename.h" // until we get our own web service
#include <cctype> // tolower()
namespace LLAvatarNameCache
{
std::map<LLUUID, LLAvatarName> sCache;
}
static std::string slid_from_full_name(const std::string& full_name)
{
std::string id = full_name;
std::string::size_type end = id.length();
for (std::string::size_type i = 0; i < end; ++i)
{
if (id[i] == ' ')
id[i] = '.';
else
id[i] = tolower(id[i]);
}
return id;
}
void LLAvatarNameCache::initClass()
{
// HACK - prepopulate the cache
LLAvatarName name;
LLUUID id;
name.mSLID = "miyazaki23";
const unsigned char miyazaki_hayao_san[]
= { 0xE5, 0xAE, 0xAE, 0xE5, 0xB4, 0x8E,
0xE9, 0xA7, 0xBF,
0xE3, 0x81, 0x95, 0xE3, 0x82, 0x93, '\0' };
name.mDisplayName = (const char*)miyazaki_hayao_san;
name.mBadge = "Person_Check";
sCache[LLUUID("27888d5f-4ddb-4df3-ad36-a1483ce0b3d9")] = name;
name.mSLID = "jim.linden";
name.mDisplayName = "Jim Jenkins";
name.mBadge = "Person_Star";
sCache[LLUUID("3e5bf676-3577-c9ee-9fac-10df430015a1")] = name;
name.mSLID = "james.linden";
const unsigned char jose_sanchez[] =
{ 'J','o','s',0xC3,0xA9,' ','S','a','n','c','h','e','z', '\0' };
name.mDisplayName = (const char*)jose_sanchez;
name.mBadge = "35f217a3-f618-49cf-bbca-c86d486551a9"; // IMG_SHOT
sCache[LLUUID("a2e76fcd-9360-4f6d-a924-938f923df11a")] = name;
name.mSLID = "bobsmith123";
name.mDisplayName = (const char*)jose_sanchez;
name.mBadge = "";
sCache[LLUUID("a23fff6c-80ae-4997-9253-48272fd01d3c")] = name;
name.mSLID = "hamilton.linden";
name.mDisplayName = "Hamilton Hitchings";
name.mBadge = "Person_Star";
sCache[LLUUID("3f7ced39-5e38-4fdd-90f2-423560b1e6e2")] = name;
name.mSLID = "rome.linden";
name.mDisplayName = "Rome Portlock";
name.mBadge = "Person_Star";
sCache[LLUUID("537da1e1-a89f-4f9b-9056-b1f0757ccdd0")] = name;
name.mSLID = "m.linden";
name.mDisplayName = "Mark Kingdon";
name.mBadge = "Person_Star";
sCache[LLUUID("244195d6-c9b7-4fd6-9229-c3a8b2e60e81")] = name;
name.mSLID = "t.linden";
name.mDisplayName = "Tom Hale";
name.mBadge = "Person_Star";
sCache[LLUUID("49856302-98d4-4e32-b5e9-035e5b4e83a4")] = name;
name.mSLID = "callen.linden";
name.mDisplayName = "Christina Allen";
name.mBadge = "Person_Star";
sCache[LLUUID("e6ed7825-708f-4c6b-b6a7-f3fe921a9176")] = name;
name.mSLID = "crimp.linden";
name.mDisplayName = "Chris Rimple";
name.mBadge = "Person_Star";
sCache[LLUUID("a7f0ac18-205f-41d2-b5b4-f75f096ae511")] = name;
}
void LLAvatarNameCache::cleanupClass()
{
}
void LLAvatarNameCache::importFile(std::istream& istr)
{
}
void LLAvatarNameCache::exportFile(std::ostream& ostr)
{
}
void LLAvatarNameCache::idle()
{
}
bool LLAvatarNameCache::get(const LLUUID& agent_id, LLAvatarName *av_name)
{
std::map<LLUUID,LLAvatarName>::iterator it = sCache.find(agent_id);
if (it != sCache.end())
{
*av_name = it->second;
return true;
}
// JAMESDEBUG Enable when we turn on display names.
//std::string full_name;
//if (gCacheName->getFullName(agent_id, full_name))
//{
// av_name->mSLID = slid_from_full_name(full_name);
// av_name->mDisplayName = full_name;
// av_name->mBadge = "Generic_Person";
// return true;
//}
return false;
}
void LLAvatarNameCache::get(const LLUUID& agent_id, name_cache_callback_t callback)
{
}
|
/**
* @file llavatarnamecache.cpp
* @brief Provides lookup of avatar SLIDs ("bobsmith123") and display names
* ("James Cook") from avatar UUIDs.
*
* $LicenseInfo:firstyear=2010&license=viewergpl$
*
* Copyright (c) 2010, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llavatarnamecache.h"
#include "llcachename.h" // until we get our own web service
#include <cctype> // tolower()
namespace LLAvatarNameCache
{
std::map<LLUUID, LLAvatarName> sCache;
}
// JAMESDEBUG re-enable when display names are turned on
//static std::string slid_from_full_name(const std::string& full_name)
//{
// std::string id = full_name;
// std::string::size_type end = id.length();
// for (std::string::size_type i = 0; i < end; ++i)
// {
// if (id[i] == ' ')
// id[i] = '.';
// else
// id[i] = tolower(id[i]);
// }
// return id;
//}
void LLAvatarNameCache::initClass()
{
// HACK - prepopulate the cache
LLAvatarName name;
LLUUID id;
name.mSLID = "miyazaki23";
const unsigned char miyazaki_hayao_san[]
= { 0xE5, 0xAE, 0xAE, 0xE5, 0xB4, 0x8E,
0xE9, 0xA7, 0xBF,
0xE3, 0x81, 0x95, 0xE3, 0x82, 0x93, '\0' };
name.mDisplayName = (const char*)miyazaki_hayao_san;
name.mBadge = "Person_Check";
sCache[LLUUID("27888d5f-4ddb-4df3-ad36-a1483ce0b3d9")] = name;
name.mSLID = "jim.linden";
name.mDisplayName = "Jim Jenkins";
name.mBadge = "Person_Star";
sCache[LLUUID("3e5bf676-3577-c9ee-9fac-10df430015a1")] = name;
name.mSLID = "james.linden";
const unsigned char jose_sanchez[] =
{ 'J','o','s',0xC3,0xA9,' ','S','a','n','c','h','e','z', '\0' };
name.mDisplayName = (const char*)jose_sanchez;
name.mBadge = "35f217a3-f618-49cf-bbca-c86d486551a9"; // IMG_SHOT
sCache[LLUUID("a2e76fcd-9360-4f6d-a924-938f923df11a")] = name;
name.mSLID = "bobsmith123";
name.mDisplayName = (const char*)jose_sanchez;
name.mBadge = "";
sCache[LLUUID("a23fff6c-80ae-4997-9253-48272fd01d3c")] = name;
name.mSLID = "hamilton.linden";
name.mDisplayName = "Hamilton Hitchings";
name.mBadge = "Person_Star";
sCache[LLUUID("3f7ced39-5e38-4fdd-90f2-423560b1e6e2")] = name;
name.mSLID = "rome.linden";
name.mDisplayName = "Rome Portlock";
name.mBadge = "Person_Star";
sCache[LLUUID("537da1e1-a89f-4f9b-9056-b1f0757ccdd0")] = name;
name.mSLID = "m.linden";
name.mDisplayName = "Mark Kingdon";
name.mBadge = "Person_Star";
sCache[LLUUID("244195d6-c9b7-4fd6-9229-c3a8b2e60e81")] = name;
name.mSLID = "t.linden";
name.mDisplayName = "Tom Hale";
name.mBadge = "Person_Star";
sCache[LLUUID("49856302-98d4-4e32-b5e9-035e5b4e83a4")] = name;
name.mSLID = "callen.linden";
name.mDisplayName = "Christina Allen";
name.mBadge = "Person_Star";
sCache[LLUUID("e6ed7825-708f-4c6b-b6a7-f3fe921a9176")] = name;
name.mSLID = "crimp.linden";
name.mDisplayName = "Chris Rimple";
name.mBadge = "Person_Star";
sCache[LLUUID("a7f0ac18-205f-41d2-b5b4-f75f096ae511")] = name;
}
void LLAvatarNameCache::cleanupClass()
{
}
void LLAvatarNameCache::importFile(std::istream& istr)
{
}
void LLAvatarNameCache::exportFile(std::ostream& ostr)
{
}
void LLAvatarNameCache::idle()
{
}
bool LLAvatarNameCache::get(const LLUUID& agent_id, LLAvatarName *av_name)
{
std::map<LLUUID,LLAvatarName>::iterator it = sCache.find(agent_id);
if (it != sCache.end())
{
*av_name = it->second;
return true;
}
// JAMESDEBUG Enable when we turn on display names.
//std::string full_name;
//if (gCacheName->getFullName(agent_id, full_name))
//{
// av_name->mSLID = slid_from_full_name(full_name);
// av_name->mDisplayName = full_name;
// av_name->mBadge = "Generic_Person";
// return true;
//}
return false;
}
void LLAvatarNameCache::get(const LLUUID& agent_id, name_cache_callback_t callback)
{
}
|
Fix Linux build warning/error for unused function
|
Fix Linux build warning/error for unused function
|
C++
|
lgpl-2.1
|
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
|
1413e53810244a88cbdbf8708c959712d51ceab5
|
PWG/EMCAL/EMCALtasks/AliEmcalCellMonitorTask.cxx
|
PWG/EMCAL/EMCALtasks/AliEmcalCellMonitorTask.cxx
|
#include <algorithm>
#include <map>
#include <vector>
#include <TArrayD.h>
#include <THashList.h>
#include <THistManager.h>
#include <TLinearBinning.h>
#include <TObjArray.h>
#include <TParameter.h>
#include "AliEMCALGeometry.h"
#include "AliEmcalCellMonitorTask.h"
#include "AliInputEventHandler.h"
#include "AliOADBContainer.h"
#include "AliVCaloCells.h"
#include "AliVEvent.h"
/// \cond CLASSIMP
ClassImp(AliEmcalCellMonitorTask)
/// \endcond
AliEmcalCellMonitorTask::AliEmcalCellMonitorTask() :
AliAnalysisTaskSE(),
fHistManager(nullptr),
fGeometry(nullptr),
fMinCellAmplitude(0),
fRequestTrigger(AliVEvent::kAnyINT),
fBadChannelContainer(""),
fTriggerString(""),
fNumberOfCells(12288),
fOldRun(-1),
fMaskedCells()
{
}
AliEmcalCellMonitorTask::AliEmcalCellMonitorTask(const char *name) :
AliAnalysisTaskSE(name),
fHistManager(nullptr),
fGeometry(nullptr),
fMinCellAmplitude(0),
fRequestTrigger(AliVEvent::kAnyINT),
fBadChannelContainer(""),
fTriggerString(""),
fNumberOfCells(12288),
fOldRun(-1),
fMaskedCells()
{
DefineOutput(1, TList::Class());
}
AliEmcalCellMonitorTask::~AliEmcalCellMonitorTask() {
if(fGeometry) delete fGeometry;
}
void AliEmcalCellMonitorTask::UserCreateOutputObjects(){
fHistManager = new THistManager("EMCALCellMonitor");
fHistManager->CreateTH1("cellMasking", "Monitoring for masked cells", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5));
fHistManager->CreateTH1("cellFrequency", "Frequency of cell firing", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5));
fHistManager->CreateTH2("cellAmplitude", "Energy distribution per cell", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5), AliEmcalCellMonitorAmplitudeBinning());
fHistManager->CreateTH2("cellAmplitudeCut", "Energy distribution per cell (after energy cut)", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5), AliEmcalCellMonitorAmplitudeBinning());
fHistManager->CreateTH2("cellTime", "Time distribution per cell", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 200, -1e-6, 1e-6);
fHistManager->CreateTH2("cellTimeOutlier", "Outlier time distribution per cell", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 100, 1e-6, 5e-5);
fHistManager->CreateTH2("cellTimeMain", "Time distribution per cell for the main bunch", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 150, -50e-9, 100e-9);
for(int ism = 0; ism < 20; ++ism){
fHistManager->CreateTH2(Form("cellAmpSM%d", ism), Form("Integrated cell amplitudes for SM %d; col; row", ism), 48, -0.5, 47.5, 24, -0.5, 23.5);
fHistManager->CreateTH2(Form("cellCountSM%d", ism), Form("Count rate per cell for SM %d; col; row", ism), 48, -0.5, 47.5, 24, -0.5, 23.5);
}
for(int ism = 0; ism < 20; ++ism){
fHistManager->CreateTH2(Form("cellAmpTimeCorrSM%d", ism), Form("Correlation between cell amplitude and time in Supermodule %d", ism), 1000, -5e-7, 5e-7, 1000, 0., 100.);
}
PostData(1, fHistManager->GetListOfHistograms());
}
void AliEmcalCellMonitorTask::UserExec(Option_t *){
if(!fGeometry) fGeometry = AliEMCALGeometry::GetInstanceFromRunNumber(fInputEvent->GetRunNumber());
// Run change
if(InputEvent()->GetRunNumber() != fOldRun){
if(fBadChannelContainer.Length()) LoadCellMasking();
for(auto cellID : fMaskedCells) fHistManager->FillTH1("cellMasking", cellID);
}
// Check trigger
if(!(fInputHandler->IsEventSelected() & fRequestTrigger)) return;
if(fTriggerString.Length()){
if(!TString(InputEvent()->GetFiredTriggerClasses()).Contains(fTriggerString)) return;
}
AliVCaloCells *emcalcells = fInputEvent->GetEMCALCells();
// input data
Short_t cellNumber;
Double_t amplitude, celltime, efrac;
Int_t mclabel;
Int_t sm, mod, meta, mphi, ieta, iphi;
for(int icell = 0; icell < emcalcells->GetNumberOfCells(); icell++){
emcalcells->GetCell(icell, cellNumber, amplitude, celltime, mclabel, efrac);
if(IsCellMasked(cellNumber)) continue;
fHistManager->FillTH2("cellAmplitude", cellNumber, amplitude);
if(amplitude < fMinCellAmplitude) continue;
fHistManager->FillTH1("cellAmplitudeCut", cellNumber, amplitude);
fHistManager->FillTH1("cellFrequency", cellNumber);
fHistManager->FillTH2("cellTime", cellNumber, celltime);
if(celltime >= 1e-6) fHistManager->FillTH2("cellTimeOutlier", cellNumber, celltime);
if(celltime > -5e-8 && celltime < 1e-7) fHistManager->FillTH2("cellTimeMain", cellNumber, celltime);
// Get Cell index in eta-phi of sm
fGeometry->GetCellIndex(cellNumber, sm, mod, mphi, meta);
fGeometry->GetCellPhiEtaIndexInSModule(sm, mod, mphi, meta, iphi, ieta);
fHistManager->FillTH2(Form("cellCountSM%d", sm), ieta, iphi);
fHistManager->FillTH2(Form("cellAmpSM%d", sm), ieta, iphi, amplitude);
fHistManager->FillTH2(Form("cellAmpTimeCorrSM%d", sm), celltime, amplitude);
}
PostData(1, fHistManager->GetListOfHistograms());
}
void AliEmcalCellMonitorTask::LoadCellMasking(){
fMaskedCells.clear();
AliOADBContainer contreader(fBadChannelContainer.Data());
TObjArray *rundata = dynamic_cast<TObjArray *>(contreader.GetObject(InputEvent()->GetRunNumber()));
if(!rundata) return;
for(TIter channeliter = TIter(rundata).Begin(); channeliter != TIter::End(); ++channeliter){
TParameter<int> *cellID = static_cast<TParameter<int> *>(*channeliter);
if(cellID) SetBadCell(cellID->GetVal());
}
}
void AliEmcalCellMonitorTask::SetBadCell(Int_t cellId){
if(std::find(fMaskedCells.begin(), fMaskedCells.end(), cellId) != fMaskedCells.end()) return;
fMaskedCells.push_back(cellId);
}
bool AliEmcalCellMonitorTask::IsCellMasked(Int_t cellId) const {
return (std::find(fMaskedCells.begin(), fMaskedCells.end(), cellId) != fMaskedCells.end());
}
AliEmcalCellMonitorTask::AliEmcalCellMonitorAmplitudeBinning::AliEmcalCellMonitorAmplitudeBinning():
TCustomBinning()
{
SetMinimum(0);
AddStep(1., 0.1);
AddStep(10., 0.5);
AddStep(20., 1.);
AddStep(50., 2.);
AddStep(100., 5.);
AddStep(200., 10.);
}
|
#include <algorithm>
#include <map>
#include <vector>
#include <TArrayD.h>
#include <TGrid.h>
#include <THashList.h>
#include <THistManager.h>
#include <TLinearBinning.h>
#include <TObjArray.h>
#include <TParameter.h>
#include "AliEMCALGeometry.h"
#include "AliEmcalCellMonitorTask.h"
#include "AliInputEventHandler.h"
#include "AliLog.h"
#include "AliOADBContainer.h"
#include "AliVCaloCells.h"
#include "AliVEvent.h"
/// \cond CLASSIMP
ClassImp(AliEmcalCellMonitorTask)
/// \endcond
AliEmcalCellMonitorTask::AliEmcalCellMonitorTask() :
AliAnalysisTaskSE(),
fHistManager(nullptr),
fGeometry(nullptr),
fMinCellAmplitude(0),
fRequestTrigger(AliVEvent::kAnyINT),
fBadChannelContainer(""),
fTriggerString(""),
fNumberOfCells(12288),
fOldRun(-1),
fMaskedCells()
{
}
AliEmcalCellMonitorTask::AliEmcalCellMonitorTask(const char *name) :
AliAnalysisTaskSE(name),
fHistManager(nullptr),
fGeometry(nullptr),
fMinCellAmplitude(0),
fRequestTrigger(AliVEvent::kAnyINT),
fBadChannelContainer(""),
fTriggerString(""),
fNumberOfCells(12288),
fOldRun(-1),
fMaskedCells()
{
DefineOutput(1, TList::Class());
}
AliEmcalCellMonitorTask::~AliEmcalCellMonitorTask() {
if(fGeometry) delete fGeometry;
}
void AliEmcalCellMonitorTask::UserCreateOutputObjects(){
fHistManager = new THistManager("EMCALCellMonitor");
fHistManager->CreateTH1("cellMasking", "Monitoring for masked cells", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5));
fHistManager->CreateTH1("cellFrequency", "Frequency of cell firing", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5));
fHistManager->CreateTH2("cellAmplitude", "Energy distribution per cell", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5), AliEmcalCellMonitorAmplitudeBinning());
fHistManager->CreateTH2("cellAmplitudeCut", "Energy distribution per cell (after energy cut)", TLinearBinning(fNumberOfCells, -0.5, fNumberOfCells - 0.5), AliEmcalCellMonitorAmplitudeBinning());
fHistManager->CreateTH2("cellTime", "Time distribution per cell", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 200, -1e-6, 1e-6);
fHistManager->CreateTH2("cellTimeOutlier", "Outlier time distribution per cell", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 100, 1e-6, 5e-5);
fHistManager->CreateTH2("cellTimeMain", "Time distribution per cell for the main bunch", fNumberOfCells, -0.5, fNumberOfCells - 0.5, 150, -50e-9, 100e-9);
for(int ism = 0; ism < 20; ++ism){
fHistManager->CreateTH2(Form("cellAmpSM%d", ism), Form("Integrated cell amplitudes for SM %d; col; row", ism), 48, -0.5, 47.5, 24, -0.5, 23.5);
fHistManager->CreateTH2(Form("cellCountSM%d", ism), Form("Count rate per cell for SM %d; col; row", ism), 48, -0.5, 47.5, 24, -0.5, 23.5);
}
for(int ism = 0; ism < 20; ++ism){
fHistManager->CreateTH2(Form("cellAmpTimeCorrSM%d", ism), Form("Correlation between cell amplitude and time in Supermodule %d", ism), 1000, -5e-7, 5e-7, 1000, 0., 100.);
}
PostData(1, fHistManager->GetListOfHistograms());
}
void AliEmcalCellMonitorTask::UserExec(Option_t *){
if(!fGeometry) fGeometry = AliEMCALGeometry::GetInstanceFromRunNumber(fInputEvent->GetRunNumber());
// Run change
if(InputEvent()->GetRunNumber() != fOldRun){
if(fBadChannelContainer.Length()) LoadCellMasking();
for(auto cellID : fMaskedCells) fHistManager->FillTH1("cellMasking", cellID);
fOldRun = InputEvent()->GetRunNumber();
}
// Check trigger
if(!(fInputHandler->IsEventSelected() & fRequestTrigger)) return;
if(fTriggerString.Length()){
if(!TString(InputEvent()->GetFiredTriggerClasses()).Contains(fTriggerString)) return;
}
AliVCaloCells *emcalcells = fInputEvent->GetEMCALCells();
// input data
Short_t cellNumber;
Double_t amplitude, celltime, efrac;
Int_t mclabel;
Int_t sm, mod, meta, mphi, ieta, iphi;
for(int icell = 0; icell < emcalcells->GetNumberOfCells(); icell++){
emcalcells->GetCell(icell, cellNumber, amplitude, celltime, mclabel, efrac);
if(IsCellMasked(cellNumber)) continue;
fHistManager->FillTH2("cellAmplitude", cellNumber, amplitude);
if(amplitude < fMinCellAmplitude) continue;
fHistManager->FillTH1("cellAmplitudeCut", cellNumber, amplitude);
fHistManager->FillTH1("cellFrequency", cellNumber);
fHistManager->FillTH2("cellTime", cellNumber, celltime);
if(celltime >= 1e-6) fHistManager->FillTH2("cellTimeOutlier", cellNumber, celltime);
if(celltime > -5e-8 && celltime < 1e-7) fHistManager->FillTH2("cellTimeMain", cellNumber, celltime);
// Get Cell index in eta-phi of sm
fGeometry->GetCellIndex(cellNumber, sm, mod, mphi, meta);
fGeometry->GetCellPhiEtaIndexInSModule(sm, mod, mphi, meta, iphi, ieta);
fHistManager->FillTH2(Form("cellCountSM%d", sm), ieta, iphi);
fHistManager->FillTH2(Form("cellAmpSM%d", sm), ieta, iphi, amplitude);
fHistManager->FillTH2(Form("cellAmpTimeCorrSM%d", sm), celltime, amplitude);
}
PostData(1, fHistManager->GetListOfHistograms());
}
void AliEmcalCellMonitorTask::LoadCellMasking(){
if(!fBadChannelContainer.Length()) return;
AliInfo(Form("Loading bad channel map from %s", fBadChannelContainer.Data()));
fMaskedCells.clear();
if(fBadChannelContainer.Contains("alien://") && ! gGrid) TGrid::Connect("alien://"); // Make sure alien connection is available as the AliOADBContainer doesn't handle it
AliOADBContainer contreader("EmcalBadChannelsAdditional");
contreader.InitFromFile(fBadChannelContainer.Data(), "EmcalBadChannelsAdditional");
TObjArray *rundata = dynamic_cast<TObjArray *>(contreader.GetObject(InputEvent()->GetRunNumber()));
if(!rundata) return;
for(TIter channeliter = TIter(rundata).Begin(); channeliter != TIter::End(); ++channeliter){
TParameter<int> *cellID = static_cast<TParameter<int> *>(*channeliter);
if(cellID) SetBadCell(cellID->GetVal());
}
}
void AliEmcalCellMonitorTask::SetBadCell(Int_t cellId){
if(std::find(fMaskedCells.begin(), fMaskedCells.end(), cellId) != fMaskedCells.end()) return;
fMaskedCells.push_back(cellId);
}
bool AliEmcalCellMonitorTask::IsCellMasked(Int_t cellId) const {
return (std::find(fMaskedCells.begin(), fMaskedCells.end(), cellId) != fMaskedCells.end());
}
AliEmcalCellMonitorTask::AliEmcalCellMonitorAmplitudeBinning::AliEmcalCellMonitorAmplitudeBinning():
TCustomBinning()
{
SetMinimum(0);
AddStep(1., 0.1);
AddStep(10., 0.5);
AddStep(20., 1.);
AddStep(50., 2.);
AddStep(100., 5.);
AddStep(200., 10.);
}
|
Add check for grid connectioon in case the OADB file with bad channels is taken from alien
|
Add check for grid connectioon in case the OADB file with bad channels is taken from alien
|
C++
|
bsd-3-clause
|
rbailhac/AliPhysics,dstocco/AliPhysics,SHornung1/AliPhysics,kreisl/AliPhysics,dlodato/AliPhysics,mvala/AliPhysics,sebaleh/AliPhysics,AudreyFrancisco/AliPhysics,lfeldkam/AliPhysics,lfeldkam/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,lfeldkam/AliPhysics,rderradi/AliPhysics,ALICEHLT/AliPhysics,sebaleh/AliPhysics,pbatzing/AliPhysics,mpuccio/AliPhysics,mvala/AliPhysics,amatyja/AliPhysics,jmargutt/AliPhysics,dlodato/AliPhysics,jmargutt/AliPhysics,lcunquei/AliPhysics,carstooon/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,rderradi/AliPhysics,pbuehler/AliPhysics,mkrzewic/AliPhysics,adriansev/AliPhysics,rderradi/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,jgronefe/AliPhysics,mazimm/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,rderradi/AliPhysics,mbjadhav/AliPhysics,mbjadhav/AliPhysics,dlodato/AliPhysics,dstocco/AliPhysics,mkrzewic/AliPhysics,fcolamar/AliPhysics,victor-gonzalez/AliPhysics,amatyja/AliPhysics,hzanoli/AliPhysics,hcab14/AliPhysics,dmuhlhei/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,ppribeli/AliPhysics,ALICEHLT/AliPhysics,btrzecia/AliPhysics,yowatana/AliPhysics,rderradi/AliPhysics,kreisl/AliPhysics,jmargutt/AliPhysics,dlodato/AliPhysics,btrzecia/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,rbailhac/AliPhysics,yowatana/AliPhysics,fbellini/AliPhysics,jgronefe/AliPhysics,pchrista/AliPhysics,btrzecia/AliPhysics,fbellini/AliPhysics,pbatzing/AliPhysics,jgronefe/AliPhysics,victor-gonzalez/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,jmargutt/AliPhysics,fbellini/AliPhysics,amatyja/AliPhysics,nschmidtALICE/AliPhysics,mazimm/AliPhysics,sebaleh/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,yowatana/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,mbjadhav/AliPhysics,carstooon/AliPhysics,AMechler/AliPhysics,nschmidtALICE/AliPhysics,dstocco/AliPhysics,carstooon/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,btrzecia/AliPhysics,dstocco/AliPhysics,ppribeli/AliPhysics,kreisl/AliPhysics,jgronefe/AliPhysics,aaniin/AliPhysics,SHornung1/AliPhysics,akubera/AliPhysics,dmuhlhei/AliPhysics,mazimm/AliPhysics,akubera/AliPhysics,amatyja/AliPhysics,sebaleh/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,aaniin/AliPhysics,mvala/AliPhysics,dstocco/AliPhysics,nschmidtALICE/AliPhysics,amatyja/AliPhysics,mpuccio/AliPhysics,hcab14/AliPhysics,pchrista/AliPhysics,rderradi/AliPhysics,ALICEHLT/AliPhysics,ALICEHLT/AliPhysics,hcab14/AliPhysics,SHornung1/AliPhysics,aaniin/AliPhysics,sebaleh/AliPhysics,pbatzing/AliPhysics,mazimm/AliPhysics,aaniin/AliPhysics,aaniin/AliPhysics,pbuehler/AliPhysics,amatyja/AliPhysics,fcolamar/AliPhysics,btrzecia/AliPhysics,dmuhlhei/AliPhysics,kreisl/AliPhysics,mkrzewic/AliPhysics,ppribeli/AliPhysics,ppribeli/AliPhysics,pbatzing/AliPhysics,yowatana/AliPhysics,mazimm/AliPhysics,amaringarcia/AliPhysics,dstocco/AliPhysics,lcunquei/AliPhysics,amatyja/AliPhysics,dstocco/AliPhysics,hzanoli/AliPhysics,pbatzing/AliPhysics,fcolamar/AliPhysics,jmargutt/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,hcab14/AliPhysics,AMechler/AliPhysics,victor-gonzalez/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,rihanphys/AliPhysics,AudreyFrancisco/AliPhysics,mazimm/AliPhysics,victor-gonzalez/AliPhysics,fbellini/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,hzanoli/AliPhysics,yowatana/AliPhysics,aaniin/AliPhysics,btrzecia/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,mvala/AliPhysics,hcab14/AliPhysics,dmuhlhei/AliPhysics,alisw/AliPhysics,pbuehler/AliPhysics,lfeldkam/AliPhysics,ppribeli/AliPhysics,carstooon/AliPhysics,kreisl/AliPhysics,pchrista/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,rderradi/AliPhysics,AMechler/AliPhysics,carstooon/AliPhysics,alisw/AliPhysics,jgronefe/AliPhysics,preghenella/AliPhysics,akubera/AliPhysics,lcunquei/AliPhysics,ALICEHLT/AliPhysics,fbellini/AliPhysics,mkrzewic/AliPhysics,ppribeli/AliPhysics,AudreyFrancisco/AliPhysics,jmargutt/AliPhysics,kreisl/AliPhysics,dlodato/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,alisw/AliPhysics,AudreyFrancisco/AliPhysics,carstooon/AliPhysics,dlodato/AliPhysics,AMechler/AliPhysics,yowatana/AliPhysics,victor-gonzalez/AliPhysics,akubera/AliPhysics,dmuhlhei/AliPhysics,hcab14/AliPhysics,hcab14/AliPhysics,SHornung1/AliPhysics,btrzecia/AliPhysics,adriansev/AliPhysics,ALICEHLT/AliPhysics,pchrista/AliPhysics,akubera/AliPhysics,lcunquei/AliPhysics,dmuhlhei/AliPhysics,dmuhlhei/AliPhysics,mbjadhav/AliPhysics,lcunquei/AliPhysics,jmargutt/AliPhysics,mbjadhav/AliPhysics,fcolamar/AliPhysics,rbailhac/AliPhysics,pbatzing/AliPhysics,AudreyFrancisco/AliPhysics,akubera/AliPhysics,aaniin/AliPhysics,hzanoli/AliPhysics,ALICEHLT/AliPhysics,carstooon/AliPhysics,jgronefe/AliPhysics,AudreyFrancisco/AliPhysics,nschmidtALICE/AliPhysics,pbatzing/AliPhysics,mkrzewic/AliPhysics,lcunquei/AliPhysics,kreisl/AliPhysics,mpuccio/AliPhysics,preghenella/AliPhysics,preghenella/AliPhysics,lfeldkam/AliPhysics,SHornung1/AliPhysics,amaringarcia/AliPhysics,mazimm/AliPhysics,akubera/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,sebaleh/AliPhysics,alisw/AliPhysics,preghenella/AliPhysics,mbjadhav/AliPhysics,mkrzewic/AliPhysics,rihanphys/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,pbuehler/AliPhysics,mbjadhav/AliPhysics,pbuehler/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,lcunquei/AliPhysics,mvala/AliPhysics,SHornung1/AliPhysics,lfeldkam/AliPhysics,dlodato/AliPhysics,mvala/AliPhysics,lfeldkam/AliPhysics,fbellini/AliPhysics,hzanoli/AliPhysics,hzanoli/AliPhysics,jgronefe/AliPhysics
|
7eb4207193eeb57ddf9e48db297949be396d4167
|
sdk-remote/src/tests/liburbi/syncvalues.cc
|
sdk-remote/src/tests/liburbi/syncvalues.cc
|
/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <bin/tests.hh>
BEGIN_TEST(syncvalues, client, syncClient)
syncClient.setErrorCallback(callback(&dump));
syncClient.setCallback(callback(&dump), "output");
SSEND("cout << 1;");
//= D output 1
assert_eq(SGET(int, "1+2*3;"), 7);
SSEND("cout << 2;");
//= D output 2
assert_eq(SGET(std::string, "\"Hello,\" + \" World!\";"), "Hello, World!");
SSEND("cout << 3;");
//= D output 3
assert_eq(SGET_ERROR("1/0;"), "3.1-3: /: division by 0");
SSEND("cout << 4;");
//= D output 4
assert_eq(SGET(int, "1+2*3;"), 7);
END_TEST
|
/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <bin/tests.hh>
BEGIN_TEST(syncvalues, client, syncClient)
syncClient.setErrorCallback(callback(&dump));
syncClient.setCallback(callback(&dump), "output");
SSEND("cout << 1;");
//= D output 1
assert_eq(SGET(int, "1+2*3;"), 7);
SSEND("cout << 2;");
//= D output 2
assert_eq(SGET(std::string, "\"Hello,\" + \" World!\";"), "Hello, World!");
SSEND("cout << 3;");
//= D output 3
assert_eq(SGET_ERROR("1/0;"), "6.1-3: /: division by 0");
SSEND("cout << 4;");
//= D output 4
assert_eq(SGET(int, "1+2*3;"), 7);
END_TEST
|
Fix liburbi/syncvalue test.
|
Fix liburbi/syncvalue test.
* src/tests/liburbi/syncvalues.cc: Update line number of the error
message.
|
C++
|
bsd-3-clause
|
urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi
|
f49e1f587cd65982b5a5fe314f74211cd20b676d
|
sdk/rms_sdk/Platform/Http/HttpClientQt.cpp
|
sdk/rms_sdk/Platform/Http/HttpClientQt.cpp
|
/*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#ifdef QTFRAMEWORK
#include "HttpClientQt.h"
#include <QThread>
#include <QMutex>
#include <QEventLoop>
#include "../Logger/Logger.h"
#include "../../ModernAPI/RMSExceptions.h"
#include "mscertificates.h"
#include "HttpClientQt.h"
using namespace std;
namespace rmscore {
namespace platform {
namespace http {
common::ByteArray ReadAllBytes(QIODevice *from) {
common::ByteArray result;
auto bytesAvailable = from->bytesAvailable();
if (bytesAvailable > 0) {
result.resize(static_cast<size_t>(bytesAvailable));
char *buf = reinterpret_cast<char *>(&result[0]);
while (bytesAvailable > 0) {
auto read = from->read(buf, bytesAvailable);
if (read <= 0) break;
bytesAvailable -= read;
}
}
return result;
}
shared_ptr<IHttpClient> IHttpClient::Create() {
static bool initialized = false;
// add Microsoft certificates to trust list
if (!initialized) {
QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration());
QList<QSslCertificate> certificates = SslConfiguration.caCertificates();
certificates.append(QSslCertificate::fromData(MicrosoftCertCA));
certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA));
SslConfiguration.setCaCertificates(certificates);
QSslConfiguration::setDefaultConfiguration(SslConfiguration);
initialized = true;
}
return make_shared<HttpClientQt>();
}
HttpClientQt::HttpClientQt() : lastReply_(nullptr) {
this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration());
}
HttpClientQt::~HttpClientQt() { }
void HttpClientQt::AddAuthorizationHeader(const string& authToken) {
this->AddHeader("Authorization", authToken);
}
void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) {
this->AddHeader("Accept", mediaType);
}
void HttpClientQt::AddAcceptLanguageHeader(const string& language) {
this->AddHeader("Accept-Language", language);
}
void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) {
this->request_.setRawHeader(headerName.c_str(), headerValue.c_str());
}
StatusCode HttpClientQt::Post(const string & url,
const common::ByteArray & request,
const string & mediaType,
common::ByteArray & response) {
Logger::Info("==> HttpClientQt::POST %s", url.data());
Logger::Debug("==> request: %s", request.data());
this->request_.setUrl(QUrl(url.c_str()));
this->AddAcceptMediaTypeHeader(mediaType);
lastReply_ =
this->manager_.post(this->request_,
QByteArray(reinterpret_cast<const char *>(request.data()),
static_cast<int>(request.size())));
QEventLoop loop;
QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QVariant statusCode = lastReply_->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Logger::Info("statusCode: %i", statusCode.toInt());
Logger::Debug("--> Header:", nullptr);
foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) {
Logger::Debug("%s : %s", pair.first.data(), pair.second.data() );
}
response = ReadAllBytes(lastReply_);
Logger::Debug("--> Body:", nullptr);
Logger::Debug(string(response.begin(), response.end()), nullptr);
QNetworkReply::NetworkError error_type = lastReply_->error();
if (error_type != QNetworkReply::NoError) {
Logger::Error(QString("error: %1").arg(
lastReply_->errorString()).toStdString(), nullptr);
}
return StatusCode(statusCode.toInt());
}
StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response) {
Logger::Debug("==> HttpClientQt::GET %s", url.data());
this->request_.setUrl(QUrl(url.c_str()));
lastReply_ = this->manager_.get(this->request_);
QEventLoop loop;
QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit()));
QObject::connect(lastReply_, &QNetworkReply::sslErrors,
[ = ](QList<QSslError>errorList) {
for (auto& error : errorList) {
Logger::Error("QSslError: %s",
error.errorString().toStdString().c_str());
throw exceptions::RMSNetworkException(
error.errorString().toStdString(),
exceptions::RMSNetworkException::ServerError);
}
});
loop.exec();
QVariant statusCode = lastReply_->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
Logger::Debug("statusCode: %i", statusCode.toInt());
Logger::Debug("--> Header:", nullptr);
foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) {
Logger::Debug("%s : %s", pair.first.data(), pair.second.data());
}
response = ReadAllBytes(lastReply_);
Logger::Debug("--> Body:", nullptr);
Logger::Debug(string(response.begin(), response.end()), nullptr);
QNetworkReply::NetworkError error_type = lastReply_->error();
if (error_type != QNetworkReply::NoError) {
Logger::Error(QString("error: %1").arg(
lastReply_->errorString()).toStdString(), nullptr);
}
return StatusCode(statusCode.toInt());
}
const string HttpClientQt::GetResponseHeader(const string& headerName) {
return string(this->lastReply_->rawHeader(headerName.c_str()).data());
}
void HttpClientQt::SetAllowUI(bool /* allow*/)
{
throw exceptions::RMSNotFoundException("Not implemented");
}
}
}
} // namespace rmscore { namespace platform { namespace http {
#endif // ifdef QTFRAMEWORK
|
/*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#ifdef QTFRAMEWORK
#include "HttpClientQt.h"
#include <QThread>
#include <QMutex>
#include <QEventLoop>
#include "../Logger/Logger.h"
#include "../../ModernAPI/RMSExceptions.h"
#include "mscertificates.h"
#include "HttpClientQt.h"
using namespace std;
namespace rmscore {
namespace platform {
namespace http {
common::ByteArray ReadAllBytes(QIODevice *from) {
common::ByteArray result;
auto bytesAvailable = from->bytesAvailable();
if (bytesAvailable > 0) {
result.resize(static_cast<size_t>(bytesAvailable));
char *buf = reinterpret_cast<char *>(&result[0]);
while (bytesAvailable > 0) {
auto read = from->read(buf, bytesAvailable);
if (read <= 0) break;
bytesAvailable -= read;
}
}
return result;
}
shared_ptr<IHttpClient> IHttpClient::Create() {
static bool initialized = false;
// add Microsoft certificates to trust list
if (!initialized) {
QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration());
QList<QSslCertificate> certificates = SslConfiguration.caCertificates();
certificates.append(QSslCertificate::fromData(MicrosoftCertCA));
certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA));
SslConfiguration.setCaCertificates(certificates);
QSslConfiguration::setDefaultConfiguration(SslConfiguration);
initialized = true;
}
return make_shared<HttpClientQt>();
}
HttpClientQt::HttpClientQt() : lastReply_(nullptr) {
this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration());
}
HttpClientQt::~HttpClientQt() { }
void HttpClientQt::AddAuthorizationHeader(const string& authToken) {
this->AddHeader("Authorization", authToken);
}
void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) {
this->AddHeader("Accept", mediaType);
}
void HttpClientQt::AddAcceptLanguageHeader(const string& language) {
this->AddHeader("Accept-Language", language);
}
void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) {
this->request_.setRawHeader(headerName.c_str(), headerValue.c_str());
}
StatusCode HttpClientQt::Post(const string & url,
const common::ByteArray & request,
const string & mediaType,
common::ByteArray & response) {
Logger::Info("==> HttpClientQt::POST %s", url.data());
std::string req(request.begin(),request.end());
Logger::Debug("==> request: %s", req.c_str());
this->request_.setUrl(QUrl(url.c_str()));
this->AddAcceptMediaTypeHeader(mediaType);
lastReply_ =
this->manager_.post(this->request_,
QByteArray(reinterpret_cast<const char *>(request.data()),
static_cast<int>(request.size())));
QEventLoop loop;
QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QVariant statusCode = lastReply_->attribute(QNetworkRequest::HttpStatusCodeAttribute);
Logger::Info("statusCode: %i", statusCode.toInt());
Logger::Debug("--> Header:", nullptr);
foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) {
Logger::Debug("%s : %s", pair.first.data(), pair.second.data() );
}
response = ReadAllBytes(lastReply_);
Logger::Debug("--> Body:", nullptr);
Logger::Debug(string(response.begin(), response.end()), nullptr);
QNetworkReply::NetworkError error_type = lastReply_->error();
if (error_type != QNetworkReply::NoError) {
Logger::Error(QString("error: %1").arg(
lastReply_->errorString()).toStdString(), nullptr);
}
return StatusCode(statusCode.toInt());
}
StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response) {
Logger::Debug("==> HttpClientQt::GET %s", url.data());
this->request_.setUrl(QUrl(url.c_str()));
lastReply_ = this->manager_.get(this->request_);
QEventLoop loop;
QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit()));
QObject::connect(lastReply_, &QNetworkReply::sslErrors,
[ = ](QList<QSslError>errorList) {
for (auto& error : errorList) {
Logger::Error("QSslError: %s",
error.errorString().toStdString().c_str());
throw exceptions::RMSNetworkException(
error.errorString().toStdString(),
exceptions::RMSNetworkException::ServerError);
}
});
loop.exec();
QVariant statusCode = lastReply_->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
Logger::Debug("statusCode: %i", statusCode.toInt());
Logger::Debug("--> Header:", nullptr);
foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) {
Logger::Debug("%s : %s", pair.first.data(), pair.second.data());
}
response = ReadAllBytes(lastReply_);
Logger::Debug("--> Body:", nullptr);
Logger::Debug(string(response.begin(), response.end()), nullptr);
QNetworkReply::NetworkError error_type = lastReply_->error();
if (error_type != QNetworkReply::NoError) {
Logger::Error(QString("error: %1").arg(
lastReply_->errorString()).toStdString(), nullptr);
}
return StatusCode(statusCode.toInt());
}
const string HttpClientQt::GetResponseHeader(const string& headerName) {
return string(this->lastReply_->rawHeader(headerName.c_str()).data());
}
void HttpClientQt::SetAllowUI(bool /* allow*/)
{
throw exceptions::RMSNotFoundException("Not implemented");
}
}
}
} // namespace rmscore { namespace platform { namespace http {
#endif // ifdef QTFRAMEWORK
|
fix request logging
|
fix request logging
|
C++
|
mit
|
AzureAD/rms-sdk-for-cpp,AzureAD/rms-sdk-for-cpp,AzureAD/rms-sdk-for-cpp
|
80eb8ab8c4a3bc1e6bb841d9dd2ab3d609786745
|
checks/bench.cpp
|
checks/bench.cpp
|
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <exception>
#include <botan/filters.h>
using Botan::byte;
using Botan::u64bit;
#include "common.h"
#include "timer.h"
#include "bench.h"
/* Discard output to reduce overhead */
struct BitBucket : public Botan::Filter
{
void write(const byte[], u32bit) {}
};
Botan::Filter* lookup(const std::string&,
const std::vector<std::string>&,
const std::string& = "All");
namespace {
double bench_filter(std::string name, Botan::Filter* filter,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
Botan::Pipe pipe(filter, new BitBucket);
Botan::SecureVector<byte> buf(128 * 1024);
rng.randomize(buf, buf.size());
pipe.start_msg();
Timer timer(name, buf.size());
while(timer.seconds() < seconds)
{
timer.start();
pipe.write(buf, buf.size());
timer.stop();
}
pipe.end_msg();
double bytes_per_sec = timer.events() / timer.seconds();
double mbytes_per_sec = bytes_per_sec / (1024.0 * 1024.0);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(2);
if(html)
{
if(name.find("<") != std::string::npos)
name.replace(name.find("<"), 1, "<");
if(name.find(">") != std::string::npos)
name.replace(name.find(">"), 1, ">");
std::cout << " <TR><TH>" << name
<< std::string(25 - name.length(), ' ') << " <TH>";
std::cout.width(6);
std::cout << mbytes_per_sec << std::endl;
}
else
{
std::cout << name << ": " << std::string(25 - name.length(), ' ');
std::cout.width(6);
std::cout << mbytes_per_sec << " MiB/sec" << std::endl;
}
return (mbytes_per_sec);
}
double bench(const std::string& name, const std::string& filtername, bool html,
double seconds, u32bit keylen, u32bit ivlen,
Botan::RandomNumberGenerator& rng)
{
std::vector<std::string> params;
Botan::SecureVector<byte> key(keylen);
rng.randomize(key, key.size());
params.push_back(hex_encode(key, key.size()));
//params.push_back(std::string(int(2*keylen), 'A'));
params.push_back(std::string(int(2* ivlen), 'A'));
Botan::Filter* filter = lookup(filtername, params);
if(filter)
return bench_filter(name, filter, rng, html, seconds);
return 0;
}
}
void benchmark(const std::string& what,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
try {
if(html)
{
std::cout << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD "
<< "HTML 4.0 Transitional//EN\">\n"
<< "<HTML>\n\n"
<< "<TITLE>Botan Benchmarks</TITLE>\n\n"
<< "<BODY>\n\n"
<< "<P><TABLE BORDER CELLSPACING=1>\n"
<< "<THEAD>\n"
<< "<TR><TH>Algorithm "
<< "<TH>Mib / second\n"
<< "<TBODY>\n";
}
double sum = 0;
u32bit how_many = 0;
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
if(what == "All" || what == algos[j].type)
{
double speed = bench(algos[j].name, algos[j].filtername,
html, seconds, algos[j].keylen,
algos[j].ivlen, rng);
if(speed > .00001) /* log(0) == -inf -> messed up average */
sum += std::log(speed);
how_many++;
}
if(html)
std::cout << "</TABLE>\n\n";
double average = std::exp(sum / static_cast<double>(how_many));
if(what == "All" && html)
std::cout << "\n<P>Overall speed average: " << average
<< "\n\n";
else if(what == "All")
std::cout << "\nOverall speed average: " << average
<< std::endl;
if(html) std::cout << "</BODY></HTML>\n";
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return;
}
}
u32bit bench_algo(const std::string& name,
Botan::RandomNumberGenerator& rng,
double seconds)
{
try {
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
{
if(algos[j].name == name)
{
bench(algos[j].name, algos[j].filtername, false, seconds,
algos[j].keylen, algos[j].ivlen, rng);
return 1;
}
}
return 0;
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return 0;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return 0;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 0;
}
}
|
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <exception>
#include <botan/filters.h>
using Botan::byte;
using Botan::u64bit;
#include "common.h"
#include "timer.h"
#include "bench.h"
/* Discard output to reduce overhead */
struct BitBucket : public Botan::Filter
{
void write(const byte[], u32bit) {}
};
Botan::Filter* lookup(const std::string&,
const std::vector<std::string>&,
const std::string& = "All");
namespace {
double bench_filter(std::string name, Botan::Filter* filter,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
Botan::Pipe pipe(filter, new BitBucket);
std::vector<byte> buf(128 * 1024);
rng.randomize(&buf[0], buf.size());
pipe.start_msg();
Timer timer(name, buf.size());
while(timer.seconds() < seconds)
{
timer.start();
pipe.write(&buf[0], buf.size());
timer.stop();
}
pipe.end_msg();
double bytes_per_sec = timer.events() / timer.seconds();
double mbytes_per_sec = bytes_per_sec / (1024.0 * 1024.0);
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(2);
if(html)
{
if(name.find("<") != std::string::npos)
name.replace(name.find("<"), 1, "<");
if(name.find(">") != std::string::npos)
name.replace(name.find(">"), 1, ">");
std::cout << " <TR><TH>" << name
<< std::string(25 - name.length(), ' ') << " <TH>";
std::cout.width(6);
std::cout << mbytes_per_sec << std::endl;
}
else
{
std::cout << name << ": " << std::string(25 - name.length(), ' ');
std::cout.width(6);
std::cout << mbytes_per_sec << " MiB/sec" << std::endl;
}
return (mbytes_per_sec);
}
double bench(const std::string& name, const std::string& filtername, bool html,
double seconds, u32bit keylen, u32bit ivlen,
Botan::RandomNumberGenerator& rng)
{
std::vector<std::string> params;
Botan::SecureVector<byte> key(keylen);
rng.randomize(key, key.size());
params.push_back(hex_encode(key, key.size()));
//params.push_back(std::string(int(2*keylen), 'A'));
params.push_back(std::string(int(2* ivlen), 'A'));
Botan::Filter* filter = lookup(filtername, params);
if(filter)
return bench_filter(name, filter, rng, html, seconds);
return 0;
}
}
void benchmark(const std::string& what,
Botan::RandomNumberGenerator& rng,
bool html, double seconds)
{
try {
if(html)
{
std::cout << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD "
<< "HTML 4.0 Transitional//EN\">\n"
<< "<HTML>\n\n"
<< "<TITLE>Botan Benchmarks</TITLE>\n\n"
<< "<BODY>\n\n"
<< "<P><TABLE BORDER CELLSPACING=1>\n"
<< "<THEAD>\n"
<< "<TR><TH>Algorithm "
<< "<TH>Mib / second\n"
<< "<TBODY>\n";
}
double sum = 0;
u32bit how_many = 0;
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
if(what == "All" || what == algos[j].type)
{
double speed = bench(algos[j].name, algos[j].filtername,
html, seconds, algos[j].keylen,
algos[j].ivlen, rng);
if(speed > .00001) /* log(0) == -inf -> messed up average */
sum += std::log(speed);
how_many++;
}
if(html)
std::cout << "</TABLE>\n\n";
double average = std::exp(sum / static_cast<double>(how_many));
if(what == "All" && html)
std::cout << "\n<P>Overall speed average: " << average
<< "\n\n";
else if(what == "All")
std::cout << "\nOverall speed average: " << average
<< std::endl;
if(html) std::cout << "</BODY></HTML>\n";
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return;
}
}
u32bit bench_algo(const std::string& name,
Botan::RandomNumberGenerator& rng,
double seconds)
{
try {
std::vector<algorithm> algos = get_algos();
for(u32bit j = 0; j != algos.size(); j++)
{
if(algos[j].name == name)
{
bench(algos[j].name, algos[j].filtername, false, seconds,
algos[j].keylen, algos[j].ivlen, rng);
return 1;
}
}
return 0;
}
catch(Botan::Exception& e)
{
std::cout << "Botan exception caught: " << e.what() << std::endl;
return 0;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: " << e.what()
<< std::endl;
return 0;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 0;
}
}
|
Use std::vector instead of SecureVector to hold random input for filter benchmark
|
Use std::vector instead of SecureVector to hold random input for filter benchmark
|
C++
|
bsd-2-clause
|
Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,webmaster128/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan
|
a61f5dcad9c419bdaaab8c6a62f1eacc39a8dc35
|
cam_qhy5.cpp
|
cam_qhy5.cpp
|
/*
* cam_qhy5.cpp
* PHD Guiding
*
* Created by Craig Stark.
* Copyright (c) 2012 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined(CAM_QHY5)
#include <libusb.h>
#include "camera.h"
#include "image_math.h"
#include "cam_qhy5.h"
#define QHY5_MATRIX_WIDTH 1558
#define QHY5_MATRIX_HEIGHT 1048
#define QHY5_BUFFER_SIZE (QHY5_MATRIX_WIDTH * (QHY5_MATRIX_HEIGHT + 2))
#define QHY5_IMAGE_WIDTH 1280
#define QHY5_IMAGE_HEIGHT 1024
#define QHY5_VID 0x16c0
#define QHY5_PID 0x296d
#define STORE_WORD_BE(var, val) *(var) = ((val) >> 8) & 0xff; *((var) + 1) = (val) & 0xff
static unsigned char reg[19];
static int gain_lut[74] = {0x000, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x00A, 0x00B,
0x00C, 0x00D, 0x00E, 0x00F, 0x010, 0x011, 0x012, 0x013, 0x014,
0x015, 0x016, 0x017, 0x018, 0x019, 0x01A, 0x01B, 0x01C, 0x01D,
0x01E, 0x01F, 0x051, 0x052, 0x053, 0x054, 0x055, 0x056, 0x057,
0x058, 0x059, 0x05A, 0x05B, 0x05C, 0x05D, 0x05E, 0x05F, 0x6CE,
0x6CF, 0x6D0, 0x6D1, 0x6D2, 0x6D3, 0x6D4, 0x6D5, 0x6D6, 0x6D7,
0x6D8, 0x6D9, 0x6DA, 0x6DB, 0x6DC, 0x6DD, 0x6DE, 0x6DF, 0x6E0,
0x6E1, 0x6E2, 0x6E3, 0x6E4, 0x6E5, 0x6E6, 0x6E7, 0x6FC, 0x6FD,
0x6FE, 0x6FF
};
static libusb_device_handle *m_handle = NULL;
static bool s_libusb_init_done;
static bool init_libusb()
{
if (s_libusb_init_done)
return false;
int ret = libusb_init(0);
if (ret != 0)
return true;
s_libusb_init_done = true;
return false;
}
static void uninit_libusb()
{
if (s_libusb_init_done)
{
libusb_exit(0);
s_libusb_init_done = false;
}
}
Camera_QHY5Class::Camera_QHY5Class()
{
Connected = FALSE;
FullSize = wxSize(QHY5_IMAGE_WIDTH, QHY5_IMAGE_HEIGHT);
m_hasGuideOutput = true;
HasGainControl = true;
RawBuffer = NULL;
Name = _T("QHY 5");
}
Camera_QHY5Class::~Camera_QHY5Class()
{
uninit_libusb();
}
wxByte Camera_QHY5Class::BitsPerPixel()
{
return 8;
}
bool Camera_QHY5Class::Connect(const wxString& camId)
{
if (init_libusb())
{
wxMessageBox(_("Could not initialize USB library"), _("Error"), wxOK | wxICON_ERROR);
return true;
}
m_handle = libusb_open_device_with_vid_pid(NULL, QHY5_VID, QHY5_PID);
if (m_handle == NULL)
{
wxMessageBox(_T("Libusb failed to open camera QHY5."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if ( libusb_kernel_driver_active( m_handle, 0 ) )
libusb_detach_kernel_driver( m_handle, 0 );
libusb_set_configuration( m_handle, 1 );
libusb_claim_interface( m_handle, 0 );
if (RawBuffer)
delete [] RawBuffer;
RawBuffer = new unsigned char[QHY5_BUFFER_SIZE];
Connected = true;
return false;
}
bool Camera_QHY5Class::ST4PulseGuideScope(int direction, int duration)
{
int result = -1;
int reg = 0;
int32_t dur[2] = { -1, -1};
// duration /= 10;
if (duration >= 2500) duration = 2500; // Max guide pulse is 2.54s -- 255 keeps it on always
switch (direction)
{
case WEST:
reg = 0x80;
dur[0] = duration;
break; // 0111 0000
case NORTH:
reg = 0x40;
dur[1] = duration;
break; // 1011 0000
case SOUTH:
reg = 0x20;
dur[1] = duration;
break; // 1101 0000
case EAST:
reg = 0x10;
dur[0] = duration;
break; // 1110 0000
default:
return true; // bad direction passed in
}
result = libusb_control_transfer(m_handle, 0x42, 0x10, 0, reg, (unsigned char *)dur, sizeof(dur), 5000);
wxMilliSleep(duration + 10);
return result < 0 ? true : false;
}
void Camera_QHY5Class::ClearGuidePort()
{
int16_t res = 0;
libusb_control_transfer(m_handle, 0xc2, 0x18, 0, 0, (unsigned char *)&res, sizeof(res), 5000);
}
void Camera_QHY5Class::InitCapture()
{
}
bool Camera_QHY5Class::Disconnect()
{
libusb_release_interface( m_handle, 0 );
libusb_close( m_handle );
m_handle = NULL;
Connected = false;
if (RawBuffer)
delete [] RawBuffer;
RawBuffer = NULL;
return false;
}
bool Camera_QHY5Class::Capture(int duration, usImage& img, int options, const wxRect& subframe)
{
// Only does full frames still
//static int last_dur = 0;
static int last_gain = 60;
static int first_time = 1;
unsigned char *bptr;
unsigned short *dptr;
int x, y;
int xsize = FullSize.GetWidth();
int ysize = FullSize.GetHeight();
int op_height = FullSize.GetHeight();
//bool firstimg = true;
unsigned char buffer[2]; // for debug purposes
int offset, value, index;
int gain, gain_val, gain_lut_sz = (int)(sizeof(gain_lut) / sizeof(int));
int ret, result;
if (img.Init(xsize, ysize))
{
DisconnectWithAlert(CAPT_FAIL_MEMORY);
return true;
}
if (GuideCameraGain != last_gain)
{
op_height -= (op_height % 4);
offset = (QHY5_MATRIX_HEIGHT - op_height) / 2;
index = (QHY5_MATRIX_WIDTH * (op_height + 26)) >> 16;
value = (QHY5_MATRIX_WIDTH * (op_height + 26)) & 0xffff;
gain = (int)(73. * (GuideCameraGain / 100.));
if ( gain >= gain_lut_sz )
gain = gain_lut_sz - 1;
if ( gain < 0 )
gain = 0;
gain_val = gain_lut[ gain ];
STORE_WORD_BE(reg + 0, gain_val);
STORE_WORD_BE(reg + 2, gain_val);
STORE_WORD_BE(reg + 4, gain_val);
STORE_WORD_BE(reg + 6, gain_val);
STORE_WORD_BE(reg + 8, offset);
STORE_WORD_BE(reg + 10, 0);
STORE_WORD_BE(reg + 12, op_height - 1);
STORE_WORD_BE(reg + 14, 0x0521);
STORE_WORD_BE(reg + 16, op_height + 25);
reg[18] = 0xcc;
if (libusb_control_transfer(m_handle, 0x42, 0x13, value, index, reg, sizeof(reg), 5000))
{
wxMilliSleep(2);
if (libusb_control_transfer(m_handle, 0x42, 0x14, 0x31a5, 0, reg, 0, 5000))
{
wxMilliSleep(1);
if (libusb_control_transfer(m_handle, 0x42, 0x16, 0, first_time, reg, 0, 5000))
{
first_time = 0;
}
}
}
last_gain = GuideCameraGain;
}
index = duration >> 16;
value = duration & 0xffff;
buffer[0] = 0;
buffer[1] = 100;
libusb_control_transfer(m_handle, 0xc2, 0x12, value, index, buffer, 2, 5000);
/* wait for exposure end */
wxMilliSleep(duration);
ret = libusb_bulk_transfer( m_handle, 0x82, RawBuffer, QHY5_BUFFER_SIZE, &result, 20000);
if (ret < 0)
{
pFrame->Alert(_T("Failed to read image: libusb_bulk_transfer() failed."));
return true;
}
if (result != QHY5_BUFFER_SIZE)
{
pFrame->Alert(_T("Failed to read image."));
return true;
}
//bptr = RawBuffer;
// Load and crop from the 800 x 525 image that came in
dptr = img.ImageData;
for (y = 0; y < ysize; y++)
{
bptr = RawBuffer + QHY5_MATRIX_WIDTH * y + 20;
for (x = 0; x < xsize; x++, bptr++, dptr++) // CAN SPEED THIS UP
{
*dptr = (unsigned short) *bptr;
}
}
if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img);
return false;
}
#endif
|
/*
* cam_qhy5.cpp
* PHD Guiding
*
* Created by Craig Stark.
* Copyright (c) 2012 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined(CAM_QHY5)
#include <libusb.h>
#include "camera.h"
#include "image_math.h"
#include "cam_qhy5.h"
#define QHY5_MATRIX_WIDTH 1558
#define QHY5_MATRIX_HEIGHT 1048
#define QHY5_BUFFER_SIZE (QHY5_MATRIX_WIDTH * (QHY5_MATRIX_HEIGHT + 2))
#define QHY5_IMAGE_WIDTH 1280
#define QHY5_IMAGE_HEIGHT 1024
#define QHY5_VID 0x16c0
#define QHY5_PID 0x296d
#define STORE_WORD_BE(var, val) *(var) = ((val) >> 8) & 0xff; *((var) + 1) = (val) & 0xff
static unsigned char reg[19];
static int gain_lut[74] = {0x000, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x00A, 0x00B,
0x00C, 0x00D, 0x00E, 0x00F, 0x010, 0x011, 0x012, 0x013, 0x014,
0x015, 0x016, 0x017, 0x018, 0x019, 0x01A, 0x01B, 0x01C, 0x01D,
0x01E, 0x01F, 0x051, 0x052, 0x053, 0x054, 0x055, 0x056, 0x057,
0x058, 0x059, 0x05A, 0x05B, 0x05C, 0x05D, 0x05E, 0x05F, 0x6CE,
0x6CF, 0x6D0, 0x6D1, 0x6D2, 0x6D3, 0x6D4, 0x6D5, 0x6D6, 0x6D7,
0x6D8, 0x6D9, 0x6DA, 0x6DB, 0x6DC, 0x6DD, 0x6DE, 0x6DF, 0x6E0,
0x6E1, 0x6E2, 0x6E3, 0x6E4, 0x6E5, 0x6E6, 0x6E7, 0x6FC, 0x6FD,
0x6FE, 0x6FF
};
static libusb_device_handle *m_handle = NULL;
static bool s_libusb_init_done;
static bool init_libusb()
{
if (s_libusb_init_done)
return false;
int ret = libusb_init(0);
if (ret != 0)
return true;
s_libusb_init_done = true;
return false;
}
static void uninit_libusb()
{
if (s_libusb_init_done)
{
libusb_exit(0);
s_libusb_init_done = false;
}
}
Camera_QHY5Class::Camera_QHY5Class()
{
Connected = FALSE;
FullSize = wxSize(QHY5_IMAGE_WIDTH, QHY5_IMAGE_HEIGHT);
m_hasGuideOutput = true;
HasGainControl = true;
RawBuffer = NULL;
Name = _T("QHY 5");
}
Camera_QHY5Class::~Camera_QHY5Class()
{
uninit_libusb();
}
wxByte Camera_QHY5Class::BitsPerPixel()
{
return 8;
}
bool Camera_QHY5Class::Connect(const wxString& camId)
{
if (init_libusb())
{
wxMessageBox(_("Could not initialize USB library"), _("Error"), wxOK | wxICON_ERROR);
return true;
}
m_handle = libusb_open_device_with_vid_pid(NULL, QHY5_VID, QHY5_PID);
if (m_handle == NULL)
{
wxMessageBox(_T("Libusb failed to open camera QHY5."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if ( libusb_kernel_driver_active( m_handle, 0 ) )
libusb_detach_kernel_driver( m_handle, 0 );
libusb_set_configuration( m_handle, 1 );
libusb_claim_interface( m_handle, 0 );
if (RawBuffer)
delete [] RawBuffer;
RawBuffer = new unsigned char[QHY5_BUFFER_SIZE];
Connected = true;
return false;
}
bool Camera_QHY5Class::ST4PulseGuideScope(int direction, int duration)
{
int result = -1;
int reg = 0;
int32_t dur[2] = { -1, -1 };
// Max guide pulse is 2.54s -- 255 keeps it on always
if (duration > 2540)
duration = 2540;
switch (direction)
{
case WEST:
reg = 0x80;
dur[0] = duration;
break; // 0111 0000
case NORTH:
reg = 0x40;
dur[1] = duration;
break; // 1011 0000
case SOUTH:
reg = 0x20;
dur[1] = duration;
break; // 1101 0000
case EAST:
reg = 0x10;
dur[0] = duration;
break; // 1110 0000
default:
return true; // bad direction passed in
}
result = libusb_control_transfer(m_handle, 0x42, 0x10, 0, reg, (unsigned char *)dur, sizeof(dur), 5000);
wxMilliSleep(duration + 10);
return result < 0 ? true : false;
}
void Camera_QHY5Class::ClearGuidePort()
{
int16_t res = 0;
libusb_control_transfer(m_handle, 0xc2, 0x18, 0, 0, (unsigned char *)&res, sizeof(res), 5000);
}
void Camera_QHY5Class::InitCapture()
{
}
bool Camera_QHY5Class::Disconnect()
{
libusb_release_interface( m_handle, 0 );
libusb_close( m_handle );
m_handle = NULL;
Connected = false;
if (RawBuffer)
delete [] RawBuffer;
RawBuffer = NULL;
return false;
}
bool Camera_QHY5Class::Capture(int duration, usImage& img, int options, const wxRect& subframe)
{
// Only does full frames still
//static int last_dur = 0;
static int last_gain = 60;
static int first_time = 1;
unsigned char *bptr;
unsigned short *dptr;
int x, y;
int xsize = FullSize.GetWidth();
int ysize = FullSize.GetHeight();
int op_height = FullSize.GetHeight();
//bool firstimg = true;
unsigned char buffer[2]; // for debug purposes
int offset, value, index;
int gain, gain_val, gain_lut_sz = (int)(sizeof(gain_lut) / sizeof(int));
int ret, result;
if (img.Init(xsize, ysize))
{
DisconnectWithAlert(CAPT_FAIL_MEMORY);
return true;
}
if (GuideCameraGain != last_gain)
{
op_height -= (op_height % 4);
offset = (QHY5_MATRIX_HEIGHT - op_height) / 2;
index = (QHY5_MATRIX_WIDTH * (op_height + 26)) >> 16;
value = (QHY5_MATRIX_WIDTH * (op_height + 26)) & 0xffff;
gain = (int)(73. * (GuideCameraGain / 100.));
if ( gain >= gain_lut_sz )
gain = gain_lut_sz - 1;
if ( gain < 0 )
gain = 0;
gain_val = gain_lut[ gain ];
STORE_WORD_BE(reg + 0, gain_val);
STORE_WORD_BE(reg + 2, gain_val);
STORE_WORD_BE(reg + 4, gain_val);
STORE_WORD_BE(reg + 6, gain_val);
STORE_WORD_BE(reg + 8, offset);
STORE_WORD_BE(reg + 10, 0);
STORE_WORD_BE(reg + 12, op_height - 1);
STORE_WORD_BE(reg + 14, 0x0521);
STORE_WORD_BE(reg + 16, op_height + 25);
reg[18] = 0xcc;
if (libusb_control_transfer(m_handle, 0x42, 0x13, value, index, reg, sizeof(reg), 5000))
{
wxMilliSleep(2);
if (libusb_control_transfer(m_handle, 0x42, 0x14, 0x31a5, 0, reg, 0, 5000))
{
wxMilliSleep(1);
if (libusb_control_transfer(m_handle, 0x42, 0x16, 0, first_time, reg, 0, 5000))
{
first_time = 0;
}
}
}
last_gain = GuideCameraGain;
}
index = duration >> 16;
value = duration & 0xffff;
buffer[0] = 0;
buffer[1] = 100;
libusb_control_transfer(m_handle, 0xc2, 0x12, value, index, buffer, 2, 5000);
/* wait for exposure end */
wxMilliSleep(duration);
ret = libusb_bulk_transfer( m_handle, 0x82, RawBuffer, QHY5_BUFFER_SIZE, &result, 20000);
if (ret < 0)
{
pFrame->Alert(_T("Failed to read image: libusb_bulk_transfer() failed."));
return true;
}
if (result != QHY5_BUFFER_SIZE)
{
pFrame->Alert(_T("Failed to read image."));
return true;
}
//bptr = RawBuffer;
// Load and crop from the 800 x 525 image that came in
dptr = img.ImageData;
for (y = 0; y < ysize; y++)
{
bptr = RawBuffer + QHY5_MATRIX_WIDTH * y + 20;
for (x = 0; x < xsize; x++, bptr++, dptr++) // CAN SPEED THIS UP
{
*dptr = (unsigned short) *bptr;
}
}
if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img);
return false;
}
#endif
|
remove commented-out line
|
remove commented-out line
|
C++
|
bsd-3-clause
|
olegkutkov/phd2guiding_crao,OpenPHDGuiding/phd2,simonct/phd2,olegkutkov/phd2guiding_crao,OpenPHDGuiding/phd2,OpenPHDGuiding/phd2,simonct/phd2,OpenPHDGuiding/phd2,simonct/phd2,OpenPHDGuiding/phd2,olegkutkov/phd2guiding_crao,simonct/phd2,olegkutkov/phd2guiding_crao,simonct/phd2,OpenPHDGuiding/phd2,simonct/phd2,olegkutkov/phd2guiding_crao,olegkutkov/phd2guiding_crao
|
67ce21f989b1220ec3b9a40dfd7f27a8cb92bf80
|
cores/fastarduino/future.cpp
|
cores/fastarduino/future.cpp
|
// Copyright 2016-2020 Jean-Francois Poilpret
//
// 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 "future.h"
namespace future
{
/// @cond notdocumented
// Static definition for AbstractFutureManager singleton
AbstractFutureManager* AbstractFutureManager::instance_ = nullptr;
uint8_t AbstractFutureManager::get_future_value_size_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return 0;
return future->get_output_size_();
}
bool AbstractFutureManager::set_future_finish_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_finish_();
}
bool AbstractFutureManager::set_future_value_(uint8_t id, uint8_t chunk) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_chunk_(chunk);
}
bool AbstractFutureManager::set_future_value_(uint8_t id, const uint8_t* chunk, uint8_t size) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_chunk_(chunk, size);
}
bool AbstractFutureManager::set_future_error_(uint8_t id, int error) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_error_(error);
}
uint8_t AbstractFutureManager::get_storage_value_size_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return 0;
return future->get_input_size_();
}
bool AbstractFutureManager::get_storage_value_(uint8_t id, uint8_t& chunk) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->get_chunk_(chunk);
}
bool AbstractFutureManager::get_storage_value_(uint8_t id, uint8_t* chunk, uint8_t size) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->get_chunk_(chunk, size);
}
bool AbstractFutureManager::register_at_index_(AbstractFuture& future, uint8_t index)
{
if (futures_[index] != nullptr)
return false;
update_future_(future.id_, &future, nullptr);
future.id_ = static_cast<uint8_t>(index + 1);
future.status_ = FutureStatus::NOT_READY;
futures_[index] = &future;
return true;
}
/// @endcond
}
|
// Copyright 2016-2020 Jean-Francois Poilpret
//
// 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 "future.h"
namespace future
{
/// @cond notdocumented
// Static definition for AbstractFutureManager singleton
AbstractFutureManager* AbstractFutureManager::instance_ = nullptr;
bool AbstractFutureManager::register_future_(AbstractFuture& future)
{
// You cannot register an already registered future
if (future.id() != 0)
return false;
// Optimization: we start search AFTER the last removed id
for (uint8_t i = last_removed_id_; i < size_; ++i)
if (register_at_index_(future, i))
return true;
for (uint8_t i = 0; i <= last_removed_id_; ++i)
if (register_at_index_(future, i))
return true;
return false;
}
uint8_t AbstractFutureManager::get_future_value_size_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return 0;
return future->get_output_size_();
}
bool AbstractFutureManager::set_future_finish_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_finish_();
}
bool AbstractFutureManager::set_future_value_(uint8_t id, uint8_t chunk) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_chunk_(chunk);
}
bool AbstractFutureManager::set_future_value_(uint8_t id, const uint8_t* chunk, uint8_t size) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_chunk_(chunk, size);
}
bool AbstractFutureManager::set_future_error_(uint8_t id, int error) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->set_error_(error);
}
uint8_t AbstractFutureManager::get_storage_value_size_(uint8_t id) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return 0;
return future->get_input_size_();
}
bool AbstractFutureManager::get_storage_value_(uint8_t id, uint8_t& chunk) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->get_chunk_(chunk);
}
bool AbstractFutureManager::get_storage_value_(uint8_t id, uint8_t* chunk, uint8_t size) const
{
AbstractFuture* future = find_future(id);
if (future == nullptr)
return false;
return future->get_chunk_(chunk, size);
}
bool AbstractFutureManager::register_at_index_(AbstractFuture& future, uint8_t index)
{
if (futures_[index] != nullptr)
return false;
update_future_(future.id_, &future, nullptr);
future.id_ = static_cast<uint8_t>(index + 1);
future.status_ = FutureStatus::NOT_READY;
futures_[index] = &future;
return true;
}
/// @endcond
}
|
Fix link error
|
Fix link error
|
C++
|
lgpl-2.1
|
jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib,jfpoilpret/fast-arduino-lib
|
5512fa6c0e89a605113b9c94bbf4697a80c3fd5c
|
Applications/Utils/otbOSMDownloader.cxx
|
Applications/Utils/otbOSMDownloader.cxx
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataProperties.h"
#include "otbOSMDataToVectorDataGenerator.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
namespace otb
{
namespace Wrapper
{
class OSMDownloader : public Application
{
public:
/** Standard class typedefs. */
typedef OSMDownloader Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(OSMDownloader, otb::Application);
/** Filter typedef */
typedef otb::OSMDataToVectorDataGenerator VectorDataProviderType;
private:
void DoInit()
{
SetName("OSMDownloader");
SetDescription("Generate a vector data from OSM on the input image extend");
// Documentation
SetDocName("Open Street Map layers importations applications");
SetDocLongDescription("Generate a vector data from Open Street Map data. A DEM could be use. By default, the entire layer is downloaded, an image can be use as support for the OSM data. The application can provide also available classes in layers . This application required an Internet access. Informations about the OSM project : http://www.openstreetmap.fr/");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Convertion");
AddDocTag(Tags::Meta);
AddParameter(ParameterType_OutputVectorData, "out", "Output vector data");
SetParameterDescription("out", "Generated output vector data path");
AddParameter(ParameterType_InputImage, "support", "Support image");
SetParameterDescription("support", "Image used as support to estimate the models");
AddParameter(ParameterType_String, "key", "OSM tag key");
SetParameterDescription("key", "OSM tag key to extract (highway, building...)");
MandatoryOff("key");
AddParameter(ParameterType_String, "value", "OSM tag value");
SetParameterDescription("key", "OSM tag value to extract (motorway, footway...)");
MandatoryOff("value");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Empty, "printclasses", "option to display available key/value classes");
std::ostringstream oss;
oss << "Print the key/value classes available for the bounding box of the input image "<<std::endl;
oss << "\t\t\t\t ** If not used : Note that the options OSMKey (-key) and Output (-out) become mandatory";
SetParameterDescription("printclasses", oss.str().c_str());
MandatoryOff("printclasses");
// Doc example parameter settings
SetDocExampleParameterValue("support", "ROI_QB_TOULOUSE.TIF");
SetDocExampleParameterValue("key", "highway");
SetDocExampleParameterValue("out", "apTvUtOSMDownloader.shp");
}
void DoUpdateParameters()
{
// CASE: when the -print option is not required and the User
// does not set the option OSMKey or the option Output or does not
// set both of them
if ( !this->HasValue("printclasses") )
{
MandatoryOn("out");
MandatoryOn("key");
}
else
{
MandatoryOff("out");
MandatoryOff("key");
}
}
void DoExecute()
{
typedef otb::ImageToEnvelopeVectorDataFilter<FloatVectorImageType, VectorDataType>
EnvelopeFilterType;
typedef otb::VectorDataProperties<VectorDataType> VectorDataPropertiesType;
//Instantiate
EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();
VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();
m_VdOSMGenerator = VectorDataProviderType::New();
// Get the support image
envelopeFilter->SetInput( this->GetParameterImage("support") ); //->Output in WGS84
//Generate the envelope : Elevation through the elevation handler
if (ElevationParametersHandler::IsElevationEnabled(this, "elev"))
{
switch(ElevationParametersHandler::GetElevationType(this, "elev"))
{
case Elevation_DEM:
{
envelopeFilter->SetDEMDirectory(ElevationParametersHandler::GetDEMDirectory(this, "elev"));
envelopeFilter->SetGeoidFile(ElevationParametersHandler::GetGeoidFile(this, "elev"));
}
break;
case Elevation_Average:
{
envelopeFilter->SetAverageElevation(ElevationParametersHandler::GetAverageElevation(this, "elev"));
}
break;
// Commented cause using a tiff file is not implemented yet
// case Elevation_Tiff:
// {
// }
// break;
}
}
envelopeFilter->Update();
vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());
vdProperties->ComputeBoundingRegion();
double north, south, east, west;
north = vdProperties->GetBoundingRegion().GetIndex()[1]
+ vdProperties->GetBoundingRegion().GetSize()[1];
south = vdProperties->GetBoundingRegion().GetIndex()[1];
east = vdProperties->GetBoundingRegion().GetIndex()[0]
+ vdProperties->GetBoundingRegion().GetSize()[0];
west = vdProperties->GetBoundingRegion().GetIndex()[0];
m_VdOSMGenerator->SetNorth(north);
m_VdOSMGenerator->SetSouth(south);
m_VdOSMGenerator->SetEast(east);
m_VdOSMGenerator->SetWest(west);
try
{
m_VdOSMGenerator->Update();
}
catch ( itk::ExceptionObject & err )
{
otbAppLogCRITICAL("Exception itk::ExceptionObject raised !");
otbAppLogCRITICAL( << err );
return;
}
// If the user wants to print the Key/Values present in the XML file
// downloaded :
if ( this->HasValue("printclasses"))
{
// Print the classes
VectorDataProviderType::KeyMapType keymap = m_VdOSMGenerator->GetKeysMap();
VectorDataProviderType::KeyMapType::iterator it = keymap.begin();
while(it != keymap.end())
{
otbAppLogINFO(" Key : "<< (*it).first<< " value : ");
std::ostringstream oss;
for(unsigned int i = 0; i < (*it).second.size(); i++)
{
oss.str();
oss << ((*it).second[i]) << " ";
}
otbAppLogINFO( << oss.str() );
++it;
}
return;
}
// Get the VectorData By name
if ( this->HasValue("value") )
{
SetParameterOutputVectorData("out", const_cast<VectorDataType*>(m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"),
this->GetParameterString("value"))));
otbAppLogINFO( << m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"), this->GetParameterString("value"))->Size()-3
<< " elements retrieved");
}
else
{
SetParameterOutputVectorData("out", const_cast<VectorDataType*>(m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"))));
otbAppLogINFO( << m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"))->Size()-3
<< " elements retrieved");
}
}
VectorDataProviderType::Pointer m_VdOSMGenerator;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::OSMDownloader)
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataProperties.h"
#include "otbOSMDataToVectorDataGenerator.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
namespace otb
{
namespace Wrapper
{
class OSMDownloader : public Application
{
public:
/** Standard class typedefs. */
typedef OSMDownloader Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(OSMDownloader, otb::Application);
/** Filter typedef */
typedef otb::OSMDataToVectorDataGenerator VectorDataProviderType;
private:
void DoInit()
{
SetName("OSMDownloader");
SetDescription("Generate a vector data from OSM on the input image extend");
// Documentation
SetDocName("Open Street Map layers importations applications");
SetDocLongDescription("Generate a vector data from Open Street Map data. A DEM could be use. By default, the entire layer is downloaded, an image can be use as support for the OSM data. The application can provide also available classes in layers . This application required an Internet access. Informations about the OSM project : http://www.openstreetmap.fr/");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Convertion");
AddDocTag(Tags::Meta);
AddParameter(ParameterType_OutputVectorData, "out", "Output vector data");
SetParameterDescription("out", "Generated output vector data path");
AddParameter(ParameterType_InputImage, "support", "Support image");
SetParameterDescription("support", "Image used as support to estimate the models");
AddParameter(ParameterType_String, "key", "OSM tag key");
SetParameterDescription("key", "OSM tag key to extract (highway, building...)");
MandatoryOff("key");
AddParameter(ParameterType_String, "value", "OSM tag value");
SetParameterDescription("key", "OSM tag value to extract (motorway, footway...)");
MandatoryOff("value");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Empty, "printclasses", "option to display available key/value classes");
std::ostringstream oss;
oss << "Print the key/value classes available for the bounding box of the input image "<<std::endl;
oss << "\t\t\t\t ** If not used : Note that the options OSMKey (-key) and Output (-out) become mandatory";
SetParameterDescription("printclasses", oss.str().c_str());
MandatoryOff("printclasses");
// Doc example parameter settings
SetDocExampleParameterValue("support", "qb_RoadExtract.tif");
SetDocExampleParameterValue("key", "highway");
SetDocExampleParameterValue("out", "apTvUtOSMDownloader.shp");
}
void DoUpdateParameters()
{
// CASE: when the -print option is not required and the User
// does not set the option OSMKey or the option Output or does not
// set both of them
if ( !this->HasValue("printclasses") )
{
MandatoryOn("out");
MandatoryOn("key");
}
else
{
MandatoryOff("out");
MandatoryOff("key");
}
}
void DoExecute()
{
typedef otb::ImageToEnvelopeVectorDataFilter<FloatVectorImageType, VectorDataType>
EnvelopeFilterType;
typedef otb::VectorDataProperties<VectorDataType> VectorDataPropertiesType;
//Instantiate
EnvelopeFilterType::Pointer envelopeFilter = EnvelopeFilterType::New();
VectorDataPropertiesType::Pointer vdProperties = VectorDataPropertiesType::New();
m_VdOSMGenerator = VectorDataProviderType::New();
// Get the support image
envelopeFilter->SetInput( this->GetParameterImage("support") ); //->Output in WGS84
//Generate the envelope : Elevation through the elevation handler
if (ElevationParametersHandler::IsElevationEnabled(this, "elev"))
{
switch(ElevationParametersHandler::GetElevationType(this, "elev"))
{
case Elevation_DEM:
{
envelopeFilter->SetDEMDirectory(ElevationParametersHandler::GetDEMDirectory(this, "elev"));
envelopeFilter->SetGeoidFile(ElevationParametersHandler::GetGeoidFile(this, "elev"));
}
break;
case Elevation_Average:
{
envelopeFilter->SetAverageElevation(ElevationParametersHandler::GetAverageElevation(this, "elev"));
}
break;
// Commented cause using a tiff file is not implemented yet
// case Elevation_Tiff:
// {
// }
// break;
}
}
envelopeFilter->Update();
vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());
vdProperties->ComputeBoundingRegion();
double north, south, east, west;
north = vdProperties->GetBoundingRegion().GetIndex()[1]
+ vdProperties->GetBoundingRegion().GetSize()[1];
south = vdProperties->GetBoundingRegion().GetIndex()[1];
east = vdProperties->GetBoundingRegion().GetIndex()[0]
+ vdProperties->GetBoundingRegion().GetSize()[0];
west = vdProperties->GetBoundingRegion().GetIndex()[0];
m_VdOSMGenerator->SetNorth(north);
m_VdOSMGenerator->SetSouth(south);
m_VdOSMGenerator->SetEast(east);
m_VdOSMGenerator->SetWest(west);
try
{
m_VdOSMGenerator->Update();
}
catch ( itk::ExceptionObject & err )
{
otbAppLogCRITICAL("Exception itk::ExceptionObject raised !");
otbAppLogCRITICAL( << err );
return;
}
// If the user wants to print the Key/Values present in the XML file
// downloaded :
if ( this->HasValue("printclasses"))
{
// Print the classes
VectorDataProviderType::KeyMapType keymap = m_VdOSMGenerator->GetKeysMap();
VectorDataProviderType::KeyMapType::iterator it = keymap.begin();
while(it != keymap.end())
{
otbAppLogINFO(" Key : "<< (*it).first<< " value : ");
std::ostringstream oss;
for(unsigned int i = 0; i < (*it).second.size(); i++)
{
oss.str();
oss << ((*it).second[i]) << " ";
}
otbAppLogINFO( << oss.str() );
++it;
}
return;
}
// Get the VectorData By name
if ( this->HasValue("value") )
{
SetParameterOutputVectorData("out", const_cast<VectorDataType*>(m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"),
this->GetParameterString("value"))));
otbAppLogINFO( << m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"), this->GetParameterString("value"))->Size()-3
<< " elements retrieved");
}
else
{
SetParameterOutputVectorData("out", const_cast<VectorDataType*>(m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"))));
otbAppLogINFO( << m_VdOSMGenerator->GetVectorDataByName(this->GetParameterString("key"))->Size()-3
<< " elements retrieved");
}
}
VectorDataProviderType::Pointer m_VdOSMGenerator;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::OSMDownloader)
|
update example for appli OSMDownloader
|
DOC: update example for appli OSMDownloader
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
bea2e406daf1455f14a0fa1b6f43859e759f2e94
|
backends/mpi/world_provider.hpp
|
backends/mpi/world_provider.hpp
|
#pragma once
#include <mpi.h>
namespace bulk {
namespace mpi {
class world_provider {
public:
world_provider() {
MPI_Comm_size(MPI_COMM_WORLD, &nprocs_);
MPI_Comm_rank(MPI_COMM_WORLD, &pid_);
MPI_Get_processor_name(name_, &name_length_);
tag_size_ = 0;
}
int active_processors() const { return nprocs_; }
int processor_id() const { return pid_; }
void sync() const {
// FIXME: what if spawning with fewer processors than exist
MPI_Barrier(MPI_COMM_WORLD);
}
void internal_put_(int processor, void* value, void* variable, size_t size,
int offset, int count) {}
int register_location_(void* location, size_t size) { return 0; }
void unregister_location_(void* location) {}
void internal_get_(int processor, void* variable, void* target, size_t size,
int offset, int count) {}
virtual void internal_send_(int processor, void* tag, void* content,
size_t tag_size, size_t content_size) {}
std::string name() {
return std::string(name_);
}
private:
size_t tag_size_ = 0;
char name_[MPI_MAX_PROCESSOR_NAME];
int name_length_;
int pid_;
int nprocs_;
};
} // namespace mpi
} // namespace bulk
|
#pragma once
#include <type_traits>
#include <mpi.h>
#include <boost/bimap.hpp>
namespace bulk {
namespace mpi {
enum class receive_category : int { var_put = 0, var_get = 1, message = 2 };
using receive_type = std::underlying_type<receive_category>::type;
class world_provider {
public:
using var_id_type = int;
struct put_header {
var_id_type var_id;
size_t offset;
};
world_provider() {
MPI_Comm_size(MPI_COMM_WORLD, &nprocs_);
MPI_Comm_rank(MPI_COMM_WORLD, &pid_);
MPI_Get_processor_name(name_, &name_length_);
tag_size_ = 0;
}
int active_processors() const { return nprocs_; }
int processor_id() const { return pid_; }
void sync() const {
// FIXME: what if spawning with fewer processors than exist
MPI_Barrier(MPI_COMM_WORLD);
//// probe for incoming messages
while (true) {
MPI_Status status = {};
int flag = 0;
MPI_Iprobe(MPI_ANY_SOURCE,
static_cast<receive_type>(receive_category::var_put),
MPI_COMM_WORLD, &flag, &status);
if (flag == 0) break;
int count = 0;
MPI_Get_count(&status, MPI_BYTE, &count);
if (count == 0) break;
// FIXME again terribly unoptimized
void* buffer = malloc(count);
MPI_Recv(buffer, count, MPI_BYTE, MPI_ANY_SOURCE,
static_cast<receive_type>(receive_category::var_put),
MPI_COMM_WORLD, &status);
put_header header = ((put_header*)buffer)[0];
memcpy((char*)locations_.right.at(header.var_id) + header.offset,
&((put_header*)buffer)[1], count - sizeof(put_header));
free(buffer);
}
MPI_Barrier(MPI_COMM_WORLD);
}
void internal_put_(int processor, void* value, void* variable, size_t size,
int offset, int count) {
/* FIXME: we really dont want to do it like this:
* - dynamic allocation
* - type erasures
* move to templated internal put and use proper code
* */
put_header header = {};
header.var_id = locations_.left.at(variable);
header.offset = offset * size;
auto data_size = sizeof(put_header) + size * count;
void* payload = malloc(data_size);
((put_header*)payload)[0] = header;
memcpy((&((put_header*)payload)[1]), value, size * count);
MPI_Send(payload, data_size, MPI_BYTE, processor,
static_cast<receive_type>(receive_category::var_put),
MPI_COMM_WORLD);
free(payload);
}
int register_location_(void* location, size_t size) {
locations_.insert(bimap_pair(location, vars_));
return vars_++;
}
void unregister_location_(void* location) {
locations_.left.erase(location);
}
void internal_get_(int processor, void* variable, void* target, size_t size,
int offset, int count) {}
virtual void internal_send_(int processor, void* tag, void* content,
size_t tag_size, size_t content_size) {}
std::string name() { return std::string(name_); }
private:
size_t tag_size_ = 0;
char name_[MPI_MAX_PROCESSOR_NAME];
int name_length_;
int pid_;
int nprocs_;
int vars_ = 0;
boost::bimap<void*, var_id_type> locations_;
using bimap_pair = decltype(locations_)::value_type;
};
} // namespace mpi
} // namespace bulk
|
Add 'put' communication to MPI backend
|
Add 'put' communication to MPI backend
|
C++
|
mit
|
jwbuurlage/Bulk
|
25de837c23f79c4bdd6d341f21b504cd3a03f70c
|
src/lib/FlightTasks/tasks/Orbit/FlightTaskOrbit.cpp
|
src/lib/FlightTasks/tasks/Orbit/FlightTaskOrbit.cpp
|
/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file FlightTaskOrbit.cpp
*/
#include "FlightTaskOrbit.hpp"
#include <mathlib/mathlib.h>
#include <lib/ecl/geo/geo.h>
#include <uORB/topics/orbit_status.h>
using namespace matrix;
FlightTaskOrbit::FlightTaskOrbit()
{
_sticks_data_required = false;
}
FlightTaskOrbit::~FlightTaskOrbit()
{
orb_unadvertise(_orbit_status_pub);
}
bool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command)
{
bool ret = true;
// save previous velocity and roatation direction
float v = fabsf(_v);
bool clockwise = _v > 0;
// commanded radius
if (PX4_ISFINITE(command.param1)) {
clockwise = command.param1 > 0;
const float r = fabsf(command.param1);
ret = ret && setRadius(r);
}
// commanded velocity, take sign of radius as rotation direction
if (PX4_ISFINITE(command.param2)) {
v = command.param2;
}
ret = ret && setVelocity(v * (clockwise ? 1.f : -1.f));
// TODO: apply x,y / z independently in geo library
// commanded center coordinates
// if(PX4_ISFINITE(command.param5) && PX4_ISFINITE(command.param6)) {
// map_projection_global_project(command.param5, command.param6, &_center(0), &_center(1));
// }
// commanded altitude
// if(PX4_ISFINITE(command.param7)) {
// _position_setpoint(2) = gl_ref.alt - command.param7;
// }
if (PX4_ISFINITE(command.param5) && PX4_ISFINITE(command.param6) && PX4_ISFINITE(command.param7)) {
if (globallocalconverter_tolocal(command.param5, command.param6, command.param7, &_center(0), &_center(1),
&_position_setpoint(2))) {
// global to local conversion failed
ret = false;
}
}
return ret;
}
bool FlightTaskOrbit::sendTelemetry()
{
orbit_status_s _orbit_status = {};
_orbit_status.timestamp = hrt_absolute_time();
_orbit_status.radius = _r;
_orbit_status.frame = 0; // MAV_FRAME::MAV_FRAME_GLOBAL
if (globallocalconverter_toglobal(_center(0), _center(1), _position_setpoint(2), &_orbit_status.x, &_orbit_status.y,
&_orbit_status.z)) {
return false; // don't send the message if the transformation failed
}
if (_orbit_status_pub == nullptr) {
_orbit_status_pub = orb_advertise(ORB_ID(orbit_status), &_orbit_status);
} else {
orb_publish(ORB_ID(orbit_status), _orbit_status_pub, &_orbit_status);
}
return true;
}
bool FlightTaskOrbit::setRadius(const float r)
{
if (math::isInRange(r, _radius_min, _radius_max)) {
// small radius is more important than high velocity for safety
if (!checkAcceleration(r, _v, _acceleration_max)) {
_v = math::sign(_v) * sqrtf(_acceleration_max * r);
}
_r = r;
return true;
}
return false;
}
bool FlightTaskOrbit::setVelocity(const float v)
{
if (fabs(v) < _velocity_max &&
checkAcceleration(_r, v, _acceleration_max)) {
_v = v;
return true;
}
return false;
}
bool FlightTaskOrbit::checkAcceleration(float r, float v, float a)
{
return v * v < a * r;
}
bool FlightTaskOrbit::activate()
{
bool ret = FlightTaskManualAltitudeSmooth::activate();
_r = _radius_min;
_v = 1.f;
_center = Vector2f(_position);
_center(0) -= _r;
// need a valid position and velocity
ret = ret && PX4_ISFINITE(_position(0))
&& PX4_ISFINITE(_position(1))
&& PX4_ISFINITE(_position(2))
&& PX4_ISFINITE(_velocity(0))
&& PX4_ISFINITE(_velocity(1))
&& PX4_ISFINITE(_velocity(2));
return ret;
}
bool FlightTaskOrbit::update()
{
// update altitude
FlightTaskManualAltitudeSmooth::update();
// stick input adjusts parameters within a fixed time frame
const float r = _r - _sticks_expo(0) * _deltatime * (_radius_max / 8.f);
const float v = _v - _sticks_expo(1) * _deltatime * (_velocity_max / 4.f);
setRadius(r);
setVelocity(v);
// xy velocity to go around in a circle
Vector2f center_to_position = Vector2f(_position) - _center;
Vector2f velocity_xy(-center_to_position(1), center_to_position(0));
velocity_xy = velocity_xy.unit_or_zero();
velocity_xy *= _v;
// xy velocity adjustment to stay on the radius distance
velocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero();
_velocity_setpoint(0) = velocity_xy(0);
_velocity_setpoint(1) = velocity_xy(1);
// make vehicle front always point towards the center
_yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F;
// yawspeed feed-forward because we know the necessary angular rate
_yawspeed_setpoint = _v / _r;
// publish telemetry
sendTelemetry();
return true;
}
|
/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file FlightTaskOrbit.cpp
*/
#include "FlightTaskOrbit.hpp"
#include <mathlib/mathlib.h>
#include <lib/ecl/geo/geo.h>
#include <uORB/topics/orbit_status.h>
using namespace matrix;
FlightTaskOrbit::FlightTaskOrbit()
{
_sticks_data_required = false;
}
FlightTaskOrbit::~FlightTaskOrbit()
{
orb_unadvertise(_orbit_status_pub);
}
bool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command)
{
bool ret = true;
// save previous velocity and roatation direction
float v = fabsf(_v);
bool clockwise = _v > 0;
// commanded radius
if (PX4_ISFINITE(command.param1)) {
clockwise = command.param1 > 0;
const float r = fabsf(command.param1);
ret = ret && setRadius(r);
}
// commanded velocity, take sign of radius as rotation direction
if (PX4_ISFINITE(command.param2)) {
v = command.param2;
}
ret = ret && setVelocity(v * (clockwise ? 1.f : -1.f));
// TODO: apply x,y / z independently in geo library
// commanded center coordinates
// if(PX4_ISFINITE(command.param5) && PX4_ISFINITE(command.param6)) {
// map_projection_global_project(command.param5, command.param6, &_center(0), &_center(1));
// }
// commanded altitude
// if(PX4_ISFINITE(command.param7)) {
// _position_setpoint(2) = gl_ref.alt - command.param7;
// }
if (PX4_ISFINITE(command.param5) && PX4_ISFINITE(command.param6) && PX4_ISFINITE(command.param7)) {
if (globallocalconverter_tolocal(command.param5, command.param6, command.param7, &_center(0), &_center(1),
&_position_setpoint(2))) {
// global to local conversion failed
ret = false;
}
}
return ret;
}
bool FlightTaskOrbit::sendTelemetry()
{
orbit_status_s _orbit_status = {};
_orbit_status.timestamp = hrt_absolute_time();
_orbit_status.radius = math::signNoZero(_v) * _r;
_orbit_status.frame = 0; // MAV_FRAME::MAV_FRAME_GLOBAL
if (globallocalconverter_toglobal(_center(0), _center(1), _position_setpoint(2), &_orbit_status.x, &_orbit_status.y,
&_orbit_status.z)) {
return false; // don't send the message if the transformation failed
}
if (_orbit_status_pub == nullptr) {
_orbit_status_pub = orb_advertise(ORB_ID(orbit_status), &_orbit_status);
} else {
orb_publish(ORB_ID(orbit_status), _orbit_status_pub, &_orbit_status);
}
return true;
}
bool FlightTaskOrbit::setRadius(const float r)
{
if (math::isInRange(r, _radius_min, _radius_max)) {
// small radius is more important than high velocity for safety
if (!checkAcceleration(r, _v, _acceleration_max)) {
_v = math::sign(_v) * sqrtf(_acceleration_max * r);
}
_r = r;
return true;
}
return false;
}
bool FlightTaskOrbit::setVelocity(const float v)
{
if (fabs(v) < _velocity_max &&
checkAcceleration(_r, v, _acceleration_max)) {
_v = v;
return true;
}
return false;
}
bool FlightTaskOrbit::checkAcceleration(float r, float v, float a)
{
return v * v < a * r;
}
bool FlightTaskOrbit::activate()
{
bool ret = FlightTaskManualAltitudeSmooth::activate();
_r = _radius_min;
_v = 1.f;
_center = Vector2f(_position);
_center(0) -= _r;
// need a valid position and velocity
ret = ret && PX4_ISFINITE(_position(0))
&& PX4_ISFINITE(_position(1))
&& PX4_ISFINITE(_position(2))
&& PX4_ISFINITE(_velocity(0))
&& PX4_ISFINITE(_velocity(1))
&& PX4_ISFINITE(_velocity(2));
return ret;
}
bool FlightTaskOrbit::update()
{
// update altitude
FlightTaskManualAltitudeSmooth::update();
// stick input adjusts parameters within a fixed time frame
const float r = _r - _sticks_expo(0) * _deltatime * (_radius_max / 8.f);
const float v = _v - _sticks_expo(1) * _deltatime * (_velocity_max / 4.f);
setRadius(r);
setVelocity(v);
// xy velocity to go around in a circle
Vector2f center_to_position = Vector2f(_position) - _center;
Vector2f velocity_xy(-center_to_position(1), center_to_position(0));
velocity_xy = velocity_xy.unit_or_zero();
velocity_xy *= _v;
// xy velocity adjustment to stay on the radius distance
velocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero();
_velocity_setpoint(0) = velocity_xy(0);
_velocity_setpoint(1) = velocity_xy(1);
// make vehicle front always point towards the center
_yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F;
// yawspeed feed-forward because we know the necessary angular rate
_yawspeed_setpoint = _v / _r;
// publish telemetry
sendTelemetry();
return true;
}
|
fix rotation direction in telemetry
|
FlightTaskOrbit: fix rotation direction in telemetry
|
C++
|
bsd-3-clause
|
dagar/Firmware,krbeverx/Firmware,acfloria/Firmware,PX4/Firmware,PX4/Firmware,acfloria/Firmware,krbeverx/Firmware,krbeverx/Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,acfloria/Firmware,dagar/Firmware,acfloria/Firmware,dagar/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,dagar/Firmware,krbeverx/Firmware,mje-nz/PX4-Firmware,krbeverx/Firmware,PX4/Firmware,krbeverx/Firmware,acfloria/Firmware,dagar/Firmware,mje-nz/PX4-Firmware,PX4/Firmware,mje-nz/PX4-Firmware,PX4/Firmware,dagar/Firmware,mje-nz/PX4-Firmware,krbeverx/Firmware,PX4/Firmware,acfloria/Firmware,PX4/Firmware,dagar/Firmware
|
df8ab9ff8670cbb54e480f9147e5cc4b3a7db0dc
|
src/DspRate.cpp
|
src/DspRate.cpp
|
#include "pch.h"
#include "DspRate.h"
namespace SaneAudioRenderer
{
DspRate::~DspRate()
{
DestroyBackend();
}
void DspRate::Initialize(uint32_t inputRate, uint32_t outputRate, uint32_t channels)
{
DestroyBackend();
m_inputRate = inputRate;
m_outputRate = outputRate;
m_channels = channels;
if (inputRate != outputRate)
{
soxr_io_spec_t ioSpec{SOXR_FLOAT32_I, SOXR_FLOAT32_I, 1.0, nullptr, 0};
soxr_quality_spec_t quality = soxr_quality_spec(SOXR_VHQ, 0);
m_soxr = soxr_create(inputRate, outputRate, channels, nullptr, &ioSpec, &quality, nullptr);
}
}
bool DspRate::Active()
{
return !!m_soxr;
}
void DspRate::Process(DspChunk& chunk)
{
if (m_soxr && !chunk.IsEmpty())
{
DspChunk::ToFloat(chunk);
assert(chunk.GetFormat() == DspFormat::Float);
assert(chunk.GetRate() == m_inputRate);
assert(chunk.GetChannelCount() == m_channels);
size_t outputFrames = (size_t)((uint64_t)chunk.GetFrameCount() * 2 * m_outputRate / chunk.GetRate());
DspChunk output(DspFormat::Float, chunk.GetChannelCount(), outputFrames, m_outputRate);
size_t inputDone = 0;
size_t outputDone = 0;
soxr_process(m_soxr, chunk.GetConstData(), chunk.GetFrameCount(), &inputDone,
output.GetData(), output.GetFrameCount(), &outputDone);
assert(inputDone == chunk.GetFrameCount());
output.Shrink(outputDone);
chunk = std::move(output);
}
}
void DspRate::Finish(DspChunk& chunk)
{
Process(chunk);
size_t delay = (size_t)soxr_delay(m_soxr);
if (delay > 0)
{
DspChunk output(DspFormat::Float, m_channels, chunk.GetFrameCount() + delay, m_outputRate);
if (!chunk.IsEmpty())
memcpy(output.GetData(), chunk.GetConstData(), chunk.GetSize());
size_t inputDone = 0;
size_t outputDone = 0;
soxr_process(m_soxr, nullptr, 0, &inputDone,
output.GetData() + chunk.GetSize(), output.GetFrameCount() - chunk.GetFrameCount(), &outputDone);
assert(outputDone == delay);
}
}
void DspRate::DestroyBackend()
{
if (m_soxr)
{
soxr_delete(m_soxr);
m_soxr = nullptr;
}
}
}
|
#include "pch.h"
#include "DspRate.h"
namespace SaneAudioRenderer
{
DspRate::~DspRate()
{
DestroyBackend();
}
void DspRate::Initialize(uint32_t inputRate, uint32_t outputRate, uint32_t channels)
{
DestroyBackend();
m_inputRate = inputRate;
m_outputRate = outputRate;
m_channels = channels;
if (inputRate != outputRate)
{
soxr_io_spec_t ioSpec{SOXR_FLOAT32_I, SOXR_FLOAT32_I, 1.0, nullptr, 0};
soxr_quality_spec_t quality = soxr_quality_spec(SOXR_VHQ, 0);
m_soxr = soxr_create(inputRate, outputRate, channels, nullptr, &ioSpec, &quality, nullptr);
}
}
bool DspRate::Active()
{
return !!m_soxr;
}
void DspRate::Process(DspChunk& chunk)
{
if (m_soxr && !chunk.IsEmpty())
{
DspChunk::ToFloat(chunk);
assert(chunk.GetFormat() == DspFormat::Float);
assert(chunk.GetRate() == m_inputRate);
assert(chunk.GetChannelCount() == m_channels);
size_t outputFrames = (size_t)((uint64_t)chunk.GetFrameCount() * 2 * m_outputRate / chunk.GetRate());
DspChunk output(DspFormat::Float, chunk.GetChannelCount(), outputFrames, m_outputRate);
size_t inputDone = 0;
size_t outputDone = 0;
soxr_process(m_soxr, chunk.GetConstData(), chunk.GetFrameCount(), &inputDone,
output.GetData(), output.GetFrameCount(), &outputDone);
assert(inputDone == chunk.GetFrameCount());
output.Shrink(outputDone);
chunk = std::move(output);
}
}
void DspRate::Finish(DspChunk& chunk)
{
if (m_soxr)
{
Process(chunk);
for (;;)
{
DspChunk output(DspFormat::Float, m_channels, chunk.GetFrameCount() + m_outputRate, m_outputRate);
if (!chunk.IsEmpty())
{
assert(output.GetFormat() == chunk.GetFormat());
assert(output.GetFrameSize() == chunk.GetFrameSize());
memcpy(output.GetData(), chunk.GetConstData(), chunk.GetSize());
}
size_t inputDone = 0;
size_t outputDo = output.GetFrameCount() - chunk.GetFrameCount();
size_t outputDone = 0;
soxr_process(m_soxr, nullptr, 0, &inputDone, output.GetData() + chunk.GetSize(), outputDo, &outputDone);
output.Shrink(outputDone);
chunk = std::move(output);
if (outputDone < outputDo)
break;
}
}
}
void DspRate::DestroyBackend()
{
if (m_soxr)
{
soxr_delete(m_soxr);
m_soxr = nullptr;
}
}
}
|
Fix rate dsp Finish() method
|
Fix rate dsp Finish() method
|
C++
|
lgpl-2.1
|
kasper93/sanear,kasper93/sanear,alexmarsev/sanear,alexmarsev/sanear,kasper93/sanear
|
c126c980270b1c5334bbb8d4532bba89dda70896
|
core/imt/src/TPoolManager.cxx
|
core/imt/src/TPoolManager.cxx
|
#include "ROOT/TPoolManager.hxx"
#include "TError.h"
#include "TROOT.h"
#include <algorithm>
#include "tbb/task_scheduler_init.h"
namespace ROOT {
namespace Internal {
//Returns the weak_ptr reflecting a shared_ptr to the only instance of the Pool Manager.
//This will allow to check if the shared_ptr is still alive, solving the dangling pointer problem.
std::weak_ptr<TPoolManager> &GetWP()
{
static std::weak_ptr<TPoolManager> weak_sched;
return weak_sched;
}
UInt_t TPoolManager::fgPoolSize = 0;
TPoolManager::TPoolManager(UInt_t nThreads): fSched(new tbb::task_scheduler_init(tbb::task_scheduler_init::deferred))
{
//Is it there another instance of the tbb scheduler running?
if (fSched->is_active()) {
mustDelete = false;
}
nThreads = nThreads != 0 ? nThreads : tbb::task_scheduler_init::default_num_threads();
fSched ->initialize(nThreads);
fgPoolSize = nThreads;
};
TPoolManager::~TPoolManager()
{
//Only terminate the tbb scheduler if there was not another instance already
// running when the constructor was called.
if (mustDelete) {
fSched->terminate();
fgPoolSize = 0;
}
GetWP().reset();
}
//Number of threads the PoolManager has been initialized with.
UInt_t TPoolManager::GetPoolSize()
{
return fgPoolSize;
}
//Factory function returning a shared pointer to the only instance of the PoolManager.
std::shared_ptr<TPoolManager> GetPoolManager(UInt_t nThreads)
{
if (GetWP().lock() == nullptr) {
std::shared_ptr<TPoolManager> shared(new TPoolManager(nThreads));
GetWP() = shared;
return GetWP().lock();
}
return GetWP().lock();
}
}
}
|
#include "ROOT/TPoolManager.hxx"
#include "TError.h"
#include "TROOT.h"
#include <algorithm>
#include "tbb/task_scheduler_init.h"
namespace ROOT {
namespace Internal {
//Returns the weak_ptr reflecting a shared_ptr to the only instance of the Pool Manager.
//This will allow to check if the shared_ptr is still alive, solving the dangling pointer problem.
std::weak_ptr<TPoolManager> &GetWP()
{
static std::weak_ptr<TPoolManager> weak_sched;
return weak_sched;
}
UInt_t TPoolManager::fgPoolSize = 0;
TPoolManager::TPoolManager(UInt_t nThreads): fSched(new tbb::task_scheduler_init(tbb::task_scheduler_init::deferred))
{
//Is it there another instance of the tbb scheduler running?
if (fSched->is_active()) {
mustDelete = false;
}
nThreads = nThreads != 0 ? nThreads : tbb::task_scheduler_init::default_num_threads();
fSched ->initialize(nThreads);
fgPoolSize = nThreads;
};
TPoolManager::~TPoolManager()
{
//Only terminate the tbb scheduler if there was not another instance already
// running when the constructor was called.
if (mustDelete) {
fSched->terminate();
fgPoolSize = 0;
}
}
//Number of threads the PoolManager has been initialized with.
UInt_t TPoolManager::GetPoolSize()
{
return fgPoolSize;
}
//Factory function returning a shared pointer to the only instance of the PoolManager.
std::shared_ptr<TPoolManager> GetPoolManager(UInt_t nThreads)
{
if (GetWP().expired()) {
std::shared_ptr<TPoolManager> shared(new TPoolManager(nThreads));
GetWP() = shared;
return GetWP().lock();
}
return GetWP().lock();
}
}
}
|
Fix ROOT-8850 avoiding to reset a shared_ptr which went out of scope
|
Fix ROOT-8850 avoiding to reset a shared_ptr which went out of scope
|
C++
|
lgpl-2.1
|
karies/root,simonpf/root,simonpf/root,root-mirror/root,karies/root,karies/root,olifre/root,root-mirror/root,karies/root,simonpf/root,root-mirror/root,olifre/root,karies/root,karies/root,zzxuanyuan/root,simonpf/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,simonpf/root,zzxuanyuan/root,root-mirror/root,simonpf/root,simonpf/root,root-mirror/root,zzxuanyuan/root,simonpf/root,simonpf/root,root-mirror/root,olifre/root,root-mirror/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,olifre/root,simonpf/root,karies/root,olifre/root,zzxuanyuan/root,root-mirror/root,root-mirror/root,karies/root,karies/root,olifre/root,root-mirror/root,olifre/root,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,olifre/root,zzxuanyuan/root,simonpf/root,karies/root,karies/root
|
c8d0a7ec460dfe67c8033e416eb3d688f0e4a287
|
core/src/crypto/AESCipher.hpp
|
core/src/crypto/AESCipher.hpp
|
/*
*
* AESCipher
* ledger-core
*
* Created by Pierre Pollastri on 08/12/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 LEDGER_CORE_AESCIPHER_HPP
#define LEDGER_CORE_AESCIPHER_HPP
#include "../api/RandomNumberGenerator.hpp"
#include <memory>
#include <string>
#include <ostream>
#include <istream>
#include "../bytes/BytesReader.h"
#include "../bytes/BytesWriter.h"
namespace ledger {
namespace core {
class AESCipher {
public:
AESCipher(const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& password, const std::string &salt, uint32_t iter);
void encrypt(std::istream *input, std::ostream *output);
void decrypt(std::istream *input, std::ostream *output);
void encrypt(BytesReader& input, BytesWriter& output);
void decrypt(BytesReader& input, BytesWriter& output);
private:
std::shared_ptr<api::RandomNumberGenerator> _rng;
std::vector<uint8_t> _key;
};
}
}
#endif //LEDGER_CORE_AESCIPHER_HPP
|
/*
*
* AESCipher
* ledger-core
*
* Created by Pierre Pollastri on 08/12/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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.
*
*/
#pragma once
#include "../api/RandomNumberGenerator.hpp"
#include <memory>
#include <string>
#include <ostream>
#include <istream>
#include "../bytes/BytesReader.h"
#include "../bytes/BytesWriter.h"
namespace ledger {
namespace core {
class AESCipher {
public:
AESCipher(const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& password, const std::string &salt, uint32_t iter);
void encrypt(std::istream *input, std::ostream *output);
void decrypt(std::istream *input, std::ostream *output);
void encrypt(BytesReader& input, BytesWriter& output);
void decrypt(BytesReader& input, BytesWriter& output);
private:
std::shared_ptr<api::RandomNumberGenerator> _rng;
std::vector<uint8_t> _key;
};
}
}
|
Use a #pragma once instead of include guards for AESCipher.
|
Use a #pragma once instead of include guards for AESCipher.
LLC-155
|
C++
|
mit
|
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
|
10888def56098e42d56d47d90bfe926a2e1e6cff
|
core/src/metadata/metadata.cc
|
core/src/metadata/metadata.cc
|
/**
* @file metadata.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice 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.
*
* @section DESCRIPTION
*
* This file implements the Metadata class.
*/
#include "metadata.h"
#include <openssl/md5.h>
#include <cassert>
#include <cstring>
/* ****************************** */
/* MACROS */
/* ****************************** */
#ifdef TILEDB_VERBOSE
#define PRINT_ERROR(x) std::cerr << TILEDB_MT_ERRMSG << x << ".\n"
#else
#define PRINT_ERROR(x) \
do { \
} while (0)
#endif
namespace tiledb {
/* ****************************** */
/* CONSTRUCTORS & DESTRUCTORS */
/* ****************************** */
Metadata::Metadata() {
array_ = nullptr;
}
Metadata::~Metadata() = default;
/* ****************************** */
/* ACCESSORS */
/* ****************************** */
Array* Metadata::array() const {
return array_;
}
const ArraySchema* Metadata::array_schema() const {
return array_->array_schema();
}
bool Metadata::overflow(int attribute_id) const {
return array_->overflow(attribute_id);
}
Status Metadata::read(const char* key, void** buffers, size_t* buffer_sizes) {
// Sanity checks
if (mode_ != TILEDB_METADATA_READ) {
std::string errmsg = "Cannot read from metadata; Invalid mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Compute subarray for the read
int subarray[8];
unsigned int coords[4];
MD5((const unsigned char*)key, strlen(key) + 1, (unsigned char*)coords);
for (int i = 0; i < 4; ++i) {
subarray[2 * i] = int(coords[i]);
subarray[2 * i + 1] = int(coords[i]);
}
// Re-init sub array
RETURN_NOT_OK(array_->reset_subarray(subarray));
// Read from array
RETURN_NOT_OK(array_->read(buffers, buffer_sizes));
return Status::Ok();
}
/* ****************************** */
/* MUTATORS */
/* ****************************** */
Status Metadata::consolidate(
Fragment*& new_fragment, std::vector<std::string>& old_fragment_names) {
// Consolidate
RETURN_NOT_OK(array_->consolidate(new_fragment, old_fragment_names));
return Status::Ok();
}
Status Metadata::finalize() {
Status st = array_->finalize();
delete array_;
array_ = nullptr;
return st;
}
Status Metadata::init(
const ArraySchema* array_schema,
const std::vector<std::string>& fragment_names,
const std::vector<BookKeeping*>& book_keeping,
tiledb_metadata_mode_t mode,
const char** attributes,
int attribute_num,
const StorageManagerConfig* config) {
// Sanity check on mode
if (mode != TILEDB_METADATA_READ && mode != TILEDB_METADATA_WRITE) {
std::string errmsg = "Cannot initialize metadata; Invalid metadata mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Set mode
mode_ = mode;
ArrayMode array_mode = (mode == TILEDB_METADATA_READ) ?
ArrayMode::READ :
ArrayMode::WRITE_UNSORTED;
// Set attributes
char** array_attributes;
int array_attribute_num;
if (attributes == nullptr) {
array_attribute_num = (mode == TILEDB_METADATA_WRITE) ?
array_schema->attribute_num() + 1 :
array_schema->attribute_num();
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < array_attribute_num; ++i) {
const char* attribute = array_schema->attribute(i).c_str();
size_t attribute_len = strlen(attribute);
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attribute);
}
} else {
array_attribute_num =
(mode == TILEDB_METADATA_WRITE) ? attribute_num + 1 : attribute_num;
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < attribute_num; ++i) {
size_t attribute_len = strlen(attributes[i]);
// Check attribute name length
if (attributes[i] == nullptr || attribute_len > TILEDB_NAME_MAX_LEN) {
std::string errmsg = "Invalid attribute name length";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attributes[i]);
}
if (mode == TILEDB_METADATA_WRITE) {
size_t attribute_len = strlen(TILEDB_COORDS);
array_attributes[array_attribute_num] = new char[attribute_len + 1];
strcpy(array_attributes[array_attribute_num], TILEDB_COORDS);
}
}
// Initialize array
array_ = new Array();
Status st = array_->init(
array_schema,
fragment_names,
book_keeping,
array_mode,
(const char**)array_attributes,
array_attribute_num,
nullptr,
config);
// Clean up
for (int i = 0; i < array_attribute_num; ++i)
delete[] array_attributes[i];
delete[] array_attributes;
return st;
}
Status Metadata::reset_attributes(const char** attributes, int attribute_num) {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Set attributes
char** array_attributes;
int array_attribute_num;
if (attributes == nullptr) {
array_attribute_num = (mode_ == TILEDB_METADATA_WRITE) ?
array_schema->attribute_num() + 1 :
array_schema->attribute_num();
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < array_attribute_num; ++i) {
const char* attribute = array_schema->attribute(i).c_str();
size_t attribute_len = strlen(attribute);
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attribute);
}
} else {
array_attribute_num =
(mode_ == TILEDB_METADATA_WRITE) ? attribute_num + 1 : attribute_num;
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < attribute_num; ++i) {
size_t attribute_len = strlen(attributes[i]);
// Check attribute name length
if (attributes[i] == nullptr || attribute_len > TILEDB_NAME_MAX_LEN) {
std::string errmsg = "Invalid attribute name length";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attributes[i]);
}
if (mode_ == TILEDB_METADATA_WRITE) {
size_t attribute_len = strlen(TILEDB_COORDS);
array_attributes[array_attribute_num] = new char[attribute_len + 1];
strcpy(array_attributes[array_attribute_num], TILEDB_COORDS);
}
}
// Reset attributes
Status st = array_->reset_attributes(
(const char**)array_attributes, array_attribute_num);
// Clean up
for (int i = 0; i < array_attribute_num; ++i)
delete[] array_attributes[i];
delete[] array_attributes;
return st;
}
Status Metadata::write(
const char* keys,
size_t keys_size,
const void** buffers,
const size_t* buffer_sizes) {
// Sanity checks
if (mode_ != TILEDB_METADATA_WRITE) {
std::string errmsg = "Cannot write to metadata; Invalid mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
if (keys == nullptr) {
std::string errmsg = "Cannot write to metadata; No keys given";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Compute array coordinates
void* coords;
size_t coords_size;
compute_array_coords(keys, keys_size, coords, coords_size);
// Prepare array buffers
const void** array_buffers;
size_t* array_buffer_sizes;
prepare_array_buffers(
coords,
coords_size,
buffers,
buffer_sizes,
array_buffers,
array_buffer_sizes);
// Write the metadata
Status st = array_->write(array_buffers, array_buffer_sizes);
// Clean up
free(coords);
free(array_buffers);
free(array_buffer_sizes);
return st;
}
/* ****************************** */
/* PRIVATE METHODS */
/* ****************************** */
void Metadata::compute_array_coords(
const char* keys,
size_t keys_size,
void*& coords,
size_t& coords_size) const {
// Compute keys offsets
size_t* keys_offsets = (size_t*)malloc(10 * sizeof(size_t));
int64_t keys_num_allocated = 10;
int64_t keys_num = 0;
bool null_char_found = true;
for (size_t i = 0; i < keys_size; ++i) {
// In case the null character is found
if (null_char_found) {
if (keys_num == keys_num_allocated) {
keys_num_allocated *= 2;
keys_offsets =
(size_t*)realloc(keys_offsets, keys_num_allocated * sizeof(size_t));
}
keys_offsets[keys_num] = i;
++keys_num;
null_char_found = false;
}
// Null character found and proper flag is set
if (keys[i] == '\0')
null_char_found = true;
}
assert(keys_num > 0);
// Compute coords
coords_size = keys_num * 4 * sizeof(int);
coords = malloc(coords_size);
size_t key_size;
const unsigned char* keys_c;
unsigned char* coords_c;
for (int64_t i = 0; i < keys_num; ++i) {
key_size = (i != keys_num - 1) ? keys_offsets[i + 1] - keys_offsets[i] :
keys_size - keys_offsets[i];
keys_c = ((const unsigned char*)keys) + keys_offsets[i];
coords_c = ((unsigned char*)coords) + i * 4 * sizeof(int);
MD5(keys_c, key_size, coords_c);
}
// Clean up
free(keys_offsets);
}
void Metadata::prepare_array_buffers(
const void* coords,
size_t coords_size,
const void** buffers,
const size_t* buffer_sizes,
const void**& array_buffers,
size_t*& array_buffer_sizes) const {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int attribute_num = array_schema->attribute_num();
const std::vector<int> attribute_ids = array_->attribute_ids();
int attribute_id_num = attribute_ids.size();
// Count number of variable-sized attributes
int var_attribute_num = 0;
for (int i = 0; i < attribute_id_num; ++i)
if (array_schema->var_size(attribute_ids[i]))
++var_attribute_num;
// Allocate space for the array buffers
array_buffers = (const void**)malloc(
(attribute_id_num + var_attribute_num) * sizeof(const void*));
array_buffer_sizes =
(size_t*)malloc((attribute_id_num + var_attribute_num) * sizeof(size_t));
// Set the array buffers
int buffer_i = 0;
int array_buffer_i = 0;
for (int i = 0; i < attribute_id_num; ++i) {
if (attribute_ids[i] == attribute_num) { // Coordinates
array_buffers[array_buffer_i] = coords;
array_buffer_sizes[array_buffer_i] = coords_size;
++array_buffer_i;
} else { // Any other attribute
array_buffers[array_buffer_i] = buffers[buffer_i];
array_buffer_sizes[array_buffer_i] = buffer_sizes[buffer_i];
++array_buffer_i;
++buffer_i;
if (array_schema->var_size(attribute_ids[i])) { // Variable-sized
array_buffers[array_buffer_i] = buffers[buffer_i];
array_buffer_sizes[array_buffer_i] = buffer_sizes[buffer_i];
++array_buffer_i;
++buffer_i;
}
}
}
}
}; // namespace tiledb
|
/**
* @file metadata.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice 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.
*
* @section DESCRIPTION
*
* This file implements the Metadata class.
*/
#include "metadata.h"
#include <openssl/md5.h>
#include <cassert>
#include <cstring>
/* ****************************** */
/* MACROS */
/* ****************************** */
#ifdef TILEDB_VERBOSE
#define PRINT_ERROR(x) std::cerr << TILEDB_MT_ERRMSG << x << ".\n"
#else
#define PRINT_ERROR(x) \
do { \
} while (0)
#endif
namespace tiledb {
/* ****************************** */
/* CONSTRUCTORS & DESTRUCTORS */
/* ****************************** */
Metadata::Metadata() {
array_ = nullptr;
}
Metadata::~Metadata() = default;
/* ****************************** */
/* ACCESSORS */
/* ****************************** */
Array* Metadata::array() const {
return array_;
}
const ArraySchema* Metadata::array_schema() const {
return array_->array_schema();
}
bool Metadata::overflow(int attribute_id) const {
return array_->overflow(attribute_id);
}
Status Metadata::read(const char* key, void** buffers, size_t* buffer_sizes) {
// Sanity checks
if (mode_ != TILEDB_METADATA_READ) {
std::string errmsg = "Cannot read from metadata; Invalid mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Compute subarray for the read
int subarray[8];
unsigned int coords[4];
MD5((const unsigned char*)key, strlen(key) + 1, (unsigned char*)coords);
for (int i = 0; i < 4; ++i) {
subarray[2 * i] = int(coords[i]);
subarray[2 * i + 1] = int(coords[i]);
}
// Re-init sub array
RETURN_NOT_OK(array_->reset_subarray(subarray));
// Read from array
RETURN_NOT_OK(array_->read(buffers, buffer_sizes));
return Status::Ok();
}
/* ****************************** */
/* MUTATORS */
/* ****************************** */
Status Metadata::consolidate(
Fragment*& new_fragment, std::vector<std::string>& old_fragment_names) {
// Consolidate
RETURN_NOT_OK(array_->consolidate(new_fragment, old_fragment_names));
return Status::Ok();
}
Status Metadata::finalize() {
Status st = array_->finalize();
delete array_;
array_ = nullptr;
return st;
}
Status Metadata::init(
const ArraySchema* array_schema,
const std::vector<std::string>& fragment_names,
const std::vector<BookKeeping*>& book_keeping,
tiledb_metadata_mode_t mode,
const char** attributes,
int attribute_num,
const StorageManagerConfig* config) {
// Sanity check on mode
if (mode != TILEDB_METADATA_READ && mode != TILEDB_METADATA_WRITE) {
std::string errmsg = "Cannot initialize metadata; Invalid metadata mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Set mode
mode_ = mode;
ArrayMode array_mode = (mode == TILEDB_METADATA_READ) ?
ArrayMode::READ :
ArrayMode::WRITE_UNSORTED;
// Set attributes
char** array_attributes;
int array_attribute_num;
if (attributes == nullptr) {
array_attribute_num = (mode == TILEDB_METADATA_WRITE) ?
array_schema->attribute_num() + 1 :
array_schema->attribute_num();
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < array_attribute_num; ++i) {
const char* attribute = array_schema->attribute(i).c_str();
size_t attribute_len = strlen(attribute);
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attribute);
}
} else {
array_attribute_num =
(mode == TILEDB_METADATA_WRITE) ? attribute_num + 1 : attribute_num;
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < attribute_num; ++i) {
size_t attribute_len = strlen(attributes[i]);
// Check attribute name length
if (attributes[i] == nullptr || attribute_len > TILEDB_NAME_MAX_LEN) {
for (int attr = 0; attr < i; ++i)
delete array_attributes[i];
delete[] array_attributes;
std::string errmsg = "Invalid attribute name length";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attributes[i]);
}
if (mode == TILEDB_METADATA_WRITE) {
size_t attribute_len = strlen(TILEDB_COORDS);
array_attributes[array_attribute_num] = new char[attribute_len + 1];
strcpy(array_attributes[array_attribute_num], TILEDB_COORDS);
}
}
// Initialize array
array_ = new Array();
Status st = array_->init(
array_schema,
fragment_names,
book_keeping,
array_mode,
(const char**)array_attributes,
array_attribute_num,
nullptr,
config);
// Clean up
for (int i = 0; i < array_attribute_num; ++i)
delete[] array_attributes[i];
delete[] array_attributes;
return st;
}
Status Metadata::reset_attributes(const char** attributes, int attribute_num) {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
// Set attributes
char** array_attributes;
int array_attribute_num;
if (attributes == nullptr) {
array_attribute_num = (mode_ == TILEDB_METADATA_WRITE) ?
array_schema->attribute_num() + 1 :
array_schema->attribute_num();
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < array_attribute_num; ++i) {
const char* attribute = array_schema->attribute(i).c_str();
size_t attribute_len = strlen(attribute);
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attribute);
}
} else {
array_attribute_num =
(mode_ == TILEDB_METADATA_WRITE) ? attribute_num + 1 : attribute_num;
array_attributes = new char*[array_attribute_num];
for (int i = 0; i < attribute_num; ++i) {
size_t attribute_len = strlen(attributes[i]);
// Check attribute name length
if (attributes[i] == nullptr || attribute_len > TILEDB_NAME_MAX_LEN) {
for (int attr = 0; attr < i; ++i)
delete array_attributes[i];
delete[] array_attributes;
std::string errmsg = "Invalid attribute name length";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
array_attributes[i] = new char[attribute_len + 1];
strcpy(array_attributes[i], attributes[i]);
}
if (mode_ == TILEDB_METADATA_WRITE) {
size_t attribute_len = strlen(TILEDB_COORDS);
array_attributes[array_attribute_num] = new char[attribute_len + 1];
strcpy(array_attributes[array_attribute_num], TILEDB_COORDS);
}
}
// Reset attributes
Status st = array_->reset_attributes(
(const char**)array_attributes, array_attribute_num);
// Clean up
for (int i = 0; i < array_attribute_num; ++i)
delete[] array_attributes[i];
delete[] array_attributes;
return st;
}
Status Metadata::write(
const char* keys,
size_t keys_size,
const void** buffers,
const size_t* buffer_sizes) {
// Sanity checks
if (mode_ != TILEDB_METADATA_WRITE) {
std::string errmsg = "Cannot write to metadata; Invalid mode";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
if (keys == nullptr) {
std::string errmsg = "Cannot write to metadata; No keys given";
PRINT_ERROR(errmsg);
return Status::MetadataError(errmsg);
}
// Compute array coordinates
void* coords;
size_t coords_size;
compute_array_coords(keys, keys_size, coords, coords_size);
// Prepare array buffers
const void** array_buffers;
size_t* array_buffer_sizes;
prepare_array_buffers(
coords,
coords_size,
buffers,
buffer_sizes,
array_buffers,
array_buffer_sizes);
// Write the metadata
Status st = array_->write(array_buffers, array_buffer_sizes);
// Clean up
free(coords);
free(array_buffers);
free(array_buffer_sizes);
return st;
}
/* ****************************** */
/* PRIVATE METHODS */
/* ****************************** */
void Metadata::compute_array_coords(
const char* keys,
size_t keys_size,
void*& coords,
size_t& coords_size) const {
// Compute keys offsets
size_t* keys_offsets = (size_t*)malloc(10 * sizeof(size_t));
int64_t keys_num_allocated = 10;
int64_t keys_num = 0;
bool null_char_found = true;
for (size_t i = 0; i < keys_size; ++i) {
// In case the null character is found
if (null_char_found) {
if (keys_num == keys_num_allocated) {
keys_num_allocated *= 2;
// TODO: this can leak if realloc fails
keys_offsets =
(size_t*)realloc(keys_offsets, keys_num_allocated * sizeof(size_t));
}
keys_offsets[keys_num] = i;
++keys_num;
null_char_found = false;
}
// Null character found and proper flag is set
if (keys[i] == '\0')
null_char_found = true;
}
assert(keys_num > 0);
// Compute coords
coords_size = keys_num * 4 * sizeof(int);
coords = malloc(coords_size);
size_t key_size;
const unsigned char* keys_c;
unsigned char* coords_c;
for (int64_t i = 0; i < keys_num; ++i) {
key_size = (i != keys_num - 1) ? keys_offsets[i + 1] - keys_offsets[i] :
keys_size - keys_offsets[i];
keys_c = ((const unsigned char*)keys) + keys_offsets[i];
coords_c = ((unsigned char*)coords) + i * 4 * sizeof(int);
MD5(keys_c, key_size, coords_c);
}
// Clean up
free(keys_offsets);
}
void Metadata::prepare_array_buffers(
const void* coords,
size_t coords_size,
const void** buffers,
const size_t* buffer_sizes,
const void**& array_buffers,
size_t*& array_buffer_sizes) const {
// For easy reference
const ArraySchema* array_schema = array_->array_schema();
int attribute_num = array_schema->attribute_num();
const std::vector<int> attribute_ids = array_->attribute_ids();
int attribute_id_num = attribute_ids.size();
// Count number of variable-sized attributes
int var_attribute_num = 0;
for (int i = 0; i < attribute_id_num; ++i)
if (array_schema->var_size(attribute_ids[i]))
++var_attribute_num;
// Allocate space for the array buffers
array_buffers = (const void**)malloc(
(attribute_id_num + var_attribute_num) * sizeof(const void*));
array_buffer_sizes =
(size_t*)malloc((attribute_id_num + var_attribute_num) * sizeof(size_t));
// Set the array buffers
int buffer_i = 0;
int array_buffer_i = 0;
for (int i = 0; i < attribute_id_num; ++i) {
if (attribute_ids[i] == attribute_num) { // Coordinates
array_buffers[array_buffer_i] = coords;
array_buffer_sizes[array_buffer_i] = coords_size;
++array_buffer_i;
} else { // Any other attribute
array_buffers[array_buffer_i] = buffers[buffer_i];
array_buffer_sizes[array_buffer_i] = buffer_sizes[buffer_i];
++array_buffer_i;
++buffer_i;
if (array_schema->var_size(attribute_ids[i])) { // Variable-sized
array_buffers[array_buffer_i] = buffers[buffer_i];
array_buffer_sizes[array_buffer_i] = buffer_sizes[buffer_i];
++array_buffer_i;
++buffer_i;
}
}
}
}
}; // namespace tiledb
|
fix memory leak in metadata
|
fix memory leak in metadata
|
C++
|
mit
|
TileDB-Inc/TileDB,npapa/TileDB,kavskalyan/TileDB,npapa/TileDB,TileDB-Inc/TileDB,TileDB-Inc/TileDB,kavskalyan/TileDB,TileDB-Inc/TileDB
|
e2a3cdf71a2dcb2a87452c17cb1ce360b1cb6465
|
src/UserSpaceInstrumentation/TestProcess.cpp
|
src/UserSpaceInstrumentation/TestProcess.cpp
|
// Copyright (c) 2021 The Orbit 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 "TestProcess.h"
#include <absl/time/clock.h>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <string>
#include <system_error>
#include <vector>
#include "OrbitBase/Logging.h"
namespace orbit_user_space_instrumentation {
namespace fs = std::filesystem;
namespace {
// Create a file at path.
void Touch(fs::path p) {
std::ofstream ofs(p);
ofs << "\n";
}
} // namespace
TestProcess::TestProcess() {
flag_file_run_child_ = std::tmpnam(nullptr);
flag_file_child_started_ = std::tmpnam(nullptr);
Touch(flag_file_run_child_);
pid_ = fork();
CHECK(pid_ != -1);
// Start the workload and have the parent wait for the startup to complete.
if (pid_ == 0) {
Workload();
exit(0);
}
std::error_code error;
while (!fs::exists(flag_file_child_started_, error)) {
CHECK(!error);
};
}
TestProcess::~TestProcess() {
std::error_code error;
fs::remove(flag_file_run_child_, error);
CHECK(!error);
int status;
waitpid(pid_, &status, 0);
CHECK(WIFEXITED(status));
fs::remove(flag_file_child_started_, error);
CHECK(!error);
}
void TestProcess::Worker() {
constexpr auto kTimeToLive = std::chrono::milliseconds(15);
const auto deadline = std::chrono::system_clock::now() + kTimeToLive;
while (true) {
if (std::chrono::system_clock::now() > deadline) {
break;
}
}
absl::MutexLock lock{&joinable_threads_mutex_};
joinable_threads_.emplace(std::this_thread::get_id());
}
void TestProcess::Workload() {
size_t kNumThreads = 4;
std::vector<std::thread> threads;
std::error_code error;
while (fs::exists(flag_file_run_child_, error) || !threads.empty()) {
CHECK(!error);
// Spawn as many threads as there are missing.
while (threads.size() < kNumThreads && fs::exists(flag_file_run_child_, error)) {
CHECK(!error);
threads.emplace_back(std::thread(&TestProcess::Worker, this));
}
Touch(flag_file_child_started_);
// Join the finished threads.
for (auto& t : threads) {
const auto id = t.get_id();
absl::MutexLock lock{&joinable_threads_mutex_};
if (joinable_threads_.count(id) != 0) {
joinable_threads_.erase(id);
t.join();
}
}
for (auto it = threads.begin(); it != threads.end();) {
if (!it->joinable()) {
it = threads.erase(it);
} else {
++it;
}
}
}
}
} // namespace orbit_user_space_instrumentation
|
// Copyright (c) 2021 The Orbit 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 "TestProcess.h"
#include <absl/time/clock.h>
#include <chrono>
#include <string>
#include <system_error>
#include <vector>
#include "OrbitBase/Logging.h"
#include "OrbitBase/WriteStringToFile.h"
namespace orbit_user_space_instrumentation {
namespace fs = std::filesystem;
namespace {
// Create a file at path.
void Touch(const fs::path& path) {
if (ErrorMessageOr<void> result = orbit_base::WriteStringToFile(path, "\n"); result.has_error()) {
ERROR("%s", result.error().message());
}
}
} // namespace
TestProcess::TestProcess() {
flag_file_run_child_ = std::tmpnam(nullptr);
flag_file_child_started_ = std::tmpnam(nullptr);
Touch(flag_file_run_child_);
pid_ = fork();
CHECK(pid_ != -1);
// Start the workload and have the parent wait for the startup to complete.
if (pid_ == 0) {
Workload();
exit(0);
}
std::error_code error;
while (!fs::exists(flag_file_child_started_, error)) {
CHECK(!error);
};
}
TestProcess::~TestProcess() {
std::error_code error;
fs::remove(flag_file_run_child_, error);
CHECK(!error);
int status;
waitpid(pid_, &status, 0);
CHECK(WIFEXITED(status));
fs::remove(flag_file_child_started_, error);
CHECK(!error);
}
void TestProcess::Worker() {
constexpr auto kTimeToLive = std::chrono::milliseconds(15);
const auto deadline = std::chrono::system_clock::now() + kTimeToLive;
while (true) {
if (std::chrono::system_clock::now() > deadline) {
break;
}
}
absl::MutexLock lock{&joinable_threads_mutex_};
joinable_threads_.emplace(std::this_thread::get_id());
}
void TestProcess::Workload() {
size_t kNumThreads = 4;
std::vector<std::thread> threads;
std::error_code error;
while (fs::exists(flag_file_run_child_, error) || !threads.empty()) {
CHECK(!error);
// Spawn as many threads as there are missing.
while (threads.size() < kNumThreads && fs::exists(flag_file_run_child_, error)) {
CHECK(!error);
threads.emplace_back(std::thread(&TestProcess::Worker, this));
}
Touch(flag_file_child_started_);
// Join the finished threads.
for (auto& t : threads) {
const auto id = t.get_id();
absl::MutexLock lock{&joinable_threads_mutex_};
if (joinable_threads_.count(id) != 0) {
joinable_threads_.erase(id);
t.join();
}
}
for (auto it = threads.begin(); it != threads.end();) {
if (!it->joinable()) {
it = threads.erase(it);
} else {
++it;
}
}
}
}
} // namespace orbit_user_space_instrumentation
|
Use WriteStringToFile in TestProcess
|
Use WriteStringToFile in TestProcess
Test: run unit-test
|
C++
|
bsd-2-clause
|
google/orbit,google/orbit,google/orbit,google/orbit
|
3255d6de4e19c359ef9bab26075df36bc1456f09
|
src/Options.cpp
|
src/Options.cpp
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#include <string>
#include <iostream>
#include <memory>
#include <vector>
#include <unordered_map>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "assert.hpp"
#include "Options.hpp"
using namespace eddic;
namespace po = boost::program_options;
struct ConfigValue {
bool defined;
boost::any value;
};
struct Configuration {
std::unordered_map<std::string, ConfigValue> values;
};
std::shared_ptr<Configuration> configuration;
std::unordered_map<std::string, std::vector<std::string>> triggers;
bool desc_init = false;
po::options_description visible("Usage : eddic [options] source.eddi");
po::options_description all("Usage : eddic [options] source.eddi");
std::pair<std::string, std::string> numeric_parser(const std::string& s){
if (s.find("-32") == 0) {
return make_pair("32", std::string("true"));
} else if (s.find("-64") == 0) {
return make_pair("64", std::string("true"));
} else {
return make_pair(std::string(), std::string());
}
}
void add_trigger(const std::string& option, std::vector<std::string> childs){
triggers[option] = childs;
}
inline void trigger_childs(const std::vector<std::string>& childs){
for(auto& child : childs){
configuration->values[child].defined = true;
configuration->values[child].value = std::string("true");
}
}
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
//Only if the description has not been already defined
if(!desc_init){
po::options_description general("General options");
general.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("keep,k", "Keep the assembly file")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("debug,g", "Add debugging symbols")
("32", "Force the compilation for 32 bits platform")
("64", "Force the compilation for 64 bits platform")
("warning-all", "Enable all the warning messages")
("warning-unused", "Warn about unused variables, parameters and functions")
("warning-cast", "Warn about useless casts");
po::options_description display("Display options");
display.add_options()
("ast", "Print the Abstract Syntax Tree representation of the source")
("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
("mtac", "Print the medium-level Three Address Code representation of the source")
("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed")
("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)")
("ltac", "Print the low-level Three Address Code representation of the source")
("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)");
po::options_description optimization("Optimization options");
optimization.add_options()
("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level")
("O0", "Disable all optimizations")
("O1", "Enable low-level optimizations")
("O2", "Enable all optimizations. This can be slow for big programs.")
("fglobal-optimization", "Enable optimizer engine")
("fvariable-allocation", "Enable variable allocation in register")
("fparameter-allocation", "Enable parameter allocation in register")
("fpeephole-optimization", "Enable peephole optimizer")
("finline-functions", "Enable inlining")
("fno-inline-functions", "Disable inlining");
po::options_description backend("Backend options");
backend.add_options()
("quiet,q", "Do not print anything")
("verbose,v", "Make the compiler verbose")
("dev,d", "Activate development mode (very verbose)")
("perfs", "Display performance information")
("input", po::value<std::string>(), "Input file");
all.add(general).add(display).add(optimization).add(backend);
visible.add(general).add(display).add(optimization);
add_trigger("warning-all", {"warning-unused", "warning-cast"});
//TODO Should be a better way to do that
add_trigger("__1", {"fpeephole-optimization"});
add_trigger("__2", {"fglobal-optimization", "fvariable-allocation", "fparameter-allocation", "finline-functions"});
desc_init = true;
}
//Add the option of the input file
po::positional_options_description p;
p.add("input", -1);
//Create a new set of options
po::variables_map options;
//Create a new configuration
configuration = std::make_shared<Configuration>();
//Parse the command line options
po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options);
po::notify(options);
//Transfer the options in the eddic configuration
for(auto& option : all.options()){
ConfigValue value;
if(options.count(option->long_name())){
value.defined = true;
value.value = options[option->long_name()].value();
} else {
value.defined = false;
value.value = std::string("false");
}
configuration->values[option->long_name()] = value;
}
if(options.count("O0") + options.count("O1") + options.count("O2") > 1){
std::cout << "Invalid command line options : only one optimization level should be set" << std::endl;
return false;
}
if(options.count("64") && options.count("32")){
std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;
return false;
}
//TODO Perhaps a more clear way to do that
if(options.count("O0")){
configuration->values["Opt"].value = 0;
} else if(options.count("O1")){
configuration->values["Opt"].value = 1;
} else if(options.count("O2")){
configuration->values["Opt"].value = 2;
}
//Triggers dependent options
for(auto& trigger : triggers){
if(option_defined(trigger.first)){
trigger_childs(trigger.second);
}
}
if(option_int_value("Opt") >= 1){
trigger_childs(triggers["__1"]);
}
if(option_int_value("Opt") >= 2){
trigger_childs(triggers["__2"]);
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
bool eddic::option_defined(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return configuration->values[option_name].defined;
}
std::string eddic::option_value(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return boost::any_cast<std::string>(configuration->values[option_name].value);
}
int eddic::option_int_value(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return boost::any_cast<int>(configuration->values[option_name].value);
}
void eddic::print_help(){
std::cout << visible << std::endl;
}
void eddic::print_version(){
std::cout << "eddic version 1.0.3" << std::endl;
}
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#include <string>
#include <iostream>
#include <memory>
#include <vector>
#include <unordered_map>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "assert.hpp"
#include "Options.hpp"
using namespace eddic;
namespace po = boost::program_options;
struct ConfigValue {
bool defined;
boost::any value;
};
struct Configuration {
std::unordered_map<std::string, ConfigValue> values;
};
std::shared_ptr<Configuration> configuration;
std::unordered_map<std::string, std::vector<std::string>> triggers;
bool desc_init = false;
po::options_description visible("Usage : eddic [options] source.eddi");
po::options_description all("Usage : eddic [options] source.eddi");
std::pair<std::string, std::string> numeric_parser(const std::string& s){
if (s.find("-32") == 0) {
return make_pair("32", std::string("true"));
} else if (s.find("-64") == 0) {
return make_pair("64", std::string("true"));
} else {
return make_pair(std::string(), std::string());
}
}
void add_trigger(const std::string& option, std::vector<std::string> childs){
triggers[option] = childs;
}
inline void trigger_childs(const std::vector<std::string>& childs){
for(auto& child : childs){
configuration->values[child].defined = true;
configuration->values[child].value = std::string("true");
}
}
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
//Only if the description has not been already defined
if(!desc_init){
po::options_description general("General options");
general.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("keep,k", "Keep the assembly file")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("debug,g", "Add debugging symbols")
("32", "Force the compilation for 32 bits platform")
("64", "Force the compilation for 64 bits platform")
("warning-all", "Enable all the warning messages")
("warning-unused", "Warn about unused variables, parameters and functions")
("warning-cast", "Warn about useless casts");
po::options_description display("Display options");
display.add_options()
("ast", "Print the Abstract Syntax Tree representation of the source")
("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
("mtac", "Print the medium-level Three Address Code representation of the source")
("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed")
("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)")
("ltac", "Print the low-level Three Address Code representation of the source")
("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)");
po::options_description optimization("Optimization options");
optimization.add_options()
("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level")
("O0", "Disable all optimizations")
("O1", "Enable low-level optimizations")
("O2", "Enable all optimizations. This can be slow for big programs.")
("fglobal-optimization", "Enable optimizer engine")
("fvariable-allocation", "Enable variable allocation in register")
("fparameter-allocation", "Enable parameter allocation in register")
("fpeephole-optimization", "Enable peephole optimizer")
("fomit-frame-pointer", "Omit frame pointer from functions")
("finline-functions", "Enable inlining")
("fno-inline-functions", "Disable inlining");
po::options_description backend("Backend options");
backend.add_options()
("quiet,q", "Do not print anything")
("verbose,v", "Make the compiler verbose")
("dev,d", "Activate development mode (very verbose)")
("perfs", "Display performance information")
("input", po::value<std::string>(), "Input file");
all.add(general).add(display).add(optimization).add(backend);
visible.add(general).add(display).add(optimization);
add_trigger("warning-all", {"warning-unused", "warning-cast"});
//TODO Should be a better way to do that
add_trigger("__1", {"fpeephole-optimization"});
add_trigger("__2", {"fglobal-optimization", "fvariable-allocation", "fparameter-allocation", "finline-functions"});
desc_init = true;
}
//Add the option of the input file
po::positional_options_description p;
p.add("input", -1);
//Create a new set of options
po::variables_map options;
//Create a new configuration
configuration = std::make_shared<Configuration>();
//Parse the command line options
po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options);
po::notify(options);
//Transfer the options in the eddic configuration
for(auto& option : all.options()){
ConfigValue value;
if(options.count(option->long_name())){
value.defined = true;
value.value = options[option->long_name()].value();
} else {
value.defined = false;
value.value = std::string("false");
}
configuration->values[option->long_name()] = value;
}
if(options.count("O0") + options.count("O1") + options.count("O2") > 1){
std::cout << "Invalid command line options : only one optimization level should be set" << std::endl;
return false;
}
if(options.count("64") && options.count("32")){
std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;
return false;
}
//TODO Perhaps a more clear way to do that
if(options.count("O0")){
configuration->values["Opt"].value = 0;
} else if(options.count("O1")){
configuration->values["Opt"].value = 1;
} else if(options.count("O2")){
configuration->values["Opt"].value = 2;
}
//Triggers dependent options
for(auto& trigger : triggers){
if(option_defined(trigger.first)){
trigger_childs(trigger.second);
}
}
if(option_int_value("Opt") >= 1){
trigger_childs(triggers["__1"]);
}
if(option_int_value("Opt") >= 2){
trigger_childs(triggers["__2"]);
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
bool eddic::option_defined(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return configuration->values[option_name].defined;
}
std::string eddic::option_value(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return boost::any_cast<std::string>(configuration->values[option_name].value);
}
int eddic::option_int_value(const std::string& option_name){
ASSERT(configuration, "The configuration have not been initialized");
return boost::any_cast<int>(configuration->values[option_name].value);
}
void eddic::print_help(){
std::cout << visible << std::endl;
}
void eddic::print_version(){
std::cout << "eddic version 1.0.3" << std::endl;
}
|
Add an option to omit frame pointers
|
Add an option to omit frame pointers
|
C++
|
mit
|
wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic,wichtounet/eddic
|
f25297528de8d7f8769155eb0421ba6e52b6d90f
|
src/Readable.hh
|
src/Readable.hh
|
<?hh // strict
/**
* This file is part of hhpack\process package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\process;
interface Readable
{
/**
* Tests for end-of-file on a pointer
*/
public function eof() : bool;
/**
* Read only bytes specified from the stream
*/
public function read(int $length) : string;
}
|
<?hh // strict
/**
* This file is part of hhpack\process package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\process;
interface Readable
{
/**
* Tests for end-of-file on a pointer
*/
public function eof() : bool;
/**
* Read only bytes specified from the stream
*/
public function read(int $length = 4096) : string;
}
|
add default value
|
add default value
|
C++
|
mit
|
hhpack/process
|
974addd9c0a4090859f4aee6a56680543f7c099d
|
src/adapter.cxx
|
src/adapter.cxx
|
/*
** See Copyright Notice in LICENSE.
**/
#include "luno.hxx"
#include <cppuhelper/typeprovider.hxx>
#include <com/sun/star/beans/MethodConcept.hpp>
#include <com/sun/star/reflection/ParamMode.hpp>
using com::sun::star::beans::UnknownPropertyException;
using com::sun::star::beans::XIntrospectionAccess;
using namespace com::sun::star::lang;
using namespace com::sun::star::reflection;
using namespace com::sun::star::script;
using namespace com::sun::star::uno;
using namespace rtl;
#define OUSTRTOASCII(s) OUStringToOString(s, RTL_TEXTENCODING_ASCII_US).getStr()
#define LUNO_ADAPTER_PUSH_WRAPPED(ref) \
LUNO_PUSH_REG_WRAPPED(); \
lua_rawgeti(L, -1, ref); \
lua_replace(L, -2)
#define LUNO_ADAPTER_PUSH_ADAPTERS(ref) \
LUNO_PUSH_REG_ADAPTERS(); \
lua_rawgeti(L, -1, ref); \
lua_replace(L, -2)
namespace luno
{
/** Wraps table at index.
*/
LunoAdapter::LunoAdapter(lua_State *L_, const int index,
const Any &aTypes, const Any &aImpleId)
: L(L_),
m_WrappedRef(0),
m_AdapterRef(0),
m_Types(aTypes),
m_ImpleId(aImpleId)
{
const int top = lua_gettop(L);
// push wrapped value to wrapped
LUNO_PUSH_REG_WRAPPED();
lua_pushvalue(L, index);
m_WrappedRef = luaL_ref(L, -2);
LUNO_PUSH_REG_ADAPTERS();
lua_pushlightuserdata(L, this);
m_AdapterRef = luaL_ref(L, -2);
lua_settop(L, top);
}
LunoAdapter::~LunoAdapter()
{
const int top = lua_gettop(L);
if (m_WrappedRef)
{
LUNO_PUSH_REG_WRAPPED();
luaL_unref(L, -1, m_WrappedRef);
m_WrappedRef = 0;
}
if (m_AdapterRef)
{
LUNO_PUSH_REG_ADAPTERS();
luaL_unref(L, -1, m_AdapterRef);
m_AdapterRef = 0;
}
lua_settop(L, top);
}
LunoAdapter *LunoAdapter::create(lua_State *L_, const int index,
const Sequence< Type > &aTypes, const Sequence< sal_Int8 > &aImpleId)
{
// ToDo get types and id at first request
Any aTypes_;
Any aImpleId_;
aTypes_ <<= aTypes;
aImpleId_ <<= aImpleId;
return new LunoAdapter(L_, index, aTypes_, aImpleId_);
}
Sequence< sal_Int16 > LunoAdapter::getOutParamIndexes(const OUString &aName)
throw (RuntimeException)
{
Sequence< sal_Int16 > ret;
Runtime runtime;
Reference< XInterface > rAdapter(
runtime.getImple()->xAdapterFactory->createAdapter(this, getWrappedTypes()));
Reference< XIntrospectionAccess > xIntrospectionAcc(
runtime.getImple()->xIntrospection->inspect(makeAny(rAdapter)));
if (!xIntrospectionAcc.is())
throw RuntimeException(
OUSTRCONST("Failed to create adapter."), Reference< XInterface >());
Reference< XIdlMethod > xIdlMethod(
xIntrospectionAcc->getMethod(aName, com::sun::star::beans::MethodConcept::ALL));
if (!xIdlMethod.is())
throw RuntimeException(
OUSTRCONST("Failed to get reflection for ") + aName, Reference< XInterface >());
const Sequence< ParamInfo > aInfos(xIdlMethod->getParameterInfos());
const ParamInfo *pInfos = aInfos.getConstArray();
const int length = aInfos.getLength();
int out = 0;
int i = 0;
for (i = 0; i < length; ++i)
{
if (pInfos[i].aMode != ParamMode_IN)
++out;
}
if (out)
{
sal_Int16 j = 0;
ret.realloc(out);
sal_Int16 *pOutIndexes = ret.getArray();
for (i = 0; i < length; ++i)
{
if (pInfos[i].aMode != ParamMode_IN)
{
pOutIndexes[j] = i;
++j;
}
}
}
return ret;
}
Reference< XIntrospectionAccess > LunoAdapter::getIntrospection()
throw (RuntimeException)
{
return Reference< XIntrospectionAccess >();
}
Sequence< Type > LunoAdapter::getWrappedTypes() const
{
Sequence< Type > aTypes;
m_Types >>= aTypes;
return aTypes;
}
// Call lua_gettable in safe mode
static int luno_gettable(lua_State *L)
{
// 1: table, 2: key
lua_pushvalue(L, 2); // key
lua_gettable(L, 1);
return 1;
}
#define THROW_ON_ERROR(error) \
if (error) \
{ \
size_t length; \
const char *message = lua_tolstring(L, -1, &length); \
const OUString aMessage(message, length, RTL_TEXTENCODING_UTF8); \
lua_pop(L, 1); \
throw RuntimeException(aMessage, Reference< XInterface >()); \
}
#define CHECK_WRAPPED(ref) \
if (!ref) \
throw RuntimeException(OUSTRCONST("Nothing wrapped"), Reference< XInterface >())
Any LunoAdapter::invoke(const OUString &aName, const Sequence< Any > &aParams,
Sequence< sal_Int16 > &aOutParamIndex, Sequence< Any > &aOutParam)
throw (IllegalArgumentException, CannotConvertException,
InvocationTargetException, RuntimeException)
{
static const OUString aNameGetSomething(RTL_CONSTASCII_USTRINGPARAM("getSomething"));
static const OUString aNameGetTypes(RTL_CONSTASCII_USTRINGPARAM("getTypes"));
static const OUString aNameGetImplementationId(RTL_CONSTASCII_USTRINGPARAM("getImplementationId"));
const int nParams = (int)aParams.getLength();
if (!nParams)
{
// return cached value
if (aName.equals(aNameGetTypes))
return m_Types;
else if (aName.equals(aNameGetImplementationId))
return m_ImpleId;
}
else if (nParams == 1 && aName.equals(aNameGetSomething))
{
Sequence< sal_Int8 > id;
if (aParams[0] >>= id)
return makeAny(getSomething(id));
}
Any retAny;
const int top = lua_gettop(L);
try
{
CHECK_WRAPPED(m_WrappedRef);
Runtime runtime;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isfunction(L, -1))
{
// ToDo check is callable?
lua_settop(L, top);
throw RuntimeException(
OUSTRCONST("Method not found: ") + aName, Reference< XInterface >());
}
lua_pushvalue(L, -2); // push wrapped to first argument
// push arguments
const Any *pParams = aParams.getConstArray();
for (int i = 0; i < nParams; ++i)
runtime.anyToLua(L, pParams[i]);
// call, obj + params, var args
const int error = lua_pcall(L, nParams + 1, LUA_MULTRET, 0);
if (error)
{
// ToDo test throw exception from Lua
if (error == LUA_ERRRUN)
{
if (lua_isuserdata(L, -1))
{
LunoAdapted *p = luno_proxy_getudata(L, -1, LUNO_META_STRUCT);
if (p != NULL && p->Wrapped.getValueTypeClass() == TypeClass_EXCEPTION)
{
lua_settop(L, top);
throw InvocationTargetException(OUString(),
Reference< XInterface >(), p->Wrapped);
}
}
size_t length;
const char *message = lua_tolstring(L, -1, &length);
throw RuntimeException(OUString(message, length, RTL_TEXTENCODING_UTF8),
Reference< XInterface >());
}
else
{
// ToDo LUA_ERRGCMM
size_t length;
const char *s = lua_tolstring(L, -1, &length);
throw RuntimeException(
OUString(s, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >());
}
}
// ignore normal return value and wrapped obj
const int nOut = lua_gettop(L) - top - 1;
// convert return value. if nOut == -1, no return value and retAny being void.
if (nOut > 0)
retAny = runtime.luaToAny(L, -nOut -1);
if (nOut > 1)
{
aOutParamIndex = getOutParamIndexes(aName);
const int nOutParams = (int)aOutParamIndex.getLength();
if (nOut != nOutParams)
throw RuntimeException(
OUSTRCONST("luno: illegal number of out values for method: ") + aName,
Reference< XInterface >());
aOutParam.realloc(nOutParams);
for (int i = 0; i < nOutParams; ++i)
aOutParam[i] = runtime.luaToAny(L, top + 1 + i);
}
lua_settop(L, top);
}
catch (RuntimeException &e)
{
lua_settop(L, top);
throw;
}
return retAny;
}
// Call lua_settable in safe mode
static int luno_settable(lua_State *L)
{
// i: table, 2: key, 3: value
lua_pushvalue(L, 2); // key
lua_pushvalue(L, 3); // value
lua_settable(L, 1);
return 0;
}
void LunoAdapter::setValue(const OUString &aName, const Any &aValue)
throw (UnknownPropertyException, CannotConvertException,
InvocationTargetException, RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
lua_pushcfunction(L, luno_settable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
try
{
Runtime runtime;
runtime.anyToLua(L, aValue);
}
catch (RuntimeException &e)
{
lua_pop(L, 3);
throw;
}
const int e = lua_pcall(L, 3, 1, 0);
THROW_ON_ERROR(e);
}
Any LunoAdapter::getValue(const OUString &aName)
throw (UnknownPropertyException, RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
Any a;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
Runtime runtime;
a = runtime.luaToAny(L, -1);
lua_pop(L, 1); // result
return a;
}
sal_Bool LunoAdapter::hasMethod(const OUString &aName)
throw (RuntimeException)
{
sal_Bool b = sal_False;
CHECK_WRAPPED(m_WrappedRef);
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isfunction(L, -1))
b = sal_True;
lua_pop(L, 1); // value
return b;
}
sal_Bool LunoAdapter::hasProperty(const OUString &aName)
throw (RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
sal_Bool b = sal_False;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isnil(L, -1))
b = sal_True;
lua_pop(L, 1); // value
return b;
}
static cppu::OImplementationId g_Id(sal_False);
Sequence< sal_Int8 > LunoAdapter::getUnoTunnelImplementationId()
{
return g_Id.getImplementationId();
}
sal_Int64 LunoAdapter::getSomething(const Sequence< sal_Int8 > &aIdentifier)
throw (RuntimeException)
{
if (aIdentifier == g_Id.getImplementationId())
return reinterpret_cast< sal_Int64 >(this);
return 0;
}
} // luno
|
/*
** See Copyright Notice in LICENSE.
**/
#include "luno.hxx"
#include <cppuhelper/typeprovider.hxx>
#include <com/sun/star/beans/MethodConcept.hpp>
#include <com/sun/star/reflection/ParamMode.hpp>
using com::sun::star::beans::UnknownPropertyException;
using com::sun::star::beans::XIntrospectionAccess;
using namespace com::sun::star::lang;
using namespace com::sun::star::reflection;
using namespace com::sun::star::script;
using namespace com::sun::star::uno;
using namespace rtl;
#define OUSTRTOASCII(s) OUStringToOString(s, RTL_TEXTENCODING_ASCII_US).getStr()
#define LUNO_ADAPTER_PUSH_WRAPPED(ref) \
LUNO_PUSH_REG_WRAPPED(); \
lua_rawgeti(L, -1, ref); \
lua_replace(L, -2)
#define LUNO_ADAPTER_PUSH_ADAPTERS(ref) \
LUNO_PUSH_REG_ADAPTERS(); \
lua_rawgeti(L, -1, ref); \
lua_replace(L, -2)
namespace luno
{
/** Wraps table at index.
*/
LunoAdapter::LunoAdapter(lua_State *L_, const int index,
const Any &aTypes, const Any &aImpleId)
: L(L_),
m_WrappedRef(0),
m_AdapterRef(0),
m_Types(aTypes),
m_ImpleId(aImpleId)
{
const int top = lua_gettop(L);
// push wrapped value to wrapped
LUNO_PUSH_REG_WRAPPED();
lua_pushvalue(L, index);
m_WrappedRef = luaL_ref(L, -2);
LUNO_PUSH_REG_ADAPTERS();
lua_pushlightuserdata(L, this);
m_AdapterRef = luaL_ref(L, -2);
lua_settop(L, top);
}
LunoAdapter::~LunoAdapter()
{
const int top = lua_gettop(L);
if (m_WrappedRef)
{
LUNO_PUSH_REG_WRAPPED();
luaL_unref(L, -1, m_WrappedRef);
m_WrappedRef = 0;
}
if (m_AdapterRef)
{
LUNO_PUSH_REG_ADAPTERS();
luaL_unref(L, -1, m_AdapterRef);
m_AdapterRef = 0;
}
lua_settop(L, top);
}
LunoAdapter *LunoAdapter::create(lua_State *L_, const int index,
const Sequence< Type > &aTypes, const Sequence< sal_Int8 > &aImpleId)
{
// ToDo get types and id at first request
Any aTypes_;
Any aImpleId_;
aTypes_ <<= aTypes;
aImpleId_ <<= aImpleId;
return new LunoAdapter(L_, index, aTypes_, aImpleId_);
}
Sequence< sal_Int16 > LunoAdapter::getOutParamIndexes(const OUString &aName)
throw (RuntimeException)
{
Sequence< sal_Int16 > ret;
Runtime runtime;
Reference< XInterface > rAdapter(
runtime.getImple()->xAdapterFactory->createAdapter(this, getWrappedTypes()));
Reference< XIntrospectionAccess > xIntrospectionAcc(
runtime.getImple()->xIntrospection->inspect(makeAny(rAdapter)));
if (!xIntrospectionAcc.is())
throw RuntimeException(
OUSTRCONST("Failed to create adapter."), Reference< XInterface >());
Reference< XIdlMethod > xIdlMethod(
xIntrospectionAcc->getMethod(aName, com::sun::star::beans::MethodConcept::ALL));
if (!xIdlMethod.is())
throw RuntimeException(
OUSTRCONST("Failed to get reflection for ") + aName, Reference< XInterface >());
const Sequence< ParamInfo > aInfos(xIdlMethod->getParameterInfos());
const ParamInfo *pInfos = aInfos.getConstArray();
const int length = aInfos.getLength();
int out = 0;
int i = 0;
for (i = 0; i < length; ++i)
{
if (pInfos[i].aMode != ParamMode_IN)
++out;
}
if (out)
{
sal_Int16 j = 0;
ret.realloc(out);
sal_Int16 *pOutIndexes = ret.getArray();
for (i = 0; i < length; ++i)
{
if (pInfos[i].aMode != ParamMode_IN)
{
pOutIndexes[j] = i;
++j;
}
}
}
return ret;
}
Reference< XIntrospectionAccess > LunoAdapter::getIntrospection()
throw (RuntimeException)
{
return Reference< XIntrospectionAccess >();
}
Sequence< Type > LunoAdapter::getWrappedTypes() const
{
Sequence< Type > aTypes;
m_Types >>= aTypes;
return aTypes;
}
// Call lua_gettable in safe mode
static int luno_gettable(lua_State *L)
{
// 1: table, 2: key
lua_pushvalue(L, 2); // key
lua_gettable(L, 1);
return 1;
}
#define THROW_ON_ERROR(error) \
if (error) \
{ \
size_t length; \
const char *message = lua_tolstring(L, -1, &length); \
const OUString aMessage(message, length, RTL_TEXTENCODING_UTF8); \
lua_pop(L, 1); \
throw RuntimeException(aMessage, Reference< XInterface >()); \
}
#define CHECK_WRAPPED(ref) \
if (!ref) \
throw RuntimeException(OUSTRCONST("Nothing wrapped"), Reference< XInterface >())
Any LunoAdapter::invoke(const OUString &aName, const Sequence< Any > &aParams,
Sequence< sal_Int16 > &aOutParamIndex, Sequence< Any > &aOutParam)
throw (IllegalArgumentException, CannotConvertException,
InvocationTargetException, RuntimeException)
{
static const OUString aNameGetSomething(RTL_CONSTASCII_USTRINGPARAM("getSomething"));
static const OUString aNameGetTypes(RTL_CONSTASCII_USTRINGPARAM("getTypes"));
static const OUString aNameGetImplementationId(RTL_CONSTASCII_USTRINGPARAM("getImplementationId"));
const int nParams = (int)aParams.getLength();
if (!nParams)
{
// return cached value
if (aName.equals(aNameGetTypes))
return m_Types;
else if (aName.equals(aNameGetImplementationId))
return m_ImpleId;
}
else if (nParams == 1 && aName.equals(aNameGetSomething))
{
Sequence< sal_Int8 > id;
if (aParams[0] >>= id)
return makeAny(getSomething(id));
}
Any retAny;
const int top = lua_gettop(L);
try
{
CHECK_WRAPPED(m_WrappedRef);
Runtime runtime;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isfunction(L, -1))
{
// ToDo check is callable?
lua_settop(L, top);
throw RuntimeException(
OUSTRCONST("Method not found: ") + aName, Reference< XInterface >());
}
lua_pushvalue(L, -2); // push wrapped to first argument
// push arguments
const Any *pParams = aParams.getConstArray();
for (int i = 0; i < nParams; ++i)
runtime.anyToLua(L, pParams[i]);
// call, obj + params, var args
const int error = lua_pcall(L, nParams + 1, LUA_MULTRET, 0);
if (error)
{
// ToDo test throw exception from Lua
if (error == LUA_ERRRUN)
{
if (lua_isuserdata(L, -1))
{
LunoAdapted *p = luno_proxy_getudata(L, -1, LUNO_META_STRUCT);
if (p != NULL && p->Wrapped.getValueTypeClass() == TypeClass_EXCEPTION)
{
lua_settop(L, top);
throw InvocationTargetException(OUString(),
Reference< XInterface >(), p->Wrapped);
}
}
size_t length;
const char *message = lua_tolstring(L, -1, &length);
throw RuntimeException(OUString(message, length, RTL_TEXTENCODING_UTF8),
Reference< XInterface >());
}
else
{
// ToDo LUA_ERRGCMM
size_t length;
const char *s = lua_tolstring(L, -1, &length);
throw RuntimeException(
OUString(s, length, RTL_TEXTENCODING_UTF8), Reference< XInterface >());
}
}
// ignore normal return value and wrapped obj
const int nOut = lua_gettop(L) - top - 1;
// convert return value. if nOut == -1, no return value and retAny being void.
if (nOut >= 0)
retAny = runtime.luaToAny(L, -nOut -1);
if (nOut > 1)
{
aOutParamIndex = getOutParamIndexes(aName);
const int nOutParams = (int)aOutParamIndex.getLength();
if (nOut != nOutParams)
throw RuntimeException(
OUSTRCONST("luno: illegal number of out values for method: ") + aName,
Reference< XInterface >());
aOutParam.realloc(nOutParams);
for (int i = 0; i < nOutParams; ++i)
aOutParam[i] = runtime.luaToAny(L, top + 1 + i);
}
lua_settop(L, top);
}
catch (RuntimeException &e)
{
lua_settop(L, top);
throw;
}
return retAny;
}
// Call lua_settable in safe mode
static int luno_settable(lua_State *L)
{
// i: table, 2: key, 3: value
lua_pushvalue(L, 2); // key
lua_pushvalue(L, 3); // value
lua_settable(L, 1);
return 0;
}
void LunoAdapter::setValue(const OUString &aName, const Any &aValue)
throw (UnknownPropertyException, CannotConvertException,
InvocationTargetException, RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
lua_pushcfunction(L, luno_settable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
try
{
Runtime runtime;
runtime.anyToLua(L, aValue);
}
catch (RuntimeException &e)
{
lua_pop(L, 3);
throw;
}
const int e = lua_pcall(L, 3, 1, 0);
THROW_ON_ERROR(e);
}
Any LunoAdapter::getValue(const OUString &aName)
throw (UnknownPropertyException, RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
Any a;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
Runtime runtime;
a = runtime.luaToAny(L, -1);
lua_pop(L, 1); // result
return a;
}
sal_Bool LunoAdapter::hasMethod(const OUString &aName)
throw (RuntimeException)
{
sal_Bool b = sal_False;
CHECK_WRAPPED(m_WrappedRef);
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isfunction(L, -1))
b = sal_True;
lua_pop(L, 1); // value
return b;
}
sal_Bool LunoAdapter::hasProperty(const OUString &aName)
throw (RuntimeException)
{
CHECK_WRAPPED(m_WrappedRef);
sal_Bool b = sal_False;
lua_pushcfunction(L, luno_gettable);
LUNO_ADAPTER_PUSH_WRAPPED(m_WrappedRef);
lua_pushstring(L, OUSTRTOASCII(aName));
const int e = lua_pcall(L, 2, 1, 0);
THROW_ON_ERROR(e);
if (!lua_isnil(L, -1))
b = sal_True;
lua_pop(L, 1); // value
return b;
}
static cppu::OImplementationId g_Id(sal_False);
Sequence< sal_Int8 > LunoAdapter::getUnoTunnelImplementationId()
{
return g_Id.getImplementationId();
}
sal_Int64 LunoAdapter::getSomething(const Sequence< sal_Int8 > &aIdentifier)
throw (RuntimeException)
{
if (aIdentifier == g_Id.getImplementationId())
return reinterpret_cast< sal_Int64 >(this);
return 0;
}
} // luno
|
Fix real return value
|
Fix real return value
|
C++
|
mit
|
hanya/luno,hanya/luno
|
27fd2b53d6fc4c1532597eada36a897c70536883
|
src/allaser.cpp
|
src/allaser.cpp
|
/**
* @author pinkasfeld joseph
* Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved.
*/
#include "allaser.h"
#include <iostream>
#include <alcommon/alproxy.h>
#include <alproxies/almemoryproxy.h>
#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <sstream>
#include <pthread.h>
#include <signal.h>
#include <cmath>
#include <qi/log.hpp>
#if defined (__linux__)
#include <sys/prctl.h>
#endif
extern "C" {
# include "urg_ctrl.h"
# include "scip_handler.h"
}
#define MODE_ON 0
#define MODE_OFF 1
#define SEND_MODE_ON 2
#define SEND_MODE_OFF 3
#define MIDDLE_ANGLE 384
#define DEFAULT_MIN_ANGLE 44
#define DEFAULT_MAX_ANGLE 725
#define MIN_ANGLE_LASER 44
#define MAX_ANGLE_LASER 725
#define RESOLUTION_LASER 1024
#define MIN_LENGTH_LASER 20
#define MAX_LENGTH_LASER 5600
#include <sys/time.h>
using namespace AL;
using namespace std;
pthread_t urgThreadId;
boost::shared_ptr<ALMemoryProxy> gSTM;
static int mode = MODE_ON;
static urg_t urg;
static int angle_min = DEFAULT_MIN_ANGLE;
static int angle_max = DEFAULT_MAX_ANGLE;
static int length_min = MIN_LENGTH_LASER;
static int length_max = MAX_LENGTH_LASER;
static void urg_exit(urg_t *urg, const char *message) {
qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg));
urg_disconnect(urg);
qiLogInfo("hardware.allaser", "urg_exit\n");
pthread_exit((void *)NULL);
}
#define URG_DEFAULT_SPEED (19200)
#define URG_FAST_SPEED (115200)
void * urgThread(void * arg) {
#if defined (__linux__)
// thread name
prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0);
#endif
ALValue urgdata;
long *data = NULL;
int data_max;
int ret;
int n;
int i,imemory,refTime,end,sampleTime, beginThread;
std::string valueName="Device/Laser/Value";
/* Connection */
connectToLaser();
/* Reserve the Receive data buffer */
data_max = urg_dataMax(&urg);
data = (long*)malloc(sizeof(long) * data_max);
memset(data, 0, sizeof(long) * data_max);
if (data == NULL) {
perror("data buffer");
pthread_exit((void *)NULL);
}
/* prepare ALValue for ALMemory*/
urgdata.arraySetSize(data_max);
for (i=0; i< data_max;i++)
{
urgdata[i].arraySetSize(4);
urgdata[i][0]= (int)0;
urgdata[i][1]= (double)0.0;
urgdata[i][2]= (int)0;
urgdata[i][3]= (int)0;
}
/* insert ALvalue in ALMemory*/
gSTM->insertData(valueName,urgdata);
gSTM->insertData("Device/Laser/LaserEnable", (bool) 1);
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)
* (DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)
* (DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MinLength",(float)(length_min));
gSTM->insertData("Device/Laser/MaxLength",(float)(length_max));
stringstream ss;
ss << "ALLaser running";
qiLogInfo("hardware.laser") << ss.str() << std::endl;
while(1)
{
if(mode==SEND_MODE_ON){
ret = urg_laserOn(&urg);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
mode=MODE_ON;
/* Connection */
connectToLaser();
}
if(mode==SEND_MODE_OFF){
scip_qt(&urg.serial_, NULL, ScipNoWaitReply);
mode=MODE_OFF;
}
if(mode==MODE_ON){
/* Request Data using GD-Command */
ret = urg_requestData(&urg, URG_GD, URG_FIRST, URG_LAST);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
refTime = getLocalTime();
/* Obtain Data */
n = urg_receiveData(&urg, data, data_max);
qiLogDebug("hardware.laser") << " n " << n << " expected " <<
angle_max - angle_min << std::endl;
if (n < 0) {
urg_exit(&urg, "urg_receiveData()");
}
end= getLocalTime();
sampleTime=end-refTime;
imemory=0;
for (i = 0; i < n; ++i) {
int x, y;
double angle = urg_index2rad(&urg, i);
qiLogDebug("hardware.laser") << i << " angle " << angle <<
" urgAngle " << urg_index2rad(&urg, i) <<
" dist " << data[i] << std::endl;
int length = data[i];
if((length>=length_min)&&(length<=length_max)){
x = (int)((double)length * cos(angle));
y = (int)((double)length * sin(angle));
urgdata[imemory][0]= length;
urgdata[imemory][1]= angle;
urgdata[imemory][2]= x;
urgdata[imemory][3]= y;
imemory++;
}
}
for(;imemory<data_max;imemory++){
urgdata[imemory][0]= 0;
urgdata[imemory][1]= 0;
urgdata[imemory][2]= 0;
urgdata[imemory][3]= 0;
}
gSTM->insertData(valueName,urgdata);
usleep(1000);
}else{
usleep(10000);
}
}
urg_disconnect(&urg);
free(data);
}
//______________________________________________
// constructor
//______________________________________________
ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName )
{
setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." );
functionName("laserOFF", "ALLaser", "Disable laser light");
BIND_METHOD( ALLaser::laserOFF );
functionName("laserON", "ALLaser", "Enable laser light and sampling");
BIND_METHOD( ALLaser::laserON );
functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser");
addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 ");
addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 ");
addMethodExample( "python",
"# Set the opening angle at -90/90 degres\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setOpeningAngle(-1.570796327,1.570796327)\n"
);
BIND_METHOD( ALLaser::setOpeningAngle );
functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser");
addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm");
addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm");
addMethodExample( "python",
"# Set detection threshold at 500/3000 mm\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setDetectingLength(500,3000)\n"
);
BIND_METHOD( ALLaser::setDetectingLength );
// get broker on DCM and ALMemory
try {
gSTM = getParentBroker()->getMemoryProxy();
} catch(ALError& e) {
qiLogError("hardware.allaser")
<< "Could not connect to Memory. Error: " << e.what() << std::endl;
}
pthread_create(&urgThreadId, NULL, urgThread, NULL);
}
//______________________________________________
// destructor
//______________________________________________
ALLaser::~ALLaser()
{
pthread_cancel(urgThreadId);
}
void ALLaser::laserOFF(void){
mode = SEND_MODE_OFF;
gSTM->insertData("Device/Laser/LaserEnable",(bool)0);
}
void ALLaser::laserON(void){
mode = SEND_MODE_ON;
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
}
void ALLaser::setOpeningAngle(const float& angle_min_f,
const float& angle_max_f){
angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER
* (float)angle_min_f / (2.0 * M_PI));
angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f
/ (2.0 * M_PI));
if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER;
if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER;
if(angle_min>=angle_max){
angle_min = MIN_ANGLE_LASER;
angle_max = MAX_ANGLE_LASER;
}
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)
* (angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)
* (angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER));
}
void ALLaser::setDetectingLength(const int& length_min_l,
const int& length_max_l){
length_min=(int)length_min_l;
length_max=(int)length_max_l;
if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER;
if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER;
if(length_min>=length_max){
length_min = MIN_LENGTH_LASER;
length_max = MAX_LENGTH_LASER;
}
gSTM->insertData("Device/Laser/MinLength",(int)length_min);
gSTM->insertData("Device/Laser/MaxLength",(int)length_max);
}
//_________________________________________________
// Service functions
//_________________________________________________
int connectToLaserViaUSB(void) {
int success = -1;
const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */
// Try to connect at low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at "
<< URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceUSB, URG_FAST_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at "
<< URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
int connectToLaserViaACM(void) {
int success = -1;
const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceACM << " at "
<< URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceACM, URG_FAST_SPEED);
if (success < 0)
{
std::stringstream ss;
ss << "Connection failure from " << deviceACM << " at "
<< URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
void connectToLaser(void){
int success = connectToLaserViaUSB();
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to USB, trying ACM... ";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
success = connectToLaserViaACM();
if (success < 0) {
std::stringstream ss;
ss << "Connection to laser failed";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
pthread_exit((void *)NULL);
}
else {
std::stringstream ss;
ss << "Connection to laser via ACM";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
else {
std::stringstream ss;
ss << "Connection to laser via USB";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
unsigned int getLocalTime(void){
struct timeval tv;
unsigned int val;
gettimeofday(&tv, NULL);
val = (unsigned int)((unsigned int)(tv.tv_usec/1000)
+ (unsigned int)(tv.tv_sec*1000));
// Time in ms
return val;
}
double index2rad(int index){
double radian = (2.0 * M_PI) *
(index - MIDDLE_ANGLE) / RESOLUTION_LASER;
return radian;
}
|
/**
* @author pinkasfeld joseph
* Copyright (c) Aldebaran Robotics 2010, 2011 All Rights Reserved.
*/
#include "allaser.h"
#include <iostream>
#include <alcommon/alproxy.h>
#include <alproxies/almemoryproxy.h>
#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <sstream>
#include <pthread.h>
#include <signal.h>
#include <cmath>
#include <qi/log.hpp>
#if defined (__linux__)
#include <sys/prctl.h>
#endif
extern "C" {
# include "urg_ctrl.h"
# include "scip_handler.h"
}
#define MODE_ON 0
#define MODE_OFF 1
#define SEND_MODE_ON 2
#define SEND_MODE_OFF 3
#define MIDDLE_ANGLE 384
#define DEFAULT_MIN_ANGLE 44
#define DEFAULT_MAX_ANGLE 725
#define MIN_ANGLE_LASER 44
#define MAX_ANGLE_LASER 725
#define RESOLUTION_LASER 1024
#define MIN_LENGTH_LASER 20
#define MAX_LENGTH_LASER 5600
#include <sys/time.h>
using namespace AL;
using namespace std;
pthread_t urgThreadId;
boost::shared_ptr<ALMemoryProxy> gSTM;
static int mode = MODE_ON;
static urg_t urg;
static int angle_min = DEFAULT_MIN_ANGLE;
static int angle_max = DEFAULT_MAX_ANGLE;
static int length_min = MIN_LENGTH_LASER;
static int length_max = MAX_LENGTH_LASER;
static void urg_exit(urg_t *urg, const char *message) {
qiLogInfo("hardware.allaser", "%s: %s\n", message, urg_error(urg));
urg_disconnect(urg);
qiLogInfo("hardware.allaser", "urg_exit\n");
pthread_exit((void *)NULL);
}
#define URG_DEFAULT_SPEED (19200)
#define URG_FAST_SPEED (115200)
void * urgThread(void * arg) {
#if defined (__linux__)
// thread name
prctl(PR_SET_NAME, "ALLaser::urgThread", 0, 0, 0);
#endif
ALValue urgdata;
long *data = NULL;
int data_max;
int ret;
int n;
int i,imemory,refTime,end,sampleTime, beginThread;
std::string valueName="Device/Laser/Value";
/* Connection */
connectToLaser();
/* Reserve the Receive data buffer */
data_max = urg_dataMax(&urg);
data = (long*)malloc(sizeof(long) * data_max);
memset(data, 0, sizeof(long) * data_max);
if (data == NULL) {
perror("data buffer");
pthread_exit((void *)NULL);
}
/* prepare ALValue for ALMemory*/
urgdata.arraySetSize(data_max);
for (i=0; i< data_max;i++)
{
urgdata[i].arraySetSize(4);
urgdata[i][0]= (int)0;
urgdata[i][1]= (double)0.0;
urgdata[i][2]= (int)0;
urgdata[i][3]= (int)0;
}
/* insert ALvalue in ALMemory*/
gSTM->insertData(valueName,urgdata);
gSTM->insertData("Device/Laser/LaserEnable", (bool) 1);
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)
* (DEFAULT_MIN_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)
* (DEFAULT_MAX_ANGLE - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MinLength",(float)(length_min));
gSTM->insertData("Device/Laser/MaxLength",(float)(length_max));
stringstream ss;
ss << "ALLaser running";
qiLogInfo("hardware.laser") << ss.str() << std::endl;
while(1)
{
if(mode==SEND_MODE_ON){
ret = urg_laserOn(&urg);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
mode=MODE_ON;
/* Connection */
connectToLaser();
}
if(mode==SEND_MODE_OFF){
scip_qt(&urg.serial_, NULL, ScipNoWaitReply);
mode=MODE_OFF;
}
if(mode==MODE_ON){
/* Request Data using GD-Command */
ret = urg_requestData(&urg, URG_GD, URG_FIRST, URG_LAST);
if (ret < 0) {
urg_exit(&urg, "urg_requestData()");
}
refTime = getLocalTime();
/* Obtain Data */
n = urg_receiveData(&urg, data, data_max);
qiLogDebug("hardware.laser") << " n " << n << " expected " <<
angle_max - angle_min << std::endl;
if (n < 0) {
urg_exit(&urg, "urg_receiveData()");
}
end= getLocalTime();
sampleTime=end-refTime;
imemory=0;
for (i = 0; i < n; ++i) {
int x, y;
double angle = urg_index2rad(&urg, i);
qiLogDebug("hardware.laser") << i << " angle " << angle <<
" urgAngle " << urg_index2rad(&urg, i) <<
" dist " << data[i] << std::endl;
int length = data[i];
if( length >= length_min && length <= length_max
&& i >= angle_min && i <= angle_max ){
x = (int)((double)length * cos(angle));
y = (int)((double)length * sin(angle));
urgdata[imemory][0]= length;
urgdata[imemory][1]= angle;
urgdata[imemory][2]= x;
urgdata[imemory][3]= y;
imemory++;
}
}
for(;imemory<data_max;imemory++){
urgdata[imemory][0]= 0;
urgdata[imemory][1]= 0;
urgdata[imemory][2]= 0;
urgdata[imemory][3]= 0;
}
gSTM->insertData(valueName,urgdata);
usleep(1000);
}else{
usleep(10000);
}
}
urg_disconnect(&urg);
free(data);
}
//______________________________________________
// constructor
//______________________________________________
ALLaser::ALLaser(boost::shared_ptr<ALBroker> pBroker, const std::string& pName ): ALModule(pBroker, pName )
{
setModuleDescription( "Allow control over Hokuyo laser when available on Nao's head." );
functionName("laserOFF", "ALLaser", "Disable laser light");
BIND_METHOD( ALLaser::laserOFF );
functionName("laserON", "ALLaser", "Enable laser light and sampling");
BIND_METHOD( ALLaser::laserON );
functionName("setOpeningAngle", "ALLaser", "Set openning angle of the laser");
addParam("angle_min_f", "float containing the min value in rad, this value must be upper than -2.35619449 ");
addParam("angle_max_f", "float containing the max value in rad, this value must be lower than 2.092349795 ");
addMethodExample( "python",
"# Set the opening angle at -90/90 degres\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setOpeningAngle(-1.570796327,1.570796327)\n"
);
BIND_METHOD( ALLaser::setOpeningAngle );
functionName("setDetectingLength", "ALLaser", "Set detection threshold of the laser");
addParam("length_min_l", "int containing the min length that the laser will detect(mm), this value must be upper than 20 mm");
addParam("length_max_l", "int containing the max length that the laser will detect(mm), this value must be lower than 5600 mm");
addMethodExample( "python",
"# Set detection threshold at 500/3000 mm\n"
"laser = ALProxy(\"ALLaser\",\"127.0.0.1\",9559)\n"
"laser.setDetectingLength(500,3000)\n"
);
BIND_METHOD( ALLaser::setDetectingLength );
// get broker on DCM and ALMemory
try {
gSTM = getParentBroker()->getMemoryProxy();
} catch(ALError& e) {
qiLogError("hardware.allaser")
<< "Could not connect to Memory. Error: " << e.what() << std::endl;
}
pthread_create(&urgThreadId, NULL, urgThread, NULL);
}
//______________________________________________
// destructor
//______________________________________________
ALLaser::~ALLaser()
{
pthread_cancel(urgThreadId);
}
void ALLaser::laserOFF(void){
mode = SEND_MODE_OFF;
gSTM->insertData("Device/Laser/LaserEnable",(bool)0);
}
void ALLaser::laserON(void){
mode = SEND_MODE_ON;
gSTM->insertData("Device/Laser/LaserEnable",(bool)1);
}
void ALLaser::setOpeningAngle(const float& angle_min_f,
const float& angle_max_f){
angle_min = MIDDLE_ANGLE + (int)(RESOLUTION_LASER
* (float)angle_min_f / (2.0 * M_PI));
angle_max = MIDDLE_ANGLE + (int)(RESOLUTION_LASER*(float)angle_max_f
/ (2.0 * M_PI));
if(angle_min<MIN_ANGLE_LASER) angle_min = MIN_ANGLE_LASER;
if(angle_max>MAX_ANGLE_LASER) angle_max = MAX_ANGLE_LASER;
if(angle_min>=angle_max){
angle_min = MIN_ANGLE_LASER;
angle_max = MAX_ANGLE_LASER;
}
gSTM->insertData("Device/Laser/MinAngle",(float)((2.0 * M_PI)
* (angle_min - MIDDLE_ANGLE) / RESOLUTION_LASER));
gSTM->insertData("Device/Laser/MaxAngle",(float)((2.0 * M_PI)
* (angle_max - MIDDLE_ANGLE) / RESOLUTION_LASER));
}
void ALLaser::setDetectingLength(const int& length_min_l,
const int& length_max_l){
length_min=(int)length_min_l;
length_max=(int)length_max_l;
if(length_min<MIN_LENGTH_LASER) length_min = MIN_LENGTH_LASER;
if(length_max>MAX_LENGTH_LASER) length_min = MAX_LENGTH_LASER;
if(length_min>=length_max){
length_min = MIN_LENGTH_LASER;
length_max = MAX_LENGTH_LASER;
}
gSTM->insertData("Device/Laser/MinLength",(int)length_min);
gSTM->insertData("Device/Laser/MaxLength",(int)length_max);
}
//_________________________________________________
// Service functions
//_________________________________________________
int connectToLaserViaUSB(void) {
int success = -1;
const char deviceUSB[] = "/dev/ttyUSB0"; /* Example when using Linux */
// Try to connect at low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at "
<< URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceUSB, URG_FAST_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceUSB << " at "
<< URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceUSB, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
int connectToLaserViaACM(void) {
int success = -1;
const char deviceACM[] = "/dev/ttyACM0"; /* Example when using Linux */
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to " << deviceACM << " at "
<< URG_DEFAULT_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
return success;
}
else {
// Try to switch to full speed.
scip_ss(&urg.serial_, URG_FAST_SPEED);
urg_disconnect(&urg);
success = urg_connect(&urg, deviceACM, URG_FAST_SPEED);
if (success < 0)
{
std::stringstream ss;
ss << "Connection failure from " << deviceACM << " at "
<< URG_FAST_SPEED << ". " << urg_error(&urg);
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
// Fall back to low speed.
success = urg_connect(&urg, deviceACM, URG_DEFAULT_SPEED);
return success;
}
else {
return success;
}
}
}
void connectToLaser(void){
int success = connectToLaserViaUSB();
if (success < 0) {
std::stringstream ss;
ss << "Connection failure to USB, trying ACM... ";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
success = connectToLaserViaACM();
if (success < 0) {
std::stringstream ss;
ss << "Connection to laser failed";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
pthread_exit((void *)NULL);
}
else {
std::stringstream ss;
ss << "Connection to laser via ACM";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
else {
std::stringstream ss;
ss << "Connection to laser via USB";
qiLogDebug("hardware.allaser") << ss.str() << std::endl;
}
}
unsigned int getLocalTime(void){
struct timeval tv;
unsigned int val;
gettimeofday(&tv, NULL);
val = (unsigned int)((unsigned int)(tv.tv_usec/1000)
+ (unsigned int)(tv.tv_sec*1000));
// Time in ms
return val;
}
double index2rad(int index){
double radian = (2.0 * M_PI) *
(index - MIDDLE_ANGLE) / RESOLUTION_LASER;
return radian;
}
|
fix setOpenning angle functionnality.
|
ALLASER: fix setOpenning angle functionnality.
|
C++
|
bsd-3-clause
|
aldebaran/allaser
|
369b70d60f774535d10a4b27e6f4ddd7aeeb7d46
|
src/sdp_solve/SDP_Solver/run/step/initialize_schur_complement_solver/initialize_Q_group.cxx
|
src/sdp_solve/SDP_Solver/run/step/initialize_schur_complement_solver/initialize_Q_group.cxx
|
#include "../../../../SDP.hxx"
#include "../../../../Block_Diagonal_Matrix.hxx"
#include "../../../../../Timers.hxx"
void initialize_Q_group(const SDP &sdp, const Block_Info &block_info,
const Block_Diagonal_Matrix &schur_complement,
Block_Matrix &schur_off_diagonal,
Block_Diagonal_Matrix &schur_complement_cholesky,
El::DistMatrix<El::BigFloat> &Q_group, Timers &timers)
{
// Explicitly deallocate the lower half of Q_group. This
// significantly reduces the total amount of memory required.
El::Matrix<El::BigFloat> &local(Q_group.Matrix());
for(int64_t row = 0; row < Q_group.Height(); ++row)
for(int64_t column = 0; column < row; ++column)
{
if(Q_group.IsLocal(row, column))
{
mpf_clear(local(Q_group.LocalRow(row), Q_group.LocalCol(column))
.gmp_float.get_mpf_t());
local(Q_group.LocalRow(row), Q_group.LocalCol(column))
.gmp_float.get_mpf_t()[0]
._mp_d
= nullptr;
}
}
schur_off_diagonal.blocks.clear();
schur_off_diagonal.blocks.reserve(schur_complement_cholesky.blocks.size());
// size_t num_rows(sdp.free_var_matrix.blocks.front().Width());
// for(auto &block: sdp.free_var_matrix.blocks)
// {
// num_rows+=block.Height();
// }
// // std::cout << "rows: " << num_rows << "\n";
// El::Matrix<double> big_matrix(num_rows,num_rows);
// El::Zero(big_matrix);
// {
// int64_t row(0);
// for(auto &block: schur_complement.blocks)
// {
// // El::Print(block,"block");
// // std::cout << "\n";
// for(int64_t block_row(0); block_row!=block.Height(); ++block_row)
// {
// for(int64_t block_column(0); block_column!=block.Width(); ++block_column)
// {
// big_matrix(row+block_row, row+block_column) = double(block.Get(block_row,block_column));
// }
// }
// row+=block.Height();
// }
// }
// {
// int64_t row(0);
// const int64_t column_offset(num_rows - sdp.free_var_matrix.blocks.front().Width());
// for(auto &block: sdp.free_var_matrix.blocks)
// {
// for(int64_t block_row(0); block_row!=block.Height(); ++block_row)
// {
// for(int64_t block_column(0); block_column!=block.Width(); ++block_column)
// {
// big_matrix(row+block_row, column_offset+block_column) =
// double(block.Get(block_row,block_column));
// big_matrix(column_offset+block_column, row+block_row) =
// big_matrix(row+block_row, column_offset+block_column);
// }
// }
// row+=block.Height();
// }
// }
// {
// // El::Print(big_matrix,"big_matrix");
// // std::cout << "\n";
// // exit(0);
// /// There is a bug in El::HermitianEig when there is more than
// /// one level of recursion when computing eigenvalues. One fix
// /// is to increase the cutoff so that there is no more than one
// /// level of recursion.
// /// An alternate workaround is to compute both eigenvalues and
// /// eigenvectors, but that seems to be significantly slower.
// El::HermitianEigCtrl<double> hermitian_eig_ctrl;
// hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = num_rows / 2 + 1;
// /// The default number of iterations is 40. That is sometimes
// /// not enough, so we bump it up significantly.
// hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 400;
// El::Matrix<double> eigenvalues;
// El::HermitianEig(El::UpperOrLowerNS::LOWER, big_matrix, eigenvalues,
// hermitian_eig_ctrl);
// double max(0), min(std::numeric_limits<double>::max());
// for(int64_t row(0); row!=eigenvalues.Height(); ++row)
// {
// max=std::max(max,std::abs(eigenvalues(row,0)));
// min=std::min(min,std::abs(eigenvalues(row,0)));
// }
// std::cout << "T Condition: "
// << (max / min) << " "
// << max << " "
// << min << "\n";
// }
El::BigFloat S_max(0), S_min(std::numeric_limits<double>::max()),
S_condition(0);
for(size_t block = 0; block < schur_complement_cholesky.blocks.size();
++block)
{
auto &cholesky_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.cholesky_"
+ std::to_string(block_info.block_indices[block])));
schur_complement_cholesky.blocks[block] = schur_complement.blocks[block];
{
/// There is a bug in El::HermitianEig when there is more than
/// one level of recursion when computing eigenvalues. One fix
/// is to increase the cutoff so that there is no more than one
/// level of recursion.
/// An alternate workaround is to compute both eigenvalues and
/// eigenvectors, but that seems to be significantly slower.
El::HermitianEigCtrl<El::BigFloat> hermitian_eig_ctrl;
hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = schur_complement_cholesky.blocks[block].Height() / 2 + 1;
/// The default number of iterations is 40. That is sometimes
/// not enough, so we bump it up significantly.
hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 400;
El::DistMatrix<El::BigFloat, El::VR, El::STAR> eigenvalues(schur_complement_cholesky.blocks[block].Grid());
El::HermitianEig(El::UpperOrLowerNS::LOWER, schur_complement_cholesky.blocks[block], eigenvalues,
hermitian_eig_ctrl);
El::BigFloat max(0), min(std::numeric_limits<double>::max());
for(int64_t row(0); row!=eigenvalues.Height(); ++row)
{
max=std::max(max,El::Abs(eigenvalues.Get(row,0)));
min=std::min(min,El::Abs(eigenvalues.Get(row,0)));
}
El::BigFloat condition(max/min);
if(condition>S_condition)
{
S_condition=condition;
S_min=min;
S_max=max;
}
// El::Print(schur_complement.blocks[block],"S");
// std::cout << "\n";
// exit(0);
schur_complement_cholesky.blocks[block] = schur_complement.blocks[block];
}
Cholesky(El::UpperOrLowerNS::LOWER,
schur_complement_cholesky.blocks[block]);
cholesky_timer.stop();
// SchurOffDiagonal = L'^{-1} FreeVarMatrix
auto &solve_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.solve_"
+ std::to_string(block_info.block_indices[block])));
schur_off_diagonal.blocks.push_back(sdp.free_var_matrix.blocks[block]);
El::Trsm(El::LeftOrRightNS::LEFT, El::UpperOrLowerNS::LOWER,
El::OrientationNS::NORMAL, El::UnitOrNonUnitNS::NON_UNIT,
El::BigFloat(1), schur_complement_cholesky.blocks[block],
schur_off_diagonal.blocks[block]);
solve_timer.stop();
// Next, we compute
//
// Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}
//
// Where B' = (B U). We think of Q as containing four blocks
// called Upper/Lower-Left/Right.
auto &syrk_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.syrk_"
+ std::to_string(block_info.block_indices[block])));
El::DistMatrix<El::BigFloat> Q_group_view(
El::View(Q_group, 0, 0, schur_off_diagonal.blocks[block].Width(),
schur_off_diagonal.blocks[block].Width()));
El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,
El::BigFloat(1), schur_off_diagonal.blocks[block],
El::BigFloat(1), Q_group_view);
syrk_timer.stop();
}
{
std::stringstream ss;
ss << "S Condition: "
<< El::mpi::Rank() << " "
<< S_condition << " "
<< S_max << " "
<< S_min << "\n";
std::cout << ss.str();
}
}
|
#include "../../../../SDP.hxx"
#include "../../../../Block_Diagonal_Matrix.hxx"
#include "../../../../../Timers.hxx"
void initialize_Q_group(const SDP &sdp, const Block_Info &block_info,
const Block_Diagonal_Matrix &schur_complement,
Block_Matrix &schur_off_diagonal,
Block_Diagonal_Matrix &schur_complement_cholesky,
El::DistMatrix<El::BigFloat> &Q_group, Timers &timers)
{
// Explicitly deallocate the lower half of Q_group. This
// significantly reduces the total amount of memory required.
El::Matrix<El::BigFloat> &local(Q_group.Matrix());
for(int64_t row = 0; row < Q_group.Height(); ++row)
for(int64_t column = 0; column < row; ++column)
{
if(Q_group.IsLocal(row, column))
{
mpf_clear(local(Q_group.LocalRow(row), Q_group.LocalCol(column))
.gmp_float.get_mpf_t());
local(Q_group.LocalRow(row), Q_group.LocalCol(column))
.gmp_float.get_mpf_t()[0]
._mp_d
= nullptr;
}
}
schur_off_diagonal.blocks.clear();
schur_off_diagonal.blocks.reserve(schur_complement_cholesky.blocks.size());
// size_t num_rows(sdp.free_var_matrix.blocks.front().Width());
// for(auto &block: sdp.free_var_matrix.blocks)
// {
// num_rows+=block.Height();
// }
// // std::cout << "rows: " << num_rows << "\n";
// El::Matrix<double> big_matrix(num_rows,num_rows);
// El::Zero(big_matrix);
// {
// int64_t row(0);
// for(auto &block: schur_complement.blocks)
// {
// // El::Print(block,"block");
// // std::cout << "\n";
// for(int64_t block_row(0); block_row!=block.Height(); ++block_row)
// {
// for(int64_t block_column(0); block_column!=block.Width(); ++block_column)
// {
// big_matrix(row+block_row, row+block_column) = double(block.Get(block_row,block_column));
// }
// }
// row+=block.Height();
// }
// }
// {
// int64_t row(0);
// const int64_t column_offset(num_rows - sdp.free_var_matrix.blocks.front().Width());
// for(auto &block: sdp.free_var_matrix.blocks)
// {
// for(int64_t block_row(0); block_row!=block.Height(); ++block_row)
// {
// for(int64_t block_column(0); block_column!=block.Width(); ++block_column)
// {
// big_matrix(row+block_row, column_offset+block_column) =
// double(block.Get(block_row,block_column));
// big_matrix(column_offset+block_column, row+block_row) =
// big_matrix(row+block_row, column_offset+block_column);
// }
// }
// row+=block.Height();
// }
// }
// {
// // El::Print(big_matrix,"big_matrix");
// // std::cout << "\n";
// // exit(0);
// /// There is a bug in El::HermitianEig when there is more than
// /// one level of recursion when computing eigenvalues. One fix
// /// is to increase the cutoff so that there is no more than one
// /// level of recursion.
// /// An alternate workaround is to compute both eigenvalues and
// /// eigenvectors, but that seems to be significantly slower.
// El::HermitianEigCtrl<double> hermitian_eig_ctrl;
// hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = num_rows / 2 + 1;
// /// The default number of iterations is 40. That is sometimes
// /// not enough, so we bump it up significantly.
// hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 400;
// El::Matrix<double> eigenvalues;
// El::HermitianEig(El::UpperOrLowerNS::LOWER, big_matrix, eigenvalues,
// hermitian_eig_ctrl);
// double max(0), min(std::numeric_limits<double>::max());
// for(int64_t row(0); row!=eigenvalues.Height(); ++row)
// {
// max=std::max(max,std::abs(eigenvalues(row,0)));
// min=std::min(min,std::abs(eigenvalues(row,0)));
// }
// std::cout << "T Condition: "
// << (max / min) << " "
// << max << " "
// << min << "\n";
// }
El::BigFloat S_max(0), S_min(std::numeric_limits<double>::max()),
S_condition(0);
for(size_t block = 0; block < schur_complement_cholesky.blocks.size();
++block)
{
auto &cholesky_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.cholesky_"
+ std::to_string(block_info.block_indices[block])));
schur_complement_cholesky.blocks[block] = schur_complement.blocks[block];
{
/// There is a bug in El::HermitianEig when there is more than
/// one level of recursion when computing eigenvalues. One fix
/// is to increase the cutoff so that there is no more than one
/// level of recursion.
/// An alternate workaround is to compute both eigenvalues and
/// eigenvectors, but that seems to be significantly slower.
El::HermitianEigCtrl<El::BigFloat> hermitian_eig_ctrl;
hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = schur_complement_cholesky.blocks[block].Height() / 2 + 1;
/// The default number of iterations is 40. That is sometimes
/// not enough, so we bump it up significantly.
hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 400;
El::DistMatrix<El::BigFloat, El::VR, El::STAR> eigenvalues(schur_complement_cholesky.blocks[block].Grid());
El::HermitianEig(El::UpperOrLowerNS::LOWER, schur_complement_cholesky.blocks[block], eigenvalues,
hermitian_eig_ctrl);
El::BigFloat max(0), min(std::numeric_limits<double>::max());
for(int64_t row(0); row!=eigenvalues.Height(); ++row)
{
max=std::max(max,El::Abs(eigenvalues.Get(row,0)));
min=std::min(min,El::Abs(eigenvalues.Get(row,0)));
}
El::BigFloat condition(max/min);
if(condition>S_condition)
{
S_condition=condition;
S_min=min;
S_max=max;
}
// El::Print(schur_complement.blocks[block],"S");
// std::cout << "\n";
// exit(0);
schur_complement_cholesky.blocks[block] = schur_complement.blocks[block];
}
Cholesky(El::UpperOrLowerNS::LOWER,
schur_complement_cholesky.blocks[block]);
cholesky_timer.stop();
// SchurOffDiagonal = L^{-1} FreeVarMatrix
auto &solve_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.solve_"
+ std::to_string(block_info.block_indices[block])));
schur_off_diagonal.blocks.push_back(sdp.free_var_matrix.blocks[block]);
El::Trsm(El::LeftOrRightNS::LEFT, El::UpperOrLowerNS::LOWER,
El::OrientationNS::NORMAL, El::UnitOrNonUnitNS::NON_UNIT,
El::BigFloat(1), schur_complement_cholesky.blocks[block],
schur_off_diagonal.blocks[block]);
solve_timer.stop();
// Next, we compute
//
// Q = (L^{-1} B)^T (L^{-1} B)
auto &syrk_timer(timers.add_and_start(
"run.step.initializeSchurComplementSolver.Q.syrk_"
+ std::to_string(block_info.block_indices[block])));
El::DistMatrix<El::BigFloat> Q_group_view(
El::View(Q_group, 0, 0, schur_off_diagonal.blocks[block].Width(),
schur_off_diagonal.blocks[block].Width()));
El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,
El::BigFloat(1), schur_off_diagonal.blocks[block],
El::BigFloat(1), Q_group_view);
syrk_timer.stop();
}
{
std::stringstream ss;
ss << "S Condition: "
<< El::mpi::Rank() << " "
<< S_condition << " "
<< S_max << " "
<< S_min << "\n";
std::cout << ss.str();
}
}
|
Fix comments
|
Fix comments
|
C++
|
mit
|
davidsd/sdpb,davidsd/sdpb,davidsd/sdpb
|
a85f5284c34f3969701a6f2121e8fcfc2fc5e81d
|
test/SemaCXX/array-bounds.cpp
|
test/SemaCXX/array-bounds.cpp
|
// RUN: %clang_cc1 -verify %s
int foo() {
int x[2]; // expected-note 4 {{array 'x' declared here}}
int y[2]; // expected-note 2 {{array 'y' declared here}}
int *p = &y[2]; // no-warning
(void) sizeof(x[2]); // no-warning
y[2] = 2; // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
return x[2] + // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
y[-1] + // expected-warning {{array index of '-1' indexes before the beginning of the array}}
x[sizeof(x)] + // expected-warning {{array index of '8' indexes past the end of an array (that contains 2 elements)}}
x[sizeof(x) / sizeof(x[0])] + // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
x[sizeof(x) / sizeof(x[0]) - 1] + // no-warning
x[sizeof(x[2])]; // expected-warning {{array index of '4' indexes past the end of an array (that contains 2 elements)}}
}
// This code example tests that -Warray-bounds works with arrays that
// are template parameters.
template <char *sz> class Qux {
bool test() { return sz[0] == 'a'; }
};
void f1(int a[1]) {
int val = a[3]; // no warning for function argumnet
}
void f2(const int (&a)[1]) { // expected-note {{declared here}}
int val = a[3]; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
}
void test() {
struct {
int a[0];
} s2;
s2.a[3] = 0; // no warning for 0-sized array
union {
short a[2]; // expected-note {{declared here}}
char c[4];
} u;
u.a[3] = 1; // expected-warning {{array index of '3' indexes past the end of an array (that contains 2 elements)}}
u.c[3] = 1; // no warning
const int const_subscript = 3;
int array[1]; // expected-note {{declared here}}
array[const_subscript] = 0; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
int *ptr;
ptr[3] = 0; // no warning for pointer references
int array2[] = { 0, 1, 2 }; // expected-note 2 {{declared here}}
array2[3] = 0; // expected-warning {{array index of '3' indexes past the end of an array (that contains 3 elements)}}
array2[2+2] = 0; // expected-warning {{array index of '4' indexes past the end of an array (that contains 3 elements)}}
const char *str1 = "foo";
char c1 = str1[5]; // no warning for pointers
const char str2[] = "foo"; // expected-note {{declared here}}
char c2 = str2[5]; // expected-warning {{array index of '5' indexes past the end of an array (that contains 4 elements)}}
int (*array_ptr)[1];
(*array_ptr)[3] = 1; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
}
template <int I> struct S {
char arr[I]; // expected-note 3 {{declared here}}
};
template <int I> void f() {
S<3> s;
s.arr[4] = 0; // expected-warning 2 {{array index of '4' indexes past the end of an array (that contains 3 elements)}}
s.arr[I] = 0; // expected-warning {{array index of '5' indexes past the end of an array (that contains 3 elements)}}
}
void test_templates() {
f<5>(); // expected-note {{in instantiation}}
}
|
// RUN: %clang_cc1 -verify %s
int foo() {
int x[2]; // expected-note 4 {{array 'x' declared here}}
int y[2]; // expected-note 2 {{array 'y' declared here}}
int *p = &y[2]; // no-warning
(void) sizeof(x[2]); // no-warning
y[2] = 2; // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
return x[2] + // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
y[-1] + // expected-warning {{array index of '-1' indexes before the beginning of the array}}
x[sizeof(x)] + // expected-warning {{array index of '8' indexes past the end of an array (that contains 2 elements)}}
x[sizeof(x) / sizeof(x[0])] + // expected-warning {{array index of '2' indexes past the end of an array (that contains 2 elements)}}
x[sizeof(x) / sizeof(x[0]) - 1] + // no-warning
x[sizeof(x[2])]; // expected-warning {{array index of '4' indexes past the end of an array (that contains 2 elements)}}
}
// This code example tests that -Warray-bounds works with arrays that
// are template parameters.
template <char *sz> class Qux {
bool test() { return sz[0] == 'a'; }
};
void f1(int a[1]) {
int val = a[3]; // no warning for function argumnet
}
void f2(const int (&a)[1]) { // expected-note {{declared here}}
int val = a[3]; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
}
void test() {
struct {
int a[0];
} s2;
s2.a[3] = 0; // no warning for 0-sized array
union {
short a[2]; // expected-note {{declared here}}
char c[4];
} u;
u.a[3] = 1; // expected-warning {{array index of '3' indexes past the end of an array (that contains 2 elements)}}
u.c[3] = 1; // no warning
const int const_subscript = 3;
int array[1]; // expected-note {{declared here}}
array[const_subscript] = 0; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
int *ptr;
ptr[3] = 0; // no warning for pointer references
int array2[] = { 0, 1, 2 }; // expected-note 2 {{declared here}}
array2[3] = 0; // expected-warning {{array index of '3' indexes past the end of an array (that contains 3 elements)}}
array2[2+2] = 0; // expected-warning {{array index of '4' indexes past the end of an array (that contains 3 elements)}}
const char *str1 = "foo";
char c1 = str1[5]; // no warning for pointers
const char str2[] = "foo"; // expected-note {{declared here}}
char c2 = str2[5]; // expected-warning {{array index of '5' indexes past the end of an array (that contains 4 elements)}}
int (*array_ptr)[1];
(*array_ptr)[3] = 1; // expected-warning {{array index of '3' indexes past the end of an array (that contains 1 elements)}}
}
template <int I> struct S {
char arr[I]; // expected-note 3 {{declared here}}
};
template <int I> void f() {
S<3> s;
s.arr[4] = 0; // expected-warning 2 {{array index of '4' indexes past the end of an array (that contains 3 elements)}}
s.arr[I] = 0; // expected-warning {{array index of '5' indexes past the end of an array (that contains 3 elements)}}
}
void test_templates() {
f<5>(); // expected-note {{in instantiation}}
}
#define SIZE 10
#define ARR_IN_MACRO(flag, arr, idx) flag ? arr[idx] : 1
int test_no_warn_macro_unreachable() {
int arr[SIZE]; // expected-note 2 {{array 'arr' declared here}}
// FIXME: We don't want to warn for the first case.
return ARR_IN_MACRO(0, arr, SIZE) + // expected-warning{{array index of '10' indexes past the end of an array (that contains 10 elements)}}
ARR_IN_MACRO(1, arr, SIZE); // expected-warning{{array index of '10' indexes past the end of an array (that contains 10 elements)}}
}
|
Add -Warray-bounds test showing how the warning currently interoperates with macros.
|
Add -Warray-bounds test showing how the warning currently interoperates with macros.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@125781 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
|
d6b16273af399e65c5132f42ea71b8eb08f99a41
|
tree/src/TSelector.cxx
|
tree/src/TSelector.cxx
|
// @(#)root/treeplayer:$Name: $:$Id: TSelector.cxx,v 1.10 2002/07/17 12:29:38 rdm Exp $
// Author: Rene Brun 05/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////
// //
// A TSelector object is used by the TTree::Draw, TTree::Scan, //
// TTree::Loop, TTree::Process to navigate in a TTree and make //
// selections. //
// //
// The following members functions are called by the TTree functions. //
// Init: Attach a new TTree during the loop //
// Begin: called everytime a loop on the tree(s) starts. //
// a convenient place to create your histograms. //
// //
// Notify(): This function is called at the first entry of a new //
// tree in a chain. //
// ProcessCut: called at the beginning of each entry to return a flag //
// true if the entry must be analyzed. //
// ProcessFill: called in the entry loop for all entries accepted //
// by Select. //
// Terminate: called at the end of a loop on a TTree. //
// a convenient place to draw/fit your histograms. //
// //
////////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TSystem.h"
#include "TTree.h"
#include "THashList.h"
#include "TError.h"
#include "TSelectorCint.h"
#include "Api.h"
ClassImp(TSelector)
//______________________________________________________________________________
TSelector::TSelector() : TObject()
{
// Default selector ctor.
fObject = 0;
fInput = 0;
fOutput = new THashList;
fOutput->SetOwner();
}
//______________________________________________________________________________
TSelector::~TSelector()
{
// Selector destructor.
delete fOutput;
}
//______________________________________________________________________________
TSelector *TSelector::GetSelector(const char *filename)
{
// The code in filename is loaded (interpreted or compiled , see below)
// filename must contain a valid class implementation derived from TSelector.
// where TSelector has the following member functions:
//
// void TSelector::Init(TTree *t). Called every time a new TTree is attached.
// void TSelector::Begin(). This function is called before looping on the
// events in the Tree. The user can create his histograms in this function.
//
// Bool_t TSelector::Notify(). This function is called at the first entry
// of a new file in a chain.
//
// Bool_t TSelector::ProcessCut(Int_t entry). This function is called
// before processing entry. It is the user's responsability to read
// the corresponding entry in memory (may be just a partial read).
// The function returns kTRUE if the entry must be processed,
// kFALSE otherwise.
// void TSelector::ProcessFill(Int_t entry). This function is called for
// all selected events. User fills histograms in this function.
// void TSelector::Terminate(). This function is called at the end of
// the loop on all events.
//
// if filename is of the form file.C, the file will be interpreted.
// if filename is of the form file.C++, the file file.C will be compiled
// and dynamically loaded. The corresponding binary file and shared library
// will be deleted at the end of the function.
// if filename is of the form file.C+, the file file.C will be compiled
// and dynamically loaded. At next call, if file.C is older than file.o
// and file.so, the file.C is not compiled, only file.so is loaded.
//
// The static function returns a pointer to a TSelector object
//Interpret/compile filename via CINT
char localname[256];
sprintf(localname,".L %s",filename);
gROOT->ProcessLine(localname);
//loop on all classes known to CINT to find the class on filename
//that derives from TSelector
const char *basename = gSystem->BaseName(filename);
if (basename==0) {
::Error("TSelector::GetSelector","Unable to determine the classname for file %s",filename);
return 0;
}
strcpy(localname,basename);
char *IsCompiled = strchr(localname,'+');
char *dot = strchr(localname,'.');
if (dot) dot[0] = 0;
G__ClassInfo cl;
Bool_t OK = kFALSE;
while (cl.Next()) {
if (strcmp(cl.Name(),localname)) continue;
if (cl.IsBase("TSelector")) OK = kTRUE;
break;
}
if (!OK) {
::Error("TSelector::GetSelector","file %s does not have a valid class deriving from TSelector",filename);
return 0;
}
// we can now create an instance of the class
TSelector *selector = (TSelector*)cl.New();
if (!selector || IsCompiled) return selector;
//interpreted selector: cannot be used as such
//create a fake selector
TSelectorCint *select = new TSelectorCint();
select->Build(selector,&cl);
return select;
}
|
// @(#)root/treeplayer:$Name: $:$Id: TSelector.cxx,v 1.11 2002/12/13 19:11:06 brun Exp $
// Author: Rene Brun 05/02/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////
// //
// A TSelector object is used by the TTree::Draw, TTree::Scan, //
// TTree::Loop, TTree::Process to navigate in a TTree and make //
// selections. //
// //
// The following members functions are called by the TTree functions. //
// Init: Attach a new TTree during the loop //
// Begin: called everytime a loop on the tree(s) starts. //
// a convenient place to create your histograms. //
// //
// Notify(): This function is called at the first entry of a new //
// tree in a chain. //
// ProcessCut: called at the beginning of each entry to return a flag //
// true if the entry must be analyzed. //
// ProcessFill: called in the entry loop for all entries accepted //
// by Select. //
// Terminate: called at the end of a loop on a TTree. //
// a convenient place to draw/fit your histograms. //
// //
////////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TSystem.h"
#include "TTree.h"
#include "THashList.h"
#include "TError.h"
#include "TSelectorCint.h"
#include "Api.h"
ClassImp(TSelector)
//______________________________________________________________________________
TSelector::TSelector() : TObject()
{
// Default selector ctor.
fStatus = 0;
fObject = 0;
fInput = 0;
fOutput = new THashList;
fOutput->SetOwner();
}
//______________________________________________________________________________
TSelector::~TSelector()
{
// Selector destructor.
delete fOutput;
}
//______________________________________________________________________________
TSelector *TSelector::GetSelector(const char *filename)
{
// The code in filename is loaded (interpreted or compiled , see below)
// filename must contain a valid class implementation derived from TSelector.
// where TSelector has the following member functions:
//
// void TSelector::Init(TTree *t). Called every time a new TTree is attached.
// void TSelector::Begin(). This function is called before looping on the
// events in the Tree. The user can create his histograms in this function.
//
// Bool_t TSelector::Notify(). This function is called at the first entry
// of a new file in a chain.
//
// Bool_t TSelector::ProcessCut(Int_t entry). This function is called
// before processing entry. It is the user's responsability to read
// the corresponding entry in memory (may be just a partial read).
// The function returns kTRUE if the entry must be processed,
// kFALSE otherwise.
// void TSelector::ProcessFill(Int_t entry). This function is called for
// all selected events. User fills histograms in this function.
// void TSelector::Terminate(). This function is called at the end of
// the loop on all events.
//
// if filename is of the form file.C, the file will be interpreted.
// if filename is of the form file.C++, the file file.C will be compiled
// and dynamically loaded. The corresponding binary file and shared library
// will be deleted at the end of the function.
// if filename is of the form file.C+, the file file.C will be compiled
// and dynamically loaded. At next call, if file.C is older than file.o
// and file.so, the file.C is not compiled, only file.so is loaded.
//
// The static function returns a pointer to a TSelector object
//Interpret/compile filename via CINT
char localname[256];
sprintf(localname,".L %s",filename);
gROOT->ProcessLine(localname);
//loop on all classes known to CINT to find the class on filename
//that derives from TSelector
const char *basename = gSystem->BaseName(filename);
if (basename==0) {
::Error("TSelector::GetSelector","Unable to determine the classname for file %s",filename);
return 0;
}
strcpy(localname,basename);
char *IsCompiled = strchr(localname,'+');
char *dot = strchr(localname,'.');
if (dot) dot[0] = 0;
G__ClassInfo cl;
Bool_t OK = kFALSE;
while (cl.Next()) {
if (strcmp(cl.Name(),localname)) continue;
if (cl.IsBase("TSelector")) OK = kTRUE;
break;
}
if (!OK) {
::Error("TSelector::GetSelector","file %s does not have a valid class deriving from TSelector",filename);
return 0;
}
// we can now create an instance of the class
TSelector *selector = (TSelector*)cl.New();
if (!selector || IsCompiled) return selector;
//interpreted selector: cannot be used as such
//create a fake selector
TSelectorCint *select = new TSelectorCint();
select->Build(selector,&cl);
return select;
}
|
Initialize fStatus in TSelector constructor
|
Initialize fStatus in TSelector constructor
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@6043 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
perovic/root,mhuwiler/rootauto,omazapa/root,0x0all/ROOT,lgiommi/root,pspe/root,davidlt/root,mhuwiler/rootauto,Y--/root,BerserkerTroll/root,veprbl/root,vukasinmilosevic/root,kirbyherm/root-r-tools,buuck/root,agarciamontoro/root,alexschlueter/cern-root,zzxuanyuan/root,vukasinmilosevic/root,jrtomps/root,krafczyk/root,gbitzes/root,ffurano/root5,jrtomps/root,Y--/root,root-mirror/root,dfunke/root,sbinet/cxx-root,georgtroska/root,davidlt/root,smarinac/root,vukasinmilosevic/root,bbockelm/root,olifre/root,thomaskeck/root,simonpf/root,evgeny-boger/root,jrtomps/root,sirinath/root,beniz/root,dfunke/root,strykejern/TTreeReader,thomaskeck/root,mattkretz/root,mhuwiler/rootauto,esakellari/my_root_for_test,tc3t/qoot,esakellari/my_root_for_test,strykejern/TTreeReader,CristinaCristescu/root,olifre/root,nilqed/root,zzxuanyuan/root-compressor-dummy,Duraznos/root,evgeny-boger/root,esakellari/my_root_for_test,Dr15Jones/root,sbinet/cxx-root,satyarth934/root,buuck/root,krafczyk/root,kirbyherm/root-r-tools,krafczyk/root,simonpf/root,0x0all/ROOT,mkret2/root,omazapa/root-old,alexschlueter/cern-root,omazapa/root,abhinavmoudgil95/root,esakellari/my_root_for_test,arch1tect0r/root,Y--/root,sbinet/cxx-root,Duraznos/root,simonpf/root,kirbyherm/root-r-tools,beniz/root,root-mirror/root,sbinet/cxx-root,arch1tect0r/root,omazapa/root,tc3t/qoot,bbockelm/root,CristinaCristescu/root,omazapa/root-old,abhinavmoudgil95/root,olifre/root,thomaskeck/root,kirbyherm/root-r-tools,mhuwiler/rootauto,esakellari/my_root_for_test,abhinavmoudgil95/root,simonpf/root,dfunke/root,ffurano/root5,CristinaCristescu/root,omazapa/root,olifre/root,dfunke/root,sbinet/cxx-root,davidlt/root,karies/root,omazapa/root-old,olifre/root,root-mirror/root,Duraznos/root,0x0all/ROOT,buuck/root,smarinac/root,zzxuanyuan/root,buuck/root,pspe/root,esakellari/root,vukasinmilosevic/root,BerserkerTroll/root,karies/root,vukasinmilosevic/root,simonpf/root,perovic/root,mkret2/root,mhuwiler/rootauto,beniz/root,mhuwiler/rootauto,evgeny-boger/root,georgtroska/root,bbockelm/root,0x0all/ROOT,georgtroska/root,sawenzel/root,gganis/root,cxx-hep/root-cern,veprbl/root,alexschlueter/cern-root,perovic/root,Duraznos/root,arch1tect0r/root,lgiommi/root,esakellari/root,davidlt/root,jrtomps/root,arch1tect0r/root,gbitzes/root,sbinet/cxx-root,agarciamontoro/root,cxx-hep/root-cern,satyarth934/root,thomaskeck/root,strykejern/TTreeReader,zzxuanyuan/root-compressor-dummy,mattkretz/root,zzxuanyuan/root-compressor-dummy,olifre/root,cxx-hep/root-cern,root-mirror/root,esakellari/my_root_for_test,Y--/root,arch1tect0r/root,agarciamontoro/root,pspe/root,ffurano/root5,beniz/root,abhinavmoudgil95/root,lgiommi/root,evgeny-boger/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,mattkretz/root,karies/root,omazapa/root,bbockelm/root,georgtroska/root,kirbyherm/root-r-tools,evgeny-boger/root,sawenzel/root,abhinavmoudgil95/root,omazapa/root,sbinet/cxx-root,krafczyk/root,mattkretz/root,satyarth934/root,BerserkerTroll/root,CristinaCristescu/root,jrtomps/root,Duraznos/root,gganis/root,root-mirror/root,jrtomps/root,cxx-hep/root-cern,thomaskeck/root,omazapa/root-old,pspe/root,sbinet/cxx-root,pspe/root,satyarth934/root,evgeny-boger/root,karies/root,zzxuanyuan/root,davidlt/root,abhinavmoudgil95/root,smarinac/root,krafczyk/root,gbitzes/root,zzxuanyuan/root,strykejern/TTreeReader,sawenzel/root,dfunke/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,Duraznos/root,dfunke/root,alexschlueter/cern-root,mkret2/root,kirbyherm/root-r-tools,karies/root,arch1tect0r/root,CristinaCristescu/root,omazapa/root,perovic/root,buuck/root,jrtomps/root,perovic/root,pspe/root,veprbl/root,buuck/root,nilqed/root,Dr15Jones/root,mhuwiler/rootauto,satyarth934/root,bbockelm/root,omazapa/root-old,mkret2/root,nilqed/root,sirinath/root,omazapa/root,zzxuanyuan/root,evgeny-boger/root,tc3t/qoot,0x0all/ROOT,smarinac/root,olifre/root,mattkretz/root,thomaskeck/root,abhinavmoudgil95/root,omazapa/root-old,sawenzel/root,esakellari/root,satyarth934/root,arch1tect0r/root,mhuwiler/rootauto,lgiommi/root,agarciamontoro/root,karies/root,buuck/root,satyarth934/root,root-mirror/root,cxx-hep/root-cern,abhinavmoudgil95/root,gganis/root,nilqed/root,gganis/root,vukasinmilosevic/root,smarinac/root,mkret2/root,simonpf/root,Dr15Jones/root,sirinath/root,esakellari/root,sawenzel/root,BerserkerTroll/root,arch1tect0r/root,mhuwiler/rootauto,karies/root,ffurano/root5,tc3t/qoot,root-mirror/root,esakellari/root,georgtroska/root,sirinath/root,omazapa/root-old,veprbl/root,simonpf/root,satyarth934/root,esakellari/root,perovic/root,sawenzel/root,agarciamontoro/root,abhinavmoudgil95/root,0x0all/ROOT,pspe/root,nilqed/root,karies/root,sbinet/cxx-root,Dr15Jones/root,sirinath/root,davidlt/root,Y--/root,mhuwiler/rootauto,omazapa/root-old,sawenzel/root,georgtroska/root,smarinac/root,agarciamontoro/root,lgiommi/root,sirinath/root,omazapa/root,agarciamontoro/root,smarinac/root,dfunke/root,beniz/root,gbitzes/root,smarinac/root,sawenzel/root,buuck/root,ffurano/root5,veprbl/root,georgtroska/root,alexschlueter/cern-root,BerserkerTroll/root,nilqed/root,satyarth934/root,sirinath/root,davidlt/root,olifre/root,gbitzes/root,root-mirror/root,mkret2/root,satyarth934/root,cxx-hep/root-cern,zzxuanyuan/root-compressor-dummy,lgiommi/root,simonpf/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,nilqed/root,mhuwiler/rootauto,buuck/root,thomaskeck/root,dfunke/root,evgeny-boger/root,jrtomps/root,veprbl/root,krafczyk/root,bbockelm/root,bbockelm/root,jrtomps/root,lgiommi/root,0x0all/ROOT,bbockelm/root,mkret2/root,alexschlueter/cern-root,pspe/root,esakellari/root,mattkretz/root,Y--/root,gganis/root,mattkretz/root,dfunke/root,davidlt/root,tc3t/qoot,omazapa/root-old,sbinet/cxx-root,CristinaCristescu/root,omazapa/root,zzxuanyuan/root-compressor-dummy,esakellari/root,beniz/root,BerserkerTroll/root,veprbl/root,krafczyk/root,mattkretz/root,strykejern/TTreeReader,georgtroska/root,agarciamontoro/root,zzxuanyuan/root,esakellari/my_root_for_test,lgiommi/root,mattkretz/root,gganis/root,perovic/root,BerserkerTroll/root,beniz/root,gbitzes/root,0x0all/ROOT,davidlt/root,cxx-hep/root-cern,Dr15Jones/root,agarciamontoro/root,cxx-hep/root-cern,perovic/root,tc3t/qoot,vukasinmilosevic/root,pspe/root,karies/root,arch1tect0r/root,zzxuanyuan/root,perovic/root,mkret2/root,gganis/root,Y--/root,buuck/root,root-mirror/root,krafczyk/root,esakellari/root,vukasinmilosevic/root,CristinaCristescu/root,abhinavmoudgil95/root,tc3t/qoot,beniz/root,strykejern/TTreeReader,CristinaCristescu/root,dfunke/root,evgeny-boger/root,vukasinmilosevic/root,bbockelm/root,veprbl/root,jrtomps/root,vukasinmilosevic/root,nilqed/root,sawenzel/root,BerserkerTroll/root,tc3t/qoot,agarciamontoro/root,sawenzel/root,ffurano/root5,sirinath/root,olifre/root,gganis/root,gganis/root,Dr15Jones/root,simonpf/root,veprbl/root,satyarth934/root,beniz/root,mkret2/root,omazapa/root,olifre/root,Y--/root,sawenzel/root,lgiommi/root,gbitzes/root,lgiommi/root,georgtroska/root,strykejern/TTreeReader,veprbl/root,beniz/root,0x0all/ROOT,perovic/root,omazapa/root-old,beniz/root,esakellari/my_root_for_test,nilqed/root,karies/root,gbitzes/root,smarinac/root,karies/root,evgeny-boger/root,Duraznos/root,Duraznos/root,gganis/root,esakellari/root,abhinavmoudgil95/root,olifre/root,thomaskeck/root,georgtroska/root,sirinath/root,zzxuanyuan/root,Y--/root,perovic/root,BerserkerTroll/root,zzxuanyuan/root,nilqed/root,jrtomps/root,nilqed/root,sirinath/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,bbockelm/root,zzxuanyuan/root,zzxuanyuan/root,sirinath/root,sbinet/cxx-root,zzxuanyuan/root,esakellari/root,simonpf/root,esakellari/my_root_for_test,ffurano/root5,pspe/root,buuck/root,smarinac/root,omazapa/root-old,tc3t/qoot,gbitzes/root,gbitzes/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,Dr15Jones/root,Y--/root,Duraznos/root,CristinaCristescu/root,agarciamontoro/root,arch1tect0r/root,pspe/root,root-mirror/root,Duraznos/root,BerserkerTroll/root,kirbyherm/root-r-tools,gganis/root,simonpf/root,evgeny-boger/root,tc3t/qoot,thomaskeck/root,Y--/root,davidlt/root,alexschlueter/cern-root,arch1tect0r/root,dfunke/root,CristinaCristescu/root,CristinaCristescu/root,lgiommi/root,krafczyk/root,davidlt/root,krafczyk/root,BerserkerTroll/root,vukasinmilosevic/root,Duraznos/root,mkret2/root,mkret2/root,bbockelm/root,georgtroska/root,veprbl/root,root-mirror/root,mattkretz/root
|
4683d8d0927d183d47b8beb66857e7de993dbdf7
|
src/plugin/external-auth-plugin/external-auth-module.cc
|
src/plugin/external-auth-plugin/external-auth-module.cc
|
/*
* Flexisip, a flexible SIP proxy server with media capabilities.
* Copyright (C) 2018 Belledonne Communications SARL, All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include "log/logmanager.hh"
#include "external-auth-module.hh"
using namespace std;
ExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo) : FlexisipAuthModuleBase(root, domain, algo) {
mEngine = nth_engine_create(root, TAG_END());
}
ExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo, int nonceExpire) : FlexisipAuthModuleBase(root, domain, algo, nonceExpire) {
mEngine = nth_engine_create(root, TAG_END());
}
ExternalAuthModule::~ExternalAuthModule() {
nth_engine_destroy(mEngine);
}
void ExternalAuthModule::checkAuthHeader(FlexisipAuthStatus &as, msg_auth_t *credentials, auth_challenger_t const *ach) {
try {
auto &externalAs = dynamic_cast<ExternalAuthModule::Status &>(as);
map<string, string> params = extractParameters(externalAs, *credentials);
string uri;
try {
uri = mUriFormater.format(params);
} catch (const invalid_argument &e) {
ostringstream os;
os << "cannot format HTTP URI: " << e.what();
throw runtime_error(os.str());
}
auto *ctx = new HttpRequestCtx({*this, as});
nth_client_t *request = nth_client_tcreate(mEngine,
onHttpResponseCb,
reinterpret_cast<nth_client_magic_t *>(ctx),
http_method_get,
"GET",
URL_STRING_MAKE(uri.c_str()),
TAG_END()
);
if (request == nullptr) {
ostringstream os;
os << "HTTP request for '" << uri << "' has failed";
delete ctx;
throw runtime_error(os.str());
}
SLOGD << "HTTP request [" << request << "] to '" << uri << "' successfully sent";
as.status(100);
} catch (const runtime_error &e) {
SLOGE << e.what();
onError(as);
}
}
void ExternalAuthModule::loadPassword(const FlexisipAuthStatus &as) {
}
std::map<std::string, std::string> ExternalAuthModule::extractParameters(const Status &as, const msg_auth_t &credentials) const {
map<string, string> params;
for (int i = 0; credentials.au_params[i] != nullptr; i++) {
const char *param = credentials.au_params[i];
const char *equal = strchr(const_cast<char *>(param), '=');
string key(param, equal-param);
string value = equal+1;
params[move(key)] = move(value);
}
params["scheme"] = credentials.au_scheme;
params["method"] = as.method();
params["from"] = as.fromHeader();
params["sip-instance"] = as.sipInstance();
params["domain"] = as.domain();
return params;
}
void ExternalAuthModule::onHttpResponse(FlexisipAuthStatus &as, nth_client_t *request, const http_t *http) {
shared_ptr<RequestSipEvent> ev;
try {
int sipCode = 0;
string phrase;
string reasonHeaderValue;
string pAssertedIdentity;
ostringstream os;
if (http == nullptr) {
os << "HTTP server responds with code " << nth_client_status(request);
throw runtime_error(os.str());
}
int status = http->http_status->st_status;
SLOGD << "HTTP response received [" << status << "]: " << endl << http->http_payload;
if (status != 200) {
os << "unhandled HTTP status code [" << status << "]";
throw runtime_error(os.str());
}
string httpBody = toString(http->http_payload);
if (httpBody.empty()) {
os << "HTTP server answered with an empty body";
throw runtime_error(os.str());
}
try {
map<string, string> kv = parseHttpBody(httpBody);
sipCode = stoi(kv["Status"]);
phrase = move(kv["Phrase"]);
reasonHeaderValue = move(kv["Reason"]);
pAssertedIdentity = move(kv["P-Asserted-Identity"]);
} catch (const logic_error &e) {
os << "error while parsing HTTP body: " << e.what();
throw runtime_error(os.str());
}
if (!validSipCode(sipCode) || reasonHeaderValue.empty()) {
os << "invalid SIP code or reason";
throw runtime_error(os.str());
}
auto &httpAuthStatus = dynamic_cast<ExternalAuthModule::Status &>(as);
httpAuthStatus.status(sipCode == 200 ? 0 : sipCode);
httpAuthStatus.phrase(su_strdup(as.home(), phrase.c_str()));
httpAuthStatus.reason(reasonHeaderValue);
httpAuthStatus.pAssertedIdentity(pAssertedIdentity);
finish(as);
} catch (const runtime_error &e) {
SLOGE << "HTTP request [" << request << "]: " << e.what();
onError(as);
}
}
std::map<std::string, std::string> ExternalAuthModule::parseHttpBody(const std::string &body) const {
istringstream is(body);
ostringstream os;
map<string, string> result;
string line;
do {
getline(is, line);
if (line.empty()) continue;
auto column = find(line.cbegin(), line.cend(), ':');
if (column == line.cend()) {
os << "invalid line '" << line << "': missing column symbol";
throw invalid_argument(os.str());
}
string &value = result[string(line.cbegin(), column)];
auto valueStart = find_if_not(column+1, line.cend(), [](const char &c){return isspace(c) != 0;});
if (valueStart == line.cend()) {
os << "invalid line '" << line << "': missing value";
throw invalid_argument(os.str());
}
value.assign(valueStart, line.cend());
} while (!is.eof());
return result;
}
int ExternalAuthModule::onHttpResponseCb(nth_client_magic_t *magic, nth_client_t *request, const http_t *http) noexcept {
auto *ctx = reinterpret_cast<HttpRequestCtx *>(magic);
ctx->am.onHttpResponse(ctx->as, request, http);
delete ctx;
return 0;
}
std::string ExternalAuthModule::toString(const http_payload_t *httpPayload) {
if (httpPayload == nullptr || httpPayload->pl_data == nullptr || httpPayload->pl_len == 0) {
return string();
}
return string(httpPayload->pl_data, httpPayload->pl_len);
}
bool ExternalAuthModule::validSipCode(int sipCode) {
const auto it = find(sValidSipCodes.cbegin(), sValidSipCodes.cend(), sipCode);
return (it != sValidSipCodes.cend());
}
std::array<int, 4> ExternalAuthModule::sValidSipCodes{{200, 401, 407, 403}};
|
/*
* Flexisip, a flexible SIP proxy server with media capabilities.
* Copyright (C) 2018 Belledonne Communications SARL, All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include "log/logmanager.hh"
#include "external-auth-module.hh"
using namespace std;
ExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo) : FlexisipAuthModuleBase(root, domain, algo) {
mEngine = nth_engine_create(root, TAG_END());
}
ExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo, int nonceExpire) : FlexisipAuthModuleBase(root, domain, algo, nonceExpire) {
mEngine = nth_engine_create(root, TAG_END());
}
ExternalAuthModule::~ExternalAuthModule() {
nth_engine_destroy(mEngine);
}
void ExternalAuthModule::checkAuthHeader(FlexisipAuthStatus &as, msg_auth_t *credentials, auth_challenger_t const *ach) {
try {
auto &externalAs = dynamic_cast<ExternalAuthModule::Status &>(as);
map<string, string> params = extractParameters(externalAs, *credentials);
string uri;
try {
uri = mUriFormater.format(params);
} catch (const invalid_argument &e) {
ostringstream os;
os << "cannot format HTTP URI: " << e.what();
throw runtime_error(os.str());
}
auto *ctx = new HttpRequestCtx({*this, as});
nth_client_t *request = nth_client_tcreate(mEngine,
onHttpResponseCb,
reinterpret_cast<nth_client_magic_t *>(ctx),
http_method_get,
"GET",
URL_STRING_MAKE(uri.c_str()),
TAG_END()
);
if (request == nullptr) {
ostringstream os;
os << "HTTP request for '" << uri << "' has failed";
delete ctx;
throw runtime_error(os.str());
}
SLOGD << "HTTP request [" << request << "] to '" << uri << "' successfully sent";
as.status(100);
} catch (const runtime_error &e) {
SLOGE << e.what();
onError(as);
}
}
void ExternalAuthModule::loadPassword(const FlexisipAuthStatus &as) {
}
std::map<std::string, std::string> ExternalAuthModule::extractParameters(const Status &as, const msg_auth_t &credentials) const {
map<string, string> params;
for (int i = 0; credentials.au_params[i] != nullptr; i++) {
const char *param = credentials.au_params[i];
const char *equal = strchr(const_cast<char *>(param), '=');
string key(param, equal-param);
string value = equal+1;
params[move(key)] = move(value);
}
params["scheme"] = credentials.au_scheme;
params["method"] = as.method();
params["from"] = as.fromHeader();
params["sip-instance"] = as.sipInstance();
params["domain"] = as.domain();
return params;
}
void ExternalAuthModule::onHttpResponse(FlexisipAuthStatus &as, nth_client_t *request, const http_t *http) {
shared_ptr<RequestSipEvent> ev;
try {
int sipCode = 0;
string phrase;
string reasonHeaderValue;
string pAssertedIdentity;
ostringstream os;
if (http == nullptr) {
os << "HTTP server responds with code " << nth_client_status(request);
throw runtime_error(os.str());
}
int status = http->http_status->st_status;
SLOGD << "HTTP response received [" << status << "]: " << endl << http->http_payload;
if (status != 200) {
os << "unhandled HTTP status code [" << status << "]";
throw runtime_error(os.str());
}
string httpBody = toString(http->http_payload);
if (httpBody.empty()) {
os << "HTTP server answered with an empty body";
throw runtime_error(os.str());
}
try {
map<string, string> kv = parseHttpBody(httpBody);
sipCode = stoi(kv["Status"]);
phrase = move(kv["Phrase"]);
reasonHeaderValue = move(kv["Reason"]);
pAssertedIdentity = move(kv["P-Asserted-Identity"]);
} catch (const logic_error &e) {
os << "error while parsing HTTP body: " << e.what();
throw runtime_error(os.str());
}
if (!validSipCode(sipCode) || reasonHeaderValue.empty()) {
os << "invalid SIP code or reason";
throw runtime_error(os.str());
}
auto &httpAuthStatus = dynamic_cast<ExternalAuthModule::Status &>(as);
httpAuthStatus.status(sipCode == 200 ? 0 : sipCode);
httpAuthStatus.phrase(su_strdup(as.home(), phrase.c_str()));
httpAuthStatus.reason(reasonHeaderValue);
httpAuthStatus.pAssertedIdentity(pAssertedIdentity);
finish(as);
} catch (const runtime_error &e) {
SLOGE << "HTTP request [" << request << "]: " << e.what();
onError(as);
} catch (...) {
if (request) nth_client_destroy(request);
throw;
}
if (request) nth_client_destroy(request);
}
std::map<std::string, std::string> ExternalAuthModule::parseHttpBody(const std::string &body) const {
istringstream is(body);
ostringstream os;
map<string, string> result;
string line;
do {
getline(is, line);
if (line.empty()) continue;
auto column = find(line.cbegin(), line.cend(), ':');
if (column == line.cend()) {
os << "invalid line '" << line << "': missing column symbol";
throw invalid_argument(os.str());
}
string &value = result[string(line.cbegin(), column)];
auto valueStart = find_if_not(column+1, line.cend(), [](const char &c){return isspace(c) != 0;});
if (valueStart == line.cend()) {
os << "invalid line '" << line << "': missing value";
throw invalid_argument(os.str());
}
value.assign(valueStart, line.cend());
} while (!is.eof());
return result;
}
int ExternalAuthModule::onHttpResponseCb(nth_client_magic_t *magic, nth_client_t *request, const http_t *http) noexcept {
auto *ctx = reinterpret_cast<HttpRequestCtx *>(magic);
ctx->am.onHttpResponse(ctx->as, request, http);
delete ctx;
return 0;
}
std::string ExternalAuthModule::toString(const http_payload_t *httpPayload) {
if (httpPayload == nullptr || httpPayload->pl_data == nullptr || httpPayload->pl_len == 0) {
return string();
}
return string(httpPayload->pl_data, httpPayload->pl_len);
}
bool ExternalAuthModule::validSipCode(int sipCode) {
const auto it = find(sValidSipCodes.cbegin(), sValidSipCodes.cend(), sipCode);
return (it != sValidSipCodes.cend());
}
std::array<int, 4> ExternalAuthModule::sValidSipCodes{{200, 401, 407, 403}};
|
Fix memory leak in the external authentication module
|
Fix memory leak in the external authentication module
|
C++
|
agpl-3.0
|
BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip
|
9dde97a0279b8a794dc2c589ed1fc07bc6ddeb1c
|
frontends/fltk_gui/CsoundPerformanceSettings.cpp
|
frontends/fltk_gui/CsoundPerformanceSettings.cpp
|
/*
CsoundPerformanceSettings.cpp:
Copyright (C) 2006 Istvan Varga
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundGUI.hpp"
using namespace std;
CsoundPerformanceSettings::CsoundPerformanceSettings()
{
orcName = "";
scoName = "";
soundFileType = "wav";
soundSampleFormat = "short";
enablePeakChunks = true;
displayMode = 1;
deferGEN1 = false;
bufFrames_SW = 1024;
nBuffers = 4;
midiInFileName = "";
midiOutFileName = "";
midiInDevName = "";
midiOutDevName = "";
terminateOnMidi = false;
// heartBeatMode = 0;
rewriteHeader = false;
inputFileName = "";
outputFileName = "dac";
enableSoundOutput = true;
beatModeTempo = -1.0;
iTimeOnly = false;
sampleRateOverride = -1.0;
controlRateOverride = -1.0;
lineInput = "";
messageLevel = 231;
enableExpressionOpt = false;
sadirPath = "";
ssdirPath = "";
sfdirPath = "";
incdirPath = "";
csdocdirPath = "";
for (int i = 0; i < 10; i++)
strsets[i] = "";
verbose = false;
enableDither = false;
pluginLibs = "";
sndidArtist = "";
sndidComment = "";
sndidCopyright = "";
sndidDate = "";
sndidSoftware = "";
sndidTitle = "";
ignoreCSDOptions = true;
jackClientName = "";
jackInPortName = "";
jackOutPortName = "";
maxStrLen = 255;
midiFileMuteTracks = "";
midiKeyMidi = -1;
midiKeyCps = -1;
midiKeyOct = -1;
midiKeyPch = -1;
midiVelMidi = -1;
midiVelAmp = -1;
rawControllerMode = false;
rtAudioModule = "PortAudio";
rtAudioOutputDevice = "dac";
rtAudioInputDevice = "adc";
rtMidiModule = "PortMidi";
scoreOffsetSeconds = 0.0;
useThreads = true;
scriptFileName = "";
additionalFlags = "";
useAdditionalFlags = false;
}
CsoundPerformanceSettings::~CsoundPerformanceSettings()
{
}
static const char *fileTypeList[] = {
"wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac",
(char*) 0
};
static const char *sampleFormatList[] = {
"alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit",
(char*) 0
};
int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType)
{
if (fileType == (char*) 0 || fileType[0] == (char) 0)
return -1;
for (int i = 0; fileTypeList[i] != (char*) 0; i++) {
if (strcmp(fileTypeList[i], fileType) == 0)
if (strcmp(fileTypeList[i], fileType) == 0)
return i;
}
return -1;
}
const char *CsoundPerformanceSettings::indexToFileType(int fileType)
{
if (fileType < 0 ||
fileType >= (int) (sizeof(fileTypeList) / sizeof(char*)))
return (char*) 0;
return fileTypeList[fileType];
}
int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat)
{
if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0)
return -1;
for (int i = 0; sampleFormatList[i] != (char*) 0; i++) {
if (strcmp(sampleFormatList[i], sampleFormat) == 0)
return i;
}
return -1;
}
const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat)
{
if (sampleFormat < 0 ||
sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*)))
return (char*) 0;
return sampleFormatList[sampleFormat];
}
static bool cmdLine_addStringOpt(vector<string>& cmdLine,
const char *optName, string& value)
{
string arg;
int i, pos0, pos1;
for (pos0 = 0; pos0 < (int) value.size(); pos0++) {
char c = value[pos0];
if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
break;
}
for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) {
char c = value[pos1];
if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
break;
}
if (pos0 > pos1)
return false;
arg = optName;
for (i = pos0; i <= pos1; i++)
arg += value[i];
cmdLine.push_back(arg);
return true;
}
static void cmdLine_addIntegerOpt(vector<string>& cmdLine,
const char *optName, int value)
{
char buf[64];
sprintf(&(buf[0]), "%s%d", optName, value);
cmdLine.push_back(&(buf[0]));
}
static void cmdLine_addDoubleOpt(vector<string>& cmdLine,
const char *optName, double value)
{
char buf[64];
if (!(value > -10000000.0 && value < 10000000.0))
return;
sprintf(&(buf[0]), "%s%g", optName, value);
cmdLine.push_back(&(buf[0]));
}
void CsoundPerformanceSettings::buildCommandLine(vector<string>&
cmdLine,
bool forceSettings)
{
cmdLine.clear();
cmdLine.push_back("csound");
if (!CsoundGUIMain::isEmptyString(soundFileType) &&
(soundFileType != "wav" || forceSettings)) {
string arg;
arg = "--format=";
arg += soundFileType;
if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
(soundSampleFormat != "short" || forceSettings)) {
arg += ':';
arg += soundSampleFormat;
}
cmdLine.push_back(arg);
}
else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
(soundSampleFormat != "short" || forceSettings)) {
cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat);
}
if (!enablePeakChunks) {
cmdLine.push_back("-K");
}
if (displayMode != 1 || forceSettings) {
switch (displayMode) { // 0: none, 1: full, 2: ASCII, 3: PS
case 0:
cmdLine.push_back("-d");
break;
case 1:
cmdLine.push_back("--displays");
break;
case 2:
if (forceSettings)
cmdLine.push_back("--displays");
cmdLine.push_back("-g");
break;
case 3:
if (forceSettings)
cmdLine.push_back("--displays");
cmdLine.push_back("-G");
break;
}
}
if (deferGEN1)
cmdLine.push_back("-D");
if (bufFrames_SW >= 16) {
cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW);
cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers);
}
cmdLine_addStringOpt(cmdLine, "-F", midiInFileName);
cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName);
cmdLine_addStringOpt(cmdLine, "-M", midiInDevName);
cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName);
if (terminateOnMidi)
cmdLine.push_back("-T");
if (heartBeatMode != 0 || forceSettings)
cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode);
if (rewriteHeader)
cmdLine.push_back("-R");
if (runRealtime)
cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice);
else
cmdLine_addStringOpt(cmdLine, "-i", inputFileName);
if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) {
cmdLine_addStringOpt(cmdLine, "-o", outputFileName);
}
else if (forceSettings && !disableDiskOutput)
cmdLine.push_back("-n");
if (disableDiskOutput && !runRealtime)
cmdLine.push_back("-n");
if (beatModeTempo > 0.0)
cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo);
if (iTimeOnly)
cmdLine.push_back("-I");
if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) {
cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride);
cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride);
}
cmdLine_addStringOpt(cmdLine, "-L", lineInput);
if (messageLevel != 135 || forceSettings)
cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel);
if (enableExpressionOpt)
cmdLine.push_back("--expression-opt");
else if (forceSettings)
cmdLine.push_back("--no-expression-opt");
cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath);
cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath);
cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath);
cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath);
// cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath);
for (int i = 0; i < 10; i++) {
if (!CsoundGUIMain::isEmptyString(strsets[i])) {
char buf[16];
sprintf(&(buf[0]), "--strset%d=", i);
cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]);
}
}
if (verbose)
cmdLine.push_back("-v");
if (enableDither)
cmdLine.push_back("-Z");
cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs);
cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist);
cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment);
cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright);
cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate);
cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware);
cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle);
if (ignoreCSDOptions)
cmdLine.push_back("-+ignore_csopts=1");
else if (forceSettings)
cmdLine.push_back("-+ignore_csopts=0");
cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName);
cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName);
cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName);
if ((maxStrLen >= 9 && maxStrLen <= 9999) &&
(maxStrLen != 255 || forceSettings)) {
cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1);
}
if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) {
if (forceSettings)
cmdLine.push_back("-+mute_tracks=");
}
if (midiKeyMidi > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi);
if (midiKeyCps > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps);
if (midiKeyOct > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct);
if (midiKeyPch > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch);
if (midiVelMidi > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi);
if (midiVelAmp > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp);
if (rawControllerMode)
cmdLine.push_back("-+raw_controller_mode=1");
else if (forceSettings)
cmdLine.push_back("-+raw_controller_mode=0");
if (runRealtime)
cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule);
cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule);
if (scoreOffsetSeconds > 0.0)
cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds);
else if (forceSettings && scoreOffsetSeconds == 0.0)
cmdLine.push_back("-+skip_seconds=0");
if (!CsoundGUIMain::isEmptyString(orcName)) {
cmdLine.push_back(orcName);
if (!CsoundGUIMain::isCSDFile(orcName) &&
!CsoundGUIMain::isEmptyString(scoName))
cmdLine.push_back(scoName);
}
if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags))
cmdLine.push_back(additionalFlags);
}
|
/*
CsoundPerformanceSettings.cpp:
Copyright (C) 2006 Istvan Varga
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundGUI.hpp"
using namespace std;
CsoundPerformanceSettings::CsoundPerformanceSettings()
{
orcName = "";
scoName = "";
soundFileType = "wav";
soundSampleFormat = "short";
enablePeakChunks = true;
displayMode = 1;
deferGEN1 = false;
bufFrames_SW = 1024;
nBuffers = 4;
midiInFileName = "";
midiOutFileName = "";
midiInDevName = "";
midiOutDevName = "";
terminateOnMidi = false;
heartBeatMode = 0;
rewriteHeader = false;
inputFileName = "";
outputFileName = "dac";
enableSoundOutput = true;
beatModeTempo = -1.0;
iTimeOnly = false;
sampleRateOverride = -1.0;
controlRateOverride = -1.0;
lineInput = "";
messageLevel = 231;
enableExpressionOpt = false;
sadirPath = "";
ssdirPath = "";
sfdirPath = "";
incdirPath = "";
csdocdirPath = "";
for (int i = 0; i < 10; i++)
strsets[i] = "";
verbose = false;
enableDither = false;
pluginLibs = "";
sndidArtist = "";
sndidComment = "";
sndidCopyright = "";
sndidDate = "";
sndidSoftware = "";
sndidTitle = "";
ignoreCSDOptions = true;
jackClientName = "";
jackInPortName = "";
jackOutPortName = "";
maxStrLen = 255;
midiFileMuteTracks = "";
midiKeyMidi = -1;
midiKeyCps = -1;
midiKeyOct = -1;
midiKeyPch = -1;
midiVelMidi = -1;
midiVelAmp = -1;
rawControllerMode = false;
rtAudioModule = "PortAudio";
rtAudioOutputDevice = "dac";
rtAudioInputDevice = "adc";
rtMidiModule = "PortMidi";
scoreOffsetSeconds = 0.0;
useThreads = true;
scriptFileName = "";
additionalFlags = "";
useAdditionalFlags = false;
}
CsoundPerformanceSettings::~CsoundPerformanceSettings()
{
}
static const char *fileTypeList[] = {
"wav", "aiff", "au", "raw", "ircam", "w64", "wavex", "sd2", "flac",
(char*) 0
};
static const char *sampleFormatList[] = {
"alaw", "ulaw", "schar", "uchar", "float", "short", "long", "24bit",
(char*) 0
};
int CsoundPerformanceSettings::fileTypeToIndex(const char *fileType)
{
if (fileType == (char*) 0 || fileType[0] == (char) 0)
return -1;
for (int i = 0; fileTypeList[i] != (char*) 0; i++) {
if (strcmp(fileTypeList[i], fileType) == 0)
if (strcmp(fileTypeList[i], fileType) == 0)
return i;
}
return -1;
}
const char *CsoundPerformanceSettings::indexToFileType(int fileType)
{
if (fileType < 0 ||
fileType >= (int) (sizeof(fileTypeList) / sizeof(char*)))
return (char*) 0;
return fileTypeList[fileType];
}
int CsoundPerformanceSettings::sampleFormatToIndex(const char *sampleFormat)
{
if (sampleFormat == (char*) 0 || sampleFormat[0] == (char) 0)
return -1;
for (int i = 0; sampleFormatList[i] != (char*) 0; i++) {
if (strcmp(sampleFormatList[i], sampleFormat) == 0)
return i;
}
return -1;
}
const char *CsoundPerformanceSettings::indexToSampleFormat(int sampleFormat)
{
if (sampleFormat < 0 ||
sampleFormat >= (int) (sizeof(sampleFormatList) / sizeof(char*)))
return (char*) 0;
return sampleFormatList[sampleFormat];
}
static bool cmdLine_addStringOpt(vector<string>& cmdLine,
const char *optName, string& value)
{
string arg;
int i, pos0, pos1;
for (pos0 = 0; pos0 < (int) value.size(); pos0++) {
char c = value[pos0];
if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
break;
}
for (pos1 = (int) value.size() - 1; pos1 >= 0; pos1--) {
char c = value[pos1];
if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
break;
}
if (pos0 > pos1)
return false;
arg = optName;
for (i = pos0; i <= pos1; i++)
arg += value[i];
cmdLine.push_back(arg);
return true;
}
static void cmdLine_addIntegerOpt(vector<string>& cmdLine,
const char *optName, int value)
{
char buf[64];
sprintf(&(buf[0]), "%s%d", optName, value);
cmdLine.push_back(&(buf[0]));
}
static void cmdLine_addDoubleOpt(vector<string>& cmdLine,
const char *optName, double value)
{
char buf[64];
if (!(value > -10000000.0 && value < 10000000.0))
return;
sprintf(&(buf[0]), "%s%g", optName, value);
cmdLine.push_back(&(buf[0]));
}
void CsoundPerformanceSettings::buildCommandLine(vector<string>&
cmdLine,
bool forceSettings)
{
cmdLine.clear();
cmdLine.push_back("csound");
if (!CsoundGUIMain::isEmptyString(soundFileType) &&
(soundFileType != "wav" || forceSettings)) {
string arg;
arg = "--format=";
arg += soundFileType;
if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
(soundSampleFormat != "short" || forceSettings)) {
arg += ':';
arg += soundSampleFormat;
}
cmdLine.push_back(arg);
}
else if (!CsoundGUIMain::isEmptyString(soundSampleFormat) &&
(soundSampleFormat != "short" || forceSettings)) {
cmdLine_addStringOpt(cmdLine, "--format=", soundSampleFormat);
}
if (!enablePeakChunks) {
cmdLine.push_back("-K");
}
if (displayMode != 1 || forceSettings) {
switch (displayMode) { // 0: none, 1: full, 2: ASCII, 3: PS
case 0:
cmdLine.push_back("-d");
break;
case 1:
cmdLine.push_back("--displays");
break;
case 2:
if (forceSettings)
cmdLine.push_back("--displays");
cmdLine.push_back("-g");
break;
case 3:
if (forceSettings)
cmdLine.push_back("--displays");
cmdLine.push_back("-G");
break;
}
}
if (deferGEN1)
cmdLine.push_back("-D");
if (bufFrames_SW >= 16) {
cmdLine_addIntegerOpt(cmdLine, "-b", bufFrames_SW);
cmdLine_addIntegerOpt(cmdLine, "-B", bufFrames_SW * nBuffers);
}
cmdLine_addStringOpt(cmdLine, "-F", midiInFileName);
cmdLine_addStringOpt(cmdLine, "--midioutfile=", midiOutFileName);
cmdLine_addStringOpt(cmdLine, "-M", midiInDevName);
cmdLine_addStringOpt(cmdLine, "-Q", midiOutDevName);
if (terminateOnMidi)
cmdLine.push_back("-T");
if (heartBeatMode != 0 || forceSettings)
cmdLine_addIntegerOpt(cmdLine, "-H", heartBeatMode);
if (rewriteHeader)
cmdLine.push_back("-R");
if (runRealtime)
cmdLine_addStringOpt(cmdLine, "-i", rtAudioInputDevice);
else
cmdLine_addStringOpt(cmdLine, "-i", inputFileName);
if (!CsoundGUIMain::isEmptyString(outputFileName) && enableSoundOutput) {
cmdLine_addStringOpt(cmdLine, "-o", outputFileName);
}
else if (forceSettings && !disableDiskOutput)
cmdLine.push_back("-n");
if (disableDiskOutput && !runRealtime)
cmdLine.push_back("-n");
if (beatModeTempo > 0.0)
cmdLine_addDoubleOpt(cmdLine, "-t", beatModeTempo);
if (iTimeOnly)
cmdLine.push_back("-I");
if (sampleRateOverride > 0.0 && controlRateOverride > 0.0) {
cmdLine_addDoubleOpt(cmdLine, "-r", sampleRateOverride);
cmdLine_addDoubleOpt(cmdLine, "-k", controlRateOverride);
}
cmdLine_addStringOpt(cmdLine, "-L", lineInput);
if (messageLevel != 135 || forceSettings)
cmdLine_addIntegerOpt(cmdLine, "-m", messageLevel);
if (enableExpressionOpt)
cmdLine.push_back("--expression-opt");
else if (forceSettings)
cmdLine.push_back("--no-expression-opt");
cmdLine_addStringOpt(cmdLine, "--env:SADIR+=", sadirPath);
cmdLine_addStringOpt(cmdLine, "--env:SSDIR+=", ssdirPath);
cmdLine_addStringOpt(cmdLine, "--env:SFDIR+=", sfdirPath);
cmdLine_addStringOpt(cmdLine, "--env:INCDIR+=", incdirPath);
// cmdLine_addStringOpt(cmdLine, "--env:CSDOCDIR+=", csdocdirPath);
for (int i = 0; i < 10; i++) {
if (!CsoundGUIMain::isEmptyString(strsets[i])) {
char buf[16];
sprintf(&(buf[0]), "--strset%d=", i);
cmdLine_addStringOpt(cmdLine, &(buf[0]), strsets[i]);
}
}
if (verbose)
cmdLine.push_back("-v");
if (enableDither)
cmdLine.push_back("-Z");
cmdLine_addStringOpt(cmdLine, "--opcode-lib=", pluginLibs);
cmdLine_addStringOpt(cmdLine, "-+id_artist=", sndidArtist);
cmdLine_addStringOpt(cmdLine, "-+id_comment=", sndidComment);
cmdLine_addStringOpt(cmdLine, "-+id_copyright=", sndidCopyright);
cmdLine_addStringOpt(cmdLine, "-+id_date=", sndidDate);
cmdLine_addStringOpt(cmdLine, "-+id_software=", sndidSoftware);
cmdLine_addStringOpt(cmdLine, "-+id_title=", sndidTitle);
if (ignoreCSDOptions)
cmdLine.push_back("-+ignore_csopts=1");
else if (forceSettings)
cmdLine.push_back("-+ignore_csopts=0");
cmdLine_addStringOpt(cmdLine, "-+jack_client=", jackClientName);
cmdLine_addStringOpt(cmdLine, "-+jack_inportname=", jackInPortName);
cmdLine_addStringOpt(cmdLine, "-+jack_outportname=", jackOutPortName);
if ((maxStrLen >= 9 && maxStrLen <= 9999) &&
(maxStrLen != 255 || forceSettings)) {
cmdLine_addIntegerOpt(cmdLine, "-+max_str_len=", maxStrLen + 1);
}
if (!cmdLine_addStringOpt(cmdLine, "-+mute_tracks=", midiFileMuteTracks)) {
if (forceSettings)
cmdLine.push_back("-+mute_tracks=");
}
if (midiKeyMidi > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key=", midiKeyMidi);
if (midiKeyCps > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-cps=", midiKeyCps);
if (midiKeyOct > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-oct=", midiKeyOct);
if (midiKeyPch > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-key-pch=", midiKeyPch);
if (midiVelMidi > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity=", midiVelMidi);
if (midiVelAmp > 0)
cmdLine_addIntegerOpt(cmdLine, "-+midi-velocity-amp=", midiVelAmp);
if (rawControllerMode)
cmdLine.push_back("-+raw_controller_mode=1");
else if (forceSettings)
cmdLine.push_back("-+raw_controller_mode=0");
if (runRealtime)
cmdLine_addStringOpt(cmdLine, "-+rtaudio=", rtAudioModule);
cmdLine_addStringOpt(cmdLine, "-+rtmidi=", rtMidiModule);
if (scoreOffsetSeconds > 0.0)
cmdLine_addDoubleOpt(cmdLine, "-+skip_seconds=", scoreOffsetSeconds);
else if (forceSettings && scoreOffsetSeconds == 0.0)
cmdLine.push_back("-+skip_seconds=0");
if (!CsoundGUIMain::isEmptyString(orcName)) {
cmdLine.push_back(orcName);
if (!CsoundGUIMain::isCSDFile(orcName) &&
!CsoundGUIMain::isEmptyString(scoName))
cmdLine.push_back(scoName);
}
if (useAdditionalFlags && !CsoundGUIMain::isEmptyString(additionalFlags))
cmdLine.push_back(additionalFlags);
}
|
Initialize heartbeat property
|
Initialize heartbeat property
|
C++
|
lgpl-2.1
|
iver56/csound,max-ilse/csound,max-ilse/csound,mcanthony/csound,audiokit/csound,Angeldude/csound,mcanthony/csound,iver56/csound,max-ilse/csound,iver56/csound,mcanthony/csound,audiokit/csound,iver56/csound,audiokit/csound,nikhilsinghmus/csound,audiokit/csound,mcanthony/csound,Angeldude/csound,nikhilsinghmus/csound,Angeldude/csound,iver56/csound,iver56/csound,Angeldude/csound,Angeldude/csound,max-ilse/csound,mcanthony/csound,max-ilse/csound,Angeldude/csound,mcanthony/csound,audiokit/csound,nikhilsinghmus/csound,audiokit/csound,audiokit/csound,Angeldude/csound,audiokit/csound,nikhilsinghmus/csound,max-ilse/csound,mcanthony/csound,max-ilse/csound,max-ilse/csound,audiokit/csound,nikhilsinghmus/csound,mcanthony/csound,mcanthony/csound,nikhilsinghmus/csound,nikhilsinghmus/csound,Angeldude/csound,Angeldude/csound,nikhilsinghmus/csound,nikhilsinghmus/csound,nikhilsinghmus/csound,Angeldude/csound,max-ilse/csound,iver56/csound,audiokit/csound,mcanthony/csound,iver56/csound,iver56/csound,iver56/csound,max-ilse/csound
|
f9fe01954e3100240c05dd50223bc504337d744d
|
virvo/virvo/vvimageclient.cpp
|
virvo/virvo/vvimageclient.cpp
|
// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <limits>
#include "vvglew.h"
#include "vvimageclient.h"
#include "vvgltools.h"
#include "vvtexrend.h"
#include "float.h"
#include "vvrayrend.h"
#include "vvshaderfactory.h"
#include "vvshaderprogram.h"
#include "vvtoolshed.h"
#include "vvsocketio.h"
#include "vvdebugmsg.h"
#include "vvimage.h"
using std::cerr;
using std::endl;
vvImageClient::vvImageClient(vvVolDesc *vd, vvRenderState renderState,
const char* slaveName, int port,
const char* slaveFileName)
: vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IMAGE, slaveName, port, slaveFileName)
, _image(NULL)
{
vvDebugMsg::msg(1, "vvImageClient::vvImageClient()");
rendererType = REMOTE_IMAGE;
glewInit();
glGenTextures(1, &_rgbaTex);
_image = new vvImage;
}
vvImageClient::~vvImageClient()
{
vvDebugMsg::msg(1, "vvImageClient::~vvImageClient()");
exit();
glDeleteTextures(1, &_rgbaTex);
}
vvRemoteClient::ErrorType vvImageClient::render()
{
vvDebugMsg::msg(1, "vvImageClient::render()");
vvRemoteClient::ErrorType err = requestFrame();
if(err != vvRemoteClient::VV_OK)
return err;
if(!_socketIO)
return vvRemoteClient::VV_SOCKET_ERROR;
vvSocket::ErrorType sockerr = _socketIO->getImage(_image);
if(sockerr != vvSocket::VV_OK)
{
std::cerr << "vvImageClient::render: socket error (" << sockerr << ") - exiting..." << std::endl;
return vvRemoteClient::VV_SOCKET_ERROR;
}
_image->decode();
const int h = _image->getHeight();
const int w = _image->getWidth();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT
| GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
// get pixel and depth-data
glBindTexture(GL_TEXTURE_2D, _rgbaTex);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr());
vvGLTools::drawViewAlignedQuad();
glPopAttrib();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
return VV_OK;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
|
// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, [email protected]
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <limits>
#include "vvglew.h"
#include "vvimageclient.h"
#include "vvgltools.h"
#include "vvtexrend.h"
#include "float.h"
#include "vvrayrend.h"
#include "vvshaderfactory.h"
#include "vvshaderprogram.h"
#include "vvtoolshed.h"
#include "vvsocketio.h"
#include "vvdebugmsg.h"
#include "vvimage.h"
using std::cerr;
using std::endl;
vvImageClient::vvImageClient(vvVolDesc *vd, vvRenderState renderState,
const char* slaveName, int port,
const char* slaveFileName)
: vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IMAGE, slaveName, port, slaveFileName)
, _image(NULL)
{
vvDebugMsg::msg(1, "vvImageClient::vvImageClient()");
rendererType = REMOTE_IMAGE;
glewInit();
glGenTextures(1, &_rgbaTex);
_image = new vvImage;
}
vvImageClient::~vvImageClient()
{
vvDebugMsg::msg(1, "vvImageClient::~vvImageClient()");
vvRemoteClient::exit();
glDeleteTextures(1, &_rgbaTex);
}
vvRemoteClient::ErrorType vvImageClient::render()
{
vvDebugMsg::msg(1, "vvImageClient::render()");
vvRemoteClient::ErrorType err = requestFrame();
if(err != vvRemoteClient::VV_OK)
return err;
if(!_socketIO)
return vvRemoteClient::VV_SOCKET_ERROR;
vvSocket::ErrorType sockerr = _socketIO->getImage(_image);
if(sockerr != vvSocket::VV_OK)
{
std::cerr << "vvImageClient::render: socket error (" << sockerr << ") - exiting..." << std::endl;
return vvRemoteClient::VV_SOCKET_ERROR;
}
_image->decode();
const int h = _image->getHeight();
const int w = _image->getWidth();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT
| GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
// get pixel and depth-data
glBindTexture(GL_TEXTURE_2D, _rgbaTex);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr());
vvGLTools::drawViewAlignedQuad();
glPopAttrib();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
return VV_OK;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
|
make namespace function call more save
|
make namespace function call more save
git-svn-id: a0a066a1d7ce87c7a04dae20f169ad0cd8bda35d@1713 04231f92-3938-0410-9931-e931ac552b4f
|
C++
|
lgpl-2.1
|
deskvox/deskvox,deskvox/deskvox,deskvox/deskvox,deskvox/deskvox,deskvox/deskvox
|
bf55be2b8f0fb14e607986caf72da2ce4a995405
|
Infovis/Core/vtkPipelineGraphSource.cxx
|
Infovis/Core/vtkPipelineGraphSource.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPipelineGraphSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAbstractArray.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkArrayData.h"
#include "vtkCollection.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkGraph.h"
#include "vtkGraph.h"
#include "vtkInformation.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPipelineGraphSource.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVariantArray.h"
#include <vtksys/stl/map>
#include <vtksys/stl/stack>
#include <vtksys/ios/sstream>
using vtksys_stl::map;
using vtksys_stl::stack;
using vtksys_ios::ostringstream;
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
vtkStandardNewMacro(vtkPipelineGraphSource);
// ----------------------------------------------------------------------
vtkPipelineGraphSource::vtkPipelineGraphSource()
{
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->Sinks = vtkCollection::New();
}
// ----------------------------------------------------------------------
vtkPipelineGraphSource::~vtkPipelineGraphSource()
{
if (this->Sinks)
{
this->Sinks->Delete();
this->Sinks = NULL;
}
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::AddSink(vtkObject* sink)
{
if (sink != NULL && !this->Sinks->IsItemPresent(sink))
{
this->Sinks->AddItem(sink);
this->Modified();
}
}
void vtkPipelineGraphSource::RemoveSink(vtkObject* sink)
{
if (sink != NULL && this->Sinks->IsItemPresent(sink))
{
this->Sinks->RemoveItem(sink);
this->Modified();
}
}
// ----------------------------------------------------------------------
static void InsertObject(
vtkObject* object,
map<vtkObject*, vtkIdType>& object_map,
vtkMutableDirectedGraph* builder,
vtkStringArray* vertex_class_name_array,
vtkVariantArray* vertex_object_array,
vtkStringArray* edge_output_port_array,
vtkStringArray* edge_input_port_array,
vtkStringArray* edge_class_name_array,
vtkVariantArray* edge_object_array)
{
if(!object)
return;
if(object_map.count(object))
return;
// Insert pipeline algorithms ...
if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object))
{
object_map[algorithm] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(algorithm->GetClassName());
vertex_object_array->InsertNextValue(algorithm);
// Recursively insert algorithm inputs ...
for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j)
{
vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer();
InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_algorithm], object_map[algorithm]);
vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex());
edge_output_port_array->InsertNextValue(vtkVariant(algorithm->GetInputConnection(i, j)->GetIndex()).ToString());
edge_input_port_array->InsertNextValue(vtkVariant(i).ToString());
edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : "");
edge_object_array->InsertNextValue(input_data);
}
}
}
}
int vtkPipelineGraphSource::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Setup the graph data structure ...
VTK_CREATE(vtkMutableDirectedGraph, builder);
vtkStringArray* vertex_class_name_array = vtkStringArray::New();
vertex_class_name_array->SetName("class_name");
builder->GetVertexData()->AddArray(vertex_class_name_array);
vertex_class_name_array->Delete();
vtkVariantArray* vertex_object_array = vtkVariantArray::New();
vertex_object_array->SetName("object");
builder->GetVertexData()->AddArray(vertex_object_array);
vertex_object_array->Delete();
vtkStringArray* edge_output_port_array = vtkStringArray::New();
edge_output_port_array->SetName("output_port");
builder->GetEdgeData()->AddArray(edge_output_port_array);
edge_output_port_array->Delete();
vtkStringArray* edge_input_port_array = vtkStringArray::New();
edge_input_port_array->SetName("input_port");
builder->GetEdgeData()->AddArray(edge_input_port_array);
edge_input_port_array->Delete();
vtkStringArray* edge_class_name_array = vtkStringArray::New();
edge_class_name_array->SetName("class_name");
builder->GetEdgeData()->AddArray(edge_class_name_array);
edge_class_name_array->Delete();
vtkVariantArray* edge_object_array = vtkVariantArray::New();
edge_object_array->SetName("object");
builder->GetEdgeData()->AddArray(edge_object_array);
edge_object_array->Delete();
// Recursively insert pipeline components into the graph ...
map<vtkObject*, vtkIdType> object_map;
for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i)
{
InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
}
// Finish creating the output graph ...
vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector);
if(!output_graph->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Invalid graph structure");
return 0;
}
return 1;
}
void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name)
{
vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New();
sinks->AddItem(sink);
PipelineToDot(sinks, output, graph_name);
}
namespace {
void replace_all(std::string& str, std::string oldStr, std::string newStr)
{
size_t pos = 0;
while((pos = str.find(oldStr, pos)) != std::string::npos)
{
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
}
void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name)
{
// Create a graph representation of the pipeline ...
vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New();
for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i)
{
pipeline->AddSink(sinks->GetItemAsObject(i));
}
pipeline->Update();
vtkGraph* const pipeline_graph = pipeline->GetOutput();
vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object");
vtkAbstractArray* const edge_output_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("output_port");
vtkAbstractArray* const edge_input_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("input_port");
vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object");
output << "digraph \"" << graph_name << "\"\n";
output << "{\n";
// Do some standard formatting ...
output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n";
output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n";
// Write-out vertices ...
for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i)
{
vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject();
std::stringstream buffer;
object->PrintSelf(buffer, vtkIndent());
std::string line;
std::string object_state;
for(std::getline(buffer, line); buffer; std::getline(buffer, line))
{
replace_all(line, "\"", "'");
replace_all(line, "\r", "");
replace_all(line, "\n", "");
if(0 == line.find("Debug:"))
continue;
if(0 == line.find("Modified Time:"))
continue;
if(0 == line.find("Reference Count:"))
continue;
if(0 == line.find("Registered Events:"))
continue;
if(0 == line.find("Executive:"))
continue;
if(0 == line.find("ErrorCode:"))
continue;
if(0 == line.find("Information:"))
continue;
if(0 == line.find("AbortExecute:"))
continue;
if(0 == line.find("Progress:"))
continue;
if(0 == line.find("Progress Text:"))
continue;
if(0 == line.find(" "))
continue;
object_state += line + "\\n";
}
std::string fillcolor = "#ccffcc";
if(vtkAnnotationLink::SafeDownCast(object))
{
fillcolor = "#ccccff";
}
output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n";
}
// Write-out edges ...
vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New();
edges->SetGraph(pipeline_graph);
while(edges->HasNext())
{
vtkEdgeType edge = edges->Next();
vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject();
vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject();
const vtkStdString output_port = edge_output_port_array->GetVariantValue(edge.Id).ToString();
const vtkStdString input_port = edge_input_port_array->GetVariantValue(edge.Id).ToString();
vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject();
std::string color = "black";
if(vtkTree::SafeDownCast(object))
{
color = "#00bb00";
}
else if(vtkTable::SafeDownCast(object))
{
color = "blue";
}
else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object))
{
if(array_data->GetNumberOfArrays())
{
color = "";
for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i)
{
if(i)
color += ":";
if(array_data->GetArray(i)->IsDense())
color += "purple";
else
color += "red";
}
}
}
else if(vtkGraph::SafeDownCast(object))
{
color = "#cc6600";
}
output << " " << "node_" << source << " -> " << "node_" << target;
output << " [";
output << " color=\"" << color << "\" fontcolor=\"" << color << "\"";
output << " label=\"" << (object ? object->GetClassName() : "") << "\"";
output << " headlabel=\"" << input_port << "\"";
output << " taillabel=\"" << output_port << "\"";
output << " ]\n";
}
output << "}\n";
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPipelineGraphSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAbstractArray.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkArrayData.h"
#include "vtkCollection.h"
#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkGraph.h"
#include "vtkGraph.h"
#include "vtkInformation.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkPipelineGraphSource.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVariantArray.h"
#include <vtksys/stl/map>
#include <vtksys/stl/stack>
#include <vtksys/ios/sstream>
using vtksys_stl::map;
using vtksys_stl::stack;
using vtksys_ios::ostringstream;
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
vtkStandardNewMacro(vtkPipelineGraphSource);
// ----------------------------------------------------------------------
vtkPipelineGraphSource::vtkPipelineGraphSource()
{
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
this->Sinks = vtkCollection::New();
}
// ----------------------------------------------------------------------
vtkPipelineGraphSource::~vtkPipelineGraphSource()
{
if (this->Sinks)
{
this->Sinks->Delete();
this->Sinks = NULL;
}
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// ----------------------------------------------------------------------
void vtkPipelineGraphSource::AddSink(vtkObject* sink)
{
if (sink != NULL && !this->Sinks->IsItemPresent(sink))
{
this->Sinks->AddItem(sink);
this->Modified();
}
}
void vtkPipelineGraphSource::RemoveSink(vtkObject* sink)
{
if (sink != NULL && this->Sinks->IsItemPresent(sink))
{
this->Sinks->RemoveItem(sink);
this->Modified();
}
}
// ----------------------------------------------------------------------
static void InsertObject(
vtkObject* object,
map<vtkObject*, vtkIdType>& object_map,
vtkMutableDirectedGraph* builder,
vtkStringArray* vertex_class_name_array,
vtkVariantArray* vertex_object_array,
vtkStringArray* edge_output_port_array,
vtkStringArray* edge_input_port_array,
vtkStringArray* edge_class_name_array,
vtkVariantArray* edge_object_array)
{
if(!object)
return;
if(object_map.count(object))
return;
// Insert pipeline algorithms ...
if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object))
{
object_map[algorithm] = builder->AddVertex();
vertex_class_name_array->InsertNextValue(algorithm->GetClassName());
vertex_object_array->InsertNextValue(algorithm);
// Recursively insert algorithm inputs ...
for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i)
{
for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j)
{
vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer();
InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
builder->AddEdge(object_map[input_algorithm], object_map[algorithm]);
vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex());
edge_output_port_array->InsertNextValue(vtkVariant(algorithm->GetInputConnection(i, j)->GetIndex()).ToString());
edge_input_port_array->InsertNextValue(vtkVariant(i).ToString());
edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : "");
edge_object_array->InsertNextValue(input_data);
}
}
}
}
int vtkPipelineGraphSource::RequestData(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
// Setup the graph data structure ...
VTK_CREATE(vtkMutableDirectedGraph, builder);
vtkStringArray* vertex_class_name_array = vtkStringArray::New();
vertex_class_name_array->SetName("class_name");
builder->GetVertexData()->AddArray(vertex_class_name_array);
vertex_class_name_array->Delete();
vtkVariantArray* vertex_object_array = vtkVariantArray::New();
vertex_object_array->SetName("object");
builder->GetVertexData()->AddArray(vertex_object_array);
vertex_object_array->Delete();
vtkStringArray* edge_output_port_array = vtkStringArray::New();
edge_output_port_array->SetName("output_port");
builder->GetEdgeData()->AddArray(edge_output_port_array);
edge_output_port_array->Delete();
vtkStringArray* edge_input_port_array = vtkStringArray::New();
edge_input_port_array->SetName("input_port");
builder->GetEdgeData()->AddArray(edge_input_port_array);
edge_input_port_array->Delete();
vtkStringArray* edge_class_name_array = vtkStringArray::New();
edge_class_name_array->SetName("class_name");
builder->GetEdgeData()->AddArray(edge_class_name_array);
edge_class_name_array->Delete();
vtkVariantArray* edge_object_array = vtkVariantArray::New();
edge_object_array->SetName("object");
builder->GetEdgeData()->AddArray(edge_object_array);
edge_object_array->Delete();
// Recursively insert pipeline components into the graph ...
map<vtkObject*, vtkIdType> object_map;
for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i)
{
InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array);
}
// Finish creating the output graph ...
vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector);
if(!output_graph->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Invalid graph structure");
return 0;
}
return 1;
}
void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name)
{
vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New();
sinks->AddItem(sink);
PipelineToDot(sinks, output, graph_name);
}
namespace {
void replace_all(std::string& str, std::string oldStr, std::string newStr)
{
size_t pos = 0;
while((pos = str.find(oldStr, pos)) != std::string::npos)
{
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
}
void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name)
{
// Create a graph representation of the pipeline ...
vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New();
for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i)
{
pipeline->AddSink(sinks->GetItemAsObject(i));
}
pipeline->Update();
vtkGraph* const pipeline_graph = pipeline->GetOutput();
vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object");
vtkAbstractArray* const edge_output_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("output_port");
vtkAbstractArray* const edge_input_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("input_port");
vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object");
output << "digraph \"" << graph_name << "\"\n";
output << "{\n";
// Do some standard formatting ...
output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n";
output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n";
// Write-out vertices ...
for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i)
{
vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject();
std::stringstream buffer;
object->PrintSelf(buffer, vtkIndent());
std::string line;
std::string object_state;
while(std::getline(buffer, line))
{
replace_all(line, "\"", "'");
replace_all(line, "\r", "");
replace_all(line, "\n", "");
if(0 == line.find("Debug:"))
continue;
if(0 == line.find("Modified Time:"))
continue;
if(0 == line.find("Reference Count:"))
continue;
if(0 == line.find("Registered Events:"))
continue;
if(0 == line.find("Executive:"))
continue;
if(0 == line.find("ErrorCode:"))
continue;
if(0 == line.find("Information:"))
continue;
if(0 == line.find("AbortExecute:"))
continue;
if(0 == line.find("Progress:"))
continue;
if(0 == line.find("Progress Text:"))
continue;
if(0 == line.find(" "))
continue;
object_state += line + "\\n";
}
std::string fillcolor = "#ccffcc";
if(vtkAnnotationLink::SafeDownCast(object))
{
fillcolor = "#ccccff";
}
output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n";
}
// Write-out edges ...
vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New();
edges->SetGraph(pipeline_graph);
while(edges->HasNext())
{
vtkEdgeType edge = edges->Next();
vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject();
vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject();
const vtkStdString output_port = edge_output_port_array->GetVariantValue(edge.Id).ToString();
const vtkStdString input_port = edge_input_port_array->GetVariantValue(edge.Id).ToString();
vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject();
std::string color = "black";
if(vtkTree::SafeDownCast(object))
{
color = "#00bb00";
}
else if(vtkTable::SafeDownCast(object))
{
color = "blue";
}
else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object))
{
if(array_data->GetNumberOfArrays())
{
color = "";
for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i)
{
if(i)
color += ":";
if(array_data->GetArray(i)->IsDense())
color += "purple";
else
color += "red";
}
}
}
else if(vtkGraph::SafeDownCast(object))
{
color = "#cc6600";
}
output << " " << "node_" << source << " -> " << "node_" << target;
output << " [";
output << " color=\"" << color << "\" fontcolor=\"" << color << "\"";
output << " label=\"" << (object ? object->GetClassName() : "") << "\"";
output << " headlabel=\"" << input_port << "\"";
output << " taillabel=\"" << output_port << "\"";
output << " ]\n";
}
output << "}\n";
}
|
Fix compilation on VS 7.1
|
vtkPipelineGraphSource: Fix compilation on VS 7.1
Fix error
Infovis\Core\vtkPipelineGraphSource.cxx(253) : error C2451: conditional expression of type 'std::stringstream' is illegal
Ambiguous user-defined-conversion
by checking the state of the std::istream& returned by getline.
Change-Id: Ib25bfc02b85ac462dfc99960b2236a06e6111845
|
C++
|
bsd-3-clause
|
ashray/VTK-EVM,SimVascular/VTK,SimVascular/VTK,SimVascular/VTK,candy7393/VTK,sankhesh/VTK,demarle/VTK,jmerkow/VTK,msmolens/VTK,collects/VTK,jmerkow/VTK,demarle/VTK,sumedhasingla/VTK,keithroe/vtkoptix,biddisco/VTK,aashish24/VTK-old,johnkit/vtk-dev,hendradarwin/VTK,gram526/VTK,jmerkow/VTK,sankhesh/VTK,johnkit/vtk-dev,mspark93/VTK,gram526/VTK,candy7393/VTK,msmolens/VTK,gram526/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,gram526/VTK,msmolens/VTK,ashray/VTK-EVM,candy7393/VTK,demarle/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,sankhesh/VTK,keithroe/vtkoptix,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,collects/VTK,johnkit/vtk-dev,keithroe/vtkoptix,jmerkow/VTK,hendradarwin/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,msmolens/VTK,biddisco/VTK,demarle/VTK,collects/VTK,mspark93/VTK,mspark93/VTK,SimVascular/VTK,jmerkow/VTK,sumedhasingla/VTK,keithroe/vtkoptix,johnkit/vtk-dev,hendradarwin/VTK,demarle/VTK,johnkit/vtk-dev,sankhesh/VTK,demarle/VTK,demarle/VTK,sankhesh/VTK,msmolens/VTK,jmerkow/VTK,sumedhasingla/VTK,keithroe/vtkoptix,sumedhasingla/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,gram526/VTK,johnkit/vtk-dev,keithroe/vtkoptix,SimVascular/VTK,biddisco/VTK,sumedhasingla/VTK,aashish24/VTK-old,gram526/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,aashish24/VTK-old,gram526/VTK,keithroe/vtkoptix,ashray/VTK-EVM,ashray/VTK-EVM,SimVascular/VTK,mspark93/VTK,mspark93/VTK,candy7393/VTK,mspark93/VTK,sumedhasingla/VTK,aashish24/VTK-old,SimVascular/VTK,jmerkow/VTK,candy7393/VTK,candy7393/VTK,mspark93/VTK,gram526/VTK,ashray/VTK-EVM,hendradarwin/VTK,biddisco/VTK,ashray/VTK-EVM,aashish24/VTK-old,aashish24/VTK-old,ashray/VTK-EVM,ashray/VTK-EVM,msmolens/VTK,biddisco/VTK,demarle/VTK,sankhesh/VTK,hendradarwin/VTK,msmolens/VTK,collects/VTK,biddisco/VTK,candy7393/VTK,msmolens/VTK,biddisco/VTK,hendradarwin/VTK,mspark93/VTK,keithroe/vtkoptix,collects/VTK,collects/VTK,jmerkow/VTK,candy7393/VTK
|
3ad55e37b71b85d68e1f3af76e90dded40fedc35
|
src/autowiring/test/AnySharedPointerTest.cpp
|
src/autowiring/test/AnySharedPointerTest.cpp
|
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
// Autowiring takes advantage of the representational equivalence of instantiations of
// shared_ptr, and therefore requires that their layouts all be the same.
static_assert(
sizeof(std::shared_ptr<void*>) == sizeof(std::shared_ptr<int>),
"Shared pointer representations must be equivalent for casting to work correctly"
);
TEST_F(AnySharedPointerTest, CanReinterpretCastSharedPtr) {
auto iShared = std::make_shared<int>(101);
auto vShared = *reinterpret_cast<std::shared_ptr<void>*>(&iShared);
ASSERT_EQ(2UL, iShared.use_count()) << "Reinterpretive assignment of a void pointer did not increment the use count";
ASSERT_EQ(iShared.get(), vShared.get()) << "Reinterpreted shared pointer did not properly hold a member variable";
}
class MyUnusedClass {};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1.empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(auto_id_t<bool>{}, slot1.type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2.empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot.reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot.reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot.init<int>();
ASSERT_EQ(auto_id_t<int>{}, slot.type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot.ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}
class AlternateBase {
public:
virtual ~AlternateBase(void) {}
};
class AnySharedPtrObjA:
public CoreObject
{
public:
int aVal = 101;
int aVal2 = 101;
};
class AnySharedPtrObjB:
public AlternateBase,
public Decoration<0>,
public AnySharedPtrObjA
{
public:
int bVal = 102;
};
TEST_F(AnySharedPointerTest, CanCrossCast) {
(void) auto_id_t_init<AnySharedPtrObjA>::init;
(void) auto_id_t_init<AnySharedPtrObjB>::init;
// Ensure that dynamic casters are non-null in the block:
auto nullCaster = &autowiring::null_cast<AnySharedPtrObjA, CoreObject>;
ASSERT_NE(
nullCaster,
(autowiring::fast_pointer_cast_blind<AnySharedPtrObjA, CoreObject>::cast)
) << "Fast pointer caster for AnySharedPtrObjA was not correctly initialized";
ASSERT_NE(
reinterpret_cast<std::shared_ptr<void>(*)(const std::shared_ptr<CoreObject>&)>(nullCaster),
auto_id_t<AnySharedPtrObjA>::s_block.pFromObj
) << "AnySharedPtrObjA dynamic caster was incorrectly assigned";
auto rootB = std::make_shared<AnySharedPtrObjB>();
auto rootA = std::static_pointer_cast<AnySharedPtrObjA>(rootB);
auto rootBPtr = rootB.get();
auto rootAPtr = static_cast<AnySharedPtrObjA*>(rootB.get());
ASSERT_NE((void*) rootBPtr, (void*) rootAPtr) << "Objects were not correctly detected as having separate offsets";
AnySharedPointer aASP = rootA;
std::shared_ptr<CoreObject> obj = aASP.as_obj();
ASSERT_NE(nullptr, obj) << "An object cast attempt did not succeed as expected";
ASSERT_EQ(101, aASP.as<AnySharedPtrObjA>()->aVal);
AnySharedPointer bASP;
bASP.init<AnySharedPtrObjB>();
bASP.try_assign(obj);
ASSERT_NE(bASP, nullptr) << "An attempted cast incorrectly resulted in a null return";
ASSERT_EQ(102, bASP.as<AnySharedPtrObjB>()->bVal);
ASSERT_EQ(aASP, bASP) << "An aliased shared pointer was not detected as being equal";
}
TEST_F(AnySharedPointerTest, NullAfterMove) {
auto ptr = std::make_shared<bool>(false);
AnySharedPointer p1 = ptr;
AnySharedPointer p2 = std::move(p1);
ASSERT_FALSE(p1) << "Move construction of AnySharedPointer did not nullify rhs";
AnySharedPointer p3;
p3 = std::move(p2);
ASSERT_FALSE(p2) << "Move assignment of AnySharedPointer did not nullify rhs";
}
|
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "TestFixtures/Decoration.hpp"
#include "TestFixtures/SimpleObject.hpp"
#include <autowiring/AnySharedPointer.h>
#include <autowiring/autowiring.h>
class AnySharedPointerTest:
public testing::Test
{};
// Autowiring takes advantage of the representational equivalence of instantiations of
// shared_ptr, and therefore requires that their layouts all be the same.
static_assert(
sizeof(std::shared_ptr<void*>) == sizeof(std::shared_ptr<int>),
"Shared pointer representations must be equivalent for casting to work correctly"
);
TEST_F(AnySharedPointerTest, CanReinterpretCastSharedPtr) {
auto iShared = std::make_shared<int>(101);
auto vShared = *reinterpret_cast<std::shared_ptr<void>*>(&iShared);
ASSERT_EQ(2UL, iShared.use_count()) << "Reinterpretive assignment of a void pointer did not increment the use count";
ASSERT_EQ(iShared.get(), vShared.get()) << "Reinterpreted shared pointer did not properly hold a member variable";
}
class MyUnusedClass {};
TEST_F(AnySharedPointerTest, OperatorEq) {
AutoRequired<SimpleObject> sobj;
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny1(sobj);
ASSERT_TRUE((bool)sobjAny1);
ASSERT_EQ(sobj, sobjAny1) << "An AnySharedPointer instance initialized by constructor violated an identity test";
// Trivial equivalence of an AnySharedPointer based on an AutoFilter instance
AnySharedPointer sobjAny2;
sobjAny2 = sobj;
ASSERT_TRUE((bool)sobjAny2);
ASSERT_EQ(sobj, sobjAny2) << "An AnySharedPointer instance initialized by assignment violated an identity test";
}
TEST_F(AnySharedPointerTest, AnySharedPointerRelease) {
auto t = std::make_shared<int>(5);
// Assign over, then reset
{
AnySharedPointer ptr;
ptr = t;
}
// Verify the AnySharedPointer destructor worked correctly
ASSERT_TRUE(t.unique()) << "AnySharedPointer instance did not properly release a reference when destroyed";
}
TEST_F(AnySharedPointerTest, SlotReassignment) {
auto sharedPointerA = std::make_shared<bool>();
auto sharedPointerB = std::make_shared<bool>();
auto sharedPointerC = std::make_shared<int>();
// Make our slot, and start off with a shared pointer of one type:
AnySharedPointer slot;
slot = sharedPointerA;
// Verify that the assignment worked as anticipated:
ASSERT_EQ(2, sharedPointerA.use_count()) << "Constructor did not properly addref a shared pointer on initialization";
// Recast to another shared pointer, verify reference count goes down:
slot = sharedPointerB;
ASSERT_EQ(2, sharedPointerB.use_count()) << "Reference count was not incremented properly during a shared pointer hold";
ASSERT_TRUE(sharedPointerA.unique()) << "Destructor was not properly invoked for a shared pointer slot";
// Now change the type completely, verify proper release:
slot = sharedPointerC;
ASSERT_TRUE(sharedPointerB.unique()) << "Second assigned shared pointer was not released under type transformation";
}
TEST_F(AnySharedPointerTest, SlotsInVector) {
auto sharedPtr = std::make_shared<bool>();
{
std::list<AnySharedPointer> slots;
// Initialize with a lot of copies of sharedPtr
for(size_t i = 0; i < 10; i++) {
slots.push_back(AnySharedPointer(sharedPtr));
ASSERT_EQ(1 + (long)slots.size(), sharedPtr.use_count()) << "Unexpected number of references to a slotted shared pointer";
}
}
// Now verify that we're unique again:
ASSERT_TRUE(sharedPtr.unique()) << "Slots in a vector did not properly release all local clones";
}
TEST_F(AnySharedPointerTest, SlotDuplication) {
auto sharedPtr = std::make_shared<bool>();
AnySharedPointer slot2;
{
// Create a base slot to hold the shared pointer:
AnySharedPointer slot1(sharedPtr);
ASSERT_FALSE(slot1.empty()) << "A slot initialized from a shared pointer was incorrectly marked as empty";
// Verify the type came across:
ASSERT_EQ(auto_id_t<bool>{}, slot1.type()) << "Dynamic initialization did not correctly adjust the dynamic type";
// Now copy it over:
slot2 = slot1;
// Verify reference count was affected as expected
ASSERT_EQ(3, sharedPtr.use_count()) << "A second-order slot copy didn't increment the reference count as expected";
}
// Verify that the slot still holds a reference and that the reference count is correct:
ASSERT_FALSE(slot2.empty()) << "A slot should have continued to hold a shared pointer, but was prematurely cleared";
ASSERT_EQ(2, sharedPtr.use_count()) << "A slot going out of scope did not correctly decrement a shared pointer reference";
}
TEST_F(AnySharedPointerTest, TrivialRelease) {
auto a = std::make_shared<bool>();
auto b = std::make_shared<int>();
// Assign the slot to two different values, and make sure that they are released properly
AnySharedPointer slot;
slot = a;
slot = b;
ASSERT_TRUE(a.unique()) << "Expected reassignment of a slot to release a formerly held instance";
ASSERT_FALSE(b.unique()) << "Expected slot to hold a reference to the second specified instance";
// Now release, and verify that a release actually took place
slot.reset();
ASSERT_TRUE(b.unique()) << "Releasing a slot did not actually release the held value as expected";
}
TEST_F(AnySharedPointerTest, NoMultipleDelete) {
auto a = std::make_shared<bool>();
std::weak_ptr<bool> b = a;
// Create a slot and validate the behavior of reset, and to ensure that the underlying
// SharedPointerSlot is not multiply deleted.
{
AnySharedPointer slot;
slot = a;
slot.reset();
}
// Now verify that we didn't accidentally overdecrement the count:
ASSERT_FALSE(b.expired()) << "Shared pointer prematurely expired; SharedPointerSlot dtor double-strike suspected";
}
TEST_F(AnySharedPointerTest, InitDerivesCorrectType) {
AnySharedPointer slot;
slot.init<int>();
ASSERT_EQ(auto_id_t<int>{}, slot.type()) << "A manually initialized slot did not have the expected type";
}
TEST_F(AnySharedPointerTest, VoidReturnExpected) {
// Fill out our slot:
auto v = std::make_shared<int>(5);
AnySharedPointer slot;
slot = v;
// Validate equivalence of the void operator:
ASSERT_EQ(v.get(), slot.ptr()) << "Shared pointer slot did not return a void* with an expected value";
}
TEST_F(AnySharedPointerTest, CanHoldCoreObject) {
auto co = std::make_shared<CoreObject>();
AnySharedPointer x = co;
ASSERT_EQ(co, x) << "Held CoreObject was not equivalent to constructed instance";
}
TEST_F(AnySharedPointerTest, CanFastCastToSelf) {
(void)autowiring::fast_pointer_cast_initializer<CoreObject, CoreObject>::sc_init;
auto co = std::make_shared<CoreObject>();
ASSERT_EQ(
co,
autowiring::fast_pointer_cast<CoreObject>(co)
) << "Could not cast a CoreObject instance to itself";
}
class AlternateBase {
public:
virtual ~AlternateBase(void) {}
};
class AnySharedPtrObjA:
public CoreObject
{
public:
int aVal = 101;
int aVal2 = 101;
};
class AnySharedPtrObjB:
public AlternateBase,
public Decoration<0>,
public AnySharedPtrObjA
{
public:
int bVal = 102;
};
TEST_F(AnySharedPointerTest, CanCrossCast) {
(void) auto_id_t_init<AnySharedPtrObjA>::init;
(void) auto_id_t_init<AnySharedPtrObjB>::init;
// Ensure that dynamic casters are non-null in the block:
auto nullCaster = &autowiring::null_cast<AnySharedPtrObjA, CoreObject>;
ASSERT_NE(
nullCaster,
(autowiring::fast_pointer_cast_blind<AnySharedPtrObjA, CoreObject>::cast)
) << "Fast pointer caster for AnySharedPtrObjA was not correctly initialized";
ASSERT_NE(
reinterpret_cast<std::shared_ptr<void>(*)(const std::shared_ptr<CoreObject>&)>(nullCaster),
auto_id_t<AnySharedPtrObjA>::s_block.pFromObj
) << "AnySharedPtrObjA dynamic caster was incorrectly assigned";
auto rootB = std::make_shared<AnySharedPtrObjB>();
auto rootA = std::static_pointer_cast<AnySharedPtrObjA>(rootB);
auto rootBPtr = rootB.get();
auto rootAPtr = static_cast<AnySharedPtrObjA*>(rootB.get());
ASSERT_NE((void*) rootBPtr, (void*) rootAPtr) << "Objects were not correctly detected as having separate offsets";
AnySharedPointer aASP = rootA;
std::shared_ptr<CoreObject> obj = aASP.as_obj();
ASSERT_NE(nullptr, obj) << "An object cast attempt did not succeed as expected";
ASSERT_EQ(101, aASP.as<AnySharedPtrObjA>()->aVal);
AnySharedPointer bASP;
bASP.init<AnySharedPtrObjB>();
bASP.try_assign(obj);
ASSERT_NE(bASP, nullptr) << "An attempted cast incorrectly resulted in a null return";
ASSERT_EQ(102, bASP.as<AnySharedPtrObjB>()->bVal);
ASSERT_EQ(aASP, bASP) << "An aliased shared pointer was not detected as being equal";
}
TEST_F(AnySharedPointerTest, NullAfterMove) {
auto ptr = std::make_shared<bool>(false);
AnySharedPointer p1 = ptr;
AnySharedPointer p2 = std::move(p1);
ASSERT_FALSE(p1) << "Move construction of AnySharedPointer did not nullify rhs";
AnySharedPointer p3;
p3 = std::move(p2);
ASSERT_FALSE(p2) << "Move assignment of AnySharedPointer did not nullify rhs";
}
TEST_F(AnySharedPointerTest, NullPtrConstruction) {
AnySharedPointer x{ nullptr };
ASSERT_EQ(auto_id_t<void>{}, x.type()) << "nullptr type_id should have been void";
AnySharedPointer y;
AnySharedPointer z;
y = nullptr;
ASSERT_EQ(x, y) << "Nullptr initialization was not null";
ASSERT_EQ(x, z) << "Nullptr assignment was not null";
ASSERT_EQ(auto_id_t<void>{}, y.type());
}
|
Add unit tests for nullptr overloads
|
Add unit tests for nullptr overloads
|
C++
|
apache-2.0
|
leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,codemercenary/autowiring,codemercenary/autowiring,leapmotion/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring
|
2f1d1827aaf346437922b8a1952dcfedd0e9f590
|
src/backend/executor/merge_join_executor.cpp
|
src/backend/executor/merge_join_executor.cpp
|
/*-------------------------------------------------------------------------
*
* merge_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/merge_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
join_clauses_ = nullptr;
}
bool MergeJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false)
return status;
const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();
join_clauses_ = node.GetJoinClauses();
if (join_clauses_ == nullptr)
return false;
left_end_ = true;
right_end_ = true;
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool MergeJoinExecutor::DExecute() {
LOG_INFO("********** Merge Join executor :: 2 children \n");
if (right_end_) {
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
return false;
}
std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
right_tiles_.push_back(right.release());
LOG_INFO("size of right tiles: %lu", right_tiles_.size());
}
LOG_INFO("Got right tile \n");
if (left_end_) {
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
left_tiles_.push_back(left.release());
LOG_INFO("size of right tiles: %lu", left_tiles_.size());
}
LOG_INFO("Got left tile \n");
LogicalTile *left_tile = left_tiles_.back();
LogicalTile *right_tile = right_tiles_.back();
// Check the input logical tiles.
assert(left_tile != nullptr);
assert(right_tile != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile->GetSchema();
auto right_tile_schema = right_tile->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile->GetPositionLists().size();
}
/* build the schema given the projection */
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile->SetSchema(std::move(output_tile_schema));
// Get position list from two logical tiles
auto left_tile_position_lists = left_tile->GetPositionLists();
auto right_tile_position_lists = right_tile->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count = left_tile_column_count
+ right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
//size_t left_tile_row_count = left_tile_position_lists[0].size();
//size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
//LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count,
// right_tile_column_count);
//LOG_INFO("left col count: %lu, right col count: %lu",
// left_tile.get()->GetColumnCount(),
// right_tile.get()->GetColumnCount());
//LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count,
// right_tile_row_count);
size_t left_start_row = 0;
size_t right_start_row = 0;
size_t left_end_row = Advance(left_tile, left_start_row, true);
size_t right_end_row = Advance(right_tile, right_start_row, false);
while (left_end_row > left_start_row && right_end_row > right_start_row) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_start_row);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_start_row);
bool diff = false;
// try to match the join clauses
for (auto &clause : *join_clauses_) {
auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
nullptr);
auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
nullptr);
int ret = left_value.Compare(right_value);
if (ret < 0) {
// Left key < Right key, advance left
LOG_INFO("left < right, advance left");
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
diff = true;
break;
} else if (ret > 0) {
// Left key > Right key, advance right
LOG_INFO("left > right, advance right");
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
diff = true;
break;
}
// Left key == Right key, go check next join clause
}
if (diff) {
// join clauses are not matched, one of the tile has been advanced
continue;
}
// join clauses are matched, try to match predicate
LOG_INFO("one pair of tuples matches join clause");
// Join predicate exists
if (predicate_ != nullptr) {
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
// Join predicate is false. Advance both.
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
}
// sub tile matched, do a Cartesian product
// Go over every pair of tuples in left and right logical tiles
for (auto left_tile_row_itr : *left_tile) {
for (auto right_tile_row_itr : *right_tile) {
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]);
}
// Then, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(
right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]);
}
}
}
// then Advance both
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
// set the corresponding flags if left or right is end
// so that next execution time, it will be re executed
if (left_end_row == left_start_row) {
left_end_ = true;
}
if (right_end_row == right_start_row) {
right_end_ = true;
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
/**
* @brief Advance the row iterator until value changes in terms of the join clauses
* @return the end row number, [start_row, end_row) are the rows of the same value
* if the end_row == start_row, the subset is empty
*/
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
size_t end_row = start_row + 1;
size_t this_row = start_row;
size_t tuple_count = tile->GetTupleCount();
if (start_row >= tuple_count)
return start_row;
while (end_row < tuple_count) {
expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
this_row);
expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);
bool diff = false;
for (auto &clause : *join_clauses_) {
// Go thru each join clauses
auto expr = is_left ? clause.left_.get() : clause.right_.get();
peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
nullptr);
peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
nullptr);
if (0 != this_value.Compare(next_value)) {
diff = true;
break;
}
}
if (diff) {
break;
}
// the two tuples are the same, we advance by 1
end_row++;
this_row = end_row;
}
LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
end_row - start_row);
return end_row;
}
} // namespace executor
} // namespace peloton
|
/*-------------------------------------------------------------------------
*
* merge_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/merge_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
join_clauses_ = nullptr;
}
bool MergeJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false)
return status;
const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();
join_clauses_ = node.GetJoinClauses();
if (join_clauses_ == nullptr)
return false;
left_end_ = true;
right_end_ = true;
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool MergeJoinExecutor::DExecute() {
LOG_INFO("********** Merge Join executor :: 2 children \n");
if (right_end_) {
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
return false;
}
std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
right_tiles_.push_back(right.release());
LOG_INFO("size of right tiles: %lu", right_tiles_.size());
}
LOG_INFO("Got right tile \n");
if (left_end_) {
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
left_tiles_.push_back(left.release());
LOG_INFO("size of right tiles: %lu", left_tiles_.size());
}
LOG_INFO("Got left tile \n");
LogicalTile *left_tile = left_tiles_.back();
LogicalTile *right_tile = right_tiles_.back();
// Check the input logical tiles.
assert(left_tile != nullptr);
assert(right_tile != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile->GetSchema();
auto right_tile_schema = right_tile->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile->GetPositionLists().size();
}
/* build the schema given the projection */
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile->SetSchema(std::move(output_tile_schema));
// Get position list from two logical tiles
auto left_tile_position_lists = left_tile->GetPositionLists();
auto right_tile_position_lists = right_tile->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count = left_tile_column_count
+ right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
//size_t left_tile_row_count = left_tile_position_lists[0].size();
//size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
//LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count,
// right_tile_column_count);
//LOG_INFO("left col count: %lu, right col count: %lu",
// left_tile.get()->GetColumnCount(),
// right_tile.get()->GetColumnCount());
//LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count,
// right_tile_row_count);
size_t left_start_row = 0;
size_t right_start_row = 0;
size_t left_end_row = Advance(left_tile, left_start_row, true);
size_t right_end_row = Advance(right_tile, right_start_row, false);
while (left_end_row > left_start_row && right_end_row > right_start_row) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_start_row);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_start_row);
bool diff = false;
// try to match the join clauses
for (auto &clause : *join_clauses_) {
auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
nullptr);
auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
nullptr);
int ret = left_value.Compare(right_value);
if (ret < 0) {
// Left key < Right key, advance left
LOG_INFO("left < right, advance left");
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
diff = true;
break;
} else if (ret > 0) {
// Left key > Right key, advance right
LOG_INFO("left > right, advance right");
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
diff = true;
break;
}
// Left key == Right key, go check next join clause
}
if (diff) {
// join clauses are not matched, one of the tile has been advanced
continue;
}
// join clauses are matched, try to match predicate
LOG_INFO("one pair of tuples matches join clause");
// Join predicate exists
if (predicate_ != nullptr) {
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
// Join predicate is false. Advance both.
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
}
// sub tile matched, do a Cartesian product
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = left_start_row;
left_tile_row_itr < left_end_row; left_tile_row_itr++) {
for (size_t right_tile_row_itr = right_start_row;
right_tile_row_itr < right_end_row; right_tile_row_itr++) {
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]);
}
// Then, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(
right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]);
}
}
}
// then Advance both
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
// set the corresponding flags if left or right is end
// so that next execution time, it will be re executed
if (left_end_row == left_start_row) {
left_end_ = true;
}
if (right_end_row == right_start_row) {
right_end_ = true;
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
/**
* @brief Advance the row iterator until value changes in terms of the join clauses
* @return the end row number, [start_row, end_row) are the rows of the same value
* if the end_row == start_row, the subset is empty
*/
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
size_t end_row = start_row + 1;
size_t this_row = start_row;
size_t tuple_count = tile->GetTupleCount();
if (start_row >= tuple_count)
return start_row;
while (end_row < tuple_count) {
expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
this_row);
expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);
bool diff = false;
for (auto &clause : *join_clauses_) {
// Go thru each join clauses
auto expr = is_left ? clause.left_.get() : clause.right_.get();
peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
nullptr);
peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
nullptr);
if (0 != this_value.Compare(next_value)) {
diff = true;
break;
}
}
if (diff) {
break;
}
// the two tuples are the same, we advance by 1
end_row++;
this_row = end_row;
}
LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
end_row - start_row);
return end_row;
}
} // namespace executor
} // namespace peloton
|
fix over outputting in merge join
|
fix over outputting in merge join
Former-commit-id: fe08354da852e22cae2e1ed581c5f2054d391c1f
|
C++
|
apache-2.0
|
omegaga/peloton,larryxiao/peloton-1,ranxian/peloton,omegaga/peloton,larryxiao/peloton-1,ranxian/peloton,omegaga/peloton,larryxiao/peloton-1,omegaga/peloton,larryxiao/peloton-1,larryxiao/peloton-1,larryxiao/peloton,ranxian/peloton,larryxiao/peloton,larryxiao/peloton,larryxiao/peloton,larryxiao/peloton-1,amaliujia/CMUDB-peloton,ranxian/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,amaliujia/CMUDB-peloton,amaliujia/CMUDB-peloton,omegaga/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,ranxian/peloton,omegaga/peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,omegaga/peloton,larryxiao/peloton
|
2718b9b11afbac56ff39967317fb06bdb1298820
|
framework/inc/macros/debug/assertion.hxx
|
framework/inc/macros/debug/assertion.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
#define __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#if defined( ENABLE_ASSERTIONS ) || defined( ENABLE_WARNINGS )
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#endif
//*****************************************************************************************************************
// special macros for assertion handling
// 1) LOGTYPE use it to define the output of all assertions, errors, exception infos
// 2) LOGFILE_ASSERTIONS use it to define the file name to log assertions if LOGTYPE=LOGTYPE_FILE...
// 3) LOGFILE_WARNINGS use it to define the file name to log warnings if LOGTYPE=LOGTYPE_FILE...
// active for "non product":
// 4) LOG_ASSERT( BCONDITION, STEXT ) assert some critical errors wich depend from given condition
// 4a) LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) same like 4) + additional location of error
// 5) LOG_ERROR( SMETHOD, STEXT ) show errors without any condition
// active for debug only!
// 6) LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE ) show/log an exception for easier debug
// 7) LOG_WARNING( SMETHOD, STEXT ) should be used to detect leaks in algorithm, mechanism or operation handling
//*****************************************************************************************************************
//_________________________________________________________________________________________________________________
#if defined( ENABLE_ASSERTIONS ) || defined( ENABLE_WARNINGS )
/*_____________________________________________________________________________________________________________
LOGFILE_ASSERTIONS
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_ASSERTIONS
#define LOGFILE_ASSERTIONS "_framework_assertions.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertion to logfile (if condition is sal_False - like a DBG_ASSERT!) and continue with program.
Set LOGTYPE to LOGTYPE_FILECONTINUE to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_FILECONTINUE
#define LOG_ASSERT( BCONDITION, STEXT ) \
if ( ( BCONDITION ) == sal_False ) \
{ \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, STEXT ) \
}
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) \
if ( ( BCONDITION ) == sal_True ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, _sAssertBuffer.makeStringAndClear() ) \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertion to file and exit the program.
Set LOGTYPE to LOGTYPE_FILEEXIT to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_FILEEXIT
#define LOG_ASSERT( BCONDITION, STEXT ) \
if ( ( BCONDITION ) == sal_False ) \
{ \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, STEXT ) \
exit(-1); \
}
#define LOG_ASSERT2( BCONDITION, SMETHODE, STEXT ) \
if ( ( BCONDITION ) == sal_True ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, _sAssertBuffer.makeStringAndClear() ) \
exit(-1); \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertions to messagebox. (We use OSL_ENSURE to do this.)
Set LOGTYPE to LOGTYPE_MESSAGEBOX to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_MESSAGEBOX
#define LOG_ASSERT( BCONDITION, STEXT ) \
OSL_ENSURE( ( BCONDITION ), STEXT );
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
OSL_ENSURE( !( BCONDITION ), _sAssertBuffer.makeStringAndClear() ); \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ERROR( SMETHOD, STEXT )
Show an error by using current set output mode by define LOGTYPE!
_____________________________________________________________________________________________________________*/
#define LOG_ERROR( SMETHOD, STEXT ) \
LOG_ASSERT2( sal_True, SMETHOD, STEXT )
#else
// If right testmode is'nt set - implements these macros empty!
#undef LOGFILE_ASSERTIONS
#define LOG_ASSERT( BCONDITION, STEXT )
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
#define LOG_ERROR( SMETHOD, STEXT )
#endif // ENABLE_ASSERTIONS
//_________________________________________________________________________________________________________________
#if defined( ENABLE_WARNINGS )
/*_____________________________________________________________________________________________________________
LOGFILE_WARNINGS
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_WARNINGS
#define LOGFILE_WARNINGS "_framework_warnings.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE )
Show some exception info by using current set output mode by define LOGTYPE!
We use a seperated scope {} do protect us against multiple variable definitions.
_____________________________________________________________________________________________________________*/
#define LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE ) \
{ \
::rtl::OStringBuffer _sAssertBuffer2( 256 ); \
_sAssertBuffer2.append( SOWNMESSAGE ); \
_sAssertBuffer2.append( "\n" ); \
_sAssertBuffer2.append( U2B(SEXCEPTIONMESSAGE) ); \
LOG_ERROR( SMETHOD, _sAssertBuffer2.makeStringAndClear() ) \
}
/*_____________________________________________________________________________________________________________
LOG_WARNING( SMETHOD, STEXT )
Use it to show/log warnings for programmer for follow reasons:
- algorithm errors
- undefined states
- unknown errors from other modules ...
_____________________________________________________________________________________________________________*/
#define LOG_WARNING( SMETHOD, STEXT ) \
LOG_ERROR( SMETHOD, STEXT )
#else
// If right testmode is'nt set - implements these macros empty!
#undef LOGFILE_WARNINGS
#define LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE )
#define LOG_WARNING( SMETHOD, STEXT )
#endif // ENABLE_WARNINGS
#endif // #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
#define __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#if defined( ENABLE_ASSERTIONS ) || defined( ENABLE_WARNINGS )
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#endif
//*****************************************************************************************************************
// special macros for assertion handling
// 1) LOGTYPE use it to define the output of all assertions, errors, exception infos
// 2) LOGFILE_ASSERTIONS use it to define the file name to log assertions if LOGTYPE=LOGTYPE_FILE...
// 3) LOGFILE_WARNINGS use it to define the file name to log warnings if LOGTYPE=LOGTYPE_FILE...
// active for "non product":
// 4) LOG_ASSERT( BCONDITION, STEXT ) assert some critical errors wich depend from given condition
// 4a) LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) same like 4) + additional location of error
// 5) LOG_ERROR( SMETHOD, STEXT ) show errors without any condition
// active for debug only!
// 6) LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE ) show/log an exception for easier debug
// 7) LOG_WARNING( SMETHOD, STEXT ) should be used to detect leaks in algorithm, mechanism or operation handling
//*****************************************************************************************************************
//_________________________________________________________________________________________________________________
#if defined( ENABLE_ASSERTIONS ) || defined( ENABLE_WARNINGS )
/*_____________________________________________________________________________________________________________
LOGFILE_ASSERTIONS
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_ASSERTIONS
#define LOGFILE_ASSERTIONS "_framework_assertions.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertion to logfile (if condition is sal_False - like a DBG_ASSERT!) and continue with program.
Set LOGTYPE to LOGTYPE_FILECONTINUE to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_FILECONTINUE
#define LOG_ASSERT( BCONDITION, STEXT ) \
if ( ( BCONDITION ) == sal_False ) \
{ \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, STEXT ) \
}
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) \
if ( ( BCONDITION ) == sal_True ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, _sAssertBuffer.getStr() ) \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertion to file and exit the program.
Set LOGTYPE to LOGTYPE_FILEEXIT to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_FILEEXIT
#define LOG_ASSERT( BCONDITION, STEXT ) \
if ( ( BCONDITION ) == sal_False ) \
{ \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, STEXT ) \
exit(-1); \
}
#define LOG_ASSERT2( BCONDITION, SMETHODE, STEXT ) \
if ( ( BCONDITION ) == sal_True ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
WRITE_LOGFILE( LOGFILE_ASSERTIONS, _sAssertBuffer.getStr() ) \
exit(-1); \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ASSERT ( BCONDITION, STEXT )
LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
Forward assertions to messagebox. (We use OSL_ENSURE to do this.)
Set LOGTYPE to LOGTYPE_MESSAGEBOX to do this.
BCONDITION is inserted in "(...)" because user can call this macro with an complex expression!
_____________________________________________________________________________________________________________*/
#if LOGTYPE==LOGTYPE_MESSAGEBOX
#define LOG_ASSERT( BCONDITION, STEXT ) \
OSL_ENSURE( ( BCONDITION ), STEXT );
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT ) \
{ \
::rtl::OStringBuffer _sAssertBuffer( 256 ); \
_sAssertBuffer.append( "ASSERT:\n\t" ); \
_sAssertBuffer.append( SMETHOD ); \
_sAssertBuffer.append( "\n\t\"" ); \
_sAssertBuffer.append( STEXT ); \
_sAssertBuffer.append( "\"\n" ); \
OSL_ENSURE( !( BCONDITION ), _sAssertBuffer.getStr() ); \
}
#endif
/*_____________________________________________________________________________________________________________
LOG_ERROR( SMETHOD, STEXT )
Show an error by using current set output mode by define LOGTYPE!
_____________________________________________________________________________________________________________*/
#define LOG_ERROR( SMETHOD, STEXT ) \
LOG_ASSERT2( sal_True, SMETHOD, STEXT )
#else
// If right testmode is'nt set - implements these macros empty!
#undef LOGFILE_ASSERTIONS
#define LOG_ASSERT( BCONDITION, STEXT )
#define LOG_ASSERT2( BCONDITION, SMETHOD, STEXT )
#define LOG_ERROR( SMETHOD, STEXT )
#endif // ENABLE_ASSERTIONS
//_________________________________________________________________________________________________________________
#if defined( ENABLE_WARNINGS )
/*_____________________________________________________________________________________________________________
LOGFILE_WARNINGS
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_WARNINGS
#define LOGFILE_WARNINGS "_framework_warnings.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE )
Show some exception info by using current set output mode by define LOGTYPE!
We use a seperated scope {} do protect us against multiple variable definitions.
_____________________________________________________________________________________________________________*/
#define LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE ) \
{ \
::rtl::OStringBuffer _sAssertBuffer2( 256 ); \
_sAssertBuffer2.append( SOWNMESSAGE ); \
_sAssertBuffer2.append( "\n" ); \
_sAssertBuffer2.append( U2B(SEXCEPTIONMESSAGE) ); \
LOG_ERROR( SMETHOD, _sAssertBuffer2.getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_WARNING( SMETHOD, STEXT )
Use it to show/log warnings for programmer for follow reasons:
- algorithm errors
- undefined states
- unknown errors from other modules ...
_____________________________________________________________________________________________________________*/
#define LOG_WARNING( SMETHOD, STEXT ) \
LOG_ERROR( SMETHOD, STEXT )
#else
// If right testmode is'nt set - implements these macros empty!
#undef LOGFILE_WARNINGS
#define LOG_EXCEPTION( SMETHOD, SOWNMESSAGE, SEXCEPTIONMESSAGE )
#define LOG_WARNING( SMETHOD, STEXT )
#endif // ENABLE_WARNINGS
#endif // #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
tweak assert
|
tweak assert
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
41226c0b6f5da3ecde6cc58b41ee88b4700a764e
|
framework/source/classes/taskcreator.cxx
|
framework/source/classes/taskcreator.cxx
|
/*************************************************************************
*
* $RCSfile: taskcreator.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: as $ $Date: 2001-08-16 09:45:11 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_CLASSES_TASKCREATOR_HXX_
#include <classes/taskcreator.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_
#include <com/sun/star/awt/XToolkit.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPPLIER_HPP_
#include <com/sun/star/frame/XFramesSupplier.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_AWT_WINDOWDESCRIPTOR_HPP_
#include <com/sun/star/awt/WindowDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWATTRIBUTE_HPP_
#include <com/sun/star/awt/WindowAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-****************************************************************************************************//**
@short create a new task with a system window inside
@descr With this method you can create a new empty system task. We create the task and the container
window inside of it. Created node will be a child of given parent frame.
@seealso method createBrowserTask()
@param "aInfo", collection of information, which are used to create task
@return A reference to the new created task.
@onerror We return a null-reference.
@threadsafe no
*//*-*****************************************************************************************************/
css::uno::Reference< css::frame::XFrame > TaskCreator::createSystemTask( const TaskInfo& aInfo )
{
// Safe impossible cases.
// Method is not designed for all incoming parameter!
LOG_ASSERT2( implcp_createSystemTask( aInfo ), "TaskCreator::createNewSystemTask()", "Invalid parameter detected!" )
// Set default return value to NULL!
css::uno::Reference< css::frame::XFrame > xTask;
// Get toolkit to create task container window.
css::uno::Reference< css::awt::XToolkit > xToolkit( aInfo.xFactory->createInstance( SERVICENAME_VCLTOOLKIT ), css::uno::UNO_QUERY );
if( xToolkit.is() == sal_True )
{
// Describe window properties.
css::awt::WindowDescriptor aDescriptor;
aDescriptor.Type = css::awt::WindowClass_TOP ;
aDescriptor.WindowServiceName = DECLARE_ASCII("window") ;
aDescriptor.ParentIndex = -1 ;
aDescriptor.Parent = css::uno::Reference< css::awt::XWindowPeer >() ;
aDescriptor.Bounds = css::awt::Rectangle(0,0,0,0) ;
aDescriptor.WindowAttributes = css::awt::WindowAttribute::BORDER |
css::awt::WindowAttribute::MOVEABLE |
css::awt::WindowAttribute::SIZEABLE |
css::awt::WindowAttribute::CLOSEABLE ;
// Create a new blank container window and get access to parent container to append new created task.
css::uno::Reference< css::awt::XWindowPeer > xPeer = xToolkit->createWindow( aDescriptor );
css::uno::Reference< css::awt::XWindow > xWindow ( xPeer, css::uno::UNO_QUERY );
css::uno::Reference< css::frame::XFrames > xContainer = aInfo.xParent->getFrames();
if(
( xWindow.is() == sal_True ) &&
( xContainer.is() == sal_True )
)
{
// Create new system task.
xTask = css::uno::Reference< css::frame::XFrame >( aInfo.xFactory->createInstance( SERVICENAME_TASK ), css::uno::UNO_QUERY );
if( xTask.is() == sal_True )
{
// Set window on task.
// Do it before you call other interface methods on task-object ...
// because this object must be initialized before you can do such things.
// Otherwise he throw an exception for UNINITIALIZED working mode!
// Don't forget to create tree-bindings! use given parent as parent node of new task ...
// ... and append it to his container.
// (task member xParent will automaticly set by "append()" call!)
// ! sTaskName already filtered by TaskInfo structure! Special targets are not allowed here ...
// Disable task window first! Otherwise it's visible during showing of any progress
// and user interaction could make some trouble ... GPF is possible!
// So we disable it here ... and our loading proccess enable it after successfully operation.
xTask->initialize ( xWindow );
xTask->setName ( aInfo.sTaskName );
xContainer->append ( xTask );
}
}
}
// Return result of this operation.
return xTask;
}
//*****************************************************************************************************************
css::uno::Reference< css::frame::XFrame > TaskCreator::createBrowserTask( const TaskInfo& aInfo )
{
LOG_ERROR( "TaskCreator::createNewBrowserTask()", "Not supported yet! Return empty reference." )
return css::uno::Reference< css::frame::XFrame >();
}
//_________________________________________________________________________________________________________________
// debug methods
//_________________________________________________________________________________________________________________
/*-----------------------------------------------------------------------------------------------------------------
The follow methods checks the parameter for other functions. If a parameter or his value is non valid,
we return "sal_False". (else sal_True) This mechanism is used to throw an ASSERT!
-----------------------------------------------------------------------------------------------------------------*/
#ifdef ENABLE_ASSERTIONS
//*****************************************************************************************************************
sal_Bool TaskCreator::implcp_createSystemTask( const TaskInfo& aInfo )
{
return(
( &aInfo == NULL ) ||
( aInfo.xFactory.is() == sal_False ) ||
( aInfo.xParent.is() == sal_False ) ||
( aInfo.sTaskName == SPECIALTARGET_SELF ) ||
( aInfo.sTaskName == SPECIALTARGET_BLANK ) ||
( aInfo.sTaskName == SPECIALTARGET_PARENT ) ||
( aInfo.sTaskName == SPECIALTARGET_TOP ) ||
( aInfo.sTaskName == SPECIALTARGET_MENUBAR ) ||
( aInfo.sTaskName == SPECIALTARGET_HELPAGENT ) ||
(
( aInfo.bVisible != sal_True ) &&
( aInfo.bVisible != sal_False )
)
);
}
//*****************************************************************************************************************
sal_Bool TaskCreator::implcp_createBrowserTask( const TaskInfo& aInfo )
{
return(
( &aInfo == NULL ) ||
( aInfo.xFactory.is() == sal_False ) ||
( aInfo.xParent.is() == sal_False ) ||
( aInfo.sTaskName == SPECIALTARGET_SELF ) ||
( aInfo.sTaskName == SPECIALTARGET_BLANK ) ||
( aInfo.sTaskName == SPECIALTARGET_PARENT ) ||
( aInfo.sTaskName == SPECIALTARGET_TOP ) ||
( aInfo.sTaskName == SPECIALTARGET_MENUBAR ) ||
( aInfo.sTaskName == SPECIALTARGET_HELPAGENT ) ||
(
( aInfo.bVisible != sal_True ) &&
( aInfo.bVisible != sal_False )
)
);
}
#endif // #ifdef ENABLE_ASSERTIONS
} // namespace framework
|
/*************************************************************************
*
* $RCSfile: taskcreator.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: mba $ $Date: 2001-09-19 08:06:50 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_CLASSES_TASKCREATOR_HXX_
#include <classes/taskcreator.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_
#include <com/sun/star/awt/XToolkit.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMESSUPPLIER_HPP_
#include <com/sun/star/frame/XFramesSupplier.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_AWT_WINDOWDESCRIPTOR_HPP_
#include <com/sun/star/awt/WindowDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_WINDOWATTRIBUTE_HPP_
#include <com/sun/star/awt/WindowAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-****************************************************************************************************//**
@short create a new task with a system window inside
@descr With this method you can create a new empty system task. We create the task and the container
window inside of it. Created node will be a child of given parent frame.
@seealso method createBrowserTask()
@param "aInfo", collection of information, which are used to create task
@return A reference to the new created task.
@onerror We return a null-reference.
@threadsafe no
*//*-*****************************************************************************************************/
css::uno::Reference< css::frame::XFrame > TaskCreator::createSystemTask( const TaskInfo& aInfo )
{
// Safe impossible cases.
// Method is not designed for all incoming parameter!
LOG_ASSERT2( implcp_createSystemTask( aInfo ), "TaskCreator::createNewSystemTask()", "Invalid parameter detected!" )
// Set default return value to NULL!
css::uno::Reference< css::frame::XFrame > xTask;
// Get toolkit to create task container window.
css::uno::Reference< css::awt::XToolkit > xToolkit( aInfo.xFactory->createInstance( SERVICENAME_VCLTOOLKIT ), css::uno::UNO_QUERY );
if( xToolkit.is() == sal_True )
{
// Describe window properties.
css::awt::WindowDescriptor aDescriptor;
aDescriptor.Type = css::awt::WindowClass_TOP ;
aDescriptor.WindowServiceName = DECLARE_ASCII("window") ;
aDescriptor.ParentIndex = -1 ;
aDescriptor.Parent = css::uno::Reference< css::awt::XWindowPeer >() ;
aDescriptor.Bounds = css::awt::Rectangle(0,0,0,0) ;
aDescriptor.WindowAttributes = css::awt::WindowAttribute::BORDER |
css::awt::WindowAttribute::MOVEABLE |
css::awt::WindowAttribute::SIZEABLE |
css::awt::WindowAttribute::CLOSEABLE ;
// Create a new blank container window and get access to parent container to append new created task.
css::uno::Reference< css::awt::XWindowPeer > xPeer = xToolkit->createWindow( aDescriptor );
css::uno::Reference< css::awt::XWindow > xWindow ( xPeer, css::uno::UNO_QUERY );
xPeer->setBackground( 0xFFFFFFFF );
css::uno::Reference< css::frame::XFrames > xContainer = aInfo.xParent->getFrames();
if(
( xWindow.is() == sal_True ) &&
( xContainer.is() == sal_True )
)
{
// Create new system task.
xTask = css::uno::Reference< css::frame::XFrame >( aInfo.xFactory->createInstance( SERVICENAME_TASK ), css::uno::UNO_QUERY );
if( xTask.is() == sal_True )
{
// Set window on task.
// Do it before you call other interface methods on task-object ...
// because this object must be initialized before you can do such things.
// Otherwise he throw an exception for UNINITIALIZED working mode!
// Don't forget to create tree-bindings! use given parent as parent node of new task ...
// ... and append it to his container.
// (task member xParent will automaticly set by "append()" call!)
// ! sTaskName already filtered by TaskInfo structure! Special targets are not allowed here ...
// Disable task window first! Otherwise it's visible during showing of any progress
// and user interaction could make some trouble ... GPF is possible!
// So we disable it here ... and our loading proccess enable it after successfully operation.
xTask->initialize ( xWindow );
xTask->setName ( aInfo.sTaskName );
xContainer->append ( xTask );
}
}
}
// Return result of this operation.
return xTask;
}
//*****************************************************************************************************************
css::uno::Reference< css::frame::XFrame > TaskCreator::createBrowserTask( const TaskInfo& aInfo )
{
LOG_ERROR( "TaskCreator::createNewBrowserTask()", "Not supported yet! Return empty reference." )
return css::uno::Reference< css::frame::XFrame >();
}
//_________________________________________________________________________________________________________________
// debug methods
//_________________________________________________________________________________________________________________
/*-----------------------------------------------------------------------------------------------------------------
The follow methods checks the parameter for other functions. If a parameter or his value is non valid,
we return "sal_False". (else sal_True) This mechanism is used to throw an ASSERT!
-----------------------------------------------------------------------------------------------------------------*/
#ifdef ENABLE_ASSERTIONS
//*****************************************************************************************************************
sal_Bool TaskCreator::implcp_createSystemTask( const TaskInfo& aInfo )
{
return(
( &aInfo == NULL ) ||
( aInfo.xFactory.is() == sal_False ) ||
( aInfo.xParent.is() == sal_False ) ||
( aInfo.sTaskName == SPECIALTARGET_SELF ) ||
( aInfo.sTaskName == SPECIALTARGET_BLANK ) ||
( aInfo.sTaskName == SPECIALTARGET_PARENT ) ||
( aInfo.sTaskName == SPECIALTARGET_TOP ) ||
( aInfo.sTaskName == SPECIALTARGET_MENUBAR ) ||
( aInfo.sTaskName == SPECIALTARGET_HELPAGENT ) ||
(
( aInfo.bVisible != sal_True ) &&
( aInfo.bVisible != sal_False )
)
);
}
//*****************************************************************************************************************
sal_Bool TaskCreator::implcp_createBrowserTask( const TaskInfo& aInfo )
{
return(
( &aInfo == NULL ) ||
( aInfo.xFactory.is() == sal_False ) ||
( aInfo.xParent.is() == sal_False ) ||
( aInfo.sTaskName == SPECIALTARGET_SELF ) ||
( aInfo.sTaskName == SPECIALTARGET_BLANK ) ||
( aInfo.sTaskName == SPECIALTARGET_PARENT ) ||
( aInfo.sTaskName == SPECIALTARGET_TOP ) ||
( aInfo.sTaskName == SPECIALTARGET_MENUBAR ) ||
( aInfo.sTaskName == SPECIALTARGET_HELPAGENT ) ||
(
( aInfo.bVisible != sal_True ) &&
( aInfo.bVisible != sal_False )
)
);
}
#endif // #ifdef ENABLE_ASSERTIONS
} // namespace framework
|
set background of taskwindow to transparent
|
#79689#: set background of taskwindow to transparent
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
5421d37da9ee6fffaa360ce902d2e2c93a90bbbb
|
boost/horner-sine.cc
|
boost/horner-sine.cc
|
#include <iostream>
#include <utility>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::cpp_dec_float;
typedef boost::multiprecision::number<cpp_dec_float<64> > mp_type;
mp_type mysin(const mp_type& x)
{
// Approximation of sin(x * pi/2) for -1 <= x <= 1, using an order 63 polynomial.
static const std::array<mp_type, 32U> coefs =
{{
mp_type("+1.5707963267948966192313216916397514420985846996875529104874722961539082031431044993140174126711"), //"),
mp_type("-0.64596409750624625365575656389794573337969351178927307696134454382929989411386887578263960484"), // ^3
mp_type("+0.07969262624616704512050554949047802252091164235106119545663865720995702920146198554317279"), // ^5
mp_type("-0.0046817541353186881006854639339534378594950280185010575749538605102665157913157426229824"), // ^7
mp_type("+0.00016044118478735982187266087016347332970280754062061156858775174056686380286868007443"), // ^9
mp_type("-3.598843235212085340458540018208389404888495232432127661083907575106196374913134E-6"), // ^11
mp_type("+5.692172921967926811775255303592184372902829756054598109818158853197797542565E-8"), // ^13
mp_type("-6.688035109811467232478226335783138689956270985704278659373558497256423498E-10"), // ^15
mp_type("+6.066935731106195667101445665327140070166203261129845646380005577490472E-12"), // ^17
mp_type("-4.377065467313742277184271313776319094862897030084226361576452003432E-14"), // ^19
mp_type("+2.571422892860473866153865950420487369167895373255729246889168337E-16"), // ^21
mp_type("-1.253899540535457665340073300390626396596970180355253776711660E-18"), // ^23
mp_type("+5.15645517658028233395375998562329055050964428219501277474E-21"), // ^25
mp_type("-1.812399312848887477410034071087545686586497030654642705E-23"), // ^27
mp_type("+5.50728578652238583570585513920522536675023562254864E-26"), // ^29
mp_type("-1.461148710664467988723468673933026649943084902958E-28"), // ^31
mp_type("+3.41405297003316172502972039913417222912445427E-31"), // ^33
mp_type("-7.07885550810745570069916712806856538290251E-34"), // ^35
mp_type("+1.31128947968267628970845439024155655665E-36"), // ^37
mp_type("-2.18318293181145698535113946654065918E-39"), // ^39
mp_type("+3.28462680978498856345937578502923E-42"), // ^41
mp_type("-4.48753699028101089490067137298E-45"), // ^43
mp_type("+5.59219884208696457859353716E-48"), // ^45
mp_type("-6.38214503973500471720565E-51"), // ^47
mp_type("+6.69528558381794452556E-54"), // ^49
mp_type("-6.47841373182350206E-57"), // ^51
mp_type("+5.800016389666445E-60"), // ^53
mp_type("-4.818507347289E-63"), // ^55
mp_type("+3.724683686E-66"), // ^57
mp_type("-2.6856479E-69"), // ^59
mp_type("+1.81046E-72"), // ^61
mp_type("-1.133E-75"), // ^63
}};
const mp_type v = x * 2 / boost::math::constants::pi<mp_type>();
const mp_type x2 = (v * v);
//
// Polynomial evaluation follows, if mp_type allocates memory then
// just one such allocation occurs - to initialize the variable "sum" -
// and no temporaries are created at all.
//
const mp_type sum = ((((((((((((((((((((((((((((((( + coefs[31U]
* x2 + coefs[30U])
* x2 + coefs[29U])
* x2 + coefs[28U])
* x2 + coefs[27U])
* x2 + coefs[26U])
* x2 + coefs[25U])
* x2 + coefs[24U])
* x2 + coefs[23U])
* x2 + coefs[22U])
* x2 + coefs[21U])
* x2 + coefs[20U])
* x2 + coefs[19U])
* x2 + coefs[18U])
* x2 + coefs[17U])
* x2 + coefs[16U])
* x2 + coefs[15U])
* x2 + coefs[14U])
* x2 + coefs[13U])
* x2 + coefs[12U])
* x2 + coefs[11U])
* x2 + coefs[10U])
* x2 + coefs[9U])
* x2 + coefs[8U])
* x2 + coefs[7U])
* x2 + coefs[6U])
* x2 + coefs[5U])
* x2 + coefs[4U])
* x2 + coefs[3U])
* x2 + coefs[2U])
* x2 + coefs[1U])
* x2 + coefs[0U])
* v;
return sum;
}
int main(void)
{
mp_type pid4 = boost::math::constants::pi<mp_type>() / 4;
std::cout << std::setprecision(std::numeric_limits< ::mp_type>::digits10) << std::scientific;
std::cout << mysin(pid4) << std::endl;
return 0;
}
|
/* based upon http://www.boost.org/doc/libs/1_55_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/poly_eg.html
* Use, modification and distribution are subject to the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
* Copyright ???? 20??. */
#include <iostream>
#include <utility>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using boost::multiprecision::cpp_dec_float;
typedef boost::multiprecision::number<cpp_dec_float<64> > mp_type;
mp_type mysin(const mp_type& x)
{
// Approximation of sin(x * pi/2) for -1 <= x <= 1, using an order 63 polynomial.
static const std::array<mp_type, 32U> coefs =
{{
mp_type("+1.5707963267948966192313216916397514420985846996875529104874722961539082031431044993140174126711"), //"),
mp_type("-0.64596409750624625365575656389794573337969351178927307696134454382929989411386887578263960484"), // ^3
mp_type("+0.07969262624616704512050554949047802252091164235106119545663865720995702920146198554317279"), // ^5
mp_type("-0.0046817541353186881006854639339534378594950280185010575749538605102665157913157426229824"), // ^7
mp_type("+0.00016044118478735982187266087016347332970280754062061156858775174056686380286868007443"), // ^9
mp_type("-3.598843235212085340458540018208389404888495232432127661083907575106196374913134E-6"), // ^11
mp_type("+5.692172921967926811775255303592184372902829756054598109818158853197797542565E-8"), // ^13
mp_type("-6.688035109811467232478226335783138689956270985704278659373558497256423498E-10"), // ^15
mp_type("+6.066935731106195667101445665327140070166203261129845646380005577490472E-12"), // ^17
mp_type("-4.377065467313742277184271313776319094862897030084226361576452003432E-14"), // ^19
mp_type("+2.571422892860473866153865950420487369167895373255729246889168337E-16"), // ^21
mp_type("-1.253899540535457665340073300390626396596970180355253776711660E-18"), // ^23
mp_type("+5.15645517658028233395375998562329055050964428219501277474E-21"), // ^25
mp_type("-1.812399312848887477410034071087545686586497030654642705E-23"), // ^27
mp_type("+5.50728578652238583570585513920522536675023562254864E-26"), // ^29
mp_type("-1.461148710664467988723468673933026649943084902958E-28"), // ^31
mp_type("+3.41405297003316172502972039913417222912445427E-31"), // ^33
mp_type("-7.07885550810745570069916712806856538290251E-34"), // ^35
mp_type("+1.31128947968267628970845439024155655665E-36"), // ^37
mp_type("-2.18318293181145698535113946654065918E-39"), // ^39
mp_type("+3.28462680978498856345937578502923E-42"), // ^41
mp_type("-4.48753699028101089490067137298E-45"), // ^43
mp_type("+5.59219884208696457859353716E-48"), // ^45
mp_type("-6.38214503973500471720565E-51"), // ^47
mp_type("+6.69528558381794452556E-54"), // ^49
mp_type("-6.47841373182350206E-57"), // ^51
mp_type("+5.800016389666445E-60"), // ^53
mp_type("-4.818507347289E-63"), // ^55
mp_type("+3.724683686E-66"), // ^57
mp_type("-2.6856479E-69"), // ^59
mp_type("+1.81046E-72"), // ^61
mp_type("-1.133E-75"), // ^63
}};
const mp_type v = x * 2 / boost::math::constants::pi<mp_type>();
const mp_type x2 = (v * v);
//
// Polynomial evaluation follows, if mp_type allocates memory then
// just one such allocation occurs - to initialize the variable "sum" -
// and no temporaries are created at all.
//
const mp_type sum = ((((((((((((((((((((((((((((((( + coefs[31U]
* x2 + coefs[30U])
* x2 + coefs[29U])
* x2 + coefs[28U])
* x2 + coefs[27U])
* x2 + coefs[26U])
* x2 + coefs[25U])
* x2 + coefs[24U])
* x2 + coefs[23U])
* x2 + coefs[22U])
* x2 + coefs[21U])
* x2 + coefs[20U])
* x2 + coefs[19U])
* x2 + coefs[18U])
* x2 + coefs[17U])
* x2 + coefs[16U])
* x2 + coefs[15U])
* x2 + coefs[14U])
* x2 + coefs[13U])
* x2 + coefs[12U])
* x2 + coefs[11U])
* x2 + coefs[10U])
* x2 + coefs[9U])
* x2 + coefs[8U])
* x2 + coefs[7U])
* x2 + coefs[6U])
* x2 + coefs[5U])
* x2 + coefs[4U])
* x2 + coefs[3U])
* x2 + coefs[2U])
* x2 + coefs[1U])
* x2 + coefs[0U])
* v;
return sum;
}
int main(void)
{
mp_type pid4 = boost::math::constants::pi<mp_type>() / 4;
std::cout << std::setprecision(std::numeric_limits< ::mp_type>::digits10) << std::scientific;
std::cout << mysin(pid4) << std::endl;
return 0;
}
|
add boost license for code copied from their website
|
add boost license for code copied from their website
|
C++
|
bsd-3-clause
|
jeffhammond/multiprecision,jeffhammond/multiprecision
|
6678efaacf47a46e33469b66db34cb5d3c1e88e2
|
shell/platform/linux/fl_platform_plugin.cc
|
shell/platform/linux/fl_platform_plugin.cc
|
// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/fl_platform_plugin.h"
#include <gtk/gtk.h>
#include <cstring>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h"
static constexpr char kChannelName[] = "flutter/platform";
static constexpr char kBadArgumentsError[] = "Bad Arguments";
static constexpr char kUnknownClipboardFormatError[] =
"Unknown Clipboard Format";
static constexpr char kFailedError[] = "Failed";
static constexpr char kGetClipboardDataMethod[] = "Clipboard.getData";
static constexpr char kSetClipboardDataMethod[] = "Clipboard.setData";
static constexpr char kClipboardHasStringsMethod[] = "Clipboard.hasStrings";
static constexpr char kSystemNavigatorPopMethod[] = "SystemNavigator.pop";
static constexpr char kTextKey[] = "text";
static constexpr char kValueKey[] = "value";
static constexpr char kTextPlainFormat[] = "text/plain";
struct _FlPlatformPlugin {
GObject parent_instance;
FlMethodChannel* channel;
};
G_DEFINE_TYPE(FlPlatformPlugin, fl_platform_plugin, G_TYPE_OBJECT)
// Sends the method call response to Flutter.
static void send_response(FlMethodCall* method_call,
FlMethodResponse* response) {
g_autoptr(GError) error = nullptr;
if (!fl_method_call_respond(method_call, response, &error)) {
g_warning("Failed to send method call response: %s", error->message);
}
}
// Called when clipboard text received.
static void clipboard_text_cb(GtkClipboard* clipboard,
const gchar* text,
gpointer user_data) {
g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data);
g_autoptr(FlValue) result = nullptr;
if (text != nullptr) {
result = fl_value_new_map();
fl_value_set_string_take(result, kTextKey, fl_value_new_string(text));
}
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_success_response_new(result));
send_response(method_call, response);
}
// Called when clipboard text received during has_strings.
static void clipboard_text_has_strings_cb(GtkClipboard* clipboard,
const gchar* text,
gpointer user_data) {
g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data);
g_autoptr(FlValue) result = fl_value_new_map();
fl_value_set_string_take(
result, kValueKey,
fl_value_new_bool(text != nullptr && strlen(text) > 0));
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_success_response_new(result));
send_response(method_call, response);
}
// Called when Flutter wants to copy to the clipboard.
static FlMethodResponse* clipboard_set_data(FlPlatformPlugin* self,
FlValue* args) {
if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Argument map missing or malformed", nullptr));
}
FlValue* text_value = fl_value_lookup_string(args, kTextKey);
if (text_value == nullptr ||
fl_value_get_type(text_value) != FL_VALUE_TYPE_STRING) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Missing clipboard text", nullptr));
}
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_set_text(clipboard, fl_value_get_string(text_value), -1);
return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
// Called when Flutter wants to paste from the clipboard.
static FlMethodResponse* clipboard_get_data_async(FlPlatformPlugin* self,
FlMethodCall* method_call) {
FlValue* args = fl_method_call_get_args(method_call);
if (fl_value_get_type(args) != FL_VALUE_TYPE_STRING) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Expected string", nullptr));
}
const gchar* format = fl_value_get_string(args);
if (strcmp(format, kTextPlainFormat) != 0) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kUnknownClipboardFormatError, "GTK clipboard API only supports text",
nullptr));
}
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_request_text(clipboard, clipboard_text_cb,
g_object_ref(method_call));
// Will respond later.
return nullptr;
}
// Called when Flutter wants to know if the content of the clipboard is able to
// be pasted, without actually accessing the clipboard content itself.
static FlMethodResponse* clipboard_has_strings_async(
FlPlatformPlugin* self,
FlMethodCall* method_call) {
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_request_text(clipboard, clipboard_text_has_strings_cb,
g_object_ref(method_call));
// Will respond later.
return nullptr;
}
// Called when Flutter wants to quit the application.
static FlMethodResponse* system_navigator_pop(FlPlatformPlugin* self) {
GApplication* app = g_application_get_default();
if (app == nullptr) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kFailedError, "Unable to get GApplication", nullptr));
}
g_application_quit(app);
return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
// Called when a method call is received from Flutter.
static void method_call_cb(FlMethodChannel* channel,
FlMethodCall* method_call,
gpointer user_data) {
FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(user_data);
const gchar* method = fl_method_call_get_name(method_call);
FlValue* args = fl_method_call_get_args(method_call);
g_autoptr(FlMethodResponse) response = nullptr;
if (strcmp(method, kSetClipboardDataMethod) == 0) {
response = clipboard_set_data(self, args);
} else if (strcmp(method, kGetClipboardDataMethod) == 0) {
response = clipboard_get_data_async(self, method_call);
} else if (strcmp(method, kClipboardHasStringsMethod) == 0) {
response = clipboard_has_strings_async(self, method_call);
} else if (strcmp(method, kSystemNavigatorPopMethod) == 0) {
response = system_navigator_pop(self);
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
if (response != nullptr) {
send_response(method_call, response);
}
}
static void fl_platform_plugin_dispose(GObject* object) {
FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(object);
g_clear_object(&self->channel);
G_OBJECT_CLASS(fl_platform_plugin_parent_class)->dispose(object);
}
static void fl_platform_plugin_class_init(FlPlatformPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_platform_plugin_dispose;
}
static void fl_platform_plugin_init(FlPlatformPlugin* self) {}
FlPlatformPlugin* fl_platform_plugin_new(FlBinaryMessenger* messenger) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
FlPlatformPlugin* self =
FL_PLATFORM_PLUGIN(g_object_new(fl_platform_plugin_get_type(), nullptr));
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
self->channel =
fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(self->channel, method_call_cb, self,
nullptr);
return self;
}
|
// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/fl_platform_plugin.h"
#include <gtk/gtk.h>
#include <cstring>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h"
static constexpr char kChannelName[] = "flutter/platform";
static constexpr char kBadArgumentsError[] = "Bad Arguments";
static constexpr char kUnknownClipboardFormatError[] =
"Unknown Clipboard Format";
static constexpr char kFailedError[] = "Failed";
static constexpr char kGetClipboardDataMethod[] = "Clipboard.getData";
static constexpr char kSetClipboardDataMethod[] = "Clipboard.setData";
static constexpr char kClipboardHasStringsMethod[] = "Clipboard.hasStrings";
static constexpr char kPlaySoundMethod[] = "SystemSound.play";
static constexpr char kSystemNavigatorPopMethod[] = "SystemNavigator.pop";
static constexpr char kTextKey[] = "text";
static constexpr char kValueKey[] = "value";
static constexpr char kTextPlainFormat[] = "text/plain";
static constexpr char kSoundTypeAlert[] = "SystemSoundType.alert";
static constexpr char kSoundTypeClick[] = "SystemSoundType.click";
struct _FlPlatformPlugin {
GObject parent_instance;
FlMethodChannel* channel;
};
G_DEFINE_TYPE(FlPlatformPlugin, fl_platform_plugin, G_TYPE_OBJECT)
// Sends the method call response to Flutter.
static void send_response(FlMethodCall* method_call,
FlMethodResponse* response) {
g_autoptr(GError) error = nullptr;
if (!fl_method_call_respond(method_call, response, &error)) {
g_warning("Failed to send method call response: %s", error->message);
}
}
// Called when clipboard text received.
static void clipboard_text_cb(GtkClipboard* clipboard,
const gchar* text,
gpointer user_data) {
g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data);
g_autoptr(FlValue) result = nullptr;
if (text != nullptr) {
result = fl_value_new_map();
fl_value_set_string_take(result, kTextKey, fl_value_new_string(text));
}
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_success_response_new(result));
send_response(method_call, response);
}
// Called when clipboard text received during has_strings.
static void clipboard_text_has_strings_cb(GtkClipboard* clipboard,
const gchar* text,
gpointer user_data) {
g_autoptr(FlMethodCall) method_call = FL_METHOD_CALL(user_data);
g_autoptr(FlValue) result = fl_value_new_map();
fl_value_set_string_take(
result, kValueKey,
fl_value_new_bool(text != nullptr && strlen(text) > 0));
g_autoptr(FlMethodResponse) response =
FL_METHOD_RESPONSE(fl_method_success_response_new(result));
send_response(method_call, response);
}
// Called when Flutter wants to copy to the clipboard.
static FlMethodResponse* clipboard_set_data(FlPlatformPlugin* self,
FlValue* args) {
if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Argument map missing or malformed", nullptr));
}
FlValue* text_value = fl_value_lookup_string(args, kTextKey);
if (text_value == nullptr ||
fl_value_get_type(text_value) != FL_VALUE_TYPE_STRING) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Missing clipboard text", nullptr));
}
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_set_text(clipboard, fl_value_get_string(text_value), -1);
return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
// Called when Flutter wants to paste from the clipboard.
static FlMethodResponse* clipboard_get_data_async(FlPlatformPlugin* self,
FlMethodCall* method_call) {
FlValue* args = fl_method_call_get_args(method_call);
if (fl_value_get_type(args) != FL_VALUE_TYPE_STRING) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Expected string", nullptr));
}
const gchar* format = fl_value_get_string(args);
if (strcmp(format, kTextPlainFormat) != 0) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kUnknownClipboardFormatError, "GTK clipboard API only supports text",
nullptr));
}
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_request_text(clipboard, clipboard_text_cb,
g_object_ref(method_call));
// Will respond later.
return nullptr;
}
// Called when Flutter wants to know if the content of the clipboard is able to
// be pasted, without actually accessing the clipboard content itself.
static FlMethodResponse* clipboard_has_strings_async(
FlPlatformPlugin* self,
FlMethodCall* method_call) {
GtkClipboard* clipboard =
gtk_clipboard_get_default(gdk_display_get_default());
gtk_clipboard_request_text(clipboard, clipboard_text_has_strings_cb,
g_object_ref(method_call));
// Will respond later.
return nullptr;
}
// Called when Flutter wants to play a sound.
static FlMethodResponse* system_sound_play(FlPlatformPlugin* self,
FlValue* args) {
if (fl_value_get_type(args) != FL_VALUE_TYPE_STRING) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Expected string", nullptr));
}
const gchar* type = fl_value_get_string(args);
if (strcmp(type, kSoundTypeAlert) == 0) {
GdkDisplay* display = gdk_display_get_default();
if (display != nullptr) {
gdk_display_beep(display);
}
} else if (strcmp(type, kSoundTypeClick) == 0) {
// We don't make sounds for keyboard on desktops.
} else {
g_warning("Ignoring unknown sound type %s in SystemSound.play.\n", type);
}
return FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
// Called when Flutter wants to quit the application.
static FlMethodResponse* system_navigator_pop(FlPlatformPlugin* self) {
GApplication* app = g_application_get_default();
if (app == nullptr) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kFailedError, "Unable to get GApplication", nullptr));
}
g_application_quit(app);
return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
// Called when a method call is received from Flutter.
static void method_call_cb(FlMethodChannel* channel,
FlMethodCall* method_call,
gpointer user_data) {
FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(user_data);
const gchar* method = fl_method_call_get_name(method_call);
FlValue* args = fl_method_call_get_args(method_call);
g_autoptr(FlMethodResponse) response = nullptr;
if (strcmp(method, kSetClipboardDataMethod) == 0) {
response = clipboard_set_data(self, args);
} else if (strcmp(method, kGetClipboardDataMethod) == 0) {
response = clipboard_get_data_async(self, method_call);
} else if (strcmp(method, kClipboardHasStringsMethod) == 0) {
response = clipboard_has_strings_async(self, method_call);
} else if (strcmp(method, kPlaySoundMethod) == 0) {
response = system_sound_play(self, args);
} else if (strcmp(method, kSystemNavigatorPopMethod) == 0) {
response = system_navigator_pop(self);
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
if (response != nullptr) {
send_response(method_call, response);
}
}
static void fl_platform_plugin_dispose(GObject* object) {
FlPlatformPlugin* self = FL_PLATFORM_PLUGIN(object);
g_clear_object(&self->channel);
G_OBJECT_CLASS(fl_platform_plugin_parent_class)->dispose(object);
}
static void fl_platform_plugin_class_init(FlPlatformPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_platform_plugin_dispose;
}
static void fl_platform_plugin_init(FlPlatformPlugin* self) {}
FlPlatformPlugin* fl_platform_plugin_new(FlBinaryMessenger* messenger) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
FlPlatformPlugin* self =
FL_PLATFORM_PLUGIN(g_object_new(fl_platform_plugin_get_type(), nullptr));
g_autoptr(FlJsonMethodCodec) codec = fl_json_method_codec_new();
self->channel =
fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(self->channel, method_call_cb, self,
nullptr);
return self;
}
|
Implement SystemSound.play
|
Implement SystemSound.play
|
C++
|
bsd-3-clause
|
aam/engine,chinmaygarde/sky_engine,jamesr/sky_engine,rmacnak-google/engine,aam/engine,jason-simmons/sky_engine,jamesr/flutter_engine,flutter/engine,jamesr/sky_engine,jason-simmons/sky_engine,devoncarew/engine,jamesr/flutter_engine,jason-simmons/sky_engine,flutter/engine,chinmaygarde/flutter_engine,devoncarew/sky_engine,devoncarew/sky_engine,chinmaygarde/flutter_engine,aam/engine,rmacnak-google/engine,chinmaygarde/flutter_engine,Hixie/sky_engine,jason-simmons/sky_engine,aam/engine,flutter/engine,jamesr/sky_engine,devoncarew/engine,flutter/engine,jamesr/flutter_engine,rmacnak-google/engine,aam/engine,jamesr/flutter_engine,jason-simmons/flutter_engine,jason-simmons/flutter_engine,rmacnak-google/engine,rmacnak-google/engine,chinmaygarde/flutter_engine,Hixie/sky_engine,chinmaygarde/flutter_engine,chinmaygarde/sky_engine,chinmaygarde/sky_engine,flutter/engine,jason-simmons/flutter_engine,devoncarew/sky_engine,devoncarew/sky_engine,jamesr/flutter_engine,rmacnak-google/engine,jason-simmons/sky_engine,rmacnak-google/engine,chinmaygarde/flutter_engine,chinmaygarde/flutter_engine,Hixie/sky_engine,jason-simmons/flutter_engine,chinmaygarde/sky_engine,jason-simmons/sky_engine,jamesr/flutter_engine,Hixie/sky_engine,Hixie/sky_engine,jason-simmons/flutter_engine,Hixie/sky_engine,aam/engine,aam/engine,chinmaygarde/sky_engine,devoncarew/engine,chinmaygarde/sky_engine,flutter/engine,devoncarew/sky_engine,devoncarew/engine,devoncarew/sky_engine,aam/engine,jamesr/flutter_engine,jamesr/sky_engine,jason-simmons/flutter_engine,jason-simmons/flutter_engine,jamesr/sky_engine,jamesr/sky_engine,jason-simmons/sky_engine,Hixie/sky_engine,jason-simmons/flutter_engine,chinmaygarde/sky_engine,flutter/engine,flutter/engine,jamesr/flutter_engine,devoncarew/engine,devoncarew/engine,devoncarew/sky_engine,jamesr/flutter_engine,jamesr/sky_engine,Hixie/sky_engine,devoncarew/engine
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.