text
stringlengths 54
60.6k
|
---|
<commit_before>//===----------------------------------------------------------------------===//
// The LLVM analyze utility
//
// This utility is designed to print out the results of running various analysis
// passes on a program. This is useful for understanding a program, or for
// debugging an analysis pass.
//
// analyze --help - Output information about command line switches
// analyze --quiet - Do not print analysis name before output
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Support/PassNameParser.h"
#include <algorithm>
struct ModulePassPrinter : public Pass {
const PassInfo *PassToPrint;
ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool run(Module &M) {
std::cout << "Printing Analysis info for Pass "
<< PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
struct FunctionPassPrinter : public FunctionPass {
const PassInfo *PassToPrint;
FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool runOnFunction(Function &F) {
std::cout << "Printing Analysis info for function '" << F.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, F.getParent());
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
struct BasicBlockPassPrinter : public BasicBlockPass {
const PassInfo *PassToPrint;
BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool runOnBasicBlock(BasicBlock &BB) {
std::cout << "Printing Analysis info for BasicBlock '" << BB.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, BB.getParent()->getParent());
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"),
cl::value_desc("filename"));
static cl::opt<bool> Quiet("q", cl::desc("Don't print analysis pass names"));
static cl::alias QuietA("quiet", cl::desc("Alias for -q"),
cl::aliasopt(Quiet));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Analysis> >
AnalysesList(cl::desc("Analyses available:"));
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
Module *CurMod = 0;
try {
CurMod = ParseBytecodeFile(InputFilename);
if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
std::cerr << argv[0] << ": input file didn't read correctly.\n";
return 1;
}
} catch (const ParseException &E) {
std::cerr << argv[0] << ": " << E.getMessage() << "\n";
return 1;
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Passes;
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < AnalysesList.size(); ++i) {
const PassInfo *Analysis = AnalysesList[i];
if (Analysis->getNormalCtor()) {
Pass *P = Analysis->getNormalCtor()();
Passes.add(P);
if (BasicBlockPass *BBP = dynamic_cast<BasicBlockPass*>(P))
Passes.add(new BasicBlockPassPrinter(Analysis));
else if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P))
Passes.add(new FunctionPassPrinter(Analysis));
else
Passes.add(new ModulePassPrinter(Analysis));
} else
std::cerr << argv[0] << ": cannot create pass: "
<< Analysis->getPassName() << "\n";
}
Passes.run(*CurMod);
delete CurMod;
return 0;
}
<commit_msg> - 'analyze' and 'as' now explicitly verify input because AsmParser doesn't.<commit_after>//===----------------------------------------------------------------------===//
// The LLVM analyze utility
//
// This utility is designed to print out the results of running various analysis
// passes on a program. This is useful for understanding a program, or for
// debugging an analysis pass.
//
// analyze --help - Output information about command line switches
// analyze --quiet - Do not print analysis name before output
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/PassNameParser.h"
#include <algorithm>
struct ModulePassPrinter : public Pass {
const PassInfo *PassToPrint;
ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool run(Module &M) {
std::cout << "Printing Analysis info for Pass "
<< PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
struct FunctionPassPrinter : public FunctionPass {
const PassInfo *PassToPrint;
FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool runOnFunction(Function &F) {
std::cout << "Printing Analysis info for function '" << F.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, F.getParent());
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
struct BasicBlockPassPrinter : public BasicBlockPass {
const PassInfo *PassToPrint;
BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
virtual bool runOnBasicBlock(BasicBlock &BB) {
std::cout << "Printing Analysis info for BasicBlock '" << BB.getName()
<< "': Pass " << PassToPrint->getPassName() << ":\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, BB.getParent()->getParent());
// Get and print pass...
return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequiredID(PassToPrint);
AU.setPreservesAll();
}
};
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"),
cl::value_desc("filename"));
static cl::opt<bool> Quiet("q", cl::desc("Don't print analysis pass names"));
static cl::alias QuietA("quiet", cl::desc("Alias for -q"),
cl::aliasopt(Quiet));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Analysis> >
AnalysesList(cl::desc("Analyses available:"));
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
Module *CurMod = 0;
try {
CurMod = ParseBytecodeFile(InputFilename);
if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
std::cerr << argv[0] << ": input file didn't read correctly.\n";
return 1;
}
} catch (const ParseException &E) {
std::cerr << argv[0] << ": " << E.getMessage() << "\n";
return 1;
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Passes;
// Make sure the input LLVM is well formed.
Passes.add(createVerifierPass());
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < AnalysesList.size(); ++i) {
const PassInfo *Analysis = AnalysesList[i];
if (Analysis->getNormalCtor()) {
Pass *P = Analysis->getNormalCtor()();
Passes.add(P);
if (BasicBlockPass *BBP = dynamic_cast<BasicBlockPass*>(P))
Passes.add(new BasicBlockPassPrinter(Analysis));
else if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P))
Passes.add(new FunctionPassPrinter(Analysis));
else
Passes.add(new ModulePassPrinter(Analysis));
} else
std::cerr << argv[0] << ": cannot create pass: "
<< Analysis->getPassName() << "\n";
}
Passes.run(*CurMod);
delete CurMod;
return 0;
}
<|endoftext|> |
<commit_before>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/hash_layout.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "../source/logging/appenders/minizip/unzip.h"
#if defined(_WIN32) || defined(_WIN64)
#include "../source/logging/appenders/minizip/iowin32.h"
#endif
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include "utility/countof.h"
#include "utility/resource.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
Path FindHashlog(const Path& path)
{
// Try to find .hashlog in the current path
Path hashlog = path.IsRegularFile() ? path : (path / ".hashlog");
if (hashlog.IsExists())
return hashlog;
// Try to find .hashlog in the parent path
Path parent = path.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return Path();
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const Path& path)
{
std::unordered_map<uint32_t, std::string> hashmap;
File hashlog(path);
// Check if .hashlog is exists
if (!hashlog.IsExists())
return hashmap;
// Open .hashlog file
hashlog.Open(true, false);
// Check if .hashlog is opened
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog.Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint16_t length;
if (hashlog.Read(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog.Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
// Close .hashlog file
hashlog.Close();
return hashmap;
}
bool WriteHashlog(const Path& path, const std::unordered_map<uint32_t, std::string>& hashmap)
{
File hashlog(path);
// Open or create .hashlog file
hashlog.OpenOrCreate(false, true, true);
// Check if .hashlog is avaliable
if (!hashlog)
return false;
// Write the hash map size
uint32_t size = (uint32_t)hashmap.size();
if (hashlog.Write(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
// Read the hash map content
for (const auto& item : hashmap)
{
uint32_t hash = (uint32_t)item.first;
if (hashlog.Write(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
uint16_t length = (uint16_t)item.second.size();
if (hashlog.Write(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return false;
auto buffer = item.second.data();
if (hashlog.Write(buffer, length) != length)
return false;
}
// Close .hashlog file
hashlog.Close();
return true;
}
Path UnzipFile(const Path& path)
{
// Open a zip archive
unzFile unzf;
#if defined(_WIN32) || defined(_WIN64)
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzf = unzOpen2_64(path.wstring().c_str(), &ffunc);
#else
unzf = unzOpen64(path.string().c_str());
#endif
if (unzf == nullptr)
throwex FileSystemException("Cannot open a zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip = resource(unzf, [](unzFile handle) { unzClose(handle); });
File destination(path + ".tmp");
// Open the destination file for writing
destination.Create(false, true);
// Get info about the zip archive
unz_global_info global_info;
int result = unzGetGlobalInfo(unzf, &global_info);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive global info!").Attach(path);
// Loop to extract all files from the zip archive
uLong i;
for (i = 0; i < global_info.number_entry; ++i)
{
unz_file_info file_info;
char filename[1024];
// Get info about the current file in the zip archive
result = unzGetCurrentFileInfo(unzf, &file_info, filename, (unsigned)countof(filename), NULL, 0, NULL, 0);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive file info!").Attach(path);
// Check if this entry is a file
const size_t filename_length = strlen(filename);
if (filename[filename_length - 1] != '/')
{
// Open the current file in the zip archive
result = unzOpenCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot open a current file in the zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip_file = resource(unzf, [](unzFile handle) { unzCloseCurrentFile(handle); });
// Read data from the current file in the zip archive
do
{
uint8_t buffer[16384];
result = unzReadCurrentFile(unzf, buffer, (unsigned)countof(buffer));
if (result > 0)
destination.Write(buffer, (size_t)result);
else if (result < 0)
throwex FileSystemException("Cannot read the current file from the zip archive!").Attach(path);
} while (result != UNZ_EOF);
// Close the current file in the zip archive
result = unzCloseCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the current file in the zip archive!").Attach(path);
unzip_file.release();
}
}
// Close the destination file
destination.Close();
// Close the zip archive
result = unzClose(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the zip archive!").Attach(path);
unzip.release();
return std::move(destination);
}
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
// Deserialize the logging message
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint32_t logger_hash;
std::memcpy(&logger_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& logger = hashmap.find(logger_hash);
record.logger.assign((logger != hashmap.end()) ? logger->second : format("0x{:X}", logger_hash));
// Deserialize the logging message
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, std::string_view message, uint32_t message_hash)
{
if (hashmap.find(message_hash) == hashmap.end())
{
std::cout << format("Discovered logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
hashmap[message_hash] = message;
return true;
}
else if (message != hashmap[message_hash])
{
std::cerr << format("Collision detected!") << std::endl;
std::cerr << format("Previous logging message: \"{}\" with hash = 0x{:08X}", hashmap[message_hash], message_hash) << std::endl;
std::cerr << format("Conflict logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
throwex Exception("Collision detected!");
}
// Skip duplicates
return false;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, Record& record)
{
bool result = false;
// Check the logger name
result |= UpdateHashmap(hashmap, record.logger, HashLayout::Hash(record.logger));
// Check the logging message
result |= UpdateHashmap(hashmap, record.message, HashLayout::Hash(record.message));
return result;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
parser.add_option("-u", "--update").dest("update").help("Update .hashlog");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
Path hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
{
hashlog = Path(options.get("hashlog"));
if (hashlog.IsDirectory())
hashlog = FindHashlog(hashlog);
}
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
Path temp_file;
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input") || options.is_set("update"))
{
Path path(options.is_set("input") ? options.get("input") : options.get("update"));
if (path.IsRegularFile() && (path.extension() == ".zip"))
temp_file = path = UnzipFile(path);
File* file = new File(path);
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
if (options.is_set("update"))
{
bool store = false;
// Update hashmap with data from all logging records
Record record;
while (InputRecord(*input, record))
store |= UpdateHashmap(hashmap, record);
// Store updated .hashlog
if (store)
WriteHashlog(hashlog, hashmap);
}
else
{
// Process all logging records
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
}
// Delete temporary file
if (temp_file)
Path::Remove(temp_file);
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<commit_msg>Fix compilation issues<commit_after>/*!
\file hashlog.cpp
\brief Hash logs reader definition
\author Ivan Shynkarenka
\date 13.12.2021
\copyright MIT License
*/
#include "logging/record.h"
#include "logging/layouts/hash_layout.h"
#include "logging/layouts/text_layout.h"
#include "logging/version.h"
#include "../source/logging/appenders/minizip/unzip.h"
#if defined(_WIN32) || defined(_WIN64)
#include "../source/logging/appenders/minizip/iowin32.h"
#endif
#include "errors/fatal.h"
#include "filesystem/file.h"
#include "system/stream.h"
#include "utility/countof.h"
#include "utility/resource.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppLogging;
Path FindHashlog(const Path& path)
{
// Try to find .hashlog in the current path
Path hashlog = path.IsRegularFile() ? path : (path / ".hashlog");
if (hashlog.IsExists())
return hashlog;
// Try to find .hashlog in the parent path
Path parent = path.parent();
if (parent)
return FindHashlog(parent);
// Cannot find .hashlog file
return Path();
}
std::unordered_map<uint32_t, std::string> ReadHashlog(const Path& path)
{
std::unordered_map<uint32_t, std::string> hashmap;
File hashlog(path);
// Check if .hashlog is exists
if (!hashlog.IsExists())
return hashmap;
// Open .hashlog file
hashlog.Open(true, false);
// Check if .hashlog is opened
if (!hashlog)
return hashmap;
// Read the hash map size
uint32_t size;
if (hashlog.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
hashmap.reserve(size);
// Read the hash map content
while (size-- > 0)
{
uint32_t hash;
if (hashlog.Read(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return hashmap;
uint16_t length;
if (hashlog.Read(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return hashmap;
std::vector<uint8_t> buffer(length);
if (hashlog.Read(buffer.data(), length) != length)
return hashmap;
std::string message(buffer.begin(), buffer.end());
hashmap[hash] = message;
}
// Close .hashlog file
hashlog.Close();
return hashmap;
}
bool WriteHashlog(const Path& path, const std::unordered_map<uint32_t, std::string>& hashmap)
{
File hashlog(path);
// Open or create .hashlog file
hashlog.OpenOrCreate(false, true, true);
// Check if .hashlog is avaliable
if (!hashlog)
return false;
// Write the hash map size
uint32_t size = (uint32_t)hashmap.size();
if (hashlog.Write(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
// Read the hash map content
for (const auto& item : hashmap)
{
uint32_t hash = (uint32_t)item.first;
if (hashlog.Write(&hash, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
uint16_t length = (uint16_t)item.second.size();
if (hashlog.Write(&length, sizeof(uint16_t)) != sizeof(uint16_t))
return false;
auto buffer = item.second.data();
if (hashlog.Write(buffer, length) != length)
return false;
}
// Close .hashlog file
hashlog.Close();
return true;
}
Path UnzipFile(const Path& path)
{
// Open a zip archive
unzFile unzf;
#if defined(_WIN32) || defined(_WIN64)
zlib_filefunc64_def ffunc;
fill_win32_filefunc64W(&ffunc);
unzf = unzOpen2_64(path.wstring().c_str(), &ffunc);
#else
unzf = unzOpen64(path.string().c_str());
#endif
if (unzf == nullptr)
throwex FileSystemException("Cannot open a zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip = resource(unzf, [](unzFile handle) { unzClose(handle); });
File destination(path + ".tmp");
// Open the destination file for writing
destination.Create(false, true);
// Get info about the zip archive
unz_global_info global_info;
int result = unzGetGlobalInfo(unzf, &global_info);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive global info!").Attach(path);
// Loop to extract all files from the zip archive
uLong i;
for (i = 0; i < global_info.number_entry; ++i)
{
unz_file_info file_info;
char filename[1024];
// Get info about the current file in the zip archive
result = unzGetCurrentFileInfo(unzf, &file_info, filename, (unsigned)countof(filename), NULL, 0, NULL, 0);
if (result != UNZ_OK)
throwex FileSystemException("Cannot read a zip archive file info!").Attach(path);
// Check if this entry is a file
const size_t filename_length = strlen(filename);
if (filename[filename_length - 1] != '/')
{
// Open the current file in the zip archive
result = unzOpenCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot open a current file in the zip archive!").Attach(path);
// Smart resource cleaner pattern
auto unzip_file = resource(unzf, [](unzFile handle) { unzCloseCurrentFile(handle); });
// Read data from the current file in the zip archive
do
{
uint8_t buffer[16384];
result = unzReadCurrentFile(unzf, buffer, (unsigned)countof(buffer));
if (result > 0)
destination.Write(buffer, (size_t)result);
else if (result < 0)
throwex FileSystemException("Cannot read the current file from the zip archive!").Attach(path);
} while (result != UNZ_EOF);
// Close the current file in the zip archive
result = unzCloseCurrentFile(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the current file in the zip archive!").Attach(path);
unzip_file.release();
}
}
// Close the destination file
destination.Close();
// Close the zip archive
result = unzClose(unzf);
if (result != UNZ_OK)
throwex FileSystemException("Cannot close the zip archive!").Attach(path);
unzip.release();
return std::move(destination);
}
bool InputRecord(Reader& input, Record& record)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint8_t logger_size;
std::memcpy(&logger_size, buffer, sizeof(uint8_t));
buffer += sizeof(uint8_t);
record.logger.insert(record.logger.begin(), buffer, buffer + logger_size);
buffer += logger_size;
// Deserialize the logging message
uint16_t message_size;
std::memcpy(&message_size, buffer, sizeof(uint16_t));
buffer += sizeof(uint16_t);
record.message.insert(record.message.begin(), buffer, buffer + message_size);
buffer += message_size;
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool InputRecord(Reader& input, Record& record, const std::unordered_map<uint32_t, std::string>& hashmap)
{
// Clear the logging record
record.Clear();
// Read the logging record size
uint32_t size;
if (input.Read(&size, sizeof(uint32_t)) != sizeof(uint32_t))
return false;
record.raw.resize(size);
// Read the logging record raw data
if (input.Read(record.raw.data(), size) != size)
{
std::cerr << "Failed to read from the input source!" << std::endl;
return false;
}
// Get the buffer start position
const uint8_t* buffer = record.raw.data();
// Deserialize logging record
std::memcpy(&record.timestamp, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.thread, buffer, sizeof(uint64_t));
buffer += sizeof(uint64_t);
std::memcpy(&record.level, buffer, sizeof(Level));
buffer += sizeof(Level);
// Deserialize the logger name
uint32_t logger_hash;
std::memcpy(&logger_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& logger = hashmap.find(logger_hash);
record.logger.assign((logger != hashmap.end()) ? logger->second : format("0x{:X}", logger_hash));
// Deserialize the logging message
uint32_t message_hash;
std::memcpy(&message_hash, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
const auto& message = hashmap.find(message_hash);
record.message.assign((message != hashmap.end()) ? message->second : format("0x{:X}", message_hash));
// Deserialize the logging buffer
uint32_t buffer_size;
std::memcpy(&buffer_size, buffer, sizeof(uint32_t));
buffer += sizeof(uint32_t);
record.buffer.insert(record.buffer.begin(), buffer, buffer + buffer_size);
buffer += buffer_size;
// Skip the last zero byte
++buffer;
return true;
}
bool OutputRecord(Writer& output, Record& record)
{
TextLayout layout;
layout.LayoutRecord(record);
size_t size = record.raw.size() - 1;
if (output.Write(record.raw.data(), size) != size)
{
std::cerr << "Failed to write into the output source!" << std::endl;
return false;
}
return true;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, std::string_view message, uint32_t message_hash)
{
if (hashmap.find(message_hash) == hashmap.end())
{
std::cout << fmt::format("Discovered logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
hashmap[message_hash] = message;
return true;
}
else if (message != hashmap[message_hash])
{
std::cerr << fmt::format("Collision detected!") << std::endl;
std::cerr << fmt::format("Previous logging message: \"{}\" with hash = 0x{:08X}", hashmap[message_hash], message_hash) << std::endl;
std::cerr << fmt::format("Conflict logging message: \"{}\" with hash = 0x{:08X}", message, message_hash) << std::endl;
throwex Exception("Collision detected!");
}
// Skip duplicates
return false;
}
bool UpdateHashmap(std::unordered_map<uint32_t, std::string>& hashmap, Record& record)
{
bool result = false;
// Check the logger name
result |= UpdateHashmap(hashmap, record.logger, HashLayout::Hash(record.logger));
// Check the logging message
result |= UpdateHashmap(hashmap, record.message, HashLayout::Hash(record.message));
return result;
}
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version(version);
parser.add_option("-x", "--hashlog").dest("hashlog").help("Hashlog file name");
parser.add_option("-i", "--input").dest("input").help("Input file name");
parser.add_option("-o", "--output").dest("output").help("Output file name");
parser.add_option("-u", "--update").dest("update").help("Update .hashlog");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
try
{
// Open the hashlog file
Path hashlog = FindHashlog(Path::current());
if (options.is_set("hashlog"))
{
hashlog = Path(options.get("hashlog"));
if (hashlog.IsDirectory())
hashlog = FindHashlog(hashlog);
}
// Read .hashlog file and fill the logging messages hash map
std::unordered_map<uint32_t, std::string> hashmap = ReadHashlog(hashlog);
Path temp_file;
// Open the input file or stdin
std::unique_ptr<Reader> input(new StdInput());
if (options.is_set("input") || options.is_set("update"))
{
Path path(options.is_set("input") ? options.get("input") : options.get("update"));
if (path.IsRegularFile() && (path.extension() == ".zip"))
temp_file = path = UnzipFile(path);
File* file = new File(path);
file->Open(true, false);
input.reset(file);
}
// Open the output file or stdout
std::unique_ptr<Writer> output(new StdOutput());
if (options.is_set("output"))
{
File* file = new File(Path(options.get("output")));
file->Open(false, true);
output.reset(file);
}
if (options.is_set("update"))
{
bool store = false;
// Update hashmap with data from all logging records
Record record;
while (InputRecord(*input, record))
store |= UpdateHashmap(hashmap, record);
// Store updated .hashlog
if (store)
WriteHashlog(hashlog, hashmap);
}
else
{
// Process all logging records
Record record;
while (InputRecord(*input, record, hashmap))
if (!OutputRecord(*output, record))
break;
}
// Delete temporary file
if (temp_file)
Path::Remove(temp_file);
return 0;
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return -1;
}
}
<|endoftext|> |
<commit_before><commit_msg>Send and recieve tests added to suite<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>
#include "EvmGdownIIR.h"
#include "Window.h"
using namespace std;
using namespace cv;
static void writeVideo(VideoCapture capture, const Mat& frame);
int main(int argc, char** argv) {
VideoCapture capture("../../vidmagSIGGRAPH2012/face_source_timecode.wmv");
// VideoCapture capture(0);
const double FPS = capture.get(CV_CAP_PROP_FPS);
const int WIDTH = capture.get(CV_CAP_PROP_FRAME_WIDTH);
const int HEIGHT = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
cout << "FPS: " << FPS << endl;
EvmGdownIIR evm;
evm.load("lbpcascade_frontalface.xml");
evm.start(WIDTH, HEIGHT);
Window window(evm);
Mat frame;
while (true) {
capture >> frame;
if (frame.empty()) {
break;
}
window.update(frame);
// writeVideo(capture, frame);
if (waitKey(1) == 27) {
return 0;
}
}
while (waitKey() != 27) {}
return 0;
}
static void writeVideo(VideoCapture& capture, const Mat& frame) {
static VideoWriter writer("out.avi",
CV_FOURCC('X', 'V', 'I', 'D'),
capture.get(CV_CAP_PROP_FPS),
Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),
capture.get(CV_CAP_PROP_FRAME_HEIGHT)));
writer << frame;
}
<commit_msg>writeVideo fix.<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>
#include "EvmGdownIIR.h"
#include "Window.h"
using namespace std;
using namespace cv;
static void writeVideo(VideoCapture& capture, const Mat& frame);
int main(int argc, char** argv) {
VideoCapture capture("../../vidmagSIGGRAPH2012/face_source_timecode.wmv");
// VideoCapture capture(0);
const double FPS = capture.get(CV_CAP_PROP_FPS);
const int WIDTH = capture.get(CV_CAP_PROP_FRAME_WIDTH);
const int HEIGHT = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
cout << "FPS: " << FPS << endl;
EvmGdownIIR evm;
evm.load("lbpcascade_frontalface.xml");
evm.start(WIDTH, HEIGHT);
Window window(evm);
Mat frame;
while (true) {
capture >> frame;
if (frame.empty()) {
break;
}
window.update(frame);
writeVideo(capture, frame);
if (waitKey(1) == 27) {
return 0;
}
}
while (waitKey() != 27) {}
return 0;
}
static void writeVideo(VideoCapture& capture, const Mat& frame) {
static VideoWriter writer("out.avi",
CV_FOURCC('X', 'V', 'I', 'D'),
capture.get(CV_CAP_PROP_FPS),
Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),
capture.get(CV_CAP_PROP_FRAME_HEIGHT)));
writer << frame;
}
<|endoftext|> |
<commit_before>#line 121 "main.nw"
#include <time.h> // for clock_gettime
#include <locale.h> // for setlocale()
#include <stdio.h>
#include <unistd.h> // for isatty()
#include "lua_interpreter.h"
#include "qtdynamic.h"
#include "network.h"
#include "timers.h"
#include "qtlua.h"
#include <assert.h>
#include <iostream>
#include <stdexcept>
#line 5 "main.nw"
extern "C" {
#include <lua5.2/lua.h>
#include <lua5.2/lualib.h>
#include <lua5.2/lauxlib.h>
}
#line 132 "main.nw"
#include <QObject>
#include <QTimer>
#include <QCoreApplication>
#include <QStringList>
namespace {
#line 142 "main.nw"
int app_quit(lua_State *L) {
lua_getglobal(L, "interp");
LuaInterpreter *li = *static_cast<LuaInterpreter**>(lua_touserdata(L, -1));
li->quitCalled = true;
if (lua_isnumber(L, 1)) {
li->retCode = lua_tointegerx(L, 1, NULL);
}
QCoreApplication::exit(li->retCode);
return 0;
}
int timestamp(lua_State *L) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
lua_pushnumber(L, ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
return 1;
}
int arguments(lua_State *L) {
QStringList args = QCoreApplication::instance()->arguments();
lua_createtable(L, args.count(), 0);
int i = 1;
for (auto& arg : args)
{
lua_pushstring(L, arg.toUtf8().constData());
lua_rawseti(L, -2, i++);
}
return 1;
}
} // anonymous namespace
LuaInterpreter::LuaInterpreter(QObject *parent, const QStringList::iterator& args, const QStringList::iterator& args_end)
: QObject(parent) {
lua_state = luaL_newstate();
luaL_requiref(lua_state, "base", &luaopen_base, 1);
luaL_requiref(lua_state, "package", &luaopen_package, 1);
luaL_requiref(lua_state, "network", &luaopen_network, 1);
luaL_requiref(lua_state, "timers", &luaopen_timers, 1);
luaL_requiref(lua_state, "string", &luaopen_string, 1);
luaL_requiref(lua_state, "table", &luaopen_table, 1);
luaL_requiref(lua_state, "debug", &luaopen_debug, 1);
luaL_requiref(lua_state, "math", &luaopen_math, 1);
luaL_requiref(lua_state, "io", &luaopen_io, 1);
luaL_requiref(lua_state, "os", &luaopen_os, 1);
luaL_requiref(lua_state, "bit32", &luaopen_bit32, 1);
luaL_requiref(lua_state, "qt", &luaopen_qt, 1);
#line 192 "main.nw"
// extend package.cpath
lua_getglobal(lua_state, "package");
assert(!lua_isnil(lua_state, -1));
lua_pushstring(lua_state, "./modules/lib?.so;./lib?.so;");
lua_getfield(lua_state, -2, "cpath");
assert(!lua_isnil(lua_state, -1));
lua_concat(lua_state, 2);
lua_setfield(lua_state, -2, "cpath");
lua_pushstring(lua_state, "./modules/?.lua;");
lua_getfield(lua_state, -2, "path");
assert(!lua_isnil(lua_state, -1));
lua_concat(lua_state, 2);
lua_setfield(lua_state, -2, "path");
lua_pushcfunction(lua_state, &app_quit);
lua_setglobal(lua_state, "quit");
lua_pushcfunction(lua_state, ×tamp);
lua_setglobal(lua_state, "timestamp");
lua_pushcfunction(lua_state, &arguments);
lua_setglobal(lua_state, "arguments");
lua_pushboolean(lua_state, !isatty(fileno(stdout)));
lua_setglobal(lua_state, "is_redirected");
// Adding global 'interp'
QObject **p = static_cast<QObject**>(lua_newuserdata(lua_state, sizeof(QObject*)));
*p = this;
lua_setglobal(lua_state, "interp");
// Adding global 'argv'
lua_createtable(lua_state, 0, 0);
int i = 1;
for (auto p = args; p != args_end; ++p) {
lua_pushstring(lua_state, p->toUtf8().constData());
lua_rawseti(lua_state, -2, i++);
}
lua_setglobal(lua_state, "argv");
}
int LuaInterpreter::load(const char *filename) {
int res = luaL_dofile(lua_state, filename);
if (res != 0) {
std::cerr << "Lua error:" << std::endl << lua_tostring(lua_state, -1) << std::endl;
}
return quitCalled ? retCode : res;
}
void LuaInterpreter::quit() {
QCoreApplication::quit();
}
LuaInterpreter::~LuaInterpreter() {
lua_close(lua_state);
}
<commit_msg>Add include path for stdlib<commit_after>#line 121 "main.nw"
#include <time.h> // for clock_gettime
#include <locale.h> // for setlocale()
#include <stdio.h>
#include <unistd.h> // for isatty()
#include "lua_interpreter.h"
#include "qtdynamic.h"
#include "network.h"
#include "timers.h"
#include "qtlua.h"
#include <assert.h>
#include <iostream>
#include <stdexcept>
#line 5 "main.nw"
extern "C" {
#include <lua5.2/lua.h>
#include <lua5.2/lualib.h>
#include <lua5.2/lauxlib.h>
}
#line 132 "main.nw"
#include <QObject>
#include <QTimer>
#include <QCoreApplication>
#include <QStringList>
namespace {
#line 142 "main.nw"
int app_quit(lua_State *L) {
lua_getglobal(L, "interp");
LuaInterpreter *li = *static_cast<LuaInterpreter**>(lua_touserdata(L, -1));
li->quitCalled = true;
if (lua_isnumber(L, 1)) {
li->retCode = lua_tointegerx(L, 1, NULL);
}
QCoreApplication::exit(li->retCode);
return 0;
}
int timestamp(lua_State *L) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
lua_pushnumber(L, ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
return 1;
}
int arguments(lua_State *L) {
QStringList args = QCoreApplication::instance()->arguments();
lua_createtable(L, args.count(), 0);
int i = 1;
for (auto& arg : args)
{
lua_pushstring(L, arg.toUtf8().constData());
lua_rawseti(L, -2, i++);
}
return 1;
}
} // anonymous namespace
LuaInterpreter::LuaInterpreter(QObject *parent, const QStringList::iterator& args, const QStringList::iterator& args_end)
: QObject(parent) {
lua_state = luaL_newstate();
luaL_requiref(lua_state, "base", &luaopen_base, 1);
luaL_requiref(lua_state, "package", &luaopen_package, 1);
luaL_requiref(lua_state, "network", &luaopen_network, 1);
luaL_requiref(lua_state, "timers", &luaopen_timers, 1);
luaL_requiref(lua_state, "string", &luaopen_string, 1);
luaL_requiref(lua_state, "table", &luaopen_table, 1);
luaL_requiref(lua_state, "debug", &luaopen_debug, 1);
luaL_requiref(lua_state, "math", &luaopen_math, 1);
luaL_requiref(lua_state, "io", &luaopen_io, 1);
luaL_requiref(lua_state, "os", &luaopen_os, 1);
luaL_requiref(lua_state, "bit32", &luaopen_bit32, 1);
luaL_requiref(lua_state, "qt", &luaopen_qt, 1);
#line 192 "main.nw"
// extend package.cpath
lua_getglobal(lua_state, "package");
assert(!lua_isnil(lua_state, -1));
lua_pushstring(lua_state, "./modules/lib?.so;./lib?.so;");
lua_getfield(lua_state, -2, "cpath");
assert(!lua_isnil(lua_state, -1));
lua_concat(lua_state, 2);
lua_setfield(lua_state, -2, "cpath");
lua_pushstring(lua_state, "./modules/?.lua;./modules/atf/stdlib/?.lua;");
lua_getfield(lua_state, -2, "path");
assert(!lua_isnil(lua_state, -1));
lua_concat(lua_state, 2);
lua_setfield(lua_state, -2, "path");
lua_pushcfunction(lua_state, &app_quit);
lua_setglobal(lua_state, "quit");
lua_pushcfunction(lua_state, ×tamp);
lua_setglobal(lua_state, "timestamp");
lua_pushcfunction(lua_state, &arguments);
lua_setglobal(lua_state, "arguments");
lua_pushboolean(lua_state, !isatty(fileno(stdout)));
lua_setglobal(lua_state, "is_redirected");
// Adding global 'interp'
QObject **p = static_cast<QObject**>(lua_newuserdata(lua_state, sizeof(QObject*)));
*p = this;
lua_setglobal(lua_state, "interp");
// Adding global 'argv'
lua_createtable(lua_state, 0, 0);
int i = 1;
for (auto p = args; p != args_end; ++p) {
lua_pushstring(lua_state, p->toUtf8().constData());
lua_rawseti(lua_state, -2, i++);
}
lua_setglobal(lua_state, "argv");
}
int LuaInterpreter::load(const char *filename) {
int res = luaL_dofile(lua_state, filename);
if (res != 0) {
std::cerr << "Lua error:" << std::endl << lua_tostring(lua_state, -1) << std::endl;
}
return quitCalled ? retCode : res;
}
void LuaInterpreter::quit() {
QCoreApplication::quit();
}
LuaInterpreter::~LuaInterpreter() {
lua_close(lua_state);
}
<|endoftext|> |
<commit_before>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <string>
#include <stdlib.h>
#define SIZET(a) static_cast<size_t>(a)
namespace {
void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
{
/* check if the mesh changed at all */
if ((PCU_Comm_Peers()!=numMasters) || in.adaptFlag || in.tetrahedronize) {
if (in.parmaPtn && PCU_Comm_Peers() > 1)
ph::balance(in,m);
apf::reorderMdsMesh(m);
}
}
void switchToMasters(int splitFactor)
{
int self = PCU_Comm_Self();
int groupRank = self / splitFactor;
int group = self % splitFactor;
MPI_Comm groupComm;
MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
PCU_Switch_Comm(groupComm);
}
void switchToAll()
{
MPI_Comm prevComm = PCU_Get_Comm();
PCU_Switch_Comm(MPI_COMM_WORLD);
MPI_Comm_free(&prevComm);
PCU_Barrier();
}
void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
ph::readBCs(in.attributeFileName.c_str(), bcs);
if(!g)
g = gmi_load(in.modelFileName.c_str());
}
void originalMain(apf::Mesh2*& m, ph::Input& in,
gmi_model* g, apf::Migration*& plan)
{
if(!m)
m = apf::loadMdsMesh(g, in.meshFileName.c_str());
else
apf::printStats(m);
m->verify();
if (in.solutionMigration)
ph::readAndAttachSolution(in, m);
else
ph::attachZeroSolution(in, m);
if (in.buildMapping)
ph::buildMapping(m);
apf::setMigrationLimit(SIZET(in.elementsPerMigration));
if (in.adaptFlag)
ph::adapt(in, m);
if (in.tetrahedronize)
ph::tetrahedronize(in, m);
plan = ph::split(in, m);
}
}//end namespace
namespace ph {
void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
std::string path = ph::setupOutputDir();
ph::setupOutputSubdir(path);
ph::enterFilteredMatching(m, in, bcs);
ph::generateOutput(in, bcs, m, out);
ph::exitFilteredMatching(m);
// a path is not needed for inmem
ph::detachAndWriteSolution(in,out,m,path); //write restart
ph::writeGeomBC(out, path); //write geombc
ph::writeAuxiliaryFiles(path, in.timeStepNumber);
if ( ! in.outMeshFileName.empty() )
m->writeNative(in.outMeshFileName.c_str());
m->verify();
if (in.adaptFlag)
ph::goToParentDir();
}
void preprocess(apf::Mesh2* m, Input& in, Output& out) {
BCs bcs;
ph::readBCs(in.attributeFileName.c_str(), bcs);
preprocess(m,in,out,bcs);
}
}
namespace chef {
static FILE* openfile_read(ph::Input&, const char* path) {
return fopen(path, "r");
}
static FILE* openfile_write(ph::Output&, const char* path) {
return fopen(path, "w");
}
static FILE* openstream_write(ph::Output& out, const char* path) {
return openGRStreamWrite(out.grs, path);
}
static FILE* openstream_read(ph::Input& in, const char* path) {
std::string fname(path);
std::string restartStr("restart");
FILE* f = NULL;
if( fname.find(restartStr) != std::string::npos )
f = openRStreamRead(in.rs);
else {
fprintf(stderr,
"ERROR %s type of stream %s is unknown... exiting\n",
__func__, fname.c_str());
exit(1);
}
return f;
}
void bake(gmi_model*& g, apf::Mesh2*& m,
ph::Input& in, ph::Output& out) {
apf::Migration* plan = 0;
ph::BCs bcs;
loadCommon(in, bcs, g);
const int worldRank = PCU_Comm_Self();
switchToMasters(in.splitFactor);
const int numMasters = PCU_Comm_Peers();
if ((worldRank % in.splitFactor) == 0)
originalMain(m, in, g, plan);
switchToAll();
if (in.adaptFlag)
ph::goToStepDir(in.timeStepNumber);
m = repeatMdsMesh(m, g, plan, in.splitFactor);
balanceAndReorder(m,in,numMasters);
ph::preprocess(m,in,out,bcs);
}
void cook(gmi_model*& g, apf::Mesh2*& m) {
ph::Input in;
in.load("adapt.inp");
in.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,in,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl) {
ctrl.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,ctrl,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, GRStream* grs) {
ctrl.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openstream_write;
out.grs = grs;
bake(g,m,ctrl,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, RStream* rs) {
ctrl.openfile_read = openstream_read;
ctrl.rs = rs;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,ctrl,out);
return;
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, RStream* rs, GRStream* grs) {
ctrl.openfile_read = openstream_read;
ctrl.rs = rs;
ph::Output out;
out.openfile_write = openstream_write;
out.grs = grs;
bake(g,m,ctrl,out);
return;
}
void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
ph::readAndAttachSolution(ctrl, m);
}
void preprocess(apf::Mesh2*& m, ph::Input& in) {
ph::Output out;
out.openfile_write = chef::openfile_write;
ph::preprocess(m,in,out);
}
void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
ph::Output out;
out.openfile_write = chef::openstream_write;
out.grs = grs;
ph::preprocess(m,in,out);
}
}
<commit_msg>but the bar is open<commit_after>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <string>
#include <stdlib.h>
#define SIZET(a) static_cast<size_t>(a)
namespace {
void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
{
/* check if the mesh changed at all */
if ((PCU_Comm_Peers()!=numMasters) || in.adaptFlag || in.tetrahedronize) {
if (in.parmaPtn && PCU_Comm_Peers() > 1)
ph::balance(in,m);
apf::reorderMdsMesh(m);
}
}
void switchToMasters(int splitFactor)
{
int self = PCU_Comm_Self();
int groupRank = self / splitFactor;
int group = self % splitFactor;
MPI_Comm groupComm;
MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
PCU_Switch_Comm(groupComm);
}
void switchToAll()
{
MPI_Comm prevComm = PCU_Get_Comm();
PCU_Switch_Comm(MPI_COMM_WORLD);
MPI_Comm_free(&prevComm);
PCU_Barrier();
}
void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
ph::readBCs(in.attributeFileName.c_str(), bcs);
if(!g)
g = gmi_load(in.modelFileName.c_str());
}
void originalMain(apf::Mesh2*& m, ph::Input& in,
gmi_model* g, apf::Migration*& plan)
{
if(!m)
m = apf::loadMdsMesh(g, in.meshFileName.c_str());
else
apf::printStats(m);
m->verify();
if (in.solutionMigration)
ph::readAndAttachSolution(in, m);
else
ph::attachZeroSolution(in, m);
if (in.buildMapping)
ph::buildMapping(m);
apf::setMigrationLimit(SIZET(in.elementsPerMigration));
if (in.adaptFlag)
ph::adapt(in, m);
if (in.tetrahedronize)
ph::tetrahedronize(in, m);
plan = ph::split(in, m);
}
}//end namespace
namespace ph {
void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
if (in.adaptFlag)
ph::goToStepDir(in.timeStepNumber);
std::string path = ph::setupOutputDir();
ph::setupOutputSubdir(path);
ph::enterFilteredMatching(m, in, bcs);
ph::generateOutput(in, bcs, m, out);
ph::exitFilteredMatching(m);
// a path is not needed for inmem
ph::detachAndWriteSolution(in,out,m,path); //write restart
ph::writeGeomBC(out, path); //write geombc
ph::writeAuxiliaryFiles(path, in.timeStepNumber);
if ( ! in.outMeshFileName.empty() )
m->writeNative(in.outMeshFileName.c_str());
m->verify();
if (in.adaptFlag)
ph::goToParentDir();
}
void preprocess(apf::Mesh2* m, Input& in, Output& out) {
BCs bcs;
ph::readBCs(in.attributeFileName.c_str(), bcs);
preprocess(m,in,out,bcs);
}
}
namespace chef {
static FILE* openfile_read(ph::Input&, const char* path) {
return fopen(path, "r");
}
static FILE* openfile_write(ph::Output&, const char* path) {
return fopen(path, "w");
}
static FILE* openstream_write(ph::Output& out, const char* path) {
return openGRStreamWrite(out.grs, path);
}
static FILE* openstream_read(ph::Input& in, const char* path) {
std::string fname(path);
std::string restartStr("restart");
FILE* f = NULL;
if( fname.find(restartStr) != std::string::npos )
f = openRStreamRead(in.rs);
else {
fprintf(stderr,
"ERROR %s type of stream %s is unknown... exiting\n",
__func__, fname.c_str());
exit(1);
}
return f;
}
void bake(gmi_model*& g, apf::Mesh2*& m,
ph::Input& in, ph::Output& out) {
apf::Migration* plan = 0;
ph::BCs bcs;
loadCommon(in, bcs, g);
const int worldRank = PCU_Comm_Self();
switchToMasters(in.splitFactor);
const int numMasters = PCU_Comm_Peers();
if ((worldRank % in.splitFactor) == 0)
originalMain(m, in, g, plan);
switchToAll();
m = repeatMdsMesh(m, g, plan, in.splitFactor);
balanceAndReorder(m,in,numMasters);
ph::preprocess(m,in,out,bcs);
}
void cook(gmi_model*& g, apf::Mesh2*& m) {
ph::Input in;
in.load("adapt.inp");
in.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,in,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl) {
ctrl.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,ctrl,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, GRStream* grs) {
ctrl.openfile_read = openfile_read;
ph::Output out;
out.openfile_write = openstream_write;
out.grs = grs;
bake(g,m,ctrl,out);
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, RStream* rs) {
ctrl.openfile_read = openstream_read;
ctrl.rs = rs;
ph::Output out;
out.openfile_write = openfile_write;
bake(g,m,ctrl,out);
return;
}
void cook(gmi_model*& g, apf::Mesh2*& m,
ph::Input& ctrl, RStream* rs, GRStream* grs) {
ctrl.openfile_read = openstream_read;
ctrl.rs = rs;
ph::Output out;
out.openfile_write = openstream_write;
out.grs = grs;
bake(g,m,ctrl,out);
return;
}
void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
ph::readAndAttachSolution(ctrl, m);
}
void preprocess(apf::Mesh2*& m, ph::Input& in) {
ph::Output out;
out.openfile_write = chef::openfile_write;
ph::preprocess(m,in,out);
}
void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
ph::Output out;
out.openfile_write = chef::openstream_write;
out.grs = grs;
ph::preprocess(m,in,out);
}
}
<|endoftext|> |
<commit_before>#include "serial.h"
#include "metrics.h"
#include "crc.h"
#include "settings.h"
#include "../teensy_rc_control/Packets.h"
#include <unistd.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <assert.h>
#include <sys/select.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <linux/input.h>
#include <linux/hidraw.h>
float gSteerScale = 1.0f;
float gThrottleScale = 0.4f;
float gThrottleMin = 0.06f;
float gSteer = 0.0f;
float gThrottle = 0.0f;
static HostControl hostControl;
static int hidport = -1;
static pthread_t hidthread;
static bool hidRunning;
static uint64_t lastHidSendTime;
static uint8_t my_frame_id = 0;
static uint8_t peer_frameid = 0;
/* microseconds */
#define HID_SEND_INTERVAL 11111
static char const *charstr(int i, char *str) {
if (i >= 32 && i < 127) {
str[0] = i;
str[1] = 0;
return str;
}
str[0] = '.';
str[1] = 0;
return str;
}
static uint16_t map_rc(float f) {
return (f < -1.0f) ? 1000 : (f > 1.0f) ? 2000 : (uint16_t)(1500 + f * 500);
}
static float clamp(float val, float from, float to) {
if (val < from) return from;
if (val > to) return to;
return val;
}
void serial_steer(float steer, float throttle) {
gSteer = clamp(steer * gSteerScale, -1.0f, 1.0f);
gThrottle = gThrottleMin + clamp(throttle * gThrottleScale, 0, 1.0f);
}
static void hexdump(void const *vp, int end) {
unsigned char const *p = (unsigned char const *)vp;
int offset = 0;
char s[10];
while (offset < end) {
fprintf(stderr, "%04x: ", offset);
for (int i = 0; i != 16; ++i) {
if (i+offset < end) {
fprintf(stderr, " %02x", p[i+offset]);
} else {
fprintf(stderr, " ");
}
}
fprintf(stderr, " ");
for (int i = 0; i != 16; ++i) {
if (i+offset < end) {
fprintf(stderr, "%s", charstr(p[i+offset], s));
} else {
fprintf(stderr, " ");
}
}
fprintf(stderr, "\n");
offset += 16;
}
}
template<typename T> struct IncomingPacket {
T data;
bool fresh;
uint64_t when;
};
static IncomingPacket<TrimInfo> g_TrimInfo;
static IncomingPacket<IBusPacket> g_IBusPacket;
static IncomingPacket<SteerControl> g_SteerControl;
TrimInfo const *serial_trim_info(uint64_t *oTime, bool *oFresh) {
*oFresh = g_TrimInfo.fresh;
if (g_TrimInfo.fresh) g_TrimInfo.fresh = false;
*oTime = g_TrimInfo.when;
return &g_TrimInfo.data;
}
IBusPacket const *serial_ibus_packet(uint64_t *oTime, bool *oFresh) {
*oFresh = g_IBusPacket.fresh;
if (g_IBusPacket.fresh) g_IBusPacket.fresh = false;
*oTime = g_IBusPacket.when;
return &g_IBusPacket.data;
}
SteerControl const *serial_steer_control(uint64_t *oTime, bool *oFresh) {
*oFresh = g_SteerControl.fresh;
if (g_SteerControl.fresh) g_SteerControl.fresh = false;
*oTime = g_SteerControl.when;
return &g_SteerControl.data;
}
#define RECVPACKET(type) \
case type::PacketCode: \
if (!unpack(g_##type, sizeof(type), ++buf, end)) { \
fprintf(stderr, "Packet too short for %s: %ld\n", #type, (long)(end-buf)); \
hexdump(buf, end-buf); \
Serial_UnknownMessage.set(); \
return; \
} \
break;
template<typename T> bool unpack(IncomingPacket<T> &dst, size_t dsz, unsigned char const *&src, unsigned char const *end) {
if (end-src < (long)dsz) {
return false;
}
memcpy(&dst.data, src, dsz);
src += dsz;
dst.fresh = true;
dst.when = metric::Collector::clock();
return true;
}
// buf points at frameid
static void handle_packet(unsigned char const *buf, unsigned char const *end) {
// framing skips initial 55 aa
assert(end - buf >= 5);
uint16_t crc = crc_kermit(buf+2, end-buf-4);
if (((crc & 0xff) != end[-2]) || (((crc >> 8) & 0xff) != end[-1])) {
Serial_CrcErrors.increment();
fprintf(stderr, "serial CRC got %x calculated %x\n", end[-2] | (end[-1] << 8), crc);
return;
}
peer_frameid = buf[0];
// ignore lastseen for now
// ignore length; already handled by caller
buf += 3; // skip preamble
end -= 2; // skip CRC
while (buf != end) {
// decode a packet
switch (*buf) {
RECVPACKET(TrimInfo);
RECVPACKET(IBusPacket);
RECVPACKET(SteerControl);
default:
fprintf(stderr, "serial unknown message ID 0x%02x; flushing to end of packet\n", *buf);
hexdump(buf, end-buf);
Serial_UnknownMessage.set();
return;
}
Serial_PacketsDecoded.increment();
}
}
/* 0x55 0xAA <frameid> <lastseen> <length> <payload> <CRC16-L> <CRC16-H>
* CRC16 is CRC16 of <length> and <payload>.
*/
static void parse_buffer(unsigned char *buf, int &bufptr) {
if (bufptr < 7) {
fprintf(stderr, "short buffer: %d bytes\n", bufptr);
return; // can't be anything
}
if (buf[0] == 0x55 && buf[1] == 0xAA) {
// header
if (buf[4] > 64-7) {
// must flush this packet
goto clear_to_i;
}
if (buf[4] + 7 > bufptr) {
// don't yet have all the data
goto clear_to_i;
}
/* why 7 ?
* 55, aa, frameid, last seen, length, ..., crc, crc
*/
handle_packet(buf + 2, buf + 7 + buf[4]);
return; // success
}
clear_to_i:
fprintf(stderr, "bufptr %d failure\n", bufptr);
return; // failure
}
static bool send_outgoing_packet() {
++my_frame_id;
if (!my_frame_id) {
my_frame_id = 1;
}
unsigned char pack[64] = { 0x55, 0xAA, my_frame_id, peer_frameid, 0 };
int dlen = 0, dmaxlen = 64-7;
(void)&dmaxlen,(void)&dlen;
// pack in some stuff
hostControl.steer = map_rc(gSteer);
hostControl.throttle = map_rc(gThrottle);
pack[5] = HostControl::PacketCode;
memcpy(&pack[6], &hostControl, sizeof(hostControl));
dlen += 1 + sizeof(hostControl);
pack[4] = (unsigned char)(dlen & 0xff);
uint16_t crc = crc_kermit(&pack[4], dlen+1);
pack[5+dlen] = (unsigned char)(crc & 0xff);
pack[6+dlen] = (unsigned char)((crc >> 8) & 0xff);
int wr = ::write(hidport, pack, dlen+7);
if (wr != dlen+7) {
if (wr < 0) {
perror("serial write");
} else {
fprintf(stderr, "serial short write: %d instead of %d\n", wr, dlen+7);
}
return false;
}
Serial_BytesSent.increment(wr);
return true;
}
static void *ser_fn(void *) {
int bufptr = 0;
unsigned char inbuf[64] = { 0 };
int nerror = 0;
puts("start hid thread");
bool shouldsleep = false;
while (hidRunning) {
if (bufptr == 256) {
bufptr = 0; // flush
}
uint64_t now = metric::Collector::clock();
int n = 0;
if (shouldsleep) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(hidport, &fds);
struct timeval tv = { 0, 0 };
tv.tv_usec = HID_SEND_INTERVAL - (now - lastHidSendTime);
if (tv.tv_usec < 1) {
tv.tv_usec = 1;
}
if (tv.tv_usec > 20000) {
tv.tv_usec = 20000;
}
n = select(hidport+1, &fds, NULL, NULL, &tv);
now = metric::Collector::clock();
}
if (n >= 0) {
if (now - lastHidSendTime >= HID_SEND_INTERVAL) {
// quantize to the send interval
lastHidSendTime = now - (now % HID_SEND_INTERVAL);
// do send
if (!send_outgoing_packet()) {
fprintf(stderr, "\nsend error");
Serial_Error.set();
++nerror;
if (nerror >= 10) {
break;
}
}
}
int r = read(hidport, inbuf, sizeof(inbuf));
if (r < 0) {
shouldsleep = true;
if (errno != EAGAIN) {
if (hidRunning) {
Serial_Error.set();
perror("serial");
++nerror;
if (nerror >= 10) {
break;
}
}
}
} else {
shouldsleep = false;
if (r > 0) {
Serial_BytesReceived.increment(r);
if (nerror) {
--nerror;
}
bufptr += r;
}
if (bufptr > 0) {
// parse and perhaps remove data
parse_buffer(inbuf, bufptr);
bufptr = 0;
}
}
} else {
perror("select");
++nerror;
if (nerror >= 10) {
break;
}
}
}
puts("end hidthread");
return 0;
}
#define TEENSY_VENDOR 0x16c0
#define TEENSY_PRODUCT 0x0486
#define TEENSY_RAWHID_ENDPOINT_DESC_SIZE 28
static int verify_open(char const *name) {
int fd;
int sz[2] = { 0 };
hidraw_devinfo hrdi = { 0 };
fd = open(name, O_RDWR | O_NONBLOCK);
if (fd < 0) {
return -1;
}
if (ioctl(fd, HIDIOCGRAWINFO, &hrdi) < 0) {
goto bad_fd;
}
if (hrdi.vendor != TEENSY_VENDOR || hrdi.product != TEENSY_PRODUCT) {
goto bad_fd;
}
if (ioctl(fd, HIDIOCGRDESCSIZE, sz) < 0) {
goto bad_fd;
}
// A magical size found by examination
if (sz[0] != TEENSY_RAWHID_ENDPOINT_DESC_SIZE) {
goto bad_fd;
}
fprintf(stderr, "serial/hidraw open %s returns fd %d\n", name, fd);
// I know this is the right fd, because if I write "reset!" to it,
// the Teensy resets, like it should.
return fd;
bad_fd:
if (fd >= 0) {
fprintf(stderr, "device %s is not the HID I want\n", name);
close(fd);
}
return -1;
}
bool open_hidport(char const *port) {
hidport = verify_open(port);
if (hidport < 0) {
// If the specified port doesn't work, then
// try all raw hid devices, looking for ours.
for (int i = 0; i != 99; ++i) {
char buf[30];
sprintf(buf, "/dev/hidraw%d", i);
hidport = verify_open(buf);
if (hidport >= 0) {
break;
}
}
if (hidport < 0) {
fprintf(stderr, "%s is not a recognized hidraw device, and couldn't find one through scanning.\n", port);
return false;
}
}
return true;
}
bool start_serial(char const *port, int speed) {
if (hidthread) {
return false;
}
if (hidport != -1) {
return false;
}
gSteerScale = get_setting_float("steer_scale", gSteerScale);
gThrottleScale = get_setting_float("throttle_scale", gThrottleScale);
gThrottleMin = get_setting_float("throttle_min", gThrottleMin);
open_hidport(port);
if (hidport < 0) {
return false;
}
hidRunning = true;
if (pthread_create(&hidthread, NULL, ser_fn, NULL) < 0) {
close(hidport);
hidport = -1;
hidRunning = false;
return false;
}
return true;
}
void stop_serial() {
if (hidthread) {
hidRunning = false;
close(hidport);
void *x = 0;
pthread_join(hidthread, &x);
hidport = -1;
hidthread = 0;
}
}
void serial_reset() {
if (hidport < 0) {
open_hidport("/dev/foo");
}
if (hidport < 0) {
fprintf(stderr, "serial_reset(): could not open HID port\n");
return;
}
int wr = ::write(hidport, "reset!", 6);
if (wr != 6) {
perror("serial_reset()");
}
close(hidport);
hidport = -1;
}
<commit_msg>param for tweaking steering<commit_after>#include "serial.h"
#include "metrics.h"
#include "crc.h"
#include "settings.h"
#include "../teensy_rc_control/Packets.h"
#include <unistd.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <assert.h>
#include <sys/select.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <linux/input.h>
#include <linux/hidraw.h>
float gSteerScale = 1.0f;
float gThrottleScale = 0.4f;
float gThrottleMin = 0.06f;
float gSteer = 0.0f;
float gThrottle = 0.0f;
float gTweakSteer = 0.0;
static HostControl hostControl;
static int hidport = -1;
static pthread_t hidthread;
static bool hidRunning;
static uint64_t lastHidSendTime;
static uint8_t my_frame_id = 0;
static uint8_t peer_frameid = 0;
/* microseconds */
#define HID_SEND_INTERVAL 11111
static char const *charstr(int i, char *str) {
if (i >= 32 && i < 127) {
str[0] = i;
str[1] = 0;
return str;
}
str[0] = '.';
str[1] = 0;
return str;
}
static uint16_t map_rc(float f) {
return (f < -1.0f) ? 1000 : (f > 1.0f) ? 2000 : (uint16_t)(1500 + f * 500);
}
static float clamp(float val, float from, float to) {
if (val < from) return from;
if (val > to) return to;
return val;
}
void serial_steer(float steer, float throttle) {
gSteer = clamp(steer * gSteerScale, -1.0f, 1.0f);
gThrottle = gThrottleMin + clamp(throttle * gThrottleScale, 0, 1.0f);
}
static void hexdump(void const *vp, int end) {
unsigned char const *p = (unsigned char const *)vp;
int offset = 0;
char s[10];
while (offset < end) {
fprintf(stderr, "%04x: ", offset);
for (int i = 0; i != 16; ++i) {
if (i+offset < end) {
fprintf(stderr, " %02x", p[i+offset]);
} else {
fprintf(stderr, " ");
}
}
fprintf(stderr, " ");
for (int i = 0; i != 16; ++i) {
if (i+offset < end) {
fprintf(stderr, "%s", charstr(p[i+offset], s));
} else {
fprintf(stderr, " ");
}
}
fprintf(stderr, "\n");
offset += 16;
}
}
template<typename T> struct IncomingPacket {
T data;
bool fresh;
uint64_t when;
};
static IncomingPacket<TrimInfo> g_TrimInfo;
static IncomingPacket<IBusPacket> g_IBusPacket;
static IncomingPacket<SteerControl> g_SteerControl;
TrimInfo const *serial_trim_info(uint64_t *oTime, bool *oFresh) {
*oFresh = g_TrimInfo.fresh;
if (g_TrimInfo.fresh) g_TrimInfo.fresh = false;
*oTime = g_TrimInfo.when;
return &g_TrimInfo.data;
}
IBusPacket const *serial_ibus_packet(uint64_t *oTime, bool *oFresh) {
*oFresh = g_IBusPacket.fresh;
if (g_IBusPacket.fresh) g_IBusPacket.fresh = false;
*oTime = g_IBusPacket.when;
return &g_IBusPacket.data;
}
SteerControl const *serial_steer_control(uint64_t *oTime, bool *oFresh) {
*oFresh = g_SteerControl.fresh;
if (g_SteerControl.fresh) g_SteerControl.fresh = false;
*oTime = g_SteerControl.when;
return &g_SteerControl.data;
}
#define RECVPACKET(type) \
case type::PacketCode: \
if (!unpack(g_##type, sizeof(type), ++buf, end)) { \
fprintf(stderr, "Packet too short for %s: %ld\n", #type, (long)(end-buf)); \
hexdump(buf, end-buf); \
Serial_UnknownMessage.set(); \
return; \
} \
break;
template<typename T> bool unpack(IncomingPacket<T> &dst, size_t dsz, unsigned char const *&src, unsigned char const *end) {
if (end-src < (long)dsz) {
return false;
}
memcpy(&dst.data, src, dsz);
src += dsz;
dst.fresh = true;
dst.when = metric::Collector::clock();
return true;
}
// buf points at frameid
static void handle_packet(unsigned char const *buf, unsigned char const *end) {
// framing skips initial 55 aa
assert(end - buf >= 5);
uint16_t crc = crc_kermit(buf+2, end-buf-4);
if (((crc & 0xff) != end[-2]) || (((crc >> 8) & 0xff) != end[-1])) {
Serial_CrcErrors.increment();
fprintf(stderr, "serial CRC got %x calculated %x\n", end[-2] | (end[-1] << 8), crc);
return;
}
peer_frameid = buf[0];
// ignore lastseen for now
// ignore length; already handled by caller
buf += 3; // skip preamble
end -= 2; // skip CRC
while (buf != end) {
// decode a packet
switch (*buf) {
RECVPACKET(TrimInfo);
RECVPACKET(IBusPacket);
RECVPACKET(SteerControl);
default:
fprintf(stderr, "serial unknown message ID 0x%02x; flushing to end of packet\n", *buf);
hexdump(buf, end-buf);
Serial_UnknownMessage.set();
return;
}
Serial_PacketsDecoded.increment();
}
}
/* 0x55 0xAA <frameid> <lastseen> <length> <payload> <CRC16-L> <CRC16-H>
* CRC16 is CRC16 of <length> and <payload>.
*/
static void parse_buffer(unsigned char *buf, int &bufptr) {
if (bufptr < 7) {
fprintf(stderr, "short buffer: %d bytes\n", bufptr);
return; // can't be anything
}
if (buf[0] == 0x55 && buf[1] == 0xAA) {
// header
if (buf[4] > 64-7) {
// must flush this packet
goto clear_to_i;
}
if (buf[4] + 7 > bufptr) {
// don't yet have all the data
goto clear_to_i;
}
/* why 7 ?
* 55, aa, frameid, last seen, length, ..., crc, crc
*/
handle_packet(buf + 2, buf + 7 + buf[4]);
return; // success
}
clear_to_i:
fprintf(stderr, "bufptr %d failure\n", bufptr);
return; // failure
}
static bool send_outgoing_packet() {
++my_frame_id;
if (!my_frame_id) {
my_frame_id = 1;
}
unsigned char pack[64] = { 0x55, 0xAA, my_frame_id, peer_frameid, 0 };
int dlen = 0, dmaxlen = 64-7;
(void)&dmaxlen,(void)&dlen;
// pack in some stuff
hostControl.steer = map_rc(gSteer + gTweakSteer);
hostControl.throttle = map_rc(gThrottle);
pack[5] = HostControl::PacketCode;
memcpy(&pack[6], &hostControl, sizeof(hostControl));
dlen += 1 + sizeof(hostControl);
pack[4] = (unsigned char)(dlen & 0xff);
uint16_t crc = crc_kermit(&pack[4], dlen+1);
pack[5+dlen] = (unsigned char)(crc & 0xff);
pack[6+dlen] = (unsigned char)((crc >> 8) & 0xff);
int wr = ::write(hidport, pack, dlen+7);
if (wr != dlen+7) {
if (wr < 0) {
perror("serial write");
} else {
fprintf(stderr, "serial short write: %d instead of %d\n", wr, dlen+7);
}
return false;
}
Serial_BytesSent.increment(wr);
return true;
}
static void *ser_fn(void *) {
int bufptr = 0;
unsigned char inbuf[64] = { 0 };
int nerror = 0;
puts("start hid thread");
bool shouldsleep = false;
while (hidRunning) {
if (bufptr == 256) {
bufptr = 0; // flush
}
uint64_t now = metric::Collector::clock();
int n = 0;
if (shouldsleep) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(hidport, &fds);
struct timeval tv = { 0, 0 };
tv.tv_usec = HID_SEND_INTERVAL - (now - lastHidSendTime);
if (tv.tv_usec < 1) {
tv.tv_usec = 1;
}
if (tv.tv_usec > 20000) {
tv.tv_usec = 20000;
}
n = select(hidport+1, &fds, NULL, NULL, &tv);
now = metric::Collector::clock();
}
if (n >= 0) {
if (now - lastHidSendTime >= HID_SEND_INTERVAL) {
// quantize to the send interval
lastHidSendTime = now - (now % HID_SEND_INTERVAL);
// do send
if (!send_outgoing_packet()) {
fprintf(stderr, "\nsend error");
Serial_Error.set();
++nerror;
if (nerror >= 10) {
break;
}
}
}
int r = read(hidport, inbuf, sizeof(inbuf));
if (r < 0) {
shouldsleep = true;
if (errno != EAGAIN) {
if (hidRunning) {
Serial_Error.set();
perror("serial");
++nerror;
if (nerror >= 10) {
break;
}
}
}
} else {
shouldsleep = false;
if (r > 0) {
Serial_BytesReceived.increment(r);
if (nerror) {
--nerror;
}
bufptr += r;
}
if (bufptr > 0) {
// parse and perhaps remove data
parse_buffer(inbuf, bufptr);
bufptr = 0;
}
}
} else {
perror("select");
++nerror;
if (nerror >= 10) {
break;
}
}
}
puts("end hidthread");
return 0;
}
#define TEENSY_VENDOR 0x16c0
#define TEENSY_PRODUCT 0x0486
#define TEENSY_RAWHID_ENDPOINT_DESC_SIZE 28
static int verify_open(char const *name) {
int fd;
int sz[2] = { 0 };
hidraw_devinfo hrdi = { 0 };
fd = open(name, O_RDWR | O_NONBLOCK);
if (fd < 0) {
return -1;
}
if (ioctl(fd, HIDIOCGRAWINFO, &hrdi) < 0) {
goto bad_fd;
}
if (hrdi.vendor != TEENSY_VENDOR || hrdi.product != TEENSY_PRODUCT) {
goto bad_fd;
}
if (ioctl(fd, HIDIOCGRDESCSIZE, sz) < 0) {
goto bad_fd;
}
// A magical size found by examination
if (sz[0] != TEENSY_RAWHID_ENDPOINT_DESC_SIZE) {
goto bad_fd;
}
fprintf(stderr, "serial/hidraw open %s returns fd %d\n", name, fd);
// I know this is the right fd, because if I write "reset!" to it,
// the Teensy resets, like it should.
return fd;
bad_fd:
if (fd >= 0) {
fprintf(stderr, "device %s is not the HID I want\n", name);
close(fd);
}
return -1;
}
bool open_hidport(char const *port) {
hidport = verify_open(port);
if (hidport < 0) {
// If the specified port doesn't work, then
// try all raw hid devices, looking for ours.
for (int i = 0; i != 99; ++i) {
char buf[30];
sprintf(buf, "/dev/hidraw%d", i);
hidport = verify_open(buf);
if (hidport >= 0) {
break;
}
}
if (hidport < 0) {
fprintf(stderr, "%s is not a recognized hidraw device, and couldn't find one through scanning.\n", port);
return false;
}
}
return true;
}
bool start_serial(char const *port, int speed) {
if (hidthread) {
return false;
}
if (hidport != -1) {
return false;
}
gTweakSteer = get_setting_float("steer_tweak", gTweakSteer);
gSteerScale = get_setting_float("steer_scale", gSteerScale);
gThrottleScale = get_setting_float("throttle_scale", gThrottleScale);
gThrottleMin = get_setting_float("throttle_min", gThrottleMin);
open_hidport(port);
if (hidport < 0) {
return false;
}
hidRunning = true;
if (pthread_create(&hidthread, NULL, ser_fn, NULL) < 0) {
close(hidport);
hidport = -1;
hidRunning = false;
return false;
}
return true;
}
void stop_serial() {
if (hidthread) {
hidRunning = false;
close(hidport);
void *x = 0;
pthread_join(hidthread, &x);
hidport = -1;
hidthread = 0;
}
}
void serial_reset() {
if (hidport < 0) {
open_hidport("/dev/foo");
}
if (hidport < 0) {
fprintf(stderr, "serial_reset(): could not open HID port\n");
return;
}
int wr = ::write(hidport, "reset!", 6);
if (wr != 6) {
perror("serial_reset()");
}
close(hidport);
hidport = -1;
}
<|endoftext|> |
<commit_before>
<commit_msg>Update ako.cpp<commit_after>
#include <iostream>
#using namespace std;
int main () {
}
<|endoftext|> |
<commit_before>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "document_field_extractor.h"
#include <vespa/document/datatype/arraydatatype.h>
#include <vespa/document/fieldvalue/arrayfieldvalue.h>
#include <vespa/document/fieldvalue/bytefieldvalue.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/fieldvalue/doublefieldvalue.h>
#include <vespa/document/fieldvalue/floatfieldvalue.h>
#include <vespa/document/fieldvalue/intfieldvalue.h>
#include <vespa/document/fieldvalue/longfieldvalue.h>
#include <vespa/document/fieldvalue/shortfieldvalue.h>
#include <vespa/document/fieldvalue/stringfieldvalue.h>
#include <vespa/document/fieldvalue/mapfieldvalue.h>
#include <vespa/searchcommon/common/undefinedvalues.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/util/exceptions.h>
using document::FieldValue;
using document::ByteFieldValue;
using document::ShortFieldValue;
using document::IntFieldValue;
using document::LongFieldValue;
using document::FloatFieldValue;
using document::DoubleFieldValue;
using document::StringFieldValue;
using document::StructFieldValue;
using document::MapFieldValue;
using document::DataType;
using document::ArrayDataType;
using document::ArrayFieldValue;
using document::Document;
using document::FieldPath;
using document::FieldPathEntry;
using document::FieldValueVisitor;
using vespalib::IllegalStateException;
using vespalib::make_string;
using search::attribute::getUndefined;
namespace proton {
namespace {
class SetUndefinedValueVisitor : public FieldValueVisitor
{
void visit(document::AnnotationReferenceFieldValue &) override { }
void visit(ArrayFieldValue &) override { }
void visit(ByteFieldValue &value) override { value = getUndefined<int8_t>(); }
void visit(Document &) override { }
void visit(DoubleFieldValue &value) override { value = getUndefined<double>(); }
void visit(FloatFieldValue &value) override { value = getUndefined<float>(); }
void visit(IntFieldValue &value) override { value = getUndefined<int32_t>(); }
void visit(LongFieldValue &value) override { value = getUndefined<int64_t>(); }
void visit(MapFieldValue &) override { }
void visit(document::PredicateFieldValue &) override { }
void visit(document::RawFieldValue &) override { }
void visit(ShortFieldValue &value) override { value = getUndefined<int16_t>(); }
void visit(StringFieldValue &) override { }
void visit(StructFieldValue &) override { }
void visit(document::WeightedSetFieldValue &) override { }
void visit(document::TensorFieldValue &) override { }
void visit(document::ReferenceFieldValue &) override { }
};
SetUndefinedValueVisitor setUndefinedValueVisitor;
const ArrayDataType arrayTypeByte(*DataType::BYTE);
const ArrayDataType arrayTypeShort(*DataType::SHORT);
const ArrayDataType arrayTypeInt(*DataType::INT);
const ArrayDataType arrayTypeLong(*DataType::LONG);
const ArrayDataType arrayTypeFloat(*DataType::FLOAT);
const ArrayDataType arrayTypeDouble(*DataType::DOUBLE);
const ArrayDataType arrayTypeString(*DataType::STRING);
const DataType *
getArrayType(const DataType &fieldType)
{
switch (fieldType.getId()) {
case DataType::Type::T_BYTE:
return &arrayTypeByte;
case DataType::Type::T_SHORT:
return &arrayTypeShort;
case DataType::Type::T_INT:
return &arrayTypeInt;
case DataType::Type::T_LONG:
return &arrayTypeLong;
case DataType::Type::T_FLOAT:
return &arrayTypeFloat;
case DataType::Type::T_DOUBLE:
return &arrayTypeDouble;
case DataType::Type::T_STRING:
return &arrayTypeString;
default:
return nullptr;
}
}
std::unique_ptr<ArrayFieldValue>
makeArray(const FieldPathEntry &fieldPathEntry, size_t size)
{
const auto arrayType = getArrayType(fieldPathEntry.getDataType());
auto array = std::make_unique<ArrayFieldValue>(*arrayType);
array->resize(size);
return array;
}
bool
checkInherits(const FieldValue &fieldValue, unsigned id)
{
const vespalib::Identifiable::RuntimeClass &rc = fieldValue.getClass();
return rc.inherits(id);
}
}
DocumentFieldExtractor::DocumentFieldExtractor(const Document &doc)
: _doc(doc),
_cachedFieldValues()
{
}
DocumentFieldExtractor::~DocumentFieldExtractor() = default;
bool
DocumentFieldExtractor::isSupported(const FieldPath &fieldPath)
{
if (!fieldPath.empty() &&
fieldPath[0].getType() != FieldPathEntry::Type::STRUCT_FIELD) {
return false;
}
if (fieldPath.size() == 2) {
if (fieldPath[1].getType() != FieldPathEntry::Type::STRUCT_FIELD &&
fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_KEYS &&
fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_VALUES) {
return false;
}
} else if (fieldPath.size() == 3) {
if (fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_VALUES ||
fieldPath[2].getType() != FieldPathEntry::Type::STRUCT_FIELD) {
return false;
}
} else if (fieldPath.size() > 3) {
return false;
}
return true;
}
const FieldValue *
DocumentFieldExtractor::getCachedFieldValue(const FieldPathEntry &fieldPathEntry)
{
auto itr = _cachedFieldValues.find(fieldPathEntry.getName());
if (itr != _cachedFieldValues.end()) {
return itr->second.get();
} else {
auto insres = _cachedFieldValues.insert(std::make_pair(fieldPathEntry.getName(), _doc.getValue(fieldPathEntry.getFieldRef())));
assert(insres.second);
return insres.first->second.get();
}
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getSimpleFieldValue(const FieldPath &fieldPath)
{
return _doc.getNestedFieldValue(fieldPath.getFullRange());
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getStructArrayFieldValue(const FieldPath &fieldPath)
{
const auto outerFieldValue = getCachedFieldValue(fieldPath[0]);
if (outerFieldValue != nullptr && checkInherits(*outerFieldValue, ArrayFieldValue::classId)) {
const auto outerArray = static_cast<const ArrayFieldValue *>(outerFieldValue);
const auto &innerFieldPathEntry = fieldPath[1];
auto array = makeArray(innerFieldPathEntry, outerArray->size());
uint32_t arrayIndex = 0;
for (const auto &outerElemBase : *outerArray) {
auto &arrayElem = (*array)[arrayIndex++];
const auto &structElem = static_cast<const StructFieldValue &>(outerElemBase);
if (!structElem.getValue(innerFieldPathEntry.getFieldRef(), arrayElem)) {
arrayElem.accept(setUndefinedValueVisitor);
}
}
return array;
}
return std::unique_ptr<FieldValue>();
}
namespace {
template <typename ExtractorFunc>
std::unique_ptr<FieldValue>
getMapFieldValue(const FieldValue *outerFieldValue, const FieldPathEntry &innerEntry, ExtractorFunc &&extractor)
{
if (outerFieldValue != nullptr && checkInherits(*outerFieldValue, MapFieldValue::classId)) {
const auto outerMap = static_cast<const MapFieldValue *>(outerFieldValue);
auto array = makeArray(innerEntry, outerMap->size());
uint32_t arrayIndex = 0;
for (const auto &mapElem : *outerMap) {
(*array)[arrayIndex++].assign(*extractor(mapElem));
}
return array;
}
return std::unique_ptr<FieldValue>();
}
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getMapKeyFieldValue(const FieldPath &fieldPath)
{
return getMapFieldValue(getCachedFieldValue(fieldPath[0]), fieldPath[1],
[](const auto &elem){ return elem.first; });
}
std::unique_ptr<document::FieldValue>
DocumentFieldExtractor::getPrimitiveMapFieldValue(const FieldPath &fieldPath)
{
return getMapFieldValue(getCachedFieldValue(fieldPath[0]), fieldPath[1],
[](const auto &elem){ return elem.second; });
}
std::unique_ptr<document::FieldValue>
DocumentFieldExtractor::getStructMapFieldValue(const FieldPath &fieldPath)
{
const auto outerFieldValue = getCachedFieldValue(fieldPath[0]);
if (outerFieldValue != nullptr && checkInherits(*outerFieldValue, MapFieldValue::classId)) {
const auto outerMap = static_cast<const MapFieldValue *>(outerFieldValue);
const auto &innerFieldPathEntry = fieldPath[2];
auto array = makeArray(innerFieldPathEntry, outerMap->size());
uint32_t arrayIndex = 0;
for (const auto &mapElem : *outerMap) {
auto &arrayElem = (*array)[arrayIndex++];
const auto &structElem = static_cast<const StructFieldValue &>(*mapElem.second);
if (!structElem.getValue(innerFieldPathEntry.getFieldRef(), arrayElem)) {
arrayElem.accept(setUndefinedValueVisitor);
}
}
return array;
}
return std::unique_ptr<FieldValue>();
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getFieldValue(const FieldPath &fieldPath)
{
if (fieldPath.size() == 1) {
return getSimpleFieldValue(fieldPath);
} else if (fieldPath.size() == 2) {
auto lastElemType = fieldPath[1].getType();
if (lastElemType == FieldPathEntry::Type::STRUCT_FIELD) {
return getStructArrayFieldValue(fieldPath);
} else if (lastElemType == FieldPathEntry::Type::MAP_ALL_KEYS) {
return getMapKeyFieldValue(fieldPath);
} else {
return getPrimitiveMapFieldValue(fieldPath);
}
} else if (fieldPath.size() == 3) {
return getStructMapFieldValue(fieldPath);
}
return std::unique_ptr<FieldValue>();
}
}
<commit_msg>Add common function to extract an array from a struct collection.<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "document_field_extractor.h"
#include <vespa/document/datatype/arraydatatype.h>
#include <vespa/document/fieldvalue/arrayfieldvalue.h>
#include <vespa/document/fieldvalue/bytefieldvalue.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/fieldvalue/doublefieldvalue.h>
#include <vespa/document/fieldvalue/floatfieldvalue.h>
#include <vespa/document/fieldvalue/intfieldvalue.h>
#include <vespa/document/fieldvalue/longfieldvalue.h>
#include <vespa/document/fieldvalue/shortfieldvalue.h>
#include <vespa/document/fieldvalue/stringfieldvalue.h>
#include <vespa/document/fieldvalue/mapfieldvalue.h>
#include <vespa/searchcommon/common/undefinedvalues.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/util/exceptions.h>
using document::FieldValue;
using document::ByteFieldValue;
using document::ShortFieldValue;
using document::IntFieldValue;
using document::LongFieldValue;
using document::FloatFieldValue;
using document::DoubleFieldValue;
using document::StringFieldValue;
using document::StructFieldValue;
using document::MapFieldValue;
using document::DataType;
using document::ArrayDataType;
using document::ArrayFieldValue;
using document::Document;
using document::FieldPath;
using document::FieldPathEntry;
using document::FieldValueVisitor;
using vespalib::IllegalStateException;
using vespalib::make_string;
using search::attribute::getUndefined;
namespace proton {
namespace {
class SetUndefinedValueVisitor : public FieldValueVisitor
{
void visit(document::AnnotationReferenceFieldValue &) override { }
void visit(ArrayFieldValue &) override { }
void visit(ByteFieldValue &value) override { value = getUndefined<int8_t>(); }
void visit(Document &) override { }
void visit(DoubleFieldValue &value) override { value = getUndefined<double>(); }
void visit(FloatFieldValue &value) override { value = getUndefined<float>(); }
void visit(IntFieldValue &value) override { value = getUndefined<int32_t>(); }
void visit(LongFieldValue &value) override { value = getUndefined<int64_t>(); }
void visit(MapFieldValue &) override { }
void visit(document::PredicateFieldValue &) override { }
void visit(document::RawFieldValue &) override { }
void visit(ShortFieldValue &value) override { value = getUndefined<int16_t>(); }
void visit(StringFieldValue &) override { }
void visit(StructFieldValue &) override { }
void visit(document::WeightedSetFieldValue &) override { }
void visit(document::TensorFieldValue &) override { }
void visit(document::ReferenceFieldValue &) override { }
};
SetUndefinedValueVisitor setUndefinedValueVisitor;
const ArrayDataType arrayTypeByte(*DataType::BYTE);
const ArrayDataType arrayTypeShort(*DataType::SHORT);
const ArrayDataType arrayTypeInt(*DataType::INT);
const ArrayDataType arrayTypeLong(*DataType::LONG);
const ArrayDataType arrayTypeFloat(*DataType::FLOAT);
const ArrayDataType arrayTypeDouble(*DataType::DOUBLE);
const ArrayDataType arrayTypeString(*DataType::STRING);
const DataType *
getArrayType(const DataType &fieldType)
{
switch (fieldType.getId()) {
case DataType::Type::T_BYTE:
return &arrayTypeByte;
case DataType::Type::T_SHORT:
return &arrayTypeShort;
case DataType::Type::T_INT:
return &arrayTypeInt;
case DataType::Type::T_LONG:
return &arrayTypeLong;
case DataType::Type::T_FLOAT:
return &arrayTypeFloat;
case DataType::Type::T_DOUBLE:
return &arrayTypeDouble;
case DataType::Type::T_STRING:
return &arrayTypeString;
default:
return nullptr;
}
}
std::unique_ptr<ArrayFieldValue>
makeArray(const FieldPathEntry &fieldPathEntry, size_t size)
{
const auto arrayType = getArrayType(fieldPathEntry.getDataType());
auto array = std::make_unique<ArrayFieldValue>(*arrayType);
array->resize(size);
return array;
}
bool
checkInherits(const FieldValue &fieldValue, unsigned id)
{
const vespalib::Identifiable::RuntimeClass &rc = fieldValue.getClass();
return rc.inherits(id);
}
}
DocumentFieldExtractor::DocumentFieldExtractor(const Document &doc)
: _doc(doc),
_cachedFieldValues()
{
}
DocumentFieldExtractor::~DocumentFieldExtractor() = default;
bool
DocumentFieldExtractor::isSupported(const FieldPath &fieldPath)
{
if (!fieldPath.empty() &&
fieldPath[0].getType() != FieldPathEntry::Type::STRUCT_FIELD) {
return false;
}
if (fieldPath.size() == 2) {
if (fieldPath[1].getType() != FieldPathEntry::Type::STRUCT_FIELD &&
fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_KEYS &&
fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_VALUES) {
return false;
}
} else if (fieldPath.size() == 3) {
if (fieldPath[1].getType() != FieldPathEntry::Type::MAP_ALL_VALUES ||
fieldPath[2].getType() != FieldPathEntry::Type::STRUCT_FIELD) {
return false;
}
} else if (fieldPath.size() > 3) {
return false;
}
return true;
}
const FieldValue *
DocumentFieldExtractor::getCachedFieldValue(const FieldPathEntry &fieldPathEntry)
{
auto itr = _cachedFieldValues.find(fieldPathEntry.getName());
if (itr != _cachedFieldValues.end()) {
return itr->second.get();
} else {
auto insres = _cachedFieldValues.insert(std::make_pair(fieldPathEntry.getName(), _doc.getValue(fieldPathEntry.getFieldRef())));
assert(insres.second);
return insres.first->second.get();
}
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getSimpleFieldValue(const FieldPath &fieldPath)
{
return _doc.getNestedFieldValue(fieldPath.getFullRange());
}
namespace {
template <typename ExtractorFunc>
std::unique_ptr<FieldValue>
getMapFieldValue(const FieldValue *outerFieldValue, const FieldPathEntry &innerEntry, ExtractorFunc &&extractor)
{
if (outerFieldValue != nullptr && checkInherits(*outerFieldValue, MapFieldValue::classId)) {
const auto outerMap = static_cast<const MapFieldValue *>(outerFieldValue);
auto array = makeArray(innerEntry, outerMap->size());
uint32_t arrayIndex = 0;
for (const auto &mapElem : *outerMap) {
(*array)[arrayIndex++].assign(*extractor(mapElem));
}
return array;
}
return std::unique_ptr<FieldValue>();
}
template <typename CollectionFieldValueT, typename ExtractorFunc>
std::unique_ptr<FieldValue>
extractArrayFromStructCollection(const FieldValue *outerFieldValue, const FieldPathEntry &innerEntry, ExtractorFunc &&extractor)
{
if (outerFieldValue != nullptr && checkInherits(*outerFieldValue, CollectionFieldValueT::classId)) {
const auto *outerCollection = static_cast<const CollectionFieldValueT *>(outerFieldValue);
auto array = makeArray(innerEntry, outerCollection->size());
uint32_t arrayIndex = 0;
for (const auto &outerElem : *outerCollection) {
auto &arrayElem = (*array)[arrayIndex++];
const auto &structElem = static_cast<const StructFieldValue &>(*extractor(&outerElem));
if (!structElem.getValue(innerEntry.getFieldRef(), arrayElem)) {
arrayElem.accept(setUndefinedValueVisitor);
}
}
return array;
}
return std::unique_ptr<FieldValue>();
}
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getStructArrayFieldValue(const FieldPath &fieldPath)
{
return extractArrayFromStructCollection<ArrayFieldValue>(getCachedFieldValue(fieldPath[0]), fieldPath[1],
[](const auto *elem){ return elem; });
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getMapKeyFieldValue(const FieldPath &fieldPath)
{
return getMapFieldValue(getCachedFieldValue(fieldPath[0]), fieldPath[1],
[](const auto &elem){ return elem.first; });
}
std::unique_ptr<document::FieldValue>
DocumentFieldExtractor::getPrimitiveMapFieldValue(const FieldPath &fieldPath)
{
return getMapFieldValue(getCachedFieldValue(fieldPath[0]), fieldPath[1],
[](const auto &elem){ return elem.second; });
}
std::unique_ptr<document::FieldValue>
DocumentFieldExtractor::getStructMapFieldValue(const FieldPath &fieldPath)
{
return extractArrayFromStructCollection<MapFieldValue>(getCachedFieldValue(fieldPath[0]), fieldPath[2],
[](const auto *elem){ return elem->second; });
}
std::unique_ptr<FieldValue>
DocumentFieldExtractor::getFieldValue(const FieldPath &fieldPath)
{
if (fieldPath.size() == 1) {
return getSimpleFieldValue(fieldPath);
} else if (fieldPath.size() == 2) {
auto lastElemType = fieldPath[1].getType();
if (lastElemType == FieldPathEntry::Type::STRUCT_FIELD) {
return getStructArrayFieldValue(fieldPath);
} else if (lastElemType == FieldPathEntry::Type::MAP_ALL_KEYS) {
return getMapKeyFieldValue(fieldPath);
} else {
return getPrimitiveMapFieldValue(fieldPath);
}
} else if (fieldPath.size() == 3) {
return getStructMapFieldValue(fieldPath);
}
return std::unique_ptr<FieldValue>();
}
}
<|endoftext|> |
<commit_before><commit_msg>fixed: unresolved references under Solaris<commit_after><|endoftext|> |
<commit_before><commit_msg>Create ph.cpp<commit_after><|endoftext|> |
<commit_before>/* Copyright (C) 2006 Imperial College London and others.
Please see the AUTHORS file in the main source directory for a full list
of copyright holders.
Prof. C Pain
Applied Modelling and Computation Group
Department of Earth Science and Engineering
Imperial College London
[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,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
*/
#include "confdefs.h"
#include <unistd.h>
#ifndef _AIX
#include <getopt.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <cassert>
#include <deque>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include "vtk.h"
#include "Halos_IO.h"
#include "fmangle.h"
#include "partition.h"
using namespace std;
using namespace Fluidity;
extern "C" {
void fldecomp_fc(const char *, const int *, const int *);
void set_global_debug_level_fc(int *val);
}
void usage(char *binary){
cerr<<"Usage: "<<binary<<" [OPTIONS] -n nparts file\n"
<<"\t-c,--cores <number of cores per node>\n\t\tApplies hierarchical partitioning.\n"
<<"\t-d,--diagnostics\n\t\tPrint out partition diagnostics.\n"
<<"\t-f,--file <file name>\n\t\tInput file (can alternatively specify as final "
<<"argument)\n"
<<"\t-h,--help\n\t\tPrints out this message\n"
<<"\t-k.--kway\n\t\tPartition a graph into k equal-size parts using the "
<<"multilevel k-way partitioning algorithm (METIS PartGraphKway). This "
<<"is the default if the number of partitions is greater than 8.\n"
<<"\t-n,--nparts <number of partitions>\n\t\tNumber of parts\n"
<<"\t-r,--recursive\n\t\tPartition a graph into k equal-size parts using multilevel recursive "
<<"bisection (METIS PartGraphRecursive). This is the default if num partitions "
<<"is less or equal to 8.\n"
<<"\t-t,--terreno [boundary id]\n\t\tRecognise as a Terreno output that is extruded in the Z direction. By default the boundary id of the extruded plane is 1.\n"
<<"\t-s,--shell\n\t\tRecognise the input as a spherical shell mesh.\n"
<<"\t-v,--verbose\n\t\tVerbose mode\n";
exit(-1);
}
void write_partitions(bool verbose, string filename, string file_format,
int nparts, int nnodes, int dim, int no_coords,
const vector<double>&x, const vector<int>& decomp,
int nloc, const vector<int>& ENList, const vector<int>& regionIds,
int snloc, const deque< vector<int> >& SENList, const vector<int>& boundaryIds){
// Construct:
// nodes - nodes in each partition (private and halo), numbered from
// one
// npnodes - number of nodes private to each partition
// elements - elements ids in each partition (private and halo), numbered
// from zero
// halo1 - receive nodes (numbered from one) in the first halo for each
// partition
// halo2 - receive nodes (numbered from one) in the second halo for
// each partition
// where in each case partitions are numbered from zero.
if(verbose)
cout<<"void write_partitions( ... )";
int nelms = ENList.size()/nloc;
vector< vector< set<int> > > halo1(nparts);
vector< vector< set<int> > > halo2(nparts);
vector< map<int, int> > renumber(nparts);
for(int part=0; part<nparts; part++){
halo1[part].resize(nparts);
halo2[part].resize(nparts);
}
vector<int> npnodes(nparts, 0);
#pragma omp parallel
{
#pragma omp for
for(int part=0; part<nparts; part++){
if(verbose)
cout<<"Making partition "<<part<<endl;
deque<int> *nodes = new deque<int>;
deque<int> *elements = new deque<int>;
vector<bool> *halo_nodes = new vector<bool>(nnodes, false);
vector<bool> *more_halo_nodes = new vector<bool>(nnodes, false);
// Find owned nodes
for(int nid=0; nid<nnodes; nid++){
if(decomp[nid]==part)
nodes->push_back(nid+1);
}
npnodes[part] = nodes->size();
if(verbose)
cout<<"Found "<<npnodes[part]<<" owned nodes\n";
// Find elements with owned nodes and halo1
deque< pair<int, int> > *sorted_elements = new deque< pair<int, int> >;
for(int eid=0;eid<nelms;eid++){
int halo_count=0;
pair<int, int> *owned_elm = new pair<int, int>(decomp[ENList[eid*nloc] - 1], eid);
if(decomp[ENList[eid*nloc] - 1]!=part){
halo_count++;
}
for(int j=1;j<nloc;j++){
owned_elm->first = min(owned_elm->first, decomp[ENList[eid*nloc+j] - 1]);
if(decomp[ENList[eid*nloc+j] - 1]!=part){
halo_count++;
}
}
if(halo_count<nloc){
sorted_elements->push_back(*owned_elm);
if(halo_count>0){
for(int j=0;j<nloc;j++){
int nid = ENList[eid*nloc+j] - 1;
if(decomp[nid]!=part){
halo1[part][decomp[nid]].insert(nid+1);
(*halo_nodes)[nid] = true;
}
}
}
}
delete owned_elm;
}
if(verbose)
cout<<"Found halo1 nodes\n";
for(deque< pair<int, int> >::const_iterator it=sorted_elements->begin();it!=sorted_elements->end();++it)
if(it->first==part)
elements->push_back(it->second);
for(deque< pair<int, int> >::const_iterator it=sorted_elements->begin();it!=sorted_elements->end();++it)
if(it->first!=part)
elements->push_back(it->second);
delete sorted_elements;
if(verbose)
cout<<"Sorted elements\n";
// Find halo2 elements and nodes
set<int> *halo2_elements = new set<int>;
for(int eid=0; eid<nelms; eid++){
int owned_node_count=0;
bool touches_halo1=false;
for(int j=0;j<nloc;j++){
int fnid = ENList[eid*nloc+j];
touches_halo1 = touches_halo1 || (*halo_nodes)[fnid-1];
if(decomp[fnid-1]==part)
owned_node_count++;
}
if(touches_halo1&&(owned_node_count==0)){
halo2_elements->insert(halo2_elements->end(), eid);
for(int j=0;j<nloc;j++){
int fnid = ENList[eid*nloc+j];
if(!(*halo_nodes)[fnid-1]){
halo2[part][decomp[fnid-1]].insert(fnid);
(*more_halo_nodes)[fnid-1]=true;
}
}
}
}
if(verbose)
cout<<"Found "<<halo2_elements->size()<<" halo2 elements\n";
for(int i=0;i<nparts;i++)
halo2[part][i].insert(halo1[part][i].begin(), halo1[part][i].end());
for(int i=0;i<nnodes;i++)
if((*halo_nodes)[i])
nodes->push_back(i+1);
delete halo_nodes;
for(int i=0;i<nnodes;i++)
if((*more_halo_nodes)[i])
nodes->push_back(i+1);
delete more_halo_nodes;
for(set<int>::const_iterator it=halo2_elements->begin(); it!=halo2_elements->end(); ++it)
elements->push_back(*it);
delete halo2_elements;
if(verbose)
cout<<"Partition: "<<part<<", Private nodes: "<<npnodes[part]<<", Total nodes: "<<nodes->size()<<"\n";
// Write out data for each partition
if(verbose)
cout<<"Write mesh data for partition "<<part<<"\n";
// Map from global node numbering (numbered from one) to partition node
// numbering (numbered from one)
for(size_t j=0;j<nodes->size();j++){
renumber[part].insert(renumber[part].end(), pair<int, int>((*nodes)[j], j+1));
}
// Coordinate data
vector<double> *partX = new vector<double>(nodes->size()*no_coords);
for(size_t j=0;j<nodes->size();j++){
for(int k=0;k<no_coords;k++){
(*partX)[j * no_coords + k] = x[((*nodes)[j] - 1) * no_coords + k];
}
}
// Volume element data
vector<int> *partENList = new vector<int>;
partENList->reserve(elements->size()*nloc);
vector<int> *partRegionIds = new vector<int>;
partRegionIds->reserve(elements->size());
// Map from partition node numbers (numbered from one) to partition
// element numbers (numbered from zero)
vector< set<int> > *partNodesToEid = new vector< set<int> >(nodes->size()+1);
int ecnt=0;
for(deque<int>::const_iterator iter=elements->begin();iter!=elements->end();iter++){
for(int j=0;j<nloc;j++){
int nid = ENList[*iter*nloc+j];
int gnid = renumber[part].find(nid)->second;
partENList->push_back(gnid);
(*partNodesToEid)[gnid].insert(ecnt);
}
partRegionIds->push_back(regionIds[*iter]);
ecnt++;
}
// Surface element data
vector<int> *partSENList = new vector<int>;
vector<int> *partBoundaryIds = new vector<int>;
for(size_t j=0;j<SENList.size();j++){
// In order for a global surface element to be a partition surface
// element, all of its nodes must be attached to at least one partition
// volume element
if(SENList[j].size()==0 or
renumber[part].find(SENList[j][0])==renumber[part].end() or
(*partNodesToEid)[renumber[part].find(SENList[j][0])->second].empty()){
continue;
}
bool SEOwned=false;
set<int> &lpartNodesToEid = (*partNodesToEid)[renumber[part].find(SENList[j][0])->second];
for(set<int>::const_iterator iter=lpartNodesToEid.begin();iter!=lpartNodesToEid.end();iter++){
SEOwned=true;
set<int> *VENodes = new set<int>;
for(int k=(*iter)*nloc;k<(*iter)*nloc+nloc;k++){
VENodes->insert((*partENList)[k]);
}
for(size_t k=1;k<SENList[j].size();k++){
if(renumber[part].find(SENList[j][k])==renumber[part].end() or
VENodes->count(renumber[part].find(SENList[j][k])->second)==0){
SEOwned=false;
break;
}
}
if(SEOwned){
break;
}
delete VENodes;
}
if(SEOwned){
for(size_t k=0;k<SENList[j].size();k++){
partSENList->push_back(renumber[part].find(SENList[j][k])->second);
}
partBoundaryIds->push_back(boundaryIds[j]);
}
}
delete partNodesToEid;
// Write out the partition mesh
ostringstream basename;
basename<<filename<<"_"<<part;
if(verbose)
cout<<"Writing out triangle mesh for partition "<<part<<" to files with base name "<<basename.str()<<"\n";
ofstream nodefile;
nodefile.open(string(basename.str()+".node").c_str());
nodefile.precision(16);
nodefile<<nodes->size()<<" "<<dim<<" 0 0\n";
for(size_t j=0;j<nodes->size();j++){
nodefile<<j+1<<" ";
for(int k=0;k<no_coords;k++){
nodefile<<(*partX)[j * no_coords + k]<<" ";
}
nodefile<<endl;
}
nodefile<<"# Produced by: fldecomp\n";
nodefile.close();
delete nodes;
delete partX;
ofstream elefile;
elefile.open(string(basename.str()+".ele").c_str());
if(partRegionIds->size())
elefile<<elements->size()<<" "<<nloc<<" 1\n";
else
elefile<<elements->size()<<" "<<nloc<<" 0\n";
for(int i=0;i<elements->size();i++){
elefile<<i+1<<" ";
for(int j=0;j<nloc;j++)
elefile<<(*partENList)[i*nloc+j]<<" ";
if(partRegionIds->size())
elefile<<(*partRegionIds)[i];
elefile<<endl;
}
elefile<<"# Produced by: fldecomp\n";
elefile.close();
delete elements;
delete partENList;
ofstream facefile;
if(snloc==1)
facefile.open(string(basename.str()+".bound").c_str());
else if(snloc==2)
facefile.open(string(basename.str()+".edge").c_str());
else
facefile.open(string(basename.str()+".face").c_str());
int nfacets = partSENList->size()/snloc;
facefile<<nfacets<<" 1\n";
for(int i=0;i<nfacets;i++){
facefile<<i+1<<" ";
for(int j=0;j<snloc;j++)
facefile<<(*partSENList)[i*snloc+j]<<" ";
facefile<<" "<<(*partBoundaryIds)[i]<<endl;
}
facefile.close();
delete partSENList;
delete partBoundaryIds;
basename.str("");
}
}
const int halo1_level = 1, halo2_level = 2;
for(int i=0;i<nparts;i++){
// Extract halo data
if(verbose)
cout<<"Extracting halo data for partition "<<i<<"\n";
map<int, vector< vector<int> > > send, recv;
map<int, int> npnodes_handle;
recv[halo1_level].resize(nparts);
send[halo1_level].resize(nparts);
recv[halo2_level].resize(nparts);
send[halo2_level].resize(nparts);
for(int j=0;j<nparts;j++){
for(set<int>::const_iterator it=halo1[i][j].begin();it!=halo1[i][j].end();++it){
recv[halo1_level][j].push_back(renumber[i][*it]);
}
for(set<int>::const_iterator it=halo1[j][i].begin();it!=halo1[j][i].end();++it){
send[halo1_level][j].push_back(renumber[i][*it]);
}
for(set<int>::const_iterator it=halo2[i][j].begin();it!=halo2[i][j].end();++it){
recv[halo2_level][j].push_back(renumber[i][*it]);
}
for(set<int>::const_iterator it=halo2[j][i].begin();it!=halo2[j][i].end();++it){
send[halo2_level][j].push_back(renumber[i][*it]);
}
}
npnodes_handle[halo1_level]=npnodes[i];
npnodes_handle[halo2_level]=npnodes[i];
ostringstream buffer;
buffer<<filename<<"_"<<i<<".halo";
if(verbose)
cout<<"Writing out halos for partition "<<i<<" to file "<<buffer.str()<<"\n";
if(WriteHalos(buffer.str(), i, nparts, npnodes_handle, send, recv)){
cerr<<"ERROR: failed to write halos to file "<<buffer.str()<<endl;
exit(-1);
}
buffer.str("");
}
return;
}
int main(int argc, char **argv){
// Get any command line arguments
// reset optarg so we can detect changes
#ifndef _AIX
struct option longOptions[] = {
{"cores", 0, 0, 'c'},
{"diagnostics", 0, 0, 'd'},
{"file", 0, 0, 'f'},
{"help", 0, 0, 'h'},
{"kway", 0, 0, 'k'},
{"nparts", 0, 0, 'n'},
{"recursive", 0, 0, 'r'},
{"terreno", optional_argument, 0, 't'},
{"shell", 0, 0, 's'},
{"verbose", 0, 0, 'v'},
{0, 0, 0, 0}
};
#endif
int optionIndex = 0;
optarg = NULL;
char c;
map<char, string> flArgs;
while (true){
#ifndef _AIX
c = getopt_long(argc, argv, "c:df:hkn:rt::s::v", longOptions, &optionIndex);
#else
c = getopt(argc, argv, "c:df:hkn:rt::s::v");
#endif
if (c == -1) break;
if (c != '?'){
if(c == 't')
flArgs[c] = (optarg == NULL) ? "1" : optarg;
else if (optarg == NULL){
flArgs[c] = "true";
}else{
flArgs[c] = optarg;
}
}else{
if (isprint(optopt)){
cerr << "Unknown option " << optopt << endl;
}else{
cerr << "Unknown option " << hex << optopt << endl;
}
usage(argv[0]);
exit(-1);
}
}
// Help?
if(flArgs.count('h')||(flArgs.count('n')==0)){
usage(argv[0]);
exit(-1);
}
// What to do with stdout?
bool verbose=false;
int val=3;
if(flArgs.count('v')){
verbose = true;
cout<<"Verbose mode enabled.\n";
}else{
val = 0;
}
set_global_debug_level_fc(&val);
if(!flArgs.count('f')){
if(argc>optind+1){
flArgs['f'] = argv[optind+1];
}else if(argc==optind+1){
flArgs['f'] = argv[optind];
}
}
string filename = flArgs['f'];
string file_format("triangle");
int nparts = atoi(flArgs['n'].c_str());
if(nparts<2){
cerr<<"ERROR: number of partitions requested is less than 2. Please check your usage and try again.\n";
usage(argv[0]);
exit(-1);
}
int ncores = 0;
if(flArgs.count('c')){
ncores = atoi(flArgs['c'].c_str());
if(nparts%ncores){
cerr<<"ERROR: The number of partitions must be some multiple of the number of cores\n";
exit(-1);
}
}
if(file_format!="triangle"){
cerr<<"ERROR: file format not supported\n";
}
// Read in the mesh
if(verbose)
cout<<"Reading in triangle mesh with base name "<<filename<<"\n";
bool extruded = (flArgs.find('t')!=flArgs.end());
if(extruded&&verbose){
// This triangle file came from Terreno and should have
// attribure data indicating the surface node lieing above the
// node in the extruded mesh.
cout<<"Reading in extrusion information\n";
}
bool shell = (flArgs.find('s')!=flArgs.end());
string filename_node = filename+".node";
if(verbose)
cout<<"Reading "<<filename_node<<endl;
fstream node_file;
node_file.open(filename_node.c_str(), ios::in);
if(!node_file.is_open()){
cerr<<"ERROR: Triangle file, "<<filename_node
<<", cannot be opened. Does it exist? Have you read permission?\n";
exit(-1);
}
int nnodes, dim, natt, nboundary;
node_file>>nnodes>>dim>>natt>>nboundary;
if(extruded){
if(natt!=1){
cerr<<"ERROR: The -t option is specified but there is not the right number "
<<"of attributes in the .node file.\n";
}
}
int no_coords; // The number of coordinates
if(shell){
no_coords=dim+1; // Shell meshes have and x, y and z coordinate.
}else{
no_coords=dim;
}
vector<double> x(nnodes*no_coords);
vector<int> surface_nids;
if(extruded||(natt==1))
surface_nids.resize(nnodes);
{
int id, pos=0;
for(int i=0;i<nnodes;i++){
node_file>>id;
for(int j=0;j<no_coords;j++)
node_file>>x[pos++];
if(natt)
node_file>>surface_nids[i];
}
}
node_file.close();
string filename_ele;
filename_ele = filename+".ele";
if(verbose)
cout<<"Reading "<<filename_ele<<endl;
fstream ele_file;
ele_file.open(filename_ele.c_str(), ios::in);
if(!ele_file.is_open()){
cerr<<"ERROR: Triangle file, "<<filename_ele
<<", cannot be opened. Does it exist? Have you read permission?\n";
exit(-1);
}
vector<int> ENList, regionIds;
int nele, nloc;
{
int natt, id, pos=0;
ele_file>>nele>>nloc>>natt;
ENList.resize(nele*nloc);
regionIds.resize(nele);
if(natt>1){
cerr<<"ERROR: Don't know what to do with more than 1 attribute.\n";
exit(-1);
}
for(int i=0;i<nele;i++){
ele_file>>id;
for(int j=0;j<nloc;j++)
ele_file>>ENList[pos++];
if(natt)
ele_file>>regionIds[i];
else
regionIds[i]=0;
}
}
ele_file.close();
string filename_face;
if((dim==3)&&(nloc==3)){
filename_face = filename+".edge";
}else if(dim==3){
filename_face = filename+".face";
}else if(dim==2){
filename_face = filename+".edge";
}else if(dim==1){
filename_face = filename+".bound";
}else{
cerr<<"ERROR: dim=="<<dim<<" not supported.\n";
exit(-1);
}
if(verbose)
cout<<"Reading "<<filename_face<<endl;
fstream face_file;
face_file.open(filename_face.c_str(), ios::in);
if(!face_file.is_open()){
cerr<<"ERROR: Triangle file, "<<filename_face
<<", cannot be opened. Does it exist? Have you read permission?\n";
exit(-1);
}
deque< vector<int> > SENList;
deque< vector<int> > columnSENList;
vector<int> topSENList;
// Set the boundary id of the extruded surface -- default 1.
int bid = 1;
if(flArgs.count('t'))
bid = atoi(flArgs['t'].c_str());
vector<int> boundaryIds;
int nsele, snloc, snnodes;
int max_snnodes=0, min_snnodes=0;
{
int natt, id;
face_file>>nsele>>natt;
if((nloc==4)&&(dim==3))
snloc=3;
else if((nloc==4)&&(dim==2))
snloc=2;
else if((nloc==2)&&(dim==1))
snloc=1;
else if(nloc==3)
snloc=2;
else if(nloc==8)
snloc=4;
else{
cerr<<"ERROR: no idea what snloc is.\n";
exit(-1);
}
SENList.resize(nsele);
columnSENList.resize(nsele);
if(natt>1){
cerr<<"ERROR: Don't know what to do with more than 1 attribute.\n";
exit(-1);
}
if(natt)
boundaryIds.resize(nsele);
for(int i=0;i<nsele;i++){
vector<int> facet(snloc);
vector<int> facet_columns(snloc);
face_file>>id;
for(int j=0;j<snloc;j++){
face_file>>facet[j];
if(surface_nids.size())
facet_columns[j]=surface_nids[facet[j]-1];
}
SENList[i] = facet;
if(surface_nids.size())
columnSENList[i] = facet_columns;
if(natt){
face_file>>boundaryIds[i];
if(boundaryIds[i]==bid){
for(int j=0;j<snloc;j++){
if(surface_nids.size()){
topSENList.push_back(columnSENList[i][j]);
max_snnodes=max(max_snnodes, columnSENList[i][j]);
min_snnodes=min(min_snnodes, columnSENList[i][j]);
snnodes=max_snnodes-min_snnodes+1;
}else{
topSENList.push_back(SENList[i][j]);
max_snnodes=max(max_snnodes, SENList[i][j]);
min_snnodes=min(min_snnodes, SENList[i][j]);
snnodes=max_snnodes-min_snnodes+1;
}
}
}
}
}
}
columnSENList.clear();
face_file.close();
vector<int> decomp;
int partition_method = -1;
if(flArgs.count('r')){
partition_method = 0; // METIS PartGraphRecursive
if(flArgs.count('k')){
cerr<<"WARNING: should not specify both -k and -r. Choosing -r.\n";
}
}
if(flArgs.count('k')){
partition_method = 1; // METIS PartGraphKway
}
vector<int> npartitions;
if(ncores>1){
npartitions.push_back(nparts/ncores);
npartitions.push_back(ncores);
}else{
npartitions.push_back(nparts);
}
int edgecut=0;
if(surface_nids.size()){
// Partition the mesh
if(verbose)
cout<<"Partitioning the extruded Terreno mesh\n";
// Partition the mesh. Generates a map "decomp" from node number
// (numbered from zero) to partition number (numbered from
// zero).
edgecut = partition(topSENList, 2, snloc, snnodes, npartitions, partition_method, decomp);
topSENList.clear();
decomp.resize(nnodes);
vector<int> decomp_temp;
decomp_temp.resize(nnodes);
for(int i=0;i<nnodes;i++){
decomp_temp[i] = decomp[surface_nids[i]-1]; // surface_nids=column number
}
decomp=decomp_temp;
decomp_temp.clear();
}else{
// Partition the mesh
if(verbose)
cout<<"Partitioning the mesh\n";
// Partition the mesh. Generates a map "decomp" from node number
// (numbered from zero) to partition number (numbered from
// zero).
edgecut = partition(ENList, dim, nloc, nnodes, npartitions, partition_method, decomp);
}
if(flArgs.count('d')){
cout<<"Edge-cut: "<<edgecut<<endl;
}
// Process the partitioning
if(verbose)
cout<<"Processing the mesh partitions\n";
write_partitions(verbose, filename, file_format,
nparts, nnodes, dim, no_coords,
x, decomp,
nloc, ENList, regionIds,
snloc, SENList, boundaryIds);
return(0);
}
<commit_msg>fluidity/fldecomp.cpp no longer needed - dead code<commit_after><|endoftext|> |
<commit_before><commit_msg>Update Lab_02_Question_04.cpp<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/system/cuda/detail/bulk/detail/config.hpp>
#include <thrust/system/cuda/detail/bulk/detail/cuda_launcher/runtime_introspection.hpp>
#include <thrust/system/cuda/detail/bulk/detail/throw_on_error.hpp>
#include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
#include <thrust/detail/util/blocking.h>
#include <thrust/detail/minmax.h>
#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
BULK_NAMESPACE_PREFIX
namespace bulk
{
namespace detail
{
__host__ __device__
inline device_properties_t device_properties_uncached(int device_id)
{
device_properties_t prop = {0,{0,0,0},0,0,0,0,0,0,0};
cudaError_t error = cudaErrorNoDevice;
#if __BULK_HAS_CUDART__
error = cudaDeviceGetAttribute(&prop.major, cudaDevAttrComputeCapabilityMajor, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[0], cudaDevAttrMaxGridDimX, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[1], cudaDevAttrMaxGridDimY, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[2], cudaDevAttrMaxGridDimZ, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerBlock, cudaDevAttrMaxThreadsPerBlock, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerMultiProcessor, cudaDevAttrMaxThreadsPerMultiProcessor, device_id);
error = cudaDeviceGetAttribute(&prop.minor, cudaDevAttrComputeCapabilityMinor, device_id);
error = cudaDeviceGetAttribute(&prop.multiProcessorCount, cudaDevAttrMultiProcessorCount, device_id);
error = cudaDeviceGetAttribute(&prop.regsPerBlock, cudaDevAttrMaxRegistersPerBlock, device_id);
int temp;
error = cudaDeviceGetAttribute(&temp, cudaDevAttrMaxSharedMemoryPerBlock, device_id);
prop.sharedMemPerBlock = temp;
error = cudaDeviceGetAttribute(&prop.warpSize, cudaDevAttrWarpSize, device_id);
#else
(void) device_id; // Surpress unused parameter warnings
#endif
throw_on_error(error, "cudaDeviceGetProperty in get_device_properties");
return prop;
}
inline device_properties_t device_properties_cached(int device_id)
{
// cache the result of get_device_properties, because it is slow
// only cache the first few devices
static const int max_num_devices = 16;
static bool properties_exist[max_num_devices] = {0};
static device_properties_t device_properties[max_num_devices] = {};
if(device_id >= max_num_devices)
{
return device_properties_uncached(device_id);
}
if(!properties_exist[device_id])
{
device_properties[device_id] = device_properties_uncached(device_id);
// disallow the compiler to move the write to properties_exist[device_id]
// before the initialization of device_properties[device_id]
__thrust_compiler_fence();
properties_exist[device_id] = true;
}
return device_properties[device_id];
}
__host__ __device__
inline device_properties_t device_properties(int device_id)
{
#ifndef __CUDA_ARCH__
return device_properties_cached(device_id);
#else
return device_properties_uncached(device_id);
#endif
}
__host__ __device__
inline int current_device()
{
int result = -1;
#if __BULK_HAS_CUDART__
bulk::detail::throw_on_error(cudaGetDevice(&result), "current_device(): after cudaGetDevice");
#endif
if(result < 0)
{
bulk::detail::throw_on_error(cudaErrorNoDevice, "current_device(): after cudaGetDevice");
}
return result;
}
__host__ __device__
inline device_properties_t device_properties()
{
return device_properties(current_device());
}
template <typename KernelFunction>
__host__ __device__
inline function_attributes_t function_attributes(KernelFunction kernel)
{
#if __BULK_HAS_CUDART__
typedef void (*fun_ptr_type)();
fun_ptr_type fun_ptr = reinterpret_cast<fun_ptr_type>(kernel);
cudaFuncAttributes attributes;
bulk::detail::throw_on_error(cudaFuncGetAttributes(&attributes, fun_ptr), "function_attributes(): after cudaFuncGetAttributes");
// be careful about how this is initialized!
function_attributes_t result = {
attributes.constSizeBytes,
attributes.localSizeBytes,
attributes.maxThreadsPerBlock,
attributes.numRegs,
attributes.ptxVersion,
attributes.sharedSizeBytes
};
return result;
#else
return function_attributes_t();
#endif // __CUDACC__
}
__host__ __device__
inline size_t compute_capability(const device_properties_t &properties)
{
return 10 * properties.major + properties.minor;
}
__host__ __device__
inline size_t compute_capability()
{
return compute_capability(device_properties());
}
} // end namespace detail
} // end namespace bulk
BULK_NAMESPACE_SUFFIX
<commit_msg>Eliminate spurious whitespace<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/system/cuda/detail/bulk/detail/config.hpp>
#include <thrust/system/cuda/detail/bulk/detail/cuda_launcher/runtime_introspection.hpp>
#include <thrust/system/cuda/detail/bulk/detail/throw_on_error.hpp>
#include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
#include <thrust/detail/util/blocking.h>
#include <thrust/detail/minmax.h>
#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
BULK_NAMESPACE_PREFIX
namespace bulk
{
namespace detail
{
__host__ __device__
inline device_properties_t device_properties_uncached(int device_id)
{
device_properties_t prop = {0,{0,0,0},0,0,0,0,0,0,0};
cudaError_t error = cudaErrorNoDevice;
#if __BULK_HAS_CUDART__
error = cudaDeviceGetAttribute(&prop.major, cudaDevAttrComputeCapabilityMajor, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[0], cudaDevAttrMaxGridDimX, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[1], cudaDevAttrMaxGridDimY, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[2], cudaDevAttrMaxGridDimZ, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerBlock, cudaDevAttrMaxThreadsPerBlock, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerMultiProcessor, cudaDevAttrMaxThreadsPerMultiProcessor, device_id);
error = cudaDeviceGetAttribute(&prop.minor, cudaDevAttrComputeCapabilityMinor, device_id);
error = cudaDeviceGetAttribute(&prop.multiProcessorCount, cudaDevAttrMultiProcessorCount, device_id);
error = cudaDeviceGetAttribute(&prop.regsPerBlock, cudaDevAttrMaxRegistersPerBlock, device_id);
int temp;
error = cudaDeviceGetAttribute(&temp, cudaDevAttrMaxSharedMemoryPerBlock, device_id);
prop.sharedMemPerBlock = temp;
error = cudaDeviceGetAttribute(&prop.warpSize, cudaDevAttrWarpSize, device_id);
#else
(void) device_id; // Surpress unused parameter warnings
#endif
throw_on_error(error, "cudaDeviceGetProperty in get_device_properties");
return prop;
}
inline device_properties_t device_properties_cached(int device_id)
{
// cache the result of get_device_properties, because it is slow
// only cache the first few devices
static const int max_num_devices = 16;
static bool properties_exist[max_num_devices] = {0};
static device_properties_t device_properties[max_num_devices] = {};
if(device_id >= max_num_devices)
{
return device_properties_uncached(device_id);
}
if(!properties_exist[device_id])
{
device_properties[device_id] = device_properties_uncached(device_id);
// disallow the compiler to move the write to properties_exist[device_id]
// before the initialization of device_properties[device_id]
__thrust_compiler_fence();
properties_exist[device_id] = true;
}
return device_properties[device_id];
}
__host__ __device__
inline device_properties_t device_properties(int device_id)
{
#ifndef __CUDA_ARCH__
return device_properties_cached(device_id);
#else
return device_properties_uncached(device_id);
#endif
}
__host__ __device__
inline int current_device()
{
int result = -1;
#if __BULK_HAS_CUDART__
bulk::detail::throw_on_error(cudaGetDevice(&result), "current_device(): after cudaGetDevice");
#endif
if(result < 0)
{
bulk::detail::throw_on_error(cudaErrorNoDevice, "current_device(): after cudaGetDevice");
}
return result;
}
__host__ __device__
inline device_properties_t device_properties()
{
return device_properties(current_device());
}
template <typename KernelFunction>
__host__ __device__
inline function_attributes_t function_attributes(KernelFunction kernel)
{
#if __BULK_HAS_CUDART__
typedef void (*fun_ptr_type)();
fun_ptr_type fun_ptr = reinterpret_cast<fun_ptr_type>(kernel);
cudaFuncAttributes attributes;
bulk::detail::throw_on_error(cudaFuncGetAttributes(&attributes, fun_ptr), "function_attributes(): after cudaFuncGetAttributes");
// be careful about how this is initialized!
function_attributes_t result = {
attributes.constSizeBytes,
attributes.localSizeBytes,
attributes.maxThreadsPerBlock,
attributes.numRegs,
attributes.ptxVersion,
attributes.sharedSizeBytes
};
return result;
#else
return function_attributes_t();
#endif // __CUDACC__
}
__host__ __device__
inline size_t compute_capability(const device_properties_t &properties)
{
return 10 * properties.major + properties.minor;
}
__host__ __device__
inline size_t compute_capability()
{
return compute_capability(device_properties());
}
} // end namespace detail
} // end namespace bulk
BULK_NAMESPACE_SUFFIX
<|endoftext|> |
<commit_before><commit_msg>Create Lab_02_Question_11.cpp<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <cxxopts.hpp>
#include <Poco/Thread.h>
#include <Poco/Util/Application.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <Poco/Util/OptionCallback.h>
#include <fun.h>
using namespace std;
using namespace fun;
using namespace Poco;
//using Poco::Util::Application;
//using Poco::Util::Option;
//using Poco::Util::OptionSet;
//using Poco::Util::HelpFormatter;
//using Poco::Util::AbstractConfiguration;
//using Poco::Util::OptionCallback;
//using Poco::AutoPtr;
class ConsoleDebugger : public Debugger {
public:
ConsoleDebugger(Printer* printer): Debugger(printer) {
}
virtual ~ConsoleDebugger() {
}
virtual void onOperandsChanged(const std::vector<Terminal*> &operands) override {
}
virtual void onMemoryChanged(const std::unordered_map<std::string, Terminal*>& memory) override {
}
virtual void onCatchBreakpoint(const Breakpoint &breakpoint) override {
}
};
bool parseAndRunCode(Visitor* visitor, const string& filename, istream& inputStream, bool debug) {
Lexer lexer(filename, &inputStream);
Ast ast;
Parser parser(lexer, &ast);
parser.set_debug_level(debug);
bool result = parser.parse();
ast.accept(visitor);
return result;
}
//class FunCommandLineFrontendApplication: public Poco::Util::Application {
//public:
// FunCommandLineFrontendApplication(): _helpRequested(false)
// {
// }
//
//protected:
// void initialize(Application& self)
// {
// loadConfiguration(); // load default configuration files, if present
// Application::initialize(self);
// // add your own initialization code here
// }
//
// void uninitialize()
// {
// // add your own uninitialization code here
// Application::uninitialize();
// }
//
// void reinitialize(Application& self)
// {
// Application::reinitialize(self);
// // add your own reinitialization code here
// }
//
// void defineOptions(OptionSet& options)
// {
// Application::defineOptions(options);
//
// options.addOption(
// Option("help", "h", "display help information on command line arguments")
// .required(false)
// .repeatable(false)
// .callback(OptionCallback<FunCommandLineFrontendApplication>(this, &FunCommandLineFrontendApplication::handleHelp)));
//
// options.addOption(
// Option("define", "D", "define a configuration property")
// .required(false)
// .repeatable(true)
// .argument("name=value")
// .callback(OptionCallback<FunCommandLineFrontendApplication>(this, &FunCommandLineFrontendApplication::handleDefine)));
//
// options.addOption(
// Option("config-file", "f", "load configuration data from a file")
// .required(false)
// .repeatable(true)
// .argument("file")
// .callback(OptionCallback<FunCommandLineFrontendApplication>(this, &FunCommandLineFrontendApplication::handleConfig)));
//
// options.addOption(
// Option("bind", "b", "bind option value to test.property")
// .required(false)
// .repeatable(false)
// .argument("value")
// .binding("test.property"));
// }
//
// void handleHelp(const std::string& name, const std::string& value) {
// _helpRequested = true;
// displayHelp();
// stopOptionsProcessing();
// }
//
// void handleDefine(const std::string& name, const std::string& value) {
// defineProperty(value);
// }
//
// void handleConfig(const std::string& name, const std::string& value) {
// loadConfiguration(value);
// }
//
// void displayHelp() {
// HelpFormatter helpFormatter(options());
// helpFormatter.setCommand(commandName());
// helpFormatter.setUsage("OPTIONS");
// helpFormatter.setHeader(
// "A sample application that demonstrates some of the features of the Poco::Util::Application class.");
// helpFormatter.format(std::cout);
// }
//
// void defineProperty(const std::string& def)
// {
// std::string name;
// std::string value;
// std::string::size_type pos = def.find('=');
// if (pos != std::string::npos)
// {
// name.assign(def, 0, pos);
// value.assign(def, pos + 1, def.length() - pos);
// }
// else name = def;
// config().setString(name, value);
// }
//
// int main(const ArgVec& args)
// {
// if (!_helpRequested)
// {
// logger().information("Command line:");
// std::ostringstream ostr;
// for (auto& arg: argv)
// {
// ostr << arg << ' ';
// }
// logger().information(ostr.str());
// logger().information("Arguments to main():");
// for (auto& arg: args)
// {
// logger().information(arg);
// }
// logger().information("Application properties:");
// printProperties("");
// }
// return Application::EXIT_OK;
// }
//
// void printProperties(const std::string& base)
// {
// AbstractConfiguration::Keys keys;
// config().keys(base, keys);
// if (keys.empty())
// {
// if (config().hasProperty(base))
// {
// std::string msg;
// msg.append(base);
// msg.append(" = ");
// msg.append(config().getString(base));
// logger().information(msg);
// }
// }
// else
// {
// for (auto& key: keys)
// {
// std::string fullKey = base;
// if (!fullKey.empty()) fullKey += '.';
// fullKey.append();
// printProperties(fullKey);
// }
// }
// }
//
//private:
// bool _helpRequested;
//};
//
//POCO_APP_MAIN(FunCommandLineFrontendApplication)
int main(int argc, char* argv[]) {
try {
cxxopts::Options options(argv[0], "Fun - command line options");
options.add_options("")
("h,help", "Help")
("f,file", "Input file", cxxopts::value<std::string>())
("r,run", "Interpret script")
("c,compile", "Compile script")
("d,debug", "Enable debug");
options.parse(argc, argv);
if (options.count("help")) {
cout << options.help({ "" }) << endl;
}
Printer printer;
ConsoleDebugger consoleDebugger(&printer);
Interpreter interpret(options.count("debug") ? &consoleDebugger : nullptr);
Compiler compiler;
Visitor* visitor = nullptr;
if (options.count("run"))
visitor = &interpret;
else if (options.count("compile"))
visitor = &compiler;
else
visitor = &printer;
auto& filename = options["file"].as<string>();
ifstream file(filename);
if (options.count("file") && file.is_open()) {
// if(options.count("debug")) // FIXME
// consoleDebugger.setBreakpoint({"", 1});
Thread th;
th.startFunc([visitor, &file, &options, &filename]{
try {
parseAndRunCode(visitor, filename, file, false);
} catch (std::exception &e) {
cerr << e.what() << endl;
}
});
static map<Terminal::Type, string> types{
{Terminal::Type::Boolean, "Boolean"},
{Terminal::Type::String, "String"},
{Terminal::Type::Integer, "Integer"},
{Terminal::Type::Real, "Real"},
{Terminal::Type::Nil, "Nil"},
{Terminal::Type::Function, "Function"},
{Terminal::Type::Object, "Object"},
};
vector<string> lastCmd;
while(options.count("debug")){
cout << ">>> ";
string input;
getline(cin, input);
stringstream ss;
ss << input;
string token;
vector<string> tokens;
while (ss >> token) {
tokens.push_back(token);
}
auto run = [&consoleDebugger] {
consoleDebugger.resume();
return 1;
};
auto stepInto = [] {
cout << "step into" << endl;
return 1;
};
auto stepOver = [&consoleDebugger] {
consoleDebugger.stepOver();
consoleDebugger.list();
return 1;
};
auto operandsCmd = [&interpret] {
cout << "########### Operands ###########" << endl;
for (auto &i: interpret.getOperands()) cout << types[i->getType()] << ": " << i->toString() << endl;
cout << "################################" << endl;
return 1;
};
auto quitCmd = []{
return 0;
};
auto listCmd = [&consoleDebugger]{
consoleDebugger.list();
return 1;
};
auto breakpointCmd = [&tokens, &consoleDebugger]{
cout << "breakpoint " << tokens.size() << endl;
if(tokens.size() < 2)
throw std::runtime_error("breakpoint command not enough arguments; Usage: b 100");
stringstream ss;
ss << tokens[1];
unsigned int line = 0;
ss >> line;
consoleDebugger.setBreakpoint(line);
return 1;
};
auto variablesCmd = [&interpret] {
cout << "########### Memory #############" << endl;
int indents = 0;
for (auto &scope: interpret.getMemory()) {
for (auto &var: scope) {
cout << [&indents] {
stringstream ss;
for (int n = 0; n < indents; ++n)
ss << " ";
return ss.str();
}() << types[var.second->getType()] << " " << var.first << " == " <<
var.second->toString() << " (" << var.second->referenceCount() << ")" << endl;
}
indents++;
}
cout << "################################" << endl;
return 1;
};
unordered_map<string, function<int()>> commands{
{"run", run},
{"r", run},
{"si", stepInto},
{"stepin", stepInto},
{"so", stepOver},
{"stepover", stepOver},
{"ops", operandsCmd},
{"operands", operandsCmd},
{"vars", variablesCmd},
{"variables", variablesCmd},
{"breakpoint", breakpointCmd},
{"b", breakpointCmd},
{"quit", quitCmd},
{"list", listCmd},
{"l", listCmd},
};
if (tokens.empty())
if(lastCmd.empty()) {
continue;
} else {
tokens = lastCmd;
}
auto cmdIt = commands.find(tokens.at(0));
if(cmdIt == commands.end())
continue;
if (cmdIt->second()) {
} else {
break;
}
lastCmd = tokens;
}
if (th.isRunning()) {
th.join();
}
} else {
stringstream sourceStream;
while (true) {
cout << ">>> ";
string input;
getline(cin, input);
if (input == "quit") {
return 0;
} else if (!input.empty()) {
sourceStream << input << endl;
continue;
}
parseAndRunCode(visitor, {}, sourceStream, options.count("debug"));
sourceStream.clear();
}
}
return 0;
} catch (const cxxopts::OptionException& e) {
cerr << e.what() << endl;
return 1;
} catch (const std::exception& e) {
cerr << e.what() << endl;
return 1;
}
}
<commit_msg>переделал консольный фронтенд на поко, пока что по простому<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <Poco/Thread.h>
#include <Poco/Util/Application.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <Poco/Util/OptionCallback.h>
#include <fun.h>
using namespace std;
using namespace fun;
using namespace Poco;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;
using Poco::Util::AbstractConfiguration;
using Poco::Util::OptionCallback;
using Poco::AutoPtr;
class ConsoleDebugger : public Debugger {
public:
ConsoleDebugger(Printer* printer): Debugger(printer) {
}
virtual ~ConsoleDebugger() {
}
virtual void onOperandsChanged(const std::vector<Terminal*> &operands) override {
}
virtual void onMemoryChanged(const std::unordered_map<std::string, Terminal*>& memory) override {
}
virtual void onCatchBreakpoint(const Breakpoint &breakpoint) override {
}
};
bool parseAndRunCode(Visitor* visitor, const string& filename, istream& inputStream, bool debug) {
Lexer lexer(filename, &inputStream);
Ast ast;
Parser parser(lexer, &ast);
parser.set_debug_level(debug);
bool result = parser.parse();
ast.accept(visitor);
return result;
}
class FunApplication: public Poco::Util::Application {
public:
FunApplication() {
}
protected:
void initialize(Application& self) {
Application::initialize(self);
}
void uninitialize() {
Application::uninitialize();
}
void reinitialize(Application& self) {
Application::reinitialize(self);
}
void defineOptions(OptionSet& options) {
Application::defineOptions(options);
options.addOption(
Option("help", "h", "help information")
.required(false)
.repeatable(false)
.callback(OptionCallback<FunApplication>(this, &FunApplication::handleHelp)));
options.addOption(
Option("debug", "d", "debug mode")
.required(false)
.repeatable(false)
.callback(OptionCallback<FunApplication>(this, &FunApplication::handleDebug)));
options.addOption(
Option("file", "f", "input script")
.required(true)
.repeatable(false)
.argument("file", true)
.callback(OptionCallback<FunApplication>(this, &FunApplication::handleScript)));
options.addOption(
Option("watch", "w", "watch for auto reload")
.callback(OptionCallback<FunApplication>(this, &FunApplication::handleWatch))
);
}
void handleHelp(const std::string& name, const std::string& value) {
cout << __PRETTY_FUNCTION__ << ", " << name << ": " << value << endl;
}
void handleDebug(const std::string& name, const std::string& value) {
cout << __PRETTY_FUNCTION__ << ", " << name << ": " << value << endl;
}
void handleWatch(const std::string& name, const std::string& value) {
cout << __PRETTY_FUNCTION__ << ", " << name << ": " << value << endl;
}
void handleScript(const std::string& name, const std::string& value) {
scriptFileName = value;
}
void displayHelp() {
// HelpFormatter helpFormatter(options());
// helpFormatter.setCommand(commandName());
// helpFormatter.setUsage("OPTIONS");
// helpFormatter.setHeader(
// "A sample application that demonstrates some of the features of the Poco::Util::Application class.");
// helpFormatter.format(std::cout);
}
int main(const ArgVec& args) {
try {
Printer printer;
ConsoleDebugger consoleDebugger(&printer);
Interpreter interpret(nullptr);
Compiler compiler;
Visitor* visitor = &interpret;
string filename = scriptFileName;
if (scriptFileName.empty())
throw std::runtime_error("no input file");
ifstream file(filename);
Thread th;
th.startFunc([visitor, &file, &filename] {
try {
parseAndRunCode(visitor, filename, file, false);
} catch (std::exception &e) {
cerr << e.what() << endl;
}
});
if (th.isRunning()) {
th.join();
}
return Application::EXIT_OK;
} catch (exception const& e) {
return Application::EXIT_SOFTWARE;
}
}
private:
string scriptFileName;
};
POCO_APP_MAIN(FunApplication)
/*
int main(int argc, char* argv[]) {
try {
cxxopts::Options options(argv[0], "Fun - command line options");
options.add_options("")
("h,help", "Help")
("f,file", "Input file", cxxopts::value<std::string>())
("r,run", "Interpret script")
("c,compile", "Compile script")
("d,debug", "Enable debug");
options.parse(argc, argv);
if (options.count("help")) {
cout << options.help({ "" }) << endl;
}
Printer printer;
ConsoleDebugger consoleDebugger(&printer);
Interpreter interpret(options.count("debug") ? &consoleDebugger : nullptr);
Compiler compiler;
Visitor* visitor = nullptr;
if (options.count("run"))
visitor = &interpret;
else if (options.count("compile"))
visitor = &compiler;
else
visitor = &printer;
auto& filename = options["file"].as<string>();
ifstream file(filename);
if (options.count("file") && file.is_open()) {
// if(options.count("debug")) // FIXME
// consoleDebugger.setBreakpoint({"", 1});
Thread th;
th.startFunc([visitor, &file, &options, &filename]{
try {
parseAndRunCode(visitor, filename, file, false);
} catch (std::exception &e) {
cerr << e.what() << endl;
}
});
static map<Terminal::Type, string> types{
{Terminal::Type::Boolean, "Boolean"},
{Terminal::Type::String, "String"},
{Terminal::Type::Integer, "Integer"},
{Terminal::Type::Real, "Real"},
{Terminal::Type::Nil, "Nil"},
{Terminal::Type::Function, "Function"},
{Terminal::Type::Object, "Object"},
};
vector<string> lastCmd;
while(options.count("debug")){
cout << ">>> ";
string input;
getline(cin, input);
stringstream ss;
ss << input;
string token;
vector<string> tokens;
while (ss >> token) {
tokens.push_back(token);
}
auto run = [&consoleDebugger] {
consoleDebugger.resume();
return 1;
};
auto stepInto = [] {
cout << "step into" << endl;
return 1;
};
auto stepOver = [&consoleDebugger] {
consoleDebugger.stepOver();
consoleDebugger.list();
return 1;
};
auto operandsCmd = [&interpret] {
cout << "########### Operands ###########" << endl;
for (auto &i: interpret.getOperands()) cout << types[i->getType()] << ": " << i->toString() << endl;
cout << "################################" << endl;
return 1;
};
auto quitCmd = []{
return 0;
};
auto listCmd = [&consoleDebugger]{
consoleDebugger.list();
return 1;
};
auto breakpointCmd = [&tokens, &consoleDebugger]{
cout << "breakpoint " << tokens.size() << endl;
if(tokens.size() < 2)
throw std::runtime_error("breakpoint command not enough arguments; Usage: b 100");
stringstream ss;
ss << tokens[1];
unsigned int line = 0;
ss >> line;
consoleDebugger.setBreakpoint(line);
return 1;
};
auto variablesCmd = [&interpret] {
cout << "########### Memory #############" << endl;
int indents = 0;
for (auto &scope: interpret.getMemory()) {
for (auto &var: scope) {
cout << [&indents] {
stringstream ss;
for (int n = 0; n < indents; ++n)
ss << " ";
return ss.str();
}() << types[var.second->getType()] << " " << var.first << " == " <<
var.second->toString() << " (" << var.second->referenceCount() << ")" << endl;
}
indents++;
}
cout << "################################" << endl;
return 1;
};
unordered_map<string, function<int()>> commands{
{"run", run},
{"r", run},
{"si", stepInto},
{"stepin", stepInto},
{"so", stepOver},
{"stepover", stepOver},
{"ops", operandsCmd},
{"operands", operandsCmd},
{"vars", variablesCmd},
{"variables", variablesCmd},
{"breakpoint", breakpointCmd},
{"b", breakpointCmd},
{"quit", quitCmd},
{"list", listCmd},
{"l", listCmd},
};
if (tokens.empty())
if(lastCmd.empty()) {
continue;
} else {
tokens = lastCmd;
}
auto cmdIt = commands.find(tokens.at(0));
if(cmdIt == commands.end())
continue;
if (cmdIt->second()) {
} else {
break;
}
lastCmd = tokens;
}
if (th.isRunning()) {
th.join();
}
} else {
stringstream sourceStream;
while (true) {
cout << ">>> ";
string input;
getline(cin, input);
if (input == "quit") {
return 0;
} else if (!input.empty()) {
sourceStream << input << endl;
continue;
}
parseAndRunCode(visitor, {}, sourceStream, options.count("debug"));
sourceStream.clear();
}
}
return 0;
} catch (const cxxopts::OptionException& e) {
cerr << e.what() << endl;
return 1;
} catch (const std::exception& e) {
cerr << e.what() << endl;
return 1;
}
}
*/
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <[email protected]>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtgridlayout.h"
#include <QDebug>
#include <math.h>
#include <QWidget>
using namespace LxQt;
class LxQt::GridLayoutPrivate
{
public:
GridLayoutPrivate();
QList<QLayoutItem*> mItems;
int mRowCount;
int mColumnCount;
GridLayout::Direction mDirection;
bool mIsValid;
QSize mCellSizeHint;
QSize mCellMaxSize;
int mVisibleCount;
GridLayout::Stretch mStretch;
void updateCache();
int rows() const;
int cols() const;
QSize mPrefCellMinSize;
QSize mPrefCellMaxSize;
};
/************************************************
************************************************/
GridLayoutPrivate::GridLayoutPrivate()
{
mColumnCount = 0;
mRowCount = 0;
mDirection = GridLayout::LeftToRight;
mIsValid = false;
mVisibleCount = 0;
mStretch = GridLayout::StretchHorizontal | GridLayout::StretchVertical;
mPrefCellMinSize = QSize(0,0);
mPrefCellMaxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
/************************************************
************************************************/
void GridLayoutPrivate::updateCache()
{
mCellSizeHint = QSize(0, 0);
mCellMaxSize = QSize(0, 0);
mVisibleCount = 0;
for (int i=0; i<mItems.count(); ++i)
{
QLayoutItem *item = mItems.at(i);
if (!item->widget() || item->widget()->isHidden())
continue;
int h = qBound(item->minimumSize().height(),
item->sizeHint().height(),
item->maximumSize().height());
int w = qBound(item->minimumSize().width(),
item->sizeHint().width(),
item->maximumSize().width());
mCellSizeHint.rheight() = qMax(mCellSizeHint.height(), h);
mCellSizeHint.rwidth() = qMax(mCellSizeHint.width(), w);
mCellMaxSize.rheight() = qMax(mCellMaxSize.height(), item->maximumSize().height());
mCellMaxSize.rwidth() = qMax(mCellMaxSize.width(), item->maximumSize().width());
mVisibleCount++;
#if 0
qDebug() << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-";
qDebug() << "item.min" << item->minimumSize().width();
qDebug() << "item.sz " << item->sizeHint().width();
qDebug() << "item.max" << item->maximumSize().width();
qDebug() << "w h" << w << h;
qDebug() << "wid.sizeHint" << item->widget()->sizeHint();
qDebug() << "mCellSizeHint:" << mCellSizeHint;
qDebug() << "mCellMaxSize: " << mCellMaxSize;
qDebug() << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-";
#endif
}
mCellSizeHint.rwidth() = qBound(mPrefCellMinSize.width(), mCellSizeHint.width(), mPrefCellMaxSize.width());
mCellSizeHint.rheight()= qBound(mPrefCellMinSize.height(), mCellSizeHint.height(), mPrefCellMaxSize.height());
mIsValid = !mCellSizeHint.isEmpty();
}
/************************************************
************************************************/
int GridLayoutPrivate::rows() const
{
if (mRowCount)
return mRowCount;
if (!mColumnCount)
return 1;
return ceil(mVisibleCount * 1.0 / mColumnCount);
}
/************************************************
************************************************/
int GridLayoutPrivate::cols() const
{
if (mColumnCount)
return mColumnCount;
int rows = mRowCount;
if (!rows)
rows = 1;
return ceil(mVisibleCount * 1.0 / rows);
}
/************************************************
************************************************/
GridLayout::GridLayout(QWidget *parent):
QLayout(parent),
d_ptr(new GridLayoutPrivate())
{
}
/************************************************
************************************************/
GridLayout::~GridLayout()
{
delete d_ptr;
}
/************************************************
************************************************/
void GridLayout::addItem(QLayoutItem *item)
{
d_ptr->mItems.append(item);
}
/************************************************
************************************************/
QLayoutItem *GridLayout::itemAt(int index) const
{
Q_D(const GridLayout);
if (index < 0 || index >= d->mItems.count())
return 0;
return d->mItems.at(index);
}
/************************************************
************************************************/
QLayoutItem *GridLayout::takeAt(int index)
{
Q_D(GridLayout);
if (index < 0 || index >= d->mItems.count())
return 0;
QLayoutItem *item = d->mItems.takeAt(index);
return item;
}
/************************************************
************************************************/
int GridLayout::count() const
{
Q_D(const GridLayout);
return d->mItems.count();
}
/************************************************
************************************************/
void GridLayout::invalidate()
{
Q_D(GridLayout);
d->mIsValid = false;
QLayout::invalidate();
}
/************************************************
************************************************/
int GridLayout::rowCount() const
{
Q_D(const GridLayout);
return d->mRowCount;
}
/************************************************
************************************************/
void GridLayout::setRowCount(int value)
{
Q_D(GridLayout);
if (d->mRowCount != value)
{
d->mRowCount = value;
invalidate();
}
}
/************************************************
************************************************/
int GridLayout::columnCount() const
{
Q_D(const GridLayout);
return d->mColumnCount;
}
/************************************************
************************************************/
void GridLayout::setColumnCount(int value)
{
Q_D(GridLayout);
if (d->mColumnCount != value)
{
d->mColumnCount = value;
invalidate();
}
}
/************************************************
************************************************/
GridLayout::Direction GridLayout::direction() const
{
Q_D(const GridLayout);
return d->mDirection;
}
/************************************************
************************************************/
void GridLayout::setDirection(GridLayout::Direction value)
{
Q_D(GridLayout);
if (d->mDirection != value)
{
d->mDirection = value;
invalidate();
}
}
/************************************************
************************************************/
GridLayout::Stretch GridLayout::stretch() const
{
Q_D(const GridLayout);
return d->mStretch;
}
/************************************************
************************************************/
void GridLayout::setStretch(Stretch value)
{
Q_D(GridLayout);
if (d->mStretch != value)
{
d->mStretch = value;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::moveItem(int from, int to)
{
Q_D(GridLayout);
d->mItems.move(from, to);
invalidate();
}
/************************************************
************************************************/
QSize GridLayout::cellMinimumSize() const
{
Q_D(const GridLayout);
return d->mPrefCellMinSize;
}
/************************************************
************************************************/
void GridLayout::setCellMinimumSize(QSize minSize)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize != minSize)
{
d->mPrefCellMinSize = minSize;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMinimumHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.height() != value)
{
d->mPrefCellMinSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMinimumWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.width() != value)
{
d->mPrefCellMinSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
QSize GridLayout::cellMaximumSize() const
{
Q_D(const GridLayout);
return d->mPrefCellMaxSize;
}
/************************************************
************************************************/
void GridLayout::setCellMaximumSize(QSize maxSize)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize != maxSize)
{
d->mPrefCellMaxSize = maxSize;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMaximumHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize.height() != value)
{
d->mPrefCellMaxSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMaximumWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize.width() != value)
{
d->mPrefCellMaxSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedSize(QSize size)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize != size ||
d->mPrefCellMaxSize != size)
{
d->mPrefCellMinSize = size;
d->mPrefCellMaxSize = size;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.height() != value ||
d->mPrefCellMaxSize.height() != value)
{
d->mPrefCellMinSize.setHeight(value);
d->mPrefCellMaxSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.width() != value ||
d->mPrefCellMaxSize.width() != value)
{
d->mPrefCellMinSize.setWidth(value);
d->mPrefCellMaxSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
QSize GridLayout::sizeHint() const
{
Q_D(const GridLayout);
if (!d->mIsValid)
const_cast<GridLayoutPrivate*>(d)->updateCache();
return QSize(d->cols() * d->mCellSizeHint.width(),
d->rows() * d->mCellSizeHint.height());
}
/************************************************
************************************************/
void GridLayout::setGeometry(const QRect &geometry)
{
Q_D(GridLayout);
if (!d->mIsValid)
d->updateCache();
int y = geometry.top();
int x = geometry.left();
// For historical reasons QRect::right returns left() + width() - 1
// and QRect::bottom() returns top() + height() - 1;
// So we use left() + height() and top() + height()
//
// http://qt-project.org/doc/qt-4.8/qrect.html
int maxX = geometry.left() + geometry.width();
int maxY = geometry.top() + geometry.height();
int itemWidth;
if (d->mStretch.testFlag(StretchHorizontal))
{
itemWidth = geometry.width() * 1.0 / d->cols();
itemWidth = qMin(itemWidth, d->mCellMaxSize.width());
}
else
{
itemWidth = d->mCellSizeHint.width();
}
itemWidth = qBound(d->mPrefCellMinSize.width(), itemWidth, d->mPrefCellMaxSize.width());
int itemHeight;
if (d->mStretch.testFlag(StretchVertical))
{
itemHeight = geometry.height() * 1.0 / d->rows();
itemHeight = qMin(itemHeight, d->mCellMaxSize.height());
}
else
{
itemHeight = d->mCellSizeHint.height();
}
itemHeight = qBound(d->mPrefCellMinSize.height(), itemHeight, d->mPrefCellMaxSize.height());
#if 0
qDebug() << "** GridLayout::setGeometry *******************************";
qDebug() << "Geometry:" << geometry;
qDebug() << "CellSize:" << d->mCellSizeHint;
qDebug() << "Constraints:" << "min" << d->mPrefCellMinSize << "max" << d->mPrefCellMaxSize;
qDebug() << "Count" << count();
qDebug() << "Cols:" << d->cols() << "(" << d->mColumnCount << ")";
qDebug() << "Rows:" << d->rows() << "(" << d->mRowCount << ")";
qDebug() << "Stretch:" << "h:" << (d->mStretch.testFlag(StretchHorizontal)) << " v:" << (d->mStretch.testFlag(StretchVertical));
qDebug() << "Item:" << "h:" << itemHeight << " w:" << itemWidth;
#endif
if (d->mDirection == LeftToRight)
{
foreach(QLayoutItem *item, d->mItems)
{
if (!item->widget() || item->widget()->isHidden())
continue;
if (x + itemWidth > maxX)
{
x = geometry.left();
if (d->mStretch.testFlag(StretchVertical))
y += geometry.height() / d->rows();
else
y += itemHeight;
}
item->setGeometry(QRect(x, y, itemWidth, itemHeight));
x += itemWidth;
}
}
else
{
foreach(QLayoutItem *item, d->mItems)
{
if (!item->widget() || item->widget()->isHidden())
continue;
if (y + itemHeight > maxY)
{
y = geometry.top();
if (d->mStretch.testFlag(StretchHorizontal))
x += geometry.width() / d->cols();
else
x += itemWidth;
}
item->setGeometry(QRect(x, y, itemWidth, itemHeight));
y += itemHeight;
}
}
}
<commit_msg>gridlayout: avoid empty margins when stretching is active<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <[email protected]>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtgridlayout.h"
#include <QDebug>
#include <math.h>
#include <QWidget>
using namespace LxQt;
class LxQt::GridLayoutPrivate
{
public:
GridLayoutPrivate();
QList<QLayoutItem*> mItems;
int mRowCount;
int mColumnCount;
GridLayout::Direction mDirection;
bool mIsValid;
QSize mCellSizeHint;
QSize mCellMaxSize;
int mVisibleCount;
GridLayout::Stretch mStretch;
void updateCache();
int rows() const;
int cols() const;
QSize mPrefCellMinSize;
QSize mPrefCellMaxSize;
};
/************************************************
************************************************/
GridLayoutPrivate::GridLayoutPrivate()
{
mColumnCount = 0;
mRowCount = 0;
mDirection = GridLayout::LeftToRight;
mIsValid = false;
mVisibleCount = 0;
mStretch = GridLayout::StretchHorizontal | GridLayout::StretchVertical;
mPrefCellMinSize = QSize(0,0);
mPrefCellMaxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
/************************************************
************************************************/
void GridLayoutPrivate::updateCache()
{
mCellSizeHint = QSize(0, 0);
mCellMaxSize = QSize(0, 0);
mVisibleCount = 0;
for (int i=0; i<mItems.count(); ++i)
{
QLayoutItem *item = mItems.at(i);
if (!item->widget() || item->widget()->isHidden())
continue;
int h = qBound(item->minimumSize().height(),
item->sizeHint().height(),
item->maximumSize().height());
int w = qBound(item->minimumSize().width(),
item->sizeHint().width(),
item->maximumSize().width());
mCellSizeHint.rheight() = qMax(mCellSizeHint.height(), h);
mCellSizeHint.rwidth() = qMax(mCellSizeHint.width(), w);
mCellMaxSize.rheight() = qMax(mCellMaxSize.height(), item->maximumSize().height());
mCellMaxSize.rwidth() = qMax(mCellMaxSize.width(), item->maximumSize().width());
mVisibleCount++;
#if 0
qDebug() << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-";
qDebug() << "item.min" << item->minimumSize().width();
qDebug() << "item.sz " << item->sizeHint().width();
qDebug() << "item.max" << item->maximumSize().width();
qDebug() << "w h" << w << h;
qDebug() << "wid.sizeHint" << item->widget()->sizeHint();
qDebug() << "mCellSizeHint:" << mCellSizeHint;
qDebug() << "mCellMaxSize: " << mCellMaxSize;
qDebug() << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-";
#endif
}
mCellSizeHint.rwidth() = qBound(mPrefCellMinSize.width(), mCellSizeHint.width(), mPrefCellMaxSize.width());
mCellSizeHint.rheight()= qBound(mPrefCellMinSize.height(), mCellSizeHint.height(), mPrefCellMaxSize.height());
mIsValid = !mCellSizeHint.isEmpty();
}
/************************************************
************************************************/
int GridLayoutPrivate::rows() const
{
if (mRowCount)
return mRowCount;
if (!mColumnCount)
return 1;
return ceil(mVisibleCount * 1.0 / mColumnCount);
}
/************************************************
************************************************/
int GridLayoutPrivate::cols() const
{
if (mColumnCount)
return mColumnCount;
int rows = mRowCount;
if (!rows)
rows = 1;
return ceil(mVisibleCount * 1.0 / rows);
}
/************************************************
************************************************/
GridLayout::GridLayout(QWidget *parent):
QLayout(parent),
d_ptr(new GridLayoutPrivate())
{
}
/************************************************
************************************************/
GridLayout::~GridLayout()
{
delete d_ptr;
}
/************************************************
************************************************/
void GridLayout::addItem(QLayoutItem *item)
{
d_ptr->mItems.append(item);
}
/************************************************
************************************************/
QLayoutItem *GridLayout::itemAt(int index) const
{
Q_D(const GridLayout);
if (index < 0 || index >= d->mItems.count())
return 0;
return d->mItems.at(index);
}
/************************************************
************************************************/
QLayoutItem *GridLayout::takeAt(int index)
{
Q_D(GridLayout);
if (index < 0 || index >= d->mItems.count())
return 0;
QLayoutItem *item = d->mItems.takeAt(index);
return item;
}
/************************************************
************************************************/
int GridLayout::count() const
{
Q_D(const GridLayout);
return d->mItems.count();
}
/************************************************
************************************************/
void GridLayout::invalidate()
{
Q_D(GridLayout);
d->mIsValid = false;
QLayout::invalidate();
}
/************************************************
************************************************/
int GridLayout::rowCount() const
{
Q_D(const GridLayout);
return d->mRowCount;
}
/************************************************
************************************************/
void GridLayout::setRowCount(int value)
{
Q_D(GridLayout);
if (d->mRowCount != value)
{
d->mRowCount = value;
invalidate();
}
}
/************************************************
************************************************/
int GridLayout::columnCount() const
{
Q_D(const GridLayout);
return d->mColumnCount;
}
/************************************************
************************************************/
void GridLayout::setColumnCount(int value)
{
Q_D(GridLayout);
if (d->mColumnCount != value)
{
d->mColumnCount = value;
invalidate();
}
}
/************************************************
************************************************/
GridLayout::Direction GridLayout::direction() const
{
Q_D(const GridLayout);
return d->mDirection;
}
/************************************************
************************************************/
void GridLayout::setDirection(GridLayout::Direction value)
{
Q_D(GridLayout);
if (d->mDirection != value)
{
d->mDirection = value;
invalidate();
}
}
/************************************************
************************************************/
GridLayout::Stretch GridLayout::stretch() const
{
Q_D(const GridLayout);
return d->mStretch;
}
/************************************************
************************************************/
void GridLayout::setStretch(Stretch value)
{
Q_D(GridLayout);
if (d->mStretch != value)
{
d->mStretch = value;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::moveItem(int from, int to)
{
Q_D(GridLayout);
d->mItems.move(from, to);
invalidate();
}
/************************************************
************************************************/
QSize GridLayout::cellMinimumSize() const
{
Q_D(const GridLayout);
return d->mPrefCellMinSize;
}
/************************************************
************************************************/
void GridLayout::setCellMinimumSize(QSize minSize)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize != minSize)
{
d->mPrefCellMinSize = minSize;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMinimumHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.height() != value)
{
d->mPrefCellMinSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMinimumWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.width() != value)
{
d->mPrefCellMinSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
QSize GridLayout::cellMaximumSize() const
{
Q_D(const GridLayout);
return d->mPrefCellMaxSize;
}
/************************************************
************************************************/
void GridLayout::setCellMaximumSize(QSize maxSize)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize != maxSize)
{
d->mPrefCellMaxSize = maxSize;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMaximumHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize.height() != value)
{
d->mPrefCellMaxSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellMaximumWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMaxSize.width() != value)
{
d->mPrefCellMaxSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedSize(QSize size)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize != size ||
d->mPrefCellMaxSize != size)
{
d->mPrefCellMinSize = size;
d->mPrefCellMaxSize = size;
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedHeight(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.height() != value ||
d->mPrefCellMaxSize.height() != value)
{
d->mPrefCellMinSize.setHeight(value);
d->mPrefCellMaxSize.setHeight(value);
invalidate();
}
}
/************************************************
************************************************/
void GridLayout::setCellFixedWidth(int value)
{
Q_D(GridLayout);
if (d->mPrefCellMinSize.width() != value ||
d->mPrefCellMaxSize.width() != value)
{
d->mPrefCellMinSize.setWidth(value);
d->mPrefCellMaxSize.setWidth(value);
invalidate();
}
}
/************************************************
************************************************/
QSize GridLayout::sizeHint() const
{
Q_D(const GridLayout);
if (!d->mIsValid)
const_cast<GridLayoutPrivate*>(d)->updateCache();
return QSize(d->cols() * d->mCellSizeHint.width(),
d->rows() * d->mCellSizeHint.height());
}
/************************************************
************************************************/
void GridLayout::setGeometry(const QRect &geometry)
{
Q_D(GridLayout);
if (!d->mIsValid)
d->updateCache();
int y = geometry.top();
int x = geometry.left();
// For historical reasons QRect::right returns left() + width() - 1
// and QRect::bottom() returns top() + height() - 1;
// So we use left() + height() and top() + height()
//
// http://qt-project.org/doc/qt-4.8/qrect.html
const int maxX = geometry.left() + geometry.width();
const int maxY = geometry.top() + geometry.height();
const bool stretch_h = d->mStretch.testFlag(StretchHorizontal);
const bool stretch_v = d->mStretch.testFlag(StretchVertical);
const int cols = d->cols();
QVector<int> itemWidths(cols);
{
int itemWidth = 0;
if (stretch_h && 0 < cols)
{
itemWidth = geometry.width() / cols;
itemWidth = qMin(itemWidth, d->mCellMaxSize.width());
}
else
{
itemWidth = d->mCellSizeHint.width();
}
itemWidth = qBound(d->mPrefCellMinSize.width(), itemWidth, d->mPrefCellMaxSize.width());
int width_remainder = stretch_h && 0 < itemWidth ? geometry.width() % itemWidth : 0;
for (auto & w : itemWidths)
{
w = itemWidth + (0 < width_remainder-- ? 1 : 0);
}
}
const int rows = d->rows();
QVector<int> itemHeights(rows);
{
int itemHeight = 0;
if (stretch_v && 0 < rows)
{
itemHeight = geometry.height() / rows;
itemHeight = qMin(itemHeight, d->mCellMaxSize.height());
}
else
{
itemHeight = d->mCellSizeHint.height();
}
itemHeight = qBound(d->mPrefCellMinSize.height(), itemHeight, d->mPrefCellMaxSize.height());
int height_remainder = stretch_v && 0 < itemHeight ? geometry.height() % itemHeight : 0;
for (auto & h : itemHeights)
{
h = itemHeight + (0 < height_remainder-- ? 1 : 0);
}
}
#if 0
qDebug() << "** GridLayout::setGeometry *******************************";
qDebug() << "Geometry:" << geometry;
qDebug() << "CellSize:" << d->mCellSizeHint;
qDebug() << "Constraints:" << "min" << d->mPrefCellMinSize << "max" << d->mPrefCellMaxSize;
qDebug() << "Count" << count();
qDebug() << "Cols:" << d->cols() << "(" << d->mColumnCount << ")";
qDebug() << "Rows:" << d->rows() << "(" << d->mRowCount << ")";
qDebug() << "Stretch:" << "h:" << (d->mStretch.testFlag(StretchHorizontal)) << " v:" << (d->mStretch.testFlag(StretchVertical));
qDebug() << "Item:" << "h:" << itemHeight << " w:" << itemWidth;
#endif
int col, row;
if (d->mDirection == LeftToRight)
{
col = row = 0;
foreach(QLayoutItem *item, d->mItems)
{
if (!item->widget() || item->widget()->isHidden())
continue;
if (cols <= col || x + itemWidths[col] > maxX)
{
x = geometry.left();
y += itemHeights[row];
col = 0;
++row;
}
item->setGeometry(QRect(x, y, itemWidths[col], itemHeights[row]));
x += itemWidths[col];
++col;
}
}
else
{
col = row = 0;
foreach(QLayoutItem *item, d->mItems)
{
if (!item->widget() || item->widget()->isHidden())
continue;
if (rows <= row || y + itemHeights[row] > maxY)
{
y = geometry.top();
x += itemWidths[col];
row = 0;
++col;
}
item->setGeometry(QRect(x, y, itemWidths[col], itemHeights[row]));
y += itemHeights[row];
++row;
}
}
}
<|endoftext|> |
<commit_before>#include <atomic>
#include <map>
#include <set>
#include "block.hpp"
#include "hash.hpp"
#include "hvectors.hpp"
struct processFunctor_t {
virtual ~processFunctor_t () {}
virtual bool initialize (const char*) {
return false;
}
virtual void operator() (const Block&) = 0;
};
struct whitelisted_t : processFunctor_t {
HSet<hash256_t> whitelist;
bool initialize (const char* arg) {
if (strncmp(arg, "-w", 2) == 0) {
const auto fileName = std::string(arg + 2);
const auto file = fopen(fileName.c_str(), "r");
assert(file != nullptr);
fseek(file, 0, SEEK_END);
const auto fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
assert(sizeof(this->whitelist[0]) == 32);
assert(fileSize % sizeof(this->whitelist[0]) == 0);
this->whitelist.resize(fileSize / sizeof(hash256_t));
const auto read = fread(&this->whitelist[0], fileSize, 1, file);
assert(read == 1);
fclose(file);
assert(!this->whitelist.empty());
assert(std::is_sorted(this->whitelist.begin(), this->whitelist.end()));
std::cerr << "Whitelisted " << this->whitelist.size() << " hashes" << std::endl;
return true;
}
return false;
}
bool shouldSkip (const Block& block) const {
if (this->whitelist.empty()) return false;
hash256_t hash;
hash256(&hash[0], block.header);
return !this->whitelist.contains(hash);
}
bool shouldSkip (const hash256_t& hash) const {
if (this->whitelist.empty()) return false;
return !this->whitelist.contains(hash);
}
};
// XXX: fwrite can be used without sizeof(sbuf) < PIPE_BUF (4096 bytes)
// BLOCK_HEADER > stdout
struct dumpHeaders : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
fwrite(block.header.begin, 80, 1, stdout);
}
};
// SCRIPT_LENGTH | SCRIPT > stdout
struct dumpScripts : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[4096];
const auto maxScriptLength = sizeof(sbuf) - sizeof(uint16_t);
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& input : transaction.inputs) {
if (input.script.length() > maxScriptLength) continue;
const auto scriptLength = static_cast<uint16_t>(input.script.length());
Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength);
memcpy(sbuf + sizeof(uint16_t), input.script.begin, scriptLength);
fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
}
for (const auto& output : transaction.outputs) {
if (output.script.length() > maxScriptLength) continue;
const auto scriptLength = static_cast<uint16_t>(output.script.length());
Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength);
memcpy(sbuf + sizeof(uint16_t), output.script.begin, scriptLength);
fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
}
transactions.popFront();
}
}
};
// PREV_TX_HASH | PREV_TX_VOUT | TX_HASH > stdout
struct dumpTxOutIndex : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[68];
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(sbuf + 36, transaction.data);
for (const auto& input : transaction.inputs) {
memcpy(sbuf, input.hash.begin, 32);
Slice(sbuf + 32, sbuf + 36).put(input.vout);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
auto perc (uint64_t a, uint64_t ab) {
return static_cast<double>(a) / static_cast<double>(ab);
}
struct dumpStatistics : whitelisted_t {
std::atomic_ulong inputs;
std::atomic_ulong outputs;
std::atomic_ulong transactions;
std::atomic_ulong version1;
std::atomic_ulong version2;
std::atomic_ulong locktimesGt0;
dumpStatistics () {
this->inputs = 0;
this->outputs = 0;
this->transactions = 0;
this->version1 = 0;
this->version2 = 0;
this->locktimesGt0 = 0;
}
~dumpStatistics () {
std::cout <<
"Transactions:\t" << this->transactions << '\n' <<
"-- Inputs:\t" << this->inputs << " (ratio " << perc(this->inputs, this->transactions) << ") \n" <<
"-- Outputs:\t" << this->outputs << " (ratio " << perc(this->outputs, this->transactions) << ") \n" <<
"-- Version1:\t" << this->version1 << " (" << perc(this->version1, this->transactions) << "%) \n" <<
"-- Version2:\t" << this->version2 << " (" << perc(this->version2, this->transactions) << "%) \n" <<
"-- Locktimes (>0):\t" << this->locktimesGt0 << " (" << perc(this->locktimesGt0, this->transactions) << "%) \n" <<
std::endl;
}
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
auto transactions = block.transactions();
this->transactions += transactions.length();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
this->inputs += transaction.inputs.size();
this->outputs += transaction.outputs.size();
this->version1 += transaction.version == 1;
this->version2 += transaction.version == 2;
this->locktimesGt0 += transaction.locktime > 0;
transactions.popFront();
}
}
};
// SHA1(TX_HASH | VOUT) | SHA1(OUTPUT_SCRIPT) > stdout
struct dumpScriptIndexMap : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[40] = {};
uint8_t tbuf[36] = {};
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(tbuf, transaction.data);
uint32_t vout = 0;
for (const auto& output : transaction.outputs) {
Slice(tbuf + 32, tbuf + sizeof(tbuf)).put(vout);
++vout;
sha1(sbuf, tbuf, sizeof(tbuf));
sha1(sbuf + 20, output.script);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
const uint8_t COINBASE[32] = {};
// BLOCK_HASH | TX_HASH | SHA1(PREVIOUS_OUTPUT_SCRIPT) > stdout
// BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT) > stdout
struct dumpScriptIndex : whitelisted_t {
HMap<hash160_t, hash160_t> txOuts;
bool initialize (const char* arg) {
if (whitelisted_t::initialize(arg)) return true;
if (strncmp(arg, "-i", 2) == 0) {
const auto fileName = std::string(arg + 2);
const auto file = fopen(fileName.c_str(), "r");
assert(file != nullptr);
fseek(file, 0, SEEK_END);
const auto fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
assert(sizeof(this->txOuts[0]) == 40);
assert(fileSize % sizeof(this->txOuts[0]) == 0);
this->txOuts.resize(fileSize / sizeof(this->txOuts[0]));
const auto read = fread(&this->txOuts[0], fileSize, 1, file);
assert(read == 1);
fclose(file);
assert(!this->txOuts.empty());
assert(std::is_sorted(this->txOuts.begin(), this->txOuts.end()));
std::cerr << "Mapped " << this->txOuts.size() << " txOuts" << std::endl;
return true;
}
return false;
}
void operator() (const Block& block) {
hash256_t hash;
hash256(&hash[0], block.header);
if (this->shouldSkip(hash)) return;
uint8_t sbuf[84] = {};
memcpy(sbuf, &hash[0], 32);
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(sbuf + 32, transaction.data);
if (!this->txOuts.empty()) {
for (const auto& input : transaction.inputs) {
// Coinbase input?
if (
input.vout == 0xffffffff &&
memcmp(input.hash.begin, COINBASE, sizeof(COINBASE)) == 0
) {
sha1(&hash[0], input.script);
memcpy(sbuf + 64, &hash[0], 20);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
continue;
}
hash160_t hash;
sha1(&hash[0], input.data.take(36));
const auto txOutIter = this->txOuts.find(hash);
assert(txOutIter != this->txOuts.end());
memcpy(sbuf + 64, &(txOutIter->second)[0], 20);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
}
for (const auto& output : transaction.outputs) {
sha1(sbuf + 64, output.script);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
<commit_msg>multiply percentages by 100<commit_after>#include <atomic>
#include <map>
#include <set>
#include "block.hpp"
#include "hash.hpp"
#include "hvectors.hpp"
struct processFunctor_t {
virtual ~processFunctor_t () {}
virtual bool initialize (const char*) {
return false;
}
virtual void operator() (const Block&) = 0;
};
struct whitelisted_t : processFunctor_t {
HSet<hash256_t> whitelist;
bool initialize (const char* arg) {
if (strncmp(arg, "-w", 2) == 0) {
const auto fileName = std::string(arg + 2);
const auto file = fopen(fileName.c_str(), "r");
assert(file != nullptr);
fseek(file, 0, SEEK_END);
const auto fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
assert(sizeof(this->whitelist[0]) == 32);
assert(fileSize % sizeof(this->whitelist[0]) == 0);
this->whitelist.resize(fileSize / sizeof(hash256_t));
const auto read = fread(&this->whitelist[0], fileSize, 1, file);
assert(read == 1);
fclose(file);
assert(!this->whitelist.empty());
assert(std::is_sorted(this->whitelist.begin(), this->whitelist.end()));
std::cerr << "Whitelisted " << this->whitelist.size() << " hashes" << std::endl;
return true;
}
return false;
}
bool shouldSkip (const Block& block) const {
if (this->whitelist.empty()) return false;
hash256_t hash;
hash256(&hash[0], block.header);
return !this->whitelist.contains(hash);
}
bool shouldSkip (const hash256_t& hash) const {
if (this->whitelist.empty()) return false;
return !this->whitelist.contains(hash);
}
};
// XXX: fwrite can be used without sizeof(sbuf) < PIPE_BUF (4096 bytes)
// BLOCK_HEADER > stdout
struct dumpHeaders : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
fwrite(block.header.begin, 80, 1, stdout);
}
};
// SCRIPT_LENGTH | SCRIPT > stdout
struct dumpScripts : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[4096];
const auto maxScriptLength = sizeof(sbuf) - sizeof(uint16_t);
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& input : transaction.inputs) {
if (input.script.length() > maxScriptLength) continue;
const auto scriptLength = static_cast<uint16_t>(input.script.length());
Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength);
memcpy(sbuf + sizeof(uint16_t), input.script.begin, scriptLength);
fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
}
for (const auto& output : transaction.outputs) {
if (output.script.length() > maxScriptLength) continue;
const auto scriptLength = static_cast<uint16_t>(output.script.length());
Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength);
memcpy(sbuf + sizeof(uint16_t), output.script.begin, scriptLength);
fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
}
transactions.popFront();
}
}
};
// PREV_TX_HASH | PREV_TX_VOUT | TX_HASH > stdout
struct dumpTxOutIndex : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[68];
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(sbuf + 36, transaction.data);
for (const auto& input : transaction.inputs) {
memcpy(sbuf, input.hash.begin, 32);
Slice(sbuf + 32, sbuf + 36).put(input.vout);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
auto perc (uint64_t a, uint64_t ab) {
return static_cast<double>(a) / static_cast<double>(ab);
}
struct dumpStatistics : whitelisted_t {
std::atomic_ulong inputs;
std::atomic_ulong outputs;
std::atomic_ulong transactions;
std::atomic_ulong version1;
std::atomic_ulong version2;
std::atomic_ulong locktimesGt0;
dumpStatistics () {
this->inputs = 0;
this->outputs = 0;
this->transactions = 0;
this->version1 = 0;
this->version2 = 0;
this->locktimesGt0 = 0;
}
~dumpStatistics () {
std::cout <<
"Transactions:\t" << this->transactions << '\n' <<
"-- Inputs:\t" << this->inputs << " (ratio " << perc(this->inputs, this->transactions) << ") \n" <<
"-- Outputs:\t" << this->outputs << " (ratio " << perc(this->outputs, this->transactions) << ") \n" <<
"-- Version1:\t" << this->version1 << " (" << perc(this->version1, this->transactions) * 100 << "%) \n" <<
"-- Version2:\t" << this->version2 << " (" << perc(this->version2, this->transactions) * 100 << "%) \n" <<
"-- Locktimes (>0):\t" << this->locktimesGt0 << " (" << perc(this->locktimesGt0, this->transactions) * 100 << "%) \n" <<
std::endl;
}
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
auto transactions = block.transactions();
this->transactions += transactions.length();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
this->inputs += transaction.inputs.size();
this->outputs += transaction.outputs.size();
this->version1 += transaction.version == 1;
this->version2 += transaction.version == 2;
this->locktimesGt0 += transaction.locktime > 0;
transactions.popFront();
}
}
};
// SHA1(TX_HASH | VOUT) | SHA1(OUTPUT_SCRIPT) > stdout
struct dumpScriptIndexMap : whitelisted_t {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
uint8_t sbuf[40] = {};
uint8_t tbuf[36] = {};
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(tbuf, transaction.data);
uint32_t vout = 0;
for (const auto& output : transaction.outputs) {
Slice(tbuf + 32, tbuf + sizeof(tbuf)).put(vout);
++vout;
sha1(sbuf, tbuf, sizeof(tbuf));
sha1(sbuf + 20, output.script);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
const uint8_t COINBASE[32] = {};
// BLOCK_HASH | TX_HASH | SHA1(PREVIOUS_OUTPUT_SCRIPT) > stdout
// BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT) > stdout
struct dumpScriptIndex : whitelisted_t {
HMap<hash160_t, hash160_t> txOuts;
bool initialize (const char* arg) {
if (whitelisted_t::initialize(arg)) return true;
if (strncmp(arg, "-i", 2) == 0) {
const auto fileName = std::string(arg + 2);
const auto file = fopen(fileName.c_str(), "r");
assert(file != nullptr);
fseek(file, 0, SEEK_END);
const auto fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
assert(sizeof(this->txOuts[0]) == 40);
assert(fileSize % sizeof(this->txOuts[0]) == 0);
this->txOuts.resize(fileSize / sizeof(this->txOuts[0]));
const auto read = fread(&this->txOuts[0], fileSize, 1, file);
assert(read == 1);
fclose(file);
assert(!this->txOuts.empty());
assert(std::is_sorted(this->txOuts.begin(), this->txOuts.end()));
std::cerr << "Mapped " << this->txOuts.size() << " txOuts" << std::endl;
return true;
}
return false;
}
void operator() (const Block& block) {
hash256_t hash;
hash256(&hash[0], block.header);
if (this->shouldSkip(hash)) return;
uint8_t sbuf[84] = {};
memcpy(sbuf, &hash[0], 32);
auto transactions = block.transactions();
while (!transactions.empty()) {
const auto& transaction = transactions.front();
hash256(sbuf + 32, transaction.data);
if (!this->txOuts.empty()) {
for (const auto& input : transaction.inputs) {
// Coinbase input?
if (
input.vout == 0xffffffff &&
memcmp(input.hash.begin, COINBASE, sizeof(COINBASE)) == 0
) {
sha1(&hash[0], input.script);
memcpy(sbuf + 64, &hash[0], 20);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
continue;
}
hash160_t hash;
sha1(&hash[0], input.data.take(36));
const auto txOutIter = this->txOuts.find(hash);
assert(txOutIter != this->txOuts.end());
memcpy(sbuf + 64, &(txOutIter->second)[0], 20);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
}
for (const auto& output : transaction.outputs) {
sha1(sbuf + 64, output.script);
fwrite(sbuf, sizeof(sbuf), 1, stdout);
}
transactions.popFront();
}
}
};
<|endoftext|> |
<commit_before>#include "Variant.h"
#include "split.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
using namespace vcf;
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "usage: " << argv[0] << " <vcf file>" << endl
<< "outputs a VCF stream in which 'long' non-complex"
<< "alleles have their position corrected." << endl
<< "assumes that VCF records can't overlap 5'->3'" << endl;
return 1;
}
string filename = argv[1];
VariantCallFile variantFile;
if (filename == "-") {
variantFile.open(std::cin);
} else {
variantFile.open(filename);
}
if (!variantFile.is_open()) {
cerr << "could not open " << filename << endl;
return 1;
}
Variant var(variantFile);
// write the new header
cout << variantFile.header << endl;
// print the records, filtering is done via the setting of varA's output sample names
while (variantFile.getNextVariant(var)) {
// if we just have one parsed alternate (non-complex case)
map<string, vector<VariantAllele> > parsedAlts = var.parsedAlternates();
// but the alt string is long
if (var.alt.size() == 1 && parsedAlts.size() == 2) {
string& alternate = var.alt.front();
if (parsedAlts[alternate].size() == 1) {
// do we have extra sequence hanging around?
VariantAllele& varallele = parsedAlts[alternate].front();
// for deletions and insertions, we have to keep a leading base
// but the variant allele doesn't have these
if (varallele.ref.size() == varallele.alt.size()) {
if (varallele.position != var.position) {
var.ref = varallele.ref;
var.alt.front() = varallele.alt;
var.position = varallele.position;
}
} else if (varallele.ref.size() < varallele.alt.size()) {
if (varallele.position != var.position + 1) {
// TODO unhandled
}
} else if (varallele.ref.size() < varallele.alt.size()) {
if (varallele.position != var.position) {
// TODO unhandled
}
}
}
}
cout << var << endl;
}
return 0;
}
<commit_msg>update vcfcleancomplex<commit_after>#include "Variant.h"
#include "split.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
using namespace vcf;
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "usage: " << argv[0] << " <vcf file>" << endl
<< "outputs a VCF stream in which 'long' non-complex"
<< "alleles have their position corrected." << endl
<< "assumes that VCF records can't overlap 5'->3'" << endl;
return 1;
}
string filename = argv[1];
VariantCallFile variantFile;
if (filename == "-") {
variantFile.open(std::cin);
} else {
variantFile.open(filename);
}
if (!variantFile.is_open()) {
cerr << "could not open " << filename << endl;
return 1;
}
Variant var(variantFile);
// write the new header
cout << variantFile.header << endl;
// print the records, filtering is done via the setting of varA's output sample names
while (variantFile.getNextVariant(var)) {
// if we just have one parsed alternate (non-complex case)
map<string, vector<VariantAllele> > parsedAlts = var.parsedAlternates(true, true); // use mnps, and previous for indels
// but the alt string is long
if (var.alt.size() == 1 && parsedAlts.size() == 2) {
string& alternate = var.alt.front();
vector<VariantAllele>& vs = parsedAlts[alternate];
vector<VariantAllele> valleles;
for (vector<VariantAllele>::iterator a = vs.begin(); a != vs.end(); ++a) {
if (a->ref != a->alt) {
valleles.push_back(*a); //cout << a->ref << " " << a->alt << endl;
}
}
if (valleles.size() == 1) {
// do we have extra sequence hanging around?
VariantAllele& varallele = valleles.front();
//cout << varallele.ref << " " << varallele.alt << endl;
// for deletions and insertions, we have to keep a leading base
// but the variant allele doesn't have these
if (varallele.ref.size() == varallele.alt.size()) {
//if (varallele.position != var.position) {
var.ref = varallele.ref;
var.alt.front() = varallele.alt;
var.position = varallele.position;
} else if (varallele.ref.size() < varallele.alt.size()) {
if (varallele.position != var.position + 1) {
// TODO unhandled
}
} else if (varallele.ref.size() < varallele.alt.size()) {
if (varallele.position != var.position) {
// TODO unhandled
}
}
}
}
cout << var << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* ========================================
ID: mathema6
TASK: bronze2
LANG: C++14
* File Name : bronze2.cpp
* Creation Date : 18-12-2021
* Last Modified : Mon 20 Dec 2021 06:48:22 PM CET
* Created By : Karel Ha <[email protected]>
* URL : http://usaco.org/index.php?page=viewproblem&cpid=1144
* Points/Time :
* Total/ETA :
* [upsolve]
* +7m
* [upsolve - sparseTables]
*
* Status :
* not submitted :-(
* [upsolve]
* [upsolve - sparseTables]
*
==========================================*/
#include <algorithm>
#define PROBLEMNAME "bronze2"
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define REP(i,n) for(ll i=0;i<(n);i++)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define FORD(i,a,b) for(ll i=(a);i>=(b);i--)
#define REPi(i,n) for(int i=0;i<(n);i++)
#define FORi(i,a,b) for(int i=(a);i<=(b);i++)
#define FORDi(i,a,b) for(int i=(a);i>=(b);i--)
#define ALL(A) (A).begin(), (A).end()
#define REVALL(A) (A).rbegin(), (A).rend()
#define F first
#define S second
#define OP first
#define CL second
#define PB push_back
#define MP make_pair
#define MTP make_tuple
#define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0)
#define CONTAINS(S,E) ((S).find(E) != (S).end())
#define SZ(x) ((ll) (x).size())
// #define SZi(x) ((int) (x).size())
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define YN(b) cout << ((b)?"YES":"NO") << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define Yn(b) cout << ((b)?"Yes":"No") << endl;
#define Imp cout << "Impossible" << endl;
#define IMP cout << "IMPOSSIBLE" << endl;
using ll = long long;
using ul = unsigned long long;
// using ulul = pair<ul, ul>;
using ld = long double;
using graph_unord = unordered_map<ll, vector<ll>>;
using graph_ord = map<ll, set<ll>>;
using graph_t = graph_unord;
#ifdef ONLINE_JUDGE
#undef MATHEMAGE_DEBUG
#endif
#ifdef MATHEMAGE_DEBUG
#define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl;
#define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl;
#define LINESEP1 cerr << "----------------------------------------------- " << endl;
#define LINESEP2 cerr << "_________________________________________________________________" << endl;
#else
#define MSG(a)
#define MSG_VEC_VEC(v)
#define LINESEP1
#define LINESEP2
#endif
ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) {
for (const auto & row: vec) {
for (const auto & col: row) {
os << "[ " << col << "] ";
}
os << endl;
}
return os;
}
template<typename T, class Compare>
ostream& operator<<(ostream& os, const set<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T, class Compare>
ostream& operator<<(ostream& os, const multiset<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const unordered_map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << "(" << p.F << ", " << p.S << ")"; }
template<typename T>
istream& operator>>(istream& is, vector<T> & vec) { for (auto & x: vec) is >> x; return is; }
template<typename T>
inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); }
template<class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
// inline bool eqDouble(double a, double b) { return fabs(a-b) < 1e-9; }
inline bool eqDouble(ld a, ld b) { return fabs(a-b) < 1e-9; }
inline bool isCollinear(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
// (x-x1)/(y-y1) == (x-x2)/(y-y2)
// (x-x1)*(y-y2) == (x-x2)*(y-y1)
return eqDouble((x-x1)*(y-y2), (x-x2)*(y-y1));
}
inline bool isBetween(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
return min(x1,x2)<=x && x<=max(x1,x2)
&& min(y1,y2)<=y && y<=max(y1,y2);
}
inline bool onLine(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
return isCollinear(x, y, x1, y1, x2, y2) && isBetween(x, y, x1, y1, x2, y2);
}
#ifndef MATHEMAGE_LOCAL
void setIO(string filename) { // the argument is the filename without the extension
freopen((filename+".in").c_str(), "r", stdin);
freopen((filename+".out").c_str(), "w", stdout);
MSG(filename);
}
#endif
const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1};
const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1};
const vector<pair<int,int>> DXY8 = {
{-1,-1}, {-1,0}, {-1,1},
{ 0,-1}, { 0,1},
{ 1,-1}, { 1,0}, { 1,1}
};
const vector<int> DX4 = {0, 1, 0, -1};
const vector<int> DY4 = {1, 0, -1, 0};
const vector<pair<int,int>> DXY4 = { {0,1}, {1,0}, {0,-1}, {-1,0} };
const string dues="NESW";
const int CLEAN = -1;
const int UNDEF = -42;
const long long MOD = 1000000007;
const double EPS = 1e-8;
const ld PI = acos((ld)-1);
const int INF = INT_MAX;
const long long INF_LL = LLONG_MAX;
const long long INF_ULL = ULLONG_MAX;
void solve() {
ll N; cin >> N;
vector<ll> p(N); cin >> p;
vector<ll> t(N); cin >> t;
MSG(p); MSG(t); LINESEP1;
vector<ll> deltas(N);
vector<ll> signs(N);
unordered_map<ll, vector<ll>> val2pos;
REP(i,N) {
deltas[i] = abs(p[i]-t[i]);
signs[i] = SGN(p[i]-t[i]);
}
deltas.PB(0); // dummy
signs.PB(0); // dummy
MSG(deltas); MSG(signs); LINESEP1;
for (ll i = 0; i < SZ(deltas); i += 1) {
val2pos[deltas[i]].PB(i);
}
MSG(val2pos); LINESEP1;
/* compute sparse tables for min queries */
vector<vector<ll>> sparseMin{deltas};
for (ll e = 1; 1<<e <= N; e += 1) {
sparseMin.PB({});
for (ll i = 0; i+(1<<e)-1 < N; i += 1) {
sparseMin[e].PB(min(
sparseMin[e-1][i],
sparseMin[e-1][i+(1<<(e-1))]
)
);
}
}
MSG_VEC_VEC(sparseMin); LINESEP1;
auto queryMin = [&](ll left, ll right) { // TODO optimize via Sparse Tables
ll e=0;
while (1<<e <= right-left+1) {
e++;
}
e--;
return min(sparseMin[e][left], sparseMin[e][right-(1<<e)+1]);
};
// unordered_map<ll, unordered_map<ll, unordered_map<ll, ll>>> memo;
function<ll(ll,ll,ll)> calculateOpt = [&](ll left, ll right, ll baseHeight) {
LINESEP1;
MSG(left); MSG(right); MSG(baseHeight);
if (left>right) { return 0LL; }
if (left==right) { return deltas[left]-baseHeight; }
// if (CONTAINS(memo, left) && CONTAINS(memo[left], right) && CONTAINS(memo[left][right], baseHeight)) {
// return memo[left][right][baseHeight];
// }
ll mn=queryMin(left, right);
ll ans = mn-baseHeight;
MSG(mn);
MSG(val2pos[mn]);
auto it = std::lower_bound(ALL(val2pos[mn]), left);
assert(left<=*it);
assert(*it<=right);
vector<ll> cutPts{left-1};
while (it!=val2pos[mn].end() && *it<=right) {
cutPts.PB(*it);
it++;
}
cutPts.PB(right+1);
MSG(cutPts);
for (ll i = 1; i < SZ(cutPts); i += 1) {
ans += calculateOpt(cutPts[i-1]+1, cutPts[i]-1, mn);
}
// return memo[left][right][baseHeight] = ans;
return ans;
};
ll result = 0LL;
ll prev=0;
for (ll i = 1; i < N+1; i += 1) {
if (signs[i] != signs[i-1]) {
if (signs[i-1]!=0) {
result += calculateOpt(prev, i-1, 0);
}
prev=i;
}
}
cout << result << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout << std::setprecision(10) << std::fixed;
#ifndef MATHEMAGE_LOCAL
// setIO(PROBLEMNAME);
#endif
int cases = 1;
FOR(tt,1,cases) {
// cout << "Case #" << tt << ": ";
solve();
LINESEP2;
}
return 0;
}
<commit_msg>Upsolve USACO 2021 December Contest, Bronze Problem 2. Air Cownditioning<commit_after>/* ========================================
ID: mathema6
TASK: bronze2
LANG: C++14
* File Name : bronze2.cpp
* Creation Date : 18-12-2021
* Last Modified : Thu 30 Dec 2021 11:08:00 PM CET
* Created By : Karel Ha <[email protected]>
* URL : http://usaco.org/index.php?page=viewproblem&cpid=1144
* Points/Time :
* Total/ETA :
* [upsolve]
* +7m
* [upsolve - sparseTables]
*
* Status :
* not submitted :-(
* [upsolve]
* [upsolve - sparseTables]
* 10/10 ACs (passed!!) :-O :-O :-O
*
==========================================*/
#include <algorithm>
#define PROBLEMNAME "bronze2"
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define REP(i,n) for(ll i=0;i<(n);i++)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define FORD(i,a,b) for(ll i=(a);i>=(b);i--)
#define REPi(i,n) for(int i=0;i<(n);i++)
#define FORi(i,a,b) for(int i=(a);i<=(b);i++)
#define FORDi(i,a,b) for(int i=(a);i>=(b);i--)
#define ALL(A) (A).begin(), (A).end()
#define REVALL(A) (A).rbegin(), (A).rend()
#define F first
#define S second
#define OP first
#define CL second
#define PB push_back
#define MP make_pair
#define MTP make_tuple
#define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0)
#define CONTAINS(S,E) ((S).find(E) != (S).end())
#define SZ(x) ((ll) (x).size())
// #define SZi(x) ((int) (x).size())
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define YN(b) cout << ((b)?"YES":"NO") << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define Yn(b) cout << ((b)?"Yes":"No") << endl;
#define Imp cout << "Impossible" << endl;
#define IMP cout << "IMPOSSIBLE" << endl;
using ll = long long;
using ul = unsigned long long;
// using ulul = pair<ul, ul>;
using ld = long double;
using graph_unord = unordered_map<ll, vector<ll>>;
using graph_ord = map<ll, set<ll>>;
using graph_t = graph_unord;
#ifdef ONLINE_JUDGE
#undef MATHEMAGE_DEBUG
#endif
#ifdef MATHEMAGE_DEBUG
#define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl;
#define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl;
#define LINESEP1 cerr << "----------------------------------------------- " << endl;
#define LINESEP2 cerr << "_________________________________________________________________" << endl;
#else
#define MSG(a)
#define MSG_VEC_VEC(v)
#define LINESEP1
#define LINESEP2
#endif
ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) {
for (const auto & row: vec) {
for (const auto & col: row) {
os << "[ " << col << "] ";
}
os << endl;
}
return os;
}
template<typename T, class Compare>
ostream& operator<<(ostream& os, const set<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T, class Compare>
ostream& operator<<(ostream& os, const multiset<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const unordered_map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << "(" << p.F << ", " << p.S << ")"; }
template<typename T>
istream& operator>>(istream& is, vector<T> & vec) { for (auto & x: vec) is >> x; return is; }
template<typename T>
inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); }
template<class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
// inline bool eqDouble(double a, double b) { return fabs(a-b) < 1e-9; }
inline bool eqDouble(ld a, ld b) { return fabs(a-b) < 1e-9; }
inline bool isCollinear(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
// (x-x1)/(y-y1) == (x-x2)/(y-y2)
// (x-x1)*(y-y2) == (x-x2)*(y-y1)
return eqDouble((x-x1)*(y-y2), (x-x2)*(y-y1));
}
inline bool isBetween(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
return min(x1,x2)<=x && x<=max(x1,x2)
&& min(y1,y2)<=y && y<=max(y1,y2);
}
inline bool onLine(ld x, ld y, ld x1, ld y1, ld x2, ld y2) {
return isCollinear(x, y, x1, y1, x2, y2) && isBetween(x, y, x1, y1, x2, y2);
}
#ifndef MATHEMAGE_LOCAL
void setIO(string filename) { // the argument is the filename without the extension
freopen((filename+".in").c_str(), "r", stdin);
freopen((filename+".out").c_str(), "w", stdout);
MSG(filename);
}
#endif
const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1};
const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1};
const vector<pair<int,int>> DXY8 = {
{-1,-1}, {-1,0}, {-1,1},
{ 0,-1}, { 0,1},
{ 1,-1}, { 1,0}, { 1,1}
};
const vector<int> DX4 = {0, 1, 0, -1};
const vector<int> DY4 = {1, 0, -1, 0};
const vector<pair<int,int>> DXY4 = { {0,1}, {1,0}, {0,-1}, {-1,0} };
const string dues="NESW";
const int CLEAN = -1;
const int UNDEF = -42;
const long long MOD = 1000000007;
const double EPS = 1e-8;
const ld PI = acos((ld)-1);
const int INF = INT_MAX;
const long long INF_LL = LLONG_MAX;
const long long INF_ULL = ULLONG_MAX;
void solve() {
ll N; cin >> N;
vector<ll> p(N); cin >> p;
vector<ll> t(N); cin >> t;
MSG(p); MSG(t); LINESEP1;
vector<ll> deltas(N);
vector<ll> signs(N);
unordered_map<ll, vector<ll>> val2pos;
REP(i,N) {
deltas[i] = abs(p[i]-t[i]);
signs[i] = SGN(p[i]-t[i]);
}
deltas.PB(0); // dummy
signs.PB(0); // dummy
MSG(deltas); MSG(signs); LINESEP1;
for (ll i = 0; i < SZ(deltas); i += 1) {
val2pos[deltas[i]].PB(i);
}
MSG(val2pos); LINESEP1;
/* compute sparse tables for min queries */
vector<vector<ll>> sparseMin{deltas};
for (ll e = 1; 1<<e <= N; e += 1) {
sparseMin.PB({});
for (ll i = 0; i+(1<<e)-1 < N; i += 1) {
sparseMin[e].PB(min(
sparseMin[e-1][i],
sparseMin[e-1][i+(1<<(e-1))]
)
);
}
}
MSG_VEC_VEC(sparseMin); LINESEP1;
auto queryMin = [&](ll left, ll right) { // TODO optimize via Sparse Tables
ll e=0;
while (1<<e <= right-left+1) {
e++;
}
e--;
return min(sparseMin[e][left], sparseMin[e][right-(1<<e)+1]);
};
// unordered_map<ll, unordered_map<ll, unordered_map<ll, ll>>> memo;
function<ll(ll,ll,ll)> calculateOpt = [&](ll left, ll right, ll baseHeight) {
LINESEP1;
MSG(left); MSG(right); MSG(baseHeight);
if (left>right) { return 0LL; }
if (left==right) { return deltas[left]-baseHeight; }
// if (CONTAINS(memo, left) && CONTAINS(memo[left], right) && CONTAINS(memo[left][right], baseHeight)) {
// return memo[left][right][baseHeight];
// }
ll mn=queryMin(left, right);
ll ans = mn-baseHeight;
MSG(mn);
MSG(val2pos[mn]);
auto it = std::lower_bound(ALL(val2pos[mn]), left);
assert(left<=*it);
assert(*it<=right);
vector<ll> cutPts{left-1};
while (it!=val2pos[mn].end() && *it<=right) {
cutPts.PB(*it);
it++;
}
cutPts.PB(right+1);
MSG(cutPts);
for (ll i = 1; i < SZ(cutPts); i += 1) {
ans += calculateOpt(cutPts[i-1]+1, cutPts[i]-1, mn);
}
// return memo[left][right][baseHeight] = ans;
return ans;
};
ll result = 0LL;
ll prev=0;
for (ll i = 1; i < N+1; i += 1) {
if (signs[i] != signs[i-1]) {
if (signs[i-1]!=0) {
result += calculateOpt(prev, i-1, 0);
}
prev=i;
}
}
cout << result << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout << std::setprecision(10) << std::fixed;
#ifndef MATHEMAGE_LOCAL
// setIO(PROBLEMNAME);
#endif
int cases = 1;
FOR(tt,1,cases) {
// cout << "Case #" << tt << ": ";
solve();
LINESEP2;
}
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* Project: VFK Reader (SQLite)
* Purpose: Implements VFKReaderSQLite class.
* Author: Martin Landa, landa.martin gmail.com
*
******************************************************************************
* Copyright (c) 2012-2014, Martin Landa <landa.martin gmail.com>
* Copyright (c) 2012-2014, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "cpl_vsi.h"
#include "vfkreader.h"
#include "vfkreadersqlite.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include <cstring>
#include "ogr_geometry.h"
CPL_CVSID("$Id: vfkreadersqlite.cpp 35933 2016-10-25 16:46:26Z goatbar $");
/*!
\brief VFKReaderSQLite constructor
*/
VFKReaderSQLite::VFKReaderSQLite( const char *pszFileName ) :
VFKReaderDB(pszFileName),
m_poDB(NULL)
{
size_t nLen = 0;
VSIStatBufL sStatBufDb;
{
GDALOpenInfo *poOpenInfo = new GDALOpenInfo(pszFileName, GA_ReadOnly);
m_bDbSource = poOpenInfo->nHeaderBytes >= 16 &&
STARTS_WITH((const char*)poOpenInfo->pabyHeader, "SQLite format 3");
delete poOpenInfo;
}
const char *pszDbNameConf = CPLGetConfigOption("OGR_VFK_DB_NAME", NULL);
CPLString osDbName;
if( !m_bDbSource )
{
m_bNewDb = true;
/* open tmp SQLite DB (re-use DB file if already exists) */
if (pszDbNameConf) {
osDbName = pszDbNameConf;
}
else
{
osDbName = CPLResetExtension(m_pszFilename, "db");
}
nLen = osDbName.length();
if( nLen > 2048 )
{
nLen = 2048;
osDbName.resize(nLen);
}
}
else
{
// m_bNewDb = false;
nLen = strlen(pszFileName);
osDbName = pszFileName;
}
m_pszDBname = new char [nLen+1];
std::strncpy(m_pszDBname, osDbName.c_str(), nLen);
m_pszDBname[nLen] = 0;
CPLDebug("OGR-VFK", "Using internal DB: %s",
m_pszDBname);
if( !m_bDbSource && VSIStatL(osDbName, &sStatBufDb) == 0 )
{
/* Internal DB exists */
if (CPLTestBool(CPLGetConfigOption("OGR_VFK_DB_OVERWRITE", "NO"))) {
m_bNewDb = true; // Overwrite existing DB.
CPLDebug("OGR-VFK", "Internal DB (%s) already exists and will be overwritten",
m_pszDBname);
VSIUnlink(osDbName);
}
else
{
if (pszDbNameConf == NULL &&
m_poFStat->st_mtime > sStatBufDb.st_mtime) {
CPLDebug("OGR-VFK",
"Found %s but ignoring because it appears\n"
"be older than the associated VFK file.",
osDbName.c_str());
m_bNewDb = true;
VSIUnlink(osDbName);
}
else
{
m_bNewDb = false; /* re-use existing DB */
}
}
}
CPLDebug("OGR-VFK", "New DB: %s Spatial: %s",
m_bNewDb ? "yes" : "no", m_bSpatial ? "yes" : "no");
if (SQLITE_OK != sqlite3_open(osDbName, &m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Creating SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
int nRowCount = 0;
int nColCount = 0;
CPLString osCommand;
if( m_bDbSource )
{
/* check if it's really VFK DB datasource */
char* pszErrMsg = NULL;
char** papszResult = NULL;
nRowCount = nColCount = 0;
osCommand.Printf("SELECT * FROM sqlite_master WHERE type='table' AND name='%s'",
VFK_DB_TABLE);
sqlite3_get_table(m_poDB,
osCommand.c_str(),
&papszResult,
&nRowCount, &nColCount, &pszErrMsg);
sqlite3_free_table(papszResult);
sqlite3_free(pszErrMsg);
if (nRowCount != 1) {
/* DB is not valid VFK datasource */
sqlite3_close(m_poDB);
m_poDB = NULL;
return;
}
}
if( !m_bNewDb )
{
/* check if DB is up-to-date datasource */
char* pszErrMsg = NULL;
char** papszResult = NULL;
nRowCount = nColCount = 0;
osCommand.Printf("SELECT * FROM %s LIMIT 1", VFK_DB_TABLE);
sqlite3_get_table(m_poDB,
osCommand.c_str(),
&papszResult,
&nRowCount, &nColCount, &pszErrMsg);
sqlite3_free_table(papszResult);
sqlite3_free(pszErrMsg);
if (nColCount != 7) {
/* it seems that DB is outdated, let's create new DB from
* scratch */
if( m_bDbSource )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid VFK DB datasource");
}
if (SQLITE_OK != sqlite3_close(m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Closing SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
VSIUnlink(osDbName);
if (SQLITE_OK != sqlite3_open(osDbName, &m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Creating SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
CPLDebug("OGR-VFK", "Internal DB (%s) is invalid - will be re-created",
m_pszDBname);
m_bNewDb = true;
}
}
char* pszErrMsg = NULL;
CPL_IGNORE_RET_VAL(sqlite3_exec(m_poDB, "PRAGMA synchronous = OFF",
NULL, NULL, &pszErrMsg));
sqlite3_free(pszErrMsg);
if( m_bNewDb )
{
/* new DB, create support metadata tables */
osCommand.Printf(
"CREATE TABLE %s (file_name text, file_size integer, "
"table_name text, num_records integer, "
"num_features integer, num_geometries integer, table_defn text)",
VFK_DB_TABLE);
ExecuteSQL(osCommand.c_str());
/* header table */
osCommand.Printf(
"CREATE TABLE %s (key text, value text)", VFK_DB_HEADER);
ExecuteSQL(osCommand.c_str());
}
}
/*!
\brief VFKReaderSQLite destructor
*/
VFKReaderSQLite::~VFKReaderSQLite()
{
// Close tmp SQLite DB.
if( SQLITE_OK != sqlite3_close(m_poDB) )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Closing SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
CPLDebug("OGR-VFK", "Internal DB (%s) closed", m_pszDBname);
/* delete tmp SQLite DB if requested */
if( CPLTestBool(CPLGetConfigOption("OGR_VFK_DB_DELETE", "NO")) )
{
CPLDebug("OGR-VFK", "Internal DB (%s) deleted", m_pszDBname);
VSIUnlink(m_pszDBname);
}
delete[] m_pszDBname;
}
/*!
\brief Prepare SQL statement
\param pszSQLCommand SQL statement to be prepared
\return pointer to sqlite3_stmt instance or NULL on error
*/
void VFKReaderSQLite::PrepareStatement(const char *pszSQLCommand, unsigned int idx)
{
int rc;
CPLDebug("OGR-VFK", "VFKReaderDB::PrepareStatement(): %s", pszSQLCommand);
if (idx < m_hStmt.size()) {
sqlite3_stmt *hStmt;
rc = sqlite3_prepare(m_poDB, pszSQLCommand, -1,
&hStmt, NULL);
m_hStmt.push_back(hStmt);
}
else {
rc = sqlite3_prepare(m_poDB, pszSQLCommand, -1,
&(m_hStmt[idx]), NULL);
}
// TODO(schwehr): if( rc == SQLITE_OK ) return NULL;
if (rc != SQLITE_OK) {
CPLError(CE_Failure, CPLE_AppDefined,
"In PrepareStatement(): sqlite3_prepare(%s):\n %s",
pszSQLCommand, sqlite3_errmsg(m_poDB));
if(m_hStmt[idx] != NULL) {
sqlite3_finalize(m_hStmt[idx]);
m_hStmt.erase(m_hStmt.begin() + idx);
}
}
}
/*!
\brief Execute prepared SQL statement
\param hStmt pointer to sqlite3_stmt
\return OGRERR_NONE on success
*/
OGRErr VFKReaderSQLite::ExecuteSQL(sqlite3_stmt *hStmt)
{
const int rc = sqlite3_step(hStmt);
if (rc != SQLITE_ROW) {
if (rc == SQLITE_DONE) {
sqlite3_finalize(hStmt);
return OGRERR_NOT_ENOUGH_DATA;
}
CPLError(CE_Failure, CPLE_AppDefined,
"In ExecuteSQL(): sqlite3_step:\n %s",
sqlite3_errmsg(m_poDB));
if (hStmt)
sqlite3_finalize(hStmt);
return OGRERR_FAILURE;
}
return OGRERR_NONE;
}
/*!
\brief Execute SQL statement (SQLITE only)
\param pszSQLCommand SQL command to execute
\param bQuiet true to print debug message on failure instead of error message
\return OGRERR_NONE on success or OGRERR_FAILURE on failure
*/
OGRErr VFKReaderSQLite::ExecuteSQL( const char *pszSQLCommand, bool bQuiet )
{
char *pszErrMsg = NULL;
if( SQLITE_OK != sqlite3_exec(m_poDB, pszSQLCommand,
NULL, NULL, &pszErrMsg) )
{
if (!bQuiet)
CPLError(CE_Failure, CPLE_AppDefined,
"In ExecuteSQL(%s): %s",
pszSQLCommand, pszErrMsg);
else
CPLError(CE_Warning, CPLE_AppDefined,
"In ExecuteSQL(%s): %s",
pszSQLCommand, pszErrMsg);
return OGRERR_FAILURE;
}
return OGRERR_NONE;
}
OGRErr VFKReaderSQLite::ExecuteSQL(const char *pszSQLCommand, int& count)
{
OGRErr ret;
PrepareStatement(pszSQLCommand);
ret = ExecuteSQL(m_hStmt[0]); // TODO: solve
if (ret == OGRERR_NONE) {
count = sqlite3_column_int(m_hStmt[0], 0); // TODO:
}
sqlite3_finalize(m_hStmt[0]); // TODO
m_hStmt[0] = NULL; // TODO
return ret;
}
OGRErr VFKReaderSQLite::ExecuteSQL(std::vector<VFKDbValue>& record, int idx)
{
OGRErr ret;
ret = ExecuteSQL(m_hStmt[idx]);
// TODO: num_of_column == size
if (ret == OGRERR_NONE) {
for (unsigned int i = 0; i < record.size(); i++) { // TODO: iterator
VFKDbValue *value = &(record[i]);
switch (value->get_type()) {
case DT_INT:
value->set_int(sqlite3_column_int(m_hStmt[idx], i));
break;
case DT_BIGINT:
case DT_UBIGINT:
value->set_bigint(sqlite3_column_int64(m_hStmt[idx], i));
break;
case DT_DOUBLE:
value->set_double(sqlite3_column_double(m_hStmt[idx], i));
break;
case DT_TEXT:
value->set_text((char *)sqlite3_column_text(m_hStmt[idx], i));
break;
}
}
}
else {
sqlite3_finalize(m_hStmt[idx]);
m_hStmt[idx] = NULL;
if (idx > 0) {
m_hStmt.erase(m_hStmt.begin() + idx);
}
}
return ret;
}
<commit_msg>Fix SQLite backend for reading (geometry still missing)<commit_after>/******************************************************************************
*
* Project: VFK Reader (SQLite)
* Purpose: Implements VFKReaderSQLite class.
* Author: Martin Landa, landa.martin gmail.com
*
******************************************************************************
* Copyright (c) 2012-2014, Martin Landa <landa.martin gmail.com>
* Copyright (c) 2012-2014, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "cpl_vsi.h"
#include "vfkreader.h"
#include "vfkreadersqlite.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include <cstring>
#include "ogr_geometry.h"
CPL_CVSID("$Id: vfkreadersqlite.cpp 35933 2016-10-25 16:46:26Z goatbar $");
/*!
\brief VFKReaderSQLite constructor
*/
VFKReaderSQLite::VFKReaderSQLite( const char *pszFileName ) :
VFKReaderDB(pszFileName),
m_poDB(NULL)
{
size_t nLen = 0;
VSIStatBufL sStatBufDb;
{
GDALOpenInfo *poOpenInfo = new GDALOpenInfo(pszFileName, GA_ReadOnly);
m_bDbSource = poOpenInfo->nHeaderBytes >= 16 &&
STARTS_WITH((const char*)poOpenInfo->pabyHeader, "SQLite format 3");
delete poOpenInfo;
}
const char *pszDbNameConf = CPLGetConfigOption("OGR_VFK_DB_NAME", NULL);
CPLString osDbName;
if( !m_bDbSource )
{
m_bNewDb = true;
/* open tmp SQLite DB (re-use DB file if already exists) */
if (pszDbNameConf) {
osDbName = pszDbNameConf;
}
else
{
osDbName = CPLResetExtension(m_pszFilename, "db");
}
nLen = osDbName.length();
if( nLen > 2048 )
{
nLen = 2048;
osDbName.resize(nLen);
}
}
else
{
// m_bNewDb = false;
nLen = strlen(pszFileName);
osDbName = pszFileName;
}
m_pszDBname = new char [nLen+1];
std::strncpy(m_pszDBname, osDbName.c_str(), nLen);
m_pszDBname[nLen] = 0;
CPLDebug("OGR-VFK", "Using internal DB: %s",
m_pszDBname);
if( !m_bDbSource && VSIStatL(osDbName, &sStatBufDb) == 0 )
{
/* Internal DB exists */
if (CPLTestBool(CPLGetConfigOption("OGR_VFK_DB_OVERWRITE", "NO"))) {
m_bNewDb = true; // Overwrite existing DB.
CPLDebug("OGR-VFK", "Internal DB (%s) already exists and will be overwritten",
m_pszDBname);
VSIUnlink(osDbName);
}
else
{
if (pszDbNameConf == NULL &&
m_poFStat->st_mtime > sStatBufDb.st_mtime) {
CPLDebug("OGR-VFK",
"Found %s but ignoring because it appears\n"
"be older than the associated VFK file.",
osDbName.c_str());
m_bNewDb = true;
VSIUnlink(osDbName);
}
else
{
m_bNewDb = false; /* re-use existing DB */
}
}
}
CPLDebug("OGR-VFK", "New DB: %s Spatial: %s",
m_bNewDb ? "yes" : "no", m_bSpatial ? "yes" : "no");
if (SQLITE_OK != sqlite3_open(osDbName, &m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Creating SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
int nRowCount = 0;
int nColCount = 0;
CPLString osCommand;
if( m_bDbSource )
{
/* check if it's really VFK DB datasource */
char* pszErrMsg = NULL;
char** papszResult = NULL;
nRowCount = nColCount = 0;
osCommand.Printf("SELECT * FROM sqlite_master WHERE type='table' AND name='%s'",
VFK_DB_TABLE);
sqlite3_get_table(m_poDB,
osCommand.c_str(),
&papszResult,
&nRowCount, &nColCount, &pszErrMsg);
sqlite3_free_table(papszResult);
sqlite3_free(pszErrMsg);
if (nRowCount != 1) {
/* DB is not valid VFK datasource */
sqlite3_close(m_poDB);
m_poDB = NULL;
return;
}
}
if( !m_bNewDb )
{
/* check if DB is up-to-date datasource */
char* pszErrMsg = NULL;
char** papszResult = NULL;
nRowCount = nColCount = 0;
osCommand.Printf("SELECT * FROM %s LIMIT 1", VFK_DB_TABLE);
sqlite3_get_table(m_poDB,
osCommand.c_str(),
&papszResult,
&nRowCount, &nColCount, &pszErrMsg);
sqlite3_free_table(papszResult);
sqlite3_free(pszErrMsg);
if (nColCount != 7) {
/* it seems that DB is outdated, let's create new DB from
* scratch */
if( m_bDbSource )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid VFK DB datasource");
}
if (SQLITE_OK != sqlite3_close(m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Closing SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
VSIUnlink(osDbName);
if (SQLITE_OK != sqlite3_open(osDbName, &m_poDB)) {
CPLError(CE_Failure, CPLE_AppDefined,
"Creating SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
CPLDebug("OGR-VFK", "Internal DB (%s) is invalid - will be re-created",
m_pszDBname);
m_bNewDb = true;
}
}
char* pszErrMsg = NULL;
CPL_IGNORE_RET_VAL(sqlite3_exec(m_poDB, "PRAGMA synchronous = OFF",
NULL, NULL, &pszErrMsg));
sqlite3_free(pszErrMsg);
if( m_bNewDb )
{
/* new DB, create support metadata tables */
osCommand.Printf(
"CREATE TABLE %s (file_name text, file_size integer, "
"table_name text, num_records integer, "
"num_features integer, num_geometries integer, table_defn text)",
VFK_DB_TABLE);
ExecuteSQL(osCommand.c_str());
/* header table */
osCommand.Printf(
"CREATE TABLE %s (key text, value text)", VFK_DB_HEADER);
ExecuteSQL(osCommand.c_str());
}
}
/*!
\brief VFKReaderSQLite destructor
*/
VFKReaderSQLite::~VFKReaderSQLite()
{
// Close tmp SQLite DB.
if( SQLITE_OK != sqlite3_close(m_poDB) )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Closing SQLite DB failed: %s",
sqlite3_errmsg(m_poDB));
}
CPLDebug("OGR-VFK", "Internal DB (%s) closed", m_pszDBname);
/* delete tmp SQLite DB if requested */
if( CPLTestBool(CPLGetConfigOption("OGR_VFK_DB_DELETE", "NO")) )
{
CPLDebug("OGR-VFK", "Internal DB (%s) deleted", m_pszDBname);
VSIUnlink(m_pszDBname);
}
}
/*!
\brief Prepare SQL statement
\param pszSQLCommand SQL statement to be prepared
\return pointer to sqlite3_stmt instance or NULL on error
*/
void VFKReaderSQLite::PrepareStatement(const char *pszSQLCommand, unsigned int idx)
{
int rc;
CPLDebug("OGR-VFK", "VFKReaderDB::PrepareStatement(): %s", pszSQLCommand);
if (idx <= m_hStmt.size()) {
sqlite3_stmt *hStmt;
m_hStmt.push_back(hStmt);
}
rc = sqlite3_prepare(m_poDB, pszSQLCommand, -1,
&(m_hStmt[idx]), NULL);
// TODO(schwehr): if( rc == SQLITE_OK ) return NULL;
if (rc != SQLITE_OK) {
CPLError(CE_Failure, CPLE_AppDefined,
"In PrepareStatement(): sqlite3_prepare(%s):\n %s",
pszSQLCommand, sqlite3_errmsg(m_poDB));
if(m_hStmt[idx] != NULL) {
sqlite3_finalize(m_hStmt[idx]);
m_hStmt.erase(m_hStmt.begin() + idx);
}
}
}
/*!
\brief Execute prepared SQL statement
\param hStmt pointer to sqlite3_stmt
\return OGRERR_NONE on success
*/
OGRErr VFKReaderSQLite::ExecuteSQL(sqlite3_stmt *hStmt)
{
const int rc = sqlite3_step(hStmt);
if (rc != SQLITE_ROW) {
if (rc == SQLITE_DONE) {
sqlite3_finalize(hStmt);
return OGRERR_NOT_ENOUGH_DATA;
}
CPLError(CE_Failure, CPLE_AppDefined,
"In ExecuteSQL(): sqlite3_step:\n %s",
sqlite3_errmsg(m_poDB));
if (hStmt) {
sqlite3_finalize(hStmt);
}
return OGRERR_FAILURE;
}
return OGRERR_NONE;
}
/*!
\brief Execute SQL statement (SQLITE only)
\param pszSQLCommand SQL command to execute
\param bQuiet true to print debug message on failure instead of error message
\return OGRERR_NONE on success or OGRERR_FAILURE on failure
*/
OGRErr VFKReaderSQLite::ExecuteSQL( const char *pszSQLCommand, bool bQuiet )
{
char *pszErrMsg = NULL;
if( SQLITE_OK != sqlite3_exec(m_poDB, pszSQLCommand,
NULL, NULL, &pszErrMsg) )
{
if (!bQuiet)
CPLError(CE_Failure, CPLE_AppDefined,
"In ExecuteSQL(%s): %s",
pszSQLCommand, pszErrMsg);
else
CPLError(CE_Warning, CPLE_AppDefined,
"In ExecuteSQL(%s): %s",
pszSQLCommand, pszErrMsg);
return OGRERR_FAILURE;
}
return OGRERR_NONE;
}
OGRErr VFKReaderSQLite::ExecuteSQL(const char *pszSQLCommand, int& count)
{
OGRErr ret;
PrepareStatement(pszSQLCommand);
ret = ExecuteSQL(m_hStmt[0]); // TODO: solve
if (ret == OGRERR_NONE) {
count = sqlite3_column_int(m_hStmt[0], 0); // TODO:
}
sqlite3_finalize(m_hStmt[0]); // TODO
m_hStmt[0] = NULL; // TODO
return ret;
}
OGRErr VFKReaderSQLite::ExecuteSQL(std::vector<VFKDbValue>& record, int idx)
{
OGRErr ret;
ret = ExecuteSQL(m_hStmt[idx]);
// TODO: num_of_column == size
if (ret == OGRERR_NONE) {
for (unsigned int i = 0; i < record.size(); i++) { // TODO: iterator
VFKDbValue *value = &(record[i]);
switch (value->get_type()) {
case DT_INT:
value->set_int(sqlite3_column_int(m_hStmt[idx], i));
break;
case DT_BIGINT:
case DT_UBIGINT:
value->set_bigint(sqlite3_column_int64(m_hStmt[idx], i));
break;
case DT_DOUBLE:
value->set_double(sqlite3_column_double(m_hStmt[idx], i));
break;
case DT_TEXT:
value->set_text((char *)sqlite3_column_text(m_hStmt[idx], i));
break;
}
}
}
else {
/* hStmt should be already finalized by ExecuteSQL() */
if (idx > 0) {
m_hStmt.erase(m_hStmt.begin() + idx);
}
else { /* idx == 0 */
m_hStmt[idx] = NULL;
}
}
return ret;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2010 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "engine/engine.h"
#include "ResourceManager.h"
#include "ResourceShiftTask.h"
#include "resourcespawner/SampleTask.h"
#include "resourcespawner/SampleResultsTask.h"
#include "server/zone/objects/resource/ResourceContainer.h"
void ResourceManagerImplementation::initialize() {
Lua::init();
info("building resource tree");
resourceSpawner = new ResourceSpawner(zoneServer.get(), processor, objectManager);
info("loading configuration");
if(!loadConfigData()) {
loadDefaultConfig();
info("***** ERROR in configuration, using default values");
}
info("starting resource spawner");
startResourceSpawner();
info("resource manager initialized");
}
bool ResourceManagerImplementation::loadConfigFile() {
return runFile("scripts/resources/config.lua");
}
int ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {
if (eventType == ObserverEventType::POSTURECHANGED) {
CreatureObject* creature = (CreatureObject*) observable;
// Cancel Sampling on posture change
//Reference<SampleTask*> task = (SampleTask*) creature->getPendingTask("sample");
Reference<SampleResultsTask*> sampleResultsTask = (SampleResultsTask*) creature->getPendingTask("sampleresults");
if (task != NULL) {
task->stopSampling();
//creature->removePendingTask("sample");
if(sampleResultsTask != NULL) {
sampleResultsTask->cancel();
creature->removePendingTask("sampleresults");
}
creature->sendSystemMessage("@survey:sample_cancel");
}
}
return 1;
}
bool ResourceManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
String zonesString = getGlobalString("activeZones");
StringTokenizer zonesTokens(zonesString);
zonesTokens.setDelimeter(",");
while(zonesTokens.hasMoreTokens()) {
int token = zonesTokens.getIntToken();
resourceSpawner->addPlanet(token);
}
shiftInterval = getGlobalInt("averageShiftTime");
int aveduration = getGlobalInt("aveduration");
float spawnThrottling = float(getGlobalInt("spawnThrottling")) / 100.0f;
int lowerGateOverride = getGlobalInt("lowerGateOverride");
int maxSpawnQuantity = getGlobalInt("maxSpawnQuantity");
resourceSpawner->setSpawningParameters(aveduration,
spawnThrottling, lowerGateOverride, maxSpawnQuantity);
String minpoolinc = getGlobalString("minimumpoolincludes");
String minpoolexc = getGlobalString("minimumpoolexcludes");
resourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc);
String randpoolinc = getGlobalString("randompoolincludes");
String randpoolexc = getGlobalString("randompoolexcludes");
int randpoolsize = getGlobalInt("randompoolsize");
resourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize);
String fixedpoolinc = getGlobalString("fixedpoolincludes");
String fixedpoolexc = getGlobalString("fixedpoolexcludes");
resourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc);
String natpoolinc = getGlobalString("nativepoolincludes");
String natpoolexc = getGlobalString("nativepoolexcludes");
resourceSpawner->initializeNativePool(natpoolinc, natpoolexc);
return true;
}
void ResourceManagerImplementation::loadDefaultConfig() {
for(int i = 0;i < 10; ++i) {
resourceSpawner->addPlanet(i);
}
shiftInterval = 7200000;
resourceSpawner->setSpawningParameters(86400, 90, 1000, 0);
}
void ResourceManagerImplementation::stop() {
}
void ResourceManagerImplementation::startResourceSpawner() {
Locker _locker(_this);
resourceSpawner->start();
ResourceShiftTask* resourceShift = new ResourceShiftTask(_this);
resourceShift->schedule(shiftInterval);
}
void ResourceManagerImplementation::shiftResources() {
Locker _locker(_this);
resourceSpawner->shiftResources();
ResourceShiftTask* resourceShift = new ResourceShiftTask(_this);
resourceShift->schedule(shiftInterval);
}
void ResourceManagerImplementation::sendResourceListForSurvey(PlayerCreature* playerCreature, const int toolType, const String& surveyType) {
rlock();
try {
resourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType);
} catch (...) {
error("unreported exception caught in ResourceManagerImplementation::sendResourceListForSurvey");
}
runlock();
}
ResourceContainer* ResourceManagerImplementation::harvestResource(PlayerCreature* player, const String& type, const int quantity) {
return resourceSpawner->harvestResource(player, type, quantity);
}
void ResourceManagerImplementation::harvestResourceToPlayer(PlayerCreature* player, ResourceSpawn* resourceSpawn, const int quantity) {
resourceSpawner->harvestResource(player, resourceSpawn, quantity);
}
void ResourceManagerImplementation::sendSurvey(PlayerCreature* playerCreature, const String& resname) {
resourceSpawner->sendSurvey(playerCreature, resname);
}
void ResourceManagerImplementation::sendSample(PlayerCreature* playerCreature, const String& resname, const String& sampleAnimation) {
resourceSpawner->sendSample(playerCreature, resname, sampleAnimation);
playerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this);
}
void ResourceManagerImplementation::createResourceSpawn(PlayerCreature* playerCreature, const String& restype) {
Locker _locker(_this);
ResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype);
if (resourceSpawn != NULL) {
StringBuffer buffer;
buffer << "Spawned " << resourceSpawn->getName() << " of type " << resourceSpawn->getType();
playerCreature->sendSystemMessage(buffer.toString());
} else {
playerCreature->sendSystemMessage("Could not create spawn " + restype);
}
}
ResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) {
ResourceSpawn* spawn = NULL;
rlock();
try {
ResourceMap* resourceMap = resourceSpawner->getResourceMap();
spawn = resourceMap->get(spawnName);
} catch (...) {
}
runlock();
return spawn;
}
ResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, int zoneid) {
return resourceSpawner->getCurrentSpawn(restype, zoneid);
}
void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, int zoneid) {
list.removeAll();
rlock();
ManagedReference<ResourceSpawn*> resourceSpawn;
try {
ResourceMap* resourceMap = resourceSpawner->getResourceMap();
ZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneid);
if (zoneMap != NULL) {
for (int i = 0; i < zoneMap->size(); ++i) {
resourceSpawn = zoneMap->get(i);
if (resourceSpawn->getSurveyToolType() == type) {
list.add(resourceSpawn);
}
}
}
} catch (Exception& e) {
error(e.getMessage());
e.printStackTrace();
} catch (...) {
error("unreported exception caught in void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, int zoneid)");
}
runlock();
}
uint64 ResourceManagerImplementation::getAvailablePowerFromPlayer(PlayerCreature* player) {
SceneObject* inventory = player->getSlottedObject("inventory");
uint64 power = 0;
for (int i = 0; i < inventory->getContainerObjectsSize(); i++) {
ManagedReference<SceneObject*> tano = (SceneObject*) inventory->getContainerObject(i);
if (tano->isResourceContainer()) {
ResourceContainer* rcno = (ResourceContainer*) tano.get();
ResourceSpawn* spawn = rcno->getSpawnObject();
if (spawn != NULL && spawn->isEnergy()) {
int PE = spawn->getValueOf(3); // potential energy
if (PE > 500)
power += (unsigned long long) ( (PE /* * 1.0 */) / 500.0 * (rcno->getQuantity() /* * 1.0 */) );
else
power += rcno->getQuantity();
}
}
}
return power;
}
void ResourceManagerImplementation::removePowerFromPlayer(PlayerCreature* player, uint64 power) {
if (power == 0)
return;
SceneObject* inventory = player->getSlottedObject("inventory");
uint64 containerPower = 0;
for (int i = 0; i < inventory->getContainerObjectsSize(); i++ && power > 0) {
ManagedReference<SceneObject*> tano = inventory->getContainerObject(i);
if (tano->isResourceContainer()) {
ResourceContainer* rcno = (ResourceContainer*)tano.get();
ResourceSpawn* spawn = rcno->getSpawnObject();
if (spawn != NULL && spawn->isEnergy()) {
int PE = spawn->getAttributeValue(3); // potential energy
if (PE > 500)
containerPower = (unsigned long long) ( (PE /* * 1.0 */) / 500.0 * (rcno->getQuantity() /* * 1.0*/) );
else
containerPower = rcno->getQuantity();
if (containerPower > power) {
// remove
uint64 consumedUnits = (unsigned long long) ( (power /* * 1.0 */) / ( (containerPower /* * 1.0*/) / rcno->getQuantity() ) );
power = 0; // zero it down
rcno->setQuantity(rcno->getQuantity() - consumedUnits);
} else {
power -= containerPower;
inventory->removeObject(rcno, true);
rcno->destroyObjectFromDatabase(true);
}
}
}
}
}
void ResourceManagerImplementation::givePlayerResource(PlayerCreature* playerCreature, const String& restype, const int quantity) {
ManagedReference<ResourceSpawn* > spawn = getResourceSpawn(restype);
if(spawn == NULL) {
playerCreature->sendSystemMessage("Selected spawn does not exist, make sure to capitalize the first letter");
return;
}
ManagedReference<SceneObject*> inventory = playerCreature->getSlottedObject("inventory");
if(inventory != NULL && !inventory->hasFullContainerObjects()) {
ResourceContainer* newResource = spawn->createResource(quantity);
if(newResource != NULL) {
spawn->extractResource(-1, quantity);
inventory->broadcastObject(newResource, true);
inventory->addObject(newResource, -1, true);
newResource->updateToDatabase();
}
}
}
/// Resource Deed Methods
void ResourceManagerImplementation::addChildrenToDeedListBox(const String& name, ResourceDeedListBox* suil, bool parent) {
resourceSpawner->addToListBox(name, suil, parent);
}
<commit_msg>[Fixed] Error in previous commit<commit_after>/*
Copyright (C) 2010 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 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 Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.
In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.
Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.
*/
#include "engine/engine.h"
#include "ResourceManager.h"
#include "ResourceShiftTask.h"
#include "resourcespawner/SampleTask.h"
#include "resourcespawner/SampleResultsTask.h"
#include "server/zone/objects/resource/ResourceContainer.h"
void ResourceManagerImplementation::initialize() {
Lua::init();
info("building resource tree");
resourceSpawner = new ResourceSpawner(zoneServer.get(), processor, objectManager);
info("loading configuration");
if(!loadConfigData()) {
loadDefaultConfig();
info("***** ERROR in configuration, using default values");
}
info("starting resource spawner");
startResourceSpawner();
info("resource manager initialized");
}
bool ResourceManagerImplementation::loadConfigFile() {
return runFile("scripts/resources/config.lua");
}
int ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {
if (eventType == ObserverEventType::POSTURECHANGED) {
CreatureObject* creature = (CreatureObject*) observable;
// Cancel Sampling on posture change
Reference<SampleTask*> task = (SampleTask*) creature->getPendingTask("sample");
Reference<SampleResultsTask*> sampleResultsTask = (SampleResultsTask*) creature->getPendingTask("sampleresults");
if (task != NULL) {
task->stopSampling();
//creature->removePendingTask("sample");
if(sampleResultsTask != NULL) {
sampleResultsTask->cancel();
creature->removePendingTask("sampleresults");
}
creature->sendSystemMessage("@survey:sample_cancel");
}
}
return 1;
}
bool ResourceManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
String zonesString = getGlobalString("activeZones");
StringTokenizer zonesTokens(zonesString);
zonesTokens.setDelimeter(",");
while(zonesTokens.hasMoreTokens()) {
int token = zonesTokens.getIntToken();
resourceSpawner->addPlanet(token);
}
shiftInterval = getGlobalInt("averageShiftTime");
int aveduration = getGlobalInt("aveduration");
float spawnThrottling = float(getGlobalInt("spawnThrottling")) / 100.0f;
int lowerGateOverride = getGlobalInt("lowerGateOverride");
int maxSpawnQuantity = getGlobalInt("maxSpawnQuantity");
resourceSpawner->setSpawningParameters(aveduration,
spawnThrottling, lowerGateOverride, maxSpawnQuantity);
String minpoolinc = getGlobalString("minimumpoolincludes");
String minpoolexc = getGlobalString("minimumpoolexcludes");
resourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc);
String randpoolinc = getGlobalString("randompoolincludes");
String randpoolexc = getGlobalString("randompoolexcludes");
int randpoolsize = getGlobalInt("randompoolsize");
resourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize);
String fixedpoolinc = getGlobalString("fixedpoolincludes");
String fixedpoolexc = getGlobalString("fixedpoolexcludes");
resourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc);
String natpoolinc = getGlobalString("nativepoolincludes");
String natpoolexc = getGlobalString("nativepoolexcludes");
resourceSpawner->initializeNativePool(natpoolinc, natpoolexc);
return true;
}
void ResourceManagerImplementation::loadDefaultConfig() {
for(int i = 0;i < 10; ++i) {
resourceSpawner->addPlanet(i);
}
shiftInterval = 7200000;
resourceSpawner->setSpawningParameters(86400, 90, 1000, 0);
}
void ResourceManagerImplementation::stop() {
}
void ResourceManagerImplementation::startResourceSpawner() {
Locker _locker(_this);
resourceSpawner->start();
ResourceShiftTask* resourceShift = new ResourceShiftTask(_this);
resourceShift->schedule(shiftInterval);
}
void ResourceManagerImplementation::shiftResources() {
Locker _locker(_this);
resourceSpawner->shiftResources();
ResourceShiftTask* resourceShift = new ResourceShiftTask(_this);
resourceShift->schedule(shiftInterval);
}
void ResourceManagerImplementation::sendResourceListForSurvey(PlayerCreature* playerCreature, const int toolType, const String& surveyType) {
rlock();
try {
resourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType);
} catch (...) {
error("unreported exception caught in ResourceManagerImplementation::sendResourceListForSurvey");
}
runlock();
}
ResourceContainer* ResourceManagerImplementation::harvestResource(PlayerCreature* player, const String& type, const int quantity) {
return resourceSpawner->harvestResource(player, type, quantity);
}
void ResourceManagerImplementation::harvestResourceToPlayer(PlayerCreature* player, ResourceSpawn* resourceSpawn, const int quantity) {
resourceSpawner->harvestResource(player, resourceSpawn, quantity);
}
void ResourceManagerImplementation::sendSurvey(PlayerCreature* playerCreature, const String& resname) {
resourceSpawner->sendSurvey(playerCreature, resname);
}
void ResourceManagerImplementation::sendSample(PlayerCreature* playerCreature, const String& resname, const String& sampleAnimation) {
resourceSpawner->sendSample(playerCreature, resname, sampleAnimation);
playerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this);
}
void ResourceManagerImplementation::createResourceSpawn(PlayerCreature* playerCreature, const String& restype) {
Locker _locker(_this);
ResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype);
if (resourceSpawn != NULL) {
StringBuffer buffer;
buffer << "Spawned " << resourceSpawn->getName() << " of type " << resourceSpawn->getType();
playerCreature->sendSystemMessage(buffer.toString());
} else {
playerCreature->sendSystemMessage("Could not create spawn " + restype);
}
}
ResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) {
ResourceSpawn* spawn = NULL;
rlock();
try {
ResourceMap* resourceMap = resourceSpawner->getResourceMap();
spawn = resourceMap->get(spawnName);
} catch (...) {
}
runlock();
return spawn;
}
ResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, int zoneid) {
return resourceSpawner->getCurrentSpawn(restype, zoneid);
}
void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, int zoneid) {
list.removeAll();
rlock();
ManagedReference<ResourceSpawn*> resourceSpawn;
try {
ResourceMap* resourceMap = resourceSpawner->getResourceMap();
ZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneid);
if (zoneMap != NULL) {
for (int i = 0; i < zoneMap->size(); ++i) {
resourceSpawn = zoneMap->get(i);
if (resourceSpawn->getSurveyToolType() == type) {
list.add(resourceSpawn);
}
}
}
} catch (Exception& e) {
error(e.getMessage());
e.printStackTrace();
} catch (...) {
error("unreported exception caught in void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, int zoneid)");
}
runlock();
}
uint64 ResourceManagerImplementation::getAvailablePowerFromPlayer(PlayerCreature* player) {
SceneObject* inventory = player->getSlottedObject("inventory");
uint64 power = 0;
for (int i = 0; i < inventory->getContainerObjectsSize(); i++) {
ManagedReference<SceneObject*> tano = (SceneObject*) inventory->getContainerObject(i);
if (tano->isResourceContainer()) {
ResourceContainer* rcno = (ResourceContainer*) tano.get();
ResourceSpawn* spawn = rcno->getSpawnObject();
if (spawn != NULL && spawn->isEnergy()) {
int PE = spawn->getValueOf(3); // potential energy
if (PE > 500)
power += (unsigned long long) ( (PE /* * 1.0 */) / 500.0 * (rcno->getQuantity() /* * 1.0 */) );
else
power += rcno->getQuantity();
}
}
}
return power;
}
void ResourceManagerImplementation::removePowerFromPlayer(PlayerCreature* player, uint64 power) {
if (power == 0)
return;
SceneObject* inventory = player->getSlottedObject("inventory");
uint64 containerPower = 0;
for (int i = 0; i < inventory->getContainerObjectsSize(); i++ && power > 0) {
ManagedReference<SceneObject*> tano = inventory->getContainerObject(i);
if (tano->isResourceContainer()) {
ResourceContainer* rcno = (ResourceContainer*)tano.get();
ResourceSpawn* spawn = rcno->getSpawnObject();
if (spawn != NULL && spawn->isEnergy()) {
int PE = spawn->getAttributeValue(3); // potential energy
if (PE > 500)
containerPower = (unsigned long long) ( (PE /* * 1.0 */) / 500.0 * (rcno->getQuantity() /* * 1.0*/) );
else
containerPower = rcno->getQuantity();
if (containerPower > power) {
// remove
uint64 consumedUnits = (unsigned long long) ( (power /* * 1.0 */) / ( (containerPower /* * 1.0*/) / rcno->getQuantity() ) );
power = 0; // zero it down
rcno->setQuantity(rcno->getQuantity() - consumedUnits);
} else {
power -= containerPower;
inventory->removeObject(rcno, true);
rcno->destroyObjectFromDatabase(true);
}
}
}
}
}
void ResourceManagerImplementation::givePlayerResource(PlayerCreature* playerCreature, const String& restype, const int quantity) {
ManagedReference<ResourceSpawn* > spawn = getResourceSpawn(restype);
if(spawn == NULL) {
playerCreature->sendSystemMessage("Selected spawn does not exist, make sure to capitalize the first letter");
return;
}
ManagedReference<SceneObject*> inventory = playerCreature->getSlottedObject("inventory");
if(inventory != NULL && !inventory->hasFullContainerObjects()) {
ResourceContainer* newResource = spawn->createResource(quantity);
if(newResource != NULL) {
spawn->extractResource(-1, quantity);
inventory->broadcastObject(newResource, true);
inventory->addObject(newResource, -1, true);
newResource->updateToDatabase();
}
}
}
/// Resource Deed Methods
void ResourceManagerImplementation::addChildrenToDeedListBox(const String& name, ResourceDeedListBox* suil, bool parent) {
resourceSpawner->addToListBox(name, suil, parent);
}
<|endoftext|> |
<commit_before>#include "config.h"
#include "vm.hpp"
#include "vm/object_utils.hpp"
#include "objectmemory.hpp"
#include "primitives.hpp"
#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/integer.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "util/time.h"
#include <sys/time.h>
#include <time.h>
#include "windows_compat.h"
namespace rubinius {
void Time::init(STATE) {
GO(time_class).set(state->new_class("Time", G(object)));
G(time_class)->set_object_type(state, TimeType);
}
Time* Time::now(STATE, Object* self) {
struct timeval tv;
/* don't fill in the 2nd argument here. getting the timezone here
* this way is not portable and broken anyway.
*/
::gettimeofday(&tv, NULL);
Time* tm = state->new_object<Time>(G(time_class));
tm->seconds_ = tv.tv_sec;
tm->microseconds_ = tv.tv_usec;
tm->is_gmt(state, Qfalse);
tm->klass(state, as<Class>(self));
return tm;
}
// Taken from MRI
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
Time* Time::specific(STATE, Integer* sec, Integer* usec, Object* gmt) {
Time* tm = state->new_object<Time>(G(time_class));
if(sizeof(time_t) == sizeof(long long)) {
tm->seconds_ = sec->to_long_long();
tm->microseconds_ = usec->to_long_long();
} else {
tm->seconds_ = sec->to_native();
tm->microseconds_ = usec->to_native();
}
// Do a little overflow cleanup.
if(tm->microseconds_ >= 1000000) {
tm->seconds_ += tm->microseconds_ / 1000000;
tm->microseconds_ %= 1000000;
}
if(tm->microseconds_ < 0) {
tm->seconds_ += NDIV(tm->microseconds_,1000000);
tm->microseconds_ = NMOD(tm->microseconds_, 1000000);
}
tm->is_gmt(state, RTEST(gmt) ? Qtrue : Qfalse);
return tm;
}
Time* Time::from_array(STATE, Fixnum* sec, Fixnum* min, Fixnum* hour,
Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* usec,
Fixnum* isdst, Object* from_gmt) {
struct tm tm;
tm.tm_sec = sec->to_native();
if(tm.tm_sec < 0 || tm.tm_sec > 60) {
Exception::argument_error(state, "sec must be in 0..60");
}
tm.tm_min = min->to_native();
if(tm.tm_min < 0 || tm.tm_min > 60) {
Exception::argument_error(state, "min must be in 0..60");
}
tm.tm_hour = hour->to_native();
if(tm.tm_hour < 0 || tm.tm_hour > 24) {
Exception::argument_error(state, "hour must be in 0..24");
}
tm.tm_mday = mday->to_native();
if(tm.tm_mday < 1 || tm.tm_mday > 31) {
Exception::argument_error(state, "mday must be in 1..31");
}
tm.tm_mon = mon->to_native() - 1;
if(tm.tm_mon < 0 || tm.tm_mon > 11) {
Exception::argument_error(state, "mon must be in 0..11");
}
tm.tm_wday = -1;
#ifndef RBX_WINDOWS
tm.tm_gmtoff = 0;
tm.tm_zone = 0;
#endif
tm.tm_year = year->to_native() - 1900;
tm.tm_isdst = isdst->to_native();
time_t seconds = -1;
if(RTEST(from_gmt)) {
seconds = ::timegm(&tm);
} else {
tzset();
seconds = ::mktime(&tm);
}
int err = 0;
if(seconds == -1) {
int utc_p = from_gmt->true_p() ? 1 : 0;
seconds = mktime_extended(&tm, utc_p, &err);
}
if(err) return (Time*)Primitives::failure();
Time* obj = state->new_object<Time>(G(time_class));
obj->seconds_ = seconds;
obj->microseconds_ = usec->to_native();
obj->is_gmt(state, RTEST(from_gmt) ? Qtrue : Qfalse);
return obj;
}
Time* Time::dup(STATE) {
Time* tm = state->new_object<Time>(G(time_class));
tm->seconds_ = seconds_;
tm->microseconds_ = microseconds_;
tm->is_gmt(state, is_gmt_);
return tm;
}
Array* Time::calculate_decompose(STATE, Object* use_gmt) {
if(!decomposed_->nil_p()) return decomposed_;
time_t seconds = seconds_;
struct tm tm;
if(RTEST(use_gmt)) {
gmtime_r(&seconds, &tm);
} else {
tzset();
localtime_r(&seconds, &tm);
}
/* update Time::TM_FIELDS when changing order of fields */
Array* ary = Array::create(state, 11);
ary->set(state, 0, Integer::from(state, tm.tm_sec));
ary->set(state, 1, Integer::from(state, tm.tm_min));
ary->set(state, 2, Integer::from(state, tm.tm_hour));
ary->set(state, 3, Integer::from(state, tm.tm_mday));
ary->set(state, 4, Integer::from(state, tm.tm_mon + 1));
ary->set(state, 5, Integer::from(state, tm.tm_year + 1900));
ary->set(state, 6, Integer::from(state, tm.tm_wday));
ary->set(state, 7, Integer::from(state, tm.tm_yday + 1));
ary->set(state, 8, tm.tm_isdst ? Qtrue : Qfalse);
#ifdef HAVE_STRUCT_TM_TM_ZONE
ary->set(state, 9, String::create(state, tm.tm_zone));
#else
ary->set(state, 9, Qnil);
#endif
// Cache it.
decomposed(state, ary);
return ary;
}
#define MAX_STRFTIME_OUTPUT 128
String* Time::strftime(STATE, String* format) {
struct tm tm;
char str[MAX_STRFTIME_OUTPUT];
int is_gmt = 0;
time_t seconds = seconds_;
if(RTEST(is_gmt_)) {
is_gmt = 1;
gmtime_r(&seconds, &tm);
} else {
tzset();
localtime_r(&seconds, &tm);
}
struct timespec ts = { seconds, 0 };
size_t chars = ::strftime_extended(str, MAX_STRFTIME_OUTPUT,
format->c_str(), &tm, &ts, is_gmt);
str[MAX_STRFTIME_OUTPUT-1] = 0;
return String::create(state, str, chars);
}
}
<commit_msg>Silence gcc 4.5.2 warning about possibly uninitialized structure members.<commit_after>#include "config.h"
#include "vm.hpp"
#include "vm/object_utils.hpp"
#include "objectmemory.hpp"
#include "primitives.hpp"
#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/integer.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "util/time.h"
#include <sys/time.h>
#include <time.h>
#include "windows_compat.h"
namespace rubinius {
void Time::init(STATE) {
GO(time_class).set(state->new_class("Time", G(object)));
G(time_class)->set_object_type(state, TimeType);
}
Time* Time::now(STATE, Object* self) {
struct timeval tv;
/* don't fill in the 2nd argument here. getting the timezone here
* this way is not portable and broken anyway.
*/
::gettimeofday(&tv, NULL);
Time* tm = state->new_object<Time>(G(time_class));
tm->seconds_ = tv.tv_sec;
tm->microseconds_ = tv.tv_usec;
tm->is_gmt(state, Qfalse);
tm->klass(state, as<Class>(self));
return tm;
}
// Taken from MRI
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
Time* Time::specific(STATE, Integer* sec, Integer* usec, Object* gmt) {
Time* tm = state->new_object<Time>(G(time_class));
if(sizeof(time_t) == sizeof(long long)) {
tm->seconds_ = sec->to_long_long();
tm->microseconds_ = usec->to_long_long();
} else {
tm->seconds_ = sec->to_native();
tm->microseconds_ = usec->to_native();
}
// Do a little overflow cleanup.
if(tm->microseconds_ >= 1000000) {
tm->seconds_ += tm->microseconds_ / 1000000;
tm->microseconds_ %= 1000000;
}
if(tm->microseconds_ < 0) {
tm->seconds_ += NDIV(tm->microseconds_,1000000);
tm->microseconds_ = NMOD(tm->microseconds_, 1000000);
}
tm->is_gmt(state, RTEST(gmt) ? Qtrue : Qfalse);
return tm;
}
Time* Time::from_array(STATE, Fixnum* sec, Fixnum* min, Fixnum* hour,
Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* usec,
Fixnum* isdst, Object* from_gmt) {
struct tm tm;
tm.tm_sec = sec->to_native();
if(tm.tm_sec < 0 || tm.tm_sec > 60) {
Exception::argument_error(state, "sec must be in 0..60");
}
tm.tm_min = min->to_native();
if(tm.tm_min < 0 || tm.tm_min > 60) {
Exception::argument_error(state, "min must be in 0..60");
}
tm.tm_hour = hour->to_native();
if(tm.tm_hour < 0 || tm.tm_hour > 24) {
Exception::argument_error(state, "hour must be in 0..24");
}
tm.tm_mday = mday->to_native();
if(tm.tm_mday < 1 || tm.tm_mday > 31) {
Exception::argument_error(state, "mday must be in 1..31");
}
tm.tm_mon = mon->to_native() - 1;
if(tm.tm_mon < 0 || tm.tm_mon > 11) {
Exception::argument_error(state, "mon must be in 0..11");
}
tm.tm_wday = -1;
#ifndef RBX_WINDOWS
tm.tm_gmtoff = 0;
tm.tm_zone = 0;
#endif
tm.tm_year = year->to_native() - 1900;
tm.tm_isdst = isdst->to_native();
time_t seconds = -1;
if(RTEST(from_gmt)) {
seconds = ::timegm(&tm);
} else {
tzset();
seconds = ::mktime(&tm);
}
int err = 0;
if(seconds == -1) {
int utc_p = from_gmt->true_p() ? 1 : 0;
seconds = mktime_extended(&tm, utc_p, &err);
}
if(err) return (Time*)Primitives::failure();
Time* obj = state->new_object<Time>(G(time_class));
obj->seconds_ = seconds;
obj->microseconds_ = usec->to_native();
obj->is_gmt(state, RTEST(from_gmt) ? Qtrue : Qfalse);
return obj;
}
Time* Time::dup(STATE) {
Time* tm = state->new_object<Time>(G(time_class));
tm->seconds_ = seconds_;
tm->microseconds_ = microseconds_;
tm->is_gmt(state, is_gmt_);
return tm;
}
Array* Time::calculate_decompose(STATE, Object* use_gmt) {
if(!decomposed_->nil_p()) return decomposed_;
time_t seconds = seconds_;
struct tm tm = {0};
if(RTEST(use_gmt)) {
gmtime_r(&seconds, &tm);
} else {
tzset();
localtime_r(&seconds, &tm);
}
/* update Time::TM_FIELDS when changing order of fields */
Array* ary = Array::create(state, 11);
ary->set(state, 0, Integer::from(state, tm.tm_sec));
ary->set(state, 1, Integer::from(state, tm.tm_min));
ary->set(state, 2, Integer::from(state, tm.tm_hour));
ary->set(state, 3, Integer::from(state, tm.tm_mday));
ary->set(state, 4, Integer::from(state, tm.tm_mon + 1));
ary->set(state, 5, Integer::from(state, tm.tm_year + 1900));
ary->set(state, 6, Integer::from(state, tm.tm_wday));
ary->set(state, 7, Integer::from(state, tm.tm_yday + 1));
ary->set(state, 8, tm.tm_isdst ? Qtrue : Qfalse);
#ifdef HAVE_STRUCT_TM_TM_ZONE
ary->set(state, 9, String::create(state, tm.tm_zone));
#else
ary->set(state, 9, Qnil);
#endif
// Cache it.
decomposed(state, ary);
return ary;
}
#define MAX_STRFTIME_OUTPUT 128
String* Time::strftime(STATE, String* format) {
struct tm tm;
char str[MAX_STRFTIME_OUTPUT];
int is_gmt = 0;
time_t seconds = seconds_;
if(RTEST(is_gmt_)) {
is_gmt = 1;
gmtime_r(&seconds, &tm);
} else {
tzset();
localtime_r(&seconds, &tm);
}
struct timespec ts = { seconds, 0 };
size_t chars = ::strftime_extended(str, MAX_STRFTIME_OUTPUT,
format->c_str(), &tm, &ts, is_gmt);
str[MAX_STRFTIME_OUTPUT-1] = 0;
return String::create(state, str, chars);
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2018, Project Pluto. See LICENSE.
This code can read a TLE and compute a geocentric state vector,
formatted such that Find_Orb can then read it in. I did this
partly to test the hypothesis that if you compute a state vector
from Space-Track TLEs at their epoch, you get the "actual" motion.
That is to say, you could numerically integrate it to get a better
result. This turns out not to be the case. Space-Track TLEs may
be a best-fit to a set of observations or (as with my own TLEs)
a best fit to a numerically integrated ephemeris, but there
doesn't seem to be a way to improve them by doing a numerical
integration.
My second purpose was to be able to feed the state vector created
by this program into Find_Orb as an initial orbit guess. For that
purpose, it seems to work. You see large residuals as a result
of the difference between numerical integration and SGP4/SDP4.
But it gets you close enough that you can then do differential
corrections (least-squares fitting). */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "norad.h"
#include "watdefs.h"
#include "afuncs.h"
#define PI \
3.1415926535897932384626433832795028841971693993751058209749445923
int main( const int argc, const char **argv)
{
FILE *ifile;
const char *filename;
char line0[100], line1[100], line2[100];
int i;
const char *norad = NULL, *intl = NULL;
for( i = 2; i < argc; i++)
if( argv[i][0] == '-')
switch( argv[i][1])
{
case 'n':
norad = argv[i] + 2;
if( !*norad && i < argc - 1)
norad = argv[++i];
printf( "Looking for NORAD %s\n", norad);
break;
case 'i':
intl = argv[i] + 2;
if( !*intl && i < argc - 1)
intl = argv[++i];
printf( "Looking for international ID %s\n", intl);
break;
default:
printf( "'%s': unrecognized option\n", argv[i]);
return( -1);
break;
}
filename = (argc == 1 ? "all_tle.txt" : argv[1]);
ifile = fopen( filename, "rb");
if( !ifile)
{
fprintf( stderr, "Couldn't open '%s': ", filename);
perror( "");
return( -1);
}
*line0 = *line1 = '\0';
while( fgets( line2, sizeof( line2), ifile))
{
if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5))
&& (!intl || !memcmp( line1 + 9, intl, strlen( intl)))
&& *line2 == '2')
{
tle_t tle;
const int err_code = parse_elements( line1, line2, &tle);
if( err_code >= 0)
{
const int is_deep = select_ephemeris( &tle);
double state[6], state_j2000[6], precess_matrix[9];
double params[N_SAT_PARAMS];
const double epoch_tdt =
tle.epoch + td_minus_utc( tle.epoch) / seconds_per_day;
const double J2000 = 2451545.;
if( is_deep)
{
SDP4_init( params, &tle);
SDP4( 0., &tle, params, state, state + 3);
}
else
{
SGP4_init( params, &tle);
SGP4( 0., &tle, params, state, state + 3);
}
if( strlen( line0) < 60)
printf( "%s", line0);
setup_precession( precess_matrix, 2000. + (epoch_tdt - J2000) / 365.25, 2000.);
precess_vector( precess_matrix, state, state_j2000);
precess_vector( precess_matrix, state + 3, state_j2000 + 3);
printf( " %.6f %.6s\n", epoch_tdt, line1 + 9);
printf( " %.5f %.5f %.5f 0408 # Ctr 3 km sec eq\n",
state_j2000[0], state_j2000[1], state_j2000[2]);
printf( " %.5f %.5f %.5f 0 0 0\n",
state_j2000[3] / seconds_per_minute,
state_j2000[4] / seconds_per_minute,
state_j2000[5] / seconds_per_minute);
}
}
strcpy( line0, line1);
strcpy( line1, line2);
}
fclose( ifile);
return( 0);
}
<commit_msg>'get_vect' (code to compute a single state vector for a particular artsat) : improved command-line arg processing. You can specify a desired date/time (instead of only getting a state vector for the epoch of the elements). You can use a '-d' switch to request coords of date instead of the usual J2000.<commit_after>/* Copyright (C) 2018, Project Pluto. See LICENSE.
This code can read a TLE and compute a geocentric state vector,
formatted such that Find_Orb can then read it in. I did this
partly to test the hypothesis that if you compute a state vector
from Space-Track TLEs at their epoch, you get the "actual" motion.
That is to say, you could numerically integrate it to get a better
result. This turns out not to be the case. Space-Track TLEs may
be a best-fit to a set of observations or (as with my own TLEs)
a best fit to a numerically integrated ephemeris, but there
doesn't seem to be a way to improve them by doing a numerical
integration.
My second purpose was to be able to feed the state vector created
by this program into Find_Orb as an initial orbit guess. For that
purpose, it seems to work. You see large residuals as a result
of the difference between numerical integration and SGP4/SDP4.
But it gets you close enough that you can then do differential
corrections (least-squares fitting). */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "norad.h"
#include "watdefs.h"
#include "afuncs.h"
#include "date.h"
#define PI \
3.1415926535897932384626433832795028841971693993751058209749445923
int main( const int argc, const char **argv)
{
FILE *ifile;
const char *filename = "all_tle.txt";
char line0[100], line1[100], line2[100];
int i;
const char *norad = NULL, *intl = NULL;
double jd = 0.;
int is_j2000 = 1, is_equatorial = 1;
for( i = 1; i < argc; i++)
if( argv[i][0] == '-')
{
const char *arg = (i < argc - 1 && !argv[i][2]
? argv[i + 1] : argv[i] + 2);
switch( argv[i][1])
{
case 'n':
norad = arg;
printf( "Looking for NORAD %s\n", norad);
break;
case 'i':
intl = arg;
printf( "Looking for international ID %s\n", intl);
break;
case 't':
jd = get_time_from_string( 0., arg, FULL_CTIME_YMD, NULL);
break;
case 'd':
is_j2000 = 0;
break;
default:
printf( "'%s': unrecognized option\n", argv[i]);
return( -1);
break;
}
}
if( argc > 1 && argv[1][0] != '-')
filename = argv[1];
ifile = fopen( filename, "rb");
if( !ifile)
{
fprintf( stderr, "Couldn't open '%s': ", filename);
perror( "");
return( -1);
}
*line0 = *line1 = '\0';
while( fgets( line2, sizeof( line2), ifile))
{
if( *line1 == '1' && (!norad || !memcmp( line1 + 2, norad, 5))
&& (!intl || !memcmp( line1 + 9, intl, strlen( intl)))
&& *line2 == '2')
{
tle_t tle;
const int err_code = parse_elements( line1, line2, &tle);
if( err_code >= 0)
{
const int is_deep = select_ephemeris( &tle);
double state[6], state_j2000[6], precess_matrix[9];
double params[N_SAT_PARAMS], t_since;
const double epoch_tdt =
tle.epoch + td_minus_utc( tle.epoch) / seconds_per_day;
const double J2000 = 2451545.;
double *state_to_show;
if( !jd)
jd = epoch_tdt;
t_since = (jd - epoch_tdt) * minutes_per_day;
if( is_deep)
{
SDP4_init( params, &tle);
SDP4( t_since, &tle, params, state, state + 3);
}
else
{
SGP4_init( params, &tle);
SGP4( t_since, &tle, params, state, state + 3);
}
if( strlen( line0) < 60)
printf( "%s", line0);
setup_precession( precess_matrix, 2000. + (jd - J2000) / 365.25, 2000.);
precess_vector( precess_matrix, state, state_j2000);
precess_vector( precess_matrix, state + 3, state_j2000 + 3);
state_to_show = (is_j2000 ? state_j2000 : state);
printf( " %.6f %.6s\n", jd, line1 + 9);
printf( " %.5f %.5f %.5f 0408 # Ctr 3 km sec %s %s\n",
state_to_show[0], state_to_show[1], state_to_show[2],
is_equatorial ? "eq" : "ecl",
is_j2000 ? "" : "of_date");
printf( " %.5f %.5f %.5f 0 0 0\n",
state_to_show[3] / seconds_per_minute,
state_to_show[4] / seconds_per_minute,
state_to_show[5] / seconds_per_minute);
}
}
strcpy( line0, line1);
strcpy( line1, line2);
}
fclose( ifile);
return( 0);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: NeighborhoodIterators4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodInnerProduct.h"
// Software Guide : BeginLatex
//
// We now introduce a variation on convolution filtering that is useful when a
// convolution kernel is separable. In this example, we create a different
// neighborhood iterator for each axial direction of the image and then take
// separate inner products with a 1D discrete Gaussian kernel.
// The idea of using several neighborhood iterators at once has applications
// beyond convolution filtering and may improve efficiency when the size of
// the whole neighborhood relative to the portion of the neighborhood used
// in calculations becomes large.
//
// The only new class necessary for this example is the Gaussian operator.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGaussianOperator.h"
// Software Guide : EndCodeSnippet
int main( int argc, char ** argv )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFile outputImageFile sigma"
<< std::endl;
return -1;
}
typedef float PixelType;
typedef itk::Image< PixelType, 2 > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ConstNeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::ImageRegionIterator< ImageType> IteratorType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
ImageType::Pointer output = ImageType::New();
output->SetRegions(reader->GetOutput()->GetRequestedRegion());
output->Allocate();
itk::NeighborhoodInnerProduct<ImageType> innerProduct;
typedef itk::NeighborhoodAlgorithm
::ImageBoundaryFacesCalculator< ImageType > FaceCalculatorType;
FaceCalculatorType faceCalculator;
FaceCalculatorType::FaceListType faceList;
FaceCalculatorType::FaceListType::iterator fit;
IteratorType out;
NeighborhoodIteratorType it;
// Software Guide : BeginLatex
// The Gaussian operator, like the Sobel operator, is instantiated with a pixel
// type and a dimensionality. Additionally, we set the variance of the
// Gaussian, which has been read from the command line as standard deviation.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
itk::GaussianOperator< PixelType, 2 > gaussianOperator;
gaussianOperator.SetVariance( ::atof(argv[3]) * ::atof(argv[3]) );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The only further changes from the previous example are in the main loop.
// Once again we use the results from face calculator to construct a loop that
// processes boundary and non-boundary image regions separately. Separable
// convolution, however, requires an additional, outer loop over all the image
// dimensions. The direction of the Gaussian operator is reset at each
// iteration of the outer loop using the new dimension. The iterators change
// direction to match because they are initialized with the radius of the
// Gaussian operator.
//
// Input and output buffers are swapped at each iteration so that the output of
// the previous iteration becomes the input for the current iteration. The swap
// is not performed on the last iteration.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::Pointer input = reader->GetOutput();
for (unsigned int i = 0; i < ImageType::ImageDimension; ++i)
{
gaussianOperator.SetDirection(i);
gaussianOperator.CreateDirectional();
faceList = faceCalculator(input, output->GetRequestedRegion(),
gaussianOperator.GetRadius());
for ( fit=faceList.begin(); fit != faceList.end(); ++fit )
{
it = NeighborhoodIteratorType( gaussianOperator.GetRadius(),
input, *fit );
out = IteratorType( output, *fit );
for (it.GoToBegin(), out.GoToBegin(); ! it.IsAtEnd(); ++it, ++out)
{
out.Set( innerProduct(it, gaussianOperator) );
}
}
// Swap the input and output buffers
if (i != ImageType::ImageDimension - 1)
{
ImageType::Pointer tmp = input;
input = output;
output = tmp;
}
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output is rescaled and written as in the previous examples.
// Figure~\ref{fig:NeighborhoodExample4} shows the results of Gaussian blurring
// the image \code{Examples/Data/BrainT1Slice.png} using increasing
// kernel widths.
//
// \begin{figure} \centering
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4a.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4b.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4c.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4d.eps}
// \itkcaption[Gaussian blurring by convolution filtering]{Results of
// convolution filtering with a Gaussian kernel of increasing standard
// deviation $\sigma$. From left to right, $\sigma = 0$, $\sigma = 1$, $\sigma
// = 2$, $\sigma = 5$}
// \protect\label{fig:NeighborhoodExample4}
// \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter<
ImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput(output);
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return 0;
}
<commit_msg>ENH: Explanation for the increased brightness of the images in the figure.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: NeighborhoodIterators4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodInnerProduct.h"
// Software Guide : BeginLatex
//
// We now introduce a variation on convolution filtering that is useful when a
// convolution kernel is separable. In this example, we create a different
// neighborhood iterator for each axial direction of the image and then take
// separate inner products with a 1D discrete Gaussian kernel.
// The idea of using several neighborhood iterators at once has applications
// beyond convolution filtering and may improve efficiency when the size of
// the whole neighborhood relative to the portion of the neighborhood used
// in calculations becomes large.
//
// The only new class necessary for this example is the Gaussian operator.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGaussianOperator.h"
// Software Guide : EndCodeSnippet
int main( int argc, char ** argv )
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFile outputImageFile sigma"
<< std::endl;
return -1;
}
typedef float PixelType;
typedef itk::Image< PixelType, 2 > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ConstNeighborhoodIterator< ImageType > NeighborhoodIteratorType;
typedef itk::ImageRegionIterator< ImageType> IteratorType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
ImageType::Pointer output = ImageType::New();
output->SetRegions(reader->GetOutput()->GetRequestedRegion());
output->Allocate();
itk::NeighborhoodInnerProduct<ImageType> innerProduct;
typedef itk::NeighborhoodAlgorithm
::ImageBoundaryFacesCalculator< ImageType > FaceCalculatorType;
FaceCalculatorType faceCalculator;
FaceCalculatorType::FaceListType faceList;
FaceCalculatorType::FaceListType::iterator fit;
IteratorType out;
NeighborhoodIteratorType it;
// Software Guide : BeginLatex
// The Gaussian operator, like the Sobel operator, is instantiated with a pixel
// type and a dimensionality. Additionally, we set the variance of the
// Gaussian, which has been read from the command line as standard deviation.
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
itk::GaussianOperator< PixelType, 2 > gaussianOperator;
gaussianOperator.SetVariance( ::atof(argv[3]) * ::atof(argv[3]) );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The only further changes from the previous example are in the main loop.
// Once again we use the results from face calculator to construct a loop that
// processes boundary and non-boundary image regions separately. Separable
// convolution, however, requires an additional, outer loop over all the image
// dimensions. The direction of the Gaussian operator is reset at each
// iteration of the outer loop using the new dimension. The iterators change
// direction to match because they are initialized with the radius of the
// Gaussian operator.
//
// Input and output buffers are swapped at each iteration so that the output of
// the previous iteration becomes the input for the current iteration. The swap
// is not performed on the last iteration.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::Pointer input = reader->GetOutput();
for (unsigned int i = 0; i < ImageType::ImageDimension; ++i)
{
gaussianOperator.SetDirection(i);
gaussianOperator.CreateDirectional();
faceList = faceCalculator(input, output->GetRequestedRegion(),
gaussianOperator.GetRadius());
for ( fit=faceList.begin(); fit != faceList.end(); ++fit )
{
it = NeighborhoodIteratorType( gaussianOperator.GetRadius(),
input, *fit );
out = IteratorType( output, *fit );
for (it.GoToBegin(), out.GoToBegin(); ! it.IsAtEnd(); ++it, ++out)
{
out.Set( innerProduct(it, gaussianOperator) );
}
}
// Swap the input and output buffers
if (i != ImageType::ImageDimension - 1)
{
ImageType::Pointer tmp = input;
input = output;
output = tmp;
}
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output is rescaled and written as in the previous examples.
// Figure~\ref{fig:NeighborhoodExample4} shows the results of Gaussian blurring
// the image \code{Examples/Data/BrainT1Slice.png} using increasing
// kernel widths.
//
// \begin{figure}
// \centering
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4a.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4b.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4c.eps}
// \includegraphics[width=0.23\textwidth]{NeighborhoodIterators4d.eps}
// \itkcaption[Gaussian blurring by convolution filtering]{Results of
// convolution filtering with a Gaussian kernel of increasing standard
// deviation $\sigma$. From left to right, $\sigma = 0$, $\sigma = 1$, $\sigma
// = 2$, $\sigma = 5$. Increased blurring reduces contrast and changes the
// average intensity value of the image, which causes the image to appear
// brighter when rescaled.}
// \protect\label{fig:NeighborhoodExample4}
// \end{figure}
//
// Software Guide : EndLatex
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::ImageFileWriter< WriteImageType > WriterType;
typedef itk::RescaleIntensityImageFilter<
ImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
rescaler->SetInput(output);
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
writer->SetInput( rescaler->GetOutput() );
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "shared_state.hpp"
#include "thread_nexus.hpp"
#include "vm.hpp"
#include "builtin/thread.hpp"
#include "gc/managed.hpp"
#include "util/atomic.hpp"
#include "instruments/timing.hpp"
#include <time.h>
namespace rubinius {
bool ThreadNexus::yielding_p(VM* vm) {
return (vm->thread_phase() & cYielding) == cYielding;
}
VM* ThreadNexus::new_vm_solo(SharedState* shared, const char* name) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
uint32_t max_id = thread_ids_;
uint32_t id = ++thread_ids_;
if(id < max_id) {
rubinius::bug("exceeded maximum number of threads");
}
return new VM(id, *shared, name);
}
VM* ThreadNexus::new_vm(SharedState* shared, const char* name) {
VM* vm = new_vm_solo(shared, name);
add_vm(vm);
return vm;
}
void ThreadNexus::add_vm(VM* vm) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
if(vm->tracked_p()) return;
vm->set_tracked();
threads_.push_back(vm);
}
void ThreadNexus::delete_vm(VM* vm) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
threads_.remove(vm);
}
void ThreadNexus::after_fork_child(STATE) {
stop_ = false;
threads_lock_.init();
lock_.init(true);
wait_mutex_.init();
wait_condition_.init();
VM* current = state->vm();
for(ThreadList::iterator i = threads_.begin();
i != threads_.end();
++i) {
if(VM* vm = (*i)->as_vm()) {
if(vm == current) continue;
if(Thread* thread = vm->thread.get()) {
if(!thread->nil_p()) {
thread->unlock_after_fork(state);
thread->stopped();
}
}
vm->reset_parked();
}
}
threads_.clear();
threads_.push_back(current);
state->shared().set_root_vm(current);
}
static const char* phase_name(VM* vm) {
switch(vm->thread_phase()) {
case ThreadNexus::cStop:
return "cStop";
case ThreadNexus::cManaged:
return "cManaged";
case ThreadNexus::cUnmanaged:
return "cUnmanaged";
case ThreadNexus::cWaiting:
return "cWaiting";
case ThreadNexus::cYielding:
return "cYielding";
}
}
static void abort_deadlock(ThreadList& threads, VM* vm) {
utilities::logger::fatal("thread nexus: thread will not yield: %s, %s",
vm->name().c_str(), phase_name(vm));
for(ThreadList::iterator i = threads.begin();
i != threads.end();
++i)
{
if(VM* other_vm = (*i)->as_vm()) {
utilities::logger::fatal("thread %d: %s, %s",
other_vm->thread_id(), other_vm->name().c_str(), phase_name(other_vm));
}
}
rubinius::abort();
}
#define RBX_MAX_STOP_ITERATIONS 10000
bool ThreadNexus::locking(VM* vm) {
timer::StopWatch<timer::nanoseconds> timer(
vm->metrics().lock.stop_the_world_ns);
for(ThreadList::iterator i = threads_.begin();
i != threads_.end();
++i)
{
if(VM* other_vm = (*i)->as_vm()) {
while(true) {
if(vm == other_vm || yielding_p(other_vm)) break;
bool yielding = false;
for(int j = 0; j < RBX_MAX_STOP_ITERATIONS; j++) {
if(yielding_p(other_vm)) {
yielding = true;
break;
}
static int delay[] = { 1, 21, 270, 482, 268, 169, 224, 481,
262, 79, 133, 448, 227, 249, 22 };
static int modulo = sizeof(delay) / sizeof(int);
static struct timespec ts = {0, 0};
atomic::memory_barrier();
ts.tv_nsec = delay[j % modulo];
nanosleep(&ts, NULL);
}
if(yielding) break;
// This thread never yielded; we could be deadlocked.
if(vm->memory()->can_gc()) abort_deadlock(threads_, other_vm);
}
}
}
return true;
}
void ThreadNexus::yielding(VM* vm) {
{
utilities::thread::Mutex::LockGuard guard(wait_mutex_);
if(stop_) {
vm->set_thread_phase(cWaiting);
wait_condition_.wait(wait_mutex_);
}
}
{
utilities::thread::Mutex::LockGuard guard(lock_);
vm->set_thread_phase(cManaged);
}
}
void ThreadNexus::become_managed(VM* vm) {
if(lock_.try_lock() == utilities::thread::cLocked) {
vm->set_thread_phase(cManaged);
lock_.unlock();
} else {
yielding(vm);
}
}
bool ThreadNexus::lock_or_yield(VM* vm) {
if(lock_.try_lock() == utilities::thread::cLocked) {
if(locking(vm)) return true;
} else {
yielding(vm);
}
return false;
}
bool ThreadNexus::lock_or_wait(VM* vm) {
while(true) {
if(lock_.try_lock() == utilities::thread::cLocked) {
set_stop();
if(locking(vm)) return true;
} else {
yielding(vm);
set_stop();
}
}
return false;
}
}
<commit_msg>Pulled check outside of loop.<commit_after>#include "shared_state.hpp"
#include "thread_nexus.hpp"
#include "vm.hpp"
#include "builtin/thread.hpp"
#include "gc/managed.hpp"
#include "util/atomic.hpp"
#include "instruments/timing.hpp"
#include <time.h>
namespace rubinius {
bool ThreadNexus::yielding_p(VM* vm) {
return (vm->thread_phase() & cYielding) == cYielding;
}
VM* ThreadNexus::new_vm_solo(SharedState* shared, const char* name) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
uint32_t max_id = thread_ids_;
uint32_t id = ++thread_ids_;
if(id < max_id) {
rubinius::bug("exceeded maximum number of threads");
}
return new VM(id, *shared, name);
}
VM* ThreadNexus::new_vm(SharedState* shared, const char* name) {
VM* vm = new_vm_solo(shared, name);
add_vm(vm);
return vm;
}
void ThreadNexus::add_vm(VM* vm) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
if(vm->tracked_p()) return;
vm->set_tracked();
threads_.push_back(vm);
}
void ThreadNexus::delete_vm(VM* vm) {
utilities::thread::SpinLock::LockGuard guard(threads_lock_);
threads_.remove(vm);
}
void ThreadNexus::after_fork_child(STATE) {
stop_ = false;
threads_lock_.init();
lock_.init(true);
wait_mutex_.init();
wait_condition_.init();
VM* current = state->vm();
for(ThreadList::iterator i = threads_.begin();
i != threads_.end();
++i) {
if(VM* vm = (*i)->as_vm()) {
if(vm == current) continue;
if(Thread* thread = vm->thread.get()) {
if(!thread->nil_p()) {
thread->unlock_after_fork(state);
thread->stopped();
}
}
vm->reset_parked();
}
}
threads_.clear();
threads_.push_back(current);
state->shared().set_root_vm(current);
}
static const char* phase_name(VM* vm) {
switch(vm->thread_phase()) {
case ThreadNexus::cStop:
return "cStop";
case ThreadNexus::cManaged:
return "cManaged";
case ThreadNexus::cUnmanaged:
return "cUnmanaged";
case ThreadNexus::cWaiting:
return "cWaiting";
case ThreadNexus::cYielding:
return "cYielding";
}
}
static void abort_deadlock(ThreadList& threads, VM* vm) {
utilities::logger::fatal("thread nexus: thread will not yield: %s, %s",
vm->name().c_str(), phase_name(vm));
for(ThreadList::iterator i = threads.begin();
i != threads.end();
++i)
{
if(VM* other_vm = (*i)->as_vm()) {
utilities::logger::fatal("thread %d: %s, %s",
other_vm->thread_id(), other_vm->name().c_str(), phase_name(other_vm));
}
}
rubinius::abort();
}
#define RBX_MAX_STOP_ITERATIONS 10000
bool ThreadNexus::locking(VM* vm) {
timer::StopWatch<timer::nanoseconds> timer(
vm->metrics().lock.stop_the_world_ns);
for(ThreadList::iterator i = threads_.begin();
i != threads_.end();
++i)
{
if(VM* other_vm = (*i)->as_vm()) {
if(vm == other_vm || yielding_p(other_vm)) continue;
while(true) {
bool yielding = false;
for(int j = 0; j < RBX_MAX_STOP_ITERATIONS; j++) {
if(yielding_p(other_vm)) {
yielding = true;
break;
}
static int delay[] = { 1, 21, 270, 482, 268, 169, 224, 481,
262, 79, 133, 448, 227, 249, 22 };
static int modulo = sizeof(delay) / sizeof(int);
static struct timespec ts = {0, 0};
atomic::memory_barrier();
ts.tv_nsec = delay[j % modulo];
nanosleep(&ts, NULL);
}
if(yielding) break;
// This thread never yielded; we could be deadlocked.
if(vm->memory()->can_gc()) abort_deadlock(threads_, other_vm);
}
}
}
return true;
}
void ThreadNexus::yielding(VM* vm) {
{
utilities::thread::Mutex::LockGuard guard(wait_mutex_);
if(stop_) {
vm->set_thread_phase(cWaiting);
wait_condition_.wait(wait_mutex_);
}
}
{
utilities::thread::Mutex::LockGuard guard(lock_);
vm->set_thread_phase(cManaged);
}
}
void ThreadNexus::become_managed(VM* vm) {
if(lock_.try_lock() == utilities::thread::cLocked) {
vm->set_thread_phase(cManaged);
lock_.unlock();
} else {
yielding(vm);
}
}
bool ThreadNexus::lock_or_yield(VM* vm) {
if(lock_.try_lock() == utilities::thread::cLocked) {
if(locking(vm)) return true;
} else {
yielding(vm);
}
return false;
}
bool ThreadNexus::lock_or_wait(VM* vm) {
while(true) {
if(lock_.try_lock() == utilities::thread::cLocked) {
set_stop();
if(locking(vm)) return true;
} else {
yielding(vm);
set_stop();
}
}
return false;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/examples/examples_window.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/process_util.h"
#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/models/combobox_model.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/examples/bubble_example.h"
#include "ui/views/examples/button_example.h"
#include "ui/views/examples/combobox_example.h"
#include "ui/views/examples/double_split_view_example.h"
#include "ui/views/examples/link_example.h"
#include "ui/views/examples/message_box_example.h"
#include "ui/views/examples/native_theme_button_example.h"
#include "ui/views/examples/native_theme_checkbox_example.h"
#include "ui/views/examples/progress_bar_example.h"
#include "ui/views/examples/radio_button_example.h"
#include "ui/views/examples/scroll_view_example.h"
#include "ui/views/examples/single_split_view_example.h"
#include "ui/views/examples/tabbed_pane_example.h"
#include "ui/views/examples/table_example.h"
#include "ui/views/examples/text_example.h"
#include "ui/views/examples/textfield_example.h"
#include "ui/views/examples/throbber_example.h"
#include "ui/views/examples/tree_view_example.h"
#include "ui/views/examples/widget_example.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#if !defined(USE_AURA)
#include "ui/views/examples/menu_example.h"
#endif
namespace views {
namespace examples {
// Model for the examples that are being added via AddExample().
class ComboboxModelExampleList : public ui::ComboboxModel {
public:
ComboboxModelExampleList() {}
virtual ~ComboboxModelExampleList() {}
// Overridden from ui::ComboboxModel:
virtual int GetItemCount() OVERRIDE { return example_list_.size(); }
virtual string16 GetItemAt(int index) OVERRIDE {
return UTF8ToUTF16(example_list_[index]->example_title());
}
View* GetItemViewAt(int index) {
return example_list_[index]->example_view();
}
void AddExample(ExampleBase* example) {
example_list_.push_back(example);
}
private:
std::vector<ExampleBase*> example_list_;
DISALLOW_COPY_AND_ASSIGN(ComboboxModelExampleList);
};
class ExamplesWindowContents : public WidgetDelegateView,
public ComboboxListener {
public:
explicit ExamplesWindowContents(bool quit_on_close)
: combobox_(new Combobox(&combobox_model_)),
example_shown_(new View),
status_label_(new Label),
quit_on_close_(quit_on_close) {
instance_ = this;
combobox_->set_listener(this);
}
virtual ~ExamplesWindowContents() {}
// Prints a message in the status area, at the bottom of the window.
void SetStatus(const std::string& status) {
status_label_->SetText(UTF8ToUTF16(status));
}
static ExamplesWindowContents* instance() { return instance_; }
private:
// Overridden from WidgetDelegateView:
virtual bool CanResize() const OVERRIDE { return true; }
virtual bool CanMaximize() const OVERRIDE { return true; }
virtual string16 GetWindowTitle() const OVERRIDE {
return ASCIIToUTF16("Views Examples");
}
virtual View* GetContentsView() OVERRIDE { return this; }
virtual void WindowClosing() OVERRIDE {
instance_ = NULL;
if (quit_on_close_)
MessageLoopForUI::current()->Quit();
}
// Overridden from View:
virtual void ViewHierarchyChanged(bool is_add,
View* parent,
View* child) OVERRIDE {
if (is_add && child == this)
InitExamplesWindow();
}
// Overridden from ComboboxListener:
virtual void ItemChanged(Combobox* combo_box,
int prev_index,
int new_index) OVERRIDE {
DCHECK(combo_box && combo_box == combobox_);
DCHECK(new_index < combobox_model_.GetItemCount());
example_shown_->RemoveAllChildViews(false);
example_shown_->AddChildView(combobox_model_.GetItemViewAt(new_index));
example_shown_->RequestFocus();
SetStatus(std::string());
Layout();
}
// Creates the layout within the examples window.
void InitExamplesWindow() {
AddExamples();
set_background(Background::CreateStandardPanelBackground());
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddPaddingColumn(0, 5);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 5);
layout->AddPaddingRow(0, 5);
layout->StartRow(0 /* no expand */, 0);
layout->AddView(combobox_);
if (combobox_model_.GetItemCount() > 0) {
layout->StartRow(1, 0);
example_shown_->SetLayoutManager(new FillLayout());
example_shown_->AddChildView(combobox_model_.GetItemViewAt(0));
layout->AddView(example_shown_);
}
layout->StartRow(0 /* no expand */, 0);
layout->AddView(status_label_);
layout->AddPaddingRow(0, 5);
}
// Adds all the individual examples to the combobox model.
void AddExamples() {
combobox_model_.AddExample(new TreeViewExample);
combobox_model_.AddExample(new TableExample);
combobox_model_.AddExample(new BubbleExample);
combobox_model_.AddExample(new ButtonExample);
combobox_model_.AddExample(new ComboboxExample);
combobox_model_.AddExample(new DoubleSplitViewExample);
combobox_model_.AddExample(new LinkExample);
#if !defined(USE_AURA)
combobox_model_.AddExample(new MenuExample);
#endif
combobox_model_.AddExample(new MessageBoxExample);
combobox_model_.AddExample(new NativeThemeButtonExample);
combobox_model_.AddExample(new NativeThemeCheckboxExample);
combobox_model_.AddExample(new ProgressBarExample);
combobox_model_.AddExample(new RadioButtonExample);
combobox_model_.AddExample(new ScrollViewExample);
combobox_model_.AddExample(new SingleSplitViewExample);
combobox_model_.AddExample(new TabbedPaneExample);
combobox_model_.AddExample(new TextExample);
combobox_model_.AddExample(new TextfieldExample);
combobox_model_.AddExample(new ThrobberExample);
combobox_model_.AddExample(new WidgetExample);
}
static ExamplesWindowContents* instance_;
ComboboxModelExampleList combobox_model_;
Combobox* combobox_;
View* example_shown_;
Label* status_label_;
bool quit_on_close_;
DISALLOW_COPY_AND_ASSIGN(ExamplesWindowContents);
};
// static
ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL;
void ShowExamplesWindow(bool quit_on_close) {
if (ExamplesWindowContents::instance()) {
ExamplesWindowContents::instance()->GetWidget()->Activate();
} else {
Widget::CreateWindowWithBounds(new ExamplesWindowContents(quit_on_close),
gfx::Rect(0, 0, 850, 300))->Show();
}
}
void LogStatus(const std::string& string) {
ExamplesWindowContents::instance()->SetStatus(string);
}
} // namespace examples
} // namespace views
<commit_msg>views: Fixes leak in ComboboxModelExampleList.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/examples/examples_window.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/memory/scoped_vector.h"
#include "base/process_util.h"
#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/ui_base_paths.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/examples/bubble_example.h"
#include "ui/views/examples/button_example.h"
#include "ui/views/examples/combobox_example.h"
#include "ui/views/examples/double_split_view_example.h"
#include "ui/views/examples/link_example.h"
#include "ui/views/examples/message_box_example.h"
#include "ui/views/examples/native_theme_button_example.h"
#include "ui/views/examples/native_theme_checkbox_example.h"
#include "ui/views/examples/progress_bar_example.h"
#include "ui/views/examples/radio_button_example.h"
#include "ui/views/examples/scroll_view_example.h"
#include "ui/views/examples/single_split_view_example.h"
#include "ui/views/examples/tabbed_pane_example.h"
#include "ui/views/examples/table_example.h"
#include "ui/views/examples/text_example.h"
#include "ui/views/examples/textfield_example.h"
#include "ui/views/examples/throbber_example.h"
#include "ui/views/examples/tree_view_example.h"
#include "ui/views/examples/widget_example.h"
#include "ui/views/focus/accelerator_handler.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#if !defined(USE_AURA)
#include "ui/views/examples/menu_example.h"
#endif
namespace views {
namespace examples {
// Model for the examples that are being added via AddExample().
class ComboboxModelExampleList : public ui::ComboboxModel {
public:
ComboboxModelExampleList() {}
virtual ~ComboboxModelExampleList() {}
// Overridden from ui::ComboboxModel:
virtual int GetItemCount() OVERRIDE { return example_list_.size(); }
virtual string16 GetItemAt(int index) OVERRIDE {
return UTF8ToUTF16(example_list_[index]->example_title());
}
View* GetItemViewAt(int index) {
return example_list_[index]->example_view();
}
void AddExample(ExampleBase* example) {
example_list_.push_back(example);
}
private:
ScopedVector<ExampleBase> example_list_;
DISALLOW_COPY_AND_ASSIGN(ComboboxModelExampleList);
};
class ExamplesWindowContents : public WidgetDelegateView,
public ComboboxListener {
public:
explicit ExamplesWindowContents(bool quit_on_close)
: combobox_(new Combobox(&combobox_model_)),
example_shown_(new View),
status_label_(new Label),
quit_on_close_(quit_on_close) {
instance_ = this;
combobox_->set_listener(this);
}
virtual ~ExamplesWindowContents() {}
// Prints a message in the status area, at the bottom of the window.
void SetStatus(const std::string& status) {
status_label_->SetText(UTF8ToUTF16(status));
}
static ExamplesWindowContents* instance() { return instance_; }
private:
// Overridden from WidgetDelegateView:
virtual bool CanResize() const OVERRIDE { return true; }
virtual bool CanMaximize() const OVERRIDE { return true; }
virtual string16 GetWindowTitle() const OVERRIDE {
return ASCIIToUTF16("Views Examples");
}
virtual View* GetContentsView() OVERRIDE { return this; }
virtual void WindowClosing() OVERRIDE {
instance_ = NULL;
if (quit_on_close_)
MessageLoopForUI::current()->Quit();
}
// Overridden from View:
virtual void ViewHierarchyChanged(bool is_add,
View* parent,
View* child) OVERRIDE {
if (is_add && child == this)
InitExamplesWindow();
}
// Overridden from ComboboxListener:
virtual void ItemChanged(Combobox* combo_box,
int prev_index,
int new_index) OVERRIDE {
DCHECK(combo_box && combo_box == combobox_);
DCHECK(new_index < combobox_model_.GetItemCount());
example_shown_->RemoveAllChildViews(false);
example_shown_->AddChildView(combobox_model_.GetItemViewAt(new_index));
example_shown_->RequestFocus();
SetStatus(std::string());
Layout();
}
// Creates the layout within the examples window.
void InitExamplesWindow() {
AddExamples();
set_background(Background::CreateStandardPanelBackground());
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddPaddingColumn(0, 5);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 5);
layout->AddPaddingRow(0, 5);
layout->StartRow(0 /* no expand */, 0);
layout->AddView(combobox_);
if (combobox_model_.GetItemCount() > 0) {
layout->StartRow(1, 0);
example_shown_->SetLayoutManager(new FillLayout());
example_shown_->AddChildView(combobox_model_.GetItemViewAt(0));
layout->AddView(example_shown_);
}
layout->StartRow(0 /* no expand */, 0);
layout->AddView(status_label_);
layout->AddPaddingRow(0, 5);
}
// Adds all the individual examples to the combobox model.
void AddExamples() {
combobox_model_.AddExample(new TreeViewExample);
combobox_model_.AddExample(new TableExample);
combobox_model_.AddExample(new BubbleExample);
combobox_model_.AddExample(new ButtonExample);
combobox_model_.AddExample(new ComboboxExample);
combobox_model_.AddExample(new DoubleSplitViewExample);
combobox_model_.AddExample(new LinkExample);
#if !defined(USE_AURA)
combobox_model_.AddExample(new MenuExample);
#endif
combobox_model_.AddExample(new MessageBoxExample);
combobox_model_.AddExample(new NativeThemeButtonExample);
combobox_model_.AddExample(new NativeThemeCheckboxExample);
combobox_model_.AddExample(new ProgressBarExample);
combobox_model_.AddExample(new RadioButtonExample);
combobox_model_.AddExample(new ScrollViewExample);
combobox_model_.AddExample(new SingleSplitViewExample);
combobox_model_.AddExample(new TabbedPaneExample);
combobox_model_.AddExample(new TextExample);
combobox_model_.AddExample(new TextfieldExample);
combobox_model_.AddExample(new ThrobberExample);
combobox_model_.AddExample(new WidgetExample);
}
static ExamplesWindowContents* instance_;
ComboboxModelExampleList combobox_model_;
Combobox* combobox_;
View* example_shown_;
Label* status_label_;
bool quit_on_close_;
DISALLOW_COPY_AND_ASSIGN(ExamplesWindowContents);
};
// static
ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL;
void ShowExamplesWindow(bool quit_on_close) {
if (ExamplesWindowContents::instance()) {
ExamplesWindowContents::instance()->GetWidget()->Activate();
} else {
Widget::CreateWindowWithBounds(new ExamplesWindowContents(quit_on_close),
gfx::Rect(0, 0, 850, 300))->Show();
}
}
void LogStatus(const std::string& string) {
ExamplesWindowContents::instance()->SetStatus(string);
}
} // namespace examples
} // namespace views
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractSelectedRows.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkExtractSelectedRows.h"
#include "vtkAnnotation.h"
#include "vtkAnnotationLayers.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataArray.h"
#include "vtkEdgeListIterator.h"
#include "vtkEventForwarderCommand.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSignedCharArray.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVertexListIterator.h"
#include <vtksys/stl/map>
#include <vector>
vtkStandardNewMacro(vtkExtractSelectedRows);
//----------------------------------------------------------------------------
vtkExtractSelectedRows::vtkExtractSelectedRows()
{
this->AddOriginalRowIdsArray = false;
this->SetNumberOfInputPorts(3);
}
//----------------------------------------------------------------------------
vtkExtractSelectedRows::~vtkExtractSelectedRows()
{
}
//----------------------------------------------------------------------------
int vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info)
{
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable");
return 1;
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
return 1;
}
else if (port == 2)
{
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAnnotationLayers");
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(1, in);
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(2, in);
}
//----------------------------------------------------------------------------
int vtkExtractSelectedRows::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkTable* input = vtkTable::GetData(inputVector[0]);
vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]);
vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
if(!inputSelection && !inputAnnotations)
{
vtkErrorMacro("No vtkSelection or vtkAnnotationLayers provided as input.");
return 0;
}
vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
int numSelections = 0;
if(inputSelection)
{
selection->DeepCopy(inputSelection);
numSelections++;
}
// If input annotations are provided, extract their selections only if
// they are enabled and not hidden.
if(inputAnnotations)
{
for(unsigned int i=0; i<inputAnnotations->GetNumberOfAnnotations(); ++i)
{
vtkAnnotation* a = inputAnnotations->GetAnnotation(i);
if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) &&
a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) ||
(a->GetInformation()->Has(vtkAnnotation::ENABLE()) &&
a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 &&
a->GetInformation()->Has(vtkAnnotation::HIDE()) &&
a->GetInformation()->Get(vtkAnnotation::HIDE())==1))
{
continue;
}
selection->Union(a->GetSelection());
numSelections++;
}
}
// Handle case where there was no input selection and no enabled, non-hidden
// annotations
if(numSelections == 0)
{
output->ShallowCopy(input);
return 1;
}
// Convert the selection to an INDICES selection
vtkSmartPointer<vtkSelection> converted;
converted.TakeReference(vtkConvertSelection::ToSelectionType(
selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW));
if (!converted.GetPointer())
{
vtkErrorMacro("Selection conversion to INDICES failed.");
return 0;
}
vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New();
originalRowIds->SetName("vtkOriginalRowIds");
output->GetRowData()->CopyStructure(input->GetRowData());
for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i)
{
vtkSelectionNode* node = converted->GetNode(i);
if (node->GetFieldType() == vtkSelectionNode::ROW)
{
vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList());
if (list)
{
int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE());
if (inverse)
{
vtkIdType numRows = input->GetNumberOfRows(); //How many rows are in the whole dataset
for (vtkIdType j = 0; j < numRows; ++j)
{
if(list->LookupValue(j) < 0)
{
output->InsertNextRow(input->GetRow(j));
if (this->AddOriginalRowIdsArray)
{
originalRowIds->InsertNextValue(j);
}
}
}
}
else
{
vtkIdType numTuples = list->GetNumberOfTuples();
for (vtkIdType j = 0; j < numTuples; ++j)
{
vtkIdType val = list->GetValue(j);
output->InsertNextRow(input->GetRow(val));
if (this->AddOriginalRowIdsArray)
{
originalRowIds->InsertNextValue(val);
}
}
}
}
}
}
if (this->AddOriginalRowIdsArray)
{
output->AddColumn(originalRowIds);
}
originalRowIds->Delete();
return 1;
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "AddOriginalRowIdsArray: " << this->AddOriginalRowIdsArray <<
endl;
}
<commit_msg>vtkExtractSelectedRows only works with IdTypeArray.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractSelectedRows.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkExtractSelectedRows.h"
#include "vtkAnnotation.h"
#include "vtkAnnotationLayers.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataArray.h"
#include "vtkEdgeListIterator.h"
#include "vtkEventForwarderCommand.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSignedCharArray.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTree.h"
#include "vtkVertexListIterator.h"
#include <vtksys/stl/map>
#include <vector>
vtkStandardNewMacro(vtkExtractSelectedRows);
//----------------------------------------------------------------------------
vtkExtractSelectedRows::vtkExtractSelectedRows()
{
this->AddOriginalRowIdsArray = false;
this->SetNumberOfInputPorts(3);
}
//----------------------------------------------------------------------------
vtkExtractSelectedRows::~vtkExtractSelectedRows()
{
}
//----------------------------------------------------------------------------
int vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info)
{
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable");
return 1;
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
return 1;
}
else if (port == 2)
{
info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAnnotationLayers");
return 1;
}
return 0;
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(1, in);
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(2, in);
}
template <class T>
void vtkCopySelectedRows(
vtkAbstractArray* list, vtkTable* input,
vtkTable* output, vtkIdTypeArray* originalRowIds,
vtkExtractSelectedRows* self)
{
bool addOriginalRowIdsArray = self->GetAddOriginalRowIdsArray();
const T* rawPtr = static_cast<T*>(list->GetVoidPointer(0));
vtkIdType numTuples = list->GetNumberOfTuples();
if (list->GetNumberOfComponents() != 1 && numTuples > 0)
{
vtkGenericWarningMacro("NumberOfComponents expected to be 1.");
}
for (vtkIdType j = 0; j < numTuples; ++j)
{
vtkIdType val = rawPtr[j];
output->InsertNextRow(input->GetRow(val));
if (addOriginalRowIdsArray)
{
originalRowIds->InsertNextValue(val);
}
}
}
//----------------------------------------------------------------------------
int vtkExtractSelectedRows::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkTable* input = vtkTable::GetData(inputVector[0]);
vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]);
vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
if(!inputSelection && !inputAnnotations)
{
vtkErrorMacro("No vtkSelection or vtkAnnotationLayers provided as input.");
return 0;
}
vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
int numSelections = 0;
if(inputSelection)
{
selection->DeepCopy(inputSelection);
numSelections++;
}
// If input annotations are provided, extract their selections only if
// they are enabled and not hidden.
if(inputAnnotations)
{
for(unsigned int i=0; i<inputAnnotations->GetNumberOfAnnotations(); ++i)
{
vtkAnnotation* a = inputAnnotations->GetAnnotation(i);
if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) &&
a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) ||
(a->GetInformation()->Has(vtkAnnotation::ENABLE()) &&
a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 &&
a->GetInformation()->Has(vtkAnnotation::HIDE()) &&
a->GetInformation()->Get(vtkAnnotation::HIDE())==1))
{
continue;
}
selection->Union(a->GetSelection());
numSelections++;
}
}
// Handle case where there was no input selection and no enabled, non-hidden
// annotations
if(numSelections == 0)
{
output->ShallowCopy(input);
return 1;
}
// Convert the selection to an INDICES selection
vtkSmartPointer<vtkSelection> converted;
converted.TakeReference(vtkConvertSelection::ToSelectionType(
selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW));
if (!converted.GetPointer())
{
vtkErrorMacro("Selection conversion to INDICES failed.");
return 0;
}
vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New();
originalRowIds->SetName("vtkOriginalRowIds");
output->GetRowData()->CopyStructure(input->GetRowData());
for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i)
{
vtkSelectionNode* node = converted->GetNode(i);
if (node->GetFieldType() == vtkSelectionNode::ROW)
{
vtkAbstractArray* list = node->GetSelectionList();
if (list)
{
int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE());
if (inverse)
{
vtkIdType numRows = input->GetNumberOfRows(); //How many rows are in the whole dataset
for (vtkIdType j = 0; j < numRows; ++j)
{
if(list->LookupValue(j) < 0)
{
output->InsertNextRow(input->GetRow(j));
if (this->AddOriginalRowIdsArray)
{
originalRowIds->InsertNextValue(j);
}
}
}
}
else
{
switch (list->GetDataType())
{
vtkTemplateMacro(vtkCopySelectedRows<VTK_TT>(list, input, output, originalRowIds, this));
}
}
}
}
}
if (this->AddOriginalRowIdsArray)
{
output->AddColumn(originalRowIds);
}
originalRowIds->Delete();
return 1;
}
//----------------------------------------------------------------------------
void vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "AddOriginalRowIdsArray: " << this->AddOriginalRowIdsArray <<
endl;
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
//
// 'LIKELIHOOD AND MINIMIZATION' RooFit tutorial macro #610
//
// Visualization of errors from a covariance matrix
//
//
//
// 04/2009 - Wouter Verkerke
//
/////////////////////////////////////////////////////////////////////////
#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooRealVar.h"
#include "RooDataHist.h"
#include "RooGaussian.h"
#include "RooAddPdf.h"
#include "RooPlot.h"
#include "TCanvas.h"
using namespace RooFit ;
void rf610_visualerror()
{
// S e t u p e x a m p l e f i t
// ---------------------------------------
// Create sum of two Gaussians p.d.f. with factory
RooRealVar x("x","x",-10,10) ;
RooRealVar m("m","m",0,-10,10) ;
RooRealVar s("s","s",2,1,50) ;
RooGaussian sig("sig","sig",x,m,s) ;
RooRealVar m2("m2","m2",-1,-10,10) ;
RooRealVar s2("s2","s2",6,1,50) ;
RooGaussian bkg("bkg","bkg",x,m2,s2) ;
RooRealVar fsig("fsig","fsig",0.33,0,1) ;
RooAddPdf model("model","model",RooArgList(sig,bkg),fsig) ;
// Create binned dataset
x.setBins(25) ;
RooAbsData* d = model.generateBinned(x,1000) ;
// Perform fit and save fit result
RooFitResult* r = model.fitTo(*d,Save()) ;
// V i s u a l i z e f i t e r r o r
// -------------------------------------
// Make plot frame
RooPlot* frame = x.frame(Bins(40),Title("P.d.f with visualized 1-sigma error band")) ;
d->plotOn(frame) ;
// Visualize 1-sigma error encoded in fit result 'r' as orange band using linear error propagation
// This results in an error band that is by construction symmetric
//
// The linear error is calculated as
// error(x) = Z* F_a(x) * Corr(a,a') F_a'(x)
//
// where F_a(x) = [ f(x,a+da) - f(x,a-da) ] / 2,
//
// with f(x) = the plotted curve
// 'da' = error taken from the fit result
// Corr(a,a') = the correlation matrix from the fit result
// Z = requested significance 'Z sigma band'
//
// The linear method is fast (required 2*N evaluations of the curve, where N is the number of parameters),
// but may not be accurate in the presence of strong correlations (~>0.9) and at Z>2 due to linear and
// Gaussian approximations made
//
model.plotOn(frame,VisualizeError(*r,1),FillColor(kOrange)) ;
// Calculate error using sampling method and visualize as dashed red line.
//
// In this method a number of curves is calculated with variations of the parameter values, as sampled
// from a multi-variate Gaussian p.d.f. that is constructed from the fit results covariance matrix.
// The error(x) is determined by calculating a central interval that capture N% of the variations
// for each valye of x, where N% is controlled by Z (i.e. Z=1 gives N=68%). The number of sampling curves
// is chosen to be such that at least 100 curves are expected to be outside the N% interval, and is minimally
// 100 (e.g. Z=1->Ncurve=356, Z=2->Ncurve=2156)) Intervals from the sampling method can be asymmetric,
// and may perform better in the presence of strong correlations, but may take (much) longer to calculate
model.plotOn(frame,VisualizeError(*r,1,kFALSE),DrawOption("L"),LineWidth(2),LineColor(kRed)) ;
// Perform the same type of error visualization on the background component only.
// The VisualizeError() option can generally applied to _any_ kind of plot (components, asymmetries, efficiencies etc..)
model.plotOn(frame,VisualizeError(*r,1),FillColor(kOrange),Components("bkg")) ;
model.plotOn(frame,VisualizeError(*r,1,kFALSE),DrawOption("L"),LineWidth(2),LineColor(kRed),Components("bkg"),LineStyle(kDashed)) ;
// Overlay central value
model.plotOn(frame) ;
model.plotOn(frame,Components("bkg"),LineStyle(kDashed)) ;
d->plotOn(frame) ;
frame->SetMinimum(0) ;
frame->GetYaxis()->SetTitleOffset(1.4);
// V i s u a l i z e p a r t i a l f i t e r r o r
// ------------------------------------------------------
// Make plot frame
RooPlot* frame2 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from (m,m2)")) ;
// Visualize partial error. For partial error visualization the covariance matrix is first reduced as follows
// ___ -1
// Vred = V22 = V11 - V12 * V22 * V21
//
// Where V11,V12,V21,V22 represent a block decomposition of the covariance matrix into observables that
// are propagated (labeled by index '1') and that are not propagated (labeled by index '2'), and V22bar
// is the Shur complement of V22, calculated as shown above
//
// (Note that Vred is _not_ a simple sub-matrix of V)
// Propagate partial error due to shape parameters (m,m2) using linear and sampling method
model.plotOn(frame2,VisualizeError(*r,RooArgSet(m,m2),2),FillColor(kCyan)) ;
model.plotOn(frame2,Components("bkg"),VisualizeError(*r,RooArgSet(m,m2),2),FillColor(kCyan)) ;
model.plotOn(frame2) ;
model.plotOn(frame2,Components("bkg"),LineStyle(kDashed)) ;
frame2->SetMinimum(0) ;
frame2->GetYaxis()->SetTitleOffset(1.8);
// Make plot frame
RooPlot* frame3 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from (s,s2)")) ;
// Propagate partial error due to yield parameter using linear and sampling method
model.plotOn(frame3,VisualizeError(*r,RooArgSet(s,s2),2),FillColor(kGreen)) ;
model.plotOn(frame3,Components("bkg"),VisualizeError(*r,RooArgSet(s,s2),2),FillColor(kGreen)) ;
model.plotOn(frame3) ;
model.plotOn(frame3,Components("bkg"),LineStyle(kDashed)) ;
frame3->SetMinimum(0) ;
frame3->GetYaxis()->SetTitleOffset(1.8);
// Make plot frame
RooPlot* frame4 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from fsig")) ;
// Propagate partial error due to yield parameter using linear and sampling method
model.plotOn(frame4,VisualizeError(*r,RooArgSet(fsig),2),FillColor(kMagenta)) ;
model.plotOn(frame4,Components("bkg"),VisualizeError(*r,RooArgSet(fsig),2),FillColor(kMagenta)) ;
model.plotOn(frame4) ;
model.plotOn(frame4,Components("bkg"),LineStyle(kDashed)) ;
frame4->SetMinimum(0) ;
frame4->GetYaxis()->SetTitleOffset(1.8);
TCanvas* c = new TCanvas("rf610_visualerror","rf610_visualerror",800,800) ;
c->Divide(2,2) ;
c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame->Draw() ;
c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->Draw() ;
c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->Draw() ;
c->cd(4) ; gPad->SetLeftMargin(0.15) ; frame4->Draw() ;
}
<commit_msg>Add missing include.<commit_after>/////////////////////////////////////////////////////////////////////////
//
// 'LIKELIHOOD AND MINIMIZATION' RooFit tutorial macro #610
//
// Visualization of errors from a covariance matrix
//
//
//
// 04/2009 - Wouter Verkerke
//
/////////////////////////////////////////////////////////////////////////
#ifndef __CINT__
#include "RooGlobalFunc.h"
#endif
#include "RooRealVar.h"
#include "RooDataHist.h"
#include "RooGaussian.h"
#include "RooAddPdf.h"
#include "RooPlot.h"
#include "TCanvas.h"
#include "TAxis.h"
using namespace RooFit ;
void rf610_visualerror()
{
// S e t u p e x a m p l e f i t
// ---------------------------------------
// Create sum of two Gaussians p.d.f. with factory
RooRealVar x("x","x",-10,10) ;
RooRealVar m("m","m",0,-10,10) ;
RooRealVar s("s","s",2,1,50) ;
RooGaussian sig("sig","sig",x,m,s) ;
RooRealVar m2("m2","m2",-1,-10,10) ;
RooRealVar s2("s2","s2",6,1,50) ;
RooGaussian bkg("bkg","bkg",x,m2,s2) ;
RooRealVar fsig("fsig","fsig",0.33,0,1) ;
RooAddPdf model("model","model",RooArgList(sig,bkg),fsig) ;
// Create binned dataset
x.setBins(25) ;
RooAbsData* d = model.generateBinned(x,1000) ;
// Perform fit and save fit result
RooFitResult* r = model.fitTo(*d,Save()) ;
// V i s u a l i z e f i t e r r o r
// -------------------------------------
// Make plot frame
RooPlot* frame = x.frame(Bins(40),Title("P.d.f with visualized 1-sigma error band")) ;
d->plotOn(frame) ;
// Visualize 1-sigma error encoded in fit result 'r' as orange band using linear error propagation
// This results in an error band that is by construction symmetric
//
// The linear error is calculated as
// error(x) = Z* F_a(x) * Corr(a,a') F_a'(x)
//
// where F_a(x) = [ f(x,a+da) - f(x,a-da) ] / 2,
//
// with f(x) = the plotted curve
// 'da' = error taken from the fit result
// Corr(a,a') = the correlation matrix from the fit result
// Z = requested significance 'Z sigma band'
//
// The linear method is fast (required 2*N evaluations of the curve, where N is the number of parameters),
// but may not be accurate in the presence of strong correlations (~>0.9) and at Z>2 due to linear and
// Gaussian approximations made
//
model.plotOn(frame,VisualizeError(*r,1),FillColor(kOrange)) ;
// Calculate error using sampling method and visualize as dashed red line.
//
// In this method a number of curves is calculated with variations of the parameter values, as sampled
// from a multi-variate Gaussian p.d.f. that is constructed from the fit results covariance matrix.
// The error(x) is determined by calculating a central interval that capture N% of the variations
// for each valye of x, where N% is controlled by Z (i.e. Z=1 gives N=68%). The number of sampling curves
// is chosen to be such that at least 100 curves are expected to be outside the N% interval, and is minimally
// 100 (e.g. Z=1->Ncurve=356, Z=2->Ncurve=2156)) Intervals from the sampling method can be asymmetric,
// and may perform better in the presence of strong correlations, but may take (much) longer to calculate
model.plotOn(frame,VisualizeError(*r,1,kFALSE),DrawOption("L"),LineWidth(2),LineColor(kRed)) ;
// Perform the same type of error visualization on the background component only.
// The VisualizeError() option can generally applied to _any_ kind of plot (components, asymmetries, efficiencies etc..)
model.plotOn(frame,VisualizeError(*r,1),FillColor(kOrange),Components("bkg")) ;
model.plotOn(frame,VisualizeError(*r,1,kFALSE),DrawOption("L"),LineWidth(2),LineColor(kRed),Components("bkg"),LineStyle(kDashed)) ;
// Overlay central value
model.plotOn(frame) ;
model.plotOn(frame,Components("bkg"),LineStyle(kDashed)) ;
d->plotOn(frame) ;
frame->SetMinimum(0) ;
frame->GetYaxis()->SetTitleOffset(1.4);
// V i s u a l i z e p a r t i a l f i t e r r o r
// ------------------------------------------------------
// Make plot frame
RooPlot* frame2 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from (m,m2)")) ;
// Visualize partial error. For partial error visualization the covariance matrix is first reduced as follows
// ___ -1
// Vred = V22 = V11 - V12 * V22 * V21
//
// Where V11,V12,V21,V22 represent a block decomposition of the covariance matrix into observables that
// are propagated (labeled by index '1') and that are not propagated (labeled by index '2'), and V22bar
// is the Shur complement of V22, calculated as shown above
//
// (Note that Vred is _not_ a simple sub-matrix of V)
// Propagate partial error due to shape parameters (m,m2) using linear and sampling method
model.plotOn(frame2,VisualizeError(*r,RooArgSet(m,m2),2),FillColor(kCyan)) ;
model.plotOn(frame2,Components("bkg"),VisualizeError(*r,RooArgSet(m,m2),2),FillColor(kCyan)) ;
model.plotOn(frame2) ;
model.plotOn(frame2,Components("bkg"),LineStyle(kDashed)) ;
frame2->SetMinimum(0) ;
frame2->GetYaxis()->SetTitleOffset(1.8);
// Make plot frame
RooPlot* frame3 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from (s,s2)")) ;
// Propagate partial error due to yield parameter using linear and sampling method
model.plotOn(frame3,VisualizeError(*r,RooArgSet(s,s2),2),FillColor(kGreen)) ;
model.plotOn(frame3,Components("bkg"),VisualizeError(*r,RooArgSet(s,s2),2),FillColor(kGreen)) ;
model.plotOn(frame3) ;
model.plotOn(frame3,Components("bkg"),LineStyle(kDashed)) ;
frame3->SetMinimum(0) ;
frame3->GetYaxis()->SetTitleOffset(1.8);
// Make plot frame
RooPlot* frame4 = x.frame(Bins(40),Title("Visualization of 2-sigma partial error from fsig")) ;
// Propagate partial error due to yield parameter using linear and sampling method
model.plotOn(frame4,VisualizeError(*r,RooArgSet(fsig),2),FillColor(kMagenta)) ;
model.plotOn(frame4,Components("bkg"),VisualizeError(*r,RooArgSet(fsig),2),FillColor(kMagenta)) ;
model.plotOn(frame4) ;
model.plotOn(frame4,Components("bkg"),LineStyle(kDashed)) ;
frame4->SetMinimum(0) ;
frame4->GetYaxis()->SetTitleOffset(1.8);
TCanvas* c = new TCanvas("rf610_visualerror","rf610_visualerror",800,800) ;
c->Divide(2,2) ;
c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame->Draw() ;
c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->Draw() ;
c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->Draw() ;
c->cd(4) ; gPad->SetLeftMargin(0.15) ; frame4->Draw() ;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: webdavprovider.hxx,v $
* $Revision: 1.10 $
*
* 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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX
#include <rtl/ref.hxx>
#include <com/sun/star/beans/Property.hpp>
#include "DAVSessionFactory.hxx"
#include <ucbhelper/providerhelper.hxx>
#include "PropertyMap.hxx"
namespace webdav_ucp {
//=========================================================================
// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38
// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
"vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH 19
#define HTTP_URL_SCHEME "http"
#define HTTP_URL_SCHEME_LENGTH 4
#define HTTPS_URL_SCHEME "https"
#define HTTPS_URL_SCHEME_LENGTH 5
#define FTP_URL_SCHEME "ftp"
#define HTTP_CONTENT_TYPE \
"application/" HTTP_URL_SCHEME "-content"
#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
"application/" WEBDAV_URL_SCHEME "-collection"
//=========================================================================
class ContentProvider : public ::ucbhelper::ContentProviderImplHelper
{
rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
PropertyMap * m_pProps;
public:
ContentProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
virtual ~ContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContent > SAL_CALL
queryContent( const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( ::com::sun::star::ucb::IllegalIdentifierException,
::com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
{ return m_xDAVSessionFactory; }
bool getProperty( const ::rtl::OUString & rPropName,
::com::sun::star::beans::Property & rProp,
bool bStrict = false );
};
}
#endif
<commit_msg>INTEGRATION: CWS tkr10 (1.9.58); FILE MERGED 2008/05/19 09:26:53 tkr 1.9.58.2: RESYNC: (1.9-1.10); FILE MERGED 2008/02/12 14:05:04 tkr 1.9.58.1: i84676 neon and gnome-vfs2<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: webdavprovider.hxx,v $
* $Revision: 1.11 $
*
* 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 _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX
#include <rtl/ref.hxx>
#include <com/sun/star/beans/Property.hpp>
#include "DAVSessionFactory.hxx"
#include <ucbhelper/providerhelper.hxx>
#include "PropertyMap.hxx"
namespace webdav_ucp {
//=========================================================================
// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
"com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38
// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
"vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH 19
#define HTTP_URL_SCHEME "http"
#define HTTP_URL_SCHEME_LENGTH 4
#define HTTPS_URL_SCHEME "https"
#define HTTPS_URL_SCHEME_LENGTH 5
#define DAV_URL_SCHEME "dav"
#define DAV_URL_SCHEME_LENGTH 3
#define DAVS_URL_SCHEME "davs"
#define DAVS_URL_SCHEME_LENGTH 4
#define FTP_URL_SCHEME "ftp"
#define HTTP_CONTENT_TYPE \
"application/" HTTP_URL_SCHEME "-content"
#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
"application/" WEBDAV_URL_SCHEME "-collection"
//=========================================================================
class ContentProvider : public ::ucbhelper::ContentProviderImplHelper
{
rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
PropertyMap * m_pProps;
public:
ContentProvider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
virtual ~ContentProvider();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
XSERVICEINFO_DECL()
// XContentProvider
virtual ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContent > SAL_CALL
queryContent( const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& Identifier )
throw( ::com::sun::star::ucb::IllegalIdentifierException,
::com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
{ return m_xDAVSessionFactory; }
bool getProperty( const ::rtl::OUString & rPropName,
::com::sun::star::beans::Property & rProp,
bool bStrict = false );
};
}
#endif
<|endoftext|> |
<commit_before>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
// 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 DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "isel-opt"
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;
/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
/// into single compound nodes like RecordChild.
static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
const CodeGenDAGPatterns &CGP) {
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// If we have a scope node, walk down all of the children.
if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
OwningPtr<Matcher> Child(Scope->takeChild(i));
ContractNodes(Child, CGP);
Scope->resetChild(i, Child.take());
}
return;
}
// If we found a movechild node with a node that comes in a 'foochild' form,
// transform it.
if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
Matcher *New = 0;
if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
RM->getResultNo());
if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
if (New) {
// Insert the new node.
New->setNext(MatcherPtr.take());
MatcherPtr.reset(New);
// Remove the old one.
MC->setNext(MC->getNext()->takeNext());
return ContractNodes(MatcherPtr, CGP);
}
}
// Zap movechild -> moveparent.
if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
if (MoveParentMatcher *MP =
dyn_cast<MoveParentMatcher>(MC->getNext())) {
MatcherPtr.reset(MP->takeNext());
return ContractNodes(MatcherPtr, CGP);
}
// Turn EmitNode->MarkFlagResults->CompleteMatch into
// MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
// MorphNodeTo formation. This is safe because MarkFlagResults never refers
// to the root of the pattern.
if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
// Unlink the two nodes from the list.
Matcher *EmitNode = MatcherPtr.take();
Matcher *MFR = EmitNode->takeNext();
Matcher *Tail = MFR->takeNext();
// Relink them.
MatcherPtr.reset(MFR);
MFR->setNext(EmitNode);
EmitNode->setNext(Tail);
return ContractNodes(MatcherPtr, CGP);
}
// Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
if (CompleteMatchMatcher *CM =
dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
// We can only use MorphNodeTo if the result values match up.
unsigned RootResultFirst = EN->getFirstResultSlot();
bool ResultsMatch = true;
for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
if (CM->getResult(i) != RootResultFirst+i)
ResultsMatch = false;
// If the selected node defines a subset of the flag/chain results, we
// can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
// matched pattern has a chain but the root node doesn't.
const PatternToMatch &Pattern = CM->getPattern();
if (!EN->hasChain() &&
Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
ResultsMatch = false;
// If the matched node has a flag and the output root doesn't, we can't
// use MorphNodeTo.
//
// NOTE: Strictly speaking, we don't have to check for the flag here
// because the code in the pattern generator doesn't handle it right. We
// do it anyway for thoroughness.
if (!EN->hasOutFlag() &&
Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
ResultsMatch = false;
// If the root result node defines more results than the source root node
// *and* has a chain or flag input, then we can't match it because it
// would end up replacing the extra result with the chain/flag.
#if 0
if ((EN->hasFlag() || EN->hasChain()) &&
EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
ResultMatch = false;
#endif
if (ResultsMatch) {
const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
VTs.data(), VTs.size(),
Operands.data(),Operands.size(),
EN->hasChain(), EN->hasInFlag(),
EN->hasOutFlag(),
EN->hasMemRefs(),
EN->getNumFixedArityOperands(),
Pattern));
return;
}
// FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
// variants.
}
ContractNodes(N->getNextPtr(), CGP);
// If we have a CheckType/CheckChildType/Record node followed by a
// CheckOpcode, invert the two nodes. We prefer to do structural checks
// before type checks, as this opens opportunities for factoring on targets
// like X86 where many operations are valid on multiple types.
if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
isa<RecordMatcher>(N)) &&
isa<CheckOpcodeMatcher>(N->getNext())) {
// Unlink the two nodes from the list.
Matcher *CheckType = MatcherPtr.take();
Matcher *CheckOpcode = CheckType->takeNext();
Matcher *Tail = CheckOpcode->takeNext();
// Relink them.
MatcherPtr.reset(CheckOpcode);
CheckOpcode->setNext(CheckType);
CheckType->setNext(Tail);
return ContractNodes(MatcherPtr, CGP);
}
}
/// SinkPatternPredicates - Pattern predicates can be checked at any level of
/// the matching tree. The generator dumps them at the top level of the pattern
/// though, which prevents factoring from being able to see past them. This
/// optimization sinks them as far down into the pattern as possible.
///
/// Conceptually, we'd like to sink these predicates all the way to the last
/// matcher predicate in the series. However, it turns out that some
/// ComplexPatterns have side effects on the graph, so we really don't want to
/// run a the complex pattern if the pattern predicate will fail. For this
/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
///
static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
// Recursively scan for a PatternPredicate.
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// Walk down all members of a scope node.
if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
OwningPtr<Matcher> Child(Scope->takeChild(i));
SinkPatternPredicates(Child);
Scope->resetChild(i, Child.take());
}
return;
}
// If this node isn't a CheckPatternPredicateMatcher we keep scanning until
// we find one.
CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
if (CPPM == 0)
return SinkPatternPredicates(N->getNextPtr());
// Ok, we found one, lets try to sink it. Check if we can sink it past the
// next node in the chain. If not, we won't be able to change anything and
// might as well bail.
if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
return;
// Okay, we know we can sink it past at least one node. Unlink it from the
// chain and scan for the new insertion point.
MatcherPtr.take(); // Don't delete CPPM.
MatcherPtr.reset(CPPM->takeNext());
N = MatcherPtr.get();
while (N->getNext()->isSafeToReorderWithPatternPredicate())
N = N->getNext();
// At this point, we want to insert CPPM after N.
CPPM->setNext(N->takeNext());
N->setNext(CPPM);
}
/// FactorNodes - Turn matches like this:
/// Scope
/// OPC_CheckType i32
/// ABC
/// OPC_CheckType i32
/// XYZ
/// into:
/// OPC_CheckType i32
/// Scope
/// ABC
/// XYZ
///
static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// If this is not a push node, just scan for one.
ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
if (Scope == 0)
return FactorNodes(N->getNextPtr());
// Okay, pull together the children of the scope node into a vector so we can
// inspect it more easily. While we're at it, bucket them up by the hash
// code of their first predicate.
SmallVector<Matcher*, 32> OptionsToMatch;
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
// Factor the subexpression.
OwningPtr<Matcher> Child(Scope->takeChild(i));
FactorNodes(Child);
if (Matcher *N = Child.take())
OptionsToMatch.push_back(N);
}
SmallVector<Matcher*, 32> NewOptionsToMatch;
// Loop over options to match, merging neighboring patterns with identical
// starting nodes into a shared matcher.
for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
// Find the set of matchers that start with this node.
Matcher *Optn = OptionsToMatch[OptionIdx++];
if (OptionIdx == e) {
NewOptionsToMatch.push_back(Optn);
continue;
}
// See if the next option starts with the same matcher. If the two
// neighbors *do* start with the same matcher, we can factor the matcher out
// of at least these two patterns. See what the maximal set we can merge
// together is.
SmallVector<Matcher*, 8> EqualMatchers;
EqualMatchers.push_back(Optn);
// Factor all of the known-equal matchers after this one into the same
// group.
while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
// If we found a non-equal matcher, see if it is contradictory with the
// current node. If so, we know that the ordering relation between the
// current sets of nodes and this node don't matter. Look past it to see if
// we can merge anything else into this matching group.
unsigned Scan = OptionIdx;
while (1) {
while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
++Scan;
// Ok, we found something that isn't known to be contradictory. If it is
// equal, we can merge it into the set of nodes to factor, if not, we have
// to cease factoring.
if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
// If is equal after all, add the option to EqualMatchers and remove it
// from OptionsToMatch.
EqualMatchers.push_back(OptionsToMatch[Scan]);
OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
--e;
}
if (Scan != e &&
// Don't print it's obvious nothing extra could be merged anyway.
Scan+1 != e) {
DEBUG(errs() << "Couldn't merge this:\n";
Optn->print(errs(), 4);
errs() << "into this:\n";
OptionsToMatch[Scan]->print(errs(), 4);
if (Scan+1 != e)
OptionsToMatch[Scan+1]->printOne(errs());
if (Scan+2 < e)
OptionsToMatch[Scan+2]->printOne(errs());
errs() << "\n");
}
// If we only found one option starting with this matcher, no factoring is
// possible.
if (EqualMatchers.size() == 1) {
NewOptionsToMatch.push_back(EqualMatchers[0]);
continue;
}
// Factor these checks by pulling the first node off each entry and
// discarding it. Take the first one off the first entry to reuse.
Matcher *Shared = Optn;
Optn = Optn->takeNext();
EqualMatchers[0] = Optn;
// Remove and delete the first node from the other matchers we're factoring.
for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
Matcher *Tmp = EqualMatchers[i]->takeNext();
delete EqualMatchers[i];
EqualMatchers[i] = Tmp;
}
Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
// Recursively factor the newly created node.
FactorNodes(Shared->getNextPtr());
NewOptionsToMatch.push_back(Shared);
}
// If we're down to a single pattern to match, then we don't need this scope
// anymore.
if (NewOptionsToMatch.size() == 1) {
MatcherPtr.reset(NewOptionsToMatch[0]);
return;
}
// If our factoring failed (didn't achieve anything) see if we can simplify in
// other ways.
// Check to see if all of the leading entries are now opcode checks. If so,
// we can convert this Scope to be a OpcodeSwitch instead.
bool AllOpcodeChecks = true;
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
if (isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) continue;
#if 0
if (i > 3) {
errs() << "FAILING OPC #" << i << "\n";
NewOptionsToMatch[i]->dump();
}
#endif
AllOpcodeChecks = false;
break;
}
// If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
if (AllOpcodeChecks) {
StringSet<> Opcodes;
SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
CheckOpcodeMatcher *COM =cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
assert(Opcodes.insert(COM->getOpcode().getEnumName()) &&
"Duplicate opcodes not factored?");
Cases.push_back(std::make_pair(&COM->getOpcode(), COM->getNext()));
}
MatcherPtr.reset(new SwitchOpcodeMatcher(&Cases[0], Cases.size()));
return;
}
// Reassemble a new Scope node.
assert(!NewOptionsToMatch.empty() &&
"Where'd all our children go? Did we really factor everything??");
if (NewOptionsToMatch.empty())
MatcherPtr.reset(0);
else {
Scope->setNumChildren(NewOptionsToMatch.size());
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
Scope->resetChild(i, NewOptionsToMatch[i]);
}
}
Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
const CodeGenDAGPatterns &CGP) {
OwningPtr<Matcher> MatcherPtr(TheMatcher);
ContractNodes(MatcherPtr, CGP);
SinkPatternPredicates(MatcherPtr);
FactorNodes(MatcherPtr);
return MatcherPtr.take();
}
<commit_msg>tolerate factoring the *last* node for CellSPU.<commit_after>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
// 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 DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "isel-opt"
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;
/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
/// into single compound nodes like RecordChild.
static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
const CodeGenDAGPatterns &CGP) {
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// If we have a scope node, walk down all of the children.
if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
OwningPtr<Matcher> Child(Scope->takeChild(i));
ContractNodes(Child, CGP);
Scope->resetChild(i, Child.take());
}
return;
}
// If we found a movechild node with a node that comes in a 'foochild' form,
// transform it.
if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
Matcher *New = 0;
if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
RM->getResultNo());
if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
if (New) {
// Insert the new node.
New->setNext(MatcherPtr.take());
MatcherPtr.reset(New);
// Remove the old one.
MC->setNext(MC->getNext()->takeNext());
return ContractNodes(MatcherPtr, CGP);
}
}
// Zap movechild -> moveparent.
if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
if (MoveParentMatcher *MP =
dyn_cast<MoveParentMatcher>(MC->getNext())) {
MatcherPtr.reset(MP->takeNext());
return ContractNodes(MatcherPtr, CGP);
}
// Turn EmitNode->MarkFlagResults->CompleteMatch into
// MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
// MorphNodeTo formation. This is safe because MarkFlagResults never refers
// to the root of the pattern.
if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
// Unlink the two nodes from the list.
Matcher *EmitNode = MatcherPtr.take();
Matcher *MFR = EmitNode->takeNext();
Matcher *Tail = MFR->takeNext();
// Relink them.
MatcherPtr.reset(MFR);
MFR->setNext(EmitNode);
EmitNode->setNext(Tail);
return ContractNodes(MatcherPtr, CGP);
}
// Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
if (CompleteMatchMatcher *CM =
dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
// We can only use MorphNodeTo if the result values match up.
unsigned RootResultFirst = EN->getFirstResultSlot();
bool ResultsMatch = true;
for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
if (CM->getResult(i) != RootResultFirst+i)
ResultsMatch = false;
// If the selected node defines a subset of the flag/chain results, we
// can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
// matched pattern has a chain but the root node doesn't.
const PatternToMatch &Pattern = CM->getPattern();
if (!EN->hasChain() &&
Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
ResultsMatch = false;
// If the matched node has a flag and the output root doesn't, we can't
// use MorphNodeTo.
//
// NOTE: Strictly speaking, we don't have to check for the flag here
// because the code in the pattern generator doesn't handle it right. We
// do it anyway for thoroughness.
if (!EN->hasOutFlag() &&
Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
ResultsMatch = false;
// If the root result node defines more results than the source root node
// *and* has a chain or flag input, then we can't match it because it
// would end up replacing the extra result with the chain/flag.
#if 0
if ((EN->hasFlag() || EN->hasChain()) &&
EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
ResultMatch = false;
#endif
if (ResultsMatch) {
const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
VTs.data(), VTs.size(),
Operands.data(),Operands.size(),
EN->hasChain(), EN->hasInFlag(),
EN->hasOutFlag(),
EN->hasMemRefs(),
EN->getNumFixedArityOperands(),
Pattern));
return;
}
// FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
// variants.
}
ContractNodes(N->getNextPtr(), CGP);
// If we have a CheckType/CheckChildType/Record node followed by a
// CheckOpcode, invert the two nodes. We prefer to do structural checks
// before type checks, as this opens opportunities for factoring on targets
// like X86 where many operations are valid on multiple types.
if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
isa<RecordMatcher>(N)) &&
isa<CheckOpcodeMatcher>(N->getNext())) {
// Unlink the two nodes from the list.
Matcher *CheckType = MatcherPtr.take();
Matcher *CheckOpcode = CheckType->takeNext();
Matcher *Tail = CheckOpcode->takeNext();
// Relink them.
MatcherPtr.reset(CheckOpcode);
CheckOpcode->setNext(CheckType);
CheckType->setNext(Tail);
return ContractNodes(MatcherPtr, CGP);
}
}
/// SinkPatternPredicates - Pattern predicates can be checked at any level of
/// the matching tree. The generator dumps them at the top level of the pattern
/// though, which prevents factoring from being able to see past them. This
/// optimization sinks them as far down into the pattern as possible.
///
/// Conceptually, we'd like to sink these predicates all the way to the last
/// matcher predicate in the series. However, it turns out that some
/// ComplexPatterns have side effects on the graph, so we really don't want to
/// run a the complex pattern if the pattern predicate will fail. For this
/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
///
static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
// Recursively scan for a PatternPredicate.
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// Walk down all members of a scope node.
if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
OwningPtr<Matcher> Child(Scope->takeChild(i));
SinkPatternPredicates(Child);
Scope->resetChild(i, Child.take());
}
return;
}
// If this node isn't a CheckPatternPredicateMatcher we keep scanning until
// we find one.
CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
if (CPPM == 0)
return SinkPatternPredicates(N->getNextPtr());
// Ok, we found one, lets try to sink it. Check if we can sink it past the
// next node in the chain. If not, we won't be able to change anything and
// might as well bail.
if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
return;
// Okay, we know we can sink it past at least one node. Unlink it from the
// chain and scan for the new insertion point.
MatcherPtr.take(); // Don't delete CPPM.
MatcherPtr.reset(CPPM->takeNext());
N = MatcherPtr.get();
while (N->getNext()->isSafeToReorderWithPatternPredicate())
N = N->getNext();
// At this point, we want to insert CPPM after N.
CPPM->setNext(N->takeNext());
N->setNext(CPPM);
}
/// FactorNodes - Turn matches like this:
/// Scope
/// OPC_CheckType i32
/// ABC
/// OPC_CheckType i32
/// XYZ
/// into:
/// OPC_CheckType i32
/// Scope
/// ABC
/// XYZ
///
static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
// If we reached the end of the chain, we're done.
Matcher *N = MatcherPtr.get();
if (N == 0) return;
// If this is not a push node, just scan for one.
ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
if (Scope == 0)
return FactorNodes(N->getNextPtr());
// Okay, pull together the children of the scope node into a vector so we can
// inspect it more easily. While we're at it, bucket them up by the hash
// code of their first predicate.
SmallVector<Matcher*, 32> OptionsToMatch;
for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
// Factor the subexpression.
OwningPtr<Matcher> Child(Scope->takeChild(i));
FactorNodes(Child);
if (Matcher *N = Child.take())
OptionsToMatch.push_back(N);
}
SmallVector<Matcher*, 32> NewOptionsToMatch;
// Loop over options to match, merging neighboring patterns with identical
// starting nodes into a shared matcher.
for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
// Find the set of matchers that start with this node.
Matcher *Optn = OptionsToMatch[OptionIdx++];
if (OptionIdx == e) {
NewOptionsToMatch.push_back(Optn);
continue;
}
// See if the next option starts with the same matcher. If the two
// neighbors *do* start with the same matcher, we can factor the matcher out
// of at least these two patterns. See what the maximal set we can merge
// together is.
SmallVector<Matcher*, 8> EqualMatchers;
EqualMatchers.push_back(Optn);
// Factor all of the known-equal matchers after this one into the same
// group.
while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
// If we found a non-equal matcher, see if it is contradictory with the
// current node. If so, we know that the ordering relation between the
// current sets of nodes and this node don't matter. Look past it to see if
// we can merge anything else into this matching group.
unsigned Scan = OptionIdx;
while (1) {
while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
++Scan;
// Ok, we found something that isn't known to be contradictory. If it is
// equal, we can merge it into the set of nodes to factor, if not, we have
// to cease factoring.
if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
// If is equal after all, add the option to EqualMatchers and remove it
// from OptionsToMatch.
EqualMatchers.push_back(OptionsToMatch[Scan]);
OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
--e;
}
if (Scan != e &&
// Don't print it's obvious nothing extra could be merged anyway.
Scan+1 != e) {
DEBUG(errs() << "Couldn't merge this:\n";
Optn->print(errs(), 4);
errs() << "into this:\n";
OptionsToMatch[Scan]->print(errs(), 4);
if (Scan+1 != e)
OptionsToMatch[Scan+1]->printOne(errs());
if (Scan+2 < e)
OptionsToMatch[Scan+2]->printOne(errs());
errs() << "\n");
}
// If we only found one option starting with this matcher, no factoring is
// possible.
if (EqualMatchers.size() == 1) {
NewOptionsToMatch.push_back(EqualMatchers[0]);
continue;
}
// Factor these checks by pulling the first node off each entry and
// discarding it. Take the first one off the first entry to reuse.
Matcher *Shared = Optn;
Optn = Optn->takeNext();
EqualMatchers[0] = Optn;
// Remove and delete the first node from the other matchers we're factoring.
for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
Matcher *Tmp = EqualMatchers[i]->takeNext();
delete EqualMatchers[i];
EqualMatchers[i] = Tmp;
}
Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
// Recursively factor the newly created node.
FactorNodes(Shared->getNextPtr());
NewOptionsToMatch.push_back(Shared);
}
// If we're down to a single pattern to match, then we don't need this scope
// anymore.
if (NewOptionsToMatch.size() == 1) {
MatcherPtr.reset(NewOptionsToMatch[0]);
return;
}
if (NewOptionsToMatch.empty()) {
MatcherPtr.reset(0);
return;
}
// If our factoring failed (didn't achieve anything) see if we can simplify in
// other ways.
// Check to see if all of the leading entries are now opcode checks. If so,
// we can convert this Scope to be a OpcodeSwitch instead.
bool AllOpcodeChecks = true;
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
if (isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) continue;
#if 0
if (i > 3) {
errs() << "FAILING OPC #" << i << "\n";
NewOptionsToMatch[i]->dump();
}
#endif
AllOpcodeChecks = false;
break;
}
// If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
if (AllOpcodeChecks) {
StringSet<> Opcodes;
SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
CheckOpcodeMatcher *COM =cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
assert(Opcodes.insert(COM->getOpcode().getEnumName()) &&
"Duplicate opcodes not factored?");
Cases.push_back(std::make_pair(&COM->getOpcode(), COM->getNext()));
}
MatcherPtr.reset(new SwitchOpcodeMatcher(&Cases[0], Cases.size()));
return;
}
// Reassemble a new Scope node.
assert(!NewOptionsToMatch.empty() &&
"Where'd all our children go? Did we really factor everything??");
if (NewOptionsToMatch.empty())
MatcherPtr.reset(0);
else {
Scope->setNumChildren(NewOptionsToMatch.size());
for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
Scope->resetChild(i, NewOptionsToMatch[i]);
}
}
Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
const CodeGenDAGPatterns &CGP) {
OwningPtr<Matcher> MatcherPtr(TheMatcher);
ContractNodes(MatcherPtr, CGP);
SinkPatternPredicates(MatcherPtr);
FactorNodes(MatcherPtr);
return MatcherPtr.take();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: proxydecider.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 16:30:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _UCBHELPER_PROXYDECIDER_HXX
#define _UCBHELPER_PROXYDECIDER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hXX>
#endif
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif
namespace com { namespace sun { namespace star { namespace lang {
class XMultiServiceFactory;
} } } }
namespace ucbhelper
{
/**
* This struct describes a proxy server.
*/
struct InternetProxyServer
{
/**
* The name of the proxy server.
*/
::rtl::OUString aName;
/**
* The port of the proxy server.
*/
sal_Int32 nPort;
/**
* Constructor.
*/
InternetProxyServer() : nPort( -1 ) {}
};
namespace proxydecider_impl { class InternetProxyDecider_Impl; }
/**
* This class is able to decide whether and which internet proxy server is to
* be used to access a given URI.
*
* The implementation reads the internet proxy settings from Office
* configuration. It listens for configuration changes and adapts itself
* accordingly. Because configuration data can change during runtime clients
* should not cache results obtained from InternetProxyDecider instances. One
* instance should be kept to be queried multiple times instead.
*/
class UCBHELPER_DLLPUBLIC InternetProxyDecider
{
public:
/**
* Constructor.
*
* Note: Every instance should be held alive as long as possible because
* because construction is quite expensive.
*
* @param rxSMgr is a Service Manager.
*/
InternetProxyDecider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rxSMgr );
/**
* Destructor.
*/
~InternetProxyDecider();
/**
* Informs whether a proxy server should be used.
*
* @param rProtocol contains the internet protocol to be used to
* access the server (i.e. "ftp", "http"). The protocol string
* is handled case-insensitive and must not be empty.
* @param rHost contains the name of the server that should be accessed.
* This parameter might be left empty. In this case the
* implementation will return whether a proxy is configured
* for the given protocol.
* @param nPort contains the port of the server that should be accessed.
* If host is not empty this parameter must always contain a valid
* port number, for instance the default port for the requested
* protocol(i.e. 80 or http).
* @return true if a proxy server should be used, false otherwise.
*/
bool
shouldUseProxy( const rtl::OUString & rProtocol,
const rtl::OUString & rHost,
sal_Int32 nPort ) const;
/**
* Returns the proxy server to be used.
*
* @param rProtocol contains the internet protocol to be used to
* access the server (i.e. "ftp", "http"). The protocol string
* is handled case-insensitive and must not be empty.
* @param rHost contains the name of the server that should be accessed.
* This parameter might be left empty. In this case the
* implementation will return the proxy that is configured
* for the given protocol.
* @param nPort contains the port of the server that should be accessed.
* If host is not empty this parameter must always contain a valid
* port number, for instance the default port for the requested
* protocol(i.e. 80 or http).
* @return a InternetProxyServer reference. If member aName of the
* InternetProxyServer is empty no proxy server is to be used.
*/
const InternetProxyServer &
getProxy( const rtl::OUString & rProtocol,
const rtl::OUString & rHost,
sal_Int32 nPort ) const;
private:
proxydecider_impl::InternetProxyDecider_Impl * m_pImpl;
};
} // namespace ucbhelper
#endif /* !_UCBHELPER_PROXYDECIDER_HXX */
<commit_msg>INTEGRATION: CWS warnings01 (1.2.12); FILE MERGED 2005/09/22 18:55:46 sb 1.2.12.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/01 12:15:24 sb 1.2.12.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: proxydecider.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 12:11:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _UCBHELPER_PROXYDECIDER_HXX
#define _UCBHELPER_PROXYDECIDER_HXX
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif
namespace com { namespace sun { namespace star { namespace lang {
class XMultiServiceFactory;
} } } }
namespace ucbhelper
{
/**
* This struct describes a proxy server.
*/
struct InternetProxyServer
{
/**
* The name of the proxy server.
*/
::rtl::OUString aName;
/**
* The port of the proxy server.
*/
sal_Int32 nPort;
/**
* Constructor.
*/
InternetProxyServer() : nPort( -1 ) {}
};
namespace proxydecider_impl { class InternetProxyDecider_Impl; }
/**
* This class is able to decide whether and which internet proxy server is to
* be used to access a given URI.
*
* The implementation reads the internet proxy settings from Office
* configuration. It listens for configuration changes and adapts itself
* accordingly. Because configuration data can change during runtime clients
* should not cache results obtained from InternetProxyDecider instances. One
* instance should be kept to be queried multiple times instead.
*/
class UCBHELPER_DLLPUBLIC InternetProxyDecider
{
public:
/**
* Constructor.
*
* Note: Every instance should be held alive as long as possible because
* because construction is quite expensive.
*
* @param rxSMgr is a Service Manager.
*/
InternetProxyDecider( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rxSMgr );
/**
* Destructor.
*/
~InternetProxyDecider();
/**
* Informs whether a proxy server should be used.
*
* @param rProtocol contains the internet protocol to be used to
* access the server (i.e. "ftp", "http"). The protocol string
* is handled case-insensitive and must not be empty.
* @param rHost contains the name of the server that should be accessed.
* This parameter might be left empty. In this case the
* implementation will return whether a proxy is configured
* for the given protocol.
* @param nPort contains the port of the server that should be accessed.
* If host is not empty this parameter must always contain a valid
* port number, for instance the default port for the requested
* protocol(i.e. 80 or http).
* @return true if a proxy server should be used, false otherwise.
*/
bool
shouldUseProxy( const rtl::OUString & rProtocol,
const rtl::OUString & rHost,
sal_Int32 nPort ) const;
/**
* Returns the proxy server to be used.
*
* @param rProtocol contains the internet protocol to be used to
* access the server (i.e. "ftp", "http"). The protocol string
* is handled case-insensitive and must not be empty.
* @param rHost contains the name of the server that should be accessed.
* This parameter might be left empty. In this case the
* implementation will return the proxy that is configured
* for the given protocol.
* @param nPort contains the port of the server that should be accessed.
* If host is not empty this parameter must always contain a valid
* port number, for instance the default port for the requested
* protocol(i.e. 80 or http).
* @return a InternetProxyServer reference. If member aName of the
* InternetProxyServer is empty no proxy server is to be used.
*/
const InternetProxyServer &
getProxy( const rtl::OUString & rProtocol,
const rtl::OUString & rHost,
sal_Int32 nPort ) const;
private:
proxydecider_impl::InternetProxyDecider_Impl * m_pImpl;
};
} // namespace ucbhelper
#endif /* !_UCBHELPER_PROXYDECIDER_HXX */
<|endoftext|> |
<commit_before>#include "Platform.hpp"
#include "genome.pb.h"
#include "CellComponent.hpp"
#include "ActivityStats.hpp"
#include "Neuron.hpp"
#include "Branch.hpp"
#include "Synapse.hpp"
#include "Base64.hpp"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include <time.h>
typedef std::vector<std::pair<Elysia::Genome::Effect, float> > CombinedResults;
namespace Elysia {
void testTwoConnectedNeurons_seq() {
ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment();
Brain *brain= new Brain(myProteinEnvironment);
FILE *dendriteTree=NULL;
dendriteTree = fopen("Dendritic_Tree.txt", "w");
std::vector<Neuron *> createdList;
int neuronNumber = 2;
for(int j=0;j<neuronNumber;j++){
float i=(float)j;
Genome::Gene gene;//FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_bounds();
sourcebb->set_minx(i);
sourcebb->set_miny(i);
sourcebb->set_minz(i);
sourcebb->set_maxx(i);
sourcebb->set_maxy(i);
sourcebb->set_maxz(i);
targetbb->set_minx(i);
targetbb->set_miny(i);
targetbb->set_minz(i);
targetbb->set_maxx(1-i);
targetbb->set_maxy(1-i);
targetbb->set_maxz(2);
Vector3f v;
v.x = i;
v.y = i;
v.z = 1;
Neuron *n;
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, 2, 2, v,gene));
createdList.push_back(n);
} // for
for(int i=0;i<neuronNumber;i++){
Neuron *n = createdList[i];
n->developSynapse(n->getActivityStats());
size_t parent;
parent = 0;
n->visualizeTree(dendriteTree, parent);
//const Vector3f &location): mNeuronLocation(location){));
}
for(int j=0; j<10; j++){
for(int i=0;i<neuronNumber;i++){
Neuron *n = createdList[i];
if(j== 0 && i==0)
n->activateComponent(*brain,100);
//if(j== 2){brain->inactivateNeuron(n);}
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
brain ->tick();
}
fclose(dendriteTree);
delete brain;
}
//Target is axon, Source is dendrite (?)
Neuron* placeTestSeqNeuron(Brain* brain, float locx, float locy, float locz, float sx, float sy, float sz, float range){
float random = rand()/(float)RAND_MAX; // some random position offset
Genome::Gene gene; // FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_dendrite_region();
sourcebb->set_minx(sx-range*random);
sourcebb->set_miny(sy-range*random);
sourcebb->set_minz(1);
sourcebb->set_maxx(sx+range*random);
sourcebb->set_maxy(sy+range*random);
sourcebb->set_maxz(1);
targetbb->set_minx(locx-range);
targetbb->set_miny(locy-range);
targetbb->set_minz(1);
targetbb->set_maxx(locx+range);
targetbb->set_maxy(locy+range);
targetbb->set_maxz(1);
Vector3f v;
v.x = locx+range*random;
v.y = locy+range*random;
v.z = 1;
Neuron *n;
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, 2, 2, v,gene));
return n;
}
void testSeqDevelopment(int neuronNumber){
ProteinEnvironment *myProteinEnvironment = new SimpleProteinEnvironment();// generate new protein environment
Brain *brain= new Brain(myProteinEnvironment); // new brain defined from this protein environment
std::vector<Neuron *> createdList; // a list of neurons created during the test
FILE *dendriteTree=NULL; // output dendrite tree
Neuron *n; // neurons created during the test sequence
size_t parent;
dendriteTree = fopen("Development_Tree.txt", "w");
srand((unsigned int)time(NULL));
//Region 1
for(int i=0;i<neuronNumber;i++)
createdList.push_back(placeTestSeqNeuron(brain, 10, 10, 1, 100, 100, 1, 5));
//Region 2
for(int i=0;i<neuronNumber;i++)
createdList.push_back(placeTestSeqNeuron(brain, 100, 100, 1, 10, 10, 1, 5));
for(int i=0;i<2*neuronNumber;i++){
n = createdList[i];
n->developSynapse(n->getActivityStats());
parent = 0; // this seems a bit pointless
n->visualizeTree(dendriteTree, parent);
//const Vector3f &location): mNeuronLocation(location){));
}
for(int j=0; j<10; j++){
for(int i=0;i<neuronNumber;i++){
n = createdList[i];
if(j==0)
n->activateComponent(*brain,100);
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
brain ->tick();
}
fclose(dendriteTree);
delete brain;
}
void testSeqResultHelper(const CombinedResults &combinedResult, float*grow_leaf_count,
float*grow_neuron_count,float*other_count){
using namespace Elysia::Genome;
*grow_neuron_count=0;
*grow_leaf_count=0;
*other_count=0;
for (size_t i=0;i<combinedResult.size();++i) {
switch(combinedResult[i].first) {
case GROW_NEURON:
*grow_neuron_count+=combinedResult[i].second;
break;
case GROW_LEAF:
*grow_leaf_count+=combinedResult[i].second;
break;
default:
*other_count+=combinedResult[i].second;
break;
}
}
}
void testSeqProteinEnvironment() {
using namespace Elysia::Genome;
Elysia::Genome::Genome twoOverlappingGenes;
Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers();
Elysia::Genome::Gene firstGene;
Elysia::Genome::Protein firstProtein;
firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where
firstProtein.set_density(0.125);
Elysia::Genome::Protein firstAuxProtein;
firstAuxProtein.set_protein_code(GROW_LEAF);//so we see that they are additive
firstAuxProtein.set_density(0.25);
*firstGene.add_external_proteins()=firstProtein;
assert(firstGene.external_proteins(0).protein_code()==GROW_NEURON);
*firstGene.add_external_proteins()=firstAuxProtein;
assert(firstGene.external_proteins(1).protein_code()==GROW_LEAF);
Elysia::Genome::TemporalBoundingBox firstRegion;
firstRegion.set_minx(0);
firstRegion.set_miny(0);
firstRegion.set_minz(0);
firstRegion.set_maxx(2);
firstRegion.set_maxy(2);
firstRegion.set_maxz(2);
*firstGene.add_bounds()=firstRegion;
Elysia::Genome::TemporalBoundingBox firstDendriteRegion;
firstDendriteRegion.set_minx(5);
firstDendriteRegion.set_miny(5);
firstDendriteRegion.set_minz(5);
firstDendriteRegion.set_maxx(8);
firstDendriteRegion.set_maxy(8);
firstDendriteRegion.set_maxz(8);
*firstGene.add_dendrite_region()=firstDendriteRegion;
Elysia::Genome::Gene secondGene;
Elysia::Genome::Protein secondProtein;
secondProtein.set_protein_code(GROW_LEAF);
secondProtein.set_density(0.5);
*secondGene.add_external_proteins()=secondProtein;
Elysia::Genome::TemporalBoundingBox secondRegion;
secondRegion.set_minx(-1);
secondRegion.set_miny(-1);
secondRegion.set_minz(-1);
secondRegion.set_maxx(1);
secondRegion.set_maxy(1);
secondRegion.set_maxz(1);
*secondGene.add_bounds()=secondRegion;
Elysia::Genome::TemporalBoundingBox secondDendriteRegion;
secondDendriteRegion.set_minx(-5);
secondDendriteRegion.set_miny(-5);
secondDendriteRegion.set_minz(-5);
secondDendriteRegion.set_maxx(3);
secondDendriteRegion.set_maxy(3);
secondDendriteRegion.set_maxz(3);
*secondGene.add_dendrite_region()=secondDendriteRegion;
*father->add_genes()=firstGene;
*father->add_genes()=secondGene;
ProteinEnvironment * pe=new SimpleProteinEnvironment;
pe->initialize(twoOverlappingGenes);
std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,0));
//check that firstResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,0));
//check that secondResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,0));
float grow_leaf_count=0;
float grow_neuron_count=0;
float other_count=0;
testSeqResultHelper(combinedResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.75);
assert(grow_neuron_count==.125);
assert(other_count==0);
testSeqResultHelper(firstResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.25);
assert(grow_neuron_count==.125);
assert(other_count==0);
testSeqResultHelper(secondResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.5);
assert(grow_neuron_count==0);
assert(other_count==0);
//return;//UNCOMMENT TO GET FAILING TEST
const Gene * grow_neuron_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0),
GROW_NEURON);
const Gene * combined_grow_leaf_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0),
GROW_LEAF);
const Gene * first_grow_leaf_gene = &pe->retrieveGene(Vector3f(1.5,1.5,0),
GROW_LEAF);
const Gene * second_grow_leaf_gene = &pe->retrieveGene(Vector3f(-0.5,-0.5,0),
GROW_LEAF);
assert(grow_neuron_gene->dendrite_region(0).minx()==5);
assert(combined_grow_leaf_gene->dendrite_region(0).minx()==5||combined_grow_leaf_gene->dendrite_region(0).minx()==-5);
assert(first_grow_leaf_gene->dendrite_region(0).minx()==5);
assert(second_grow_leaf_gene->dendrite_region(0).minx()==-5);
delete pe;
}
}
int runtestsequence(){
//Elysia::testTwoConnectedNeurons();
Elysia::testSeqDevelopment(4);
Elysia::testSeqProteinEnvironment();
if (0) for (int i=0;i<30000;++i) {
Elysia::Brain b(new Elysia::SimpleProteinEnvironment);
// usleep(10);
}
//getchar();
return 1;
}
<commit_msg>Make it build in windows<commit_after>#include "Platform.hpp"
#include "genome.pb.h"
#include "CellComponent.hpp"
#include "ActivityStats.hpp"
#include "Neuron.hpp"
#include "Branch.hpp"
#include "Synapse.hpp"
#include "Base64.hpp"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "Development.hpp"
#include <time.h>
typedef std::vector<std::pair<Elysia::Genome::Effect, float> > CombinedResults;
namespace Elysia {
void testTwoConnectedNeurons_seq() {
ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment();
Brain *brain= new Brain(myProteinEnvironment);
FILE *dendriteTree=NULL;
dendriteTree = fopen("Dendritic_Tree.txt", "w");
std::vector<Neuron *> createdList;
int neuronNumber = 2;
for(int j=0;j<neuronNumber;j++){
float i=(float)j;
Genome::Gene gene;//FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_bounds();
sourcebb->set_minx(i);
sourcebb->set_miny(i);
sourcebb->set_minz(i);
sourcebb->set_maxx(i);
sourcebb->set_maxy(i);
sourcebb->set_maxz(i);
targetbb->set_minx(i);
targetbb->set_miny(i);
targetbb->set_minz(i);
targetbb->set_maxx(1-i);
targetbb->set_maxy(1-i);
targetbb->set_maxz(2);
Vector3f v;
v.x = i;
v.y = i;
v.z = 1;
Neuron *n;
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, 2, 2, v,gene));
createdList.push_back(n);
} // for
for(int i=0;i<neuronNumber;i++){
Neuron *n = createdList[i];
n->development()->develop();
size_t parent;
parent = 0;
n->visualizeTree(dendriteTree, parent);
//const Vector3f &location): mNeuronLocation(location){));
}
for(int j=0; j<10; j++){
for(int i=0;i<neuronNumber;i++){
Neuron *n = createdList[i];
if(j== 0 && i==0)
n->activateComponent(*brain,100);
//if(j== 2){brain->inactivateNeuron(n);}
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
brain ->tick();
}
fclose(dendriteTree);
delete brain;
}
//Target is axon, Source is dendrite (?)
Neuron* placeTestSeqNeuron(Brain* brain, float locx, float locy, float locz, float sx, float sy, float sz, float range){
float random = rand()/(float)RAND_MAX; // some random position offset
Genome::Gene gene; // FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_dendrite_region();
sourcebb->set_minx(sx-range*random);
sourcebb->set_miny(sy-range*random);
sourcebb->set_minz(1);
sourcebb->set_maxx(sx+range*random);
sourcebb->set_maxy(sy+range*random);
sourcebb->set_maxz(1);
targetbb->set_minx(locx-range);
targetbb->set_miny(locy-range);
targetbb->set_minz(1);
targetbb->set_maxx(locx+range);
targetbb->set_maxy(locy+range);
targetbb->set_maxz(1);
Vector3f v;
v.x = locx+range*random;
v.y = locy+range*random;
v.z = 1;
Neuron *n;
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, 2, 2, v,gene));
return n;
}
void testSeqDevelopment(int neuronNumber){
ProteinEnvironment *myProteinEnvironment = new SimpleProteinEnvironment();// generate new protein environment
Brain *brain= new Brain(myProteinEnvironment); // new brain defined from this protein environment
std::vector<Neuron *> createdList; // a list of neurons created during the test
FILE *dendriteTree=NULL; // output dendrite tree
Neuron *n; // neurons created during the test sequence
size_t parent;
dendriteTree = fopen("Development_Tree.txt", "w");
srand((unsigned int)time(NULL));
//Region 1
for(int i=0;i<neuronNumber;i++)
createdList.push_back(placeTestSeqNeuron(brain, 10, 10, 1, 100, 100, 1, 5));
//Region 2
for(int i=0;i<neuronNumber;i++)
createdList.push_back(placeTestSeqNeuron(brain, 100, 100, 1, 10, 10, 1, 5));
for(int i=0;i<2*neuronNumber;i++){
n = createdList[i];
n->development()->develop();
parent = 0; // this seems a bit pointless
n->visualizeTree(dendriteTree, parent);
//const Vector3f &location): mNeuronLocation(location){));
}
for(int j=0; j<10; j++){
for(int i=0;i<neuronNumber;i++){
n = createdList[i];
if(j==0)
n->activateComponent(*brain,100);
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
brain ->tick();
}
fclose(dendriteTree);
delete brain;
}
void testSeqResultHelper(const CombinedResults &combinedResult, float*grow_leaf_count,
float*grow_neuron_count,float*other_count){
using namespace Elysia::Genome;
*grow_neuron_count=0;
*grow_leaf_count=0;
*other_count=0;
for (size_t i=0;i<combinedResult.size();++i) {
switch(combinedResult[i].first) {
case GROW_NEURON:
*grow_neuron_count+=combinedResult[i].second;
break;
case GROW_LEAF:
*grow_leaf_count+=combinedResult[i].second;
break;
default:
*other_count+=combinedResult[i].second;
break;
}
}
}
void testSeqProteinEnvironment() {
using namespace Elysia::Genome;
Elysia::Genome::Genome twoOverlappingGenes;
Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers();
Elysia::Genome::Gene firstGene;
Elysia::Genome::Protein firstProtein;
firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where
firstProtein.set_density(0.125);
Elysia::Genome::Protein firstAuxProtein;
firstAuxProtein.set_protein_code(GROW_LEAF);//so we see that they are additive
firstAuxProtein.set_density(0.25);
*firstGene.add_external_proteins()=firstProtein;
assert(firstGene.external_proteins(0).protein_code()==GROW_NEURON);
*firstGene.add_external_proteins()=firstAuxProtein;
assert(firstGene.external_proteins(1).protein_code()==GROW_LEAF);
Elysia::Genome::TemporalBoundingBox firstRegion;
firstRegion.set_minx(0);
firstRegion.set_miny(0);
firstRegion.set_minz(0);
firstRegion.set_maxx(2);
firstRegion.set_maxy(2);
firstRegion.set_maxz(2);
*firstGene.add_bounds()=firstRegion;
Elysia::Genome::TemporalBoundingBox firstDendriteRegion;
firstDendriteRegion.set_minx(5);
firstDendriteRegion.set_miny(5);
firstDendriteRegion.set_minz(5);
firstDendriteRegion.set_maxx(8);
firstDendriteRegion.set_maxy(8);
firstDendriteRegion.set_maxz(8);
*firstGene.add_dendrite_region()=firstDendriteRegion;
Elysia::Genome::Gene secondGene;
Elysia::Genome::Protein secondProtein;
secondProtein.set_protein_code(GROW_LEAF);
secondProtein.set_density(0.5);
*secondGene.add_external_proteins()=secondProtein;
Elysia::Genome::TemporalBoundingBox secondRegion;
secondRegion.set_minx(-1);
secondRegion.set_miny(-1);
secondRegion.set_minz(-1);
secondRegion.set_maxx(1);
secondRegion.set_maxy(1);
secondRegion.set_maxz(1);
*secondGene.add_bounds()=secondRegion;
Elysia::Genome::TemporalBoundingBox secondDendriteRegion;
secondDendriteRegion.set_minx(-5);
secondDendriteRegion.set_miny(-5);
secondDendriteRegion.set_minz(-5);
secondDendriteRegion.set_maxx(3);
secondDendriteRegion.set_maxy(3);
secondDendriteRegion.set_maxz(3);
*secondGene.add_dendrite_region()=secondDendriteRegion;
*father->add_genes()=firstGene;
*father->add_genes()=secondGene;
ProteinEnvironment * pe=new SimpleProteinEnvironment;
pe->initialize(twoOverlappingGenes);
std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,0));
//check that firstResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,0));
//check that secondResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,0));
float grow_leaf_count=0;
float grow_neuron_count=0;
float other_count=0;
testSeqResultHelper(combinedResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.75);
assert(grow_neuron_count==.125);
assert(other_count==0);
testSeqResultHelper(firstResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.25);
assert(grow_neuron_count==.125);
assert(other_count==0);
testSeqResultHelper(secondResult,&grow_leaf_count,&grow_neuron_count,&other_count);
assert(grow_leaf_count==.5);
assert(grow_neuron_count==0);
assert(other_count==0);
//return;//UNCOMMENT TO GET FAILING TEST
const Gene * grow_neuron_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0),
GROW_NEURON);
const Gene * combined_grow_leaf_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0),
GROW_LEAF);
const Gene * first_grow_leaf_gene = &pe->retrieveGene(Vector3f(1.5,1.5,0),
GROW_LEAF);
const Gene * second_grow_leaf_gene = &pe->retrieveGene(Vector3f(-0.5,-0.5,0),
GROW_LEAF);
assert(grow_neuron_gene->dendrite_region(0).minx()==5);
assert(combined_grow_leaf_gene->dendrite_region(0).minx()==5||combined_grow_leaf_gene->dendrite_region(0).minx()==-5);
assert(first_grow_leaf_gene->dendrite_region(0).minx()==5);
assert(second_grow_leaf_gene->dendrite_region(0).minx()==-5);
delete pe;
}
}
int runtestsequence(){
//Elysia::testTwoConnectedNeurons();
Elysia::testSeqDevelopment(4);
Elysia::testSeqProteinEnvironment();
if (0) for (int i=0;i<30000;++i) {
Elysia::Brain b(new Elysia::SimpleProteinEnvironment);
// usleep(10);
}
//getchar();
return 1;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010,
*
* Luis Degaldo
* Francois Keith
* Florent Lamiraux
* Layale Saab
* Olivier Stasse,
*
* JRL/LAAS, CNRS/AIST
*
* This file is part of dynamicsJRLJapan.
* dynamicsJRLJapan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dynamicsJRLJapan 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 Lesser Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with dynamicsJRLJapan. If not, see <http://www.gnu.org/licenses/>.
*
* Research carried out within the scope of the Associated
* International Laboratory: Joint Japanese-French Robotics
* Laboratory (JRL)
*
*/
/* @doc \file Object to generate a file following AMELIF format. */
#include <string>
#include <iostream>
#include <fstream>
#include <jrl/dynamics/dynamicsfactory.hh>
#include "CommonTools.h"
using namespace std;
using namespace dynamicsJRLJapan;
void DisplayDynamicRobotInformation(CjrlDynamicRobot *aDynamicRobot,
ostream &tcout)
{
std::vector<CjrlJoint *> aVec = aDynamicRobot->jointVector();
int r = aVec.size();
tcout << "Number of joints :" << r << endl;
}
int main(int argc, char *argv[])
{
string aSpecificitiesFileName;
string aPath;
string aName;
string aMapFromJointToRank;
ofstream tcout("output.txt",ofstream::out);
if (argc!=5)
{
aPath="./";
aName="sample.wrl";
aSpecificitiesFileName = "sampleSpecificities.xml";
aMapFromJointToRank = "sampleLinkJointRank.xml";
}
else
{
aSpecificitiesFileName = argv[3];
aPath=argv[1];
aName=argv[2];
aMapFromJointToRank=argv[4];
}
dynamicsJRLJapan::ObjectFactory aRobotDynamicsObjectConstructor;
CjrlHumanoidDynamicRobot * aHDR = aRobotDynamicsObjectConstructor.createHumanoidDynamicRobot();
if (aHDR==0)
{
cerr<< "Dynamic cast on HDR failed " << endl;
exit(-1);
}
string RobotFileName = aPath+aName;
dynamicsJRLJapan::parseOpenHRPVRMLFile(*aHDR,RobotFileName,aMapFromJointToRank,aSpecificitiesFileName);
// Display tree of the joints.
CjrlJoint* rootJoint = aHDR->rootJoint();
int NbOfDofs = aHDR->numberDof();
tcout << "NbOfDofs :" << NbOfDofs << std::endl;
if (NbOfDofs==0)
{
cerr << "Empty Robot..."<< endl;
return -1;
}
MAL_VECTOR_DIM(aCurrentConf,double,NbOfDofs);
int lindex=0;
for(int i=0;i<6;i++)
aCurrentConf[lindex++] = 0.0;
aCurrentConf[2] = 0.705;
for(int i=0;i<NbOfDofs-6 ;i++)
aCurrentConf[lindex++] = 0.0;
aHDR->currentConfiguration(aCurrentConf);
MAL_VECTOR_DIM(aCurrentVel,double,NbOfDofs);
lindex=0;
for(int i=0;i<NbOfDofs;i++)
aCurrentVel[lindex++] = 0.0;
MAL_S3_VECTOR(ZMPval,double);
aHDR->currentVelocity(aCurrentVel);
// aHDR->setComputeZMP(true);
string inProperty="ComputeZMP"; string aValue="true";
aHDR->setProperty(inProperty,aValue);
aHDR->computeForwardKinematics();
ZMPval = aHDR->zeroMomentumPoint();
tcout << "First value of ZMP : "
<< filterprecision(ZMPval(0)) << " "
<< filterprecision(ZMPval(1)) << " "
<< filterprecision(ZMPval(2)) << endl;
MAL_S3_VECTOR(poscom,double);
poscom = aHDR->positionCenterOfMass();
tcout << "Should be equal to the CoM: "
<< filterprecision(poscom(0)) << " "
<< filterprecision(poscom(1)) << " "
<< filterprecision(poscom(2)) << endl;
matrixNxP InertiaMatrix;
aHDR->computeInertiaMatrix();
InertiaMatrix = aHDR->inertiaMatrix();
tcout << "InertiaMatrix("
<< MAL_MATRIX_NB_ROWS(InertiaMatrix)<< ","
<< MAL_MATRIX_NB_COLS(InertiaMatrix)<< ")"<< endl;
DisplayMatrix(InertiaMatrix,tcout);
ofstream aof;
aof.open("InertiaMatrix.dat");
for(unsigned int i=0;i<MAL_MATRIX_NB_ROWS(InertiaMatrix);i++)
{
for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(InertiaMatrix);j++)
{
aof << InertiaMatrix(i,j) << " ";
}
aof << endl;
}
aof.close();
std::vector<CjrlJoint *> aVec = aHDR->jointVector();
// Get the Jacobian of the right ankle.
CjrlJoint * aJoint = aHDR->rightAnkle();
aJoint->computeJacobianJointWrtConfig();
tcout << "Jacobian of the right ankle." << endl;
MAL_MATRIX_TYPE(double) aJ;
aJ = aJoint->jacobianJointWrtConfig();
DisplayMatrix(aJ,tcout);
// Get the articular Jacobian from the right ankle to the right wrist.
vector3d origin; origin(0) = 0.0; origin(1) = 0.0; origin(2) = 0.0;
aHDR->getJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
origin,
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
MAL_MATRIX_RESIZE(aJ,3, MAL_MATRIX_NB_COLS(aJ));
// Get the linear part of the articular Jacobian from the right ankle to the right wrist.
aHDR->getPositionJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
origin,
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
// Get the angular part of the articular Jacobian from the right ankle to the right wrist.
aHDR->getOrientationJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
tcout << "****************************" << endl;
rootJoint->computeJacobianJointWrtConfig();
aJ = rootJoint->jacobianJointWrtConfig();
tcout << "Rank of Root: " << rootJoint->rankInConfiguration() << endl;
// DisplayMatrix(aJ);
aJoint = aHDR->waist();
tcout << "****************************" << endl;
#if 0
aHDR->computeJacobianCenterOfMass();
DisplayMatrix(aHDR->jacobianCenterOfMass(),tcout);
#else
matrixNxP JCM;
MAL_MATRIX_RESIZE(JCM,3,MAL_MATRIX_NB_COLS(aJ));
aHDR->getJacobianCenterOfMass(*aHDR->rootJoint(),JCM);
DisplayMatrix(JCM,tcout);
#endif
tcout << "****************************" << endl;
RecursiveDisplayOfJoints(rootJoint,tcout,10);
tcout << "****************************" << endl;
// Test rank of the hands.
tcout << "Rank of the right hand "<< endl;
tcout << aHDR->rightWrist()->rankInConfiguration() << endl;
CjrlHand *rightHand = aHDR->rightHand();
string empty("");
DisplayHand(rightHand,empty,tcout);
tcout << "Rank of the left hand "<< endl;
tcout << aHDR->leftWrist()->rankInConfiguration() << endl;
CjrlHand *leftHand = aHDR->leftHand();
DisplayHand(leftHand,empty,tcout);
// Test rank of the feet.
tcout << "Rank of the right foot "<< endl;
tcout << aHDR->rightFoot()->associatedAnkle()->rankInConfiguration() << endl;
CjrlFoot *rightFoot = aHDR->rightFoot();
DisplayFoot(rightFoot,empty,tcout);
tcout << "Rank of the left foot "<< endl;
tcout << aHDR->leftFoot()->associatedAnkle()->rankInConfiguration() << endl;
CjrlFoot *leftFoot = aHDR->leftFoot();
DisplayFoot(leftFoot,empty,tcout);
tcout << "Current transformation of left Ankle."<< endl;
dm4d(aHDR->leftAnkle()->currentTransformation(),tcout,empty);
tcout << endl;
tcout << "Current transformation of right Ankle."<< endl;
dm4d(aHDR->rightAnkle()->currentTransformation(),tcout,empty);
tcout << endl;
MAL_VECTOR_FILL(aCurrentVel,0.0);
MAL_VECTOR_DIM(aCurrentAcc,double,NbOfDofs);
MAL_VECTOR_FILL(aCurrentAcc,0.0);
// This is mandatory for this implementation of computeForwardKinematics
// to compute the derivative of the momentum.
{
string inProperty[5]={"TimeStep","ComputeAcceleration",
"ComputeBackwardDynamics", "ComputeZMP","ComputeAccelerationCoM"};
string inValue[5]={"0.005","true","true","true","true"};
for(unsigned int i=0;i<5;i++)
aHDR->setProperty(inProperty[i],inValue[i]);
}
for(int i=0;i<4;i++)
{
aHDR->currentVelocity(aCurrentVel);
aHDR->currentAcceleration(aCurrentAcc);
aHDR->computeForwardKinematics();
ZMPval = aHDR->zeroMomentumPoint();
tcout << i << "-th value of ZMP : "
<< filterprecision(ZMPval(0)) << " "
<< filterprecision(ZMPval(1)) << " "
<< filterprecision(ZMPval(2)) << endl;
poscom = aHDR->positionCenterOfMass();
tcout << "Should be equal to the CoM: "
<< filterprecision(poscom(0)) << " "
<< filterprecision(poscom(1)) << " "
<< filterprecision(poscom(2)) << endl;
}
// Check the information on actuated joints.
std::vector<CjrlJoint *> ActuatedJoints = aHDR->getActuatedJoints();
tcout << "Size of actuated Joints:" << ActuatedJoints.size() << endl;
for(unsigned int i=0;i<ActuatedJoints.size();i++)
tcout << "Rank of actuated joints ("<<i<< ") in configuration :"
<< ActuatedJoints[i]->rankInConfiguration() << endl;
tcout << "Humanoid mass:" << aHDR->mass() << endl;
DisplayForces(aHDR,empty,tcout);
DisplayTorques(aHDR,empty, tcout);
// Test torques.
tcout << "Test Torques:" << endl;
const matrixNxP& Torques = aHDR->currentTorques();
for(unsigned int i=6;i<MAL_MATRIX_NB_ROWS(Torques);i++)
{
double torquefrominertia = 9.81 * InertiaMatrix(i,2);
tcout << filterprecision(Torques(i,0)) << " "
<< filterprecision(torquefrominertia) << endl;
}
tcout.close();
// ASCII Comparison between the generated output and the reference one
// given in argument.
if (argc==2)
{
char OurFileName[120]="output.txt";
char ReportFileName[120]="reportthdr.txt";
if (CompareTwoFiles(argv[1],
OurFileName,
ReportFileName))
{
delete aHDR;
return 0;
}
}
delete aHDR;
return -1;
}
<commit_msg>Display the robot model name.<commit_after>/*
* Copyright 2010,
*
* Luis Degaldo
* Francois Keith
* Florent Lamiraux
* Layale Saab
* Olivier Stasse,
*
* JRL/LAAS, CNRS/AIST
*
* This file is part of dynamicsJRLJapan.
* dynamicsJRLJapan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dynamicsJRLJapan 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 Lesser Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with dynamicsJRLJapan. If not, see <http://www.gnu.org/licenses/>.
*
* Research carried out within the scope of the Associated
* International Laboratory: Joint Japanese-French Robotics
* Laboratory (JRL)
*
*/
/* @doc \file Object to generate a file following AMELIF format. */
#include <string>
#include <iostream>
#include <fstream>
#include <jrl/dynamics/dynamicsfactory.hh>
#include "CommonTools.h"
using namespace std;
using namespace dynamicsJRLJapan;
void DisplayDynamicRobotInformation(CjrlDynamicRobot *aDynamicRobot,
ostream &tcout)
{
std::vector<CjrlJoint *> aVec = aDynamicRobot->jointVector();
int r = aVec.size();
tcout << "Number of joints :" << r << endl;
}
int main(int argc, char *argv[])
{
string aSpecificitiesFileName;
string aPath;
string aName;
string aMapFromJointToRank;
ofstream tcout("output.txt",ofstream::out);
if (argc!=5)
{
aPath="./";
aName="sample.wrl";
aSpecificitiesFileName = "sampleSpecificities.xml";
aMapFromJointToRank = "sampleLinkJointRank.xml";
}
else
{
aSpecificitiesFileName = argv[3];
aPath=argv[1];
aName=argv[2];
aMapFromJointToRank=argv[4];
}
dynamicsJRLJapan::ObjectFactory aRobotDynamicsObjectConstructor;
CjrlHumanoidDynamicRobot * aHDR = aRobotDynamicsObjectConstructor.createHumanoidDynamicRobot();
if (aHDR==0)
{
cerr<< "Dynamic cast on HDR failed " << endl;
exit(-1);
}
string RobotFileName = aPath+aName;
cout << "RobotFileName:" << RobotFileName <<endl;
dynamicsJRLJapan::parseOpenHRPVRMLFile(*aHDR,RobotFileName,aMapFromJointToRank,aSpecificitiesFileName);
// Display tree of the joints.
CjrlJoint* rootJoint = aHDR->rootJoint();
int NbOfDofs = aHDR->numberDof();
tcout << "NbOfDofs :" << NbOfDofs << std::endl;
if (NbOfDofs==0)
{
cerr << "Empty Robot..."<< endl;
return -1;
}
MAL_VECTOR_DIM(aCurrentConf,double,NbOfDofs);
int lindex=0;
for(int i=0;i<6;i++)
aCurrentConf[lindex++] = 0.0;
aCurrentConf[2] = 0.705;
for(int i=0;i<NbOfDofs-6 ;i++)
aCurrentConf[lindex++] = 0.0;
aHDR->currentConfiguration(aCurrentConf);
MAL_VECTOR_DIM(aCurrentVel,double,NbOfDofs);
lindex=0;
for(int i=0;i<NbOfDofs;i++)
aCurrentVel[lindex++] = 0.0;
MAL_S3_VECTOR(ZMPval,double);
aHDR->currentVelocity(aCurrentVel);
// aHDR->setComputeZMP(true);
string inProperty="ComputeZMP"; string aValue="true";
aHDR->setProperty(inProperty,aValue);
aHDR->computeForwardKinematics();
ZMPval = aHDR->zeroMomentumPoint();
tcout << "First value of ZMP : "
<< filterprecision(ZMPval(0)) << " "
<< filterprecision(ZMPval(1)) << " "
<< filterprecision(ZMPval(2)) << endl;
MAL_S3_VECTOR(poscom,double);
poscom = aHDR->positionCenterOfMass();
tcout << "Should be equal to the CoM: "
<< filterprecision(poscom(0)) << " "
<< filterprecision(poscom(1)) << " "
<< filterprecision(poscom(2)) << endl;
matrixNxP InertiaMatrix;
aHDR->computeInertiaMatrix();
InertiaMatrix = aHDR->inertiaMatrix();
tcout << "InertiaMatrix("
<< MAL_MATRIX_NB_ROWS(InertiaMatrix)<< ","
<< MAL_MATRIX_NB_COLS(InertiaMatrix)<< ")"<< endl;
DisplayMatrix(InertiaMatrix,tcout);
ofstream aof;
aof.open("InertiaMatrix.dat");
for(unsigned int i=0;i<MAL_MATRIX_NB_ROWS(InertiaMatrix);i++)
{
for(unsigned int j=0;j<MAL_MATRIX_NB_COLS(InertiaMatrix);j++)
{
aof << InertiaMatrix(i,j) << " ";
}
aof << endl;
}
aof.close();
std::vector<CjrlJoint *> aVec = aHDR->jointVector();
// Get the Jacobian of the right ankle.
CjrlJoint * aJoint = aHDR->rightAnkle();
aJoint->computeJacobianJointWrtConfig();
tcout << "Jacobian of the right ankle." << endl;
MAL_MATRIX_TYPE(double) aJ;
aJ = aJoint->jacobianJointWrtConfig();
DisplayMatrix(aJ,tcout);
// Get the articular Jacobian from the right ankle to the right wrist.
vector3d origin; origin(0) = 0.0; origin(1) = 0.0; origin(2) = 0.0;
aHDR->getJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
origin,
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
MAL_MATRIX_RESIZE(aJ,3, MAL_MATRIX_NB_COLS(aJ));
// Get the linear part of the articular Jacobian from the right ankle to the right wrist.
aHDR->getPositionJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
origin,
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
// Get the angular part of the articular Jacobian from the right ankle to the right wrist.
aHDR->getOrientationJacobian(*aHDR->rightAnkle(),
*aHDR->rightWrist(),
aJ);
tcout << "Jacobian from the right ankle to the right wrist. " << endl;
DisplayMatrix(aJ,tcout);
tcout << "****************************" << endl;
rootJoint->computeJacobianJointWrtConfig();
aJ = rootJoint->jacobianJointWrtConfig();
tcout << "Rank of Root: " << rootJoint->rankInConfiguration() << endl;
// DisplayMatrix(aJ);
aJoint = aHDR->waist();
tcout << "****************************" << endl;
#if 0
aHDR->computeJacobianCenterOfMass();
DisplayMatrix(aHDR->jacobianCenterOfMass(),tcout);
#else
matrixNxP JCM;
MAL_MATRIX_RESIZE(JCM,3,MAL_MATRIX_NB_COLS(aJ));
aHDR->getJacobianCenterOfMass(*aHDR->rootJoint(),JCM);
DisplayMatrix(JCM,tcout);
#endif
tcout << "****************************" << endl;
RecursiveDisplayOfJoints(rootJoint,tcout,10);
tcout << "****************************" << endl;
// Test rank of the hands.
tcout << "Rank of the right hand "<< endl;
tcout << aHDR->rightWrist()->rankInConfiguration() << endl;
CjrlHand *rightHand = aHDR->rightHand();
string empty("");
DisplayHand(rightHand,empty,tcout);
tcout << "Rank of the left hand "<< endl;
tcout << aHDR->leftWrist()->rankInConfiguration() << endl;
CjrlHand *leftHand = aHDR->leftHand();
DisplayHand(leftHand,empty,tcout);
// Test rank of the feet.
tcout << "Rank of the right foot "<< endl;
tcout << aHDR->rightFoot()->associatedAnkle()->rankInConfiguration() << endl;
CjrlFoot *rightFoot = aHDR->rightFoot();
DisplayFoot(rightFoot,empty,tcout);
tcout << "Rank of the left foot "<< endl;
tcout << aHDR->leftFoot()->associatedAnkle()->rankInConfiguration() << endl;
CjrlFoot *leftFoot = aHDR->leftFoot();
DisplayFoot(leftFoot,empty,tcout);
tcout << "Current transformation of left Ankle."<< endl;
dm4d(aHDR->leftAnkle()->currentTransformation(),tcout,empty);
tcout << endl;
tcout << "Current transformation of right Ankle."<< endl;
dm4d(aHDR->rightAnkle()->currentTransformation(),tcout,empty);
tcout << endl;
MAL_VECTOR_FILL(aCurrentVel,0.0);
MAL_VECTOR_DIM(aCurrentAcc,double,NbOfDofs);
MAL_VECTOR_FILL(aCurrentAcc,0.0);
// This is mandatory for this implementation of computeForwardKinematics
// to compute the derivative of the momentum.
{
string inProperty[5]={"TimeStep","ComputeAcceleration",
"ComputeBackwardDynamics", "ComputeZMP","ComputeAccelerationCoM"};
string inValue[5]={"0.005","true","true","true","true"};
for(unsigned int i=0;i<5;i++)
aHDR->setProperty(inProperty[i],inValue[i]);
}
for(int i=0;i<4;i++)
{
aHDR->currentVelocity(aCurrentVel);
aHDR->currentAcceleration(aCurrentAcc);
aHDR->computeForwardKinematics();
ZMPval = aHDR->zeroMomentumPoint();
tcout << i << "-th value of ZMP : "
<< filterprecision(ZMPval(0)) << " "
<< filterprecision(ZMPval(1)) << " "
<< filterprecision(ZMPval(2)) << endl;
poscom = aHDR->positionCenterOfMass();
tcout << "Should be equal to the CoM: "
<< filterprecision(poscom(0)) << " "
<< filterprecision(poscom(1)) << " "
<< filterprecision(poscom(2)) << endl;
}
// Check the information on actuated joints.
std::vector<CjrlJoint *> ActuatedJoints = aHDR->getActuatedJoints();
tcout << "Size of actuated Joints:" << ActuatedJoints.size() << endl;
for(unsigned int i=0;i<ActuatedJoints.size();i++)
tcout << "Rank of actuated joints ("<<i<< ") in configuration :"
<< ActuatedJoints[i]->rankInConfiguration() << endl;
tcout << "Humanoid mass:" << aHDR->mass() << endl;
DisplayForces(aHDR,empty,tcout);
DisplayTorques(aHDR,empty, tcout);
// Test torques.
tcout << "Test Torques:" << endl;
const matrixNxP& Torques = aHDR->currentTorques();
for(unsigned int i=6;i<MAL_MATRIX_NB_ROWS(Torques);i++)
{
double torquefrominertia = 9.81 * InertiaMatrix(i,2);
tcout << filterprecision(Torques(i,0)) << " "
<< filterprecision(torquefrominertia) << endl;
}
tcout.close();
// ASCII Comparison between the generated output and the reference one
// given in argument.
if (argc==2)
{
char OurFileName[120]="output.txt";
char ReportFileName[120]="reportthdr.txt";
if (CompareTwoFiles(argv[1],
OurFileName,
ReportFileName))
{
delete aHDR;
return 0;
}
}
delete aHDR;
return -1;
}
<|endoftext|> |
<commit_before>/**
* @file Vector3.hpp
*
* 3D vector class.
*
* @author James Goppert <[email protected]>
*/
#pragma once
#include "matrix.hpp"
namespace matrix
{
template<typename Type>
class Vector3 : public Vector<Type, 3>
{
public:
virtual ~Vector3() {};
Vector3() : Vector<Type, 3>()
{
}
Vector3(Type x, Type y, Type z) : Vector<Type, 3>()
{
Vector3 &v(*this);
v(0) = x;
v(1) = y;
v(2) = z;
}
Vector3 cross(const Vector3 & b) {
// TODO
Vector3 &a(*this);
(void)a;
Vector3 c;
c(0) = 0;
c(1) = 0;
c(2) = 0;
return c;
}
};
typedef Vector3<float> Vector3f;
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Added more vector ctors.<commit_after>/**
* @file Vector3.hpp
*
* 3D vector class.
*
* @author James Goppert <[email protected]>
*/
#pragma once
#include "matrix.hpp"
namespace matrix
{
template <typename Type, size_t M>
class Vector;
template<typename Type>
class Vector3 : public Vector<Type, 3>
{
public:
virtual ~Vector3() {};
Vector3() :
Vector<Type, 3>()
{
}
Vector3(const Vector<Type, 3> & other) :
Vector<Type, 3>(other)
{
}
Vector3(const Matrix<Type, 3, 1> & other) :
Vector<Type, 3>(other)
{
}
Vector3(const Type *data_) :
Vector<Type, 3>(data_)
{
}
Vector3(Type x, Type y, Type z) : Vector<Type, 3>()
{
Vector3 &v(*this);
v(0) = x;
v(1) = y;
v(2) = z;
}
Vector3 cross(const Vector3 & b) {
// TODO
Vector3 &a(*this);
(void)a;
Vector3 c;
c(0) = 0;
c(1) = 0;
c(2) = 0;
return c;
}
};
typedef Vector3<float> Vector3f;
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|> |
<commit_before>//===- lld/unittest/InputGraphTest.cpp -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief InputGraph Tests
///
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "lld/Core/InputGraph.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Simple.h"
using namespace lld;
namespace {
class MyLinkingContext : public LinkingContext {
public:
Writer &writer() const override { llvm_unreachable("no writer!"); }
bool validateImpl(raw_ostream &) override { return true; }
};
class MyFileNode : public SimpleFileNode {
public:
MyFileNode(StringRef path) : SimpleFileNode(path) {}
void resetNextIndex() override { FileNode::resetNextIndex(); }
};
class MyExpandFileNode : public SimpleFileNode {
public:
MyExpandFileNode(StringRef path) : SimpleFileNode(path) {}
/// Returns true as we want to expand this file
bool shouldExpand() const override { return true; }
/// Returns the elements replacing this node
range<InputGraph::InputElementIterT> expandElements() override {
return make_range(_expandElements.begin(), _expandElements.end());
}
void addElement(std::unique_ptr<InputElement> element) {
_expandElements.push_back(std::move(element));
}
private:
InputGraph::InputElementVectorT _expandElements;
};
class InputGraphTest : public testing::Test {
public:
InputGraphTest() {
_ctx.setInputGraph(std::unique_ptr<InputGraph>(new InputGraph()));
_graph = &_ctx.getInputGraph();
}
StringRef getNext() {
ErrorOr<File &> file = _graph->getNextFile();
EXPECT_TRUE(!file.getError());
return file.get().path();
}
void expectEnd() {
ErrorOr<File &> file = _graph->getNextFile();
EXPECT_EQ(InputGraphError::no_more_files, file.getError());
}
protected:
MyLinkingContext _ctx;
InputGraph *_graph;
};
} // end anonymous namespace
static std::unique_ptr<MyFileNode> createFile1(StringRef name) {
std::vector<std::unique_ptr<File>> files;
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name)));
std::unique_ptr<MyFileNode> file(new MyFileNode("filenode"));
file->addFiles(std::move(files));
return file;
}
static std::unique_ptr<MyFileNode> createFile2(StringRef name1, StringRef name2) {
std::vector<std::unique_ptr<File>> files;
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name1)));
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name2)));
std::unique_ptr<MyFileNode> file(new MyFileNode("filenode"));
file->addFiles(std::move(files));
return file;
}
TEST_F(InputGraphTest, Empty) {
expectEnd();
}
TEST_F(InputGraphTest, File) {
_graph->addInputElement(createFile1("file1"));
EXPECT_EQ("file1", getNext());
expectEnd();
}
TEST_F(InputGraphTest, Files) {
_graph->addInputElement(createFile2("file1", "file2"));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
expectEnd();
}
TEST_F(InputGraphTest, Group) {
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<Group> group(new Group());
group->addFile(createFile2("file3", "file4"));
group->addFile(createFile1("file5"));
group->addFile(createFile1("file6"));
_graph->addInputElement(std::move(group));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
expectEnd();
}
// Iterate through the group
TEST_F(InputGraphTest, GroupIteration) {
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<Group> group(new Group());
group->addFile(createFile2("file3", "file4"));
group->addFile(createFile1("file5"));
group->addFile(createFile1("file6"));
_graph->addInputElement(std::move(group));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
_graph->notifyProgress();
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
expectEnd();
}
// Node expansion tests
TEST_F(InputGraphTest, Normalize) {
std::vector<std::unique_ptr<File>> objfiles;
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<MyExpandFileNode> expandFile(new MyExpandFileNode("node"));
expandFile->addElement(createFile1("file3"));
expandFile->addElement(createFile1("file4"));
_graph->addInputElement(std::move(expandFile));
_graph->addInputElement(createFile2("file5", "file6"));
_graph->normalize();
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
_graph->notifyProgress();
}
<commit_msg>s/My/Test/ as these classes are for tests.<commit_after>//===- lld/unittest/InputGraphTest.cpp -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief InputGraph Tests
///
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "lld/Core/InputGraph.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Simple.h"
using namespace lld;
namespace {
class TestLinkingContext : public LinkingContext {
public:
Writer &writer() const override { llvm_unreachable("no writer!"); }
bool validateImpl(raw_ostream &) override { return true; }
};
class TestFileNode : public SimpleFileNode {
public:
TestFileNode(StringRef path) : SimpleFileNode(path) {}
void resetNextIndex() override { FileNode::resetNextIndex(); }
};
class TestExpandFileNode : public SimpleFileNode {
public:
TestExpandFileNode(StringRef path) : SimpleFileNode(path) {}
/// Returns true as we want to expand this file
bool shouldExpand() const override { return true; }
/// Returns the elements replacing this node
range<InputGraph::InputElementIterT> expandElements() override {
return make_range(_expandElements.begin(), _expandElements.end());
}
void addElement(std::unique_ptr<InputElement> element) {
_expandElements.push_back(std::move(element));
}
private:
InputGraph::InputElementVectorT _expandElements;
};
class InputGraphTest : public testing::Test {
public:
InputGraphTest() {
_ctx.setInputGraph(std::unique_ptr<InputGraph>(new InputGraph()));
_graph = &_ctx.getInputGraph();
}
StringRef getNext() {
ErrorOr<File &> file = _graph->getNextFile();
EXPECT_TRUE(!file.getError());
return file.get().path();
}
void expectEnd() {
ErrorOr<File &> file = _graph->getNextFile();
EXPECT_EQ(InputGraphError::no_more_files, file.getError());
}
protected:
TestLinkingContext _ctx;
InputGraph *_graph;
};
} // end anonymous namespace
static std::unique_ptr<TestFileNode> createFile1(StringRef name) {
std::vector<std::unique_ptr<File>> files;
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name)));
std::unique_ptr<TestFileNode> file(new TestFileNode("filenode"));
file->addFiles(std::move(files));
return file;
}
static std::unique_ptr<TestFileNode> createFile2(StringRef name1,
StringRef name2) {
std::vector<std::unique_ptr<File>> files;
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name1)));
files.push_back(std::unique_ptr<SimpleFile>(new SimpleFile(name2)));
std::unique_ptr<TestFileNode> file(new TestFileNode("filenode"));
file->addFiles(std::move(files));
return file;
}
TEST_F(InputGraphTest, Empty) {
expectEnd();
}
TEST_F(InputGraphTest, File) {
_graph->addInputElement(createFile1("file1"));
EXPECT_EQ("file1", getNext());
expectEnd();
}
TEST_F(InputGraphTest, Files) {
_graph->addInputElement(createFile2("file1", "file2"));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
expectEnd();
}
TEST_F(InputGraphTest, Group) {
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<Group> group(new Group());
group->addFile(createFile2("file3", "file4"));
group->addFile(createFile1("file5"));
group->addFile(createFile1("file6"));
_graph->addInputElement(std::move(group));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
expectEnd();
}
// Iterate through the group
TEST_F(InputGraphTest, GroupIteration) {
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<Group> group(new Group());
group->addFile(createFile2("file3", "file4"));
group->addFile(createFile1("file5"));
group->addFile(createFile1("file6"));
_graph->addInputElement(std::move(group));
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
_graph->notifyProgress();
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
expectEnd();
}
// Node expansion tests
TEST_F(InputGraphTest, Normalize) {
std::vector<std::unique_ptr<File>> objfiles;
_graph->addInputElement(createFile2("file1", "file2"));
std::unique_ptr<TestExpandFileNode> expandFile(
new TestExpandFileNode("node"));
expandFile->addElement(createFile1("file3"));
expandFile->addElement(createFile1("file4"));
_graph->addInputElement(std::move(expandFile));
_graph->addInputElement(createFile2("file5", "file6"));
_graph->normalize();
EXPECT_EQ("file1", getNext());
EXPECT_EQ("file2", getNext());
EXPECT_EQ("file3", getNext());
EXPECT_EQ("file4", getNext());
EXPECT_EQ("file5", getNext());
EXPECT_EQ("file6", getNext());
_graph->notifyProgress();
}
<|endoftext|> |
<commit_before>//===--- BindingInferenceTests.cpp ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SemaFixture.h"
#include "swift/AST/Expr.h"
#include "swift/Sema/ConstraintSystem.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace swift;
using namespace swift::unittest;
using namespace swift::constraints;
TEST_F(SemaTest, TestIntLiteralBindingInference) {
ConstraintSystemOptions options;
options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables;
ConstraintSystem cs(DC, options);
auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42);
auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral),
/*options=*/0);
cs.addConstraint(
ConstraintKind::LiteralConformsTo, literalTy,
Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)
->getDeclaredInterfaceType(),
cs.getConstraintLocator(intLiteral));
auto intTy = getStdlibType("Int");
{
auto bindings = cs.inferBindingsFor(literalTy);
ASSERT_EQ(bindings.Literals.size(), (unsigned)1);
const auto &literal = bindings.Literals.front().second;
ASSERT_TRUE(literal.hasDefaultType());
ASSERT_TRUE(literal.getDefaultType()->isEqual(intTy));
ASSERT_FALSE(literal.isCovered());
}
}
// Given a set of inferred protocol requirements, make sure that
// all of the expected types are present.
static void verifyProtocolInferenceResults(
const llvm::SmallPtrSetImpl<Constraint *> &protocols,
ArrayRef<Type> expectedTypes) {
ASSERT_TRUE(protocols.size() >= expectedTypes.size());
llvm::SmallPtrSet<Type, 2> inferredProtocolTypes;
for (auto *protocol : protocols)
inferredProtocolTypes.insert(protocol->getSecondType());
for (auto expectedTy : expectedTypes) {
ASSERT_TRUE(inferredProtocolTypes.count(expectedTy));
}
}
TEST_F(SemaTest, TestTransitiveProtocolInference) {
ConstraintSystemOptions options;
ConstraintSystem cs(DC, options);
auto *protocolTy1 = createProtocol("P1");
auto *protocolTy2 = createProtocol("P2");
auto *GPT1 = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/TVO_CanBindToNoEscape);
auto *GPT2 = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/TVO_CanBindToNoEscape);
cs.addConstraint(
ConstraintKind::ConformsTo, GPT1, protocolTy1,
cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(
0, RequirementKind::Conformance)));
cs.addConstraint(
ConstraintKind::ConformsTo, GPT2, protocolTy2,
cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(
0, RequirementKind::Conformance)));
// First, let's try inferring through a single conversion
// relationship.
{
auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/0);
cs.addConstraint(
ConstraintKind::Conversion, typeVar, GPT1,
cs.getConstraintLocator({}, LocatorPathElt::ContextualType()));
auto bindings = inferBindings(cs, typeVar);
ASSERT_TRUE(bindings.Protocols.empty());
ASSERT_TRUE(bool(bindings.TransitiveProtocols));
verifyProtocolInferenceResults(*bindings.TransitiveProtocols,
{protocolTy1});
}
// Now, let's make sure that protocol requirements could be propagated
// down conversion/equality chains through multiple hops.
{
// GPT1 is a subtype of GPT2 and GPT2 is convertible to a target type
// variable, target should get both protocols inferred - P1 & P2.
auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/0);
cs.addConstraint(ConstraintKind::Subtype, GPT1, GPT2,
cs.getConstraintLocator({}));
cs.addConstraint(ConstraintKind::Conversion, typeVar, GPT1,
cs.getConstraintLocator({}));
auto bindings = inferBindings(cs, typeVar);
ASSERT_TRUE(bindings.Protocols.empty());
ASSERT_TRUE(bool(bindings.TransitiveProtocols));
verifyProtocolInferenceResults(*bindings.TransitiveProtocols,
{protocolTy1, protocolTy2});
}
}
/// Let's try a more complicated situation where there protocols
/// are inferred from multiple sources on different levels of
/// convertion chain.
///
/// (P1) T0 T4 (T3) T6 (P4)
/// \ / /
/// T3 = T1 (P2) = T5
/// \ /
/// T2
TEST_F(SemaTest, TestComplexTransitiveProtocolInference) {
ConstraintSystemOptions options;
ConstraintSystem cs(DC, options);
auto *protocolTy1 = createProtocol("P1");
auto *protocolTy2 = createProtocol("P2");
auto *protocolTy3 = createProtocol("P3");
auto *protocolTy4 = createProtocol("P4");
auto *nilLocator = cs.getConstraintLocator({});
auto typeVar0 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar1 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar2 = cs.createTypeVariable(nilLocator, /*options=*/0);
// Allow this type variable to be bound to l-value type to prevent
// it from being merged with the rest of the type variables.
auto typeVar3 =
cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue);
auto typeVar4 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar5 =
cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue);
auto typeVar6 = cs.createTypeVariable(nilLocator, /*options=*/0);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar0, protocolTy1,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar1, protocolTy2,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar4, protocolTy3,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar6, protocolTy4,
nilLocator);
// T3 <: T0, T3 <: T4
cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar0, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar4, nilLocator);
// T2 <: T3, T2 <: T1, T3 == T1
cs.addConstraint(ConstraintKind::Subtype, typeVar2, typeVar3, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar2, typeVar1, nilLocator);
cs.addConstraint(ConstraintKind::Equal, typeVar3, typeVar1, nilLocator);
// T1 == T5, T <: T6
cs.addConstraint(ConstraintKind::Equal, typeVar1, typeVar5, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar5, typeVar6, nilLocator);
auto bindingsForT1 = inferBindings(cs, typeVar1);
auto bindingsForT2 = inferBindings(cs, typeVar2);
auto bindingsForT3 = inferBindings(cs, typeVar3);
auto bindingsForT5 = inferBindings(cs, typeVar5);
ASSERT_TRUE(bool(bindingsForT1.TransitiveProtocols));
verifyProtocolInferenceResults(*bindingsForT1.TransitiveProtocols,
{protocolTy1, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT2.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT2.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT3.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT3.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT5.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT5.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
}
<commit_msg>[unittests/Sema] NFC: Add tests for literal requirement inference/coverage<commit_after>//===--- BindingInferenceTests.cpp ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SemaFixture.h"
#include "swift/AST/Expr.h"
#include "swift/Sema/ConstraintSystem.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace swift;
using namespace swift::unittest;
using namespace swift::constraints;
TEST_F(SemaTest, TestIntLiteralBindingInference) {
ConstraintSystemOptions options;
options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables;
ConstraintSystem cs(DC, options);
auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42);
auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral),
/*options=*/0);
cs.addConstraint(
ConstraintKind::LiteralConformsTo, literalTy,
Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)
->getDeclaredInterfaceType(),
cs.getConstraintLocator(intLiteral));
auto intTy = getStdlibType("Int");
{
auto bindings = cs.inferBindingsFor(literalTy);
ASSERT_EQ(bindings.Literals.size(), (unsigned)1);
const auto &literal = bindings.Literals.front().second;
ASSERT_TRUE(literal.hasDefaultType());
ASSERT_TRUE(literal.getDefaultType()->isEqual(intTy));
ASSERT_FALSE(literal.isCovered());
}
// Make sure that coverage by direct bindings works as expected.
// First, let's attempt a binding which would match default type
// of the literal.
cs.addConstraint(ConstraintKind::Conversion, literalTy, intTy,
cs.getConstraintLocator(intLiteral));
{
auto bindings = cs.inferBindingsFor(literalTy);
ASSERT_EQ(bindings.Bindings.size(), (unsigned)1);
ASSERT_EQ(bindings.Literals.size(), (unsigned)1);
ASSERT_TRUE(bindings.Bindings[0].BindingType->isEqual(intTy));
const auto &literal = bindings.Literals.front().second;
ASSERT_TRUE(literal.isCovered());
ASSERT_TRUE(literal.isDirectRequirement());
ASSERT_TRUE(literal.getDefaultType()->isEqual(intTy));
}
// Now let's use non-default type that conforms to
// `ExpressibleByIntegerLiteral` protocol.
auto *floatLiteralTy =
cs.createTypeVariable(cs.getConstraintLocator(intLiteral),
/*options=*/0);
auto floatTy = getStdlibType("Float");
// $T_float <conforms to> ExpressibleByIntegerLiteral
cs.addConstraint(
ConstraintKind::LiteralConformsTo, floatLiteralTy,
Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)
->getDeclaredInterfaceType(),
cs.getConstraintLocator(intLiteral));
// Float <covertible> $T_float
cs.addConstraint(ConstraintKind::Conversion, floatTy, floatLiteralTy,
cs.getConstraintLocator(intLiteral));
{
auto bindings = cs.inferBindingsFor(floatLiteralTy);
ASSERT_EQ(bindings.Bindings.size(), (unsigned)1);
ASSERT_EQ(bindings.Literals.size(), (unsigned)1);
ASSERT_TRUE(bindings.Bindings[0].BindingType->isEqual(floatTy));
const auto &literal = bindings.Literals.front().second;
ASSERT_TRUE(literal.isCovered());
ASSERT_TRUE(literal.isDirectRequirement());
ASSERT_FALSE(literal.getDefaultType()->isEqual(floatTy));
}
// Let's test transitive literal requirement coverage,
// literal requirements are prepagated up the subtype chain.
auto *otherTy = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/0);
cs.addConstraint(ConstraintKind::Subtype, floatLiteralTy, otherTy,
cs.getConstraintLocator({}));
{
auto bindings = cs.inferBindingsFor(otherTy, /*finalize=*/false);
// Make sure that there are no direct bindings or protocol requirements.
ASSERT_EQ(bindings.Bindings.size(), (unsigned)0);
ASSERT_EQ(bindings.Literals.size(), (unsigned)0);
llvm::SmallDenseMap<TypeVariableType *, ConstraintSystem::PotentialBindings>
env;
env.insert({floatLiteralTy, cs.inferBindingsFor(floatLiteralTy)});
bindings.finalize(cs, env);
// Inferred a single transitive binding through `$T_float`.
ASSERT_EQ(bindings.Bindings.size(), (unsigned)1);
// Inferred literal requirement through `$T_float` as well.
ASSERT_EQ(bindings.Literals.size(), (unsigned)1);
const auto &literal = bindings.Literals.front().second;
ASSERT_TRUE(literal.isCovered());
ASSERT_FALSE(literal.isDirectRequirement());
ASSERT_FALSE(literal.getDefaultType()->isEqual(floatTy));
}
}
// Given a set of inferred protocol requirements, make sure that
// all of the expected types are present.
static void verifyProtocolInferenceResults(
const llvm::SmallPtrSetImpl<Constraint *> &protocols,
ArrayRef<Type> expectedTypes) {
ASSERT_TRUE(protocols.size() >= expectedTypes.size());
llvm::SmallPtrSet<Type, 2> inferredProtocolTypes;
for (auto *protocol : protocols)
inferredProtocolTypes.insert(protocol->getSecondType());
for (auto expectedTy : expectedTypes) {
ASSERT_TRUE(inferredProtocolTypes.count(expectedTy));
}
}
TEST_F(SemaTest, TestTransitiveProtocolInference) {
ConstraintSystemOptions options;
ConstraintSystem cs(DC, options);
auto *protocolTy1 = createProtocol("P1");
auto *protocolTy2 = createProtocol("P2");
auto *GPT1 = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/TVO_CanBindToNoEscape);
auto *GPT2 = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/TVO_CanBindToNoEscape);
cs.addConstraint(
ConstraintKind::ConformsTo, GPT1, protocolTy1,
cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(
0, RequirementKind::Conformance)));
cs.addConstraint(
ConstraintKind::ConformsTo, GPT2, protocolTy2,
cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(
0, RequirementKind::Conformance)));
// First, let's try inferring through a single conversion
// relationship.
{
auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/0);
cs.addConstraint(
ConstraintKind::Conversion, typeVar, GPT1,
cs.getConstraintLocator({}, LocatorPathElt::ContextualType()));
auto bindings = inferBindings(cs, typeVar);
ASSERT_TRUE(bindings.Protocols.empty());
ASSERT_TRUE(bool(bindings.TransitiveProtocols));
verifyProtocolInferenceResults(*bindings.TransitiveProtocols,
{protocolTy1});
}
// Now, let's make sure that protocol requirements could be propagated
// down conversion/equality chains through multiple hops.
{
// GPT1 is a subtype of GPT2 and GPT2 is convertible to a target type
// variable, target should get both protocols inferred - P1 & P2.
auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),
/*options=*/0);
cs.addConstraint(ConstraintKind::Subtype, GPT1, GPT2,
cs.getConstraintLocator({}));
cs.addConstraint(ConstraintKind::Conversion, typeVar, GPT1,
cs.getConstraintLocator({}));
auto bindings = inferBindings(cs, typeVar);
ASSERT_TRUE(bindings.Protocols.empty());
ASSERT_TRUE(bool(bindings.TransitiveProtocols));
verifyProtocolInferenceResults(*bindings.TransitiveProtocols,
{protocolTy1, protocolTy2});
}
}
/// Let's try a more complicated situation where there protocols
/// are inferred from multiple sources on different levels of
/// convertion chain.
///
/// (P1) T0 T4 (T3) T6 (P4)
/// \ / /
/// T3 = T1 (P2) = T5
/// \ /
/// T2
TEST_F(SemaTest, TestComplexTransitiveProtocolInference) {
ConstraintSystemOptions options;
ConstraintSystem cs(DC, options);
auto *protocolTy1 = createProtocol("P1");
auto *protocolTy2 = createProtocol("P2");
auto *protocolTy3 = createProtocol("P3");
auto *protocolTy4 = createProtocol("P4");
auto *nilLocator = cs.getConstraintLocator({});
auto typeVar0 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar1 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar2 = cs.createTypeVariable(nilLocator, /*options=*/0);
// Allow this type variable to be bound to l-value type to prevent
// it from being merged with the rest of the type variables.
auto typeVar3 =
cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue);
auto typeVar4 = cs.createTypeVariable(nilLocator, /*options=*/0);
auto typeVar5 =
cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue);
auto typeVar6 = cs.createTypeVariable(nilLocator, /*options=*/0);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar0, protocolTy1,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar1, protocolTy2,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar4, protocolTy3,
nilLocator);
cs.addConstraint(ConstraintKind::ConformsTo, typeVar6, protocolTy4,
nilLocator);
// T3 <: T0, T3 <: T4
cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar0, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar4, nilLocator);
// T2 <: T3, T2 <: T1, T3 == T1
cs.addConstraint(ConstraintKind::Subtype, typeVar2, typeVar3, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar2, typeVar1, nilLocator);
cs.addConstraint(ConstraintKind::Equal, typeVar3, typeVar1, nilLocator);
// T1 == T5, T <: T6
cs.addConstraint(ConstraintKind::Equal, typeVar1, typeVar5, nilLocator);
cs.addConstraint(ConstraintKind::Conversion, typeVar5, typeVar6, nilLocator);
auto bindingsForT1 = inferBindings(cs, typeVar1);
auto bindingsForT2 = inferBindings(cs, typeVar2);
auto bindingsForT3 = inferBindings(cs, typeVar3);
auto bindingsForT5 = inferBindings(cs, typeVar5);
ASSERT_TRUE(bool(bindingsForT1.TransitiveProtocols));
verifyProtocolInferenceResults(*bindingsForT1.TransitiveProtocols,
{protocolTy1, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT2.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT2.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT3.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT3.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
ASSERT_TRUE(bool(bindingsForT5.TransitiveProtocols));
verifyProtocolInferenceResults(
*bindingsForT5.TransitiveProtocols,
{protocolTy1, protocolTy2, protocolTy3, protocolTy4});
}
<|endoftext|> |
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/data_reduction_proxy_resource_throttle_android.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_request.h"
using content::BrowserThread;
using content::ResourceThrottle;
// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
// unit test coverage.
// TODO(sgurun) following the comment above, also provide tests for
// checking whether the headers are injected correctly and the SPDY proxy
// origin is tested properly.
const char* DataReductionProxyResourceThrottle::kUnsafeUrlProceedHeader =
"X-Unsafe-Url-Proceed";
// static
DataReductionProxyResourceThrottle*
DataReductionProxyResourceThrottle::MaybeCreate(
net::URLRequest* request,
content::ResourceContext* resource_context,
content::ResourceType resource_type,
SafeBrowsingService* sb_service) {
ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
// Don't create the throttle if we can't handle the request.
if (io_data->IsOffTheRecord() || !io_data->IsDataReductionProxyEnabled() ||
request->url().SchemeIsSecure()) {
return NULL;
}
return new DataReductionProxyResourceThrottle(request, resource_type,
sb_service);
}
DataReductionProxyResourceThrottle::DataReductionProxyResourceThrottle(
net::URLRequest* request,
content::ResourceType resource_type,
SafeBrowsingService* safe_browsing)
: state_(STATE_NONE),
safe_browsing_(safe_browsing),
request_(request),
is_subresource_(resource_type != content::RESOURCE_TYPE_MAIN_FRAME),
is_subframe_(resource_type == content::RESOURCE_TYPE_SUB_FRAME) {
}
DataReductionProxyResourceThrottle::~DataReductionProxyResourceThrottle() { }
void DataReductionProxyResourceThrottle::WillRedirectRequest(
const net::RedirectInfo& redirect_info,
bool* defer) {
CHECK(state_ == STATE_NONE);
// Save the redirect urls for possible malware detail reporting later.
redirect_urls_.push_back(redirect_info.new_url);
// We need to check the new URL before following the redirect.
SBThreatType threat_type = CheckUrl();
if (threat_type == SB_THREAT_TYPE_SAFE)
return;
if (request_->load_flags() & net::LOAD_PREFETCH) {
controller()->Cancel();
return;
}
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request_);
state_ = STATE_DISPLAYING_BLOCKING_PAGE;
SafeBrowsingUIManager::UnsafeResource unsafe_resource;
unsafe_resource.url = redirect_info.new_url;
unsafe_resource.original_url = request_->original_url();
unsafe_resource.redirect_urls = redirect_urls_;
unsafe_resource.is_subresource = is_subresource_;
unsafe_resource.is_subframe = is_subframe_;
unsafe_resource.threat_type = threat_type;
unsafe_resource.callback = base::Bind(
&DataReductionProxyResourceThrottle::OnBlockingPageComplete, AsWeakPtr());
unsafe_resource.render_process_host_id = info->GetChildID();
unsafe_resource.render_view_id = info->GetRouteID();
unsafe_resource.threat_source = SafeBrowsingUIManager::FROM_DATA_SAVER;
*defer = true;
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(
&DataReductionProxyResourceThrottle::StartDisplayingBlockingPage,
AsWeakPtr(), safe_browsing_->ui_manager(), unsafe_resource));
}
const char* DataReductionProxyResourceThrottle::GetNameForLogging() const {
return "DataReductionProxyResourceThrottle";
}
// static
void DataReductionProxyResourceThrottle::StartDisplayingBlockingPage(
const base::WeakPtr<DataReductionProxyResourceThrottle>& throttle,
scoped_refptr<SafeBrowsingUIManager> ui_manager,
const SafeBrowsingUIManager::UnsafeResource& resource) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::RenderViewHost* rvh = content::RenderViewHost::FromID(
resource.render_process_host_id, resource.render_view_id);
if (rvh) {
content::WebContents* web_contents =
content::WebContents::FromRenderViewHost(rvh);
prerender::PrerenderContents* prerender_contents =
prerender::PrerenderContents::FromWebContents(web_contents);
if (prerender_contents) {
prerender_contents->Destroy(prerender::FINAL_STATUS_SAFE_BROWSING);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(resource.callback, false));
return;
}
}
ui_manager->DisplayBlockingPage(resource);
}
// SafeBrowsingService::UrlCheckCallback implementation, called on the IO
// thread when the user has decided to proceed with the current request, or
// go back.
void DataReductionProxyResourceThrottle::OnBlockingPageComplete(bool proceed) {
CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
state_ = STATE_NONE;
if (proceed)
ResumeRequest();
else
controller()->Cancel();
}
SBThreatType DataReductionProxyResourceThrottle::CheckUrl() {
SBThreatType result = SB_THREAT_TYPE_SAFE;
// TODO(sgurun) Check for spdy proxy origin.
if (request_->response_headers() == NULL)
return result;
if (request_->response_headers()->HasHeader("X-Phishing-Url"))
result = SB_THREAT_TYPE_URL_PHISHING;
else if (request_->response_headers()->HasHeader("X-Malware-Url"))
result = SB_THREAT_TYPE_URL_MALWARE;
// If safe browsing is disabled and the request is sent to the DRP server,
// we need to break the redirect loop by setting the extra header.
if (result != SB_THREAT_TYPE_SAFE && !safe_browsing_->enabled()) {
request_->SetExtraRequestHeaderByName(kUnsafeUrlProceedHeader, "1", true);
result = SB_THREAT_TYPE_SAFE;
}
return result;
}
void DataReductionProxyResourceThrottle::ResumeRequest() {
CHECK(state_ == STATE_NONE);
// Inject the header before resuming the request.
request_->SetExtraRequestHeaderByName(kUnsafeUrlProceedHeader, "1", true);
controller()->Resume();
}
<commit_msg>Switch DataReductionProxyResourceThrottle::MaybeCreate() from SchemeIsSecure() to SchemeIsCryptographic().<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/data_reduction_proxy_resource_throttle_android.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/url_request.h"
using content::BrowserThread;
using content::ResourceThrottle;
// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
// unit test coverage.
// TODO(sgurun) following the comment above, also provide tests for
// checking whether the headers are injected correctly and the SPDY proxy
// origin is tested properly.
const char* DataReductionProxyResourceThrottle::kUnsafeUrlProceedHeader =
"X-Unsafe-Url-Proceed";
// static
DataReductionProxyResourceThrottle*
DataReductionProxyResourceThrottle::MaybeCreate(
net::URLRequest* request,
content::ResourceContext* resource_context,
content::ResourceType resource_type,
SafeBrowsingService* sb_service) {
ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
// Don't create the throttle if we can't handle the request.
if (io_data->IsOffTheRecord() || !io_data->IsDataReductionProxyEnabled() ||
request->url().SchemeIsCryptographic()) {
return NULL;
}
return new DataReductionProxyResourceThrottle(request, resource_type,
sb_service);
}
DataReductionProxyResourceThrottle::DataReductionProxyResourceThrottle(
net::URLRequest* request,
content::ResourceType resource_type,
SafeBrowsingService* safe_browsing)
: state_(STATE_NONE),
safe_browsing_(safe_browsing),
request_(request),
is_subresource_(resource_type != content::RESOURCE_TYPE_MAIN_FRAME),
is_subframe_(resource_type == content::RESOURCE_TYPE_SUB_FRAME) {
}
DataReductionProxyResourceThrottle::~DataReductionProxyResourceThrottle() { }
void DataReductionProxyResourceThrottle::WillRedirectRequest(
const net::RedirectInfo& redirect_info,
bool* defer) {
CHECK(state_ == STATE_NONE);
// Save the redirect urls for possible malware detail reporting later.
redirect_urls_.push_back(redirect_info.new_url);
// We need to check the new URL before following the redirect.
SBThreatType threat_type = CheckUrl();
if (threat_type == SB_THREAT_TYPE_SAFE)
return;
if (request_->load_flags() & net::LOAD_PREFETCH) {
controller()->Cancel();
return;
}
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request_);
state_ = STATE_DISPLAYING_BLOCKING_PAGE;
SafeBrowsingUIManager::UnsafeResource unsafe_resource;
unsafe_resource.url = redirect_info.new_url;
unsafe_resource.original_url = request_->original_url();
unsafe_resource.redirect_urls = redirect_urls_;
unsafe_resource.is_subresource = is_subresource_;
unsafe_resource.is_subframe = is_subframe_;
unsafe_resource.threat_type = threat_type;
unsafe_resource.callback = base::Bind(
&DataReductionProxyResourceThrottle::OnBlockingPageComplete, AsWeakPtr());
unsafe_resource.render_process_host_id = info->GetChildID();
unsafe_resource.render_view_id = info->GetRouteID();
unsafe_resource.threat_source = SafeBrowsingUIManager::FROM_DATA_SAVER;
*defer = true;
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(
&DataReductionProxyResourceThrottle::StartDisplayingBlockingPage,
AsWeakPtr(), safe_browsing_->ui_manager(), unsafe_resource));
}
const char* DataReductionProxyResourceThrottle::GetNameForLogging() const {
return "DataReductionProxyResourceThrottle";
}
// static
void DataReductionProxyResourceThrottle::StartDisplayingBlockingPage(
const base::WeakPtr<DataReductionProxyResourceThrottle>& throttle,
scoped_refptr<SafeBrowsingUIManager> ui_manager,
const SafeBrowsingUIManager::UnsafeResource& resource) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
content::RenderViewHost* rvh = content::RenderViewHost::FromID(
resource.render_process_host_id, resource.render_view_id);
if (rvh) {
content::WebContents* web_contents =
content::WebContents::FromRenderViewHost(rvh);
prerender::PrerenderContents* prerender_contents =
prerender::PrerenderContents::FromWebContents(web_contents);
if (prerender_contents) {
prerender_contents->Destroy(prerender::FINAL_STATUS_SAFE_BROWSING);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(resource.callback, false));
return;
}
}
ui_manager->DisplayBlockingPage(resource);
}
// SafeBrowsingService::UrlCheckCallback implementation, called on the IO
// thread when the user has decided to proceed with the current request, or
// go back.
void DataReductionProxyResourceThrottle::OnBlockingPageComplete(bool proceed) {
CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
state_ = STATE_NONE;
if (proceed)
ResumeRequest();
else
controller()->Cancel();
}
SBThreatType DataReductionProxyResourceThrottle::CheckUrl() {
SBThreatType result = SB_THREAT_TYPE_SAFE;
// TODO(sgurun) Check for spdy proxy origin.
if (request_->response_headers() == NULL)
return result;
if (request_->response_headers()->HasHeader("X-Phishing-Url"))
result = SB_THREAT_TYPE_URL_PHISHING;
else if (request_->response_headers()->HasHeader("X-Malware-Url"))
result = SB_THREAT_TYPE_URL_MALWARE;
// If safe browsing is disabled and the request is sent to the DRP server,
// we need to break the redirect loop by setting the extra header.
if (result != SB_THREAT_TYPE_SAFE && !safe_browsing_->enabled()) {
request_->SetExtraRequestHeaderByName(kUnsafeUrlProceedHeader, "1", true);
result = SB_THREAT_TYPE_SAFE;
}
return result;
}
void DataReductionProxyResourceThrottle::ResumeRequest() {
CHECK(state_ == STATE_NONE);
// Inject the header before resuming the request.
request_->SetExtraRequestHeaderByName(kUnsafeUrlProceedHeader, "1", true);
controller()->Resume();
}
<|endoftext|> |
<commit_before>#include "flaggedarrayset.h"
#include <map>
#include <set>
#include <vector>
#include <list>
#include <thread>
#include <mutex>
#include <string.h>
#include <assert.h>
#include <stdio.h>
/******************************
**** FlaggedArraySet util ****
******************************/
struct PtrPair {
std::shared_ptr<std::vector<unsigned char> > elem;
std::shared_ptr<std::vector<unsigned char> > elemHash;
PtrPair(const std::shared_ptr<std::vector<unsigned char> >& elemIn, const std::shared_ptr<std::vector<unsigned char> >& elemHashIn) :
elem(elemIn), elemHash(elemHashIn) {}
};
struct SharedPtrElem {
PtrPair e;
bool operator==(const SharedPtrElem& o) const { return *e.elemHash == *o.e.elemHash; }
bool operator!=(const SharedPtrElem& o) const { return *e.elemHash != *o.e.elemHash; }
bool operator< (const SharedPtrElem& o) const { return *e.elemHash < *o.e.elemHash; }
bool operator<=(const SharedPtrElem& o) const { return *e.elemHash <= *o.e.elemHash; }
bool operator> (const SharedPtrElem& o) const { return *e.elemHash > *o.e.elemHash; }
bool operator>=(const SharedPtrElem& o) const { return *e.elemHash >= *o.e.elemHash; }
SharedPtrElem(const PtrPair& eIn) : e(eIn) {}
};
class Deduper {
private:
std::mutex dedup_mutex;
std::set<FlaggedArraySet*> allArraySets;
std::thread dedup_thread;
public:
Deduper()
: dedup_thread([&]() {
#ifdef PRECISE_BENCH
return;
#endif
while (true) {
if (allArraySets.size() > 1) {
std::list<PtrPair> ptrlist;
{
std::lock_guard<std::mutex> lock(dedup_mutex);
for (FlaggedArraySet* fas : allArraySets) {
if (fas->allowDups)
continue;
if (!fas->mutex.try_lock())
continue;
std::lock_guard<WaitCountMutex> lock(fas->mutex, std::adopt_lock);
for (const auto& e : fas->backingMap) {
if (fas->mutex.wait_count())
break;
assert(e.first.elem);
ptrlist.push_back(PtrPair(e.first.elem, e.first.elemHash));
}
}
}
std::set<SharedPtrElem> txset;
std::map<std::vector<unsigned char>*, PtrPair> duplicateMap;
std::list<PtrPair> deallocList;
for (const auto& ptr : ptrlist) {
assert(ptr.elemHash);
auto res = txset.insert(SharedPtrElem(ptr));
if (!res.second && res.first->e.elem != ptr.elem)
duplicateMap.insert(std::make_pair(&(*ptr.elem), res.first->e));
}
int dedups = 0;
{
std::lock_guard<std::mutex> lock(dedup_mutex);
for (FlaggedArraySet* fas : allArraySets) {
if (fas->allowDups)
continue;
if (!fas->mutex.try_lock())
continue;
std::lock_guard<WaitCountMutex> lock(fas->mutex, std::adopt_lock);
for (auto& e : fas->backingMap) {
if (fas->mutex.wait_count())
break;
assert(e.first.elem);
auto it = duplicateMap.find(&(*e.first.elem));
if (it != duplicateMap.end()) {
assert(*it->second.elem == *e.first.elem);
assert(*it->second.elemHash == *e.first.elemHash);
deallocList.emplace_back(it->second);
const_cast<ElemAndFlag&>(e.first).elem.swap(deallocList.back().elem);
const_cast<ElemAndFlag&>(e.first).elemHash.swap(deallocList.back().elemHash);
dedups++;
}
}
}
}
#ifdef FOR_TEST
if (dedups)
printf("Deduped %d txn\n", dedups);
#endif
}
#ifdef FOR_TEST
std::this_thread::sleep_for(std::chrono::milliseconds(5));
#else
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
#endif
}
})
{}
~Deduper() {
//TODO: close thread
}
void addFAS(FlaggedArraySet* fas) {
std::lock_guard<std::mutex> lock(dedup_mutex);
allArraySets.insert(fas);
}
void removeFAS(FlaggedArraySet* fas) {
std::lock_guard<std::mutex> lock(dedup_mutex);
allArraySets.erase(fas);
}
};
static Deduper* deduper;
FlaggedArraySet::FlaggedArraySet(unsigned int maxSizeIn, bool allowDupsIn) :
maxSize(maxSizeIn), backingMap(maxSize), allowDups(allowDupsIn) {
clear();
if (!deduper)
deduper = new Deduper();
deduper->addFAS(this);
}
FlaggedArraySet::~FlaggedArraySet() {
deduper->removeFAS(this);
}
ElemAndFlag::ElemAndFlag(const std::shared_ptr<std::vector<unsigned char> >& elemIn, bool flagIn, bool allowDupsIn, bool setHash) :
flag(flagIn), allowDups(allowDupsIn), elem(elemIn)
{
if (setHash) {
elemHash = std::make_shared<std::vector<unsigned char> >(32);
double_sha256(&(*elem)[0], &(*elemHash)[0], elem->size());
}
}
ElemAndFlag::ElemAndFlag(const std::vector<unsigned char>::const_iterator& elemBeginIn, const std::vector<unsigned char>::const_iterator& elemEndIn, bool flagIn, bool allowDupsIn) :
flag(flagIn), allowDups(allowDupsIn), elemBegin(elemBeginIn), elemEnd(elemEndIn) {}
bool ElemAndFlag::operator == (const ElemAndFlag& o) const {
if (elem && o.elem) {
if (allowDups)
return o.elem == elem;
bool hashSet = o.elemHash && elemHash;
return o.elem == elem ||
(hashSet && *o.elemHash == *elemHash) ||
(!hashSet && *o.elem == *elem);
} else {
std::vector<unsigned char>::const_iterator o_begin, o_end, e_begin, e_end;
if (elem) {
e_begin = elem->begin();
e_end = elem->end();
} else {
e_begin = elemBegin;
e_end = elemEnd;
}
if (o.elem) {
o_begin = o.elem->begin();
o_end = o.elem->end();
} else {
o_begin = o.elemBegin;
o_end = o.elemEnd;
}
return o_end - o_begin == e_end - e_begin && !memcmp(&(*o_begin), &(*e_begin), o_end - o_begin);
}
}
size_t std::hash<ElemAndFlag>::operator()(const ElemAndFlag& e) const {
std::vector<unsigned char>::const_iterator it, end;
if (e.elem) {
it = e.elem->begin();
end = e.elem->end();
} else {
it = e.elemBegin;
end = e.elemEnd;
}
if (end - it < 5 + 32 + 4) {
assert(0);
return 42; // WAT?
}
it += 5 + 32 + 4 - 8;
size_t res = 0;
static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "Your size_t is neither 32-bit nor 64-bit?");
for (unsigned int i = 0; i < 8; i += sizeof(size_t)) {
for (unsigned int j = 0; j < sizeof(size_t); j++)
res ^= *(it + i + j) << 8*j;
}
return res;
}
bool FlaggedArraySet::sanity_check() const {
size_t size = indexMap.size();
if (backingMap.size() != size) return false;
if (this->size() != size - to_be_removed.size()) return false;
for (uint64_t i = 0; i < size; i++) {
std::unordered_map<ElemAndFlag, uint64_t>::iterator it = indexMap.at(i);
if (it == backingMap.end()) return false;
if (it->second != i + offset) return false;
if (backingMap.find(it->first) != it) return false;
if (&backingMap.find(it->first)->first != &it->first) return false;
}
return true;
}
void FlaggedArraySet::remove_(size_t index) {
auto& rm = indexMap[index];
assert(index < indexMap.size());
if (rm->first.flag)
flag_count--;
size_t size = backingMap.size();
if (index < size/2) {
for (uint64_t i = 0; i < index; i++)
indexMap[i]->second++;
offset++;
} else
for (uint64_t i = index + 1; i < size; i++)
indexMap[i]->second--;
backingMap.erase(rm);
indexMap.erase(indexMap.begin() + index);
}
inline void FlaggedArraySet::cleanup_late_remove() const {
assert(sanity_check());
if (to_be_removed.size()) {
for (unsigned int i = 0; i < to_be_removed.size(); i++) {
assert((unsigned int)to_be_removed[i] < indexMap.size());
const_cast<FlaggedArraySet*>(this)->remove_(to_be_removed[i]);
}
to_be_removed.clear();
max_remove = 0;
}
assert(sanity_check());
}
bool FlaggedArraySet::contains(const std::shared_ptr<std::vector<unsigned char> >& e) const {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
return backingMap.count(ElemAndFlag(e, false, allowDups, false));
}
void FlaggedArraySet::add(const std::shared_ptr<std::vector<unsigned char> >& e, bool flag) {
ElemAndFlag elem(e, flag, allowDups, true);
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
auto res = backingMap.insert(std::make_pair(elem, size() + offset));
if (!res.second)
return;
indexMap.push_back(res.first);
assert(size() <= maxSize + 1);
while (size() > maxSize)
remove_(0);
if (flag)
flag_count++;
assert(sanity_check());
}
int FlaggedArraySet::remove(const std::vector<unsigned char>::const_iterator& start, const std::vector<unsigned char>::const_iterator& end) {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
auto it = backingMap.find(ElemAndFlag(start, end, false, allowDups));
if (it == backingMap.end())
return -1;
int res = it->second - offset;
remove_(res);
assert(sanity_check());
return res;
}
bool FlaggedArraySet::remove(int index, std::shared_ptr<std::vector<unsigned char> >& elem, std::shared_ptr<std::vector<unsigned char> >& elemHash) {
std::lock_guard<WaitCountMutex> lock(mutex);
if (index < max_remove)
cleanup_late_remove();
int lookup_index = index + to_be_removed.size();
if ((unsigned int)lookup_index >= indexMap.size())
return false;
const ElemAndFlag& e = indexMap[lookup_index]->first;
assert(e.elem && e.elemHash);
elem = e.elem;
elemHash = e.elemHash;
if (index >= max_remove) {
to_be_removed.push_back(index);
max_remove = index;
if (e.flag) flags_to_remove++;
} else {
cleanup_late_remove();
remove_(index);
}
assert(sanity_check());
return true;
}
void FlaggedArraySet::clear() {
std::lock_guard<WaitCountMutex> lock(mutex);
flag_count = 0; offset = 0;
flags_to_remove = 0; max_remove = 0;
backingMap.clear(); indexMap.clear(); to_be_removed.clear();
}
void FlaggedArraySet::for_all_txn(const std::function<void (const std::shared_ptr<std::vector<unsigned char> >&)> callback) const {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
for (const auto& e : indexMap) {
assert(e->first.elem);
callback(e->first.elem);
}
}
<commit_msg>Sanity check before clear in FAS<commit_after>#include "flaggedarrayset.h"
#include <map>
#include <set>
#include <vector>
#include <list>
#include <thread>
#include <mutex>
#include <string.h>
#include <assert.h>
#include <stdio.h>
/******************************
**** FlaggedArraySet util ****
******************************/
struct PtrPair {
std::shared_ptr<std::vector<unsigned char> > elem;
std::shared_ptr<std::vector<unsigned char> > elemHash;
PtrPair(const std::shared_ptr<std::vector<unsigned char> >& elemIn, const std::shared_ptr<std::vector<unsigned char> >& elemHashIn) :
elem(elemIn), elemHash(elemHashIn) {}
};
struct SharedPtrElem {
PtrPair e;
bool operator==(const SharedPtrElem& o) const { return *e.elemHash == *o.e.elemHash; }
bool operator!=(const SharedPtrElem& o) const { return *e.elemHash != *o.e.elemHash; }
bool operator< (const SharedPtrElem& o) const { return *e.elemHash < *o.e.elemHash; }
bool operator<=(const SharedPtrElem& o) const { return *e.elemHash <= *o.e.elemHash; }
bool operator> (const SharedPtrElem& o) const { return *e.elemHash > *o.e.elemHash; }
bool operator>=(const SharedPtrElem& o) const { return *e.elemHash >= *o.e.elemHash; }
SharedPtrElem(const PtrPair& eIn) : e(eIn) {}
};
class Deduper {
private:
std::mutex dedup_mutex;
std::set<FlaggedArraySet*> allArraySets;
std::thread dedup_thread;
public:
Deduper()
: dedup_thread([&]() {
#ifdef PRECISE_BENCH
return;
#endif
while (true) {
if (allArraySets.size() > 1) {
std::list<PtrPair> ptrlist;
{
std::lock_guard<std::mutex> lock(dedup_mutex);
for (FlaggedArraySet* fas : allArraySets) {
if (fas->allowDups)
continue;
if (!fas->mutex.try_lock())
continue;
std::lock_guard<WaitCountMutex> lock(fas->mutex, std::adopt_lock);
for (const auto& e : fas->backingMap) {
if (fas->mutex.wait_count())
break;
assert(e.first.elem);
ptrlist.push_back(PtrPair(e.first.elem, e.first.elemHash));
}
}
}
std::set<SharedPtrElem> txset;
std::map<std::vector<unsigned char>*, PtrPair> duplicateMap;
std::list<PtrPair> deallocList;
for (const auto& ptr : ptrlist) {
assert(ptr.elemHash);
auto res = txset.insert(SharedPtrElem(ptr));
if (!res.second && res.first->e.elem != ptr.elem)
duplicateMap.insert(std::make_pair(&(*ptr.elem), res.first->e));
}
int dedups = 0;
{
std::lock_guard<std::mutex> lock(dedup_mutex);
for (FlaggedArraySet* fas : allArraySets) {
if (fas->allowDups)
continue;
if (!fas->mutex.try_lock())
continue;
std::lock_guard<WaitCountMutex> lock(fas->mutex, std::adopt_lock);
for (auto& e : fas->backingMap) {
if (fas->mutex.wait_count())
break;
assert(e.first.elem);
auto it = duplicateMap.find(&(*e.first.elem));
if (it != duplicateMap.end()) {
assert(*it->second.elem == *e.first.elem);
assert(*it->second.elemHash == *e.first.elemHash);
deallocList.emplace_back(it->second);
const_cast<ElemAndFlag&>(e.first).elem.swap(deallocList.back().elem);
const_cast<ElemAndFlag&>(e.first).elemHash.swap(deallocList.back().elemHash);
dedups++;
}
}
}
}
#ifdef FOR_TEST
if (dedups)
printf("Deduped %d txn\n", dedups);
#endif
}
#ifdef FOR_TEST
std::this_thread::sleep_for(std::chrono::milliseconds(5));
#else
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
#endif
}
})
{}
~Deduper() {
//TODO: close thread
}
void addFAS(FlaggedArraySet* fas) {
std::lock_guard<std::mutex> lock(dedup_mutex);
allArraySets.insert(fas);
}
void removeFAS(FlaggedArraySet* fas) {
std::lock_guard<std::mutex> lock(dedup_mutex);
allArraySets.erase(fas);
}
};
static Deduper* deduper;
FlaggedArraySet::FlaggedArraySet(unsigned int maxSizeIn, bool allowDupsIn) :
maxSize(maxSizeIn), backingMap(maxSize), allowDups(allowDupsIn) {
clear();
if (!deduper)
deduper = new Deduper();
deduper->addFAS(this);
}
FlaggedArraySet::~FlaggedArraySet() {
deduper->removeFAS(this);
assert(sanity_check());
}
ElemAndFlag::ElemAndFlag(const std::shared_ptr<std::vector<unsigned char> >& elemIn, bool flagIn, bool allowDupsIn, bool setHash) :
flag(flagIn), allowDups(allowDupsIn), elem(elemIn)
{
if (setHash) {
elemHash = std::make_shared<std::vector<unsigned char> >(32);
double_sha256(&(*elem)[0], &(*elemHash)[0], elem->size());
}
}
ElemAndFlag::ElemAndFlag(const std::vector<unsigned char>::const_iterator& elemBeginIn, const std::vector<unsigned char>::const_iterator& elemEndIn, bool flagIn, bool allowDupsIn) :
flag(flagIn), allowDups(allowDupsIn), elemBegin(elemBeginIn), elemEnd(elemEndIn) {}
bool ElemAndFlag::operator == (const ElemAndFlag& o) const {
if (elem && o.elem) {
if (allowDups)
return o.elem == elem;
bool hashSet = o.elemHash && elemHash;
return o.elem == elem ||
(hashSet && *o.elemHash == *elemHash) ||
(!hashSet && *o.elem == *elem);
} else {
std::vector<unsigned char>::const_iterator o_begin, o_end, e_begin, e_end;
if (elem) {
e_begin = elem->begin();
e_end = elem->end();
} else {
e_begin = elemBegin;
e_end = elemEnd;
}
if (o.elem) {
o_begin = o.elem->begin();
o_end = o.elem->end();
} else {
o_begin = o.elemBegin;
o_end = o.elemEnd;
}
return o_end - o_begin == e_end - e_begin && !memcmp(&(*o_begin), &(*e_begin), o_end - o_begin);
}
}
size_t std::hash<ElemAndFlag>::operator()(const ElemAndFlag& e) const {
std::vector<unsigned char>::const_iterator it, end;
if (e.elem) {
it = e.elem->begin();
end = e.elem->end();
} else {
it = e.elemBegin;
end = e.elemEnd;
}
if (end - it < 5 + 32 + 4) {
assert(0);
return 42; // WAT?
}
it += 5 + 32 + 4 - 8;
size_t res = 0;
static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "Your size_t is neither 32-bit nor 64-bit?");
for (unsigned int i = 0; i < 8; i += sizeof(size_t)) {
for (unsigned int j = 0; j < sizeof(size_t); j++)
res ^= *(it + i + j) << 8*j;
}
return res;
}
bool FlaggedArraySet::sanity_check() const {
size_t size = indexMap.size();
if (backingMap.size() != size) return false;
if (this->size() != size - to_be_removed.size()) return false;
for (uint64_t i = 0; i < size; i++) {
std::unordered_map<ElemAndFlag, uint64_t>::iterator it = indexMap.at(i);
if (it == backingMap.end()) return false;
if (it->second != i + offset) return false;
if (backingMap.find(it->first) != it) return false;
if (&backingMap.find(it->first)->first != &it->first) return false;
}
return true;
}
void FlaggedArraySet::remove_(size_t index) {
auto& rm = indexMap[index];
assert(index < indexMap.size());
if (rm->first.flag)
flag_count--;
size_t size = backingMap.size();
if (index < size/2) {
for (uint64_t i = 0; i < index; i++)
indexMap[i]->second++;
offset++;
} else
for (uint64_t i = index + 1; i < size; i++)
indexMap[i]->second--;
backingMap.erase(rm);
indexMap.erase(indexMap.begin() + index);
}
inline void FlaggedArraySet::cleanup_late_remove() const {
assert(sanity_check());
if (to_be_removed.size()) {
for (unsigned int i = 0; i < to_be_removed.size(); i++) {
assert((unsigned int)to_be_removed[i] < indexMap.size());
const_cast<FlaggedArraySet*>(this)->remove_(to_be_removed[i]);
}
to_be_removed.clear();
max_remove = 0;
}
assert(sanity_check());
}
bool FlaggedArraySet::contains(const std::shared_ptr<std::vector<unsigned char> >& e) const {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
return backingMap.count(ElemAndFlag(e, false, allowDups, false));
}
void FlaggedArraySet::add(const std::shared_ptr<std::vector<unsigned char> >& e, bool flag) {
ElemAndFlag elem(e, flag, allowDups, true);
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
auto res = backingMap.insert(std::make_pair(elem, size() + offset));
if (!res.second)
return;
indexMap.push_back(res.first);
assert(size() <= maxSize + 1);
while (size() > maxSize)
remove_(0);
if (flag)
flag_count++;
assert(sanity_check());
}
int FlaggedArraySet::remove(const std::vector<unsigned char>::const_iterator& start, const std::vector<unsigned char>::const_iterator& end) {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
auto it = backingMap.find(ElemAndFlag(start, end, false, allowDups));
if (it == backingMap.end())
return -1;
int res = it->second - offset;
remove_(res);
assert(sanity_check());
return res;
}
bool FlaggedArraySet::remove(int index, std::shared_ptr<std::vector<unsigned char> >& elem, std::shared_ptr<std::vector<unsigned char> >& elemHash) {
std::lock_guard<WaitCountMutex> lock(mutex);
if (index < max_remove)
cleanup_late_remove();
int lookup_index = index + to_be_removed.size();
if ((unsigned int)lookup_index >= indexMap.size())
return false;
const ElemAndFlag& e = indexMap[lookup_index]->first;
assert(e.elem && e.elemHash);
elem = e.elem;
elemHash = e.elemHash;
if (index >= max_remove) {
to_be_removed.push_back(index);
max_remove = index;
if (e.flag) flags_to_remove++;
} else {
cleanup_late_remove();
remove_(index);
}
assert(sanity_check());
return true;
}
void FlaggedArraySet::clear() {
std::lock_guard<WaitCountMutex> lock(mutex);
assert(sanity_check());
flag_count = 0; offset = 0;
flags_to_remove = 0; max_remove = 0;
backingMap.clear(); indexMap.clear(); to_be_removed.clear();
}
void FlaggedArraySet::for_all_txn(const std::function<void (const std::shared_ptr<std::vector<unsigned char> >&)> callback) const {
std::lock_guard<WaitCountMutex> lock(mutex);
cleanup_late_remove();
for (const auto& e : indexMap) {
assert(e->first.elem);
callback(e->first.elem);
}
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2017-2017 ARM Limited
*
* 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 <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// mbed Includes
#include "mbed_assert.h"
#include "rtos/rtos_idle.h"
#include "platform/mbed_power_mgmt.h"
#include "mbed_critical.h"
// Cordio Includes
#include "ll_init_api.h"
#include "ll_defs.h"
#include "chci_drv.h"
#include "lhci_api.h"
#include "platform_api.h"
#include "platform_ble_api.h"
#include "wsf_assert.h"
#include "wsf_buf.h"
#include "wsf_timer.h"
#include "wsf_trace.h"
// Nordic Includes
#include "nrf.h"
#include "NRFCordioHCIDriver.h"
#include "NRFCordioHCITransportDriver.h"
#ifdef DEBUG
#include <stdio.h>
#include <stdarg.h>
#define DBG_WARN(...) printf(__VA_ARGS__)
#else
#define DBG_WARN(...)
#endif
using namespace ble::vendor::nordic;
using namespace ble::vendor::cordio;
/*! \brief Memory that should be reserved for the stack. */
#define CORDIO_LL_MEMORY_FOOTPRINT 3776UL
/*! \brief Typical implementation revision number (LlRtCfg_t::implRev). */
#define LL_IMPL_REV 0x2303
// Note to implementer: this should be amended if the Cordio stack is updated
// The Nordic-specific baseband configuration
// The BB_ config macros are set in the bb_api.h header file
const BbRtCfg_t NRFCordioHCIDriver::_bb_cfg = {
/*clkPpm*/ 20,
/*rfSetupDelayUsec*/ BB_RF_SETUP_DELAY_US,
/*maxScanPeriodMsec*/ BB_MAX_SCAN_PERIOD_MS,
/*schSetupDelayUsec*/ BB_SCH_SETUP_DELAY_US
};
static const uint16_t maxAdvReports = 16;
static const uint16_t numRxBufs = 8;
#if !defined(NRF52840_XXAA)
static const uint16_t advDataLen = 128;
static const uint16_t connDataLen = 256;
static const uint16_t numTxBufs = 8;
#else
static const uint16_t advDataLen = LL_MAX_ADV_DATA_LEN;
static const uint16_t connDataLen = 512;
static const uint16_t numTxBufs = 16;
#endif
/* +12 for message headroom, + 2 event header, +255 maximum parameter length. */
static const uint16_t maxRptBufSize = 12 + 2 + 255;
/* +12 for message headroom, +4 for header. */
static const uint16_t aclBufSize = 12 + connDataLen + 4 + BB_DATA_PDU_TAILROOM;
const LlRtCfg_t NRFCordioHCIDriver::_ll_cfg = {
/* Device */
/*compId*/ LL_COMP_ID_ARM,
/*implRev*/ LL_IMPL_REV,
/*btVer*/ LL_VER_BT_CORE_SPEC_4_2,
0, // padding
/* Advertiser */
/*maxAdvSets*/ 0, /* Disable extended advertising. */
/*maxAdvReports*/ 4,
/*maxExtAdvDataLen*/ advDataLen,
/*defExtAdvDataFrag*/ 64,
0, // Aux delay
/* Scanner */
/*maxScanReqRcvdEvt*/ 4,
/*maxExtScanDataLen*/ advDataLen,
/* Connection */
/*maxConn*/ 4,
/*numTxBufs*/ numTxBufs,
/*numRxBufs*/ numRxBufs,
/*maxAclLen*/ connDataLen,
/*defTxPwrLvl*/ 0,
/*ceJitterUsec*/ 0,
/* DTM */
/*dtmRxSyncMs*/ 10000,
/* PHY */
/*phy2mSup*/ TRUE,
/*phyCodedSup*/ TRUE,
/*stableModIdxTxSup*/ TRUE,
/*stableModIdxRxSup*/ TRUE
};
extern "C" void TIMER0_IRQHandler(void);
static void idle_hook(void)
{
wsfTimerTicks_t nextExpiration;
bool_t timerRunning;
nextExpiration = WsfTimerNextExpiration(&timerRunning);
if(timerRunning && nextExpiration > 0)
{
// Make sure we hae enough time to go to sleep
if( nextExpiration < 1 /* 10 ms per tick which is long enough to got to sleep */ )
{
// Bail
return;
}
}
// critical section to complete sleep with locked deepsleep
core_util_critical_section_enter();
sleep_manager_lock_deep_sleep();
sleep();
sleep_manager_unlock_deep_sleep();
core_util_critical_section_exit();
}
NRFCordioHCIDriver::NRFCordioHCIDriver(CordioHCITransportDriver& transport_driver) : cordio::CordioHCIDriver(transport_driver), _is_init(false), _stack_buffer(NULL)
{
_stack_buffer = (uint8_t*)malloc(CORDIO_LL_MEMORY_FOOTPRINT);
MBED_ASSERT(_stack_buffer != NULL);
}
NRFCordioHCIDriver::~NRFCordioHCIDriver()
{
// Deativate all interrupts
NVIC_DisableIRQ(RADIO_IRQn);
NVIC_DisableIRQ(TIMER0_IRQn);
// Switch off Radio peripheral
// TODO interop with 802.15.4
NRF_RADIO->POWER = 0;
// Stop timer
NRF_TIMER0->TASKS_STOP = 1;
NRF_TIMER0->TASKS_CLEAR = 1;
NVIC_ClearPendingIRQ(RADIO_IRQn);
NVIC_ClearPendingIRQ(TIMER0_IRQn);
MBED_ASSERT(_stack_buffer != NULL);
free(_stack_buffer);
_stack_buffer = NULL;
// Restore RTOS idle thread
rtos_attach_idle_hook(NULL);
MBED_ASSERT(_stack_buffer == NULL);
}
ble::vendor::cordio::buf_pool_desc_t NRFCordioHCIDriver::get_buffer_pool_description()
{
static union {
uint8_t buffer[ 8920 ];
uint64_t align;
};
static const wsfBufPoolDesc_t pool_desc[] = {
{ 16, 16 + 8},
{ 32, 16 + 4 },
{ 64, 8 },
{ 128, 4 + maxAdvReports },
{ aclBufSize, numTxBufs + numRxBufs },
{ 272, 1 }
};
return buf_pool_desc_t(buffer, pool_desc);
}
void NRFCordioHCIDriver::do_initialize()
{
if(_is_init) {
return;
}
_is_init = true;
// Setup BB & LL config
LlInitRtCfg_t ll_init_cfg =
{
.pBbRtCfg = &_bb_cfg,
.wlSizeCfg = 4,
.rlSizeCfg = 4,
.plSizeCfg = 4,
.pLlRtCfg = &_ll_cfg,
.pFreeMem = _stack_buffer,
.freeMemAvail = CORDIO_LL_MEMORY_FOOTPRINT
};
// Override RTOS idle thread
rtos_attach_idle_hook(idle_hook);
/* switch to more accurate 16 MHz crystal oscillator (system starts up using 16MHz RC oscillator) */
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0)
{
}
/* configure low-frequency clock */
NRF_CLOCK->LFCLKSRC = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
NRF_CLOCK->TASKS_LFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0)
{
}
NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
// Start RTC0
NRF_RTC0->TASKS_STOP = 1;
NRF_RTC0->TASKS_CLEAR = 1;
NRF_RTC0->PRESCALER = 0; /* clear prescaler */
NRF_RTC0->TASKS_START = 1;
// Cycle radio peripheral power to guarantee known radio state
NRF_RADIO->POWER = 0;
NRF_RADIO->POWER = 1;
// For some reason, the mbed target uses this (TIMER0_IRQHandler_v) vector name instead of the "standard" TIMER0_IRQHandler one
NVIC_SetVector(TIMER0_IRQn, (uint32_t)TIMER0_IRQHandler);
// Extremely ugly
for(uint32_t irqn = 0; irqn < 32; irqn++)
{
uint8_t prio = NVIC_GetPriority((IRQn_Type)irqn);
if( prio < 2 ) {
NVIC_SetPriority((IRQn_Type)irqn, 2);
}
}
// WARNING
// If a submodule does not have enough space to allocate its memory from buffer, it will still allocate its memory (and do a buffer overflow) and return 0 (as in 0 byte used)
// however that method will still continue which will lead to undefined behaviour
// So whenever a change of configuration is done, it's a good idea to set CORDIO_LL_MEMORY_FOOTPRINT to a high value and then reduce accordingly
uint32_t mem_used = LlInitControllerInit(&ll_init_cfg);
if( mem_used < CORDIO_LL_MEMORY_FOOTPRINT )
{
// Sub-optimal, give warning
DBG_WARN("NRFCordioHCIDriver: CORDIO_LL_MEMORY_FOOTPRINT can be reduced to %lu instead of %lu", mem_used, CORDIO_LL_MEMORY_FOOTPRINT);
}
// BD Addr
bdAddr_t bd_addr;
PlatformLoadBdAddress(bd_addr);
LlSetBdAddr((uint8_t *)&bd_addr);
LlMathSetSeed((uint32_t *)&bd_addr);
//#ifdef DEBUG
// WsfTraceRegister(wsf_trace_handler);
//#endif
// We're sharing the host stack's event queue
}
void NRFCordioHCIDriver::do_terminate()
{
}
ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
static NRFCordioHCITransportDriver transport_driver;
static NRFCordioHCIDriver hci_driver(
transport_driver
);
return hci_driver;
}
// Do not handle any vendor specific command
extern "C" bool_t lhciCommonVsStdDecodeCmdPkt(LhciHdr_t *pHdr, uint8_t *pBuf)
{
return false;
}
// Nordic implementation
void PlatformLoadBdAddress(uint8_t *pDevAddr)
{
unsigned int devAddrLen = 6;
/* Load address from nRF configuration. */
uint64_t devAddr = (((uint64_t)NRF_FICR->DEVICEID[0]) << 0) |
(((uint64_t)NRF_FICR->DEVICEID[1]) << 32);
unsigned int i = 0;
while (i < devAddrLen)
{
pDevAddr[i] = devAddr >> (i * 8);
i++;
}
pDevAddr[5] |= 0xC0; /* cf. "Static Address" (Vol C, Part 3, section 10.8.1) */
}
<commit_msg>Fix buffer size for NRF Cordio HCI driver<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2017-2017 ARM Limited
*
* 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 <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// mbed Includes
#include "mbed_assert.h"
#include "rtos/rtos_idle.h"
#include "platform/mbed_power_mgmt.h"
#include "mbed_critical.h"
// Cordio Includes
#include "ll_init_api.h"
#include "ll_defs.h"
#include "chci_drv.h"
#include "lhci_api.h"
#include "platform_api.h"
#include "platform_ble_api.h"
#include "wsf_assert.h"
#include "wsf_buf.h"
#include "wsf_timer.h"
#include "wsf_trace.h"
// Nordic Includes
#include "nrf.h"
#include "NRFCordioHCIDriver.h"
#include "NRFCordioHCITransportDriver.h"
#ifdef DEBUG
#include <stdio.h>
#include <stdarg.h>
#define DBG_WARN(...) printf(__VA_ARGS__)
#else
#define DBG_WARN(...)
#endif
using namespace ble::vendor::nordic;
using namespace ble::vendor::cordio;
/*! \brief Memory that should be reserved for the stack. */
#define CORDIO_LL_MEMORY_FOOTPRINT 3776UL
/*! \brief Typical implementation revision number (LlRtCfg_t::implRev). */
#define LL_IMPL_REV 0x2303
// Note to implementer: this should be amended if the Cordio stack is updated
// The Nordic-specific baseband configuration
// The BB_ config macros are set in the bb_api.h header file
const BbRtCfg_t NRFCordioHCIDriver::_bb_cfg = {
/*clkPpm*/ 20,
/*rfSetupDelayUsec*/ BB_RF_SETUP_DELAY_US,
/*maxScanPeriodMsec*/ BB_MAX_SCAN_PERIOD_MS,
/*schSetupDelayUsec*/ BB_SCH_SETUP_DELAY_US
};
static const uint16_t maxAdvReports = 16;
static const uint16_t numRxBufs = 8;
#if !defined(NRF52840_XXAA)
static const uint16_t advDataLen = 128;
static const uint16_t connDataLen = 256;
static const uint16_t numTxBufs = 8;
#else
static const uint16_t advDataLen = LL_MAX_ADV_DATA_LEN;
static const uint16_t connDataLen = 512;
static const uint16_t numTxBufs = 16;
#endif
/* +12 for message headroom, + 2 event header, +255 maximum parameter length. */
static const uint16_t maxRptBufSize = 12 + 2 + 255;
/* +12 for message headroom, +4 for header. */
static const uint16_t aclBufSize = 12 + connDataLen + 4 + BB_DATA_PDU_TAILROOM;
const LlRtCfg_t NRFCordioHCIDriver::_ll_cfg = {
/* Device */
/*compId*/ LL_COMP_ID_ARM,
/*implRev*/ LL_IMPL_REV,
/*btVer*/ LL_VER_BT_CORE_SPEC_4_2,
0, // padding
/* Advertiser */
/*maxAdvSets*/ 0, /* Disable extended advertising. */
/*maxAdvReports*/ 4,
/*maxExtAdvDataLen*/ advDataLen,
/*defExtAdvDataFrag*/ 64,
0, // Aux delay
/* Scanner */
/*maxScanReqRcvdEvt*/ 4,
/*maxExtScanDataLen*/ advDataLen,
/* Connection */
/*maxConn*/ 4,
/*numTxBufs*/ numTxBufs,
/*numRxBufs*/ numRxBufs,
/*maxAclLen*/ connDataLen,
/*defTxPwrLvl*/ 0,
/*ceJitterUsec*/ 0,
/* DTM */
/*dtmRxSyncMs*/ 10000,
/* PHY */
/*phy2mSup*/ TRUE,
/*phyCodedSup*/ TRUE,
/*stableModIdxTxSup*/ TRUE,
/*stableModIdxRxSup*/ TRUE
};
extern "C" void TIMER0_IRQHandler(void);
static void idle_hook(void)
{
wsfTimerTicks_t nextExpiration;
bool_t timerRunning;
nextExpiration = WsfTimerNextExpiration(&timerRunning);
if(timerRunning && nextExpiration > 0)
{
// Make sure we hae enough time to go to sleep
if( nextExpiration < 1 /* 10 ms per tick which is long enough to got to sleep */ )
{
// Bail
return;
}
}
// critical section to complete sleep with locked deepsleep
core_util_critical_section_enter();
sleep_manager_lock_deep_sleep();
sleep();
sleep_manager_unlock_deep_sleep();
core_util_critical_section_exit();
}
NRFCordioHCIDriver::NRFCordioHCIDriver(CordioHCITransportDriver& transport_driver) : cordio::CordioHCIDriver(transport_driver), _is_init(false), _stack_buffer(NULL)
{
_stack_buffer = (uint8_t*)malloc(CORDIO_LL_MEMORY_FOOTPRINT);
MBED_ASSERT(_stack_buffer != NULL);
}
NRFCordioHCIDriver::~NRFCordioHCIDriver()
{
// Deativate all interrupts
NVIC_DisableIRQ(RADIO_IRQn);
NVIC_DisableIRQ(TIMER0_IRQn);
// Switch off Radio peripheral
// TODO interop with 802.15.4
NRF_RADIO->POWER = 0;
// Stop timer
NRF_TIMER0->TASKS_STOP = 1;
NRF_TIMER0->TASKS_CLEAR = 1;
NVIC_ClearPendingIRQ(RADIO_IRQn);
NVIC_ClearPendingIRQ(TIMER0_IRQn);
MBED_ASSERT(_stack_buffer != NULL);
free(_stack_buffer);
_stack_buffer = NULL;
// Restore RTOS idle thread
rtos_attach_idle_hook(NULL);
MBED_ASSERT(_stack_buffer == NULL);
}
ble::vendor::cordio::buf_pool_desc_t NRFCordioHCIDriver::get_buffer_pool_description()
{
static union {
uint8_t buffer[ 17304 ];
uint64_t align;
};
static const wsfBufPoolDesc_t pool_desc[] = {
{ 16, 16 + 8},
{ 32, 16 + 4 },
{ 64, 8 },
{ 128, 4 + maxAdvReports },
{ aclBufSize, numTxBufs + numRxBufs },
{ 272, 1 }
};
return buf_pool_desc_t(buffer, pool_desc);
}
void NRFCordioHCIDriver::do_initialize()
{
if(_is_init) {
return;
}
_is_init = true;
// Setup BB & LL config
LlInitRtCfg_t ll_init_cfg =
{
.pBbRtCfg = &_bb_cfg,
.wlSizeCfg = 4,
.rlSizeCfg = 4,
.plSizeCfg = 4,
.pLlRtCfg = &_ll_cfg,
.pFreeMem = _stack_buffer,
.freeMemAvail = CORDIO_LL_MEMORY_FOOTPRINT
};
// Override RTOS idle thread
rtos_attach_idle_hook(idle_hook);
/* switch to more accurate 16 MHz crystal oscillator (system starts up using 16MHz RC oscillator) */
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0)
{
}
/* configure low-frequency clock */
NRF_CLOCK->LFCLKSRC = (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos);
NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
NRF_CLOCK->TASKS_LFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0)
{
}
NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
// Start RTC0
NRF_RTC0->TASKS_STOP = 1;
NRF_RTC0->TASKS_CLEAR = 1;
NRF_RTC0->PRESCALER = 0; /* clear prescaler */
NRF_RTC0->TASKS_START = 1;
// Cycle radio peripheral power to guarantee known radio state
NRF_RADIO->POWER = 0;
NRF_RADIO->POWER = 1;
// For some reason, the mbed target uses this (TIMER0_IRQHandler_v) vector name instead of the "standard" TIMER0_IRQHandler one
NVIC_SetVector(TIMER0_IRQn, (uint32_t)TIMER0_IRQHandler);
// Extremely ugly
for(uint32_t irqn = 0; irqn < 32; irqn++)
{
uint8_t prio = NVIC_GetPriority((IRQn_Type)irqn);
if( prio < 2 ) {
NVIC_SetPriority((IRQn_Type)irqn, 2);
}
}
// WARNING
// If a submodule does not have enough space to allocate its memory from buffer, it will still allocate its memory (and do a buffer overflow) and return 0 (as in 0 byte used)
// however that method will still continue which will lead to undefined behaviour
// So whenever a change of configuration is done, it's a good idea to set CORDIO_LL_MEMORY_FOOTPRINT to a high value and then reduce accordingly
uint32_t mem_used = LlInitControllerInit(&ll_init_cfg);
if( mem_used < CORDIO_LL_MEMORY_FOOTPRINT )
{
// Sub-optimal, give warning
DBG_WARN("NRFCordioHCIDriver: CORDIO_LL_MEMORY_FOOTPRINT can be reduced to %lu instead of %lu", mem_used, CORDIO_LL_MEMORY_FOOTPRINT);
}
// BD Addr
bdAddr_t bd_addr;
PlatformLoadBdAddress(bd_addr);
LlSetBdAddr((uint8_t *)&bd_addr);
LlMathSetSeed((uint32_t *)&bd_addr);
//#ifdef DEBUG
// WsfTraceRegister(wsf_trace_handler);
//#endif
// We're sharing the host stack's event queue
}
void NRFCordioHCIDriver::do_terminate()
{
}
ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() {
static NRFCordioHCITransportDriver transport_driver;
static NRFCordioHCIDriver hci_driver(
transport_driver
);
return hci_driver;
}
// Do not handle any vendor specific command
extern "C" bool_t lhciCommonVsStdDecodeCmdPkt(LhciHdr_t *pHdr, uint8_t *pBuf)
{
return false;
}
// Nordic implementation
void PlatformLoadBdAddress(uint8_t *pDevAddr)
{
unsigned int devAddrLen = 6;
/* Load address from nRF configuration. */
uint64_t devAddr = (((uint64_t)NRF_FICR->DEVICEID[0]) << 0) |
(((uint64_t)NRF_FICR->DEVICEID[1]) << 32);
unsigned int i = 0;
while (i < devAddrLen)
{
pDevAddr[i] = devAddr >> (i * 8);
i++;
}
pDevAddr[5] |= 0xC0; /* cf. "Static Address" (Vol C, Part 3, section 10.8.1) */
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/appcache/appcache_backend_impl.h"
#include "base/stl_util-inl.h"
#include "webkit/appcache/appcache.h"
#include "webkit/appcache/appcache_group.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
namespace appcache {
AppCacheBackendImpl::~AppCacheBackendImpl() {
STLDeleteValues(&hosts_);
if (service_)
service_->UnregisterBackend(this);
}
void AppCacheBackendImpl::Initialize(AppCacheService* service,
AppCacheFrontend* frontend,
int process_id) {
DCHECK(!service_ && !frontend_ && frontend && service);
service_ = service;
frontend_ = frontend;
process_id_ = process_id;
service_->RegisterBackend(this);
}
bool AppCacheBackendImpl::RegisterHost(int id) {
if (GetHost(id))
return false;
hosts_.insert(
HostMap::value_type(id, new AppCacheHost(id, frontend_, service_)));
return true;
}
bool AppCacheBackendImpl::UnregisterHost(int id) {
HostMap::iterator found = hosts_.find(id);
if (found == hosts_.end())
return false;
delete found->second;
hosts_.erase(found);
return true;
}
bool AppCacheBackendImpl::SelectCache(
int host_id,
const GURL& document_url,
const int64 cache_document_was_loaded_from,
const GURL& manifest_url) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->SelectCache(document_url, cache_document_was_loaded_from,
manifest_url);
return true;
}
bool AppCacheBackendImpl::MarkAsForeignEntry(
int host_id,
const GURL& document_url,
int64 cache_document_was_loaded_from) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from);
return true;
}
bool AppCacheBackendImpl::GetStatusWithCallback(
int host_id, GetStatusCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->GetStatusWithCallback(callback, callback_param);
return true;
}
bool AppCacheBackendImpl::StartUpdateWithCallback(
int host_id, StartUpdateCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->StartUpdateWithCallback(callback, callback_param);
return true;
}
bool AppCacheBackendImpl::SwapCacheWithCallback(
int host_id, SwapCacheCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->SwapCacheWithCallback(callback, callback_param);
return true;
}
} // namespace appcache
<commit_msg>(More) Copyright housecleaning (i missed one before).<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/appcache/appcache_backend_impl.h"
#include "base/stl_util-inl.h"
#include "webkit/appcache/appcache.h"
#include "webkit/appcache/appcache_group.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
namespace appcache {
AppCacheBackendImpl::~AppCacheBackendImpl() {
STLDeleteValues(&hosts_);
if (service_)
service_->UnregisterBackend(this);
}
void AppCacheBackendImpl::Initialize(AppCacheService* service,
AppCacheFrontend* frontend,
int process_id) {
DCHECK(!service_ && !frontend_ && frontend && service);
service_ = service;
frontend_ = frontend;
process_id_ = process_id;
service_->RegisterBackend(this);
}
bool AppCacheBackendImpl::RegisterHost(int id) {
if (GetHost(id))
return false;
hosts_.insert(
HostMap::value_type(id, new AppCacheHost(id, frontend_, service_)));
return true;
}
bool AppCacheBackendImpl::UnregisterHost(int id) {
HostMap::iterator found = hosts_.find(id);
if (found == hosts_.end())
return false;
delete found->second;
hosts_.erase(found);
return true;
}
bool AppCacheBackendImpl::SelectCache(
int host_id,
const GURL& document_url,
const int64 cache_document_was_loaded_from,
const GURL& manifest_url) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->SelectCache(document_url, cache_document_was_loaded_from,
manifest_url);
return true;
}
bool AppCacheBackendImpl::MarkAsForeignEntry(
int host_id,
const GURL& document_url,
int64 cache_document_was_loaded_from) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from);
return true;
}
bool AppCacheBackendImpl::GetStatusWithCallback(
int host_id, GetStatusCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->GetStatusWithCallback(callback, callback_param);
return true;
}
bool AppCacheBackendImpl::StartUpdateWithCallback(
int host_id, StartUpdateCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->StartUpdateWithCallback(callback, callback_param);
return true;
}
bool AppCacheBackendImpl::SwapCacheWithCallback(
int host_id, SwapCacheCallback* callback, void* callback_param) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->SwapCacheWithCallback(callback, callback_param);
return true;
}
} // namespace appcache
<|endoftext|> |
<commit_before>#define __STDC_FORMAT_MACROS
#include "parser.h"
#include "pageTags.h"
#include "util/exception.h"
#include "util/minmax.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <limits.h>
#define STREQ(src, literal) (strncmp(src, literal, strlen(literal)) == 0)
#define WH ".wowhead.com/"
#define WW ".wowwiki.com/"
#define FLUSH flush(ptr)
void Parser::flush(const char* end) {
int len = end - mNodeStart;
EASSERT(len >= 0);
if(len > 0) {
addTextNode(mNodeStart, len);
mNodeStart = end;
}
}
void Parser::parse(const char* src) {
const char* ptr = src;
mNodeStart = ptr;
mbtowc(NULL, NULL, 0); // reset shift state.
while(*ptr) {
// skip invalid utf-8 sequences.
wchar_t w;
int res = mbtowc(&w, ptr, MB_LEN_MAX);
if(res <= 0) {
if(res < 0) {
printf("Invalid UTF-8 0x%x @ pos %" PRIuPTR "\n", (unsigned char)*ptr, ptr - src);
}
FLUSH;
ptr++;
mNodeStart = ptr;
continue;
} else if(res > 1) { // valid utf-8 beyond ascii
ptr += res;
continue;
}
if(STREQ(ptr, "http://")) { // unescaped link
FLUSH;
ptr = parseUnescapedUrl(ptr);
mNodeStart = ptr;
continue;
}
char c = *ptr;
ptr++;
if(c == '[') { // start tag
while(*ptr == '[') {
ptr++;
}
const char* endPtr = strchr(ptr, ']');
if(!endPtr) {
break;
}
flush(ptr-1);
mNodeStart = ptr;
parseTag(ptr, endPtr - ptr);
ptr = endPtr + 1;
mNodeStart = ptr;
} else if(c == '\\' && *ptr == 'n') {
flush(ptr-1);
ptr++;
mNodeStart = ptr;
addLinebreakNode();
}
}
FLUSH;
}
template<class Map>
bool Parser::pageTag(const char* type, size_t typeLen, const char* tag, size_t tagLen,
Map& map)
{
if(strncmp(type, tag, typeLen) != 0)
return false;
//printf("%*s tag: %.*s\n", (int)(typeLen-1), type, (int)tagLen, tag);
const char* idString = tag + typeLen;
size_t idLen = tagLen - typeLen;
const char* space = (char*)memchr(idString, ' ', idLen);
if(space)
idLen = space - idString;
map.load();
addPageNode(map, type, idString, idLen);
return true;
}
enum CompRes {
crMatch,
crMismatch,
crIgnore,
};
static CompRes compareTag(const char* t, size_t tLen, const char* tag, size_t tagLen,
bool& hasAttributes)
{
bool match = strncmp(t, tag, tLen) == 0 &&
(tagLen == tLen || (hasAttributes = isspace(tag[tLen])));
if(!match)
return crMismatch;
return crMatch;
}
// intentional fallthrough
#define COMPARE_TAG(t, matchAction) { CompRes cr = compareTag(t, strlen(t), tag, len, hasAttributes);\
switch(cr) {\
case crIgnore: printf("Ignored tag: %s\n", t); return;\
case crMatch: matchAction\
case crMismatch: break;\
} }
#define COMPLEX_TAG(t, type, dst, end) COMPARE_TAG(t, addTagNode(type, tag, len, strlen(t), dst, end); return;)
#define END_TAG(t) COMPARE_TAG(t, addEndTag(t); return;)
#define SIMPLE_TAG(t, type) COMPLEX_TAG(t, type, t, "/" t); END_TAG("/" t)
#define C_TAG(t, type, dst, end) COMPLEX_TAG(t, type, dst, end); END_TAG("/" t)
#define FORMATTING_TAG(t, type) COMPARE_TAG(t, addFormattingTag(tag, len, strlen(t), type); return;); END_TAG("/" t)
#define SPECIAL_TAG(t, addFunc) COMPARE_TAG(t, addFunc; return;); END_TAG("/" t)
void Parser::parseTag(const char* tag, size_t len) {
bool hasAttributes;
//printf("tag: %i %.*s\n", tagState, (int)len, tag);
FORMATTING_TAG("b", BOLD);
FORMATTING_TAG("i", ITALIC);
FORMATTING_TAG("small", SMALL);
FORMATTING_TAG("s", SMALL);
FORMATTING_TAG("u", UNDERLINED);
SIMPLE_TAG("table", TABLE);
SIMPLE_TAG("tr", NO_TYPE);
SIMPLE_TAG("td", NO_TYPE);
//SIMPLE_TAG("li", LIST_ITEM);
SPECIAL_TAG("li", addListItem());
SPECIAL_TAG("code", addCodeTag());
SPECIAL_TAG("quote", addQuoteTag());
SIMPLE_TAG("ul", LIST);
SIMPLE_TAG("ol", LIST);
if(!strncmp("url=", tag, 4) || !strncmp("url:", tag, 4) || !strncmp("url ", tag, 4)) {
//printf("url tag: %i %.*s\n", tagState, (int)len, tag);
const char* url = tag + 4;
size_t urlLen = len - 4;
parseUrl(url, urlLen);
return;
}
C_TAG("url", ANCHOR, "a", "/a");
if(strncmp("color=", tag, 6) == 0) {
const char* idString = tag + 6;
size_t idLen = len - 6;
addColorTag(idString, idLen);
return;
}
END_TAG("/color");
// todo: code, quote
#define PAGE_TAG(name, map) if(pageTag(name "=", sizeof(name), tag, len, map)) return;
PAGE_TAGS(PAGE_TAG);
// Unknown tag.
// Assume it is intended to be printed as plain text, with its brackets[].
printf("unknown tag: %.*s\n", (int)len, tag);
mNodeStart = tag-1;
flush(tag+len+1);
}
#ifdef WIN32
#include <algorithm>
static const char* memmem(const char* a, size_t alen, const char* b, size_t blen) {
const char* res = std::search(a, a+alen, b, b+blen);
if(res >= a+alen)
return NULL;
return res;
}
#endif
static bool isUrlChar(char c) {
//gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
//sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
return isalnum(c) || c == '_' || c == '#' || c == '?' || c == '/' || c == '-' ||
c == '=' || c == '.' || c == ':' || c == '&' || c == '(' || c == ')' ||
c == '%';
}
static bool isWowheadNonUrlChar(char c) {
return c == '/' || c == '?' || c == '.' || c == '-' || c == '&' || ((unsigned int)c) > 127;
}
void Parser::parseUrl(const char* url, size_t len) {
// skip starting whitespace
while(isspace(*url)) {
len--;
url++;
}
// skip broken '['
if(*url == '[') {
url++;
len--;
}
// check for start-quote mark.
if(*url == '"') {
url++;
len--;
}
// check for whitespace.
// skip whitespace and any data afterwards.
const char* ptr = url;
const char* end = url + len;
while(ptr < end) {
// also check for end-quote mark and the invalid start-tag marker.
if(isspace(*ptr) || *ptr == '"' || *ptr == '[')
break;
ptr++;
}
len = ptr - url;
// s/http://*.wowhead.com/
const char* whf = (char*)memmem(url, len, WH, strlen(WH));
if(whf) {
const char* path = whf + strlen(WH);
if(*path == '?')
path += 1;
size_t pathLen = len - (path - url);
// cut off broken parts
const char* c = path;
while(c < (path + pathLen)) {
if(isWowheadNonUrlChar(*c))
break;
c++;
}
pathLen = c - path;
addWowfootUrlNode(path, pathLen);
return;
}
// s/http://*.wowwiki.com/
//printf("URL test: %*s\n", (int)len, url);
const char* wwf = (char*)memmem(url, len, WW, strlen(WW));
if(wwf) {
const char* path = wwf + strlen(WW);
size_t pathLen = len - (path - url);
addWowpediaUrlNode(path, pathLen);
return;
}
// old-style wowhead paths.
if(strncmp(url, "/?", 2) == 0) {
url += 2;
len -= 2;
}
addUrlNode(url, len);
}
// returns new ptr.
const char* Parser::parseUnescapedUrl(const char* ptr) {
const char* domain = ptr + 7;
const char* slash = strchr(domain, '/');
if(!slash)
return domain;
const char* path = slash + 1;
// we can assume wowhead urls never have slashes '/',
// or '?', except as the first character in the path.
const char* subdomain = slash - (strlen(WH) - 1);
//printf("sd: %s\n", subdomain);
bool isWowhead = STREQ(subdomain, WH);
if(isWowhead && *path == '?')
path++;
const char* end = path;
while(isUrlChar(*end)) {
if(isWowhead && isWowheadNonUrlChar(*end))
break;
end++;
}
size_t pathLen = end - path;
size_t urlLen = end - ptr;
//printf("uu: %i %.*s\n", isWowhead, urlLen, ptr);
size_t len;
if(isWowhead) {
// write name of linked entity (item, object, spell, quest, et. al)
// use PAGE_TAG code
#define UE_TAG(name, map) if(pageTag(name "=", sizeof(name), path, pathLen, map)) return end;
PAGE_TAGS(UE_TAG);
len = pathLen;
} else {
len = urlLen;
}
// wowwiki->wowpedia
const char* wwf = (char*)memmem(ptr, urlLen, WW, strlen(WW));
if(wwf) {
addWowpediaUrlNode(path, pathLen);
addStaticTextNode("http://www.wowpedia.org/");
addTextNode(path, pathLen);
addUrlEndNode();
return end;
}
if(!isWowhead)
path = ptr;
addUrlNode(path, len);
addTextNode(path, len);
addUrlEndNode();
return end;
}
<commit_msg>comments: find end of unescaped URL before searching through it.<commit_after>#define __STDC_FORMAT_MACROS
#include "parser.h"
#include "pageTags.h"
#include "util/exception.h"
#include "util/minmax.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <limits.h>
#define STREQ(src, literal) (strncmp(src, literal, strlen(literal)) == 0)
#define WH ".wowhead.com/"
#define WW ".wowwiki.com/"
#define FLUSH flush(ptr)
void Parser::flush(const char* end) {
int len = end - mNodeStart;
EASSERT(len >= 0);
if(len > 0) {
addTextNode(mNodeStart, len);
mNodeStart = end;
}
}
void Parser::parse(const char* src) {
const char* ptr = src;
mNodeStart = ptr;
mbtowc(NULL, NULL, 0); // reset shift state.
while(*ptr) {
// skip invalid utf-8 sequences.
wchar_t w;
int res = mbtowc(&w, ptr, MB_LEN_MAX);
if(res <= 0) {
if(res < 0) {
printf("Invalid UTF-8 0x%x @ pos %" PRIuPTR "\n", (unsigned char)*ptr, ptr - src);
}
FLUSH;
ptr++;
mNodeStart = ptr;
continue;
} else if(res > 1) { // valid utf-8 beyond ascii
ptr += res;
continue;
}
if(STREQ(ptr, "http://")) { // unescaped link
FLUSH;
ptr = parseUnescapedUrl(ptr);
mNodeStart = ptr;
continue;
}
char c = *ptr;
ptr++;
if(c == '[') { // start tag
while(*ptr == '[') {
ptr++;
}
const char* endPtr = strchr(ptr, ']');
if(!endPtr) {
break;
}
flush(ptr-1);
mNodeStart = ptr;
parseTag(ptr, endPtr - ptr);
ptr = endPtr + 1;
mNodeStart = ptr;
} else if(c == '\\' && *ptr == 'n') {
flush(ptr-1);
ptr++;
mNodeStart = ptr;
addLinebreakNode();
}
}
FLUSH;
}
template<class Map>
bool Parser::pageTag(const char* type, size_t typeLen, const char* tag, size_t tagLen,
Map& map)
{
if(strncmp(type, tag, typeLen) != 0)
return false;
//printf("%*s tag: %.*s\n", (int)(typeLen-1), type, (int)tagLen, tag);
const char* idString = tag + typeLen;
size_t idLen = tagLen - typeLen;
const char* space = (char*)memchr(idString, ' ', idLen);
if(space)
idLen = space - idString;
map.load();
addPageNode(map, type, idString, idLen);
return true;
}
enum CompRes {
crMatch,
crMismatch,
crIgnore,
};
static CompRes compareTag(const char* t, size_t tLen, const char* tag, size_t tagLen,
bool& hasAttributes)
{
bool match = strncmp(t, tag, tLen) == 0 &&
(tagLen == tLen || (hasAttributes = isspace(tag[tLen])));
if(!match)
return crMismatch;
return crMatch;
}
// intentional fallthrough
#define COMPARE_TAG(t, matchAction) { CompRes cr = compareTag(t, strlen(t), tag, len, hasAttributes);\
switch(cr) {\
case crIgnore: printf("Ignored tag: %s\n", t); return;\
case crMatch: matchAction\
case crMismatch: break;\
} }
#define COMPLEX_TAG(t, type, dst, end) COMPARE_TAG(t, addTagNode(type, tag, len, strlen(t), dst, end); return;)
#define END_TAG(t) COMPARE_TAG(t, addEndTag(t); return;)
#define SIMPLE_TAG(t, type) COMPLEX_TAG(t, type, t, "/" t); END_TAG("/" t)
#define C_TAG(t, type, dst, end) COMPLEX_TAG(t, type, dst, end); END_TAG("/" t)
#define FORMATTING_TAG(t, type) COMPARE_TAG(t, addFormattingTag(tag, len, strlen(t), type); return;); END_TAG("/" t)
#define SPECIAL_TAG(t, addFunc) COMPARE_TAG(t, addFunc; return;); END_TAG("/" t)
void Parser::parseTag(const char* tag, size_t len) {
bool hasAttributes;
//printf("tag: %i %.*s\n", tagState, (int)len, tag);
FORMATTING_TAG("b", BOLD);
FORMATTING_TAG("i", ITALIC);
FORMATTING_TAG("small", SMALL);
FORMATTING_TAG("s", SMALL);
FORMATTING_TAG("u", UNDERLINED);
SIMPLE_TAG("table", TABLE);
SIMPLE_TAG("tr", NO_TYPE);
SIMPLE_TAG("td", NO_TYPE);
//SIMPLE_TAG("li", LIST_ITEM);
SPECIAL_TAG("li", addListItem());
SPECIAL_TAG("code", addCodeTag());
SPECIAL_TAG("quote", addQuoteTag());
SIMPLE_TAG("ul", LIST);
SIMPLE_TAG("ol", LIST);
if(!strncmp("url=", tag, 4) || !strncmp("url:", tag, 4) || !strncmp("url ", tag, 4)) {
//printf("url tag: %i %.*s\n", tagState, (int)len, tag);
const char* url = tag + 4;
size_t urlLen = len - 4;
parseUrl(url, urlLen);
return;
}
C_TAG("url", ANCHOR, "a", "/a");
if(strncmp("color=", tag, 6) == 0) {
const char* idString = tag + 6;
size_t idLen = len - 6;
addColorTag(idString, idLen);
return;
}
END_TAG("/color");
// todo: code, quote
#define PAGE_TAG(name, map) if(pageTag(name "=", sizeof(name), tag, len, map)) return;
PAGE_TAGS(PAGE_TAG);
// Unknown tag.
// Assume it is intended to be printed as plain text, with its brackets[].
printf("unknown tag: %.*s\n", (int)len, tag);
mNodeStart = tag-1;
flush(tag+len+1);
}
#ifdef WIN32
#include <algorithm>
static const char* memmem(const char* a, size_t alen, const char* b, size_t blen) {
const char* res = std::search(a, a+alen, b, b+blen);
if(res >= a+alen)
return NULL;
return res;
}
#endif
static bool isUrlChar(char c) {
//gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
//sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
return isalnum(c) || c == '_' || c == '#' || c == '?' || c == '/' || c == '-' ||
c == '=' || c == '.' || c == ':' || c == '&' || c == '(' || c == ')' ||
c == '%';
}
static bool isWowheadNonUrlChar(char c) {
return c == '/' || c == '?' || c == '.' || c == '-' || c == '&' || ((unsigned int)c) > 127;
}
void Parser::parseUrl(const char* url, size_t len) {
// skip starting whitespace
while(isspace(*url)) {
len--;
url++;
}
// skip broken '['
if(*url == '[') {
url++;
len--;
}
// check for start-quote mark.
if(*url == '"') {
url++;
len--;
}
// check for whitespace.
// skip whitespace and any data afterwards.
const char* ptr = url;
const char* end = url + len;
while(ptr < end) {
// also check for end-quote mark and the invalid start-tag marker.
if(isspace(*ptr) || *ptr == '"' || *ptr == '[')
break;
ptr++;
}
len = ptr - url;
// s/http://*.wowhead.com/
const char* whf = (char*)memmem(url, len, WH, strlen(WH));
if(whf) {
const char* path = whf + strlen(WH);
if(*path == '?')
path += 1;
size_t pathLen = len - (path - url);
// cut off broken parts
const char* c = path;
while(c < (path + pathLen)) {
if(isWowheadNonUrlChar(*c))
break;
c++;
}
pathLen = c - path;
addWowfootUrlNode(path, pathLen);
return;
}
// s/http://*.wowwiki.com/
//printf("URL test: %*s\n", (int)len, url);
const char* wwf = (char*)memmem(url, len, WW, strlen(WW));
if(wwf) {
const char* path = wwf + strlen(WW);
size_t pathLen = len - (path - url);
addWowpediaUrlNode(path, pathLen);
return;
}
// old-style wowhead paths.
if(strncmp(url, "/?", 2) == 0) {
url += 2;
len -= 2;
}
addUrlNode(url, len);
}
// returns new ptr.
const char* Parser::parseUnescapedUrl(const char* ptr) {
// find the end of the URL
const char* end = ptr;
while(isUrlChar(*end)) {
end++;
}
size_t len = end - ptr;
// check for path
const char* domain = ptr + 7;
const char* slash = (char*)memchr(domain, '/', end - domain);
if(!slash) {
addUrlNode(ptr, len);
addTextNode(ptr, len);
addUrlEndNode();
return end;
}
const char* path = slash + 1;
// we can assume wowhead urls never have slashes '/',
// or '?', except as the first character in the path.
// todo: if(len < strlen(WH))...
const char* subdomain = slash - (strlen(WH) - 1);
//printf("sd: %s\n", subdomain);
bool isWowhead = STREQ(subdomain, WH);
if(isWowhead && *path == '?')
path++;
end = path;
while(isUrlChar(*end)) {
if(isWowhead && isWowheadNonUrlChar(*end))
break;
end++;
}
size_t pathLen = end - path;
size_t urlLen = end - ptr;
//printf("uu: %i %.*s\n", isWowhead, urlLen, ptr);
if(isWowhead) {
// write name of linked entity (item, object, spell, quest, et. al)
// use PAGE_TAG code
#define UE_TAG(name, map) if(pageTag(name "=", sizeof(name), path, pathLen, map)) return end;
PAGE_TAGS(UE_TAG);
len = pathLen;
} else {
len = urlLen;
}
// wowwiki->wowpedia
const char* wwf = (char*)memmem(ptr, urlLen, WW, strlen(WW));
if(wwf) {
addWowpediaUrlNode(path, pathLen);
addStaticTextNode("http://www.wowpedia.org/");
addTextNode(path, pathLen);
addUrlEndNode();
return end;
}
if(!isWowhead)
path = ptr;
addUrlNode(path, len);
addTextNode(path, len);
addUrlEndNode();
return end;
}
<|endoftext|> |
<commit_before>
#include <QLayout>
#include <QTimer>
#include "wd.h"
#include "bitmap.h"
#include "child.h"
#include "cmd.h"
#include "font.h"
#include "form.h"
#include "isigraph.h"
#include "menus.h"
#include "../base/term.h"
extern "C" {
int wd(char *s,char *&r,int &len,char *loc);
// TODO
int wdisparent(char *s);
void *wdgetparentid(void *s);
}
extern int jedo(char *);
void wd1();
void wdbin();
void wdcc();
void wdcn();
void wdfontdef();
void wdmenu(string);
void wdnotyet();
void wdpactive();
void wdp(string c);
void wdpc();
void wdpclose();
void wdpmovex();
void wdpn();
void wdpsel();
void wdpshow();
void wdptop();
void wdq();
void wdqd();
void wdqueries(string);
void wdrem();
void wdreset();
void wdset();
void wdsetenable();
void wdsetp();
void wdsetx(string);
void wdstate(int);
void wdtimer();
void wdxywh(int);
void wdwh();
void error(string s);
bool nochild();
bool nochildset(string id);
bool noform();
int setchild(string id);
Cmd cmd;
Child *cc=0;
Form *form=0;
Form *evtform=0;
QList<Form *>Forms;
int rc;
string lasterror="";
string result="";
string tlocale="";
// TODO for debug
string cmdstr;
string ccmd;
// TODO
// ---------------------------------------------------------------------
int wdisparent(char *s)
{
string p= string(s);
string q= p;
Form *f;
if (q[0]=='_') q[0]='-';
void *n=(void *) strtol(q.c_str(),NULL,0);
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (n==f || p==f->id)
return 1;
}
return 0;
}
// ---------------------------------------------------------------------
void *wdgetparentid(void *s)
{
Form *f;
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (f->ischild((Child *) s))
return (void *)(f->id).c_str();
}
return 0;
}
// ---------------------------------------------------------------------
int wd(char *s,char *&res,int &len,char *loc)
{
rc=0;
result.clear();
tlocale=loc;
cmd.init(s);
noevents(1);
wd1();
noevents(0);
len=result.size();
res=(char *)result.c_str();
return rc;
}
// ---------------------------------------------------------------------
// subroutines may set int rc and wd1 returns if non-zero
void wd1()
{
string c,p;
while ((rc==0) && cmd.more()) {
// TODO
cmdstr=cmd.getcmdstr();
c=cmd.getid();
ccmd=c;
if (c.empty()) continue;
if (c=="q")
wdq();
else if (c=="bin")
wdbin();
else if (c=="cc")
wdcc();
else if (c=="cn")
wdcn();
else if (c=="fontdef")
wdfontdef();
else if (c.substr(0,4)=="menu")
wdmenu(c);
else if (c[0]=='p')
wdp(c);
else if (c[0]=='q')
wdqueries(c);
else if (c=="rem")
wdrem();
else if (c=="reset")
wdreset();
else if (c=="set")
wdset();
else if (c=="setp")
wdsetp();
else if (c=="setenable")
wdsetenable();
else if (c.substr(0,3)=="set")
wdsetx(c);
else if (c=="timer")
wdtimer();
else if (c=="xywh")
wdxywh(2);
else if (c=="wh")
wdwh();
else if (((c.substr(0,4)=="tbar") || (c.substr(0,4)=="sbar") || c=="msgs") || 0) {
cmd.getparms();
wdnotyet();
} else
error("command not found");
}
}
// ---------------------------------------------------------------------
void wdbin()
{
if (noform()) return;
form->bin(cmd.getparms());
}
// ---------------------------------------------------------------------
void wdcc()
{
if (noform()) return;
string c,n,p;
n=cmd.getid();
c=cmd.getid();
p=cmd.getparms();
if (form->addchild(n,c,p)) return;
error ("child not supported: " + c);
}
// ---------------------------------------------------------------------
void wdcn()
{
if (noform()) return;
cc=form->child;
if (nochild()) return;
string p=remquotes(cmd.getparms());
cc->setp("caption",p);
}
// ---------------------------------------------------------------------
void wdfontdef()
{
if (noform()) return;
string p=cmd.getparms();
form->fontdef = new Font(p);
}
// ---------------------------------------------------------------------
void wdmenu(string s)
{
int rc=0;
if (noform()) return;
if (form->menubar==0) form->addmenu();
string c,p;
if (s=="menu") {
c=cmd.getid();
p=cmd.getparms();
rc=form->menubar->menu(c,p);
} else if (s=="menupop") {
p=remquotes(cmd.getparms());
rc=form->menubar->menupop(p);
} else if (s=="menupopz") {
p=cmd.getparms();
rc=form->menubar->menupopz();
} else if (s=="menusep") {
p=cmd.getparms();
rc=form->menubar->menusep();
} else {
p=cmd.getparms();
error("menu command not found");
}
if (rc) error("menu command failed");
}
// ---------------------------------------------------------------------
// not yet
void wdnotyet()
{
cmd.getparms();
}
// ---------------------------------------------------------------------
void wdp(string c)
{
if (c=="pc")
wdpc();
else if (c=="pclose")
wdpclose();
else if (c=="pmovex")
wdpmovex();
else if (c=="pn")
wdpn();
else if (c=="psel")
wdpsel();
else if (c=="pshow")
wdpshow();
else if (c=="pactive")
wdpactive();
else if (c=="ptop")
wdptop();
else if (c=="pas" || c=="pcenter" || 0) {
cmd.getparms();
wdnotyet();
} else
error("parent command not found: " + c);
}
// ---------------------------------------------------------------------
void wdpactive()
{
if (noform()) return;
cmd.getparms();
#ifndef ANDROID
form->activateWindow();
form->raise();
#endif
}
// ---------------------------------------------------------------------
void wdpc()
{
string c,p;
c=cmd.getid();
p=cmd.getparms();
form=new Form(c,p,tlocale);
Forms.append(form);
}
// ---------------------------------------------------------------------
void wdpclose()
{
if (noform()) return;
cmd.getparms();
if (form->closed) return;
form->closed=true;
form->close();
}
// ---------------------------------------------------------------------
void wdpmovex()
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=4)
error("pmovex requires 4 numbers: " + p);
else {
#ifndef ANDROID
if (!((n.at(0)==QString("-1"))
||(n.at(0)==QString("_1"))
||(n.at(1)==QString("-1"))
||(n.at(1)==QString("_1"))))
form->move(n.at(0).toInt(),n.at(1).toInt());
form->resize(n.at(2).toInt(),n.at(3).toInt());
#endif
}
}
// ---------------------------------------------------------------------
void wdpn()
{
if (noform()) return;
string p=remquotes(cmd.getparms());
form->setpn(p);
}
// ---------------------------------------------------------------------
void wdpsel()
{
string p=cmd.getparms();
if (p.size()==0) {
form=0;
return;
}
Form *f;
string q=p;
if (q[0]=='_') q[0]='-';
void *n=(void *) strtol(q.c_str(),NULL,0);
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (n==f || p==f->id) {
form=f;
return;
}
}
error("command failed: psel");
}
// ---------------------------------------------------------------------
void wdpshow()
{
if (noform()) return;
cmd.getparms();
form->showit();
}
// ---------------------------------------------------------------------
void wdptop()
{
if (noform()) return;
cmd.getparms();
// TODO
#ifndef ANDROID
form->raise();
#endif
}
// ---------------------------------------------------------------------
void wdq()
{
string p=cmd.getparms();
wdstate(1);
}
// ---------------------------------------------------------------------
void wdqueries(string s)
{
string p=cmd.getparms();
if (s=="qd") {
wdstate(0);
return;
}
rc=-1;
if (s=="qer") {
result=lasterror;
return;
}
// queries that form not needed
if (s=="qm"||s=="qscreen"||s=="qcolor") {
error("command not found");
return;
}
if (noform()) return;
if (s=="qhwndp")
result=form->hsform();
else if (s=="qhwndc") {
Child *cc;
if ((cc=form->id2child(p))) result=p2s(cc);
else error("command failed: " + s);
} else
error("command not found");
}
// ---------------------------------------------------------------------
void wdrem()
{
cmd.getparms();
// TODO getline infinite loop bug?
// cmd.getline();
}
// ---------------------------------------------------------------------
void wdreset()
{
cmd.getparms();
foreach (Form *f,Forms) {
f->closed=true;
f->close();
}
form=0;
evtform=0;
}
// ---------------------------------------------------------------------
void wdset()
{
string n=cmd.getid();
string p=cmd.getparms();
int type=setchild(n);
switch (type) {
case 1 :
cc->set(p);
break;
case 2 :
cc->setp(n,p);
break;
}
}
// ---------------------------------------------------------------------
void wdsetenable()
{
string n=cmd.getid();
string p=cmd.getparms();
switch (setchild(n)) {
case 1:
cc->setenable(p);
break;
case 2:
cc->setenable(n+" "+p);
break;
}
}
// ---------------------------------------------------------------------
void wdsetp()
{
string n=cmd.getid();
if (nochildset(n)) return;
string p=cmd.getid();
string v=cmd.getparms();
if (p=="stretch")
form->setstretch(cc,v);
else {
cc->setp(p,v);
}
}
// ---------------------------------------------------------------------
void wdsetx(string c)
{
string n=cmd.getid();
// TODO
if (1!=setchild(n)) {
string p=cmd.getparms();
return;
}
if (nochildset(n)) return;
string p=cmd.getparms();
cc->setp(c.substr(3),p);
}
// ---------------------------------------------------------------------
void wdstate(int event)
{
if (evtform)
result=evtform->state(event);
rc=-2;
}
// ---------------------------------------------------------------------
void wdtimer()
{
string p=cmd.getparms();
int n=atoi(p.c_str());
if (n)
timer->start(n);
else
timer->stop();
}
// ---------------------------------------------------------------------
void wdxywh(int mul)
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=4)
error("xywh requires 2 numbers: " + p);
else {
form->sizew=mul*n.at(2).toInt();
form->sizeh=mul*n.at(3).toInt();
}
}
// ---------------------------------------------------------------------
void wdwh()
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=2)
error("wh requires 2 numbers: " + p);
else {
form->sizew=n.at(0).toInt();
form->sizeh=n.at(1).toInt();
}
}
// ---------------------------------------------------------------------
void error(string s)
{
lasterror=ccmd+" : "+s;
rc=1;
}
// ---------------------------------------------------------------------
bool nochild()
{
if (cc) return false;
// TODO
qDebug() << "no child selected " + s2q(cmdstr);
error("no child selected");
return true;
}
// ---------------------------------------------------------------------
bool nochildset(string id)
{
if (noform()) return true;
cc=form->id2child(id);
return nochild();
}
// ---------------------------------------------------------------------
// returns: 0=id not found
// 1=child id (cc=child)
// 2=menu id (cc=menubar)
int setchild(string id)
{
if (noform()) return 0;
cc=form->id2child(id);
if (cc) return 1;
cc=form->setmenuid(id);
if (cc) return 2;
// TODO
qDebug() << "no child selected " + s2q(cmdstr);
// nochild();
return 0;
}
// ---------------------------------------------------------------------
bool noform()
{
if (form) return false;
error("no parent selected");
return true;
}
// ---------------------------------------------------------------------
string remquotes(string s)
{
int len=s.size();
if (len==0) return s;
if ((s[0]=='"' && s[len-1]=='"')||(s[0]=='\177' && s[len-1]=='\177'))
s=s.substr(1,len-2);
return s;
}
<commit_msg>set noevents only for wdset and wdsetp<commit_after>
#include <QLayout>
#include <QTimer>
#include "wd.h"
#include "bitmap.h"
#include "child.h"
#include "cmd.h"
#include "font.h"
#include "form.h"
#include "isigraph.h"
#include "menus.h"
#include "../base/term.h"
extern "C" {
int wd(char *s,char *&r,int &len,char *loc);
// TODO
int wdisparent(char *s);
void *wdgetparentid(void *s);
}
extern int jedo(char *);
void wd1();
void wdbin();
void wdcc();
void wdcn();
void wdfontdef();
void wdmenu(string);
void wdnotyet();
void wdpactive();
void wdp(string c);
void wdpc();
void wdpclose();
void wdpmovex();
void wdpn();
void wdpsel();
void wdpshow();
void wdptop();
void wdq();
void wdqd();
void wdqueries(string);
void wdrem();
void wdreset();
void wdset();
void wdsetenable();
void wdsetp();
void wdsetx(string);
void wdstate(int);
void wdtimer();
void wdxywh(int);
void wdwh();
void error(string s);
bool nochild();
bool nochildset(string id);
bool noform();
int setchild(string id);
Cmd cmd;
Child *cc=0;
Form *form=0;
Form *evtform=0;
QList<Form *>Forms;
int rc;
string lasterror="";
string result="";
string tlocale="";
// TODO for debug
string cmdstr;
string ccmd;
// TODO
// ---------------------------------------------------------------------
int wdisparent(char *s)
{
string p= string(s);
string q= p;
Form *f;
if (q[0]=='_') q[0]='-';
void *n=(void *) strtol(q.c_str(),NULL,0);
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (n==f || p==f->id)
return 1;
}
return 0;
}
// ---------------------------------------------------------------------
void *wdgetparentid(void *s)
{
Form *f;
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (f->ischild((Child *) s))
return (void *)(f->id).c_str();
}
return 0;
}
// ---------------------------------------------------------------------
int wd(char *s,char *&res,int &len,char *loc)
{
rc=0;
result.clear();
tlocale=loc;
cmd.init(s);
// noevents(1);
wd1();
// noevents(0);
len=result.size();
res=(char *)result.c_str();
return rc;
}
// ---------------------------------------------------------------------
// subroutines may set int rc and wd1 returns if non-zero
void wd1()
{
string c,p;
while ((rc==0) && cmd.more()) {
// TODO
cmdstr=cmd.getcmdstr();
c=cmd.getid();
ccmd=c;
if (c.empty()) continue;
if (c=="q")
wdq();
else if (c=="bin")
wdbin();
else if (c=="cc")
wdcc();
else if (c=="cn")
wdcn();
else if (c=="fontdef")
wdfontdef();
else if (c.substr(0,4)=="menu")
wdmenu(c);
else if (c[0]=='p')
wdp(c);
else if (c[0]=='q')
wdqueries(c);
else if (c=="rem")
wdrem();
else if (c=="reset")
wdreset();
else if (c=="set") {
noevents(1);
wdset();
noevents(0);
} else if (c=="setp") {
noevents(1);
wdsetp();
noevents(0);
} else if (c=="setenable")
wdsetenable();
else if (c.substr(0,3)=="set")
wdsetx(c);
else if (c=="timer")
wdtimer();
else if (c=="xywh")
wdxywh(2);
else if (c=="wh")
wdwh();
else if (((c.substr(0,4)=="tbar") || (c.substr(0,4)=="sbar") || c=="msgs") || 0) {
cmd.getparms();
wdnotyet();
} else
error("command not found");
}
}
// ---------------------------------------------------------------------
void wdbin()
{
if (noform()) return;
form->bin(cmd.getparms());
}
// ---------------------------------------------------------------------
void wdcc()
{
if (noform()) return;
string c,n,p;
n=cmd.getid();
c=cmd.getid();
p=cmd.getparms();
if (form->addchild(n,c,p)) return;
error ("child not supported: " + c);
}
// ---------------------------------------------------------------------
void wdcn()
{
if (noform()) return;
cc=form->child;
if (nochild()) return;
string p=remquotes(cmd.getparms());
cc->setp("caption",p);
}
// ---------------------------------------------------------------------
void wdfontdef()
{
if (noform()) return;
string p=cmd.getparms();
form->fontdef = new Font(p);
}
// ---------------------------------------------------------------------
void wdmenu(string s)
{
int rc=0;
if (noform()) return;
if (form->menubar==0) form->addmenu();
string c,p;
if (s=="menu") {
c=cmd.getid();
p=cmd.getparms();
rc=form->menubar->menu(c,p);
} else if (s=="menupop") {
p=remquotes(cmd.getparms());
rc=form->menubar->menupop(p);
} else if (s=="menupopz") {
p=cmd.getparms();
rc=form->menubar->menupopz();
} else if (s=="menusep") {
p=cmd.getparms();
rc=form->menubar->menusep();
} else {
p=cmd.getparms();
error("menu command not found");
}
if (rc) error("menu command failed");
}
// ---------------------------------------------------------------------
// not yet
void wdnotyet()
{
cmd.getparms();
}
// ---------------------------------------------------------------------
void wdp(string c)
{
if (c=="pc")
wdpc();
else if (c=="pclose")
wdpclose();
else if (c=="pmovex")
wdpmovex();
else if (c=="pn")
wdpn();
else if (c=="psel")
wdpsel();
else if (c=="pshow")
wdpshow();
else if (c=="pactive")
wdpactive();
else if (c=="ptop")
wdptop();
else if (c=="pas" || c=="pcenter" || 0) {
cmd.getparms();
wdnotyet();
} else
error("parent command not found: " + c);
}
// ---------------------------------------------------------------------
void wdpactive()
{
if (noform()) return;
cmd.getparms();
#ifndef ANDROID
form->activateWindow();
form->raise();
#endif
}
// ---------------------------------------------------------------------
void wdpc()
{
string c,p;
c=cmd.getid();
p=cmd.getparms();
form=new Form(c,p,tlocale);
Forms.append(form);
}
// ---------------------------------------------------------------------
void wdpclose()
{
if (noform()) return;
cmd.getparms();
if (form->closed) return;
form->closed=true;
form->close();
}
// ---------------------------------------------------------------------
void wdpmovex()
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=4)
error("pmovex requires 4 numbers: " + p);
else {
#ifndef ANDROID
if (!((n.at(0)==QString("-1"))
||(n.at(0)==QString("_1"))
||(n.at(1)==QString("-1"))
||(n.at(1)==QString("_1"))))
form->move(n.at(0).toInt(),n.at(1).toInt());
form->resize(n.at(2).toInt(),n.at(3).toInt());
#endif
}
}
// ---------------------------------------------------------------------
void wdpn()
{
if (noform()) return;
string p=remquotes(cmd.getparms());
form->setpn(p);
}
// ---------------------------------------------------------------------
void wdpsel()
{
string p=cmd.getparms();
if (p.size()==0) {
form=0;
return;
}
Form *f;
string q=p;
if (q[0]=='_') q[0]='-';
void *n=(void *) strtol(q.c_str(),NULL,0);
for (int i=0; i<Forms.size(); i++) {
f=Forms.at(i);
if (n==f || p==f->id) {
form=f;
return;
}
}
error("command failed: psel");
}
// ---------------------------------------------------------------------
void wdpshow()
{
if (noform()) return;
cmd.getparms();
form->showit();
}
// ---------------------------------------------------------------------
void wdptop()
{
if (noform()) return;
cmd.getparms();
// TODO
#ifndef ANDROID
form->raise();
#endif
}
// ---------------------------------------------------------------------
void wdq()
{
string p=cmd.getparms();
wdstate(1);
}
// ---------------------------------------------------------------------
void wdqueries(string s)
{
string p=cmd.getparms();
if (s=="qd") {
wdstate(0);
return;
}
rc=-1;
if (s=="qer") {
result=lasterror;
return;
}
// queries that form not needed
if (s=="qm"||s=="qscreen"||s=="qcolor") {
error("command not found");
return;
}
if (noform()) return;
if (s=="qhwndp")
result=form->hsform();
else if (s=="qhwndc") {
Child *cc;
if ((cc=form->id2child(p))) result=p2s(cc);
else error("command failed: " + s);
} else
error("command not found");
}
// ---------------------------------------------------------------------
void wdrem()
{
cmd.getparms();
// TODO getline infinite loop bug?
// cmd.getline();
}
// ---------------------------------------------------------------------
void wdreset()
{
cmd.getparms();
foreach (Form *f,Forms) {
f->closed=true;
f->close();
}
form=0;
evtform=0;
}
// ---------------------------------------------------------------------
void wdset()
{
string n=cmd.getid();
string p=cmd.getparms();
int type=setchild(n);
switch (type) {
case 1 :
cc->set(p);
break;
case 2 :
cc->setp(n,p);
break;
}
}
// ---------------------------------------------------------------------
void wdsetenable()
{
string n=cmd.getid();
string p=cmd.getparms();
switch (setchild(n)) {
case 1:
cc->setenable(p);
break;
case 2:
cc->setenable(n+" "+p);
break;
}
}
// ---------------------------------------------------------------------
void wdsetp()
{
string n=cmd.getid();
if (nochildset(n)) return;
string p=cmd.getid();
string v=cmd.getparms();
if (p=="stretch")
form->setstretch(cc,v);
else {
cc->setp(p,v);
}
}
// ---------------------------------------------------------------------
void wdsetx(string c)
{
string n=cmd.getid();
// TODO
if (1!=setchild(n)) {
string p=cmd.getparms();
return;
}
if (nochildset(n)) return;
string p=cmd.getparms();
cc->setp(c.substr(3),p);
}
// ---------------------------------------------------------------------
void wdstate(int event)
{
if (evtform)
result=evtform->state(event);
rc=-2;
}
// ---------------------------------------------------------------------
void wdtimer()
{
string p=cmd.getparms();
int n=atoi(p.c_str());
if (n)
timer->start(n);
else
timer->stop();
}
// ---------------------------------------------------------------------
void wdxywh(int mul)
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=4)
error("xywh requires 2 numbers: " + p);
else {
form->sizew=mul*n.at(2).toInt();
form->sizeh=mul*n.at(3).toInt();
}
}
// ---------------------------------------------------------------------
void wdwh()
{
if (noform()) return;
string p=cmd.getparms();
QStringList n=s2q(p).split(" ",QString::SkipEmptyParts);
if (n.size()!=2)
error("wh requires 2 numbers: " + p);
else {
form->sizew=n.at(0).toInt();
form->sizeh=n.at(1).toInt();
}
}
// ---------------------------------------------------------------------
void error(string s)
{
lasterror=ccmd+" : "+s;
rc=1;
}
// ---------------------------------------------------------------------
bool nochild()
{
if (cc) return false;
// TODO
qDebug() << "no child selected " + s2q(cmdstr);
error("no child selected");
return true;
}
// ---------------------------------------------------------------------
bool nochildset(string id)
{
if (noform()) return true;
cc=form->id2child(id);
return nochild();
}
// ---------------------------------------------------------------------
// returns: 0=id not found
// 1=child id (cc=child)
// 2=menu id (cc=menubar)
int setchild(string id)
{
if (noform()) return 0;
cc=form->id2child(id);
if (cc) return 1;
cc=form->setmenuid(id);
if (cc) return 2;
// TODO
qDebug() << "no child selected " + s2q(cmdstr);
// nochild();
return 0;
}
// ---------------------------------------------------------------------
bool noform()
{
if (form) return false;
error("no parent selected");
return true;
}
// ---------------------------------------------------------------------
string remquotes(string s)
{
int len=s.size();
if (len==0) return s;
if ((s[0]=='"' && s[len-1]=='"')||(s[0]=='\177' && s[len-1]=='\177'))
s=s.substr(1,len-2);
return s;
}
<|endoftext|> |
<commit_before>//===-- io.cpp ------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// I/O routines for registered fd's
//
//===----------------------------------------------------------------------===//
#include "ipcopt.h"
#include "debug.h"
#include "ipcd.h"
#include "ipcreg_internal.h"
#include "real.h"
#include <algorithm>
#include <cassert>
#include <limits.h>
#include <sched.h>
#include <stdlib.h>
#include <string.h>
const size_t TRANS_THRESHOLD = 1ULL << 20;
const size_t MAX_SYNC_ATTEMPTS = 20;
const size_t MILLIS_IN_MICROSECONDS = 1000;
const size_t IPCD_SYNC_DELAY = 100 * MILLIS_IN_MICROSECONDS;
const size_t ATTEMPT_SLEEP_INTERVAL = IPCD_SYNC_DELAY / MAX_SYNC_ATTEMPTS;
void copy_bufsize(int src, int dst, int buftype) {
int bufsize;
socklen_t sz = sizeof(bufsize);
int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz);
assert(!ret);
// ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize);
ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz);
assert(!ret);
}
void copy_bufsizes(int src, int dst) {
copy_bufsize(src, dst, SO_RCVBUF);
copy_bufsize(src, dst, SO_SNDBUF);
}
void attempt_optimization(int fd) {
endpoint ep = getEP(fd);
assert(valid_ep(ep));
ipc_info &i = getInfo(ep);
assert(i.state != STATE_INVALID);
if (i.bytes_trans == TRANS_THRESHOLD) {
ipclog("Completed partial operation to sync at THRESHOLD for fd=%d!\n", fd);
// TODO: Async!
endpoint remote;
size_t attempts = 0;
while (((remote = ipcd_endpoint_kludge(ep)) == EP_INVALID) &&
++attempts < MAX_SYNC_ATTEMPTS) {
sched_yield();
usleep(ATTEMPT_SLEEP_INTERVAL);
}
if (valid_ep(remote)) {
ipclog("Found remote endpoint! Local=%d, Remote=%d Attempts=%zu!\n", ep,
remote, attempts);
bool success = ipcd_localize(ep, remote);
assert(success && "Failed to localize! Sadtimes! :(");
i.localfd = getlocalfd(fd);
i.state = STATE_OPTIMIZED;
// Configure localfd
copy_bufsizes(fd, i.localfd);
set_local_nonblocking(fd, i.non_blocking);
}
}
}
typedef ssize_t (*IOFunc)(...);
template <typename buf_t>
ssize_t do_ipc_io(int fd, buf_t buf, size_t count, int flags, IOFunc IO) {
endpoint ep = getEP(fd);
ipc_info &i = getInfo(ep);
assert(i.state != STATE_INVALID);
// If localized, just use fast socket:
if (i.state == STATE_OPTIMIZED) {
ssize_t ret = IO(i.localfd, buf, count, flags);
if (ret != -1 && !(flags & MSG_PEEK)) {
i.bytes_trans += ret;
}
return ret;
}
// Otherwise, use original fd:
ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans);
if (rem > 0 && size_t(rem) <= count) {
ssize_t ret = IO(fd, buf, rem, flags);
if (ret == -1 || (flags & MSG_PEEK)) {
return ret;
}
i.bytes_trans += ret;
attempt_optimization(fd);
return ret;
}
assert(i.state == STATE_UNOPT);
ssize_t ret = IO(fd, buf, count, flags);
if (ret == -1 || (flags & MSG_PEEK))
return ret;
// Successful operation, add to running total.
i.bytes_trans += ret;
return ret;
}
ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) {
return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_send);
}
ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) {
return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_recv);
}
ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr,
socklen_t /* unused */) {
// if (dest_addr)
// return __real_sendto(fd, message, length, flags, dest_addr, dest_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!dest_addr);
// As a bonus from the above check, we can forward to plain send()
return do_ipc_send(fd, message, length, flags);
}
ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags,
struct sockaddr *address, socklen_t * /* unused */) {
// if (address)
// return __real_recvfrom(fd, buffer, length, flags, address, address_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!address);
// As a bonus from the above check, we can forward to plain recv()
return do_ipc_recv(fd, buffer, length, flags);
}
template <typename IOVFunc>
ssize_t do_ipc_iov(int fd, const struct iovec *vec, int count, IOVFunc IO) {
// TODO: Combine shared logic with do_ipc_io!
ipc_info &i = getInfo(getEP(fd));
assert(i.state != STATE_INVALID);
// If localized, just use fast socket!
if (i.state == STATE_OPTIMIZED) {
ssize_t ret = IO(i.localfd, vec, count);
if (ret != -1) {
i.bytes_trans += ret;
}
return ret;
}
size_t bytes = 0;
for (int i = 0; i < count; ++i) {
// Overflow check...
if (SSIZE_MAX - bytes < vec[i].iov_len) {
// We could try to set errno here,
// but easier to just let actual writev/readv do this:
return IO(fd, vec, count);
}
bytes += vec[i].iov_len;
}
ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans);
if (rem > 0 && size_t(rem) <= bytes) {
// Need to construct alternate iovec!
iovec newvec[100];
assert(100 > count);
int newcount = 0;
for (; newcount < count && rem != 0; ++newcount) {
int copy = std::min(size_t(rem), vec[newcount].iov_len);
// Put this iov into our newvec
newvec[newcount].iov_base = vec[newcount].iov_base;
newvec[newcount].iov_len = copy;
rem -= copy;
}
assert(rem == 0);
ssize_t ret = IO(fd, newvec, newcount);
if (ret == -1)
return ret;
i.bytes_trans += ret;
attempt_optimization(fd);
return ret;
}
ssize_t ret = IO(fd, vec, count);
// We don't handle other states yet
assert(i.state == STATE_UNOPT);
if (ret == -1)
return ret;
// Successful operation, add to running total.
i.bytes_trans += ret;
return ret;
}
ssize_t do_ipc_writev(int fd, const struct iovec *vec, int count) {
return do_ipc_iov(fd, vec, count, __real_writev);
}
ssize_t do_ipc_readv(int fd, const struct iovec *vec, int count) {
return do_ipc_iov(fd, vec, count, __real_readv);
}
<commit_msg>libipc: Try to sync quickly, then sleep between requests.<commit_after>//===-- io.cpp ------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// I/O routines for registered fd's
//
//===----------------------------------------------------------------------===//
#include "ipcopt.h"
#include "debug.h"
#include "ipcd.h"
#include "ipcreg_internal.h"
#include "real.h"
#include <algorithm>
#include <cassert>
#include <limits.h>
#include <sched.h>
#include <stdlib.h>
#include <string.h>
const size_t TRANS_THRESHOLD = 1ULL << 20;
const size_t MAX_SYNC_ATTEMPTS = 20;
const size_t MILLIS_IN_MICROSECONDS = 1000;
const size_t IPCD_SYNC_DELAY = 100 * MILLIS_IN_MICROSECONDS;
const size_t ATTEMPT_SLEEP_INTERVAL = IPCD_SYNC_DELAY / MAX_SYNC_ATTEMPTS;
void copy_bufsize(int src, int dst, int buftype) {
int bufsize;
socklen_t sz = sizeof(bufsize);
int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz);
assert(!ret);
// ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize);
ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz);
assert(!ret);
}
void copy_bufsizes(int src, int dst) {
copy_bufsize(src, dst, SO_RCVBUF);
copy_bufsize(src, dst, SO_SNDBUF);
}
void attempt_optimization(int fd) {
endpoint ep = getEP(fd);
assert(valid_ep(ep));
ipc_info &i = getInfo(ep);
assert(i.state != STATE_INVALID);
if (i.bytes_trans == TRANS_THRESHOLD) {
ipclog("Completed partial operation to sync at THRESHOLD for fd=%d!\n", fd);
// TODO: Async!
endpoint remote = EP_INVALID;
size_t attempts = 0;
for (size_t attempts = 0; attempts <= MAX_SYNC_ATTEMPTS; ++attempts) {
remote = ipcd_endpoint_kludge(ep);
if (remote != EP_INVALID)
break;
if (attempts > 3) {
sched_yield();
usleep(ATTEMPT_SLEEP_INTERVAL);
}
}
if (valid_ep(remote)) {
ipclog("Found remote endpoint! Local=%d, Remote=%d Attempts=%zu!\n", ep,
remote, attempts);
bool success = ipcd_localize(ep, remote);
assert(success && "Failed to localize! Sadtimes! :(");
i.localfd = getlocalfd(fd);
i.state = STATE_OPTIMIZED;
// Configure localfd
copy_bufsizes(fd, i.localfd);
set_local_nonblocking(fd, i.non_blocking);
}
}
}
typedef ssize_t (*IOFunc)(...);
template <typename buf_t>
ssize_t do_ipc_io(int fd, buf_t buf, size_t count, int flags, IOFunc IO) {
endpoint ep = getEP(fd);
ipc_info &i = getInfo(ep);
assert(i.state != STATE_INVALID);
// If localized, just use fast socket:
if (i.state == STATE_OPTIMIZED) {
ssize_t ret = IO(i.localfd, buf, count, flags);
if (ret != -1 && !(flags & MSG_PEEK)) {
i.bytes_trans += ret;
}
return ret;
}
// Otherwise, use original fd:
ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans);
if (rem > 0 && size_t(rem) <= count) {
ssize_t ret = IO(fd, buf, rem, flags);
if (ret == -1 || (flags & MSG_PEEK)) {
return ret;
}
i.bytes_trans += ret;
attempt_optimization(fd);
return ret;
}
assert(i.state == STATE_UNOPT);
ssize_t ret = IO(fd, buf, count, flags);
if (ret == -1 || (flags & MSG_PEEK))
return ret;
// Successful operation, add to running total.
i.bytes_trans += ret;
return ret;
}
ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) {
return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_send);
}
ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) {
return do_ipc_io(fd, buf, count, flags, (IOFunc)__real_recv);
}
ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr,
socklen_t /* unused */) {
// if (dest_addr)
// return __real_sendto(fd, message, length, flags, dest_addr, dest_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!dest_addr);
// As a bonus from the above check, we can forward to plain send()
return do_ipc_send(fd, message, length, flags);
}
ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags,
struct sockaddr *address, socklen_t * /* unused */) {
// if (address)
// return __real_recvfrom(fd, buffer, length, flags, address, address_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!address);
// As a bonus from the above check, we can forward to plain recv()
return do_ipc_recv(fd, buffer, length, flags);
}
template <typename IOVFunc>
ssize_t do_ipc_iov(int fd, const struct iovec *vec, int count, IOVFunc IO) {
// TODO: Combine shared logic with do_ipc_io!
ipc_info &i = getInfo(getEP(fd));
assert(i.state != STATE_INVALID);
// If localized, just use fast socket!
if (i.state == STATE_OPTIMIZED) {
ssize_t ret = IO(i.localfd, vec, count);
if (ret != -1) {
i.bytes_trans += ret;
}
return ret;
}
size_t bytes = 0;
for (int i = 0; i < count; ++i) {
// Overflow check...
if (SSIZE_MAX - bytes < vec[i].iov_len) {
// We could try to set errno here,
// but easier to just let actual writev/readv do this:
return IO(fd, vec, count);
}
bytes += vec[i].iov_len;
}
ssize_t rem = (TRANS_THRESHOLD - i.bytes_trans);
if (rem > 0 && size_t(rem) <= bytes) {
// Need to construct alternate iovec!
iovec newvec[100];
assert(100 > count);
int newcount = 0;
for (; newcount < count && rem != 0; ++newcount) {
int copy = std::min(size_t(rem), vec[newcount].iov_len);
// Put this iov into our newvec
newvec[newcount].iov_base = vec[newcount].iov_base;
newvec[newcount].iov_len = copy;
rem -= copy;
}
assert(rem == 0);
ssize_t ret = IO(fd, newvec, newcount);
if (ret == -1)
return ret;
i.bytes_trans += ret;
attempt_optimization(fd);
return ret;
}
ssize_t ret = IO(fd, vec, count);
// We don't handle other states yet
assert(i.state == STATE_UNOPT);
if (ret == -1)
return ret;
// Successful operation, add to running total.
i.bytes_trans += ret;
return ret;
}
ssize_t do_ipc_writev(int fd, const struct iovec *vec, int count) {
return do_ipc_iov(fd, vec, count, __real_writev);
}
ssize_t do_ipc_readv(int fd, const struct iovec *vec, int count) {
return do_ipc_iov(fd, vec, count, __real_readv);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xsecverify.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: mmi $ $Date: 2004-08-12 02:29:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <xsecctl.hxx>
#include "xsecparser.hxx"
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#include <com/sun/star/xml/crypto/sax/XKeyCollector.hpp>
#include <com/sun/star/xml/crypto/sax/ElementMarkPriority.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceResolvedBroadcaster.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceCollector.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultBroadcaster.hpp>
#include <com/sun/star/xml/sax/SAXParseException.hpp>
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxs = com::sun::star::xml::sax;
/* xml security framework components */
#define SIGNATUREVERIFIER_COMPONENT "com.sun.star.xml.crypto.sax.SignatureVerifier"
/* protected: for signature verify */
cssu::Reference< cssxc::sax::XReferenceResolvedListener > XSecController::prepareSignatureToRead(
sal_Int32 nSecurityId)
{
if ( m_nStatusOfSecurityComponents != INITIALIZED )
{
return NULL;
}
sal_Int32 nIdOfSignatureElementCollector;
cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener;
nIdOfSignatureElementCollector =
m_xSAXEventKeeper->addSecurityElementCollector( cssxc::sax::ElementMarkPriority_PRI_BEFOREMODIFY, sal_False);
m_xSAXEventKeeper->setSecurityId(nIdOfSignatureElementCollector, nSecurityId);
/*
* create a SignatureVerifier
*/
xReferenceResolvedListener = cssu::Reference< cssxc::sax::XReferenceResolvedListener >(
mxMSF->createInstance(
rtl::OUString::createFromAscii( SIGNATUREVERIFIER_COMPONENT )),
cssu::UNO_QUERY);
cssu::Reference<cssl::XInitialization> xInitialization(xReferenceResolvedListener, cssu::UNO_QUERY);
cssu::Sequence<cssu::Any> args(5);
args[0] = cssu::makeAny(rtl::OUString::valueOf(nSecurityId));
args[1] = cssu::makeAny(m_xSAXEventKeeper);
args[2] = cssu::makeAny(rtl::OUString::valueOf(nIdOfSignatureElementCollector));
args[3] = cssu::makeAny(m_xSecurityContext);
args[4] = cssu::makeAny(m_xXMLSignature);
xInitialization->initialize(args);
cssu::Reference< cssxc::sax::XSignatureVerifyResultBroadcaster >
signatureVerifyResultBroadcaster(xReferenceResolvedListener, cssu::UNO_QUERY);
signatureVerifyResultBroadcaster->addSignatureVerifyResultListener( this );
cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster> xReferenceResolvedBroadcaster
(m_xSAXEventKeeper,
cssu::UNO_QUERY);
xReferenceResolvedBroadcaster->addReferenceResolvedListener(
nIdOfSignatureElementCollector,
xReferenceResolvedListener);
cssu::Reference<cssxc::sax::XKeyCollector> keyCollector (xReferenceResolvedListener, cssu::UNO_QUERY);
keyCollector->setKeyId(0);
return xReferenceResolvedListener;
}
void XSecController::addSignature()
{
cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener = NULL;
sal_Int32 nSignatureId = 0;
if (m_bVerifyCurrentSignature)
{
chainOn(true);
xReferenceResolvedListener = prepareSignatureToRead( m_nReservedSignatureId );
m_bVerifyCurrentSignature = false;
nSignatureId = m_nReservedSignatureId;
}
InternalSignatureInformation isi( nSignatureId, xReferenceResolvedListener );
m_vInternalSignatureInformations.push_back( isi );
}
void XSecController::addReference( const rtl::OUString& ouUri)
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.addReference(TYPE_SAMEDOCUMENT_REFERENCE,ouUri, -1 );
}
void XSecController::addStreamReference(
const rtl::OUString& ouUri,
bool isBinary )
{
sal_Int32 type = (isBinary?TYPE_BINARYSTREAM_REFERENCE:TYPE_XMLSTREAM_REFERENCE);
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
if ( isi.xReferenceResolvedListener.is() )
{
/*
* get the input stream
*/
cssu::Reference< com::sun::star::io::XInputStream > xObjectInputStream
= getObjectInputStream( ouUri );
if ( xObjectInputStream.is() )
{
cssu::Reference<cssxc::XUriBinding> xUriBinding
(isi.xReferenceResolvedListener, cssu::UNO_QUERY);
xUriBinding->setUriBinding(ouUri, xObjectInputStream);
}
}
isi.addReference(type, ouUri, -1);
}
void XSecController::setReferenceCount() const
{
const InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
if ( isi.xReferenceResolvedListener.is() )
{
const SignatureReferenceInformations &refInfors = isi.signatureInfor.vSignatureReferenceInfors;
int refNum = refInfors.size();
sal_Int32 referenceCount = 0;
for(int i=0 ; i<refNum; ++i)
{
if (refInfors[i].nType == TYPE_SAMEDOCUMENT_REFERENCE )
/*
* same-document reference
*/
{
referenceCount++;
}
}
cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
(isi.xReferenceResolvedListener, cssu::UNO_QUERY);
xReferenceCollector->setReferenceCount( referenceCount );
}
}
void XSecController::setX509IssuerName( rtl::OUString& ouX509IssuerName )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509IssuerName = ouX509IssuerName;
}
void XSecController::setX509SerialNumber( rtl::OUString& ouX509SerialNumber )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509SerialNumber = ouX509SerialNumber;
}
void XSecController::setX509Certificate( rtl::OUString& ouX509Certificate )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509Certificate = ouX509Certificate;
}
void XSecController::setSignatureValue( rtl::OUString& ouSignatureValue )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouSignatureValue = ouSignatureValue;
}
void XSecController::setDigestValue( rtl::OUString& ouDigestValue )
{
SignatureInformation &si = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1].signatureInfor;
SignatureReferenceInformation &reference = si.vSignatureReferenceInfors[si.vSignatureReferenceInfors.size()-1];
reference.ouDigestValue = ouDigestValue;
}
void XSecController::setDate( rtl::OUString& ouDate )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
convertDateTime( isi.signatureInfor.stDateTime, ouDate );
}
/*
void XSecController::setTime( rtl::OUString& ouTime )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouTime = ouTime;
}
*/
void XSecController::setId( rtl::OUString& ouId )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouSignatureId = ouId;
}
void XSecController::setPropertyId( rtl::OUString& ouPropertyId )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouPropertyId = ouPropertyId;
}
/* public: for signature verify */
void XSecController::collectToVerify( const rtl::OUString& referenceId )
{
/* DBG_ASSERT( m_xSAXEventKeeper.is(), "the SAXEventKeeper is NULL" ); */
if ( m_nStatusOfSecurityComponents == INITIALIZED )
/*
* if all security components are ready, verify the signature.
*/
{
bool bJustChainingOn = false;
cssu::Reference< cssxs::XDocumentHandler > xHandler = NULL;
int i,j;
int sigNum = m_vInternalSignatureInformations.size();
for (i=0; i<sigNum; ++i)
{
InternalSignatureInformation& isi = m_vInternalSignatureInformations[i];
SignatureReferenceInformations& vReferenceInfors = isi.signatureInfor.vSignatureReferenceInfors;
int refNum = vReferenceInfors.size();
for (j=0; j<refNum; ++j)
{
SignatureReferenceInformation &refInfor = vReferenceInfors[j];
if (refInfor.ouURI == referenceId)
{
if (chainOn(false))
{
bJustChainingOn = true;
xHandler = m_xSAXEventKeeper->setNextHandler(NULL);
}
sal_Int32 nKeeperId = m_xSAXEventKeeper->addSecurityElementCollector(
cssxc::sax::ElementMarkPriority_PRI_BEFOREMODIFY, sal_False );
cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster> xReferenceResolvedBroadcaster
(m_xSAXEventKeeper,
cssu::UNO_QUERY );
cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
( isi.xReferenceResolvedListener, cssu::UNO_QUERY );
m_xSAXEventKeeper->setSecurityId(nKeeperId, isi.signatureInfor.nSecurityId);
xReferenceResolvedBroadcaster->addReferenceResolvedListener( nKeeperId, isi.xReferenceResolvedListener);
xReferenceCollector->setReferenceId( nKeeperId );
isi.vKeeperIds[j] = nKeeperId;
break;
}
}
}
if ( bJustChainingOn )
{
cssu::Reference< cssxs::XDocumentHandler > xSEKHandler(m_xSAXEventKeeper, cssu::UNO_QUERY);
if (m_xElementStackKeeper.is())
{
m_xElementStackKeeper->retrieve(xSEKHandler, sal_True);
}
m_xSAXEventKeeper->setNextHandler(xHandler);
}
}
}
void XSecController::addSignature( sal_Int32 nSignatureId )
{
DBG_ASSERT( m_pXSecParser != NULL, "No XSecParser initialized" );
m_nReservedSignatureId = nSignatureId;
m_bVerifyCurrentSignature = true;
}
cssu::Reference< cssxs::XDocumentHandler > XSecController::createSignatureReader()
{
m_pXSecParser = new XSecParser( this, NULL );
cssu::Reference< cssl::XInitialization > xInitialization = m_pXSecParser;
setSAXChainConnector(xInitialization, NULL, NULL);
return m_pXSecParser;
}
void XSecController::releaseSignatureReader()
{
clearSAXChainConnector( );
m_pXSecParser = NULL;
}
<commit_msg>INTEGRATION: CWS xmlsec10 (1.4.38); FILE MERGED 2005/03/23 09:52:49 mmi 1.4.38.1: idl review Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
*
* $RCSfile: xsecverify.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-03-29 13:23:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <xsecctl.hxx>
#include "xsecparser.hxx"
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#include <com/sun/star/xml/crypto/sax/XKeyCollector.hpp>
#include <com/sun/star/xml/crypto/sax/ElementMarkPriority.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceResolvedBroadcaster.hpp>
#include <com/sun/star/xml/crypto/sax/XReferenceCollector.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultBroadcaster.hpp>
#include <com/sun/star/xml/sax/SAXParseException.hpp>
namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;
namespace cssxs = com::sun::star::xml::sax;
/* xml security framework components */
#define SIGNATUREVERIFIER_COMPONENT "com.sun.star.xml.crypto.sax.SignatureVerifier"
/* protected: for signature verify */
cssu::Reference< cssxc::sax::XReferenceResolvedListener > XSecController::prepareSignatureToRead(
sal_Int32 nSecurityId)
{
if ( m_nStatusOfSecurityComponents != INITIALIZED )
{
return NULL;
}
sal_Int32 nIdOfSignatureElementCollector;
cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener;
nIdOfSignatureElementCollector =
m_xSAXEventKeeper->addSecurityElementCollector( cssxc::sax::ElementMarkPriority_BEFOREMODIFY, sal_False);
m_xSAXEventKeeper->setSecurityId(nIdOfSignatureElementCollector, nSecurityId);
/*
* create a SignatureVerifier
*/
xReferenceResolvedListener = cssu::Reference< cssxc::sax::XReferenceResolvedListener >(
mxMSF->createInstance(
rtl::OUString::createFromAscii( SIGNATUREVERIFIER_COMPONENT )),
cssu::UNO_QUERY);
cssu::Reference<cssl::XInitialization> xInitialization(xReferenceResolvedListener, cssu::UNO_QUERY);
cssu::Sequence<cssu::Any> args(5);
args[0] = cssu::makeAny(rtl::OUString::valueOf(nSecurityId));
args[1] = cssu::makeAny(m_xSAXEventKeeper);
args[2] = cssu::makeAny(rtl::OUString::valueOf(nIdOfSignatureElementCollector));
args[3] = cssu::makeAny(m_xSecurityContext);
args[4] = cssu::makeAny(m_xXMLSignature);
xInitialization->initialize(args);
cssu::Reference< cssxc::sax::XSignatureVerifyResultBroadcaster >
signatureVerifyResultBroadcaster(xReferenceResolvedListener, cssu::UNO_QUERY);
signatureVerifyResultBroadcaster->addSignatureVerifyResultListener( this );
cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster> xReferenceResolvedBroadcaster
(m_xSAXEventKeeper,
cssu::UNO_QUERY);
xReferenceResolvedBroadcaster->addReferenceResolvedListener(
nIdOfSignatureElementCollector,
xReferenceResolvedListener);
cssu::Reference<cssxc::sax::XKeyCollector> keyCollector (xReferenceResolvedListener, cssu::UNO_QUERY);
keyCollector->setKeyId(0);
return xReferenceResolvedListener;
}
void XSecController::addSignature()
{
cssu::Reference< cssxc::sax::XReferenceResolvedListener > xReferenceResolvedListener = NULL;
sal_Int32 nSignatureId = 0;
if (m_bVerifyCurrentSignature)
{
chainOn(true);
xReferenceResolvedListener = prepareSignatureToRead( m_nReservedSignatureId );
m_bVerifyCurrentSignature = false;
nSignatureId = m_nReservedSignatureId;
}
InternalSignatureInformation isi( nSignatureId, xReferenceResolvedListener );
m_vInternalSignatureInformations.push_back( isi );
}
void XSecController::addReference( const rtl::OUString& ouUri)
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.addReference(TYPE_SAMEDOCUMENT_REFERENCE,ouUri, -1 );
}
void XSecController::addStreamReference(
const rtl::OUString& ouUri,
bool isBinary )
{
sal_Int32 type = (isBinary?TYPE_BINARYSTREAM_REFERENCE:TYPE_XMLSTREAM_REFERENCE);
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
if ( isi.xReferenceResolvedListener.is() )
{
/*
* get the input stream
*/
cssu::Reference< com::sun::star::io::XInputStream > xObjectInputStream
= getObjectInputStream( ouUri );
if ( xObjectInputStream.is() )
{
cssu::Reference<cssxc::XUriBinding> xUriBinding
(isi.xReferenceResolvedListener, cssu::UNO_QUERY);
xUriBinding->setUriBinding(ouUri, xObjectInputStream);
}
}
isi.addReference(type, ouUri, -1);
}
void XSecController::setReferenceCount() const
{
const InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
if ( isi.xReferenceResolvedListener.is() )
{
const SignatureReferenceInformations &refInfors = isi.signatureInfor.vSignatureReferenceInfors;
int refNum = refInfors.size();
sal_Int32 referenceCount = 0;
for(int i=0 ; i<refNum; ++i)
{
if (refInfors[i].nType == TYPE_SAMEDOCUMENT_REFERENCE )
/*
* same-document reference
*/
{
referenceCount++;
}
}
cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
(isi.xReferenceResolvedListener, cssu::UNO_QUERY);
xReferenceCollector->setReferenceCount( referenceCount );
}
}
void XSecController::setX509IssuerName( rtl::OUString& ouX509IssuerName )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509IssuerName = ouX509IssuerName;
}
void XSecController::setX509SerialNumber( rtl::OUString& ouX509SerialNumber )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509SerialNumber = ouX509SerialNumber;
}
void XSecController::setX509Certificate( rtl::OUString& ouX509Certificate )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouX509Certificate = ouX509Certificate;
}
void XSecController::setSignatureValue( rtl::OUString& ouSignatureValue )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouSignatureValue = ouSignatureValue;
}
void XSecController::setDigestValue( rtl::OUString& ouDigestValue )
{
SignatureInformation &si = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1].signatureInfor;
SignatureReferenceInformation &reference = si.vSignatureReferenceInfors[si.vSignatureReferenceInfors.size()-1];
reference.ouDigestValue = ouDigestValue;
}
void XSecController::setDate( rtl::OUString& ouDate )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
convertDateTime( isi.signatureInfor.stDateTime, ouDate );
}
/*
void XSecController::setTime( rtl::OUString& ouTime )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouTime = ouTime;
}
*/
void XSecController::setId( rtl::OUString& ouId )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouSignatureId = ouId;
}
void XSecController::setPropertyId( rtl::OUString& ouPropertyId )
{
InternalSignatureInformation &isi = m_vInternalSignatureInformations[m_vInternalSignatureInformations.size()-1];
isi.signatureInfor.ouPropertyId = ouPropertyId;
}
/* public: for signature verify */
void XSecController::collectToVerify( const rtl::OUString& referenceId )
{
/* DBG_ASSERT( m_xSAXEventKeeper.is(), "the SAXEventKeeper is NULL" ); */
if ( m_nStatusOfSecurityComponents == INITIALIZED )
/*
* if all security components are ready, verify the signature.
*/
{
bool bJustChainingOn = false;
cssu::Reference< cssxs::XDocumentHandler > xHandler = NULL;
int i,j;
int sigNum = m_vInternalSignatureInformations.size();
for (i=0; i<sigNum; ++i)
{
InternalSignatureInformation& isi = m_vInternalSignatureInformations[i];
SignatureReferenceInformations& vReferenceInfors = isi.signatureInfor.vSignatureReferenceInfors;
int refNum = vReferenceInfors.size();
for (j=0; j<refNum; ++j)
{
SignatureReferenceInformation &refInfor = vReferenceInfors[j];
if (refInfor.ouURI == referenceId)
{
if (chainOn(false))
{
bJustChainingOn = true;
xHandler = m_xSAXEventKeeper->setNextHandler(NULL);
}
sal_Int32 nKeeperId = m_xSAXEventKeeper->addSecurityElementCollector(
cssxc::sax::ElementMarkPriority_BEFOREMODIFY, sal_False );
cssu::Reference<cssxc::sax::XReferenceResolvedBroadcaster> xReferenceResolvedBroadcaster
(m_xSAXEventKeeper,
cssu::UNO_QUERY );
cssu::Reference<cssxc::sax::XReferenceCollector> xReferenceCollector
( isi.xReferenceResolvedListener, cssu::UNO_QUERY );
m_xSAXEventKeeper->setSecurityId(nKeeperId, isi.signatureInfor.nSecurityId);
xReferenceResolvedBroadcaster->addReferenceResolvedListener( nKeeperId, isi.xReferenceResolvedListener);
xReferenceCollector->setReferenceId( nKeeperId );
isi.vKeeperIds[j] = nKeeperId;
break;
}
}
}
if ( bJustChainingOn )
{
cssu::Reference< cssxs::XDocumentHandler > xSEKHandler(m_xSAXEventKeeper, cssu::UNO_QUERY);
if (m_xElementStackKeeper.is())
{
m_xElementStackKeeper->retrieve(xSEKHandler, sal_True);
}
m_xSAXEventKeeper->setNextHandler(xHandler);
}
}
}
void XSecController::addSignature( sal_Int32 nSignatureId )
{
DBG_ASSERT( m_pXSecParser != NULL, "No XSecParser initialized" );
m_nReservedSignatureId = nSignatureId;
m_bVerifyCurrentSignature = true;
}
cssu::Reference< cssxs::XDocumentHandler > XSecController::createSignatureReader()
{
m_pXSecParser = new XSecParser( this, NULL );
cssu::Reference< cssl::XInitialization > xInitialization = m_pXSecParser;
setSAXChainConnector(xInitialization, NULL, NULL);
return m_pXSecParser;
}
void XSecController::releaseSignatureReader()
{
clearSAXChainConnector( );
m_pXSecParser = NULL;
}
<|endoftext|> |
<commit_before>/**
* @file
* @author Nico Wollenzin <[email protected]>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2014] [Nico Wollenzin]
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*
* @section DESCRIPTION
*
* first class
*/
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int area (void) {return (width*height);}
};
// Constructors
Rectangle::Rectangle () {
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
// End
int main () {
Rectangle rect (3,4);
Rectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
<commit_msg>Scary OOP - not so scary anymore<commit_after>/**
* @file
* @author Nico Wollenzin <[email protected]>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2014] [Nico Wollenzin]
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*
* @section DESCRIPTION
*
* first class
*/
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle ();
Rectangle (int,int);
int area (void);
};
// Constructors
Rectangle::Rectangle () {
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
// End
int Rectangle::area (void) {return (width*height);}
int main () {
Rectangle rect (3,4);
Rectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
<|endoftext|> |
<commit_before>/* Definition of member functions of class Scanner */
#include "../headers/Scanner.hpp"
#include <string>
#include <sstream>
#ifdef DEBUG
# include <iostream>
# include <iomanip>
#endif
using namespace std;
Scanner::Scanner(FileReader* fileReader, ErrorReporter* errorReporter) :
m_lineNo(1),
m_column(1),
m_currentToken(0),
m_nTokens(0),
m_nTokensProcessed(0),
m_tokensLexemes(),
m_keywordsMap(),
m_errorReporter(errorReporter),
m_fileReader(fileReader)
{
buildKeywordsMap();
}
void Scanner::scan()
{
if (m_fileReader->getTotalLines() > 0)
{
char currentChar;
int nextState = 0, currentState = 0;
TokenType_t token;
string lexeme;
string line;
size_t lineLength;
m_lineNo = 1;
while (m_lineNo <= m_fileReader->getTotalLines() &&
m_errorReporter->getErrors() < m_errorReporter->getMaxErrors())
{
line = m_fileReader->getTextAtLine(m_lineNo - 1);
lineLength = line.length();
m_column = 1;
while (m_column <= lineLength &&
m_errorReporter->getErrors() <= m_errorReporter->getMaxErrors())
{
currentChar = line.at(m_column - 1);
nextState = automata[currentState][getTransitionIndex(currentChar)];
#ifdef DEBUG
cout << "CState: " << setw(2) << currentState << " NState: " <<
setw(2) << nextState << " TIndex: " <<
setw(2) << getTransitionIndex(currentChar) <<
" Char: ";
if (!isspace(currentChar))
cout << currentChar;
else
cout << ' ';
cout << " : " << setw(3) << (int)currentChar << endl;
#endif
if (nextState == STATE_ACCEPT_ERROR)
{
switch (currentState)
{
case 1 :
case 2 : token = TOKEN_OCT;
break;
case 4 :
token = TOKEN_HEX;
break;
case 5 :
token = TOKEN_DEC;
break;
case 6 :
case 11 :
token = TOKEN_FLOAT;
break;
case 7 :
case 26 :
token = TOKEN_DELIMITER;
break;
case 8 :
token = TOKEN_FLOAT;
break;
case 13 :
token = TOKEN_STRING;
break;
case 14 :
case 19 :
token = TOKEN_ARITHOP;
break;
case 16 :
token = TOKEN_LINECOMMENT;
break;
case 18 :
token = TOKEN_MULTICOMMENT;
break;
case 22 :
case 24 :
token = TOKEN_LOGICOP;
break;
case 23 :
case 27 :
token = TOKEN_ASSIGNOP;
break;
case 25 :
case 35 :
case 36 :
token = TOKEN_RELOP;
break;
case 28 :
token = TOKEN_IDEN;
if (m_keywordsMap.find(lexeme) != m_keywordsMap.end())
{
token = TOKEN_KEYWORD;
}
else if (lexeme.compare("verdadero") == 0 ||
lexeme.compare("falso") == 0)
{
token = TOKEN_LOGICCONST;
}
break;
case 29 :
token = TOKEN_DELIMITER;
break;
case 33 :
token = TOKEN_CHARCONST;
break;
case 37 :
token = TOKEN_NEWLINE;
break;
default :
#ifdef DEBUG
cerr << "vecomp: error de estado siguiente" << endl;
#endif
break;
}
if (token != TOKEN_LINECOMMENT && token != TOKEN_MULTICOMMENT)
{
m_tokensLexemes.push_back(TokenLexeme(token, lexeme, m_lineNo,
m_column - lexeme.length()));
#ifdef DEBUG
cout << "pushed element: " << setw(20) <<
TokenLexeme::getTokenString(token) << ": " << setw(20) <<
lexeme << " at: " << m_lineNo << ", " <<
m_column - lexeme.length() << endl;
#endif
}
token = TOKEN_INVALID;
lexeme = "";
nextState = 0;
--m_column;
}
else if (nextState == STATE_ERROR)
{
#ifdef DEBUG
cout << "calling lexicalerror" << currentState << " " <<
currentChar << endl;
#endif
m_errorReporter->writeLexicalError(currentState, currentChar, lexeme,
m_lineNo, m_column);
token = TOKEN_INVALID;
lexeme = "";
nextState = 0;
}
else if ( isspace(currentChar) &&
(currentState == 12 || currentState == 15 ||
currentState == 17))
lexeme += currentChar;
else if (!isspace(currentChar))
lexeme += currentChar;
currentState = nextState;
++m_column;
}
++m_lineNo;
line = "";
}
#ifdef DEBUG
cout << "final state: " << currentState << endl;
#endif
if (currentState != 0 && !isTerminalState(currentState))
m_errorReporter->writeLexicalError(currentState, currentChar, lexeme,
m_lineNo, m_column);
m_nTokens = m_tokensLexemes.size();
if (m_tokensLexemes.empty())
{
m_errorReporter->writeError("archivo vacio");
}
}
}
void Scanner::moveTokenBackward()
{
--m_currentToken;
}
void Scanner::moveTokenForward()
{
++m_currentToken;
}
TokenLexeme Scanner::getNextTokenLexeme()
{
TokenLexeme temporal;
if (!m_tokensLexemes.empty())
{
temporal = m_tokensLexemes.at(m_currentToken);
}
#ifdef DEBUG
cout << "::: returning token at: " << m_currentToken << ", " <<
m_tokensLexemes.at(m_currentToken).getLexeme() << endl;
#endif
moveTokenForward();
++m_nTokensProcessed;
return temporal;
}
Transition_t Scanner::getTransitionIndex(char character)
{
Transition_t transitionIndex = TRANS_ANY;
if (isdigit(character))
{
if (character == '0')
transitionIndex = TRANS_ZERO;
else if (character <= '7')
transitionIndex = TRANS_OCT;
else
transitionIndex = TRANS_DEC;
}
else if (isalpha(character))
{
if (tolower(character) == 'e')
transitionIndex = TRANS_E;
else if (tolower(character) == 'x')
transitionIndex = TRANS_X;
else if (tolower(character) <= 'f')
transitionIndex = TRANS_HEX;
else
transitionIndex = TRANS_LETTER;
}
else
{
switch (character)
{
case '|' :
transitionIndex = TRANS_PIPE;
break;
case '&' :
transitionIndex = TRANS_AMPERS;
break;
case '!' :
transitionIndex = TRANS_EXCLAMATION;
break;
case ' ' :
case '\t' :
case '\r' :
transitionIndex = TRANS_SPACE;
break;
case '\n' :
transitionIndex = TRANS_NEWLINE;
break;
case ',' :
case ';' :
case '(' :
case ')' :
case '[' :
case ']' :
case '{' :
case '}' :
transitionIndex = TRANS_DELIMITER;
break;
case '+' :
case '-' :
transitionIndex = TRANS_SIGN;
break;
case '*' :
transitionIndex = TRANS_ASTERISK;
break;
case '/' :
transitionIndex = TRANS_SLASH;
break;
case '%' :
case '^' :
transitionIndex = TRANS_ARITHMETIC;
break;
case ':' :
transitionIndex = TRANS_COLON;
break;
case '=' :
transitionIndex = TRANS_EQUAL;
break;
case '<' :
transitionIndex = TRANS_LESSER;
break;
case '>' :
transitionIndex = TRANS_GREATER;
break;
case '_' :
transitionIndex = TRANS_UNDERSCORE;
break;
case '\'' :
transitionIndex = TRANS_SQUOTE;
break;
case '\\' :
transitionIndex = TRANS_BACKSLASH;
case '"' :
transitionIndex = TRANS_DQUOTE;
break;
case '.' :
transitionIndex = TRANS_DOT;
break;
default :
transitionIndex = TRANS_ANY;
break;
}
}
return transitionIndex;
}
int Scanner::getMaxTokens() const
{
return m_nTokens;
}
int Scanner::getTokensProcessed() const
{
return m_nTokensProcessed;
}
bool Scanner::isTerminalState(int state)
{
switch (state)
{
case 1 :
case 2 :
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 11 :
case 13 :
case 14 :
case 16 :
case 18 :
case 19 :
case 22 :
case 23 :
case 24 :
case 25 :
case 26 :
case 27 :
case 28 :
case 29 :
case 33 :
case 35 :
case 36 :
case 37 :
return true;
break;
}
return false;
}
void Scanner::buildKeywordsMap()
{
m_keywordsMap["alfanumerico"] = KEYWORD_ALPHANUM;
m_keywordsMap["canal"] = KEYWORD_CHANNEL;
m_keywordsMap["caracter"] = KEYWORD_CHAR;
m_keywordsMap["caso"] = KEYWORD_CASE;
m_keywordsMap["const"] = KEYWORD_CONST;
m_keywordsMap["continua"] = KEYWORD_CONTINUE;
m_keywordsMap["defecto"] = KEYWORD_DEFAULT;
m_keywordsMap["desde"] = KEYWORD_FOR;
m_keywordsMap["diferir"] = KEYWORD_DIFFER;
m_keywordsMap["div"] = KEYWORD_DIV;
m_keywordsMap["entero"] = KEYWORD_INT;
m_keywordsMap["enteros"] = KEYWORD_UINT;
m_keywordsMap["estructura"] = KEYWORD_STRUCT;
m_keywordsMap["funcion"] = KEYWORD_FUNCTION;
m_keywordsMap["importar"] = KEYWORD_IMPORT;
m_keywordsMap["interfaz"] = KEYWORD_INTERFACE;
m_keywordsMap["interrumpe"] = KEYWORD_BREAK;
m_keywordsMap["ir"] = KEYWORD_GO;
m_keywordsMap["ir_a"] = KEYWORD_GOTO;
m_keywordsMap["logico"] = KEYWORD_LOGIC;
m_keywordsMap["mapa"] = KEYWORD_MAP;
m_keywordsMap["mod"] = KEYWORD_MOD;
m_keywordsMap["paquete"] = KEYWORD_PACKET;
m_keywordsMap["principal"] = KEYWORD_MAIN;
m_keywordsMap["rango"] = KEYWORD_RANGE;
m_keywordsMap["real"] = KEYWORD_REAL;
m_keywordsMap["regresa"] = KEYWORD_RETURN;
m_keywordsMap["si"] = KEYWORD_IF;
m_keywordsMap["sino"] = KEYWORD_ELSE;
m_keywordsMap["selecciona"] = KEYWORD_SELECT;
m_keywordsMap["tipo"] = KEYWORD_TYPE;
m_keywordsMap["valor"] = KEYWORD_SWITCH;
m_keywordsMap["var"] = KEYWORD_VAR;
}
<commit_msg>changed state error messge in scan()<commit_after>/* Definition of member functions of class Scanner */
#include "../headers/Scanner.hpp"
#include <string>
#include <sstream>
#ifdef DEBUG
# include <iostream>
# include <iomanip>
#endif
using namespace std;
Scanner::Scanner(FileReader* fileReader, ErrorReporter* errorReporter) :
m_lineNo(1),
m_column(1),
m_currentToken(0),
m_nTokens(0),
m_nTokensProcessed(0),
m_tokensLexemes(),
m_keywordsMap(),
m_errorReporter(errorReporter),
m_fileReader(fileReader)
{
buildKeywordsMap();
}
void Scanner::scan()
{
if (m_fileReader->getTotalLines() > 0)
{
char currentChar;
int nextState = 0, currentState = 0;
TokenType_t token;
string lexeme;
string line;
size_t lineLength;
m_lineNo = 1;
while (m_lineNo <= m_fileReader->getTotalLines() &&
m_errorReporter->getErrors() < m_errorReporter->getMaxErrors())
{
line = m_fileReader->getTextAtLine(m_lineNo - 1);
lineLength = line.length();
m_column = 1;
while (m_column <= lineLength &&
m_errorReporter->getErrors() <= m_errorReporter->getMaxErrors())
{
currentChar = line.at(m_column - 1);
nextState = automata[currentState][getTransitionIndex(currentChar)];
#ifdef DEBUG
cout << "CState: " << setw(2) << currentState << " NState: " <<
setw(2) << nextState << " TIndex: " <<
setw(2) << getTransitionIndex(currentChar) <<
" Char: ";
if (!isspace(currentChar))
cout << currentChar;
else
cout << ' ';
cout << " : " << setw(3) << (int)currentChar << endl;
#endif
if (nextState == STATE_ACCEPT_ERROR)
{
switch (currentState)
{
case 1 :
case 2 : token = TOKEN_OCT;
break;
case 4 :
token = TOKEN_HEX;
break;
case 5 :
token = TOKEN_DEC;
break;
case 6 :
case 11 :
token = TOKEN_FLOAT;
break;
case 7 :
case 26 :
token = TOKEN_DELIMITER;
break;
case 8 :
token = TOKEN_FLOAT;
break;
case 13 :
token = TOKEN_STRING;
break;
case 14 :
case 19 :
token = TOKEN_ARITHOP;
break;
case 16 :
token = TOKEN_LINECOMMENT;
break;
case 18 :
token = TOKEN_MULTICOMMENT;
break;
case 22 :
case 24 :
token = TOKEN_LOGICOP;
break;
case 23 :
case 27 :
token = TOKEN_ASSIGNOP;
break;
case 25 :
case 35 :
case 36 :
token = TOKEN_RELOP;
break;
case 28 :
token = TOKEN_IDEN;
if (m_keywordsMap.find(lexeme) != m_keywordsMap.end())
{
token = TOKEN_KEYWORD;
}
else if (lexeme.compare("verdadero") == 0 ||
lexeme.compare("falso") == 0)
{
token = TOKEN_LOGICCONST;
}
break;
case 29 :
token = TOKEN_DELIMITER;
break;
case 33 :
token = TOKEN_CHARCONST;
break;
case 37 :
token = TOKEN_NEWLINE;
break;
default :
#ifdef DEBUG
cerr << "vecomp: next state error while scanning" << endl;
#endif
break;
}
if (token != TOKEN_LINECOMMENT && token != TOKEN_MULTICOMMENT)
{
m_tokensLexemes.push_back(TokenLexeme(token, lexeme, m_lineNo,
m_column - lexeme.length()));
#ifdef DEBUG
cout << "pushed element: " << setw(20) <<
TokenLexeme::getTokenString(token) << ": " << setw(20) <<
lexeme << " at: " << m_lineNo << ", " <<
m_column - lexeme.length() << endl;
#endif
}
token = TOKEN_INVALID;
lexeme = "";
nextState = 0;
--m_column;
}
else if (nextState == STATE_ERROR)
{
#ifdef DEBUG
cout << "calling lexicalerror" << currentState << " " <<
currentChar << endl;
#endif
m_errorReporter->writeLexicalError(currentState, currentChar, lexeme,
m_lineNo, m_column);
token = TOKEN_INVALID;
lexeme = "";
nextState = 0;
}
else if ( isspace(currentChar) &&
(currentState == 12 || currentState == 15 ||
currentState == 17))
lexeme += currentChar;
else if (!isspace(currentChar))
lexeme += currentChar;
currentState = nextState;
++m_column;
}
++m_lineNo;
line = "";
}
#ifdef DEBUG
cout << "final state: " << currentState << endl;
#endif
if (currentState != 0 && !isTerminalState(currentState))
m_errorReporter->writeLexicalError(currentState, currentChar, lexeme,
m_lineNo, m_column);
m_nTokens = m_tokensLexemes.size();
if (m_tokensLexemes.empty())
{
m_errorReporter->writeError("archivo vacio");
}
}
}
void Scanner::moveTokenBackward()
{
--m_currentToken;
}
void Scanner::moveTokenForward()
{
++m_currentToken;
}
TokenLexeme Scanner::getNextTokenLexeme()
{
TokenLexeme temporal;
if (!m_tokensLexemes.empty())
{
temporal = m_tokensLexemes.at(m_currentToken);
}
#ifdef DEBUG
cout << "::: returning token at: " << m_currentToken << ", " <<
m_tokensLexemes.at(m_currentToken).getLexeme() << endl;
#endif
moveTokenForward();
++m_nTokensProcessed;
return temporal;
}
Transition_t Scanner::getTransitionIndex(char character)
{
Transition_t transitionIndex = TRANS_ANY;
if (isdigit(character))
{
if (character == '0')
transitionIndex = TRANS_ZERO;
else if (character <= '7')
transitionIndex = TRANS_OCT;
else
transitionIndex = TRANS_DEC;
}
else if (isalpha(character))
{
if (tolower(character) == 'e')
transitionIndex = TRANS_E;
else if (tolower(character) == 'x')
transitionIndex = TRANS_X;
else if (tolower(character) <= 'f')
transitionIndex = TRANS_HEX;
else
transitionIndex = TRANS_LETTER;
}
else
{
switch (character)
{
case '|' :
transitionIndex = TRANS_PIPE;
break;
case '&' :
transitionIndex = TRANS_AMPERS;
break;
case '!' :
transitionIndex = TRANS_EXCLAMATION;
break;
case ' ' :
case '\t' :
case '\r' :
transitionIndex = TRANS_SPACE;
break;
case '\n' :
transitionIndex = TRANS_NEWLINE;
break;
case ',' :
case ';' :
case '(' :
case ')' :
case '[' :
case ']' :
case '{' :
case '}' :
transitionIndex = TRANS_DELIMITER;
break;
case '+' :
case '-' :
transitionIndex = TRANS_SIGN;
break;
case '*' :
transitionIndex = TRANS_ASTERISK;
break;
case '/' :
transitionIndex = TRANS_SLASH;
break;
case '%' :
case '^' :
transitionIndex = TRANS_ARITHMETIC;
break;
case ':' :
transitionIndex = TRANS_COLON;
break;
case '=' :
transitionIndex = TRANS_EQUAL;
break;
case '<' :
transitionIndex = TRANS_LESSER;
break;
case '>' :
transitionIndex = TRANS_GREATER;
break;
case '_' :
transitionIndex = TRANS_UNDERSCORE;
break;
case '\'' :
transitionIndex = TRANS_SQUOTE;
break;
case '\\' :
transitionIndex = TRANS_BACKSLASH;
case '"' :
transitionIndex = TRANS_DQUOTE;
break;
case '.' :
transitionIndex = TRANS_DOT;
break;
default :
transitionIndex = TRANS_ANY;
break;
}
}
return transitionIndex;
}
int Scanner::getMaxTokens() const
{
return m_nTokens;
}
int Scanner::getTokensProcessed() const
{
return m_nTokensProcessed;
}
bool Scanner::isTerminalState(int state)
{
switch (state)
{
case 1 :
case 2 :
case 4 :
case 5 :
case 6 :
case 7 :
case 8 :
case 11 :
case 13 :
case 14 :
case 16 :
case 18 :
case 19 :
case 22 :
case 23 :
case 24 :
case 25 :
case 26 :
case 27 :
case 28 :
case 29 :
case 33 :
case 35 :
case 36 :
case 37 :
return true;
break;
}
return false;
}
void Scanner::buildKeywordsMap()
{
m_keywordsMap["alfanumerico"] = KEYWORD_ALPHANUM;
m_keywordsMap["canal"] = KEYWORD_CHANNEL;
m_keywordsMap["caracter"] = KEYWORD_CHAR;
m_keywordsMap["caso"] = KEYWORD_CASE;
m_keywordsMap["const"] = KEYWORD_CONST;
m_keywordsMap["continua"] = KEYWORD_CONTINUE;
m_keywordsMap["defecto"] = KEYWORD_DEFAULT;
m_keywordsMap["desde"] = KEYWORD_FOR;
m_keywordsMap["diferir"] = KEYWORD_DIFFER;
m_keywordsMap["div"] = KEYWORD_DIV;
m_keywordsMap["entero"] = KEYWORD_INT;
m_keywordsMap["enteros"] = KEYWORD_UINT;
m_keywordsMap["estructura"] = KEYWORD_STRUCT;
m_keywordsMap["funcion"] = KEYWORD_FUNCTION;
m_keywordsMap["importar"] = KEYWORD_IMPORT;
m_keywordsMap["interfaz"] = KEYWORD_INTERFACE;
m_keywordsMap["interrumpe"] = KEYWORD_BREAK;
m_keywordsMap["ir"] = KEYWORD_GO;
m_keywordsMap["ir_a"] = KEYWORD_GOTO;
m_keywordsMap["logico"] = KEYWORD_LOGIC;
m_keywordsMap["mapa"] = KEYWORD_MAP;
m_keywordsMap["mod"] = KEYWORD_MOD;
m_keywordsMap["paquete"] = KEYWORD_PACKET;
m_keywordsMap["principal"] = KEYWORD_MAIN;
m_keywordsMap["rango"] = KEYWORD_RANGE;
m_keywordsMap["real"] = KEYWORD_REAL;
m_keywordsMap["regresa"] = KEYWORD_RETURN;
m_keywordsMap["si"] = KEYWORD_IF;
m_keywordsMap["sino"] = KEYWORD_ELSE;
m_keywordsMap["selecciona"] = KEYWORD_SELECT;
m_keywordsMap["tipo"] = KEYWORD_TYPE;
m_keywordsMap["valor"] = KEYWORD_SWITCH;
m_keywordsMap["var"] = KEYWORD_VAR;
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param s input string
* @return the longest palindromic substring
*/
string longestPalindrome(string& s) {
string T = preProcess(s);
const int n = T.length();
vector<int> P(n);
int C = 0, R = 0;
for (int i = 1; i < n - 1; ++i) {
int i_mirror = 2 * C - i; // equals to i' = C - (i-C)
P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) {
++P[i];
}
// If palindrome centered at i expand past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
// Find the maximum element in P.
int max_len = 0, center_index = 0;
for (int i = 1; i < n - 1; ++i) {
if (P[i] > max_len) {
max_len = P[i];
center_index = i;
}
}
return s.substr((center_index - 1 - max_len) / 2, max_len);
}
private:
string preProcess(const string& s) {
if (s.empty()) {
return "^$";
}
string ret = "^";
for (int i = 0; i < s.length(); ++i) {
ret += "#" + s.substr(i, 1);
}
ret += "#$";
return ret;
}
};
<commit_msg>Update longest-palindromic-substring.cpp<commit_after>// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param s input string
* @return the longest palindromic substring
*/
string longestPalindrome(string& s) {
string T = preProcess(s);
const int n = T.length();
vector<int> P(n);
int C = 0, R = 0;
for (int i = 1; i < n - 1; ++i) {
int i_mirror = 2 * C - i; // equals to i' = C - (i-C)
P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) {
++P[i];
}
// If palindrome centered at i expands the past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
// Find the maximum element in P.
int max_len = 0, center_index = 0;
for (int i = 1; i < n - 1; ++i) {
if (P[i] > max_len) {
max_len = P[i];
center_index = i;
}
}
return s.substr((center_index - 1 - max_len) / 2, max_len);
}
private:
string preProcess(const string& s) {
if (s.empty()) {
return "^$";
}
string ret = "^";
for (int i = 0; i < s.length(); ++i) {
ret += "#" + s.substr(i, 1);
}
ret += "#$";
return ret;
}
};
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at [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 version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QtTest/qtestspontaneevent.h>
#include <QDesktopWidget>
#include "tascoreutils.h"
#include "tastoucheventgenerator.h"
#include "taslogger.h"
int TasTouchEventGenerator::mTouchPointCounter = 0;
TasTouchEventGenerator::TasTouchEventGenerator(QObject* parent)
:QObject(parent)
{
}
TasTouchEventGenerator::~TasTouchEventGenerator()
{
}
void TasTouchEventGenerator::doTouchBegin(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchBegin(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchUpdate(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchEnd(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchEnd(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchBegin(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointPressed, points, identifier);
QTouchEvent* touchPress = new QTouchEvent(QEvent::TouchBegin, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointPressed, touchPoints);
touchPress->setWidget(target);
sendTouchEvent(target, touchPress);
}
void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointMoved, points, identifier);
QTouchEvent* touchMove = new QTouchEvent(QEvent::TouchUpdate, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointMoved, touchPoints);
touchMove->setWidget(target);
sendTouchEvent(target, touchMove);
}
void TasTouchEventGenerator::doTouchEnd(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointReleased, points, identifier);
QTouchEvent *touchRelease = new QTouchEvent(QEvent::TouchEnd, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointReleased, touchPoints);
touchRelease->setWidget(target);
sendTouchEvent(target, touchRelease);
}
void TasTouchEventGenerator::sendTouchEvent(QWidget* target, QTouchEvent* event)
{
QSpontaneKeyEvent::setSpontaneous(event);
qApp->postEvent(target, event);
qApp->processEvents();
}
QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(TargetData targetData, Qt::TouchPointState state)
{
return convertToTouchPoints(targetData.target, state, toTouchPoints(targetData.targetPoint, false),
TasCoreUtils::pointerId(targetData.targetItem));
}
QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(QWidget* target, Qt::TouchPointState state,
QList<TasTouchPoints> points, QString identifier)
{
QList<QVariant> pointIds;
if(!identifier.isEmpty()) {
QVariant pointStore = qApp->property(identifier.toAscii());
if(pointStore.isValid()){
pointIds = pointStore.toList();
}
}
QList<QTouchEvent::TouchPoint> touchPoints;
if(!points.isEmpty()){
for(int i = 0 ; i < points.size() ; i++){
if(pointIds.size() <= i ){
mTouchPointCounter++;
pointIds.append(QVariant(mTouchPointCounter));
}
touchPoints.append(makeTouchPoint(target, points.at(i), state, pointIds.at(i).toInt()));
}
}
if(state == Qt::TouchPointReleased){
qApp->setProperty(identifier.toAscii(), QVariant());
mTouchPointCounter = 0;
}
else if(!identifier.isEmpty()){
//we store the point id to the app as property
//this allows new gestures to use the ids when needed
qApp->setProperty(identifier.toAscii(), QVariant(pointIds));
}
return touchPoints;
}
QTouchEvent::TouchPoint TasTouchEventGenerator::makeTouchPoint(QWidget* target, TasTouchPoints points,
Qt::TouchPointState state, int id)
{
QTouchEvent::TouchPoint touchPoint(id);
Qt::TouchPointStates states = state;
if(points.isPrimary){
states |= Qt::TouchPointPrimary;
}
touchPoint.setPressure(1.0);
touchPoint.setState(states);
touchPoint.setPos(target->mapFromGlobal(points.screenPoint));
touchPoint.setScreenPos(points.screenPoint);
QRect screenGeometry = QApplication::desktop()->screenGeometry(points.screenPoint);
touchPoint.setNormalizedPos(QPointF(points.screenPoint.x() / screenGeometry.width(),
points.screenPoint.y() / screenGeometry.height()));
//in addition to the position we also need to set last and start positions as
//some gesture may depend on them
if(!points.lastScreenPoint.isNull()){
touchPoint.setLastPos(target->mapFromGlobal(points.lastScreenPoint));
touchPoint.setLastScreenPos(points.lastScreenPoint);
touchPoint.setLastNormalizedPos(QPointF(points.lastScreenPoint.x() / screenGeometry.width(),
points.lastScreenPoint.y() / screenGeometry.height()));
}
if(!points.startScreenPoint.isNull()){
touchPoint.setStartPos(target->mapFromGlobal(points.startScreenPoint));
touchPoint.setStartScreenPos(points.startScreenPoint);
touchPoint.setStartNormalizedPos(QPointF(points.startScreenPoint.x() / screenGeometry.width(),
points.startScreenPoint.y() / screenGeometry.height()));
}
return touchPoint;
}
QList<TasTouchPoints> TasTouchEventGenerator::toTouchPoints(QPoint point, bool primary)
{
QList<TasTouchPoints> points;
points.append(toTouchPoint(point, primary));
return points;
}
TasTouchPoints TasTouchEventGenerator::toTouchPoint(QPoint point, bool primary)
{
TasTouchPoints touchPoint;
touchPoint.screenPoint = point;
touchPoint.isPrimary = primary;
return touchPoint;
}
bool TasTouchEventGenerator::areIdentical(QList<TasTouchPoints> points1, QList<TasTouchPoints> points2)
{
if(points1.size() != points2.size()){
return false;
}
//loop points to detect differences
for(int i = 0 ; i < points1.size() ; i++){
TasTouchPoints t = points1.at(i);
TasTouchPoints p = points2.at(i);
if(p.screenPoint != t.screenPoint || t.lastScreenPoint != p.lastScreenPoint ||
p.startScreenPoint != t.startScreenPoint){
return false;
}
}
return true;
}
<commit_msg>set primary point for id 0<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at [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 version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QtTest/qtestspontaneevent.h>
#include <QDesktopWidget>
#include "tascoreutils.h"
#include "tastoucheventgenerator.h"
#include "taslogger.h"
int TasTouchEventGenerator::mTouchPointCounter = 0;
TasTouchEventGenerator::TasTouchEventGenerator(QObject* parent)
:QObject(parent)
{
}
TasTouchEventGenerator::~TasTouchEventGenerator()
{
}
void TasTouchEventGenerator::doTouchBegin(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchBegin(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchUpdate(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchEnd(QWidget* target, QPoint point, bool primary, QString identifier)
{
doTouchEnd(target, toTouchPoints(point,primary), identifier);
}
void TasTouchEventGenerator::doTouchBegin(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointPressed, points, identifier);
QTouchEvent* touchPress = new QTouchEvent(QEvent::TouchBegin, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointPressed, touchPoints);
touchPress->setWidget(target);
sendTouchEvent(target, touchPress);
}
void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointMoved, points, identifier);
QTouchEvent* touchMove = new QTouchEvent(QEvent::TouchUpdate, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointMoved, touchPoints);
touchMove->setWidget(target);
sendTouchEvent(target, touchMove);
}
void TasTouchEventGenerator::doTouchEnd(QWidget* target, QList<TasTouchPoints> points, QString identifier)
{
QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointReleased, points, identifier);
QTouchEvent *touchRelease = new QTouchEvent(QEvent::TouchEnd, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointReleased, touchPoints);
touchRelease->setWidget(target);
sendTouchEvent(target, touchRelease);
}
void TasTouchEventGenerator::sendTouchEvent(QWidget* target, QTouchEvent* event)
{
QSpontaneKeyEvent::setSpontaneous(event);
qApp->postEvent(target, event);
qApp->processEvents();
}
QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(TargetData targetData, Qt::TouchPointState state)
{
return convertToTouchPoints(targetData.target, state, toTouchPoints(targetData.targetPoint, false),
TasCoreUtils::pointerId(targetData.targetItem));
}
QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(QWidget* target, Qt::TouchPointState state,
QList<TasTouchPoints> points, QString identifier)
{
QList<QVariant> pointIds;
if(!identifier.isEmpty()) {
QVariant pointStore = qApp->property(identifier.toAscii());
if(pointStore.isValid()){
pointIds = pointStore.toList();
}
}
QList<QTouchEvent::TouchPoint> touchPoints;
if(!points.isEmpty()){
for(int i = 0 ; i < points.size() ; i++){
if(pointIds.size() <= i ){
mTouchPointCounter++;
pointIds.append(QVariant(mTouchPointCounter));
}
touchPoints.append(makeTouchPoint(target, points.at(i), state, pointIds.at(i).toInt()-1));
}
}
if(state == Qt::TouchPointReleased){
qApp->setProperty(identifier.toAscii(), QVariant());
mTouchPointCounter = 0;
}
else if(!identifier.isEmpty()){
//we store the point id to the app as property
//this allows new gestures to use the ids when needed
qApp->setProperty(identifier.toAscii(), QVariant(pointIds));
}
return touchPoints;
}
QTouchEvent::TouchPoint TasTouchEventGenerator::makeTouchPoint(QWidget* target, TasTouchPoints points,
Qt::TouchPointState state, int id)
{
TasLogger::logger()->debug("TasTouchEventGenerator:: generating point with id: " +
QString::number(id));
QTouchEvent::TouchPoint touchPoint(id);
Qt::TouchPointStates states = state;
if(points.isPrimary || id == 0){
TasLogger::logger()->debug("TasTouchEventGenerator:: is primary");
states |= Qt::TouchPointPrimary;
}
touchPoint.setPressure(1.0);
touchPoint.setState(states);
touchPoint.setPos(target->mapFromGlobal(points.screenPoint));
touchPoint.setScreenPos(points.screenPoint);
QRect screenGeometry = QApplication::desktop()->screenGeometry(points.screenPoint);
touchPoint.setNormalizedPos(QPointF(points.screenPoint.x() / screenGeometry.width(),
points.screenPoint.y() / screenGeometry.height()));
//in addition to the position we also need to set last and start positions as
//some gesture may depend on them
if(!points.lastScreenPoint.isNull()){
touchPoint.setLastPos(target->mapFromGlobal(points.lastScreenPoint));
touchPoint.setLastScreenPos(points.lastScreenPoint);
touchPoint.setLastNormalizedPos(QPointF(points.lastScreenPoint.x() / screenGeometry.width(),
points.lastScreenPoint.y() / screenGeometry.height()));
}
if(!points.startScreenPoint.isNull()){
touchPoint.setStartPos(target->mapFromGlobal(points.startScreenPoint));
touchPoint.setStartScreenPos(points.startScreenPoint);
touchPoint.setStartNormalizedPos(QPointF(points.startScreenPoint.x() / screenGeometry.width(),
points.startScreenPoint.y() / screenGeometry.height()));
}
return touchPoint;
}
QList<TasTouchPoints> TasTouchEventGenerator::toTouchPoints(QPoint point, bool primary)
{
QList<TasTouchPoints> points;
points.append(toTouchPoint(point, primary));
return points;
}
TasTouchPoints TasTouchEventGenerator::toTouchPoint(QPoint point, bool primary)
{
TasTouchPoints touchPoint;
touchPoint.screenPoint = point;
touchPoint.isPrimary = primary;
return touchPoint;
}
bool TasTouchEventGenerator::areIdentical(QList<TasTouchPoints> points1, QList<TasTouchPoints> points2)
{
if(points1.size() != points2.size()){
return false;
}
//loop points to detect differences
for(int i = 0 ; i < points1.size() ; i++){
TasTouchPoints t = points1.at(i);
TasTouchPoints p = points2.at(i);
if(p.screenPoint != t.screenPoint || t.lastScreenPoint != p.lastScreenPoint ||
p.startScreenPoint != t.startScreenPoint){
return false;
}
}
return true;
}
<|endoftext|> |
<commit_before><commit_msg>add two-points-radius circles<commit_after><|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <algorithm>
// template <class PopulationIterator, class SampleIterator, class Distance,
// class UniformRandomNumberGenerator>
// SampleIterator sample(PopulationIterator first, PopulationIterator last,
// SampleIterator out, Distance n,
// UniformRandomNumberGenerator &&g);
#include <algorithm>
#include <random>
#include <cassert>
#include "test_iterators.h"
struct ReservoirSampleExpectations {
enum { os = 4 };
static int oa1[os];
static int oa2[os];
};
int ReservoirSampleExpectations::oa1[] = {10, 5, 9, 4};
int ReservoirSampleExpectations::oa2[] = {5, 2, 10, 4};
struct SelectionSampleExpectations {
enum { os = 4 };
static int oa1[os];
static int oa2[os];
};
int SelectionSampleExpectations::oa1[] = {1, 4, 6, 7};
int SelectionSampleExpectations::oa2[] = {1, 2, 6, 8};
template <class IteratorCategory> struct TestExpectations
: public SelectionSampleExpectations {};
template <>
struct TestExpectations<std::input_iterator_tag>
: public ReservoirSampleExpectations {};
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
typedef TestExpectations<typename std::iterator_traits<
PopulationIterator>::iterator_category> Expectations;
const unsigned os = Expectations::os;
SampleItem oa[os];
const int *oa1 = Expectations::oa1;
const int *oa2 = Expectations::oa2;
std::minstd_rand g;
SampleIterator end;
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, g);
assert(end.base() - oa == std::min(os, is));
assert(std::equal(oa, oa + os, oa1));
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, std::move(g));
assert(end.base() - oa == std::min(os, is));
assert(std::equal(oa, oa + os, oa2));
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_empty_population() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {42};
const unsigned os = 4;
SampleItem oa[os];
std::minstd_rand g;
SampleIterator end =
std::sample(PopulationIterator(ia), PopulationIterator(ia),
SampleIterator(oa), os, g);
assert(end.base() == oa);
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_empty_sample() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
SampleItem oa[1];
std::minstd_rand g;
SampleIterator end =
std::sample(PopulationIterator(ia), PopulationIterator(ia + is),
SampleIterator(oa), 0, g);
assert(end.base() == oa);
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_small_population() {
// The population size is less than the sample size.
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
const unsigned os = 8;
SampleItem oa[os];
const SampleItem oa1[] = {1, 2, 3, 4, 5};
std::minstd_rand g;
SampleIterator end;
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, g);
assert(end.base() - oa == std::min(os, is));
assert(std::equal(oa, end.base(), oa1));
}
int main() {
test<input_iterator, int, random_access_iterator, int>();
test<forward_iterator, int, output_iterator, int>();
test<forward_iterator, int, random_access_iterator, int>();
test<input_iterator, int, random_access_iterator, double>();
test<forward_iterator, int, output_iterator, double>();
test<forward_iterator, int, random_access_iterator, double>();
test_empty_population<input_iterator, int, random_access_iterator, int>();
test_empty_population<forward_iterator, int, output_iterator, int>();
test_empty_population<forward_iterator, int, random_access_iterator, int>();
test_empty_sample<input_iterator, int, random_access_iterator, int>();
test_empty_sample<forward_iterator, int, output_iterator, int>();
test_empty_sample<forward_iterator, int, random_access_iterator, int>();
test_small_population<input_iterator, int, random_access_iterator, int>();
test_small_population<forward_iterator, int, output_iterator, int>();
test_small_population<forward_iterator, int, random_access_iterator, int>();
}
<commit_msg>[libcxx] [test] D26816: Fix non-Standard assumptions when testing sample().<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <algorithm>
// template <class PopulationIterator, class SampleIterator, class Distance,
// class UniformRandomNumberGenerator>
// SampleIterator sample(PopulationIterator first, PopulationIterator last,
// SampleIterator out, Distance n,
// UniformRandomNumberGenerator &&g);
#include <algorithm>
#include <random>
#include <type_traits>
#include <cassert>
#include "test_iterators.h"
#include "test_macros.h"
struct ReservoirSampleExpectations {
enum { os = 4 };
static int oa1[os];
static int oa2[os];
};
int ReservoirSampleExpectations::oa1[] = {10, 5, 9, 4};
int ReservoirSampleExpectations::oa2[] = {5, 2, 10, 4};
struct SelectionSampleExpectations {
enum { os = 4 };
static int oa1[os];
static int oa2[os];
};
int SelectionSampleExpectations::oa1[] = {1, 4, 6, 7};
int SelectionSampleExpectations::oa2[] = {1, 2, 6, 8};
template <class IteratorCategory> struct TestExpectations
: public SelectionSampleExpectations {};
template <>
struct TestExpectations<std::input_iterator_tag>
: public ReservoirSampleExpectations {};
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
typedef TestExpectations<typename std::iterator_traits<
PopulationIterator>::iterator_category> Expectations;
const unsigned os = Expectations::os;
SampleItem oa[os];
const int *oa1 = Expectations::oa1;
((void)oa1); // Prevent unused warning
const int *oa2 = Expectations::oa2;
((void)oa2); // Prevent unused warning
std::minstd_rand g;
SampleIterator end;
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, g);
assert(end.base() - oa == std::min(os, is));
// sample() is deterministic but non-reproducible;
// its results can vary between implementations.
LIBCPP_ASSERT(std::equal(oa, oa + os, oa1));
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, std::move(g));
assert(end.base() - oa == std::min(os, is));
LIBCPP_ASSERT(std::equal(oa, oa + os, oa2));
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_empty_population() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {42};
const unsigned os = 4;
SampleItem oa[os];
std::minstd_rand g;
SampleIterator end =
std::sample(PopulationIterator(ia), PopulationIterator(ia),
SampleIterator(oa), os, g);
assert(end.base() == oa);
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_empty_sample() {
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
SampleItem oa[1];
std::minstd_rand g;
SampleIterator end =
std::sample(PopulationIterator(ia), PopulationIterator(ia + is),
SampleIterator(oa), 0, g);
assert(end.base() == oa);
}
template <template<class...> class PopulationIteratorType, class PopulationItem,
template<class...> class SampleIteratorType, class SampleItem>
void test_small_population() {
// The population size is less than the sample size.
typedef PopulationIteratorType<PopulationItem *> PopulationIterator;
typedef SampleIteratorType<SampleItem *> SampleIterator;
PopulationItem ia[] = {1, 2, 3, 4, 5};
const unsigned is = sizeof(ia) / sizeof(ia[0]);
const unsigned os = 8;
SampleItem oa[os];
const SampleItem oa1[] = {1, 2, 3, 4, 5};
std::minstd_rand g;
SampleIterator end;
end = std::sample(PopulationIterator(ia),
PopulationIterator(ia + is),
SampleIterator(oa), os, g);
assert(end.base() - oa == std::min(os, is));
typedef typename std::iterator_traits<PopulationIterator>::iterator_category PopulationCategory;
if (std::is_base_of<std::forward_iterator_tag, PopulationCategory>::value) {
assert(std::equal(oa, end.base(), oa1));
} else {
assert(std::is_permutation(oa, end.base(), oa1));
}
}
int main() {
test<input_iterator, int, random_access_iterator, int>();
test<forward_iterator, int, output_iterator, int>();
test<forward_iterator, int, random_access_iterator, int>();
test<input_iterator, int, random_access_iterator, double>();
test<forward_iterator, int, output_iterator, double>();
test<forward_iterator, int, random_access_iterator, double>();
test_empty_population<input_iterator, int, random_access_iterator, int>();
test_empty_population<forward_iterator, int, output_iterator, int>();
test_empty_population<forward_iterator, int, random_access_iterator, int>();
test_empty_sample<input_iterator, int, random_access_iterator, int>();
test_empty_sample<forward_iterator, int, output_iterator, int>();
test_empty_sample<forward_iterator, int, random_access_iterator, int>();
test_small_population<input_iterator, int, random_access_iterator, int>();
test_small_population<forward_iterator, int, output_iterator, int>();
test_small_population<forward_iterator, int, random_access_iterator, int>();
}
<|endoftext|> |
<commit_before>
/**
* @file BallDetector.cpp
*
* Implementation of class BallDetector
*
*/
#include "BallDetector.h"
#include "Tools/DataStructures/ArrayQueue.h"
#include "Tools/CameraGeometry.h"
#include <Representations/Infrastructure/CameraInfoConstants.h>
#include "Tools/Math/Geometry.h"
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include "Tools/ImageProcessing/MaximumScan.h"
#include "Tools/ImageProcessing/Filter.h"
BallDetector::BallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeakScanFull", "mark the scanned points in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeakScan", "mark the scanned points in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeak", "mark found maximum red peak in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:drawScanlines", "", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:drawScanEndPoints", "", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:draw_ball_estimated","..", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:draw_ball","..", false);
getDebugParameterList().add(¶ms);
}
BallDetector::~BallDetector()
{
getDebugParameterList().remove(¶ms);
}
void BallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallPercept().reset();
// STEP 1: find the starting point for the search
listOfRedPoints.clear();
//??? single condition
if(!findMaximumRedPoint(listOfRedPoints) || listOfRedPoints.empty()) {
return;
}
bool ballFound = false;
//NOTE: the points are sorted - the most red points are at the end
double radius = -1;
Vector2d center;
//Liste von rotenPunkten durchgehen
for(int i = (int)listOfRedPoints.size()-1; i >= 0 ; i--)
{
const Vector2i& point = listOfRedPoints[i];
// the point is within the previously calculated ball
if(radius > 0 && radius*radius*2 > (center - Vector2d(point)).abs2()) {
continue;
}
//3d Projection -> Aus der Entfernung der Punktes die ungefhre Ballposition berechenen
double estimatedRadius = estimatedBallRadius(point);
DEBUG_REQUEST("Vision:BallDetector:draw_ball_estimated",
//estimatedRadius <=0 possible? will be a problem in "radius < 2*estimatedRadius"
if(estimatedRadius > 0) {
CIRCLE_PX(ColorClasses::white, point.x, point.y, (int)(estimatedRadius+0.5));
}
);
///***********///
ballEndPoints.clear();
bool goodBallCandidateFound = spiderScan(point, ballEndPoints);
if(goodBallCandidateFound && Geometry::calculateCircle(ballEndPoints, center, radius) && radius > 0 && radius < 2*estimatedRadius)
{
ballFound = true;
calculateBallPercept(center, radius);
break;
}
}
if(ballFound) {
/*
Vector2d betterCenter;
double betterRadius;
ckecknearBall(center, betterCenter, betterRadius);
calculateBallPercept(betterCenter, betterRadius);
*/
//calculateBallPercept(center, radius);
}
}
bool BallDetector::findMaximumRedPoint(std::vector<Vector2i>& points) const
{
//
// STEP I: find the maximal height minY to be scanned in the image
//
if(!getFieldPercept().valid) {
return false;
}
const FieldPercept::FieldPoly& fieldPolygon = getFieldPercept().getValidField();
// find the top point of the polygon
int minY = getImage().height();
for(int i = 0; i < fieldPolygon.length ; i++)
{
if(fieldPolygon.points[i].y < minY && fieldPolygon.points[i].y >= 0) {
minY = fieldPolygon.points[i].y;
}
}
// double check: polygon is empty
if(minY == (int)getImage().height() || minY < 0) {
return false;
}
//
// STEP II: calculate the step size for the scan
//
int stepSizeAdjusted = params.stepSize;
if(getCameraMatrix().rotation.getYAngle() > Math::fromDegrees(40))
{
stepSizeAdjusted *= 3;
}
else if(getCameraMatrix().rotation.getYAngle() > Math::fromDegrees(10))
{
stepSizeAdjusted *= 2;
}
int maxRedPeak = getFieldColorPercept().range.getMax().v; // initialize with the maximal red croma of the field color
Vector2i point;
Pixel pixel;
Vector2i redPeak;
for(point.y = (int) (getImage().height() - 3); point.y > minY; point.y -= stepSizeAdjusted) {
for(point.x = 0; point.x < (int) getImage().width(); point.x += stepSizeAdjusted)
{
getImage().get(point.x, point.y, pixel);
DEBUG_REQUEST("Vision:BallDetector:markPeakScanFull",
POINT_PX(ColorClasses::blue, point.x, point.y);
);
if
(
maxRedPeak < pixel.v && // "v" is the croma RED channel
isOrange(pixel) &&
fieldPolygon.isInside_inline(point) // only points inside the field polygon
//&& !getGoalPostHistograms().isPostColor(pixel) // ball is not goal like colored
//&& getGoalPostHistograms().histogramV.mean + params.minOffsetToGoalV < pixel.v
)
{
//if(ckecknearBall(point) > 1)
{
maxRedPeak = (int)pixel.v;
redPeak = point;
points.push_back(point);
}
}
DEBUG_REQUEST("Vision:BallDetector:markPeakScan",
if
(
isOrange(pixel) &&
fieldPolygon.isInside_inline(point) // only points inside the field polygon
)
{
POINT_PX(ColorClasses::red, point.x, point.y);
}
);
}
}
DEBUG_REQUEST("Vision:BallDetector:markPeak",
LINE_PX(ColorClasses::skyblue, redPeak.x-10, redPeak.y, redPeak.x+10, redPeak.y);
LINE_PX(ColorClasses::skyblue, redPeak.x, redPeak.y-10, redPeak.x, redPeak.y+10);
CIRCLE_PX(ColorClasses::white, redPeak.x, redPeak.y, 5);
);
// maxRedPeak is larger than its initial value
return maxRedPeak > getFieldColorPercept().range.getMax().v;
}
bool BallDetector::spiderScan(const Vector2i& start, std::vector<Vector2i>& endPoints) const
{
int goodBorderPointCount = 0;
goodBorderPointCount += scanForEdges(start, Vector2d( 1, 0), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1, 0), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 0, 1), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 0,-1), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 1, 1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1, 1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 1,-1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1,-1).normalize(), endPoints);
DEBUG_REQUEST("Vision:BallDetector:drawScanEndPoints",
for(size_t i = 0; i < endPoints.size(); i++)
{
ColorClasses::Color col = ColorClasses::green;
if(goodBorderPointCount == 0)
{
col = ColorClasses::red;
}
POINT_PX(col, endPoints[i].x, endPoints[i].y);
}
);
return goodBorderPointCount != 0;
}
bool BallDetector::scanForEdges(const Vector2i& start, const Vector2d& direction, std::vector<Vector2i>& points) const
{
Vector2i point(start);
BresenhamLineScan scanner(point, direction, getImage().cameraInfo);
// initialize the scanner
Vector2i peak_point_min(start);
MaximumScan<Vector2i,double> negativeScan(peak_point_min, params.thresholdGradientUV);
Filter<Prewitt3x1, Vector2i, double, 3> filter;
Pixel pixel;
double stepLength = 0;
Vector2i lastPoint(point); // needed for step length
//int max_length = 6;
//int i = 0;
while(scanner.getNextWithCheck(point)) // i < max_length*/)
{
getImage().get(point.x, point.y, pixel);
int f_y = (int)pixel.v - (int)pixel.u;
// hack
/*
if(pixel.v < getFieldColorPercept().range.getMax().v)
i++;
else
i = 0;
*/
filter.add(point, f_y);
if(!filter.ready()) {
// assume the step length is constant, so we only calculate it in the starting phase of the filter
stepLength += Vector2d(point - lastPoint).abs();
lastPoint = point;
ASSERT(stepLength > 0);
continue;
}
DEBUG_REQUEST("Vision:BallDetector:drawScanlines",
POINT_PX(ColorClasses::blue, point.x, point.y);
);
// jump down found
// NOTE: we scale the filter value with the stepLength to acount for diagonal scans
if(negativeScan.add(filter.point(), -filter.value()/stepLength))
{
DEBUG_REQUEST("Vision:BallDetector:drawScanlines",
POINT_PX(ColorClasses::pink, peak_point_min.x, peak_point_min.y);
);
points.push_back(peak_point_min);
return pixel.y < params.maxBorderBrightness;
}
}//end while
return false; //getFieldColorPercept().isFieldColor(pixel);
}//end scanForEdges
void BallDetector::calculateBallPercept(const Vector2i& center, double radius)
{
// calculate the ball
bool projectionOK = CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
getFieldInfo().ballRadius,
getBallPercept().bearingBasedOffsetOnField);
// HACK: don't take to far balls
projectionOK = projectionOK && getBallPercept().bearingBasedOffsetOnField.abs2() < 10000*10000; // closer than 10m
// HACK: if the ball center is in image it has to be in the field polygon
Vector2d ballPointToCheck(center.x, center.y - 5);
projectionOK = projectionOK &&
(!getImage().isInside((int)(ballPointToCheck.x+0.5), (int)(ballPointToCheck.y+0.5)) ||
getFieldPercept().getValidField().isInside(ballPointToCheck));
if(projectionOK)
{
getBallPercept().radiusInImage = radius;
getBallPercept().centerInImage = center;
getBallPercept().ballWasSeen = projectionOK;
getBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
DEBUG_REQUEST("Vision:BallDetector:draw_ball",
CIRCLE_PX(ColorClasses::orange, center.x, center.y, (int)(radius+0.5));
);
}
}
double BallDetector::estimatedBallRadius(const Vector2i& point) const
{
Vector2d pointOnField;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
point.x,
point.y,
getFieldInfo().ballRadius,
pointOnField))
{
return -1;
}
Vector3d d = getCameraMatrix()*Vector3d(pointOnField.x, pointOnField.y, getFieldInfo().ballRadius);
double cameraBallDistance = d.abs();
if(cameraBallDistance > getFieldInfo().ballRadius) {
double a = asin(getFieldInfo().ballRadius / d.abs());
return a / getImage().cameraInfo.getOpeningAngleHeight() * getImage().cameraInfo.resolutionHeight;
}
return -1;
}
void BallDetector::estimateCircleSimple(const std::vector<Vector2i>& endPoints, Vector2d& center, double& radius) const
{
Vector2d sum;
for(size_t i = 0; i < endPoints.size(); i++) {
sum += endPoints[i];
}
center = sum/((double)endPoints.size());
RingBufferWithSum<double, 8> radiusBuffer;
for(size_t i = 0; i < endPoints.size(); i++) {
radiusBuffer.add((center - Vector2d(endPoints[i])).abs2());
}
radius = sqrt(radiusBuffer.getAverage());
}
<commit_msg>small cleanup<commit_after>
/**
* @file BallDetector.cpp
*
* Implementation of class BallDetector
*
*/
#include "BallDetector.h"
#include "Tools/DataStructures/ArrayQueue.h"
#include "Tools/CameraGeometry.h"
#include <Representations/Infrastructure/CameraInfoConstants.h>
#include "Tools/Math/Geometry.h"
#include "Tools/ImageProcessing/BresenhamLineScan.h"
#include "Tools/ImageProcessing/MaximumScan.h"
#include "Tools/ImageProcessing/Filter.h"
BallDetector::BallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeakScanFull", "mark the scanned points in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeakScan", "mark the scanned points in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:markPeak", "mark found maximum red peak in image", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:drawScanlines", "", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:drawScanEndPoints", "", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:draw_ball_estimated","..", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:draw_ball_radius_match", "..", false);
DEBUG_REQUEST_REGISTER("Vision:BallDetector:draw_ball","..", false);
getDebugParameterList().add(¶ms);
}
BallDetector::~BallDetector()
{
getDebugParameterList().remove(¶ms);
}
void BallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallPercept().reset();
// STEP 1: find the starting point for the search
listOfRedPoints.clear();
//??? single condition
if(!findMaximumRedPoint(listOfRedPoints) || listOfRedPoints.empty()) {
return;
}
bool ballFound = false;
//NOTE: the points are sorted - the most red points are at the end
double radius = -1;
Vector2d center;
//Liste von rotenPunkten durchgehen
for(int i = (int)listOfRedPoints.size()-1; i >= 0 ; i--)
{
const Vector2i& point = listOfRedPoints[i];
// the point is within the previously calculated ball
if(radius > 0 && radius*radius*2 > (center - Vector2d(point)).abs2()) {
continue;
}
//3d Projection -> Aus der Entfernung der Punktes die ungefhre Ballposition berechenen
double estimatedRadius = estimatedBallRadius(point);
DEBUG_REQUEST("Vision:BallDetector:draw_ball_estimated",
//estimatedRadius <=0 possible? will be a problem in "radius < 2*estimatedRadius"
if(estimatedRadius > 0) {
CIRCLE_PX(ColorClasses::white, point.x, point.y, (int)(estimatedRadius+0.5));
}
);
ballEndPoints.clear();
bool goodBallCandidateFound = spiderScan(point, ballEndPoints);
if(goodBallCandidateFound && Geometry::calculateCircle(ballEndPoints, center, radius))
{
DEBUG_REQUEST("Vision:BallDetector:draw_ball_radius_match",
CIRCLE_PX(ColorClasses::yellow, (int)(center.x+0.5), (int)(center.y+0.5), (int)(radius+0.5));
);
if(radius > 0 && radius < 2*estimatedRadius) {
ballFound = true;
calculateBallPercept(center, radius);
break;
}
}
}
if(ballFound) {
/*
Vector2d betterCenter;
double betterRadius;
ckecknearBall(center, betterCenter, betterRadius);
calculateBallPercept(betterCenter, betterRadius);
*/
//calculateBallPercept(center, radius);
}
}
bool BallDetector::findMaximumRedPoint(std::vector<Vector2i>& points) const
{
//
// STEP I: find the maximal height minY to be scanned in the image
//
if(!getFieldPercept().valid) {
return false;
}
const FieldPercept::FieldPoly& fieldPolygon = getFieldPercept().getValidField();
// find the top point of the polygon
int minY = getImage().height();
for(int i = 0; i < fieldPolygon.length ; i++)
{
if(fieldPolygon.points[i].y < minY && fieldPolygon.points[i].y >= 0) {
minY = fieldPolygon.points[i].y;
}
}
// double check: polygon is empty
if(minY == (int)getImage().height() || minY < 0) {
return false;
}
//
// STEP II: calculate the step size for the scan
//
int stepSizeAdjusted = params.stepSize;
if(getCameraMatrix().rotation.getYAngle() > Math::fromDegrees(40))
{
stepSizeAdjusted *= 3;
}
else if(getCameraMatrix().rotation.getYAngle() > Math::fromDegrees(10))
{
stepSizeAdjusted *= 2;
}
int maxRedPeak = getFieldColorPercept().range.getMax().v; // initialize with the maximal red croma of the field color
Vector2i point;
Pixel pixel;
Vector2i redPeak;
for(point.y = (int) (getImage().height() - 3); point.y > minY; point.y -= stepSizeAdjusted) {
for(point.x = 0; point.x < (int) getImage().width(); point.x += stepSizeAdjusted)
{
getImage().get(point.x, point.y, pixel);
DEBUG_REQUEST("Vision:BallDetector:markPeakScanFull",
POINT_PX(ColorClasses::blue, point.x, point.y);
);
if
(
maxRedPeak < pixel.v && // "v" is the croma RED channel
isOrange(pixel) &&
fieldPolygon.isInside_inline(point) // only points inside the field polygon
//&& !getGoalPostHistograms().isPostColor(pixel) // ball is not goal like colored
//&& getGoalPostHistograms().histogramV.mean + params.minOffsetToGoalV < pixel.v
)
{
//if(ckecknearBall(point) > 1)
{
maxRedPeak = (int)pixel.v;
redPeak = point;
points.push_back(point);
}
}
DEBUG_REQUEST("Vision:BallDetector:markPeakScan",
if
(
isOrange(pixel) &&
fieldPolygon.isInside_inline(point) // only points inside the field polygon
)
{
POINT_PX(ColorClasses::red, point.x, point.y);
}
);
}
}
DEBUG_REQUEST("Vision:BallDetector:markPeak",
LINE_PX(ColorClasses::skyblue, redPeak.x-10, redPeak.y, redPeak.x+10, redPeak.y);
LINE_PX(ColorClasses::skyblue, redPeak.x, redPeak.y-10, redPeak.x, redPeak.y+10);
CIRCLE_PX(ColorClasses::white, redPeak.x, redPeak.y, 5);
);
// maxRedPeak is larger than its initial value
return maxRedPeak > getFieldColorPercept().range.getMax().v;
}
bool BallDetector::spiderScan(const Vector2i& start, std::vector<Vector2i>& endPoints) const
{
int goodBorderPointCount = 0;
goodBorderPointCount += scanForEdges(start, Vector2d( 1, 0), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1, 0), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 0, 1), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 0,-1), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 1, 1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1, 1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d( 1,-1).normalize(), endPoints);
goodBorderPointCount += scanForEdges(start, Vector2d(-1,-1).normalize(), endPoints);
DEBUG_REQUEST("Vision:BallDetector:drawScanEndPoints",
for(size_t i = 0; i < endPoints.size(); i++)
{
ColorClasses::Color col = ColorClasses::green;
if(goodBorderPointCount == 0)
{
col = ColorClasses::red;
}
POINT_PX(col, endPoints[i].x, endPoints[i].y);
}
);
return goodBorderPointCount > 0;
}
bool BallDetector::scanForEdges(const Vector2i& start, const Vector2d& direction, std::vector<Vector2i>& points) const
{
Vector2i point(start);
BresenhamLineScan scanner(point, direction, getImage().cameraInfo);
// initialize the scanner
Vector2i peak_point_min(start);
MaximumScan<Vector2i,double> negativeScan(peak_point_min, params.thresholdGradientUV);
Filter<Prewitt3x1, Vector2i, double, 3> filter;
Pixel pixel;
double stepLength = 0;
Vector2i lastPoint(point); // needed for step length
//int max_length = 6;
//int i = 0;
while(scanner.getNextWithCheck(point)) // i < max_length*/)
{
getImage().get(point.x, point.y, pixel);
int f_y = (int)pixel.v - (int)pixel.u;
// hack
/*
if(pixel.v < getFieldColorPercept().range.getMax().v)
i++;
else
i = 0;
*/
filter.add(point, f_y);
if(!filter.ready()) {
// assume the step length is constant, so we only calculate it in the starting phase of the filter
stepLength += Vector2d(point - lastPoint).abs();
lastPoint = point;
ASSERT(stepLength > 0);
continue;
}
DEBUG_REQUEST("Vision:BallDetector:drawScanlines",
POINT_PX(ColorClasses::blue, point.x, point.y);
);
// jump down found
// NOTE: we scale the filter value with the stepLength to acount for diagonal scans
if(negativeScan.add(filter.point(), -filter.value()/stepLength))
{
DEBUG_REQUEST("Vision:BallDetector:drawScanlines",
POINT_PX(ColorClasses::pink, peak_point_min.x, peak_point_min.y);
);
points.push_back(peak_point_min);
return pixel.y < params.maxBorderBrightness;
}
}//end while
return false; //getFieldColorPercept().isFieldColor(pixel);
}//end scanForEdges
void BallDetector::calculateBallPercept(const Vector2i& center, double radius)
{
// calculate the ball
bool projectionOK = CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
getFieldInfo().ballRadius,
getBallPercept().bearingBasedOffsetOnField);
// HACK: don't take to far balls
projectionOK = projectionOK && getBallPercept().bearingBasedOffsetOnField.abs2() < 10000*10000; // closer than 10m
// HACK: if the ball center is in image it has to be in the field polygon
Vector2d ballPointToCheck(center.x, center.y - 5);
projectionOK = projectionOK &&
(!getImage().isInside((int)(ballPointToCheck.x+0.5), (int)(ballPointToCheck.y+0.5)) ||
getFieldPercept().getValidField().isInside(ballPointToCheck));
if(projectionOK)
{
getBallPercept().radiusInImage = radius;
getBallPercept().centerInImage = center;
getBallPercept().ballWasSeen = projectionOK;
getBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
DEBUG_REQUEST("Vision:BallDetector:draw_ball",
CIRCLE_PX(ColorClasses::orange, center.x, center.y, (int)(radius+0.5));
);
}
}
double BallDetector::estimatedBallRadius(const Vector2i& point) const
{
Vector2d pointOnField;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
point.x,
point.y,
getFieldInfo().ballRadius,
pointOnField))
{
return -1;
}
Vector3d d = getCameraMatrix()*Vector3d(pointOnField.x, pointOnField.y, getFieldInfo().ballRadius);
double cameraBallDistance = d.abs();
if(cameraBallDistance > getFieldInfo().ballRadius) {
double a = asin(getFieldInfo().ballRadius / d.abs());
return a / getImage().cameraInfo.getOpeningAngleHeight() * getImage().cameraInfo.resolutionHeight;
}
return -1;
}
void BallDetector::estimateCircleSimple(const std::vector<Vector2i>& endPoints, Vector2d& center, double& radius) const
{
Vector2d sum;
for(size_t i = 0; i < endPoints.size(); i++) {
sum += endPoints[i];
}
center = sum/((double)endPoints.size());
RingBufferWithSum<double, 8> radiusBuffer;
for(size_t i = 0; i < endPoints.size(); i++) {
radiusBuffer.add((center - Vector2d(endPoints[i])).abs2());
}
radius = sqrt(radiusBuffer.getAverage());
}
<|endoftext|> |
<commit_before>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. 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.
********************************************************************/
#include "monte_carlo_renderer.h"
#include "Output/clwoutput.h"
#include "Estimators/estimator.h"
#include <numeric>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <random>
#include <algorithm>
#include "Utils/sobol.h"
#include "math/int2.h"
#ifdef RR_EMBED_KERNELS
#include "./Kernels/CL/cache/kernels.h"
#endif
namespace Baikal
{
using namespace RadeonRays;
int constexpr kTileSizeX = 1920;
int constexpr kTileSizeY = 1080;
// Constructor
MonteCarloRenderer::MonteCarloRenderer(
CLWContext context,
std::unique_ptr<Estimator> estimator,
std::string const& cache_path
)
: Baikal::ClwClass(context, "../Baikal/Kernels/CL/monte_carlo_renderer.cl", "", cache_path)
, m_estimator(std::move(estimator))
, m_sample_counter(0u)
{
m_estimator->SetWorkBufferSize(kTileSizeX * kTileSizeY);
}
void MonteCarloRenderer::Clear(RadeonRays::float3 const& val, Output& output) const
{
static_cast<ClwOutput&>(output).Clear(val);
m_sample_counter = 0u;
}
void MonteCarloRenderer::Render(ClwScene const& scene)
{
auto output = FindFirstNonZeroOutput();
if (!output)
{
if (GetOutput(OutputType::kVisibility))
{
throw std::runtime_error("Visibility AOV requires color AOV to be set");
}
else
{
throw std::runtime_error("No outputs set");
}
}
auto output_size = int2(output->width(), output->height());
if (output_size.x > kTileSizeX || output_size.y > kTileSizeY)
{
auto num_tiles_x = (output_size.x + kTileSizeX - 1) / kTileSizeX;
auto num_tiles_y = (output_size.y + kTileSizeY - 1) / kTileSizeY;
for (auto x = 0; x < num_tiles_x; ++x)
for (auto y = 0; y < num_tiles_y; ++y)
{
auto tile_offset = int2(x * kTileSizeX, y * kTileSizeY);
auto tile_size = int2(std::min(kTileSizeX, output_size.x - tile_offset.x),
std::min(kTileSizeY, output_size.y - tile_offset.y));
RenderTile(scene, tile_offset, tile_size);
}
}
else
{
RenderTile(scene, int2(), output_size);
}
++m_sample_counter;
}
// Render the scene into the output
void MonteCarloRenderer::RenderTile(ClwScene const& scene, int2 const& tile_origin, int2 const& tile_size)
{
// Number of rays to generate
auto output = static_cast<ClwOutput*>(GetOutput(OutputType::kColor));
if (output)
{
auto num_rays = tile_size.x * tile_size.y;
auto output_size = int2(output->width(), output->height());
GenerateTileDomain(output_size, tile_origin, tile_size);
GeneratePrimaryRays(scene, *output, tile_size);
m_estimator->Estimate(
scene,
num_rays,
Estimator::QualityLevel::kStandard,
output->data());
}
// Check if we have other outputs, than color
bool aov_pass_needed = (FindFirstNonZeroOutput(false) != nullptr);
if (aov_pass_needed)
{
FillAOVs(scene, tile_origin, tile_size);
GetContext().Flush(0);
}
}
void MonteCarloRenderer::GenerateTileDomain(
int2 const& output_size,
int2 const& tile_origin,
int2 const& tile_size
)
{
// Fetch kernel
CLWKernel generate_kernel = GetKernel("GenerateTileDomain");
// Set kernel parameters
int argc = 0;
generate_kernel.SetArg(argc++, output_size.x);
generate_kernel.SetArg(argc++, output_size.y);
generate_kernel.SetArg(argc++, tile_origin.x);
generate_kernel.SetArg(argc++, tile_origin.y);
generate_kernel.SetArg(argc++, tile_size.x);
generate_kernel.SetArg(argc++, tile_size.y);
generate_kernel.SetArg(argc++, rand_uint());
generate_kernel.SetArg(argc++, m_sample_counter);
generate_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
generate_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
generate_kernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
generate_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
// Run shading kernel
{
size_t gs[] = { static_cast<size_t>((tile_size.x + 15) / 16 * 16), static_cast<size_t>((tile_size.y + 15) / 16 * 16) };
size_t ls[] = { 16, 16 };
GetContext().Launch2D(0, gs, ls, generate_kernel);
}
}
Output* MonteCarloRenderer::FindFirstNonZeroOutput(bool include_color) const
{
// Find first non-zero output
auto current_output = include_color ? GetOutput(Renderer::OutputType::kColor) : nullptr;
if (!current_output)
{
for (auto i = 1U; i < static_cast<std::uint32_t>(Renderer::OutputType::kVisibility); ++i)
{
current_output = GetOutput(static_cast<Renderer::OutputType>(i));
if (current_output)
{
break;
}
}
}
return current_output;
}
void MonteCarloRenderer::SetOutput(OutputType type, Output* output)
{
if (type == OutputType::kVisibility)
{
if (!m_estimator->SupportsIntermediateValue(Estimator::IntermediateValue::kVisibility))
{
throw std::runtime_error("Visibility AOV not supported by an underlying estimator");
}
auto clw_output = static_cast<ClwOutput*>(output);
m_estimator->SetIntermediateValueBuffer(Estimator::IntermediateValue::kVisibility, clw_output->data());
}
Renderer::SetOutput(type, output);
}
void MonteCarloRenderer::FillAOVs(ClwScene const& scene, int2 const& tile_origin, int2 const& tile_size)
{
// Find first non-zero AOV to get buffer dimensions
auto output = FindFirstNonZeroOutput();
auto output_size = int2(output->width(), output->height());
// Generate tile domain
GenerateTileDomain(output_size, tile_origin, tile_size);
// Generate primary
GeneratePrimaryRays(scene, *output, tile_size, true);
auto num_rays = tile_size.x * tile_size.y;
// Intersect ray batch
m_estimator->TraceFirstHit(scene, num_rays);
CLWKernel fill_kernel = GetKernel("FillAOVs");
auto argc = 0U;
fill_kernel.SetArg(argc++, m_estimator->GetRayBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetFirstHitBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
fill_kernel.SetArg(argc++, scene.vertices);
fill_kernel.SetArg(argc++, scene.normals);
fill_kernel.SetArg(argc++, scene.uvs);
fill_kernel.SetArg(argc++, scene.indices);
fill_kernel.SetArg(argc++, scene.shapes);
fill_kernel.SetArg(argc++, scene.materialids);
fill_kernel.SetArg(argc++, scene.materials);
fill_kernel.SetArg(argc++, scene.textures);
fill_kernel.SetArg(argc++, scene.texturedata);
fill_kernel.SetArg(argc++, scene.envmapidx);
fill_kernel.SetArg(argc++, scene.lights);
fill_kernel.SetArg(argc++, scene.num_lights);
fill_kernel.SetArg(argc++, rand_uint());
fill_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
fill_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
fill_kernel.SetArg(argc++, m_sample_counter);
for (auto i = 1U; i < static_cast<std::uint32_t>(Renderer::OutputType::kMax); ++i)
{
if (auto aov = static_cast<ClwOutput*>(GetOutput(static_cast<Renderer::OutputType>(i))))
{
fill_kernel.SetArg(argc++, 1);
fill_kernel.SetArg(argc++, aov->data());
}
else
{
fill_kernel.SetArg(argc++, 0);
// This is simply a dummy buffer
fill_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
}
}
// Run AOV kernel
{
int globalsize = tile_size.x * tile_size.y;
GetContext().Launch1D(0, ((globalsize + 63) / 64) * 64, 64, fill_kernel);
}
}
void MonteCarloRenderer::GeneratePrimaryRays(
ClwScene const& scene,
Output const& output,
int2 const& tile_size,
bool generate_at_pixel_center
)
{
// Fetch kernel
std::string kernel_name = (scene.camera_type == CameraType::kDefault) ? "PerspectiveCamera_GeneratePaths" : "PerspectiveCameraDof_GeneratePaths";
auto genkernel = GetKernel(kernel_name, generate_at_pixel_center ? " -D BAIKAL_GENERATE_SAMPLE_AT_PIXEL_CENTER " : "");
// Set kernel parameters
int argc = 0;
genkernel.SetArg(argc++, scene.camera);
genkernel.SetArg(argc++, output.width());
genkernel.SetArg(argc++, output.height());
genkernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
genkernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
genkernel.SetArg(argc++, (int)rand_uint());
genkernel.SetArg(argc++, m_sample_counter);
genkernel.SetArg(argc++, m_estimator->GetRayBuffer());
genkernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
genkernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
{
int globalsize = tile_size.x * tile_size.y;
GetContext().Launch1D(0, ((globalsize + 63) / 64) * 64, 64, genkernel);
}
}
CLWKernel MonteCarloRenderer::GetCopyKernel()
{
return GetKernel("ApplyGammaAndCopyData");
}
CLWKernel MonteCarloRenderer::GetAccumulateKernel()
{
return GetKernel("AccumulateData");
}
void MonteCarloRenderer::SetRandomSeed(std::uint32_t seed)
{
m_estimator->SetRandomSeed(seed);
}
void MonteCarloRenderer::Benchmark(ClwScene const& scene, Estimator::RayTracingStats& stats)
{
auto output = static_cast<ClwOutput*>(GetOutput(OutputType::kColor));
int num_rays = output->width() * output->height();
int2 tile_size = int2(output->width(), output->height());
GenerateTileDomain(tile_size, int2(), tile_size);
GeneratePrimaryRays(scene, *output, tile_size);
m_estimator->Benchmark(scene, num_rays, stats);
}
void MonteCarloRenderer::SetMaxBounces(std::uint32_t max_bounces)
{
m_estimator->SetMaxBounces(max_bounces);
}
}
<commit_msg>Fix AOV test on OSX<commit_after>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. 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.
********************************************************************/
#include "monte_carlo_renderer.h"
#include "Output/clwoutput.h"
#include "Estimators/estimator.h"
#include <numeric>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <random>
#include <algorithm>
#include "Utils/sobol.h"
#include "math/int2.h"
#ifdef RR_EMBED_KERNELS
#include "./Kernels/CL/cache/kernels.h"
#endif
namespace Baikal
{
using namespace RadeonRays;
int constexpr kTileSizeX = 1920;
int constexpr kTileSizeY = 1080;
// Constructor
MonteCarloRenderer::MonteCarloRenderer(
CLWContext context,
std::unique_ptr<Estimator> estimator,
std::string const& cache_path
)
: Baikal::ClwClass(context, "../Baikal/Kernels/CL/monte_carlo_renderer.cl", "", cache_path)
, m_estimator(std::move(estimator))
, m_sample_counter(0u)
{
m_estimator->SetWorkBufferSize(kTileSizeX * kTileSizeY);
}
void MonteCarloRenderer::Clear(RadeonRays::float3 const& val, Output& output) const
{
static_cast<ClwOutput&>(output).Clear(val);
m_sample_counter = 0u;
}
void MonteCarloRenderer::Render(ClwScene const& scene)
{
auto output = FindFirstNonZeroOutput();
if (!output)
{
if (GetOutput(OutputType::kVisibility))
{
throw std::runtime_error("Visibility AOV requires color AOV to be set");
}
else
{
throw std::runtime_error("No outputs set");
}
}
auto output_size = int2(output->width(), output->height());
if (output_size.x > kTileSizeX || output_size.y > kTileSizeY)
{
auto num_tiles_x = (output_size.x + kTileSizeX - 1) / kTileSizeX;
auto num_tiles_y = (output_size.y + kTileSizeY - 1) / kTileSizeY;
for (auto x = 0; x < num_tiles_x; ++x)
for (auto y = 0; y < num_tiles_y; ++y)
{
auto tile_offset = int2(x * kTileSizeX, y * kTileSizeY);
auto tile_size = int2(std::min(kTileSizeX, output_size.x - tile_offset.x),
std::min(kTileSizeY, output_size.y - tile_offset.y));
RenderTile(scene, tile_offset, tile_size);
}
}
else
{
RenderTile(scene, int2(), output_size);
}
++m_sample_counter;
}
// Render the scene into the output
void MonteCarloRenderer::RenderTile(ClwScene const& scene, int2 const& tile_origin, int2 const& tile_size)
{
// Number of rays to generate
auto output = static_cast<ClwOutput*>(GetOutput(OutputType::kColor));
if (output)
{
auto num_rays = tile_size.x * tile_size.y;
auto output_size = int2(output->width(), output->height());
GenerateTileDomain(output_size, tile_origin, tile_size);
GeneratePrimaryRays(scene, *output, tile_size);
m_estimator->Estimate(
scene,
num_rays,
Estimator::QualityLevel::kStandard,
output->data());
}
// Check if we have other outputs, than color
bool aov_pass_needed = (FindFirstNonZeroOutput(false) != nullptr);
if (aov_pass_needed)
{
FillAOVs(scene, tile_origin, tile_size);
GetContext().Flush(0);
}
}
void MonteCarloRenderer::GenerateTileDomain(
int2 const& output_size,
int2 const& tile_origin,
int2 const& tile_size
)
{
// Fetch kernel
CLWKernel generate_kernel = GetKernel("GenerateTileDomain");
// Set kernel parameters
int argc = 0;
generate_kernel.SetArg(argc++, output_size.x);
generate_kernel.SetArg(argc++, output_size.y);
generate_kernel.SetArg(argc++, tile_origin.x);
generate_kernel.SetArg(argc++, tile_origin.y);
generate_kernel.SetArg(argc++, tile_size.x);
generate_kernel.SetArg(argc++, tile_size.y);
generate_kernel.SetArg(argc++, rand_uint());
generate_kernel.SetArg(argc++, m_sample_counter);
generate_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
generate_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
generate_kernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
generate_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
// Run shading kernel
{
size_t gs[] = { static_cast<size_t>((tile_size.x + 15) / 16 * 16), static_cast<size_t>((tile_size.y + 15) / 16 * 16) };
size_t ls[] = { 16, 16 };
GetContext().Launch2D(0, gs, ls, generate_kernel);
}
}
Output* MonteCarloRenderer::FindFirstNonZeroOutput(bool include_color) const
{
// Find first non-zero output
auto current_output = include_color ? GetOutput(Renderer::OutputType::kColor) : nullptr;
if (!current_output)
{
for (auto i = 1U; i < static_cast<std::uint32_t>(Renderer::OutputType::kVisibility); ++i)
{
current_output = GetOutput(static_cast<Renderer::OutputType>(i));
if (current_output)
{
break;
}
}
}
return current_output;
}
void MonteCarloRenderer::SetOutput(OutputType type, Output* output)
{
if (type == OutputType::kVisibility)
{
if (!m_estimator->SupportsIntermediateValue(Estimator::IntermediateValue::kVisibility))
{
throw std::runtime_error("Visibility AOV not supported by an underlying estimator");
}
auto clw_output = static_cast<ClwOutput*>(output);
m_estimator->SetIntermediateValueBuffer(Estimator::IntermediateValue::kVisibility, clw_output->data());
}
Renderer::SetOutput(type, output);
}
void MonteCarloRenderer::FillAOVs(ClwScene const& scene, int2 const& tile_origin, int2 const& tile_size)
{
// Find first non-zero AOV to get buffer dimensions
auto output = FindFirstNonZeroOutput();
auto output_size = int2(output->width(), output->height());
// Generate tile domain
GenerateTileDomain(output_size, tile_origin, tile_size);
// Generate primary
GeneratePrimaryRays(scene, *output, tile_size, true);
auto num_rays = tile_size.x * tile_size.y;
// Intersect ray batch
m_estimator->TraceFirstHit(scene, num_rays);
CLWKernel fill_kernel = GetKernel("FillAOVs");
auto argc = 0U;
fill_kernel.SetArg(argc++, m_estimator->GetRayBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetFirstHitBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
fill_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
fill_kernel.SetArg(argc++, scene.vertices);
fill_kernel.SetArg(argc++, scene.normals);
fill_kernel.SetArg(argc++, scene.uvs);
fill_kernel.SetArg(argc++, scene.indices);
fill_kernel.SetArg(argc++, scene.shapes);
fill_kernel.SetArg(argc++, scene.materialids);
fill_kernel.SetArg(argc++, scene.materials);
fill_kernel.SetArg(argc++, scene.textures);
fill_kernel.SetArg(argc++, scene.texturedata);
fill_kernel.SetArg(argc++, scene.envmapidx);
fill_kernel.SetArg(argc++, scene.lights);
fill_kernel.SetArg(argc++, scene.num_lights);
fill_kernel.SetArg(argc++, rand_uint());
fill_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
fill_kernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
fill_kernel.SetArg(argc++, m_sample_counter);
for (auto i = 1U; i < static_cast<std::uint32_t>(Renderer::OutputType::kMax); ++i)
{
if (auto aov = static_cast<ClwOutput*>(GetOutput(static_cast<Renderer::OutputType>(i))))
{
fill_kernel.SetArg(argc++, 1);
fill_kernel.SetArg(argc++, aov->data());
}
else
{
fill_kernel.SetArg(argc++, 0);
// This is simply a dummy buffer
fill_kernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
}
}
// Run AOV kernel
{
int globalsize = tile_size.x * tile_size.y;
GetContext().Launch1D(0, ((globalsize + 63) / 64) * 64, 64, fill_kernel);
}
}
void MonteCarloRenderer::GeneratePrimaryRays(
ClwScene const& scene,
Output const& output,
int2 const& tile_size,
bool generate_at_pixel_center
)
{
// Fetch kernel
std::string kernel_name = (scene.camera_type == CameraType::kDefault) ? "PerspectiveCamera_GeneratePaths" : "PerspectiveCameraDof_GeneratePaths";
auto genkernel = GetKernel(kernel_name, generate_at_pixel_center ? "-D BAIKAL_GENERATE_SAMPLE_AT_PIXEL_CENTER " : "");
// Set kernel parameters
int argc = 0;
genkernel.SetArg(argc++, scene.camera);
genkernel.SetArg(argc++, output.width());
genkernel.SetArg(argc++, output.height());
genkernel.SetArg(argc++, m_estimator->GetOutputIndexBuffer());
genkernel.SetArg(argc++, m_estimator->GetRayCountBuffer());
genkernel.SetArg(argc++, (int)rand_uint());
genkernel.SetArg(argc++, m_sample_counter);
genkernel.SetArg(argc++, m_estimator->GetRayBuffer());
genkernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kRandomSeed));
genkernel.SetArg(argc++, m_estimator->GetRandomBuffer(Estimator::RandomBufferType::kSobolLUT));
{
int globalsize = tile_size.x * tile_size.y;
GetContext().Launch1D(0, ((globalsize + 63) / 64) * 64, 64, genkernel);
}
}
CLWKernel MonteCarloRenderer::GetCopyKernel()
{
return GetKernel("ApplyGammaAndCopyData");
}
CLWKernel MonteCarloRenderer::GetAccumulateKernel()
{
return GetKernel("AccumulateData");
}
void MonteCarloRenderer::SetRandomSeed(std::uint32_t seed)
{
m_estimator->SetRandomSeed(seed);
}
void MonteCarloRenderer::Benchmark(ClwScene const& scene, Estimator::RayTracingStats& stats)
{
auto output = static_cast<ClwOutput*>(GetOutput(OutputType::kColor));
int num_rays = output->width() * output->height();
int2 tile_size = int2(output->width(), output->height());
GenerateTileDomain(tile_size, int2(), tile_size);
GeneratePrimaryRays(scene, *output, tile_size);
m_estimator->Benchmark(scene, num_rays, stats);
}
void MonteCarloRenderer::SetMaxBounces(std::uint32_t max_bounces)
{
m_estimator->SetMaxBounces(max_bounces);
}
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkStlVolumeTimeSeriesReader.h"
#include "mitkSurface.h"
#include "vtkPolyData.h"
#include <mitkIOUtil.h>
void mitk::StlVolumeTimeSeriesReader::GenerateData()
{
if ( !this->GenerateFileList() )
{
itkWarningMacro( << "Sorry, file list could not be determined..." );
return ;
}
mitk::Surface::Pointer surface = this->GetOutput();
MITK_INFO << "prefix: "<< m_FilePrefix << ", pattern: " <<m_FilePattern << std::endl;
surface->Expand(m_MatchedFileNames.size());
for ( unsigned int i = 0 ; i < m_MatchedFileNames.size(); ++i )
{
std::string fileName = m_MatchedFileNames[i];
MITK_INFO << "Loading " << fileName << " as stl..." << std::endl;
mitk::Surface::Pointer surface = IOUtil::LoadSurface(fileName.c_str());
if (surface.IsNull())
{
itkWarningMacro(<< "stlReader returned NULL while reading " << fileName << ". Trying to continue with empty vtkPolyData...");
surface->SetVtkPolyData(vtkPolyData::New(), i);
return;
}
surface->SetVtkPolyData(surface->GetVtkPolyData(), i);
}
}
bool mitk::StlVolumeTimeSeriesReader::CanReadFile(const std::string /*filename*/, const std::string filePrefix, const std::string filePattern)
{
if( filePattern != "" && filePrefix != "" )
return false;
bool extensionFound = false;
std::string::size_type STLPos = filePattern.rfind(".stl");
if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4))
extensionFound = true;
STLPos = filePattern.rfind(".STL");
if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4))
extensionFound = true;
if( !extensionFound )
return false;
return true;
}
mitk::StlVolumeTimeSeriesReader::StlVolumeTimeSeriesReader()
{}
mitk::StlVolumeTimeSeriesReader::~StlVolumeTimeSeriesReader()
{}
<commit_msg>Fix and clearer names for surfaces in STLTimeSeriesReader<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkStlVolumeTimeSeriesReader.h"
#include "mitkSurface.h"
#include "vtkPolyData.h"
#include <mitkIOUtil.h>
void mitk::StlVolumeTimeSeriesReader::GenerateData()
{
if ( !this->GenerateFileList() )
{
itkWarningMacro( << "Sorry, file list could not be determined..." );
return ;
}
mitk::Surface::Pointer result = this->GetOutput();
MITK_INFO << "prefix: "<< m_FilePrefix << ", pattern: " <<m_FilePattern << std::endl;
result->Expand(m_MatchedFileNames.size());
for ( unsigned int i = 0 ; i < m_MatchedFileNames.size(); ++i )
{
std::string fileName = m_MatchedFileNames[i];
MITK_INFO << "Loading " << fileName << " as stl..." << std::endl;
mitk::Surface::Pointer timestepSurface = IOUtil::LoadSurface(fileName.c_str());
if (timestepSurface.IsNull())
{
itkWarningMacro(<< "stlReader returned NULL while reading " << fileName << ". Trying to continue with empty vtkPolyData...");
result->SetVtkPolyData(vtkPolyData::New(), i);
return;
}
result->SetVtkPolyData(timestepSurface->GetVtkPolyData(), i);
}
}
bool mitk::StlVolumeTimeSeriesReader::CanReadFile(const std::string /*filename*/, const std::string filePrefix, const std::string filePattern)
{
if( filePattern != "" && filePrefix != "" )
return false;
bool extensionFound = false;
std::string::size_type STLPos = filePattern.rfind(".stl");
if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4))
extensionFound = true;
STLPos = filePattern.rfind(".STL");
if ((STLPos != std::string::npos) && (STLPos == filePattern.length() - 4))
extensionFound = true;
if( !extensionFound )
return false;
return true;
}
mitk::StlVolumeTimeSeriesReader::StlVolumeTimeSeriesReader()
{}
mitk::StlVolumeTimeSeriesReader::~StlVolumeTimeSeriesReader()
{}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCGuildRedisModule.h
// @Author : LvSheng.Huang
// @Date : 2013-10-03
// @Module : NFCGuildRedisModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFCGuildRedisModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
#include "NFComm/NFPluginModule/NFINetModule.h"
NFCGuildRedisModule::NFCGuildRedisModule(NFIPluginManager * p)
{
pPluginManager = p;
}
bool NFCGuildRedisModule::Init()
{
return true;
}
bool NFCGuildRedisModule::Shut()
{
return true;
}
bool NFCGuildRedisModule::Execute()
{
return true;
}
bool NFCGuildRedisModule::AfterInit()
{
m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>();
m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>();
m_pCommonRedisModule = pPluginManager->FindModule<NFICommonRedisModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pKernelModule->AddClassCallBack(NFrame::Guild::ThisName(), this, &NFCGuildRedisModule::OnObjectClassEvent);
return true;
}
int NFCGuildRedisModule::OnObjectClassEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
switch (eClassEvent)
{
case CLASS_OBJECT_EVENT::COE_CREATE_FINISH:
{
NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self);
if (pSelf)
{
SetGuildCachePropertyInfo(self, pSelf->GetPropertyManager());
SetGuildCacheRecordManager(self, pSelf->GetRecordManager());
}
}
break;
default:
break;
}
return 0;
}
NF_SHARE_PTR<NFIPropertyManager> NFCGuildRedisModule::GetGuildCachePropertyInfo(const NFGUID& xGuid)
{
return m_pCommonRedisModule->GetCachePropertyInfo(xGuid, NFrame::Guild::ThisName());
}
bool NFCGuildRedisModule::GetGuildCachePropertyInfo(const std::vector<std::string>& xGuidList, std::vector<NF_SHARE_PTR<NFIPropertyManager>>& xPMList)
{
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetPropertyCacheKey(NFrame::Guild::ThisName());
std::vector<std::string> strValueList;
if (!pDriver->HMGet(strKey, xGuidList, strValueList))
{
return nullptr;
}
for (std::vector<std::string>::iterator it; it != strValueList.end(); ++it)
{
std::string& strValue = *it;
NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = m_pCommonRedisModule->NewPropertyManager(NFrame::Guild::ThisName());
if (!pPropertyManager.get())
{
continue;
}
NFMsg::ObjectPropertyList xMsg;
if (!xMsg.ParseFromString(strValue))
{
continue;
}
if (!m_pCommonRedisModule->ConvertPBToPropertyManager(xMsg, pPropertyManager))
{
continue;
}
xPMList.push_back(pPropertyManager);
}
return true;
}
NF_SHARE_PTR<NFIRecordManager> NFCGuildRedisModule::GetGuildCacheRecordManager(const NFGUID& xGuid)
{
NF_SHARE_PTR<NFIRecordManager> pRecordManager = m_pCommonRedisModule->NewRecordManager(NFrame::Guild::ThisName());
if (!pRecordManager.get())
{
return nullptr;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return nullptr;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
std::string strValue;
if (!pDriver->HGet(strKey, xGuid.ToString(), strValue))
{
return nullptr;
}
NFMsg::ObjectRecordList xMsg;
if (!xMsg.ParseFromString(strValue))
{
return nullptr;
}
if (!m_pCommonRedisModule->ConvertPBToRecordManager(xMsg, pRecordManager))
{
return nullptr;
}
return pRecordManager;
}
bool NFCGuildRedisModule::GetGuildCacheRecordManager(const std::vector<std::string>& xGuidList, std::vector<NF_SHARE_PTR<NFIRecordManager>>& xRMList)
{
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
std::vector<std::string> strValueList;
if (!pDriver->HMGet(strKey, xGuidList, strValueList))
{
return nullptr;
}
for (std::vector<std::string>::iterator it; it != strValueList.end(); ++it)
{
std::string& strValue = *it;
NF_SHARE_PTR<NFIRecordManager> pRecordManager = m_pCommonRedisModule->NewRecordManager(NFrame::Guild::ThisName());
if (!pRecordManager.get())
{
continue;
}
NFMsg::ObjectRecordList xMsg;
if (!xMsg.ParseFromString(strValue))
{
continue;
}
if (!m_pCommonRedisModule->ConvertPBToRecordManager(xMsg, pRecordManager))
{
continue;
}
xRMList.push_back(pRecordManager);
}
return true;
}
bool NFCGuildRedisModule::SetGuildCachePropertyInfo(const NFGUID& xGuid, NF_SHARE_PTR<NFIPropertyManager>& pPropertyManager)
{
if (xGuid.IsNull())
{
return false;
}
if (!pPropertyManager.get())
{
return false;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
NFMsg::ObjectPropertyList xMsg;
if (!m_pCommonRedisModule->ConvertPropertyManagerToPB(pPropertyManager, xMsg, true))
{
return false;
}
*xMsg.mutable_player_id() = NFINetModule::NFToPB(xGuid);
std::string strValue;
if (!xMsg.SerializeToString(&strValue))
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetPropertyCacheKey(NFrame::Guild::ThisName());
if (!pDriver->HSet(strKey, xGuid.ToString(), strValue))
{
return false;
}
return true;
}
bool NFCGuildRedisModule::SetGuildCacheRecordManager(const NFGUID& xGuid, NF_SHARE_PTR<NFIRecordManager>& pRecordManager)
{
if (xGuid.IsNull())
{
return false;
}
if (!pRecordManager.get())
{
return false;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
NFMsg::ObjectRecordList xMsg;
if (!m_pCommonRedisModule->ConvertRecordManagerToPB(pRecordManager, xMsg, true))
{
return false;
}
*xMsg.mutable_player_id() = NFINetModule::NFToPB(xGuid);
std::string strValue;
if (!xMsg.SerializeToString(&strValue))
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
if (!pDriver->HSet(strKey, xGuid.ToString(), strValue))
{
return false;
}
return true;
}
<commit_msg>fixed for compile<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCGuildRedisModule.h
// @Author : LvSheng.Huang
// @Date : 2013-10-03
// @Module : NFCGuildRedisModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFCGuildRedisModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"
#include "NFComm/NFPluginModule/NFINetModule.h"
NFCGuildRedisModule::NFCGuildRedisModule(NFIPluginManager * p)
{
pPluginManager = p;
}
bool NFCGuildRedisModule::Init()
{
return true;
}
bool NFCGuildRedisModule::Shut()
{
return true;
}
bool NFCGuildRedisModule::Execute()
{
return true;
}
bool NFCGuildRedisModule::AfterInit()
{
m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>();
m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>();
m_pCommonRedisModule = pPluginManager->FindModule<NFICommonRedisModule>();
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pKernelModule->AddClassCallBack(NFrame::Guild::ThisName(), this, &NFCGuildRedisModule::OnObjectClassEvent);
return true;
}
int NFCGuildRedisModule::OnObjectClassEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
switch (eClassEvent)
{
case CLASS_OBJECT_EVENT::COE_CREATE_FINISH:
{
NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self);
if (pSelf)
{
SetGuildCachePropertyInfo(self, pSelf->GetPropertyManager());
SetGuildCacheRecordManager(self, pSelf->GetRecordManager());
}
}
break;
default:
break;
}
return 0;
}
NF_SHARE_PTR<NFIPropertyManager> NFCGuildRedisModule::GetGuildCachePropertyInfo(const NFGUID& xGuid)
{
return m_pCommonRedisModule->GetCachePropertyInfo(xGuid, NFrame::Guild::ThisName());
}
bool NFCGuildRedisModule::GetGuildCachePropertyInfo(const std::vector<std::string>& xGuidList, std::vector<NF_SHARE_PTR<NFIPropertyManager>>& xPMList)
{
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetPropertyCacheKey(NFrame::Guild::ThisName());
std::vector<std::string> strValueList;
if (!pDriver->HMGet(strKey, xGuidList, strValueList))
{
return false;
}
for (std::vector<std::string>::iterator it; it != strValueList.end(); ++it)
{
std::string& strValue = *it;
NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = m_pCommonRedisModule->NewPropertyManager(NFrame::Guild::ThisName());
if (!pPropertyManager.get())
{
continue;
}
NFMsg::ObjectPropertyList xMsg;
if (!xMsg.ParseFromString(strValue))
{
continue;
}
if (!m_pCommonRedisModule->ConvertPBToPropertyManager(xMsg, pPropertyManager))
{
continue;
}
xPMList.push_back(pPropertyManager);
}
return true;
}
NF_SHARE_PTR<NFIRecordManager> NFCGuildRedisModule::GetGuildCacheRecordManager(const NFGUID& xGuid)
{
NF_SHARE_PTR<NFIRecordManager> pRecordManager = m_pCommonRedisModule->NewRecordManager(NFrame::Guild::ThisName());
if (!pRecordManager.get())
{
return nullptr;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return nullptr;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
std::string strValue;
if (!pDriver->HGet(strKey, xGuid.ToString(), strValue))
{
return nullptr;
}
NFMsg::ObjectRecordList xMsg;
if (!xMsg.ParseFromString(strValue))
{
return nullptr;
}
if (!m_pCommonRedisModule->ConvertPBToRecordManager(xMsg, pRecordManager))
{
return nullptr;
}
return pRecordManager;
}
bool NFCGuildRedisModule::GetGuildCacheRecordManager(const std::vector<std::string>& xGuidList, std::vector<NF_SHARE_PTR<NFIRecordManager>>& xRMList)
{
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
std::vector<std::string> strValueList;
if (!pDriver->HMGet(strKey, xGuidList, strValueList))
{
return false;
}
for (std::vector<std::string>::iterator it; it != strValueList.end(); ++it)
{
std::string& strValue = *it;
NF_SHARE_PTR<NFIRecordManager> pRecordManager = m_pCommonRedisModule->NewRecordManager(NFrame::Guild::ThisName());
if (!pRecordManager.get())
{
continue;
}
NFMsg::ObjectRecordList xMsg;
if (!xMsg.ParseFromString(strValue))
{
continue;
}
if (!m_pCommonRedisModule->ConvertPBToRecordManager(xMsg, pRecordManager))
{
continue;
}
xRMList.push_back(pRecordManager);
}
return true;
}
bool NFCGuildRedisModule::SetGuildCachePropertyInfo(const NFGUID& xGuid, NF_SHARE_PTR<NFIPropertyManager>& pPropertyManager)
{
if (xGuid.IsNull())
{
return false;
}
if (!pPropertyManager.get())
{
return false;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
NFMsg::ObjectPropertyList xMsg;
if (!m_pCommonRedisModule->ConvertPropertyManagerToPB(pPropertyManager, xMsg, true))
{
return false;
}
*xMsg.mutable_player_id() = NFINetModule::NFToPB(xGuid);
std::string strValue;
if (!xMsg.SerializeToString(&strValue))
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetPropertyCacheKey(NFrame::Guild::ThisName());
if (!pDriver->HSet(strKey, xGuid.ToString(), strValue))
{
return false;
}
return true;
}
bool NFCGuildRedisModule::SetGuildCacheRecordManager(const NFGUID& xGuid, NF_SHARE_PTR<NFIRecordManager>& pRecordManager)
{
if (xGuid.IsNull())
{
return false;
}
if (!pRecordManager.get())
{
return false;
}
NFINoSqlDriver* pDriver = m_pNoSqlModule->GetDriver();
if (!pDriver)
{
return false;
}
NFMsg::ObjectRecordList xMsg;
if (!m_pCommonRedisModule->ConvertRecordManagerToPB(pRecordManager, xMsg, true))
{
return false;
}
*xMsg.mutable_player_id() = NFINetModule::NFToPB(xGuid);
std::string strValue;
if (!xMsg.SerializeToString(&strValue))
{
return false;
}
const std::string strKey = m_pCommonRedisModule->GetRecordCacheKey(NFrame::Guild::ThisName());
if (!pDriver->HSet(strKey, xGuid.ToString(), strValue))
{
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "tst_request.h"
void TST_Request::test()
{
QTcpSocket socket;
CWF::QMapThreadSafety<QString, CWF::Session *> sessions;
CWF::Configuration configuration;
CWF::Request request(socket, sessions, configuration);
ClientTest client;
QMap<QByteArray, QByteArray> parameters({{"a", "Test"}, {"b", "Test"}, {"c", "true"},
{"d", ""}, {"e", ""}, {"f", "Test"}, {"g", "Test"},
{"h", "10"}, {"i", "10"}, {"j", "10"}, {"k", "10"},
{"l", "10"}, {"m", "10"}, {"n", "10"}, {"o", "10"},
{"p", "10"}, {"q", "10"}});
request.fillQObject(&client, parameters);
QVERIFY2(client.getA() == "Test", "Should be equal 'Test'");
QVERIFY2(client.getB() == "Test", "Should be equal 'Test'");
QVERIFY2(client.getC(), "Should return 'true'");
QVERIFY2(client.getD() == ' ', "Should be equal ' '");
QVERIFY2(client.getE() == ' ', "Should be equal ' '");
QVERIFY2(QString(client.getF()) == "Test", "Should be equal 'Test'");
QVERIFY2(QString((const char*)client.getG()) == "Test", "Should be equal 'Test'");
QVERIFY2(client.getH() == 10, "Should be equal 10");
QVERIFY2(client.getI() == 10, "Should be equal 10");
QVERIFY2(client.getJ() == 10, "Should be equal 10");
QVERIFY2(client.getK() == 10, "Should be equal 10");
QVERIFY2(client.getL() == 10, "Should be equal 10");
QVERIFY2(client.getM() == 10, "Should be equal 10");
QVERIFY2(client.getN() == 10, "Should be equal 10");
QVERIFY2(client.getO() == 10, "Should be equal 10");
QVERIFY2(client.getP() <= 10, "Should be <= 10");
QVERIFY2(client.getQ() <= 10, "Should be <= 10");
}
<commit_msg>Request test adjust<commit_after>#include "tst_request.h"
void TST_Request::test()
{
QTcpSocket socket;
CWF::QMapThreadSafety<QString, CWF::Session *> sessions;
CWF::Configuration configuration;
CWF::Request request(socket, sessions, configuration);
ClientTest client;
QMap<QByteArray, QByteArray> parameters({{"a", "Test"}, {"b", "Test"}, {"c", "true"},
{"d", ""}, {"e", ""}, {"f", "Test"}, {"g", "Test"},
{"h", "10"}, {"i", "10"}, {"j", "10"}, {"k", "10"},
{"l", "10"}, {"m", "10"}, {"n", "10"}, {"o", "10"},
{"p", "10"}, {"q", "10"}});
request.fillQObject(&client, parameters);
QVERIFY2(client.getA() == "Test", "Should be equal 'Test'");
QVERIFY2(client.getB() == "Test", "Should be equal 'Test'");
QVERIFY2(client.getC(), "Should return 'true'");
QVERIFY2(client.getD() == ' ', "Should be equal ' '");
QVERIFY2(client.getE() == ' ', "Should be equal ' '");
QVERIFY2(QString(client.getF()).contains("Test"), "Should be equal 'Test'");
QVERIFY2(QString((const char*)client.getG()).contains("Test"), "Should be equal 'Test'");
QVERIFY2(client.getH() == 10, "Should be equal 10");
QVERIFY2(client.getI() == 10, "Should be equal 10");
QVERIFY2(client.getJ() == 10, "Should be equal 10");
QVERIFY2(client.getK() == 10, "Should be equal 10");
QVERIFY2(client.getL() == 10, "Should be equal 10");
QVERIFY2(client.getM() == 10, "Should be equal 10");
QVERIFY2(client.getN() == 10, "Should be equal 10");
QVERIFY2(client.getO() == 10, "Should be equal 10");
QVERIFY2(client.getP() <= 10, "Should be <= 10");
QVERIFY2(client.getQ() <= 10, "Should be <= 10");
}
<|endoftext|> |
<commit_before>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiHTTPServer.h"
#include "nuiNetworkHost.h"
//class nuiURLHandler
nuiURLHandler::nuiURLHandler(const nglString& rRegExp, const HandlerDelegate& rDelegate)
: mRegExp(rRegExp), mDelegate(rDelegate)
{
}
nuiURLHandler::~nuiURLHandler()
{
}
const nglString& nuiURLHandler::GetRegExp() const
{
return mRegExp.GetExpression();
}
nuiHTTPHandler* nuiURLHandler::Handle(const nglString& rURL)
{
if (mRegExp.Match(rURL))
{
std::vector<nglString> args;
for (uint32 i = 0; i < mRegExp.SubStrings(); i++)
args.push_back(rURL.Extract(mRegExp.SubStart(i), mRegExp.SubLength(i)));
return mDelegate(rURL, args);
}
}
//class nuiURLDispatcher
nuiURLDispatcher::nuiURLDispatcher()
{
}
nuiURLDispatcher::~nuiURLDispatcher()
{
for (int i = 0; i < mpHandlers.size(); i++)
delete mpHandlers[i];
}
void nuiURLDispatcher::AddHandler(nuiURLHandler* pHandler)
{
mpHandlers.push_back(pHandler);
}
void nuiURLDispatcher::AddHandler(const nglString& rRegExp, const nuiURLHandler::HandlerDelegate& rDelegate)
{
mpHandlers.push_back(new nuiURLHandler(rRegExp, rDelegate));
}
nuiHTTPHandler* nuiURLDispatcher::Dispatch(const nglString& rURL)
{
for (int i = 0; i < mpHandlers.size(); i++)
{
nuiHTTPHandler* pHandler = mpHandlers[i]->Handle(rURL);
if (pHandler)
return pHandler;
}
return NULL;
}
//class nuiHTTPHandler
nuiHTTPHandler::nuiHTTPHandler(nuiTCPClient* pClient)
: mpClient(pClient)
{
}
nuiHTTPHandler::~nuiHTTPHandler()
{
delete mpClient;
}
void nuiHTTPHandler::Parse()
{
std::vector<uint8> data;
nglChar cur = 0;
State state = Request;
data.resize(1024);
while (mpClient->Receive(data))
{
size_t index = 0;
while (index < data.size())
{
cur = data[index];
if (state == Body)
{
std::vector<uint8> d(data.begin() + index, data.end());
//NGL_OUT("...Body data... (%d)\n", d.size());
OnBodyData(d);
index = data.size();
}
else
{
index++;
if (cur == 10)
{
// skip...
}
else if (cur == 13)
{
// found a line:
switch (state)
{
case Request:
{
mCurrentLine.Trim();
int pos = mCurrentLine.Find(' ');
if (pos < 0)
{
// Error!
return;
}
mMethod = mCurrentLine.GetLeft(pos);
//NGL_OUT("Method: %s\n", mMethod.GetChars());
if (!OnMethod(mMethod))
return;
while (mCurrentLine[pos] == ' ')
pos++;
int pos2 = pos;
while (mCurrentLine[pos2] != ' ')
pos2++;
mURL = mCurrentLine.Extract(pos, pos2 - pos);
//NGL_OUT("URL: %s\n", mURL.GetChars());
if (!OnMethod(mURL))
return;
pos = pos2;
while (mCurrentLine[pos] == ' ')
pos++;
pos2 = pos;
while (mCurrentLine[pos2] != '/')
pos2++;
mProtocol = mCurrentLine.Extract(pos, pos2 - pos);
mVersion = mCurrentLine.Extract(pos2 + 1);
mVersion.Trim();
//NGL_OUT("Protocol: %s\n", mProtocol.GetChars());
//NGL_OUT("Version: %s\n", mVersion.GetChars());
if (!OnProtocol(mProtocol, mVersion))
return;
state = Header;
mCurrentLine.Wipe();
}
break;
case Header:
{
if (mCurrentLine.IsEmpty())
{
//NGL_OUT("Start body...\n");
if (!OnBodyStart())
return;
state = Body;
}
else
{
mCurrentLine.Trim();
int pos = mCurrentLine.Find(':');
if (pos < 0)
{
// Error!
return;
}
nglString key = mCurrentLine.GetLeft(pos);
nglString value = mCurrentLine.Extract(pos + 1);
key.Trim();
value.Trim();
mHeaders[key] = value;
//NGL_OUT("[%s]: '%s'\n", key.GetChars(), value.GetChars());
if (!OnHeader(key, value))
return;
state = Header;
mCurrentLine.Wipe();
}
}
break;
default:
NGL_ASSERT(0);
break;
}
}
else
{
mCurrentLine.Append(cur);
}
}
}
}
//NGL_OUT("End body\n");
OnBodyEnd();
}
bool nuiHTTPHandler::OnMethod(const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnURL(const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnProtocol(const nglString& rValue, const nglString rVersion)
{
return true;
}
bool nuiHTTPHandler::OnHeader(const nglString& rKey, const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnBodyStart()
{
return true;
}
bool nuiHTTPHandler::OnBodyData(const std::vector<uint8>& rData)
{
return true;
}
void nuiHTTPHandler::OnBodyEnd()
{
}
bool nuiHTTPHandler::ReplyLine(const nglString& rString)
{
bool res = mpClient->Send(rString);
res &= mpClient->Send("\r\n");
return res;
}
bool nuiHTTPHandler::ReplyHeader(const nglString& rKey, const nglString& rValue)
{
nglString str;
str.Add(rKey).Add(": ").Add(rValue);
return ReplyLine(str);
}
bool nuiHTTPHandler::ReplyError(int32 code, const nglString& rErrorStr)
{
nglString errstr;
errstr.Add("HTTP/1.1 ").Add(code).Add(" ").Add(rErrorStr);
ReplyLine(errstr);
ReplyHeader("Content-Type", "text/plain");
ReplyHeader("Server", "Yastream 1.0.0");
ReplyLine("");
ReplyLine(rErrorStr);
// Log the error:
Log(code);
}
bool nuiHTTPHandler::Log(int32 code)
{
nuiNetworkHost client(0, 0, nuiNetworkHost::eTCP);
bool res = mpClient->GetDistantHost(client);
if (!res)
return false;
uint32 ip = client.GetIP();
uint8* pIp = (uint8*)&ip;
nglString t = nglTime().GetLocalTimeStr("%a, %d %b %Y %H:%M:%S %z");
NGL_OUT("%d.%d.%d.%d \"%s %s\" %d %s\n", pIp[0], pIp[1], pIp[2], pIp[3], mMethod.GetChars(), mURL.GetChars(), code, t.GetChars());
}
//class nuiHTTPServerThread : public nglThread
nuiHTTPServerThread::nuiHTTPServerThread(nuiHTTPHandler* pHandler, size_t StackSize)
: nglThread(nglThread::Normal, StackSize), mpHandler(pHandler)
{
SetAutoDelete(true);
}
nuiHTTPServerThread::~nuiHTTPServerThread()
{
delete mpHandler;
}
void nuiHTTPServerThread::OnStart()
{
mpHandler->Parse();
}
//class nuiHTTPServer : public nuiTCPServer
nuiHTTPServer::nuiHTTPServer()
{
mClientStackSize = 0;
SetHandlerDelegate(nuiMakeDelegate(this, &nuiHTTPServer::DefaultHandler));
}
nuiHTTPServer::~nuiHTTPServer()
{
}
void nuiHTTPServer::AcceptConnections()
{
nuiTCPClient* pClient = NULL;
Listen();
while ((pClient = Accept()))
{
OnNewClient(pClient);
//Listen();
}
}
void nuiHTTPServer::OnNewClient(nuiTCPClient* pClient)
{
//NGL_OUT("Received new connection...\n");
nuiHTTPServerThread* pThread = new nuiHTTPServerThread(mDelegate(pClient), mClientStackSize);
pThread->Start();
}
void nuiHTTPServer::SetHandlerDelegate(const nuiFastDelegate1<nuiTCPClient*, nuiHTTPHandler*>& rDelegate)
{
mDelegate = rDelegate;
}
nuiHTTPHandler* nuiHTTPServer::DefaultHandler(nuiTCPClient* pClient)
{
return new nuiHTTPHandler(pClient);
}
void nuiHTTPServer::SetClientStackSize(size_t StackSize)
{
mClientStackSize = StackSize;
}
size_t nuiHTTPServer::GetClientStackSize() const
{
return mClientStackSize;
}
<commit_msg>fixed http server callbacks<commit_after>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiHTTPServer.h"
#include "nuiNetworkHost.h"
//class nuiURLHandler
nuiURLHandler::nuiURLHandler(const nglString& rRegExp, const HandlerDelegate& rDelegate)
: mRegExp(rRegExp), mDelegate(rDelegate)
{
}
nuiURLHandler::~nuiURLHandler()
{
}
const nglString& nuiURLHandler::GetRegExp() const
{
return mRegExp.GetExpression();
}
nuiHTTPHandler* nuiURLHandler::Handle(const nglString& rURL)
{
if (mRegExp.Match(rURL))
{
std::vector<nglString> args;
for (uint32 i = 0; i < mRegExp.SubStrings(); i++)
args.push_back(rURL.Extract(mRegExp.SubStart(i), mRegExp.SubLength(i)));
return mDelegate(rURL, args);
}
}
//class nuiURLDispatcher
nuiURLDispatcher::nuiURLDispatcher()
{
}
nuiURLDispatcher::~nuiURLDispatcher()
{
for (int i = 0; i < mpHandlers.size(); i++)
delete mpHandlers[i];
}
void nuiURLDispatcher::AddHandler(nuiURLHandler* pHandler)
{
mpHandlers.push_back(pHandler);
}
void nuiURLDispatcher::AddHandler(const nglString& rRegExp, const nuiURLHandler::HandlerDelegate& rDelegate)
{
mpHandlers.push_back(new nuiURLHandler(rRegExp, rDelegate));
}
nuiHTTPHandler* nuiURLDispatcher::Dispatch(const nglString& rURL)
{
for (int i = 0; i < mpHandlers.size(); i++)
{
nuiHTTPHandler* pHandler = mpHandlers[i]->Handle(rURL);
if (pHandler)
return pHandler;
}
return NULL;
}
//class nuiHTTPHandler
nuiHTTPHandler::nuiHTTPHandler(nuiTCPClient* pClient)
: mpClient(pClient)
{
}
nuiHTTPHandler::~nuiHTTPHandler()
{
delete mpClient;
}
void nuiHTTPHandler::Parse()
{
std::vector<uint8> data;
nglChar cur = 0;
State state = Request;
data.resize(1024);
while (mpClient->Receive(data))
{
size_t index = 0;
while (index < data.size())
{
cur = data[index];
if (state == Body)
{
std::vector<uint8> d(data.begin() + index, data.end());
//NGL_OUT("...Body data... (%d)\n", d.size());
OnBodyData(d);
index = data.size();
}
else
{
index++;
if (cur == 10)
{
// skip...
}
else if (cur == 13)
{
// found a line:
switch (state)
{
case Request:
{
mCurrentLine.Trim();
int pos = mCurrentLine.Find(' ');
if (pos < 0)
{
// Error!
return;
}
mMethod = mCurrentLine.GetLeft(pos);
//NGL_OUT("Method: %s\n", mMethod.GetChars());
if (!OnMethod(mMethod))
return;
while (mCurrentLine[pos] == ' ')
pos++;
int pos2 = pos;
while (mCurrentLine[pos2] != ' ')
pos2++;
mURL = mCurrentLine.Extract(pos, pos2 - pos);
//NGL_OUT("URL: %s\n", mURL.GetChars());
if (!OnURL(mURL))
return;
pos = pos2;
while (mCurrentLine[pos] == ' ')
pos++;
pos2 = pos;
while (mCurrentLine[pos2] != '/')
pos2++;
mProtocol = mCurrentLine.Extract(pos, pos2 - pos);
mVersion = mCurrentLine.Extract(pos2 + 1);
mVersion.Trim();
//NGL_OUT("Protocol: %s\n", mProtocol.GetChars());
//NGL_OUT("Version: %s\n", mVersion.GetChars());
if (!OnProtocol(mProtocol, mVersion))
return;
state = Header;
mCurrentLine.Wipe();
}
break;
case Header:
{
if (mCurrentLine.IsEmpty())
{
//NGL_OUT("Start body...\n");
if (!OnBodyStart())
return;
state = Body;
}
else
{
mCurrentLine.Trim();
int pos = mCurrentLine.Find(':');
if (pos < 0)
{
// Error!
return;
}
nglString key = mCurrentLine.GetLeft(pos);
nglString value = mCurrentLine.Extract(pos + 1);
key.Trim();
value.Trim();
mHeaders[key] = value;
//NGL_OUT("[%s]: '%s'\n", key.GetChars(), value.GetChars());
if (!OnHeader(key, value))
return;
state = Header;
mCurrentLine.Wipe();
}
}
break;
default:
NGL_ASSERT(0);
break;
}
}
else
{
mCurrentLine.Append(cur);
}
}
}
}
//NGL_OUT("End body\n");
OnBodyEnd();
}
bool nuiHTTPHandler::OnMethod(const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnURL(const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnProtocol(const nglString& rValue, const nglString rVersion)
{
return true;
}
bool nuiHTTPHandler::OnHeader(const nglString& rKey, const nglString& rValue)
{
return true;
}
bool nuiHTTPHandler::OnBodyStart()
{
return true;
}
bool nuiHTTPHandler::OnBodyData(const std::vector<uint8>& rData)
{
return true;
}
void nuiHTTPHandler::OnBodyEnd()
{
}
bool nuiHTTPHandler::ReplyLine(const nglString& rString)
{
bool res = mpClient->Send(rString);
res &= mpClient->Send("\r\n");
return res;
}
bool nuiHTTPHandler::ReplyHeader(const nglString& rKey, const nglString& rValue)
{
nglString str;
str.Add(rKey).Add(": ").Add(rValue);
return ReplyLine(str);
}
bool nuiHTTPHandler::ReplyError(int32 code, const nglString& rErrorStr)
{
nglString errstr;
errstr.Add("HTTP/1.1 ").Add(code).Add(" ").Add(rErrorStr);
ReplyLine(errstr);
ReplyHeader("Content-Type", "text/plain");
ReplyHeader("Server", "Yastream 1.0.0");
ReplyLine("");
ReplyLine(rErrorStr);
// Log the error:
Log(code);
}
bool nuiHTTPHandler::Log(int32 code)
{
nuiNetworkHost client(0, 0, nuiNetworkHost::eTCP);
bool res = mpClient->GetDistantHost(client);
if (!res)
return false;
uint32 ip = client.GetIP();
uint8* pIp = (uint8*)&ip;
nglString t = nglTime().GetLocalTimeStr("%a, %d %b %Y %H:%M:%S %z");
NGL_OUT("%d.%d.%d.%d \"%s %s\" %d %s\n", pIp[0], pIp[1], pIp[2], pIp[3], mMethod.GetChars(), mURL.GetChars(), code, t.GetChars());
}
//class nuiHTTPServerThread : public nglThread
nuiHTTPServerThread::nuiHTTPServerThread(nuiHTTPHandler* pHandler, size_t StackSize)
: nglThread(nglThread::Normal, StackSize), mpHandler(pHandler)
{
SetAutoDelete(true);
}
nuiHTTPServerThread::~nuiHTTPServerThread()
{
delete mpHandler;
}
void nuiHTTPServerThread::OnStart()
{
mpHandler->Parse();
}
//class nuiHTTPServer : public nuiTCPServer
nuiHTTPServer::nuiHTTPServer()
{
mClientStackSize = 0;
SetHandlerDelegate(nuiMakeDelegate(this, &nuiHTTPServer::DefaultHandler));
}
nuiHTTPServer::~nuiHTTPServer()
{
}
void nuiHTTPServer::AcceptConnections()
{
nuiTCPClient* pClient = NULL;
Listen();
while ((pClient = Accept()))
{
OnNewClient(pClient);
//Listen();
}
}
void nuiHTTPServer::OnNewClient(nuiTCPClient* pClient)
{
//NGL_OUT("Received new connection...\n");
nuiHTTPServerThread* pThread = new nuiHTTPServerThread(mDelegate(pClient), mClientStackSize);
pThread->Start();
}
void nuiHTTPServer::SetHandlerDelegate(const nuiFastDelegate1<nuiTCPClient*, nuiHTTPHandler*>& rDelegate)
{
mDelegate = rDelegate;
}
nuiHTTPHandler* nuiHTTPServer::DefaultHandler(nuiTCPClient* pClient)
{
return new nuiHTTPHandler(pClient);
}
void nuiHTTPServer::SetClientStackSize(size_t StackSize)
{
mClientStackSize = StackSize;
}
size_t nuiHTTPServer::GetClientStackSize() const
{
return mClientStackSize;
}
<|endoftext|> |
<commit_before>/*
* E_Link.cpp
*
* Created on: 2014. 11. 9.
* Author: Keunhong Lee
*/
#include <E/E_Common.hpp>
#include <E/E_TimeUtil.hpp>
#include <E/Networking/E_Link.hpp>
#include <E/Networking/E_Networking.hpp>
#include <E/Networking/E_Packet.hpp>
#include <E/Networking/E_Port.hpp>
namespace E {
struct pcap_packet_header {
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
};
Module::Message *Link::messageReceived(Module *from, Module::Message *message) {
Port::Message *portMessage = dynamic_cast<Port::Message *>(message);
if (portMessage != nullptr) {
Port *port = dynamic_cast<Port *>(from);
assert(port != nullptr);
this->packetArrived(port, std::move(portMessage->packet));
}
Link::Message *selfMessage = dynamic_cast<Link::Message *>(message);
if (selfMessage != nullptr) {
if (selfMessage->type == CHECK_QUEUE) {
Port *port = selfMessage->port;
std::list<Packet> ¤t_queue = this->outputQueue[port];
assert(current_queue.size() > 0);
Time current_time = this->getSystem()->getCurrentTime();
Time &avail_time = this->nextAvailable[port];
if (current_time >= avail_time) {
Packet packet = current_queue.front();
current_queue.pop_front();
print_log(NetworkLog::PACKET_QUEUE,
"Output queue length for port[%s] decreased to [%zu]",
port->getModuleName().c_str(), current_queue.size());
Time trans_delay = 0;
if (this->bps != 0)
trans_delay = (((Real)packet.getSize() * 8 * (1000 * 1000 * 1000UL)) /
(Real)this->bps);
Port::Message *portMessage = new Port::Message(
Port::PACKET_TO_PORT, Packet(packet)); // explicit copy for pcap
avail_time = current_time + trans_delay;
if (pcap_enabled) {
struct pcap_packet_header pcap_header;
memset(&pcap_header, 0, sizeof(pcap_header));
pcap_header.ts_sec = TimeUtil::getTime(current_time, TimeUtil::SEC);
pcap_header.ts_usec =
(TimeUtil::getTime(current_time, TimeUtil::NSEC) % 1000000000);
pcap_header.incl_len = std::min(snaplen, packet.getSize());
pcap_header.orig_len = packet.getSize();
// nanosecond precision
pcap_file.write((char *)&pcap_header, sizeof(pcap_header));
char *temp_buffer = new char[pcap_header.incl_len];
packet.readData(0, temp_buffer, pcap_header.incl_len);
pcap_file.write(temp_buffer, pcap_header.incl_len);
delete[] temp_buffer;
}
this->sendMessage(port, portMessage, trans_delay);
if (current_queue.size() > 0) {
Time wait_time = 0;
if (avail_time > current_time)
wait_time += (avail_time - current_time);
assert(wait_time == trans_delay);
Link::Message *selfMessage = new Link::Message;
selfMessage->port = port;
selfMessage->type = Link::CHECK_QUEUE;
this->sendMessage(this, selfMessage, wait_time);
}
}
}
}
return nullptr;
}
void Link::messageFinished(Module *to, Module::Message *message,
Module::Message *response) {
(void)to;
assert(response == nullptr);
delete message;
}
void Link::messageCancelled(Module *to, Module::Message *message) {
Port::Message *portMessage = dynamic_cast<Port::Message *>(message);
Port *port = dynamic_cast<Port *>(to);
if (portMessage != nullptr && port != nullptr) {
delete portMessage;
} else
delete message;
}
void Link::sendPacket(Port *port, Packet &&packet) {
std::list<Packet> ¤t_queue = this->outputQueue[port];
Time current_time = this->getSystem()->getCurrentTime();
Time &avail_time = this->nextAvailable[port];
if ((this->max_queue_length != 0) &&
(current_queue.size() >= this->max_queue_length)) {
// evict one
Size min_drop = this->max_queue_length / 2;
Size max_drop = this->max_queue_length;
Real rand = this->rand_dist.nextDistribution(min_drop, max_drop);
Size index = floor(rand);
if (index >= this->max_queue_length)
index = this->max_queue_length - 1;
if (index < current_queue.size()) {
auto iter = current_queue.begin();
for (Size k = 0; k < index; k++) {
++iter;
}
assert(iter != current_queue.end());
Packet toBeRemoved = *iter;
current_queue.erase(iter);
print_log(NetworkLog::PACKET_QUEUE,
"Output queue for port[%s] is full, remove at %zu, packet "
"length: %zu",
port->getModuleName().c_str(), index, toBeRemoved.getSize());
}
}
assert(this->max_queue_length == 0 ||
current_queue.size() < this->max_queue_length);
current_queue.push_back(packet);
print_log(NetworkLog::PACKET_QUEUE,
"Output queue length for port[%s] increased to [%zu]",
port->getModuleName().c_str(), current_queue.size());
if (current_queue.size() == 1) {
Time wait_time = 0;
if (avail_time > current_time)
wait_time += (avail_time - current_time);
Link::Message *selfMessage = new Link::Message;
selfMessage->port = port;
selfMessage->type = Link::CHECK_QUEUE;
this->sendMessage(this, selfMessage, wait_time);
}
}
void Link::setLinkSpeed(Size bps) { this->bps = bps; }
void Link::setQueueSize(Size max_queue_length) {
this->max_queue_length = max_queue_length;
}
Link::Link(std::string name, NetworkSystem *system)
: Module(system), NetworkModule(name, system), NetworkLog(system) {
this->bps = 1000000000;
this->max_queue_length = 0;
this->pcap_enabled = false;
this->snaplen = 65535;
}
Link::~Link() {
for (auto port : connectedPorts)
port->disconnect(this);
if (pcap_enabled) {
pcap_enabled = false;
pcap_file.close();
}
}
void Link::addPort(Port *port) {
this->connectedPorts.insert(port);
this->nextAvailable[port] = this->getSystem()->getCurrentTime();
this->outputQueue[port] = std::list<Packet>();
port->connect(this);
}
struct pcap_file_header {
uint32_t magic;
uint16_t version_major;
uint16_t version_minor;
uint32_t thiszone; /* gmt to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length saved portion of each pkt */
uint32_t linktype; /* data link type (LINKTYPE_*) */
};
void Link::enablePCAPLogging(const std::string &filename, Size snaplen) {
if (!pcap_enabled) {
pcap_file.open(filename);
pcap_enabled = true;
this->snaplen = snaplen;
struct pcap_file_header pcap_header;
memset(&pcap_header, 0, sizeof(pcap_header));
pcap_header.magic = 0xa1b23c4d; // nanosecond resolution
pcap_header.version_major = 2;
pcap_header.version_minor = 4;
pcap_header.snaplen = snaplen;
pcap_header.linktype = 1; // LINKTYPE_ETHERNET
pcap_file.write((char *)&pcap_header, sizeof(pcap_header));
}
}
} // namespace E
<commit_msg>Generated from commit b0000ea80df042e0edf1080683e676823cbd3a6d<commit_after>/*
* E_Link.cpp
*
* Created on: 2014. 11. 9.
* Author: Keunhong Lee
*/
#include <E/E_Common.hpp>
#include <E/E_TimeUtil.hpp>
#include <E/Networking/E_Link.hpp>
#include <E/Networking/E_Networking.hpp>
#include <E/Networking/E_Packet.hpp>
#include <E/Networking/E_Port.hpp>
namespace E {
struct pcap_packet_header {
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
};
Module::Message *Link::messageReceived(Module *from, Module::Message *message) {
Port::Message *portMessage = dynamic_cast<Port::Message *>(message);
if (portMessage != nullptr) {
Port *port = dynamic_cast<Port *>(from);
assert(port != nullptr);
this->packetArrived(port, std::move(portMessage->packet));
}
Link::Message *selfMessage = dynamic_cast<Link::Message *>(message);
if (selfMessage != nullptr) {
if (selfMessage->type == CHECK_QUEUE) {
Port *port = selfMessage->port;
std::list<Packet> ¤t_queue = this->outputQueue[port];
assert(current_queue.size() > 0);
Time current_time = this->getSystem()->getCurrentTime();
Time &avail_time = this->nextAvailable[port];
if (current_time >= avail_time) {
Packet packet = current_queue.front();
current_queue.pop_front();
print_log(NetworkLog::PACKET_QUEUE,
"Output queue length for port[%s] decreased to [%zu]",
port->getModuleName().c_str(), current_queue.size());
Time trans_delay = 0;
if (this->bps != 0)
trans_delay = (((Real)packet.getSize() * 8 * (1000 * 1000 * 1000UL)) /
(Real)this->bps);
Port::Message *portMessage = new Port::Message(
Port::PACKET_TO_PORT, Packet(packet)); // explicit copy for pcap
avail_time = current_time + trans_delay;
if (pcap_enabled) {
struct pcap_packet_header pcap_header;
memset(&pcap_header, 0, sizeof(pcap_header));
pcap_header.ts_sec = TimeUtil::getTime(current_time, TimeUtil::SEC);
pcap_header.ts_usec =
(TimeUtil::getTime(current_time, TimeUtil::NSEC) % 1000000000);
pcap_header.incl_len = std::min(snaplen, packet.getSize());
pcap_header.orig_len = packet.getSize();
// nanosecond precision
pcap_file.write((char *)&pcap_header, sizeof(pcap_header));
char *temp_buffer = new char[pcap_header.incl_len];
packet.readData(0, temp_buffer, pcap_header.incl_len);
pcap_file.write(temp_buffer, pcap_header.incl_len);
delete[] temp_buffer;
}
this->sendMessage(port, portMessage, trans_delay);
if (current_queue.size() > 0) {
Time wait_time = 0;
if (avail_time > current_time)
wait_time += (avail_time - current_time);
assert(wait_time == trans_delay);
Link::Message *selfMessage = new Link::Message;
selfMessage->port = port;
selfMessage->type = Link::CHECK_QUEUE;
this->sendMessage(this, selfMessage, wait_time);
}
}
}
}
return nullptr;
}
void Link::messageFinished(Module *to, Module::Message *message,
Module::Message *response) {
(void)to;
assert(response == nullptr);
delete message;
}
void Link::messageCancelled(Module *to, Module::Message *message) {
Port::Message *portMessage = dynamic_cast<Port::Message *>(message);
Port *port = dynamic_cast<Port *>(to);
if (portMessage != nullptr && port != nullptr) {
delete portMessage;
} else
delete message;
}
void Link::sendPacket(Port *port, Packet &&packet) {
std::list<Packet> ¤t_queue = this->outputQueue[port];
Time current_time = this->getSystem()->getCurrentTime();
Time &avail_time = this->nextAvailable[port];
if ((this->max_queue_length != 0) &&
(current_queue.size() >= this->max_queue_length)) {
// evict one
Size min_drop = this->max_queue_length / 2;
Size max_drop = this->max_queue_length;
Real rand = this->rand_dist.nextDistribution(min_drop, max_drop);
Size index = floor(rand);
if (index >= this->max_queue_length)
index = this->max_queue_length - 1;
if (index < current_queue.size()) {
auto iter = current_queue.begin();
for (Size k = 0; k < index; k++) {
++iter;
}
assert(iter != current_queue.end());
Packet toBeRemoved = *iter;
current_queue.erase(iter);
print_log(NetworkLog::PACKET_QUEUE,
"Output queue for port[%s] is full, remove at %zu, packet "
"length: %zu",
port->getModuleName().c_str(), index, toBeRemoved.getSize());
}
}
assert(this->max_queue_length == 0 ||
current_queue.size() < this->max_queue_length);
current_queue.push_back(packet);
print_log(NetworkLog::PACKET_QUEUE,
"Output queue length for port[%s] increased to [%zu]",
port->getModuleName().c_str(), current_queue.size());
if (current_queue.size() == 1) {
Time wait_time = 0;
if (avail_time > current_time)
wait_time += (avail_time - current_time);
Link::Message *selfMessage = new Link::Message;
selfMessage->port = port;
selfMessage->type = Link::CHECK_QUEUE;
this->sendMessage(this, selfMessage, wait_time);
}
}
void Link::setLinkSpeed(Size bps) { this->bps = bps; }
void Link::setQueueSize(Size max_queue_length) {
this->max_queue_length = max_queue_length;
}
Link::Link(std::string name, NetworkSystem *system)
: Module(system), NetworkModule(name, system), NetworkLog(system) {
this->bps = 1000000000;
this->max_queue_length = 0;
this->pcap_enabled = false;
this->snaplen = 65535;
}
Link::~Link() {
for (auto port : connectedPorts)
port->disconnect(this);
if (pcap_enabled) {
pcap_enabled = false;
pcap_file.close();
}
}
void Link::addPort(Port *port) {
this->connectedPorts.insert(port);
this->nextAvailable[port] = this->getSystem()->getCurrentTime();
this->outputQueue[port] = std::list<Packet>();
port->connect(this);
}
struct pcap_file_header {
uint32_t magic;
uint16_t version_major;
uint16_t version_minor;
uint32_t thiszone; /* gmt to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length saved portion of each pkt */
uint32_t linktype; /* data link type (LINKTYPE_*) */
};
void Link::enablePCAPLogging(const std::string &filename, Size snaplen) {
if (!pcap_enabled) {
pcap_file.open(filename, std::ofstream::binary);
pcap_enabled = true;
this->snaplen = snaplen;
struct pcap_file_header pcap_header;
memset(&pcap_header, 0, sizeof(pcap_header));
pcap_header.magic = 0xa1b23c4d; // nanosecond resolution
pcap_header.version_major = 2;
pcap_header.version_minor = 4;
pcap_header.snaplen = snaplen;
pcap_header.linktype = 1; // LINKTYPE_ETHERNET
pcap_file.write((char *)&pcap_header, sizeof(pcap_header));
}
}
} // namespace E
<|endoftext|> |
<commit_before>#include <iostream>
#include "CaffeBatchPrediction.hpp"
#include "scalefactor.hpp"
#include "fast_nms.hpp"
#include "detect.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/gpu/gpu.hpp>
using namespace std;
using namespace cv;
static double gtod_wrapper(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
}
// TODO :: Make a call for GPU Mat input.
// Simple multi-scale detect. Take a single image, scale it into a number
// of diffent sized images. Run a fixed-size detection window across each
// of them. Keep track of the scale of each scaled image to map the
// detected rectangles back to the correct location and size on the
// original input images
template<class MatT>
void NNDetect<MatT>::detectMultiscale(const Mat& inputImg,
const Mat& depthMat,
const Size& minSize,
const Size& maxSize,
double scaleFactor,
const vector<double>& nmsThreshold,
const vector<double>& detectThreshold,
vector<Rect>& rectsOut)
{
// Size of the first level classifier. Others are an integer multiple
// of this initial size (2x and maybe 4x if we need it)
int wsize = d12_.getInputGeometry().width;
// scaled images which allow us to find images between min and max
// size for the given classifier input window
vector<pair<MatT, double> > scaledImages12;
vector<pair<MatT, double> > scaledImages24;
// Maybe later ? vector<pair<MatT, double> > scaledImages48;
// list of windows to work with.
// A window is a rectangle from a given scaled image along
// with the index of the scaled image it corresponds with.
vector<Window> windowsIn;
vector<Window> windowsOut;
// Confidence scores (0.0 - 1.0) for each detected rectangle
vector<float> scores;
// Generate a list of initial windows to search. Each window will be 12x12 from a scaled image
// These scaled images let us search for variable sized objects using a fixed-width detector
MatT f32Img;
MatT(inputImg).convertTo(f32Img, CV_32FC3); // classifier runs on float pixel data
generateInitialWindows(f32Img, depthMat, minSize, maxSize, wsize, scaleFactor, scaledImages12, windowsIn);
// Generate scaled images for the larger detect sizes as well. Subsequent passes will use larger
// input sizes. These images will let us grab higher res input as the detector size goes up (as
// opposed to just scaling up the 12x12 images to a larger size).
scalefactor(f32Img, Size(wsize * 2, wsize * 2), minSize, maxSize, scaleFactor, scaledImages24);
// not yet - scalefactor(f32Img, Size(wsize*4,wsize*4), minSize, maxSize, scaleFactor, scaledImages48);
// Do 1st level of detection. This takes the initial list of windows
// and returns the list which have a score for "ball" above the
// threshold listed.
cout << "d12 windows in = " << windowsIn.size() << endl;
runDetection(d12_, scaledImages12, windowsIn, detectThreshold[0], "ball", windowsOut, scores);
cout << "d12 windows out = " << windowsOut.size() << endl;
runNMS(windowsOut, scores, scaledImages12, nmsThreshold[0], windowsIn);
cout << "d12 nms windows out = " << windowsIn.size() << endl;
// Double the size of the rects to get from a 12x12 to 24x24
// detection window. Use scaledImages24 for the detection call
// since that has the scales appropriate for the 24x24 detector
for (auto it = windowsIn.begin(); it != windowsIn.end(); ++it)
{
it->first = Rect(it->first.x * 2, it->first.y * 2,
it->first.width * 2, it->first.height * 2);
}
if ((detectThreshold.size() > 1) && (detectThreshold[1] > 0.0))
{
cout << "d24 windows in = " << windowsIn.size() << endl;
runDetection(d24_, scaledImages24, windowsIn, detectThreshold[1], "ball", windowsOut, scores);
cout << "d24 windows out = " << windowsOut.size() << endl;
runNMS(windowsOut, scores, scaledImages24, nmsThreshold[1], windowsIn);
cout << "d24 nms windows out = " << windowsIn.size() << endl;
}
// Final result - scale the output rectangles back to the
// correct scale for the original sized image
rectsOut.clear();
for (auto it = windowsIn.cbegin(); it != windowsIn.cend(); ++it)
{
double scale = scaledImages24[it->second].second;
Rect rect(it->first);
Rect scaledRect(Rect(rect.x / scale, rect.y / scale, rect.width / scale, rect.height / scale));
rectsOut.push_back(scaledRect);
}
}
template<class MatT>
void NNDetect<MatT>::runNMS(const vector<Window>& windows,
const vector<float>& scores,
const vector<pair<MatT, double> >& scaledImages,
double nmsThreshold,
vector<Window>& windowsOut)
{
if ((nmsThreshold > 0.0) && (nmsThreshold < 1.0))
{
// Detected is a rect, score pair.
vector<Detected> detected;
// Need to scale each rect to the correct mapping to the
// original image, since rectangles from multiple different
// scales might overlap
for (size_t i = 0; i < windows.size(); i++)
{
double scale = scaledImages[windows[i].second].second;
Rect rect(windows[i].first);
Rect scaledRect(Rect(rect.x / scale, rect.y / scale, rect.width / scale, rect.height / scale));
detected.push_back(Detected(scaledRect, scores[i]));
}
vector<size_t> nmsOut;
fastNMS(detected, nmsThreshold, nmsOut);
// Each entry of nmsOut is the index of a saved rect/scales
// pair. Save the entries from those indexes as the output
windowsOut.clear();
for (auto it = nmsOut.cbegin(); it != nmsOut.cend(); ++it)
{
windowsOut.push_back(windows[*it]);
}
}
else
{
// If not running NMS, output is the same as the input
windowsOut = windows;
}
}
template<class MatT>
void NNDetect<MatT>::generateInitialWindows(
const MatT& input,
const Mat& depthIn,
const Size& minSize,
const Size& maxSize,
int wsize,
double scaleFactor,
vector<pair<MatT, double> >& scaledImages,
vector<Window>& windows)
{
windows.clear();
size_t windowsChecked = 0;
// How many pixels to move the window for each step
// We use 4 - the calibration step can adjust +/- 2 pixels
// in each direction, which means they will correct for
// anything which is actually centered in one of the
// pixels we step over.
const int step = 4;
// Create array of scaled images
vector<pair<MatT, double> > scaledDepth;
if (!depthIn.empty())
{
MatT depthGpu = MatT(depthIn);
scalefactor(depthGpu, Size(wsize, wsize), minSize, maxSize, scaleFactor, scaledDepth);
}
scalefactor(input, Size(wsize, wsize), minSize, maxSize, scaleFactor, scaledImages);
// Main loop. Look at each scaled image in turn
for (size_t scale = 0; scale < scaledImages.size(); ++scale)
{
float depth_multiplier = 0.2;
float ball_real_size = 247.6; // ball is 9.75in diameter = 247.6 mm
float percent_image = (float)wsize / scaledImages[scale].first.cols;
float size_fov = percent_image * hfov_; //TODO fov size
float depth_avg = (ball_real_size / (2.0 * tanf(size_fov / 2.0))) - (4.572 * 25.4);
float depth_min = depth_avg - depth_avg * depth_multiplier;
float depth_max = depth_avg + depth_avg * depth_multiplier;
cout << fixed << "Target size:" << wsize / scaledImages[scale].second << " Dist:" << depth_avg << " Min/max:" << depth_min << "/" << depth_max;
size_t thisWindowsChecked = 0;
size_t thisWindowsPassed = 0;
// Start at the upper left corner. Loop through the rows and cols until
// the detection window falls off the edges of the scaled image
for (int r = 0; (r + wsize) < scaledImages[scale].first.rows; r += step)
{
for (int c = 0; (c + wsize) < scaledImages[scale].first.cols; c += step)
{
thisWindowsChecked += 1;
if (!depthIn.empty())
{
Mat detectCheck = Mat(scaledDepth[scale].first(Rect(c, r, wsize, wsize)));
if(!depthInRange(depth_min, depth_max, detectCheck))
{
continue;
}
}
windows.push_back(Window(Rect(c, r, wsize, wsize), scale));
thisWindowsPassed += 1;
}
}
windowsChecked += thisWindowsChecked;
cout << " Windows Passed:"<< thisWindowsPassed << "/" << thisWindowsChecked << endl;
}
cout << "generateInitialWindows checked " << windowsChecked << " windows and passed " << windows.size() << endl;
}
template<class MatT>
void NNDetect<MatT>::runDetection(CaffeClassifier<MatT>& classifier,
const vector<pair<MatT, double> >& scaledImages,
const vector<Window>& windows,
float threshold,
string label,
vector<Window>& windowsOut,
vector<float>& scores)
{
windowsOut.clear();
scores.clear();
// Accumulate a number of images to test and pass them in to
// the NN prediction as a batch
vector<MatT> images;
// Return value from detection. This is a list of indexes from
// the input which have a high enough confidence score
vector<size_t> detected;
size_t batchSize = classifier.BatchSize();
int counter = 0;
double start = gtod_wrapper(); // grab start time
// For each input window, grab the correct image
// subset from the correct scaled image.
// Detection happens in batches, so save up a list of
// images and submit them all at once.
for (auto it = windows.cbegin(); it != windows.cend(); ++it)
{
// scaledImages[x].first is a Mat holding the image
// scaled to the correct size for the given rect.
// it->second is the index into scaledImages to look at
// so scaledImages[it->second] is a Mat at the correct
// scale for the current window. it->first is the
// rect describing the subset of that image we need to process
images.push_back(scaledImages[it->second].first(it->first));
if ((images.size() == batchSize) || ((it + 1) == windows.cend()))
{
doBatchPrediction(classifier, images, threshold, label, detected, scores);
// Clear out images array to start the next batch
// of processing fresh
images.clear();
for (size_t j = 0; j < detected.size(); j++)
{
// Indexes in detected array are relative to the start of the
// current batch just passed in to doBatchPrediction.
// Use counter to keep track of which batch we're in
windowsOut.push_back(windows[counter * batchSize + detected[j]]);
}
// Keep track of the batch number
counter++;
}
}
double end = gtod_wrapper();
cout << "runDetection time = " << (end - start) << endl;
}
// do 1 run of the classifier. This takes up batch_size predictions
// and adds the index of anything found to the detected list
template<class MatT>
void NNDetect<MatT>::doBatchPrediction(CaffeClassifier<MatT>& classifier,
const vector<MatT>& imgs,
float threshold,
const string& label,
vector<size_t>& detected,
vector<float>& scores)
{
detected.clear();
// Grab the top 2 detected classes. Since we're doing an object /
// not object split, that will get everything
vector<vector<Prediction> > predictions = classifier.ClassifyBatch(imgs, 2);
// Each outer loop is the predictions for one input image
for (size_t i = 0; i < imgs.size(); ++i)
{
// Each inner loop is the prediction for a particular label
// for the given image, sorted by score.
//
// Look for object with label <label>, > threshold confidence
for (vector<Prediction>::const_iterator it = predictions[i].begin(); it != predictions[i].end(); ++it)
{
if (it->first == label)
{
if (it->second >= threshold)
{
detected.push_back(i);
scores.push_back(it->second);
}
break;
}
}
}
}
// Be conservative here - if any of the depth values in the target rect
// are in the expected range, consider the rect in range. Also
// say that it is in range if any of the depth values are negative (i.e. no
// depth info for those pixels)
template <class MatT>
bool NNDetect<MatT>::depthInRange(float depth_min, float depth_max, const Mat &detectCheck)
{
for (int py = 0; py < detectCheck.rows; py++)
{
const float *p = detectCheck.ptr<float>(py);
for (int px = 0; px < detectCheck.cols; px++)
{
if ((p[px] <= 0.0) || ((p[px] < depth_max) && (p[px] > depth_min)))
{
return true;
}
}
}
return false;
}
// Explicitly instatiate classes used elsewhere
template class NNDetect<Mat>;
template class NNDetect<gpu::GpuMat>;
<commit_msg>Fix off by one error<commit_after>#include <iostream>
#include "CaffeBatchPrediction.hpp"
#include "scalefactor.hpp"
#include "fast_nms.hpp"
#include "detect.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/gpu/gpu.hpp>
using namespace std;
using namespace cv;
static double gtod_wrapper(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
}
// TODO :: Make a call for GPU Mat input.
// Simple multi-scale detect. Take a single image, scale it into a number
// of diffent sized images. Run a fixed-size detection window across each
// of them. Keep track of the scale of each scaled image to map the
// detected rectangles back to the correct location and size on the
// original input images
template<class MatT>
void NNDetect<MatT>::detectMultiscale(const Mat& inputImg,
const Mat& depthMat,
const Size& minSize,
const Size& maxSize,
double scaleFactor,
const vector<double>& nmsThreshold,
const vector<double>& detectThreshold,
vector<Rect>& rectsOut)
{
// Size of the first level classifier. Others are an integer multiple
// of this initial size (2x and maybe 4x if we need it)
int wsize = d12_.getInputGeometry().width;
// scaled images which allow us to find images between min and max
// size for the given classifier input window
vector<pair<MatT, double> > scaledImages12;
vector<pair<MatT, double> > scaledImages24;
// Maybe later ? vector<pair<MatT, double> > scaledImages48;
// list of windows to work with.
// A window is a rectangle from a given scaled image along
// with the index of the scaled image it corresponds with.
vector<Window> windowsIn;
vector<Window> windowsOut;
// Confidence scores (0.0 - 1.0) for each detected rectangle
vector<float> scores;
// Generate a list of initial windows to search. Each window will be 12x12 from a scaled image
// These scaled images let us search for variable sized objects using a fixed-width detector
MatT f32Img;
MatT(inputImg).convertTo(f32Img, CV_32FC3); // classifier runs on float pixel data
generateInitialWindows(f32Img, depthMat, minSize, maxSize, wsize, scaleFactor, scaledImages12, windowsIn);
// Generate scaled images for the larger detect sizes as well. Subsequent passes will use larger
// input sizes. These images will let us grab higher res input as the detector size goes up (as
// opposed to just scaling up the 12x12 images to a larger size).
scalefactor(f32Img, Size(wsize * 2, wsize * 2), minSize, maxSize, scaleFactor, scaledImages24);
// not yet - scalefactor(f32Img, Size(wsize*4,wsize*4), minSize, maxSize, scaleFactor, scaledImages48);
// Do 1st level of detection. This takes the initial list of windows
// and returns the list which have a score for "ball" above the
// threshold listed.
cout << "d12 windows in = " << windowsIn.size() << endl;
runDetection(d12_, scaledImages12, windowsIn, detectThreshold[0], "ball", windowsOut, scores);
cout << "d12 windows out = " << windowsOut.size() << endl;
runNMS(windowsOut, scores, scaledImages12, nmsThreshold[0], windowsIn);
cout << "d12 nms windows out = " << windowsIn.size() << endl;
// Double the size of the rects to get from a 12x12 to 24x24
// detection window. Use scaledImages24 for the detection call
// since that has the scales appropriate for the 24x24 detector
for (auto it = windowsIn.begin(); it != windowsIn.end(); ++it)
{
it->first = Rect(it->first.x * 2, it->first.y * 2,
it->first.width * 2, it->first.height * 2);
}
if ((detectThreshold.size() > 1) && (detectThreshold[1] > 0.0))
{
cout << "d24 windows in = " << windowsIn.size() << endl;
runDetection(d24_, scaledImages24, windowsIn, detectThreshold[1], "ball", windowsOut, scores);
cout << "d24 windows out = " << windowsOut.size() << endl;
runNMS(windowsOut, scores, scaledImages24, nmsThreshold[1], windowsIn);
cout << "d24 nms windows out = " << windowsIn.size() << endl;
}
// Final result - scale the output rectangles back to the
// correct scale for the original sized image
rectsOut.clear();
for (auto it = windowsIn.cbegin(); it != windowsIn.cend(); ++it)
{
double scale = scaledImages24[it->second].second;
Rect rect(it->first);
Rect scaledRect(Rect(rect.x / scale, rect.y / scale, rect.width / scale, rect.height / scale));
rectsOut.push_back(scaledRect);
}
}
template<class MatT>
void NNDetect<MatT>::runNMS(const vector<Window>& windows,
const vector<float>& scores,
const vector<pair<MatT, double> >& scaledImages,
double nmsThreshold,
vector<Window>& windowsOut)
{
if ((nmsThreshold > 0.0) && (nmsThreshold < 1.0))
{
// Detected is a rect, score pair.
vector<Detected> detected;
// Need to scale each rect to the correct mapping to the
// original image, since rectangles from multiple different
// scales might overlap
for (size_t i = 0; i < windows.size(); i++)
{
double scale = scaledImages[windows[i].second].second;
Rect rect(windows[i].first);
Rect scaledRect(Rect(rect.x / scale, rect.y / scale, rect.width / scale, rect.height / scale));
detected.push_back(Detected(scaledRect, scores[i]));
}
vector<size_t> nmsOut;
fastNMS(detected, nmsThreshold, nmsOut);
// Each entry of nmsOut is the index of a saved rect/scales
// pair. Save the entries from those indexes as the output
windowsOut.clear();
for (auto it = nmsOut.cbegin(); it != nmsOut.cend(); ++it)
{
windowsOut.push_back(windows[*it]);
}
}
else
{
// If not running NMS, output is the same as the input
windowsOut = windows;
}
}
template<class MatT>
void NNDetect<MatT>::generateInitialWindows(
const MatT& input,
const Mat& depthIn,
const Size& minSize,
const Size& maxSize,
int wsize,
double scaleFactor,
vector<pair<MatT, double> >& scaledImages,
vector<Window>& windows)
{
windows.clear();
size_t windowsChecked = 0;
// How many pixels to move the window for each step
// We use 4 - the calibration step can adjust +/- 2 pixels
// in each direction, which means they will correct for
// anything which is actually centered in one of the
// pixels we step over.
const int step = 4;
// Create array of scaled images
vector<pair<MatT, double> > scaledDepth;
if (!depthIn.empty())
{
MatT depthGpu = MatT(depthIn);
scalefactor(depthGpu, Size(wsize, wsize), minSize, maxSize, scaleFactor, scaledDepth);
}
scalefactor(input, Size(wsize, wsize), minSize, maxSize, scaleFactor, scaledImages);
// Main loop. Look at each scaled image in turn
for (size_t scale = 0; scale < scaledImages.size(); ++scale)
{
float depth_multiplier = 0.2;
float ball_real_size = 247.6; // ball is 9.75in diameter = 247.6 mm
float percent_image = (float)wsize / scaledImages[scale].first.cols;
float size_fov = percent_image * hfov_; //TODO fov size
float depth_avg = (ball_real_size / (2.0 * tanf(size_fov / 2.0))) - (4.572 * 25.4);
float depth_min = depth_avg - depth_avg * depth_multiplier;
float depth_max = depth_avg + depth_avg * depth_multiplier;
cout << fixed << "Target size:" << wsize / scaledImages[scale].second << " Dist:" << depth_avg << " Min/max:" << depth_min << "/" << depth_max;
size_t thisWindowsChecked = 0;
size_t thisWindowsPassed = 0;
// Start at the upper left corner. Loop through the rows and cols until
// the detection window falls off the edges of the scaled image
for (int r = 0; (r + wsize) <= scaledImages[scale].first.rows; r += step)
{
for (int c = 0; (c + wsize) <= scaledImages[scale].first.cols; c += step)
{
thisWindowsChecked += 1;
if (!depthIn.empty())
{
Mat detectCheck = Mat(scaledDepth[scale].first(Rect(c, r, wsize, wsize)));
if(!depthInRange(depth_min, depth_max, detectCheck))
{
continue;
}
}
windows.push_back(Window(Rect(c, r, wsize, wsize), scale));
thisWindowsPassed += 1;
}
}
windowsChecked += thisWindowsChecked;
cout << " Windows Passed:"<< thisWindowsPassed << "/" << thisWindowsChecked << endl;
}
cout << "generateInitialWindows checked " << windowsChecked << " windows and passed " << windows.size() << endl;
}
template<class MatT>
void NNDetect<MatT>::runDetection(CaffeClassifier<MatT>& classifier,
const vector<pair<MatT, double> >& scaledImages,
const vector<Window>& windows,
float threshold,
string label,
vector<Window>& windowsOut,
vector<float>& scores)
{
windowsOut.clear();
scores.clear();
// Accumulate a number of images to test and pass them in to
// the NN prediction as a batch
vector<MatT> images;
// Return value from detection. This is a list of indexes from
// the input which have a high enough confidence score
vector<size_t> detected;
size_t batchSize = classifier.BatchSize();
int counter = 0;
double start = gtod_wrapper(); // grab start time
// For each input window, grab the correct image
// subset from the correct scaled image.
// Detection happens in batches, so save up a list of
// images and submit them all at once.
for (auto it = windows.cbegin(); it != windows.cend(); ++it)
{
// scaledImages[x].first is a Mat holding the image
// scaled to the correct size for the given rect.
// it->second is the index into scaledImages to look at
// so scaledImages[it->second] is a Mat at the correct
// scale for the current window. it->first is the
// rect describing the subset of that image we need to process
images.push_back(scaledImages[it->second].first(it->first));
if ((images.size() == batchSize) || ((it + 1) == windows.cend()))
{
doBatchPrediction(classifier, images, threshold, label, detected, scores);
// Clear out images array to start the next batch
// of processing fresh
images.clear();
for (size_t j = 0; j < detected.size(); j++)
{
// Indexes in detected array are relative to the start of the
// current batch just passed in to doBatchPrediction.
// Use counter to keep track of which batch we're in
windowsOut.push_back(windows[counter * batchSize + detected[j]]);
}
// Keep track of the batch number
counter++;
}
}
double end = gtod_wrapper();
cout << "runDetection time = " << (end - start) << endl;
}
// do 1 run of the classifier. This takes up batch_size predictions
// and adds the index of anything found to the detected list
template<class MatT>
void NNDetect<MatT>::doBatchPrediction(CaffeClassifier<MatT>& classifier,
const vector<MatT>& imgs,
float threshold,
const string& label,
vector<size_t>& detected,
vector<float>& scores)
{
detected.clear();
// Grab the top 2 detected classes. Since we're doing an object /
// not object split, that will get everything
vector<vector<Prediction> > predictions = classifier.ClassifyBatch(imgs, 2);
// Each outer loop is the predictions for one input image
for (size_t i = 0; i < imgs.size(); ++i)
{
// Each inner loop is the prediction for a particular label
// for the given image, sorted by score.
//
// Look for object with label <label>, > threshold confidence
for (vector<Prediction>::const_iterator it = predictions[i].begin(); it != predictions[i].end(); ++it)
{
if (it->first == label)
{
if (it->second >= threshold)
{
detected.push_back(i);
scores.push_back(it->second);
}
break;
}
}
}
}
// Be conservative here - if any of the depth values in the target rect
// are in the expected range, consider the rect in range. Also
// say that it is in range if any of the depth values are negative (i.e. no
// depth info for those pixels)
template <class MatT>
bool NNDetect<MatT>::depthInRange(float depth_min, float depth_max, const Mat &detectCheck)
{
for (int py = 0; py < detectCheck.rows; py++)
{
const float *p = detectCheck.ptr<float>(py);
for (int px = 0; px < detectCheck.cols; px++)
{
if ((p[px] <= 0.0) || ((p[px] < depth_max) && (p[px] > depth_min)))
{
return true;
}
}
}
return false;
}
// Explicitly instatiate classes used elsewhere
template class NNDetect<Mat>;
template class NNDetect<gpu::GpuMat>;
<|endoftext|> |
<commit_before>#include <UtH\Platform\Graphics.hpp>
#include <UtH\Platform\Configuration.hpp>
#include <UtH\Platform\OpenGL.hpp>
#include <UtH\Platform\OGLCheck.hpp>
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "freeglut_staticd.lib")
#pragma comment(lib, "glew32sd.lib")
#else // Release
// FIXME: Static 'Release' version of the GLEW lib breaks the build
// consider using dynamic linking for release
#pragma comment(lib, "freeglut_static.lib")
#pragma comment(lib, "glew32sd.lib")
#endif
namespace uth
{
static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,
GL_FRAGMENT_SHADER};
static int dataTypes[DATATYPE_LAST] = {GL_BYTE,
GL_UNSIGNED_BYTE,
GL_SHORT,
GL_UNSIGNED_SHORT,
GL_INT,
GL_UNSIGNED_INT,
GL_FLOAT,
GL_DOUBLE};
static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,
GL_READ_BUFFER,
GL_COPY_WRITE_BUFFER,
GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER,
GL_PIXEL_UNPACK_BUFFER,
GL_TEXTURE_BUFFER,
GL_TRANSFORM_FEEDBACK_BUFFER,
GL_UNIFORM_BUFFER};
static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,
GL_STREAM_READ,
GL_STREAM_COPY,
GL_STATIC_DRAW,
GL_STATIC_READ,
GL_STATIC_COPY,
GL_DYNAMIC_DRAW,
GL_DYNAMIC_READ,
GL_DYNAMIC_COPY};
static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,
GL_PACK_LSB_FIRST,
GL_PACK_ROW_LENGTH,
GL_PACK_IMAGE_HEIGHT,
GL_PACK_SKIP_PIXELS,
GL_PACK_SKIP_ROWS,
GL_PACK_SKIP_IMAGES,
GL_PACK_ALIGNMENT,
GL_UNPACK_SWAP_BYTES,
GL_UNPACK_LSB_FIRST,
GL_UNPACK_ROW_LENGTH,
GL_UNPACK_IMAGE_HEIGHT,
GL_UNPACK_SKIP_PIXELS,
GL_UNPACK_SKIP_ROWS,
GL_UNPACK_SKIP_IMAGES,
GL_UNPACK_ALIGNMENT};
static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D,
TEXTURE_2D,
TEXTURE_3D,
TEXTURE_1D_ARRAY,
TEXTURE_2D_ARRAY,
TEXTURE_RECTANGLE,
TEXTURE_CUBE_MAP,
TEXTURE_2D_MULTISAMPLE,
TEXTURE_2D_MULTISAMPLE_ARRAY};
static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,
GL_RGBA};
static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL,
GL_TEXTURE_COMPARE_FUNC,
GL_TEXTURE_COMPARE_MODE,
GL_TEXTURE_LOD_BIAS,
GL_TEXTURE_MIN_FILTER,
GL_TEXTURE_MAG_FILTER,
GL_TEXTURE_MIN_LOD,
GL_TEXTURE_MAX_LOD,
GL_TEXTURE_MAX_LEVEL,
GL_TEXTURE_SWIZZLE_R,
GL_TEXTURE_SWIZZLE_G,
GL_TEXTURE_SWIZZLE_B,
GL_TEXTURE_SWIZZLE_A,
GL_TEXTURE_WRAP_S,
GL_TEXTURE_WRAP_T,
GL_TEXTURE_WRAP_R};
static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_LINES,
GL_LINE_STRIP_ADJACENCY,
GL_LINES_ADJACENCY,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_TRIANGLES,
GL_TRIANGLE_STRIP_ADJACENCY,
GL_TRIANGLES_ADJACENCY};
static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS};
static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_CONSTANT_COLOR,
GL_ONE_MINUS_CONSTANT_COLOR,
GL_CONSTANT_ALPHA,
GL_ONE_MINUS_CONSTANT_ALPHA};
static int faceCullings[FACECULLING_LAST] = {GL_FRONT,
GL_BACK,
GL_FRONT_AND_BACK};
// Window functions
bool Graphics::createWindow(const WindowSettings& settings)
{
if (m_windowHandle) destroyWindow();
m_windowSettings = settings;
// Context settings
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
// Extra settings
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
// Position & size
glutInitWindowPosition(settings.position.x, settings.position.y);
glutInitWindowSize(settings.size.x, settings.size.y);
// Display settings
glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |
settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |
settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |
settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);
int majorVer = settings.contextVersionMajor,
minorVer = settings.contextVersionMinor;
glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);
m_windowHandle = glutCreateWindow("Generic Window Title");
return true;
}
void Graphics::destroyWindow()
{
oglCheck(glutDestroyWindow(m_windowHandle));
}
void Graphics::clear(const float r, const float g, const float b, const float a)
{
oglCheck(glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
oglCheck(glClearColor(r, g, b, a));
if (!m_windowSettings.useDepthBuffer) return;
#ifdef UTH_SYSTEM_OPENGLES
oglCheck(glClearDepthf(1));
#else
oglCheck(glClearDepth(1));
#endif
if (!m_windowSettings.useStencilBuffer) return;
oglCheck(glClearStencil(1));
}
void Graphics::swapBuffers()
{
oglCheck(glutSwapBuffers());
}
void setViewport(const int x, const int y, const size_t width, const size_t height)
{
oglCheck(glViewport(x, y, width, height));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Shaders
int Graphics::createShaderProgram()
{
return glCreateProgram();
}
bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)
{
if (!shaderCode) return false;
unsigned int shader = glCreateShader(shaderTypes[type]);
oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));
oglCheck(glCompileShader(shader));
int success;
oglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));
if (!success)
{
glDeleteShader(shader);
return false;
}
oglCheck(glAttachShader(shaderProgram, shader));
oglCheck(glDeleteShader(shader));
return true;
}
bool Graphics::linkShaderProgram(const int shaderProgram)
{
oglCheck(glLinkProgram(shaderProgram));
int success;
oglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));
if (!success)
{
destroyShaderProgram(shaderProgram);
return false;
}
return true;
}
void Graphics::bindProgram(const int shaderProgram)
{
if (shaderProgram)
oglCheck(glUseProgram(shaderProgram));
}
void unbindProgram()
{
oglCheck(glUseProgram(0));
}
void Graphics::destroyShaderProgram(const int shaderProgram)
{
oglCheck(glDeleteProgram(shaderProgram));
}
int Graphics::getUniformLocation(const int shaderProgram, const char* name)
{
return glGetUniformLocation(shaderProgram, name);
}
int Graphics::getAttributeLocation(const int shaderProgram, const char* name)
{
return glGetAttribLocation(shaderProgram, name);
}
void Graphics::setUniform(const int location, const float x)
{
oglCheck(glUniform1f(location, x));
}
void Graphics::setUniform(const int location, const float x, const float y)
{
oglCheck(glUniform2f(location, x, y));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z)
{
oglCheck(glUniform3f(location, x, y, z));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)
{
oglCheck(glUniform4f(location, x, y, z, w));
}
void Graphics::setUniform(const int location, const umath::vector2& vector)
{
oglCheck(glUniform2fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector3& vector)
{
oglCheck(glUniform3fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector4& vector)
{
oglCheck(glUniform4fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::matrix3& matrix)
{
oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::setUniform(const int location, const umath::matrix4& matrix)
{
oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::enableVertexAttribArray(const int location)
{
oglCheck(glEnableVertexAttribArray(location));
}
void Graphics::disableVertexAttribArray(const int location)
{
oglCheck(glDisableVertexAttribArray(location));
}
void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)
{
oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Buffers
void generateBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glGenBuffers(amount, buffers));
}
void deleteBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glDeleteBuffers(amount, buffers));
}
void bindBuffer(BufferType type, const unsigned int buffer)
{
oglCheck(glBindBuffer(bufferTypes[type], buffer));
}
void setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)
{
oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));
}
void setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)
{
oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Texture functions
void setPixelStore(PixelStoreParam param, const int value)
{
oglCheck(glPixelStorei(pixelStoreParams[param], value));
}
void generateTextures(const unsigned int amount, unsigned int* data)
{
oglCheck(glGenTextures(amount, data));
}
void setActiveTexUnit(TexUnit unit)
{
oglCheck(glActiveTexture(unit));
}
void bindTexture(TextureType type, const int texture)
{
oglCheck(glBindTexture(textureTypes[type], texture));
}
void setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void setTextureParameter(TextureType type, TextureParam param, const int value)
{
oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Drawing functions
void drawArrays(PrimitiveType type, const int first, const size_t count)
{
oglCheck(glDrawArrays(primitiveTypes[type], first, count));
}
void drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)
{
oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));
}
void setPointSize(const float size)
{
oglCheck(glPointSize(size));
}
void setLineWidth(const float width)
{
oglCheck(glLineWidth(width));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Other
void flush()
{
oglCheck(glFlush());
}
void setDepthFunction(const bool enable, DepthFunction func)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_DEPTH_TEST));
else
oglCheck(glDisable(GL_DEPTH_TEST));
enabled = !enabled;
}
oglCheck(glDepthFunc(depthFunctions[func]));
}
void setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_BLEND));
else
oglCheck(glDisable(GL_BLEND));
enabled = !enabled;
}
oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));
}
void setFaceCulling(const bool enable, FaceCulling mode)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_CULL_FACE));
else
oglCheck(glDisable(GL_CULL_FACE));
enabled = !enabled;
}
oglCheck(glCullFace(faceCullings[mode]));
}
// Private
Graphics::Graphics()
: m_windowHandle(0),
m_windowSettings()
{
char* myargv[1];
int myargc = 1;
myargv[0] = strdup("UtH Engine");
glutInit(&myargc, myargv);
glewInit();
}
Graphics::~Graphics()
{
destroyWindow();
}
}<commit_msg>Fixed GLEW initialization shenanigans<commit_after>#include <UtH\Platform\Graphics.hpp>
#include <UtH\Platform\Configuration.hpp>
#include <UtH\Platform\OpenGL.hpp>
#include <UtH\Platform\OGLCheck.hpp>
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "freeglut_staticd.lib")
#pragma comment(lib, "glew32sd.lib")
#else // Release
// FIXME: Static 'Release' version of the GLEW lib breaks the build
// consider using dynamic linking for release
#pragma comment(lib, "freeglut_static.lib")
#pragma comment(lib, "glew32sd.lib")
#endif
namespace uth
{
static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,
GL_FRAGMENT_SHADER};
static int dataTypes[DATATYPE_LAST] = {GL_BYTE,
GL_UNSIGNED_BYTE,
GL_SHORT,
GL_UNSIGNED_SHORT,
GL_INT,
GL_UNSIGNED_INT,
GL_FLOAT,
GL_DOUBLE};
static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,
GL_READ_BUFFER,
GL_COPY_WRITE_BUFFER,
GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER,
GL_PIXEL_UNPACK_BUFFER,
GL_TEXTURE_BUFFER,
GL_TRANSFORM_FEEDBACK_BUFFER,
GL_UNIFORM_BUFFER};
static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,
GL_STREAM_READ,
GL_STREAM_COPY,
GL_STATIC_DRAW,
GL_STATIC_READ,
GL_STATIC_COPY,
GL_DYNAMIC_DRAW,
GL_DYNAMIC_READ,
GL_DYNAMIC_COPY};
static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,
GL_PACK_LSB_FIRST,
GL_PACK_ROW_LENGTH,
GL_PACK_IMAGE_HEIGHT,
GL_PACK_SKIP_PIXELS,
GL_PACK_SKIP_ROWS,
GL_PACK_SKIP_IMAGES,
GL_PACK_ALIGNMENT,
GL_UNPACK_SWAP_BYTES,
GL_UNPACK_LSB_FIRST,
GL_UNPACK_ROW_LENGTH,
GL_UNPACK_IMAGE_HEIGHT,
GL_UNPACK_SKIP_PIXELS,
GL_UNPACK_SKIP_ROWS,
GL_UNPACK_SKIP_IMAGES,
GL_UNPACK_ALIGNMENT};
static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D,
TEXTURE_2D,
TEXTURE_3D,
TEXTURE_1D_ARRAY,
TEXTURE_2D_ARRAY,
TEXTURE_RECTANGLE,
TEXTURE_CUBE_MAP,
TEXTURE_2D_MULTISAMPLE,
TEXTURE_2D_MULTISAMPLE_ARRAY};
static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,
GL_RGBA};
static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL,
GL_TEXTURE_COMPARE_FUNC,
GL_TEXTURE_COMPARE_MODE,
GL_TEXTURE_LOD_BIAS,
GL_TEXTURE_MIN_FILTER,
GL_TEXTURE_MAG_FILTER,
GL_TEXTURE_MIN_LOD,
GL_TEXTURE_MAX_LOD,
GL_TEXTURE_MAX_LEVEL,
GL_TEXTURE_SWIZZLE_R,
GL_TEXTURE_SWIZZLE_G,
GL_TEXTURE_SWIZZLE_B,
GL_TEXTURE_SWIZZLE_A,
GL_TEXTURE_WRAP_S,
GL_TEXTURE_WRAP_T,
GL_TEXTURE_WRAP_R};
static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_LINES,
GL_LINE_STRIP_ADJACENCY,
GL_LINES_ADJACENCY,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_TRIANGLES,
GL_TRIANGLE_STRIP_ADJACENCY,
GL_TRIANGLES_ADJACENCY};
static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS};
static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_CONSTANT_COLOR,
GL_ONE_MINUS_CONSTANT_COLOR,
GL_CONSTANT_ALPHA,
GL_ONE_MINUS_CONSTANT_ALPHA};
static int faceCullings[FACECULLING_LAST] = {GL_FRONT,
GL_BACK,
GL_FRONT_AND_BACK};
// Window functions
bool Graphics::createWindow(const WindowSettings& settings)
{
if (m_windowHandle) destroyWindow();
m_windowSettings = settings;
// Context settings
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
// Extra settings
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
// Position & size
glutInitWindowPosition(settings.position.x, settings.position.y);
glutInitWindowSize(settings.size.x, settings.size.y);
// Display settings
glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |
settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |
settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |
settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);
int majorVer = settings.contextVersionMajor,
minorVer = settings.contextVersionMinor;
glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);
m_windowHandle = glutCreateWindow("Generic Window Title");
glewInit();
return true;
}
void Graphics::destroyWindow()
{
oglCheck(glutDestroyWindow(m_windowHandle));
}
void Graphics::clear(const float r, const float g, const float b, const float a)
{
oglCheck(glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
oglCheck(glClearColor(r, g, b, a));
if (!m_windowSettings.useDepthBuffer) return;
#ifdef UTH_SYSTEM_OPENGLES
oglCheck(glClearDepthf(1));
#else
oglCheck(glClearDepth(1));
#endif
if (!m_windowSettings.useStencilBuffer) return;
oglCheck(glClearStencil(1));
}
void Graphics::swapBuffers()
{
oglCheck(glutSwapBuffers());
}
void setViewport(const int x, const int y, const size_t width, const size_t height)
{
oglCheck(glViewport(x, y, width, height));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Shaders
int Graphics::createShaderProgram()
{
return glCreateProgram();
}
bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)
{
if (!shaderCode) return false;
unsigned int shader = glCreateShader(shaderTypes[type]);
oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));
oglCheck(glCompileShader(shader));
int success;
oglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));
if (!success)
{
glDeleteShader(shader);
return false;
}
oglCheck(glAttachShader(shaderProgram, shader));
oglCheck(glDeleteShader(shader));
return true;
}
bool Graphics::linkShaderProgram(const int shaderProgram)
{
oglCheck(glLinkProgram(shaderProgram));
int success;
oglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));
if (!success)
{
destroyShaderProgram(shaderProgram);
return false;
}
return true;
}
void Graphics::bindProgram(const int shaderProgram)
{
if (shaderProgram)
oglCheck(glUseProgram(shaderProgram));
}
void unbindProgram()
{
oglCheck(glUseProgram(0));
}
void Graphics::destroyShaderProgram(const int shaderProgram)
{
oglCheck(glDeleteProgram(shaderProgram));
}
int Graphics::getUniformLocation(const int shaderProgram, const char* name)
{
return glGetUniformLocation(shaderProgram, name);
}
int Graphics::getAttributeLocation(const int shaderProgram, const char* name)
{
return glGetAttribLocation(shaderProgram, name);
}
void Graphics::setUniform(const int location, const float x)
{
oglCheck(glUniform1f(location, x));
}
void Graphics::setUniform(const int location, const float x, const float y)
{
oglCheck(glUniform2f(location, x, y));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z)
{
oglCheck(glUniform3f(location, x, y, z));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)
{
oglCheck(glUniform4f(location, x, y, z, w));
}
void Graphics::setUniform(const int location, const umath::vector2& vector)
{
oglCheck(glUniform2fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector3& vector)
{
oglCheck(glUniform3fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector4& vector)
{
oglCheck(glUniform4fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::matrix3& matrix)
{
oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::setUniform(const int location, const umath::matrix4& matrix)
{
oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::enableVertexAttribArray(const int location)
{
oglCheck(glEnableVertexAttribArray(location));
}
void Graphics::disableVertexAttribArray(const int location)
{
oglCheck(glDisableVertexAttribArray(location));
}
void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)
{
oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Buffers
void generateBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glGenBuffers(amount, buffers));
}
void deleteBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glDeleteBuffers(amount, buffers));
}
void bindBuffer(BufferType type, const unsigned int buffer)
{
oglCheck(glBindBuffer(bufferTypes[type], buffer));
}
void setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)
{
oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));
}
void setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)
{
oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Texture functions
void setPixelStore(PixelStoreParam param, const int value)
{
oglCheck(glPixelStorei(pixelStoreParams[param], value));
}
void generateTextures(const unsigned int amount, unsigned int* data)
{
oglCheck(glGenTextures(amount, data));
}
void setActiveTexUnit(TexUnit unit)
{
oglCheck(glActiveTexture(unit));
}
void bindTexture(TextureType type, const int texture)
{
oglCheck(glBindTexture(textureTypes[type], texture));
}
void setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void setTextureParameter(TextureType type, TextureParam param, const int value)
{
oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Drawing functions
void drawArrays(PrimitiveType type, const int first, const size_t count)
{
oglCheck(glDrawArrays(primitiveTypes[type], first, count));
}
void drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)
{
oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));
}
void setPointSize(const float size)
{
oglCheck(glPointSize(size));
}
void setLineWidth(const float width)
{
oglCheck(glLineWidth(width));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Other
void flush()
{
oglCheck(glFlush());
}
void setDepthFunction(const bool enable, DepthFunction func)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_DEPTH_TEST));
else
oglCheck(glDisable(GL_DEPTH_TEST));
enabled = !enabled;
}
oglCheck(glDepthFunc(depthFunctions[func]));
}
void setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_BLEND));
else
oglCheck(glDisable(GL_BLEND));
enabled = !enabled;
}
oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));
}
void setFaceCulling(const bool enable, FaceCulling mode)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_CULL_FACE));
else
oglCheck(glDisable(GL_CULL_FACE));
enabled = !enabled;
}
oglCheck(glCullFace(faceCullings[mode]));
}
// Private
Graphics::Graphics()
: m_windowHandle(0),
m_windowSettings()
{
char* myargv[1];
int myargc = 1;
myargv[0] = strdup("UtH Engine");
glutInit(&myargc, myargv);
}
Graphics::~Graphics()
{
destroyWindow();
}
}<|endoftext|> |
<commit_before>/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ShortMacros.h"
#include "Context.h"
#include "CoordinatorServerList.h"
#include "CoordinatorSession.h"
#include "ServerIdRpcWrapper.h"
#include "Cycles.h"
#include "RamCloud.h"
namespace RAMCloud {
bool ServerIdRpcWrapper::convertExceptionsToDoesntExist = false;
/**
* Constructor for ServerIdRpcWrapper objects.
* \param context
* Overall information about the RAMCloud server.
* \param id
* The server to which this RPC should be sent. The RPC will be
* retried as long as this server is still up.
* \param responseHeaderLength
* The size of header expected in the response for this RPC;
* incoming responses will be checked here to ensure that they
* contain at least this much data, and a pointer to the header
* will be stored in the responseHeader for the use of wrapper
* subclasses.
* \param response
* Optional client-supplied buffer to use for the RPC's response;
* if NULL then we use a built-in buffer.
*/
ServerIdRpcWrapper::ServerIdRpcWrapper(Context* context, ServerId id,
uint32_t responseHeaderLength, Buffer* response)
: RpcWrapper(responseHeaderLength, response)
, context(context)
, id(id)
, serverDown(false)
{
}
// See RpcWrapper for documentation.
bool
ServerIdRpcWrapper::handleTransportError()
{
if (convertExceptionsToDoesntExist) {
serverDown = true;
return true;
}
// There was a transport-level failure. The transport should already
// have logged this. Retry unless the server is down.
if (serverDown) {
// We've already done everything we can; no need to repeat the
// work (returning now eliminates some duplicate log messages that
// would occur during testing otherwise).
return true;
}
context->serverList->flushSession(id);
if (!context->serverList->isUp(id)) {
serverDown = true;
return true;
}
send();
return false;
}
// See RpcWrapper for documentation.
void
ServerIdRpcWrapper::send()
{
assert(context->serverList != NULL);
session = context->serverList->getSession(id);
state = IN_PROGRESS;
session->sendRequest(&request, response, this);
}
/**
* Wait for the RPC to complete, and throw exceptions for any errors.
*
* \throw ServerNotUpException
* The intended server for this RPC is not part of the cluster;
* if it ever existed, it has since crashed.
*/
void
ServerIdRpcWrapper::waitAndCheckErrors()
{
// Note: this method is a generic shared version for RPCs that don't
// return results and don't need to do any processing of the response
// packet except checking for errors.
waitInternal(context->dispatch);
if (serverDown) {
throw ServerNotUpException(HERE);
}
if (responseHeader->status != STATUS_OK)
ClientException::throwException(HERE, responseHeader->status);
}
} // namespace RAMCloud
<commit_msg>Copied docs from header to cc for convertExceptionsToDoesntExist.<commit_after>/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ShortMacros.h"
#include "Context.h"
#include "CoordinatorServerList.h"
#include "CoordinatorSession.h"
#include "ServerIdRpcWrapper.h"
#include "Cycles.h"
#include "RamCloud.h"
namespace RAMCloud {
/// For testing; prefer using ConvertExceptionsToDoesntExist where possible.
/// When set instead of retrying the rpc on a TransportException all
/// instances of this wrapper will internally flag the server as down
/// instead. This causes waiting on the rpc throw a
/// ServerNotUpException. Useful with MockTransport to convert
/// responses set with transport.setInput(NULL) to
/// ServerNotUpExceptions.
bool ServerIdRpcWrapper::convertExceptionsToDoesntExist = false;
/**
* Constructor for ServerIdRpcWrapper objects.
* \param context
* Overall information about the RAMCloud server.
* \param id
* The server to which this RPC should be sent. The RPC will be
* retried as long as this server is still up.
* \param responseHeaderLength
* The size of header expected in the response for this RPC;
* incoming responses will be checked here to ensure that they
* contain at least this much data, and a pointer to the header
* will be stored in the responseHeader for the use of wrapper
* subclasses.
* \param response
* Optional client-supplied buffer to use for the RPC's response;
* if NULL then we use a built-in buffer.
*/
ServerIdRpcWrapper::ServerIdRpcWrapper(Context* context, ServerId id,
uint32_t responseHeaderLength, Buffer* response)
: RpcWrapper(responseHeaderLength, response)
, context(context)
, id(id)
, serverDown(false)
{
}
// See RpcWrapper for documentation.
bool
ServerIdRpcWrapper::handleTransportError()
{
if (convertExceptionsToDoesntExist) {
serverDown = true;
return true;
}
// There was a transport-level failure. The transport should already
// have logged this. Retry unless the server is down.
if (serverDown) {
// We've already done everything we can; no need to repeat the
// work (returning now eliminates some duplicate log messages that
// would occur during testing otherwise).
return true;
}
context->serverList->flushSession(id);
if (!context->serverList->isUp(id)) {
serverDown = true;
return true;
}
send();
return false;
}
// See RpcWrapper for documentation.
void
ServerIdRpcWrapper::send()
{
assert(context->serverList != NULL);
session = context->serverList->getSession(id);
state = IN_PROGRESS;
session->sendRequest(&request, response, this);
}
/**
* Wait for the RPC to complete, and throw exceptions for any errors.
*
* \throw ServerNotUpException
* The intended server for this RPC is not part of the cluster;
* if it ever existed, it has since crashed.
*/
void
ServerIdRpcWrapper::waitAndCheckErrors()
{
// Note: this method is a generic shared version for RPCs that don't
// return results and don't need to do any processing of the response
// packet except checking for errors.
waitInternal(context->dispatch);
if (serverDown) {
throw ServerNotUpException(HERE);
}
if (responseHeader->status != STATUS_OK)
ClientException::throwException(HERE, responseHeader->status);
}
} // namespace RAMCloud
<|endoftext|> |
<commit_before>/*
* System_httpServer.cpp
*
* Created on: Jun 15, 2014
* Author: Pimenta
*/
// this
#include "System.hpp"
// standard
#include <cstring>
#include <cstdio>
#include <string>
// local
#include "Defines.hpp"
#include "Concurrency.hpp"
#include "Network.hpp"
#include "Helpers.hpp"
#include "FileSystem.hpp"
using namespace std;
using namespace concurrency;
using namespace network;
using namespace helpers;
// static variables
static TCPConnection* client = nullptr;
static ByteQueue fileData;
static void recvFile() {
size_t fileSize;
string tmp;
while(true){
tmp = "";
for (char c; (c = client->recv<char>()) != '\n'; tmp += c);
if(tmp.find("Tamanho") != string::npos){
fileSize = fromString<size_t>(tmp.substr(tmp.find(":") + 1, tmp.size() - 2).c_str());
} else if (tmp == "\r"){
break;
}
}
while(true){
tmp = "";
for (char c; (c = client->recv<char>()) != '\n'; tmp += c);
if (tmp == "\r"){
break;
}
}
size_t bytesRecvd = 0;
ByteQueue buf;
fileData.resize(0);
while (bytesRecvd < fileSize) {
size_t diff = fileSize - bytesRecvd;
buf.resize(SIZE_FILEUPLOAD_MAXLEN < diff ? SIZE_FILEUPLOAD_MAXLEN : diff);
client->recv(buf);
bytesRecvd += buf.size();
fileData.push(buf.ptr(), buf.size());
}
printf("Tamanho: %d\n", bytesRecvd);
fflush(stdout);
client->recv<char>();
client->recv<char>();
for (char c; (c = client->recv<char>()) != '\n';);
}
void System::httpServer() {
client = httpTCPServer.accept();
if (client == nullptr)
return;
string requestLine;
// check dumb requests
{
char c;
if (!client->recv(&c, 1)) return;
else requestLine += c;
}
for (char c; (c = client->recv<char>()) != '\n'; requestLine += c); // receive the request line
for (; requestLine[0] != ' '; requestLine = requestLine.substr(1, requestLine.size())); // remove method
requestLine = requestLine.substr(1, requestLine.size()); // remove space after method
for (; requestLine[requestLine.size() - 1] != ' '; requestLine = requestLine.substr(0, requestLine.size() - 1)); // remove http version
requestLine = requestLine.substr(0, requestLine.size() - 1);// remove space before http version
if (requestLine.find("Cfile") != string::npos)
recvFile();
else { // if the request is NOT for file upload
fileData.resize(SIZE_HTTPSERVER_MAXLEN);
client->recv(fileData); // actually, this is the request body... discarding
}
if (requestLine.find("?") != string::npos) {
httpServer_dataRequest(requestLine);
} else {
if (requestLine == "/")
requestLine += "/index.html";
FILE* fp = fopen((string("./www") + requestLine).c_str(), "rb");
if (fp) {
if (requestLine.find(".html") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/html\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else if (requestLine.find(".css") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/css\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else if (requestLine.find(".js") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: application/javascript\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: application/octet-stream\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
client->send(FileSystem::readFile(fp));
fclose(fp);
}
else {
const char* msg =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/html\r\n"
"\r\n"
"<html><body>Pagina nao encontrada.</body></html>"
;
client->send(msg, strlen(msg) + 1);
}
}
delete client;
client = nullptr;
}
void System::httpServer_dataRequest(const string& cRequest) {
string request = cRequest.substr(cRequest.find("?") + 1, cRequest.size());
if (request == "logout"){
client->send(string("1"), true);
changeToLogin();
} else if (request == "host-ip"){
client->send(localAddress.toString());
} else if( request == "total-files" ){
client->send(toString(FileSystem::getTotalFiles()));
} else if( request == "username" ){
client->send(users[localAddress.ip].name);
} else if( request == "total-folders" ){
client->send(toString(FileSystem::getTotalFolders()));
} else if( request == "total-size" ){
client->send(toString(FileSystem::getTotalSize()));
} else if( request == "n-hosts" ){
client->send(toString(users.size()));
} else if( request == "server-state" ){
client->send("1");
} else if( request.find("folder-tfolders") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalFolders()));
} else if( request.find("folder-tfiles") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalFiles()));
} else if( request.find("folder-tsize") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalSize()));
} else if( request.find("Cfolder") != string::npos ){
string tmp = request.substr(request.find("=") + 1, request.size());
if(!FileSystem::createFolder(tmp)){
client->send("0");
} else {
client->send(string("1"), true);
send_createFolder(tmp);
}
} else if( request.find("RfolderPath") != string::npos ){
string folderPath = request.substr(request.find("=") + 1, request.size());
string foundPath;
FileSystem::retrieveFolder(folderPath, foundPath);
client->send(foundPath, true);
} else if( request.find("Rfolder") != string::npos ){
string folderPath = request.substr(request.find("=") + 1, request.size());
string foundPath;
FileSystem::Folder* folder = FileSystem::retrieveFolder(folderPath, foundPath);
if (!folder){
client->send("0");
return;
}
string tableContent;
for(auto& kv : folder->subfolders) {
tableContent += "<tr><td><img src='img/folder.png'/></td><td><label onclick='retrieveFolder(\"";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\")'>";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "</label></td><td>";
tableContent += toString(kv.second.getTotalSize());
tableContent += "</td><td></td><td><a onclick='editFolder(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/edit.png'/></a><a onclick='deleteFolder(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/delete.png'/></a></td></tr>";
}
for(auto& kv : folder->files){
tableContent += "<tr><td><img src='img/fileimg.png'/></td><td><label onclick='retrieveFile(";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += ")'>";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "</label></td><td>";
tableContent += toString(kv.second.size);
tableContent += "</td><td>";
tableContent += kv.second.author;
tableContent += "</td><td><a onclick='editFile(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/edit.png'/></a><a onclick='deleteFile(\"";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\")'><img src='img/delete.png'/></a><a href=\"http://";
tableContent += Address(kv.second.peer1, Address("", TCP_HTTPSERVER).port).toString();
tableContent += "/?Rfile=";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\" download=\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\"><img src='img/download.png'/></a><a href=\"http://";
tableContent += Address(kv.second.peer2, Address("", TCP_HTTPSERVER).port).toString();
tableContent += "/?Rfile=";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\" download=\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\"><img src='img/download.png'/></a></td></tr>";
}
client->send(tableContent);
} else if( request.find("Ufolder") != string::npos ){
string data = request.substr(request.find("=") + 1, request.size());
string oldPath = data.substr(0, data.find("?&"));
string newName = data.substr(data.find("?&") + 2, data.size());
if(!FileSystem::updateFolder(oldPath, newName))
client->send("0");
else {
client->send(string("1"), true);
send_updateFolder(oldPath, newName);
}
} else if( request.find("Dfolder") != string::npos ){
string tmp = string(request).substr(string(request).find("=") + 1, request.size());
if(!FileSystem::deleteFolder(tmp)){
client->send("0");
} else {
client->send(string("1"), true);
send_deleteFolder(tmp);
}
} else if( request.find("Cfile") != string::npos ){
string fullPath = request.substr(request.find("=") + 1, request.size());
FileSystem::File* file = FileSystem::createFile(fullPath, fileData, users[localAddress.ip].name);
if(!file){
client->send("0");
} else {
client->send(string("1"), true);
ByteQueue info;
file->serialize(info);
send_createFile(fullPath, info);
}
} else if( request.find("Rfile") != string::npos ){
FileSystem::File* file = FileSystem::retrieveFile(string(request).substr(string(request).find("=") + 1, request.size()));
if (file)
client->send(file->read());
} else if( request.find("Ufile") != string::npos ){
string data = request.substr(request.find("=") + 1, request.size());
string oldPath = data.substr(0, data.find("?&"));
string newName = data.substr(data.find("?&") + 2, data.size());
if(!FileSystem::updateFile(oldPath, newName))
client->send("0");
else {
client->send(string("1"), true);
send_updateFile(oldPath, newName);
}
} else if( request.find("Dfile") != string::npos ){
string fullPath = string(request).substr(string(request).find("=") + 1, request.size());
if(!FileSystem::deleteFile(fullPath)){
client->send("0");
} else {
client->send(string("1"), true);
send_deleteFile(fullPath);
}
} else if( request == "list-users" ){
string tableContent;
for(auto& kv : users) {
tableContent += "<tr><td>";
tableContent += kv.second.name;
tableContent += "</td>";
tableContent += "<td>";
tableContent += Address(kv.first, 0).toString();
tableContent += "</td></tr>";
}
client->send(tableContent);
}
}
<commit_msg>Removing printf<commit_after>/*
* System_httpServer.cpp
*
* Created on: Jun 15, 2014
* Author: Pimenta
*/
// this
#include "System.hpp"
// standard
#include <cstring>
#include <cstdio>
#include <string>
// local
#include "Defines.hpp"
#include "Concurrency.hpp"
#include "Network.hpp"
#include "Helpers.hpp"
#include "FileSystem.hpp"
using namespace std;
using namespace concurrency;
using namespace network;
using namespace helpers;
// static variables
static TCPConnection* client = nullptr;
static ByteQueue fileData;
static void recvFile() {
size_t fileSize;
string tmp;
while(true){
tmp = "";
for (char c; (c = client->recv<char>()) != '\n'; tmp += c);
if(tmp.find("Tamanho") != string::npos){
fileSize = fromString<size_t>(tmp.substr(tmp.find(":") + 1, tmp.size() - 2).c_str());
} else if (tmp == "\r"){
break;
}
}
while(true){
tmp = "";
for (char c; (c = client->recv<char>()) != '\n'; tmp += c);
if (tmp == "\r"){
break;
}
}
size_t bytesRecvd = 0;
ByteQueue buf;
fileData.resize(0);
while (bytesRecvd < fileSize) {
size_t diff = fileSize - bytesRecvd;
buf.resize(SIZE_FILEUPLOAD_MAXLEN < diff ? SIZE_FILEUPLOAD_MAXLEN : diff);
client->recv(buf);
bytesRecvd += buf.size();
fileData.push(buf.ptr(), buf.size());
}
client->recv<char>();
client->recv<char>();
for (char c; (c = client->recv<char>()) != '\n';);
}
void System::httpServer() {
client = httpTCPServer.accept();
if (client == nullptr)
return;
string requestLine;
// check dumb requests
{
char c;
if (!client->recv(&c, 1)) return;
else requestLine += c;
}
for (char c; (c = client->recv<char>()) != '\n'; requestLine += c); // receive the request line
for (; requestLine[0] != ' '; requestLine = requestLine.substr(1, requestLine.size())); // remove method
requestLine = requestLine.substr(1, requestLine.size()); // remove space after method
for (; requestLine[requestLine.size() - 1] != ' '; requestLine = requestLine.substr(0, requestLine.size() - 1)); // remove http version
requestLine = requestLine.substr(0, requestLine.size() - 1);// remove space before http version
if (requestLine.find("Cfile") != string::npos)
recvFile();
else { // if the request is NOT for file upload
fileData.resize(SIZE_HTTPSERVER_MAXLEN);
client->recv(fileData); // actually, this is the request body... discarding
}
if (requestLine.find("?") != string::npos) {
httpServer_dataRequest(requestLine);
} else {
if (requestLine == "/")
requestLine += "/index.html";
FILE* fp = fopen((string("./www") + requestLine).c_str(), "rb");
if (fp) {
if (requestLine.find(".html") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/html\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else if (requestLine.find(".css") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/css\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else if (requestLine.find(".js") != string::npos) {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: application/javascript\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
else {
const char* header =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: application/octet-stream\r\n"
"\r\n"
;
client->send(header, strlen(header));
}
client->send(FileSystem::readFile(fp));
fclose(fp);
}
else {
const char* msg =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\r"
"Content-Type: text/html\r\n"
"\r\n"
"<html><body>Pagina nao encontrada.</body></html>"
;
client->send(msg, strlen(msg) + 1);
}
}
delete client;
client = nullptr;
}
void System::httpServer_dataRequest(const string& cRequest) {
string request = cRequest.substr(cRequest.find("?") + 1, cRequest.size());
if (request == "logout"){
client->send(string("1"), true);
changeToLogin();
} else if (request == "host-ip"){
client->send(localAddress.toString());
} else if( request == "total-files" ){
client->send(toString(FileSystem::getTotalFiles()));
} else if( request == "username" ){
client->send(users[localAddress.ip].name);
} else if( request == "total-folders" ){
client->send(toString(FileSystem::getTotalFolders()));
} else if( request == "total-size" ){
client->send(toString(FileSystem::getTotalSize()));
} else if( request == "n-hosts" ){
client->send(toString(users.size()));
} else if( request == "server-state" ){
client->send("1");
} else if( request.find("folder-tfolders") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalFolders()));
} else if( request.find("folder-tfiles") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalFiles()));
} else if( request.find("folder-tsize") != string::npos ){
string tmp;
FileSystem::Folder* folder = FileSystem::retrieveFolder(request.substr(request.find("=") + 1, request.size()), tmp);
if (folder)
client->send(toString(folder->getTotalSize()));
} else if( request.find("Cfolder") != string::npos ){
string tmp = request.substr(request.find("=") + 1, request.size());
if(!FileSystem::createFolder(tmp)){
client->send("0");
} else {
client->send(string("1"), true);
send_createFolder(tmp);
}
} else if( request.find("RfolderPath") != string::npos ){
string folderPath = request.substr(request.find("=") + 1, request.size());
string foundPath;
FileSystem::retrieveFolder(folderPath, foundPath);
client->send(foundPath, true);
} else if( request.find("Rfolder") != string::npos ){
string folderPath = request.substr(request.find("=") + 1, request.size());
string foundPath;
FileSystem::Folder* folder = FileSystem::retrieveFolder(folderPath, foundPath);
if (!folder){
client->send("0");
return;
}
string tableContent;
for(auto& kv : folder->subfolders) {
tableContent += "<tr><td><img src='img/folder.png'/></td><td><label onclick='retrieveFolder(\"";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\")'>";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "</label></td><td>";
tableContent += toString(kv.second.getTotalSize());
tableContent += "</td><td></td><td><a onclick='editFolder(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/edit.png'/></a><a onclick='deleteFolder(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/delete.png'/></a></td></tr>";
}
for(auto& kv : folder->files){
tableContent += "<tr><td><img src='img/fileimg.png'/></td><td><label onclick='retrieveFile(";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += ")'>";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "</label></td><td>";
tableContent += toString(kv.second.size);
tableContent += "</td><td>";
tableContent += kv.second.author;
tableContent += "</td><td><a onclick='editFile(\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\")'><img src='img/edit.png'/></a><a onclick='deleteFile(\"";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\")'><img src='img/delete.png'/></a><a href=\"http://";
tableContent += Address(kv.second.peer1, Address("", TCP_HTTPSERVER).port).toString();
tableContent += "/?Rfile=";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\" download=\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\"><img src='img/download.png'/></a><a href=\"http://";
tableContent += Address(kv.second.peer2, Address("", TCP_HTTPSERVER).port).toString();
tableContent += "/?Rfile=";
tableContent += (folderPath == "/") ? kv.first : folderPath + kv.first;
tableContent += "\" download=\"";
tableContent += kv.first.substr(1, kv.first.size());
tableContent += "\"><img src='img/download.png'/></a></td></tr>";
}
client->send(tableContent);
} else if( request.find("Ufolder") != string::npos ){
string data = request.substr(request.find("=") + 1, request.size());
string oldPath = data.substr(0, data.find("?&"));
string newName = data.substr(data.find("?&") + 2, data.size());
if(!FileSystem::updateFolder(oldPath, newName))
client->send("0");
else {
client->send(string("1"), true);
send_updateFolder(oldPath, newName);
}
} else if( request.find("Dfolder") != string::npos ){
string tmp = string(request).substr(string(request).find("=") + 1, request.size());
if(!FileSystem::deleteFolder(tmp)){
client->send("0");
} else {
client->send(string("1"), true);
send_deleteFolder(tmp);
}
} else if( request.find("Cfile") != string::npos ){
string fullPath = request.substr(request.find("=") + 1, request.size());
FileSystem::File* file = FileSystem::createFile(fullPath, fileData, users[localAddress.ip].name);
if(!file){
client->send("0");
} else {
client->send(string("1"), true);
ByteQueue info;
file->serialize(info);
send_createFile(fullPath, info);
}
} else if( request.find("Rfile") != string::npos ){
FileSystem::File* file = FileSystem::retrieveFile(string(request).substr(string(request).find("=") + 1, request.size()));
if (file)
client->send(file->read());
} else if( request.find("Ufile") != string::npos ){
string data = request.substr(request.find("=") + 1, request.size());
string oldPath = data.substr(0, data.find("?&"));
string newName = data.substr(data.find("?&") + 2, data.size());
if(!FileSystem::updateFile(oldPath, newName))
client->send("0");
else {
client->send(string("1"), true);
send_updateFile(oldPath, newName);
}
} else if( request.find("Dfile") != string::npos ){
string fullPath = string(request).substr(string(request).find("=") + 1, request.size());
if(!FileSystem::deleteFile(fullPath)){
client->send("0");
} else {
client->send(string("1"), true);
send_deleteFile(fullPath);
}
} else if( request == "list-users" ){
string tableContent;
for(auto& kv : users) {
tableContent += "<tr><td>";
tableContent += kv.second.name;
tableContent += "</td>";
tableContent += "<td>";
tableContent += Address(kv.first, 0).toString();
tableContent += "</td></tr>";
}
client->send(tableContent);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: acceleratorexecute.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:03:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
#define INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
//===============================================
// includes
#include <vector>
#ifndef __COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef __COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef __COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef __COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#endif
#ifndef __COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef __COM_SUN_STAR_AWT_KEYEVENT_HPP_
#include <com/sun/star/awt/KeyEvent.hpp>
#endif
#ifndef _SV_KEYCODE_HXX
#include <vcl/keycod.hxx>
#endif
#ifndef _VCL_EVNTPOST_HXX
#include <vcl/evntpost.hxx>
#endif
#ifndef _OSL_MUTEX_H_
#include <osl/mutex.h>
#endif
//===============================================
// namespace
namespace svt
{
#ifdef css
#error "Who define css? I need it as namespace alias."
#else
#define css ::com::sun::star
#endif
//===============================================
// definitions
struct TMutexInit
{
::osl::Mutex m_aLock;
};
//===============================================
/**
@descr implements a helper, which can be used to
convert vcl key codes into awt key codes ...
and reverse.
Further such key code can be triggered.
Doing so different accelerator
configurations are merged together; a suitable
command registered for the given key code is searched
and will be dispatched.
@attention
Because exceution of an accelerator command can be dangerous
(in case it force an office shutdown for key "ALT+F4"!)
all internal dispatches are done asynchronous.
Menas that the trigger call doesnt wait till the dispatch
is finished. You can call very often. All requests will be
queued internal and dispatched ASAP.
Of course this queue will be stopped if the environment
will be destructed ...
*/
class AcceleratorExecute : private TMutexInit
{
//-------------------------------------------
// const, types
private:
/** TODO document me */
typedef ::std::vector< ::rtl::OUString > TCommandQueue;
//-------------------------------------------
// member
private:
/** TODO document me */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** TODO document me */
css::uno::Reference< css::util::XURLTransformer > m_xURLParser;
/** TODO document me */
css::uno::Reference< css::frame::XDispatchProvider > m_xDispatcher;
/** TODO document me */
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xGlobalCfg;
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xModuleCfg;
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xDocCfg;
/** TODO document me */
TCommandQueue m_lCommandQueue;
/** TODO document me */
::vcl::EventPoster m_aAsyncCallback;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short factory method to create new accelerator
helper instance.
@descr Such helper instance must be initialized at first.
So it can know its environment (global/module or
document specific).
Afterwards it can be used to execute incoming
accelerator requests.
The "end of life" of such helper can be reached as follow:
- delete the object
=> If it stands currently in its execute method, they will
be finished. All further queued requests will be removed
and further not executed!
Other modes are possible and will be implemented ASAP :-)
*/
static AcceleratorExecute* createAcceleratorHelper();
//---------------------------------------
/** @short fight against inlining ... */
virtual ~AcceleratorExecute();
//---------------------------------------
/** @short init this instance.
@descr It must be called as first method after creation.
And further it can be called more then once ...
but at least its should be used one times only.
Otherwhise nobody can say, which asynchronous
executions will be used inside the old and which one
will be used inside the new environment.
@param xSMGR
reference to an uno service manager.
@param xEnv
if it points to a valid frame it will be used
to execute the dispatch there. Further the frame
is used to locate the right module configuration
and use it merged together with the document and
the global configuration.
If this parameter is set to NULL, the global configuration
is used only. Further the global Desktop instance is
used for dispatch.
*/
virtual void init(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR,
const css::uno::Reference< css::frame::XFrame >& xEnv );
//---------------------------------------
/** @short trigger this accelerator.
@descr The internal configuartions are used to find
as suitable command for this key code.
This command will be queued and executed later
asynchronous.
@param aKey
specify the accelerator for execute.
*/
virtual void execute(const KeyCode& aKey);
virtual void execute(const css::awt::KeyEvent& aKey);
//---------------------------------------
/** TODO document me */
static css::awt::KeyEvent st_VCLKey2AWTKey(const KeyCode& aKey);
static KeyCode st_AWTKey2VCLKey(const css::awt::KeyEvent& aKey);
//-------------------------------------------
// internal
private:
//---------------------------------------
/** @short allow creation of instances of this class
by using our factory only!
*/
AcceleratorExecute();
AcceleratorExecute(const AcceleratorExecute& rCopy);
void operator=(const AcceleratorExecute& rCopy) {};
//---------------------------------------
/** TODO document me */
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openGlobalConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openModuleConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame);
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel);
//---------------------------------------
/** TODO document me */
::rtl::OUString impl_ts_findCommand(const css::awt::KeyEvent& aKey);
//---------------------------------------
/** TODO document me */
css::uno::Reference< css::util::XURLTransformer > impl_ts_getURLParser();
//---------------------------------------
/** TODO document me */
DECL_LINK(impl_ts_asyncCallback, void*);
};
#undef css
#undef css
} // namespace svt
#endif // INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.458); FILE MERGED 2008/04/01 15:18:33 thb 1.4.458.2: #i85898# Stripping all external header guards 2008/03/28 15:35:08 rt 1.4.458.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: acceleratorexecute.hxx,v $
* $Revision: 1.5 $
*
* 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 INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
#define INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
//===============================================
// includes
#include <vector>
#ifndef __COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef __COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef __COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef __COM_SUN_STAR_UI_XACCELERATORCONFIGURATION_HPP_
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#endif
#ifndef __COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef __COM_SUN_STAR_AWT_KEYEVENT_HPP_
#include <com/sun/star/awt/KeyEvent.hpp>
#endif
#include <vcl/keycod.hxx>
#include <vcl/evntpost.hxx>
#include <osl/mutex.h>
//===============================================
// namespace
namespace svt
{
#ifdef css
#error "Who define css? I need it as namespace alias."
#else
#define css ::com::sun::star
#endif
//===============================================
// definitions
struct TMutexInit
{
::osl::Mutex m_aLock;
};
//===============================================
/**
@descr implements a helper, which can be used to
convert vcl key codes into awt key codes ...
and reverse.
Further such key code can be triggered.
Doing so different accelerator
configurations are merged together; a suitable
command registered for the given key code is searched
and will be dispatched.
@attention
Because exceution of an accelerator command can be dangerous
(in case it force an office shutdown for key "ALT+F4"!)
all internal dispatches are done asynchronous.
Menas that the trigger call doesnt wait till the dispatch
is finished. You can call very often. All requests will be
queued internal and dispatched ASAP.
Of course this queue will be stopped if the environment
will be destructed ...
*/
class AcceleratorExecute : private TMutexInit
{
//-------------------------------------------
// const, types
private:
/** TODO document me */
typedef ::std::vector< ::rtl::OUString > TCommandQueue;
//-------------------------------------------
// member
private:
/** TODO document me */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** TODO document me */
css::uno::Reference< css::util::XURLTransformer > m_xURLParser;
/** TODO document me */
css::uno::Reference< css::frame::XDispatchProvider > m_xDispatcher;
/** TODO document me */
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xGlobalCfg;
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xModuleCfg;
css::uno::Reference< css::ui::XAcceleratorConfiguration > m_xDocCfg;
/** TODO document me */
TCommandQueue m_lCommandQueue;
/** TODO document me */
::vcl::EventPoster m_aAsyncCallback;
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short factory method to create new accelerator
helper instance.
@descr Such helper instance must be initialized at first.
So it can know its environment (global/module or
document specific).
Afterwards it can be used to execute incoming
accelerator requests.
The "end of life" of such helper can be reached as follow:
- delete the object
=> If it stands currently in its execute method, they will
be finished. All further queued requests will be removed
and further not executed!
Other modes are possible and will be implemented ASAP :-)
*/
static AcceleratorExecute* createAcceleratorHelper();
//---------------------------------------
/** @short fight against inlining ... */
virtual ~AcceleratorExecute();
//---------------------------------------
/** @short init this instance.
@descr It must be called as first method after creation.
And further it can be called more then once ...
but at least its should be used one times only.
Otherwhise nobody can say, which asynchronous
executions will be used inside the old and which one
will be used inside the new environment.
@param xSMGR
reference to an uno service manager.
@param xEnv
if it points to a valid frame it will be used
to execute the dispatch there. Further the frame
is used to locate the right module configuration
and use it merged together with the document and
the global configuration.
If this parameter is set to NULL, the global configuration
is used only. Further the global Desktop instance is
used for dispatch.
*/
virtual void init(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR,
const css::uno::Reference< css::frame::XFrame >& xEnv );
//---------------------------------------
/** @short trigger this accelerator.
@descr The internal configuartions are used to find
as suitable command for this key code.
This command will be queued and executed later
asynchronous.
@param aKey
specify the accelerator for execute.
*/
virtual void execute(const KeyCode& aKey);
virtual void execute(const css::awt::KeyEvent& aKey);
//---------------------------------------
/** TODO document me */
static css::awt::KeyEvent st_VCLKey2AWTKey(const KeyCode& aKey);
static KeyCode st_AWTKey2VCLKey(const css::awt::KeyEvent& aKey);
//-------------------------------------------
// internal
private:
//---------------------------------------
/** @short allow creation of instances of this class
by using our factory only!
*/
AcceleratorExecute();
AcceleratorExecute(const AcceleratorExecute& rCopy);
void operator=(const AcceleratorExecute& rCopy) {};
//---------------------------------------
/** TODO document me */
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openGlobalConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openModuleConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame);
css::uno::Reference< css::ui::XAcceleratorConfiguration > impl_st_openDocConfig(const css::uno::Reference< css::frame::XModel >& xModel);
//---------------------------------------
/** TODO document me */
::rtl::OUString impl_ts_findCommand(const css::awt::KeyEvent& aKey);
//---------------------------------------
/** TODO document me */
css::uno::Reference< css::util::XURLTransformer > impl_ts_getURLParser();
//---------------------------------------
/** TODO document me */
DECL_LINK(impl_ts_asyncCallback, void*);
};
#undef css
#undef css
} // namespace svt
#endif // INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
#define IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
#include <mutex>
namespace iox
{
namespace concurrent
{
struct ForwardArgsToCTor_t
{
};
constexpr ForwardArgsToCTor_t ForwardArgsToCTor{};
/// @brief The smart_lock class is a wrapping class which can be used to make
/// an arbitrary class threadsafe by wrapping it with the help of the
/// arrow operator.
/// IMPORTANT: If you generate a threadsafe container with smart_lock,
/// only the container is threadsafe not the containing
/// elements!
/// @code
/// #include <algorithm>
/// #include <vector>
/// #include "smart_lock.hpp"
///
/// int main() {
/// concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123);
/// threadSafeVector->push_back(456);
/// threadSafeVector->push_back(789);
/// size_t vectorSize = threadSafeVector->size();
///
/// {
/// auto guardedVector = threadSafeVector.getScopeGuard();
/// auto iter = std::find(guardVector->begin(), guardVector->end(), 456);
/// if (iter != guardVector->end()) guardVector->erase(iter);
/// }
/// }
/// @endcode
template <typename T, typename MutexType = ::std::mutex>
class smart_lock
{
private:
class Proxy
{
public:
Proxy(T& base, MutexType& lock) noexcept;
~Proxy() noexcept;
Proxy(const Proxy&) noexcept = default;
Proxy(Proxy&&) noexcept = default;
Proxy& operator=(const Proxy&) noexcept = default;
Proxy& operator=(Proxy&&) noexcept = default;
T* operator->() noexcept;
const T* operator->() const noexcept;
private:
T& base;
MutexType& lock;
};
public:
/// @brief c'tor creating empty smart_lock
smart_lock() noexcept = default;
/// @brief c'tor forwarding all args to the underlying object
/// @param[in] ForwardArgsToCTor is a compile time constant to indicate that this constructor forwards all arguments
/// to the underlying object
/// @param[in] args are the arguments that are forwarded to the underlying object
template <typename... ArgTypes>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in Doxygen documentation
explicit smart_lock(ForwardArgsToCTor_t, ArgTypes&&... args) noexcept;
smart_lock(const smart_lock& rhs) noexcept;
smart_lock(smart_lock&& rhs) noexcept;
smart_lock& operator=(const smart_lock& rhs) noexcept;
smart_lock& operator=(smart_lock&& rhs) noexcept;
~smart_lock() noexcept = default;
/// @brief The arrow operator returns a proxy object which locks the mutex
/// of smart_lock and has another arrow operator defined which
/// returns the pointer of the underlying object. You use this
/// operator to call an arbitrary method of the base object which
/// is secured by the smart_lock mutex
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123); // this call is secured by a mutex
/// @endcode
Proxy operator->() noexcept;
/// @brief The arrow operator returns a proxy object which locks the mutex
/// of smart_lock and has another arrow operator defined which
/// returns the pointer of the underlying object. You use this
/// operator to call an arbitrary method of the base object which
/// is secured by the smart_lock mutex
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123); // this call is secured by a mutex
/// @endcode
const Proxy operator->() const noexcept;
/// @brief If you need to lock your object over multiple method calls you
/// acquire a scope guard which locks the object as long as this
/// guard is in scope, like a std::lock_guard.
///
/// IMPORTANT:
/// You need to work with this guard in that scope and not with the
/// smart_lock object, otherwise a deadlock occurs!
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
///
/// // The following scope is secured by the smart_lock mutex. In that
/// // scope you should not use the -> operator of threadSafeVector
/// // since it would lead to a deadlock.
/// // You access the underlying object by using the vectorGuard object!
/// {
/// auto vectorGuard = threadSafeVector.getScopeGuard();
/// auto iter = std::find(vectorGuard->begin(), vectorGuard->end(),
/// 123);
/// if ( iter != vectorGuard->end() )
/// vectorGuard->erase(iter);
/// }
Proxy getScopeGuard() noexcept;
/// @brief If you need to lock your object over multiple method calls you
/// acquire a scope guard which locks the object as long as this
/// guard is in scope, like a std::lock_guard.
///
/// IMPORTANT:
/// You need to work with this guard in that scope and not with the
/// smart_lock object, otherwise a deadlock occurs!
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
///
/// // The following scope is secured by the smart_lock mutex. In that
/// // scope you should not use the -> operator of threadSafeVector
/// // since it would lead to a deadlock.
/// // You access the underlying object by using the vectorGuard object!
/// {
/// auto vectorGuard = threadSafeVector.getScopeGuard();
/// auto iter = std::find(vectorGuard->begin(), vectorGuard->end(),
/// 123);
/// if ( iter != vectorGuard->end() )
/// vectorGuard->erase(iter);
/// }
const Proxy getScopeGuard() const noexcept;
/// @brief Returns a copy of the underlying object
T getCopy() const noexcept;
private:
T base;
mutable MutexType lock;
};
} // namespace concurrent
} // namespace iox
#include "iceoryx_hoofs/internal/concurrent/smart_lock.inl"
#endif // IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
<commit_msg>iox-#1196 Remove noexcept from smart_lock default c'tor<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
#define IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
#include <mutex>
namespace iox
{
namespace concurrent
{
struct ForwardArgsToCTor_t
{
};
constexpr ForwardArgsToCTor_t ForwardArgsToCTor{};
/// @brief The smart_lock class is a wrapping class which can be used to make
/// an arbitrary class threadsafe by wrapping it with the help of the
/// arrow operator.
/// IMPORTANT: If you generate a threadsafe container with smart_lock,
/// only the container is threadsafe not the containing
/// elements!
/// @code
/// #include <algorithm>
/// #include <vector>
/// #include "smart_lock.hpp"
///
/// int main() {
/// concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123);
/// threadSafeVector->push_back(456);
/// threadSafeVector->push_back(789);
/// size_t vectorSize = threadSafeVector->size();
///
/// {
/// auto guardedVector = threadSafeVector.getScopeGuard();
/// auto iter = std::find(guardVector->begin(), guardVector->end(), 456);
/// if (iter != guardVector->end()) guardVector->erase(iter);
/// }
/// }
/// @endcode
template <typename T, typename MutexType = ::std::mutex>
class smart_lock
{
private:
class Proxy
{
public:
Proxy(T& base, MutexType& lock) noexcept;
~Proxy() noexcept;
Proxy(const Proxy&) noexcept = default;
Proxy(Proxy&&) noexcept = default;
Proxy& operator=(const Proxy&) noexcept = default;
Proxy& operator=(Proxy&&) noexcept = default;
T* operator->() noexcept;
const T* operator->() const noexcept;
private:
T& base;
MutexType& lock;
};
public:
/// @brief c'tor creating empty smart_lock
smart_lock() = default;
/// @brief c'tor forwarding all args to the underlying object
/// @param[in] ForwardArgsToCTor is a compile time constant to indicate that this constructor forwards all arguments
/// to the underlying object
/// @param[in] args are the arguments that are forwarded to the underlying object
template <typename... ArgTypes>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in Doxygen documentation
explicit smart_lock(ForwardArgsToCTor_t, ArgTypes&&... args) noexcept;
smart_lock(const smart_lock& rhs) noexcept;
smart_lock(smart_lock&& rhs) noexcept;
smart_lock& operator=(const smart_lock& rhs) noexcept;
smart_lock& operator=(smart_lock&& rhs) noexcept;
~smart_lock() noexcept = default;
/// @brief The arrow operator returns a proxy object which locks the mutex
/// of smart_lock and has another arrow operator defined which
/// returns the pointer of the underlying object. You use this
/// operator to call an arbitrary method of the base object which
/// is secured by the smart_lock mutex
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123); // this call is secured by a mutex
/// @endcode
Proxy operator->() noexcept;
/// @brief The arrow operator returns a proxy object which locks the mutex
/// of smart_lock and has another arrow operator defined which
/// returns the pointer of the underlying object. You use this
/// operator to call an arbitrary method of the base object which
/// is secured by the smart_lock mutex
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
/// threadSafeVector->push_back(123); // this call is secured by a mutex
/// @endcode
const Proxy operator->() const noexcept;
/// @brief If you need to lock your object over multiple method calls you
/// acquire a scope guard which locks the object as long as this
/// guard is in scope, like a std::lock_guard.
///
/// IMPORTANT:
/// You need to work with this guard in that scope and not with the
/// smart_lock object, otherwise a deadlock occurs!
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
///
/// // The following scope is secured by the smart_lock mutex. In that
/// // scope you should not use the -> operator of threadSafeVector
/// // since it would lead to a deadlock.
/// // You access the underlying object by using the vectorGuard object!
/// {
/// auto vectorGuard = threadSafeVector.getScopeGuard();
/// auto iter = std::find(vectorGuard->begin(), vectorGuard->end(),
/// 123);
/// if ( iter != vectorGuard->end() )
/// vectorGuard->erase(iter);
/// }
Proxy getScopeGuard() noexcept;
/// @brief If you need to lock your object over multiple method calls you
/// acquire a scope guard which locks the object as long as this
/// guard is in scope, like a std::lock_guard.
///
/// IMPORTANT:
/// You need to work with this guard in that scope and not with the
/// smart_lock object, otherwise a deadlock occurs!
/// @code
/// iox::concurrent::smart_lock<std::vector<int>> threadSafeVector;
///
/// // The following scope is secured by the smart_lock mutex. In that
/// // scope you should not use the -> operator of threadSafeVector
/// // since it would lead to a deadlock.
/// // You access the underlying object by using the vectorGuard object!
/// {
/// auto vectorGuard = threadSafeVector.getScopeGuard();
/// auto iter = std::find(vectorGuard->begin(), vectorGuard->end(),
/// 123);
/// if ( iter != vectorGuard->end() )
/// vectorGuard->erase(iter);
/// }
const Proxy getScopeGuard() const noexcept;
/// @brief Returns a copy of the underlying object
T getCopy() const noexcept;
private:
T base;
mutable MutexType lock;
};
} // namespace concurrent
} // namespace iox
#include "iceoryx_hoofs/internal/concurrent/smart_lock.inl"
#endif // IOX_HOOFS_CONCURRENT_SMART_LOCK_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
#define MAYBE_TestShowScriptsTab TestShowScriptsTab
#define MAYBE_TestSetBreakpoint TestSetBreakpoint
#elif defined(OS_LINUX)
// http://crbug.com/19748
#define MAYBE_TestShowScriptsTab DISABLED_TestShowScriptsTab
#define MAYBE_TestSetBreakpoint DISABLED_TestSetBreakpoint
#endif
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kDebuggerTestPage);
}
// Tests profiler panel.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
// DISABLED: See http://crbug.com/18786
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
// DISABLED: See http://crbug.com/18786
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<commit_msg>Disable DevToolsSanityTest.TestShowScriptsTab, which has been flaky for quite a while.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#if defined(OS_WIN)
#define MAYBE_TestShowScriptsTab DISABLED_TestShowScriptsTab
#define MAYBE_TestSetBreakpoint TestSetBreakpoint
#elif defined(OS_LINUX)
// http://crbug.com/19748
#define MAYBE_TestShowScriptsTab DISABLED_TestShowScriptsTab
#define MAYBE_TestSetBreakpoint DISABLED_TestSetBreakpoint
#endif
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kDebuggerTestPage);
}
// Tests profiler panel.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
// DISABLED: See http://crbug.com/18786
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
// DISABLED: See http://crbug.com/18786
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
RunTest("testEvalCallFrame", kEvalTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kPauseWhenScriptIsRunning[] =
L"files/devtools/pause_when_script_is_running.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<commit_msg>Disable 2 tests in DevToolsSanityTest<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kPauseWhenScriptIsRunning[] =
L"files/devtools/pause_when_script_is_running.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
// TODO(skerner): This test is flaky in chromeos. Figure out why and fix.
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
StartHTTPServer();
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
<commit_msg>Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
// TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6. Figure
// out why and fix.
#if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
StartHTTPServer();
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/load_timing_observer.h"
#include "base/compiler_specific.h"
#include "base/format_macros.h"
#include "base/string_util.h"
#include "base/time.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_netlog_params.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
using net::NetLog;
using base::TimeDelta;
base::TimeTicks current_time;
void AddStartEntry(LoadTimingObserver& observer,
const NetLog::Source& source,
NetLog::EventType type,
NetLog::EventParameters* params) {
observer.OnAddEntry(type, current_time, source, NetLog::PHASE_BEGIN, params);
}
void AddEndEntry(LoadTimingObserver& observer,
const NetLog::Source& source,
NetLog::EventType type,
NetLog::EventParameters* params) {
observer.OnAddEntry(type, current_time, source, NetLog::PHASE_END, params);
}
void AddStartURLRequestEntries(LoadTimingObserver& observer,
uint32 id,
bool request_timing) {
scoped_refptr<URLRequestStartEventParameters> params(
new URLRequestStartEventParameters(
GURL(StringPrintf("http://req%d", id)),
"GET",
request_timing ? net::LOAD_ENABLE_LOAD_TIMING : 0,
net::LOW));
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, id);
AddStartEntry(observer, source, NetLog::TYPE_REQUEST_ALIVE, NULL);
AddStartEntry(observer,
source,
NetLog::TYPE_URL_REQUEST_START_JOB,
params.get());
}
void AddEndURLRequestEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, id);
AddEndEntry(observer, source, NetLog::TYPE_REQUEST_ALIVE, NULL);
AddEndEntry(observer,
source,
NetLog::TYPE_URL_REQUEST_START_JOB,
NULL);
}
void AddStartConnectJobEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_CONNECT_JOB, id);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
}
void AddEndConnectJobEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_CONNECT_JOB, id);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
}
void AddStartSocketEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_SOCKET, id);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_ALIVE, NULL);
}
void AddEndSocketEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_SOCKET, id);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_ALIVE, NULL);
}
} // namespace
// Test that URLRequest with no load timing flag is not processed.
TEST(LoadTimingObserverTest, NoLoadTimingEnabled) {
LoadTimingObserver observer;
AddStartURLRequestEntries(observer, 0, false);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_TRUE(record == NULL);
}
// Test that URLRequestRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, URLRequestRecord) {
LoadTimingObserver observer;
// Create record.
AddStartURLRequestEntries(observer, 0, true);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_FALSE(record == NULL);
// Collect record.
AddEndURLRequestEntries(observer, 0);
record = observer.GetURLRequestRecord(0);
ASSERT_TRUE(record == NULL);
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartURLRequestEntries(observer, i, true);
record = observer.GetURLRequestRecord(1);
ASSERT_TRUE(record == NULL);
}
// Test that ConnectJobRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, ConnectJobRecord) {
LoadTimingObserver observer;
// Create record.
AddStartConnectJobEntries(observer, 0);
ASSERT_FALSE(observer.connect_job_to_record_.find(0) ==
observer.connect_job_to_record_.end());
// Collect record.
AddEndConnectJobEntries(observer, 0);
ASSERT_TRUE(observer.connect_job_to_record_.find(0) ==
observer.connect_job_to_record_.end());
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartConnectJobEntries(observer, i);
ASSERT_TRUE(observer.connect_job_to_record_.find(1) ==
observer.connect_job_to_record_.end());
}
// Test that SocketRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, SocketRecord) {
LoadTimingObserver observer;
// Create record.
AddStartSocketEntries(observer, 0);
ASSERT_FALSE(observer.socket_to_record_.find(0) ==
observer.socket_to_record_.end());
// Collect record.
AddEndSocketEntries(observer, 0);
ASSERT_TRUE(observer.socket_to_record_.find(0) ==
observer.socket_to_record_.end());
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartSocketEntries(observer, i);
ASSERT_TRUE(observer.socket_to_record_.find(1) ==
observer.socket_to_record_.end());
}
// Test that basic time is set to the request.
TEST(LoadTimingObserverTest, BaseTicks) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000000, record->base_ticks.ToInternalValue());
}
// Test proxy time detection.
TEST(LoadTimingObserverTest, ProxyTime) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
current_time += TimeDelta::FromSeconds(2);
AddStartEntry(observer, source, NetLog::TYPE_PROXY_SERVICE, NULL);
current_time += TimeDelta::FromSeconds(3);
AddEndEntry(observer, source, NetLog::TYPE_PROXY_SERVICE, NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.proxy_start);
ASSERT_EQ(5000, record->timing.proxy_end);
}
// Test connect time detection.
TEST(LoadTimingObserverTest, ConnectTime) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
current_time += TimeDelta::FromSeconds(2);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_POOL, NULL);
current_time += TimeDelta::FromSeconds(3);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_POOL, NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.connect_start);
ASSERT_EQ(5000, record->timing.connect_end);
}
// Test dns time detection.
TEST(LoadTimingObserverTest, DnsTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(1);
// Add resolver entry.
AddStartConnectJobEntries(observer, 1);
NetLog::Source connect_source(NetLog::SOURCE_CONNECT_JOB, 1);
AddStartEntry(observer,
connect_source,
NetLog::TYPE_HOST_RESOLVER_IMPL,
NULL);
current_time += TimeDelta::FromSeconds(2);
AddEndEntry(observer, connect_source, NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
// Bind to connect job.
AddStartEntry(observer,
source,
NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
new net::NetLogSourceParameter("connect_job", connect_source));
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000, record->timing.dns_start);
ASSERT_EQ(3000, record->timing.dns_end);
}
// Test send time detection.
TEST(LoadTimingObserverTest, SendTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(2);
// Add send request entry.
AddStartEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST,
NULL);
current_time += TimeDelta::FromSeconds(5);
AddEndEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST,
NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.send_start);
ASSERT_EQ(7000, record->timing.send_end);
}
// Test receive time detection.
TEST(LoadTimingObserverTest, ReceiveTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(2);
// Add send request entry.
AddStartEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS,
NULL);
current_time += TimeDelta::FromSeconds(5);
AddEndEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS,
NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.receive_headers_start);
ASSERT_EQ(7000, record->timing.receive_headers_end);
}
// Test ssl time detection.
TEST(LoadTimingObserverTest, SslTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(1);
// Add resolver entry.
AddStartSocketEntries(observer, 1);
NetLog::Source socket_source(NetLog::SOURCE_SOCKET, 1);
AddStartEntry(observer, socket_source, NetLog::TYPE_SSL_CONNECT, NULL);
current_time += TimeDelta::FromSeconds(2);
AddEndEntry(observer, socket_source, NetLog::TYPE_SSL_CONNECT, NULL);
// Bind to connect job.
AddStartEntry(observer,
source,
NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
new net::NetLogSourceParameter("socket", socket_source));
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000, record->timing.ssl_start);
ASSERT_EQ(3000, record->timing.ssl_end);
}
<commit_msg>DevTools: more leak fixes in LoadTimingObserverTest. BUG=49828<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/load_timing_observer.h"
#include "base/compiler_specific.h"
#include "base/format_macros.h"
#include "base/string_util.h"
#include "base/time.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_netlog_params.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
using net::NetLog;
using base::TimeDelta;
base::TimeTicks current_time;
void AddStartEntry(LoadTimingObserver& observer,
const NetLog::Source& source,
NetLog::EventType type,
NetLog::EventParameters* params) {
observer.OnAddEntry(type, current_time, source, NetLog::PHASE_BEGIN, params);
}
void AddEndEntry(LoadTimingObserver& observer,
const NetLog::Source& source,
NetLog::EventType type,
NetLog::EventParameters* params) {
observer.OnAddEntry(type, current_time, source, NetLog::PHASE_END, params);
}
void AddStartURLRequestEntries(LoadTimingObserver& observer,
uint32 id,
bool request_timing) {
scoped_refptr<URLRequestStartEventParameters> params(
new URLRequestStartEventParameters(
GURL(StringPrintf("http://req%d", id)),
"GET",
request_timing ? net::LOAD_ENABLE_LOAD_TIMING : 0,
net::LOW));
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, id);
AddStartEntry(observer, source, NetLog::TYPE_REQUEST_ALIVE, NULL);
AddStartEntry(observer,
source,
NetLog::TYPE_URL_REQUEST_START_JOB,
params.get());
}
void AddEndURLRequestEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, id);
AddEndEntry(observer, source, NetLog::TYPE_REQUEST_ALIVE, NULL);
AddEndEntry(observer,
source,
NetLog::TYPE_URL_REQUEST_START_JOB,
NULL);
}
void AddStartConnectJobEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_CONNECT_JOB, id);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
}
void AddEndConnectJobEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_CONNECT_JOB, id);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_POOL_CONNECT_JOB, NULL);
}
void AddStartSocketEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_SOCKET, id);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_ALIVE, NULL);
}
void AddEndSocketEntries(LoadTimingObserver& observer, uint32 id) {
NetLog::Source source(NetLog::SOURCE_SOCKET, id);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_ALIVE, NULL);
}
} // namespace
// Test that URLRequest with no load timing flag is not processed.
TEST(LoadTimingObserverTest, NoLoadTimingEnabled) {
LoadTimingObserver observer;
AddStartURLRequestEntries(observer, 0, false);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_TRUE(record == NULL);
}
// Test that URLRequestRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, URLRequestRecord) {
LoadTimingObserver observer;
// Create record.
AddStartURLRequestEntries(observer, 0, true);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_FALSE(record == NULL);
// Collect record.
AddEndURLRequestEntries(observer, 0);
record = observer.GetURLRequestRecord(0);
ASSERT_TRUE(record == NULL);
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartURLRequestEntries(observer, i, true);
record = observer.GetURLRequestRecord(1);
ASSERT_TRUE(record == NULL);
}
// Test that ConnectJobRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, ConnectJobRecord) {
LoadTimingObserver observer;
// Create record.
AddStartConnectJobEntries(observer, 0);
ASSERT_FALSE(observer.connect_job_to_record_.find(0) ==
observer.connect_job_to_record_.end());
// Collect record.
AddEndConnectJobEntries(observer, 0);
ASSERT_TRUE(observer.connect_job_to_record_.find(0) ==
observer.connect_job_to_record_.end());
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartConnectJobEntries(observer, i);
ASSERT_TRUE(observer.connect_job_to_record_.find(1) ==
observer.connect_job_to_record_.end());
}
// Test that SocketRecord is created, deleted and is not growing unbound.
TEST(LoadTimingObserverTest, SocketRecord) {
LoadTimingObserver observer;
// Create record.
AddStartSocketEntries(observer, 0);
ASSERT_FALSE(observer.socket_to_record_.find(0) ==
observer.socket_to_record_.end());
// Collect record.
AddEndSocketEntries(observer, 0);
ASSERT_TRUE(observer.socket_to_record_.find(0) ==
observer.socket_to_record_.end());
// Check unbound growth.
for (size_t i = 1; i < 1100; ++i)
AddStartSocketEntries(observer, i);
ASSERT_TRUE(observer.socket_to_record_.find(1) ==
observer.socket_to_record_.end());
}
// Test that basic time is set to the request.
TEST(LoadTimingObserverTest, BaseTicks) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000000, record->base_ticks.ToInternalValue());
}
// Test proxy time detection.
TEST(LoadTimingObserverTest, ProxyTime) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
current_time += TimeDelta::FromSeconds(2);
AddStartEntry(observer, source, NetLog::TYPE_PROXY_SERVICE, NULL);
current_time += TimeDelta::FromSeconds(3);
AddEndEntry(observer, source, NetLog::TYPE_PROXY_SERVICE, NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.proxy_start);
ASSERT_EQ(5000, record->timing.proxy_end);
}
// Test connect time detection.
TEST(LoadTimingObserverTest, ConnectTime) {
LoadTimingObserver observer;
current_time += TimeDelta::FromSeconds(1);
AddStartURLRequestEntries(observer, 0, true);
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
current_time += TimeDelta::FromSeconds(2);
AddStartEntry(observer, source, NetLog::TYPE_SOCKET_POOL, NULL);
current_time += TimeDelta::FromSeconds(3);
AddEndEntry(observer, source, NetLog::TYPE_SOCKET_POOL, NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.connect_start);
ASSERT_EQ(5000, record->timing.connect_end);
}
// Test dns time detection.
TEST(LoadTimingObserverTest, DnsTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(1);
// Add resolver entry.
AddStartConnectJobEntries(observer, 1);
NetLog::Source connect_source(NetLog::SOURCE_CONNECT_JOB, 1);
AddStartEntry(observer,
connect_source,
NetLog::TYPE_HOST_RESOLVER_IMPL,
NULL);
current_time += TimeDelta::FromSeconds(2);
AddEndEntry(observer, connect_source, NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
// Bind to connect job.
scoped_refptr<net::NetLogSourceParameter> params(
new net::NetLogSourceParameter("connect_job", connect_source));
AddStartEntry(observer,
source,
NetLog::TYPE_SOCKET_POOL_BOUND_TO_CONNECT_JOB,
params.get());
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000, record->timing.dns_start);
ASSERT_EQ(3000, record->timing.dns_end);
}
// Test send time detection.
TEST(LoadTimingObserverTest, SendTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(2);
// Add send request entry.
AddStartEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST,
NULL);
current_time += TimeDelta::FromSeconds(5);
AddEndEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST,
NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.send_start);
ASSERT_EQ(7000, record->timing.send_end);
}
// Test receive time detection.
TEST(LoadTimingObserverTest, ReceiveTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(2);
// Add send request entry.
AddStartEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS,
NULL);
current_time += TimeDelta::FromSeconds(5);
AddEndEntry(observer,
source,
NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS,
NULL);
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(2000, record->timing.receive_headers_start);
ASSERT_EQ(7000, record->timing.receive_headers_end);
}
// Test ssl time detection.
TEST(LoadTimingObserverTest, SslTime) {
LoadTimingObserver observer;
// Start request.
NetLog::Source source(NetLog::SOURCE_URL_REQUEST, 0);
AddStartURLRequestEntries(observer, 0, true);
current_time += TimeDelta::FromSeconds(1);
// Add resolver entry.
AddStartSocketEntries(observer, 1);
NetLog::Source socket_source(NetLog::SOURCE_SOCKET, 1);
AddStartEntry(observer, socket_source, NetLog::TYPE_SSL_CONNECT, NULL);
current_time += TimeDelta::FromSeconds(2);
AddEndEntry(observer, socket_source, NetLog::TYPE_SSL_CONNECT, NULL);
// Bind to connect job.
scoped_refptr<net::NetLogSourceParameter> params(
new net::NetLogSourceParameter("socket", socket_source));
AddStartEntry(observer,
source,
NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET,
params.get());
LoadTimingObserver::URLRequestRecord* record =
observer.GetURLRequestRecord(0);
ASSERT_EQ(1000, record->timing.ssl_start);
ASSERT_EQ(3000, record->timing.ssl_end);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/internal/cxx/function.hpp"
#include "test.hpp"
#include <iostream>
using namespace ::testing;
using namespace iox::cxx;
namespace
{
using std::cout;
using std::endl;
using signature = int32_t(int32_t);
template <typename T>
using fixed_size_function = iox::cxx::function<T, 128>;
using test_function = fixed_size_function<signature>;
// helper template to count construction and copy statistics,
// for our purpose (test_function) we do not need to distinguish
// between copy (move) ctor and copy(move) assignment
template <typename T>
class Counter
{
public:
static uint64_t numCreated;
static uint64_t numCopied;
static uint64_t numMoved;
static uint64_t numDestroyed;
Counter()
{
++numCreated;
}
Counter(const Counter&)
{
++numCreated;
++numCopied;
}
Counter(Counter&&)
{
++numMoved;
}
~Counter()
{
++numDestroyed;
}
Counter& operator=(const Counter&)
{
++numCopied;
}
Counter& operator=(Counter&&)
{
++numMoved;
}
static void resetCounts()
{
numCreated = 0U;
numCopied = 0U;
numMoved = 0U;
numDestroyed = 0U;
}
};
template <typename T>
uint64_t Counter<T>::numCreated = 0U;
template <typename T>
uint64_t Counter<T>::numCopied = 0U;
template <typename T>
uint64_t Counter<T>::numMoved = 0U;
template <typename T>
uint64_t Counter<T>::numDestroyed = 0U;
class Functor : public Counter<Functor>
{
public:
Functor(int32_t state)
: Counter<Functor>()
, m_state(state)
{
}
int32_t operator()(int32_t n)
{
m_state += n;
return m_state;
}
int32_t m_state{0};
};
int32_t freeFunction(int32_t n)
{
return n + 1;
};
class function_test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
static int32_t staticFunction(int32_t n)
{
return n + 1;
}
};
TEST_F(function_test, DefaultConstructionCreatesNoCallable)
{
test_function sut;
EXPECT_FALSE(sut.operator bool());
}
TEST_F(function_test, ConstructionFromFunctorIsCallable)
{
Functor f(73);
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCreated, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, ConstructionFromLambdaIsCallable)
{
int32_t capture = 37;
auto lambda = [state = capture](int32_t n) { return state + n; };
test_function sut(lambda);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), lambda(1));
}
TEST_F(function_test, ConstructionFromFreeFunctionIsCallable)
{
test_function sut(freeFunction);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
}
TEST_F(function_test, ConstructionFromStaticFunctionIsCallable)
{
// is essentially also a free function but we test the case to be sure
test_function sut(staticFunction);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), staticFunction(1));
}
TEST_F(function_test, FunctionStateIsIndependentOfSource)
{
constexpr uint32_t INITIAL_STATE = 73U;
static_storage<1024U> storage;
auto p = storage.allocate<Functor>();
p = new (p) Functor(INITIAL_STATE);
auto& functor = *p;
// test whether the function really owns the functor
// (no dependency or side effects)
test_function sut(functor);
ASSERT_TRUE(sut.operator bool());
// both increment their state independently
EXPECT_EQ(sut(1U), functor(1U));
// clear original (set to 0)
p->~Functor();
storage.clear();
EXPECT_EQ(sut(1U), INITIAL_STATE + 2U);
}
// The implementation uses type erasure and we need to verify that the corresponding
// constructors and operators of the underlying object (functor) are called.
TEST_F(function_test, DestructorCallsDestructorOfStoredFunctor)
{
Functor f(73);
Functor::resetCounts();
{
test_function sut(f);
}
EXPECT_EQ(Functor::numDestroyed, 1U);
}
TEST_F(function_test, CopyCtorCopiesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCopied, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveCtorMovesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
Functor::resetCounts();
test_function sut(std::move(f));
EXPECT_EQ(Functor::numMoved, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), functor(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignmentCopiesStoredFunctor)
{
test_function f(Functor(73));
test_function sut(Functor(42));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveAssignmentMovesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
test_function sut(Functor(42));
Functor::resetCounts();
sut = std::move(f);
// destroy previous Functor in sut and Functor in f after move
// (f is not callable but can be reassigned)
EXPECT_EQ(Functor::numDestroyed, 2U);
EXPECT_EQ(Functor::numMoved, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), functor(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyCtorCopiesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(f);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveCtorMovesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(std::move(f));
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignmentCopiesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(Functor(73));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveAssignmentMovesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(Functor(73));
Functor::resetCounts();
sut = std::move(f);
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopiedNonCallableFunctionIsNotCallable)
{
test_function f;
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
}
TEST_F(function_test, MovedNonCallableFunctionIsNotCallable)
{
test_function f;
Functor::resetCounts();
test_function sut(std::move(f));
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignedNonCallableFunctionIsNotCallable)
{
test_function f;
test_function sut(Functor(73));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, MoveAssignedNonCallableFunctionIsNotCallable)
{
test_function f;
test_function sut(Functor(73));
Functor::resetCounts();
sut = std::move(f);
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, MemberSwapWorks)
{
Functor f1(73);
Functor f2(37);
test_function sut1(f1);
test_function sut2(f2);
sut1.swap(sut2);
ASSERT_TRUE(sut1.operator bool());
EXPECT_EQ(sut1(1), f2(1));
ASSERT_TRUE(sut2.operator bool());
EXPECT_EQ(sut2(1), f1(1));
}
TEST_F(function_test, StaticSwapWorks)
{
Functor f1(73);
Functor f2(37);
test_function sut1(f1);
test_function sut2(f2);
test_function::swap(sut1, sut2);
ASSERT_TRUE(sut1.operator bool());
EXPECT_EQ(sut1(1), f2(1));
ASSERT_TRUE(sut2.operator bool());
EXPECT_EQ(sut2(1), f1(1));
}
} // namespace<commit_msg>iox-#391 test construction from member function<commit_after>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_utils/internal/cxx/function.hpp"
#include "test.hpp"
#include <iostream>
using namespace ::testing;
using namespace iox::cxx;
namespace
{
using std::cout;
using std::endl;
using signature = int32_t(int32_t);
template <typename T>
using fixed_size_function = iox::cxx::function<T, 128>;
using test_function = fixed_size_function<signature>;
// helper template to count construction and copy statistics,
// for our purpose (test_function) we do not need to distinguish
// between copy (move) ctor and copy(move) assignment
template <typename T>
class Counter
{
public:
static uint64_t numCreated;
static uint64_t numCopied;
static uint64_t numMoved;
static uint64_t numDestroyed;
Counter()
{
++numCreated;
}
Counter(const Counter&)
{
++numCreated;
++numCopied;
}
Counter(Counter&&)
{
++numMoved;
}
~Counter()
{
++numDestroyed;
}
Counter& operator=(const Counter&)
{
++numCopied;
}
Counter& operator=(Counter&&)
{
++numMoved;
}
static void resetCounts()
{
numCreated = 0U;
numCopied = 0U;
numMoved = 0U;
numDestroyed = 0U;
}
};
template <typename T>
uint64_t Counter<T>::numCreated = 0U;
template <typename T>
uint64_t Counter<T>::numCopied = 0U;
template <typename T>
uint64_t Counter<T>::numMoved = 0U;
template <typename T>
uint64_t Counter<T>::numDestroyed = 0U;
class Functor : public Counter<Functor>
{
public:
Functor(int32_t state)
: Counter<Functor>()
, m_state(state)
{
}
int32_t operator()(int32_t n)
{
m_state += n;
return m_state;
}
// integer arg to satisfy signature requirement of our test_function
int32_t getState(int32_t n = 0) const
{
return m_state + n;
}
int32_t m_state{0};
};
int32_t freeFunction(int32_t n)
{
return n + 1;
};
class function_test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
static int32_t staticFunction(int32_t n)
{
return n + 1;
}
};
TEST_F(function_test, DefaultConstructionCreatesNoCallable)
{
test_function sut;
EXPECT_FALSE(sut.operator bool());
}
TEST_F(function_test, ConstructionFromFunctorIsCallable)
{
Functor f(73);
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCreated, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, ConstructionFromLambdaIsCallable)
{
int32_t capture = 37;
auto lambda = [state = capture](int32_t n) { return state + n; };
test_function sut(lambda);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), lambda(1));
}
TEST_F(function_test, ConstructionFromFreeFunctionIsCallable)
{
test_function sut(freeFunction);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
}
TEST_F(function_test, ConstructionFromStaticFunctionIsCallable)
{
// is essentially also a free function but we test the case to be sure
test_function sut(staticFunction);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), staticFunction(1));
}
TEST_F(function_test, ConstructionFromMemberFunctionIsCallable)
{
Functor f(37);
test_function sut(f, &Functor::operator());
ASSERT_TRUE(sut.operator bool());
auto result = f(1);
EXPECT_EQ(sut(1), result + 1);
}
TEST_F(function_test, ConstructionFromConstMemberFunctionIsCallable)
{
Functor f(37);
test_function sut(f, &Functor::getState);
ASSERT_TRUE(sut.operator bool());
auto state = f.getState(1);
EXPECT_EQ(sut(1), state);
EXPECT_EQ(f.getState(1), state); // state is unchanged by the previous call
}
TEST_F(function_test, FunctionStateIsIndependentOfSource)
{
constexpr uint32_t INITIAL_STATE = 73U;
static_storage<1024U> storage;
auto p = storage.allocate<Functor>();
p = new (p) Functor(INITIAL_STATE);
auto& functor = *p;
// test whether the function really owns the functor
// (no dependency or side effects)
test_function sut(functor);
ASSERT_TRUE(sut.operator bool());
// both increment their state independently
EXPECT_EQ(sut(1U), functor(1U));
// clear original (set to 0)
p->~Functor();
storage.clear();
EXPECT_EQ(sut(1U), INITIAL_STATE + 2U);
}
// The implementation uses type erasure and we need to verify that the corresponding
// constructors and operators of the underlying object (functor) are called.
TEST_F(function_test, DestructorCallsDestructorOfStoredFunctor)
{
Functor f(73);
Functor::resetCounts();
{
test_function sut(f);
}
EXPECT_EQ(Functor::numDestroyed, 1U);
}
TEST_F(function_test, CopyCtorCopiesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCopied, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveCtorMovesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
Functor::resetCounts();
test_function sut(std::move(f));
EXPECT_EQ(Functor::numMoved, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), functor(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignmentCopiesStoredFunctor)
{
test_function f(Functor(73));
test_function sut(Functor(42));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveAssignmentMovesStoredFunctor)
{
Functor functor(73);
test_function f(functor);
test_function sut(Functor(42));
Functor::resetCounts();
sut = std::move(f);
// destroy previous Functor in sut and Functor in f after move
// (f is not callable but can be reassigned)
EXPECT_EQ(Functor::numDestroyed, 2U);
EXPECT_EQ(Functor::numMoved, 1U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), functor(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyCtorCopiesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(f);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveCtorMovesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(std::move(f));
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignmentCopiesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(Functor(73));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), f(1));
}
TEST_F(function_test, MoveAssignmentMovesStoredFreeFunction)
{
test_function f(freeFunction);
test_function sut(Functor(73));
Functor::resetCounts();
sut = std::move(f);
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
ASSERT_TRUE(sut.operator bool());
EXPECT_EQ(sut(1), freeFunction(1));
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopiedNonCallableFunctionIsNotCallable)
{
test_function f;
Functor::resetCounts();
test_function sut(f);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
}
TEST_F(function_test, MovedNonCallableFunctionIsNotCallable)
{
test_function f;
Functor::resetCounts();
test_function sut(std::move(f));
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, CopyAssignedNonCallableFunctionIsNotCallable)
{
test_function f;
test_function sut(Functor(73));
Functor::resetCounts();
sut = f;
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, MoveAssignedNonCallableFunctionIsNotCallable)
{
test_function f;
test_function sut(Functor(73));
Functor::resetCounts();
sut = std::move(f);
EXPECT_EQ(Functor::numDestroyed, 1U);
EXPECT_EQ(Functor::numCopied, 0U);
EXPECT_EQ(Functor::numMoved, 0U);
EXPECT_FALSE(sut.operator bool());
EXPECT_FALSE(f.operator bool());
}
TEST_F(function_test, MemberSwapWorks)
{
Functor f1(73);
Functor f2(37);
test_function sut1(f1);
test_function sut2(f2);
sut1.swap(sut2);
ASSERT_TRUE(sut1.operator bool());
EXPECT_EQ(sut1(1), f2(1));
ASSERT_TRUE(sut2.operator bool());
EXPECT_EQ(sut2(1), f1(1));
}
TEST_F(function_test, StaticSwapWorks)
{
Functor f1(73);
Functor f2(37);
test_function sut1(f1);
test_function sut2(f2);
test_function::swap(sut1, sut2);
ASSERT_TRUE(sut1.operator bool());
EXPECT_EQ(sut1(1), f2(1));
ASSERT_TRUE(sut2.operator bool());
EXPECT_EQ(sut2(1), f1(1));
}
} // namespace<|endoftext|> |
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"
extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);
static const bool prezero = true;
struct zallocator {
run* run;
kmem kmem;
wframe frame;
void init(int);
char* alloc(const char*);
void free(char*);
void tryrefill();
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame, zallocator* zer)
: frame_(frame), zer_(zer)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
struct run* r = (struct run*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
zer_->kmem.free(r);
}
frame_->dec();
delete this;
}
wframe* frame_;
zallocator* zer_;
NEW_DELETE_OPS(zwork);
};
//
// zallocator
//
void
zallocator::tryrefill(void)
{
if (prezero && kmem.nfree < 16 && frame.zero()) {
zwork* w = new zwork(&frame, this);
if (wq_push(w) < 0)
delete w;
}
}
void
zallocator::init(int c)
{
frame.clear();
kmem.name[0] = (char) c + '0';
safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
kmem.size = PGSIZE;
}
char*
zallocator::alloc(const char* name)
{
char* p;
p = (char*) kmem.alloc(name);
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
} else {
// Zero the run header used by kmem
memset(p, 0, sizeof(struct run));
}
tryrefill();
return p;
}
void
zallocator::free(char* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(p[i] == 0);
kmem.free((struct run*)p);
}
char*
zalloc(const char* name)
{
return z_->alloc(name);
}
void
zfree(char* p)
{
z_->free(p);
}
void
initz(void)
{
for (int c = 0; c < NCPU; c++)
z_[c].init(c);
}
<commit_msg>Remove unused field from zallocator<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"
extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);
static const bool prezero = true;
struct zallocator {
kmem kmem;
wframe frame;
void init(int);
char* alloc(const char*);
void free(char*);
void tryrefill();
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame, zallocator* zer)
: frame_(frame), zer_(zer)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
struct run* r = (struct run*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
zer_->kmem.free(r);
}
frame_->dec();
delete this;
}
wframe* frame_;
zallocator* zer_;
NEW_DELETE_OPS(zwork);
};
//
// zallocator
//
void
zallocator::tryrefill(void)
{
if (prezero && kmem.nfree < 16 && frame.zero()) {
zwork* w = new zwork(&frame, this);
if (wq_push(w) < 0)
delete w;
}
}
void
zallocator::init(int c)
{
frame.clear();
kmem.name[0] = (char) c + '0';
safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
kmem.size = PGSIZE;
}
char*
zallocator::alloc(const char* name)
{
char* p;
p = (char*) kmem.alloc(name);
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
} else {
// Zero the run header used by kmem
memset(p, 0, sizeof(struct run));
}
tryrefill();
return p;
}
void
zallocator::free(char* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(p[i] == 0);
kmem.free((struct run*)p);
}
char*
zalloc(const char* name)
{
return z_->alloc(name);
}
void
zfree(char* p)
{
z_->free(p);
}
void
initz(void)
{
for (int c = 0; c < NCPU; c++)
z_[c].init(c);
}
<|endoftext|> |
<commit_before>#include "mpi.h"
#include "hdf5.h"
#include <Python.h>
#include <string>
#include <iostream>
#include <cstdio>
#include <boost/filesystem.hpp>
hid_t hpat_h5_open(char* file_name, char* mode, int64_t is_parallel);
int64_t hpat_h5_size(hid_t file_id, char* dset_name, int dim);
int hpat_h5_read(hid_t file_id, char* dset_name, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum);
int hpat_h5_close(hid_t file_id);
hid_t hpat_h5_create_dset(hid_t file_id, char* dset_name, int ndims,
int64_t* counts, int typ_enum);
hid_t hpat_h5_create_group(hid_t file_id, char* group_name);
int hpat_h5_write(hid_t file_id, hid_t dataset_id, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum);
int hpat_h5_get_type_enum(std::string *s);
hid_t get_h5_typ(int typ_enum);
int64_t h5g_get_num_objs(hid_t file_id);
void* h5g_get_objname_by_idx(hid_t file_id, int64_t ind);
uint64_t get_file_size(std::string* file_name);
void file_read(std::string* file_name, void* buff, int64_t size);
PyMODINIT_FUNC PyInit_hio(void) {
PyObject *m;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "hio", "No docs", -1, NULL, };
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
PyObject_SetAttrString(m, "hpat_h5_open",
PyLong_FromVoidPtr((void*)(&hpat_h5_open)));
PyObject_SetAttrString(m, "hpat_h5_size",
PyLong_FromVoidPtr((void*)(&hpat_h5_size)));
PyObject_SetAttrString(m, "hpat_h5_read",
PyLong_FromVoidPtr((void*)(&hpat_h5_read)));
PyObject_SetAttrString(m, "hpat_h5_close",
PyLong_FromVoidPtr((void*)(&hpat_h5_close)));
PyObject_SetAttrString(m, "hpat_h5_create_dset",
PyLong_FromVoidPtr((void*)(&hpat_h5_create_dset)));
PyObject_SetAttrString(m, "hpat_h5_create_group",
PyLong_FromVoidPtr((void*)(&hpat_h5_create_group)));
PyObject_SetAttrString(m, "hpat_h5_write",
PyLong_FromVoidPtr((void*)(&hpat_h5_write)));
PyObject_SetAttrString(m, "hpat_h5_get_type_enum",
PyLong_FromVoidPtr((void*)(&hpat_h5_get_type_enum)));
PyObject_SetAttrString(m, "h5g_get_num_objs",
PyLong_FromVoidPtr((void*)(&h5g_get_num_objs)));
PyObject_SetAttrString(m, "h5g_get_objname_by_idx",
PyLong_FromVoidPtr((void*)(&h5g_get_objname_by_idx)));
// numpy read
PyObject_SetAttrString(m, "get_file_size",
PyLong_FromVoidPtr((void*)(&get_file_size)));
PyObject_SetAttrString(m, "file_read",
PyLong_FromVoidPtr((void*)(&file_read)));
return m;
}
hid_t hpat_h5_open(char* file_name, char* mode, int64_t is_parallel)
{
// printf("h5_open file_name: %s mode:%s\n", file_name, mode);
hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS);
assert(plist_id != -1);
herr_t ret;
hid_t file_id = -1;
unsigned flag = H5F_ACC_RDWR;
if(is_parallel)
ret = H5Pset_fapl_mpio(plist_id, MPI_COMM_WORLD, MPI_INFO_NULL);
assert(ret != -1);
// TODO: handle 'a' mode
if(strcmp(mode, "r")==0)
{
flag = H5F_ACC_RDONLY;
file_id = H5Fopen((const char*)file_name, flag, plist_id);
}
else if(strcmp(mode, "r+")==0)
{
flag = H5F_ACC_RDWR;
file_id = H5Fopen((const char*)file_name, flag, plist_id);
}
else if(strcmp(mode, "w")==0)
{
flag = H5F_ACC_TRUNC;
file_id = H5Fcreate((const char*)file_name, flag, H5P_DEFAULT, plist_id);
}
else if(strcmp(mode, "w-")==0 || strcmp(mode, "x")==0)
{
flag = H5F_ACC_EXCL;
file_id = H5Fcreate((const char*)file_name, flag, H5P_DEFAULT, plist_id);
// printf("w- fid:%d\n", file_id);
}
assert(file_id != -1);
ret = H5Pclose(plist_id);
assert(ret != -1);
return file_id;
}
int64_t hpat_h5_size(hid_t file_id, char* dset_name, int dim)
{
hid_t dataset_id;
dataset_id = H5Dopen2(file_id, dset_name, H5P_DEFAULT);
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t data_ndim = H5Sget_simple_extent_ndims(space_id);
hsize_t *space_dims = new hsize_t[data_ndim];
H5Sget_simple_extent_dims(space_id, space_dims, NULL);
H5Dclose(dataset_id);
hsize_t ret = space_dims[dim];
delete[] space_dims;
return ret;
}
int hpat_h5_read(hid_t file_id, char* dset_name, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum)
{
//printf("dset_name:%s ndims:%d size:%d typ:%d\n", dset_name, ndims, counts[0], typ_enum);
// fflush(stdout);
// printf("start %lld end %lld\n", start_ind, end_ind);
hid_t dataset_id;
herr_t ret;
dataset_id = H5Dopen2(file_id, dset_name, H5P_DEFAULT);
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t* HDF5_start = (hsize_t*)starts;
hsize_t* HDF5_count = (hsize_t*)counts;
hid_t xfer_plist_id = H5P_DEFAULT;
if(is_parallel)
{
xfer_plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(xfer_plist_id, H5FD_MPIO_COLLECTIVE);
}
ret = H5Sselect_hyperslab(space_id, H5S_SELECT_SET, HDF5_start, NULL, HDF5_count, NULL);
assert(ret != -1);
hid_t mem_dataspace = H5Screate_simple((hsize_t)ndims, HDF5_count, NULL);
assert (mem_dataspace != -1);
hid_t h5_typ = get_h5_typ(typ_enum);
ret = H5Dread(dataset_id, h5_typ, mem_dataspace, space_id, xfer_plist_id, out);
assert(ret != -1);
// printf("out: %lf %lf ...\n", ((double*)out)[0], ((double*)out)[1]);
H5Dclose(dataset_id);
return ret;
}
// _h5_typ_table = {
// int8:0,
// uint8:1,
// int32:2,
// int64:3,
// float32:4,
// float64:5
// }
hid_t get_h5_typ(int typ_enum)
{
// printf("h5 type enum:%d\n", typ_enum);
hid_t types_list[] = {H5T_NATIVE_CHAR, H5T_NATIVE_UCHAR,
H5T_NATIVE_INT, H5T_NATIVE_LLONG, H5T_NATIVE_FLOAT, H5T_NATIVE_DOUBLE};
return types_list[typ_enum];
}
// _h5_str_typ_table = {
// 'i1':0,
// 'u1':1,
// 'i4':2,
// 'i8':3,
// 'f4':4,
// 'f8':5
// }
int hpat_h5_get_type_enum(std::string *s)
{
int typ = -1;
if ((*s)=="i1")
typ = 0;
if ((*s)=="u1")
typ = 1;
if ((*s)=="i4")
typ = 2;
if ((*s)=="i8")
typ = 3;
if ((*s)=="f4")
typ = 4;
if ((*s)=="f8")
typ = 5;
return typ;
}
int hpat_h5_close(hid_t file_id)
{
// printf("closing: %d\n", file_id);
H5Fclose(file_id);
return 0;
}
hid_t hpat_h5_create_dset(hid_t file_id, char* dset_name, int ndims,
int64_t* counts, int typ_enum)
{
// printf("dset_name:%s ndims:%d size:%d typ:%d\n", dset_name, ndims, counts[0], typ_enum);
// fflush(stdout);
hid_t dataset_id;
hid_t filespace;
hid_t h5_typ = get_h5_typ(typ_enum);
filespace = H5Screate_simple(ndims, (const hsize_t *)counts, NULL);
dataset_id = H5Dcreate(file_id, dset_name, h5_typ, filespace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Sclose(filespace);
return dataset_id;
}
hid_t hpat_h5_create_group(hid_t file_id, char* group_name)
{
// printf("group_name:%s\n", group_name);
// fflush(stdout);
hid_t group_id;
group_id = H5Gcreate2(file_id, group_name,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
return group_id;
}
int hpat_h5_write(hid_t file_id, hid_t dataset_id, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum)
{
//printf("dset_id:%s ndims:%d size:%d typ:%d\n", dset_id, ndims, counts[0], typ_enum);
// fflush(stdout);
herr_t ret;
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t* HDF5_start = (hsize_t*)starts;
hsize_t* HDF5_count = (hsize_t*)counts;
hid_t xfer_plist_id = H5P_DEFAULT;
if(is_parallel)
{
xfer_plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(xfer_plist_id, H5FD_MPIO_COLLECTIVE);
}
ret = H5Sselect_hyperslab(space_id, H5S_SELECT_SET, HDF5_start, NULL, HDF5_count, NULL);
assert(ret != -1);
hid_t mem_dataspace = H5Screate_simple((hsize_t)ndims, HDF5_count, NULL);
assert (mem_dataspace != -1);
hid_t h5_typ = get_h5_typ(typ_enum);
ret = H5Dwrite(dataset_id, h5_typ, mem_dataspace, space_id, xfer_plist_id, out);
assert(ret != -1);
H5Dclose(dataset_id);
return ret;
}
int64_t h5g_get_num_objs(hid_t file_id)
{
H5G_info_t group_info;
herr_t err;
err = H5Gget_info(file_id, &group_info);
// printf("num links:%lld\n", group_info.nlinks);
return (int64_t)group_info.nlinks;
}
void* h5g_get_objname_by_idx(hid_t file_id, int64_t ind)
{
herr_t err;
// first call gets size:
// https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5L.html#Link-GetNameByIdx
int size = H5Lget_name_by_idx(file_id, ".", H5_INDEX_NAME, H5_ITER_NATIVE,
(hsize_t)ind, NULL, 0, H5P_DEFAULT);
char* name = (char*) malloc(size+1);
err = H5Lget_name_by_idx(file_id, ".", H5_INDEX_NAME, H5_ITER_NATIVE,
(hsize_t)ind, name, size+1, H5P_DEFAULT);
// printf("g name:%s\n", name);
std::string *outstr = new std::string(name);
// std::cout<<"out: "<<*outstr<<std::endl;
return outstr;
}
uint64_t get_file_size(std::string* file_name)
{
boost::filesystem::path f_path(*file_name);
// TODO: throw FileNotFoundError
if (!boost::filesystem::exists(f_path))
{
std::cerr << "No such file or directory: " << *file_name << '\n';
return 0;
}
return (uint64_t)boost::filesystem::file_size(f_path);
}
void file_read(std::string* file_name, void* buff, int64_t size)
{
FILE* fp = fopen(file_name->c_str(), "rb");
size_t ret_code = fread(buff, 1, (size_t)size, fp);
if (ret_code != (size_t)size)
{
std::cerr << "File read error: " << *file_name << '\n';
}
fclose(fp);
return;
}
<commit_msg>file size on rank 0 only<commit_after>#include "mpi.h"
#include "hdf5.h"
#include <Python.h>
#include <string>
#include <iostream>
#include <cstdio>
#include <boost/filesystem.hpp>
hid_t hpat_h5_open(char* file_name, char* mode, int64_t is_parallel);
int64_t hpat_h5_size(hid_t file_id, char* dset_name, int dim);
int hpat_h5_read(hid_t file_id, char* dset_name, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum);
int hpat_h5_close(hid_t file_id);
hid_t hpat_h5_create_dset(hid_t file_id, char* dset_name, int ndims,
int64_t* counts, int typ_enum);
hid_t hpat_h5_create_group(hid_t file_id, char* group_name);
int hpat_h5_write(hid_t file_id, hid_t dataset_id, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum);
int hpat_h5_get_type_enum(std::string *s);
hid_t get_h5_typ(int typ_enum);
int64_t h5g_get_num_objs(hid_t file_id);
void* h5g_get_objname_by_idx(hid_t file_id, int64_t ind);
uint64_t get_file_size(std::string* file_name);
void file_read(std::string* file_name, void* buff, int64_t size);
#define MPI_ROOT 0
PyMODINIT_FUNC PyInit_hio(void) {
PyObject *m;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "hio", "No docs", -1, NULL, };
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
PyObject_SetAttrString(m, "hpat_h5_open",
PyLong_FromVoidPtr((void*)(&hpat_h5_open)));
PyObject_SetAttrString(m, "hpat_h5_size",
PyLong_FromVoidPtr((void*)(&hpat_h5_size)));
PyObject_SetAttrString(m, "hpat_h5_read",
PyLong_FromVoidPtr((void*)(&hpat_h5_read)));
PyObject_SetAttrString(m, "hpat_h5_close",
PyLong_FromVoidPtr((void*)(&hpat_h5_close)));
PyObject_SetAttrString(m, "hpat_h5_create_dset",
PyLong_FromVoidPtr((void*)(&hpat_h5_create_dset)));
PyObject_SetAttrString(m, "hpat_h5_create_group",
PyLong_FromVoidPtr((void*)(&hpat_h5_create_group)));
PyObject_SetAttrString(m, "hpat_h5_write",
PyLong_FromVoidPtr((void*)(&hpat_h5_write)));
PyObject_SetAttrString(m, "hpat_h5_get_type_enum",
PyLong_FromVoidPtr((void*)(&hpat_h5_get_type_enum)));
PyObject_SetAttrString(m, "h5g_get_num_objs",
PyLong_FromVoidPtr((void*)(&h5g_get_num_objs)));
PyObject_SetAttrString(m, "h5g_get_objname_by_idx",
PyLong_FromVoidPtr((void*)(&h5g_get_objname_by_idx)));
// numpy read
PyObject_SetAttrString(m, "get_file_size",
PyLong_FromVoidPtr((void*)(&get_file_size)));
PyObject_SetAttrString(m, "file_read",
PyLong_FromVoidPtr((void*)(&file_read)));
return m;
}
hid_t hpat_h5_open(char* file_name, char* mode, int64_t is_parallel)
{
// printf("h5_open file_name: %s mode:%s\n", file_name, mode);
hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS);
assert(plist_id != -1);
herr_t ret;
hid_t file_id = -1;
unsigned flag = H5F_ACC_RDWR;
if(is_parallel)
ret = H5Pset_fapl_mpio(plist_id, MPI_COMM_WORLD, MPI_INFO_NULL);
assert(ret != -1);
// TODO: handle 'a' mode
if(strcmp(mode, "r")==0)
{
flag = H5F_ACC_RDONLY;
file_id = H5Fopen((const char*)file_name, flag, plist_id);
}
else if(strcmp(mode, "r+")==0)
{
flag = H5F_ACC_RDWR;
file_id = H5Fopen((const char*)file_name, flag, plist_id);
}
else if(strcmp(mode, "w")==0)
{
flag = H5F_ACC_TRUNC;
file_id = H5Fcreate((const char*)file_name, flag, H5P_DEFAULT, plist_id);
}
else if(strcmp(mode, "w-")==0 || strcmp(mode, "x")==0)
{
flag = H5F_ACC_EXCL;
file_id = H5Fcreate((const char*)file_name, flag, H5P_DEFAULT, plist_id);
// printf("w- fid:%d\n", file_id);
}
assert(file_id != -1);
ret = H5Pclose(plist_id);
assert(ret != -1);
return file_id;
}
int64_t hpat_h5_size(hid_t file_id, char* dset_name, int dim)
{
hid_t dataset_id;
dataset_id = H5Dopen2(file_id, dset_name, H5P_DEFAULT);
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t data_ndim = H5Sget_simple_extent_ndims(space_id);
hsize_t *space_dims = new hsize_t[data_ndim];
H5Sget_simple_extent_dims(space_id, space_dims, NULL);
H5Dclose(dataset_id);
hsize_t ret = space_dims[dim];
delete[] space_dims;
return ret;
}
int hpat_h5_read(hid_t file_id, char* dset_name, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum)
{
//printf("dset_name:%s ndims:%d size:%d typ:%d\n", dset_name, ndims, counts[0], typ_enum);
// fflush(stdout);
// printf("start %lld end %lld\n", start_ind, end_ind);
hid_t dataset_id;
herr_t ret;
dataset_id = H5Dopen2(file_id, dset_name, H5P_DEFAULT);
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t* HDF5_start = (hsize_t*)starts;
hsize_t* HDF5_count = (hsize_t*)counts;
hid_t xfer_plist_id = H5P_DEFAULT;
if(is_parallel)
{
xfer_plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(xfer_plist_id, H5FD_MPIO_COLLECTIVE);
}
ret = H5Sselect_hyperslab(space_id, H5S_SELECT_SET, HDF5_start, NULL, HDF5_count, NULL);
assert(ret != -1);
hid_t mem_dataspace = H5Screate_simple((hsize_t)ndims, HDF5_count, NULL);
assert (mem_dataspace != -1);
hid_t h5_typ = get_h5_typ(typ_enum);
ret = H5Dread(dataset_id, h5_typ, mem_dataspace, space_id, xfer_plist_id, out);
assert(ret != -1);
// printf("out: %lf %lf ...\n", ((double*)out)[0], ((double*)out)[1]);
H5Dclose(dataset_id);
return ret;
}
// _h5_typ_table = {
// int8:0,
// uint8:1,
// int32:2,
// int64:3,
// float32:4,
// float64:5
// }
hid_t get_h5_typ(int typ_enum)
{
// printf("h5 type enum:%d\n", typ_enum);
hid_t types_list[] = {H5T_NATIVE_CHAR, H5T_NATIVE_UCHAR,
H5T_NATIVE_INT, H5T_NATIVE_LLONG, H5T_NATIVE_FLOAT, H5T_NATIVE_DOUBLE};
return types_list[typ_enum];
}
// _h5_str_typ_table = {
// 'i1':0,
// 'u1':1,
// 'i4':2,
// 'i8':3,
// 'f4':4,
// 'f8':5
// }
int hpat_h5_get_type_enum(std::string *s)
{
int typ = -1;
if ((*s)=="i1")
typ = 0;
if ((*s)=="u1")
typ = 1;
if ((*s)=="i4")
typ = 2;
if ((*s)=="i8")
typ = 3;
if ((*s)=="f4")
typ = 4;
if ((*s)=="f8")
typ = 5;
return typ;
}
int hpat_h5_close(hid_t file_id)
{
// printf("closing: %d\n", file_id);
H5Fclose(file_id);
return 0;
}
hid_t hpat_h5_create_dset(hid_t file_id, char* dset_name, int ndims,
int64_t* counts, int typ_enum)
{
// printf("dset_name:%s ndims:%d size:%d typ:%d\n", dset_name, ndims, counts[0], typ_enum);
// fflush(stdout);
hid_t dataset_id;
hid_t filespace;
hid_t h5_typ = get_h5_typ(typ_enum);
filespace = H5Screate_simple(ndims, (const hsize_t *)counts, NULL);
dataset_id = H5Dcreate(file_id, dset_name, h5_typ, filespace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Sclose(filespace);
return dataset_id;
}
hid_t hpat_h5_create_group(hid_t file_id, char* group_name)
{
// printf("group_name:%s\n", group_name);
// fflush(stdout);
hid_t group_id;
group_id = H5Gcreate2(file_id, group_name,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
return group_id;
}
int hpat_h5_write(hid_t file_id, hid_t dataset_id, int ndims, int64_t* starts,
int64_t* counts, int64_t is_parallel, void* out, int typ_enum)
{
//printf("dset_id:%s ndims:%d size:%d typ:%d\n", dset_id, ndims, counts[0], typ_enum);
// fflush(stdout);
herr_t ret;
assert(dataset_id != -1);
hid_t space_id = H5Dget_space(dataset_id);
assert(space_id != -1);
hsize_t* HDF5_start = (hsize_t*)starts;
hsize_t* HDF5_count = (hsize_t*)counts;
hid_t xfer_plist_id = H5P_DEFAULT;
if(is_parallel)
{
xfer_plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(xfer_plist_id, H5FD_MPIO_COLLECTIVE);
}
ret = H5Sselect_hyperslab(space_id, H5S_SELECT_SET, HDF5_start, NULL, HDF5_count, NULL);
assert(ret != -1);
hid_t mem_dataspace = H5Screate_simple((hsize_t)ndims, HDF5_count, NULL);
assert (mem_dataspace != -1);
hid_t h5_typ = get_h5_typ(typ_enum);
ret = H5Dwrite(dataset_id, h5_typ, mem_dataspace, space_id, xfer_plist_id, out);
assert(ret != -1);
H5Dclose(dataset_id);
return ret;
}
int64_t h5g_get_num_objs(hid_t file_id)
{
H5G_info_t group_info;
herr_t err;
err = H5Gget_info(file_id, &group_info);
// printf("num links:%lld\n", group_info.nlinks);
return (int64_t)group_info.nlinks;
}
void* h5g_get_objname_by_idx(hid_t file_id, int64_t ind)
{
herr_t err;
// first call gets size:
// https://support.hdfgroup.org/HDF5/doc1.8/RM/RM_H5L.html#Link-GetNameByIdx
int size = H5Lget_name_by_idx(file_id, ".", H5_INDEX_NAME, H5_ITER_NATIVE,
(hsize_t)ind, NULL, 0, H5P_DEFAULT);
char* name = (char*) malloc(size+1);
err = H5Lget_name_by_idx(file_id, ".", H5_INDEX_NAME, H5_ITER_NATIVE,
(hsize_t)ind, name, size+1, H5P_DEFAULT);
// printf("g name:%s\n", name);
std::string *outstr = new std::string(name);
// std::cout<<"out: "<<*outstr<<std::endl;
return outstr;
}
uint64_t get_file_size(std::string* file_name)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
uint64_t f_size = 0;
if (f_size==MPI_ROOT)
{
boost::filesystem::path f_path(*file_name);
// TODO: throw FileNotFoundError
if (!boost::filesystem::exists(f_path))
{
std::cerr << "No such file or directory: " << *file_name << '\n';
return 0;
}
f_size = (uint64_t)boost::filesystem::file_size(f_path);
}
MPI_Bcast(&f_size, 1, MPI_UNSIGNED_LONG_LONG, MPI_ROOT, MPI_COMM_WORLD);
return f_size;
}
void file_read(std::string* file_name, void* buff, int64_t size)
{
FILE* fp = fopen(file_name->c_str(), "rb");
size_t ret_code = fread(buff, 1, (size_t)size, fp);
if (ret_code != (size_t)size)
{
std::cerr << "File read error: " << *file_name << '\n';
}
fclose(fp);
return;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017-2019 the rbfx 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.
//
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Core/ProcessUtils.h>
#include "Project.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Importers/ModelImporter.h"
namespace Urho3D
{
static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations";
static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials";
static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures";
static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color";
static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals";
static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones";
static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency";
static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion";
static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes";
ModelImporter::ModelImporter(Context* context)
: AssetImporter(context)
{
}
void ModelImporter::RegisterObject(Context* context)
{
context->RegisterFactory<ModelImporter>();
URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT);
}
void ModelImporter::RenderInspector(const char* filter)
{
BaseClassName::RenderInspector(filter);
}
bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& inputFile, const ea::string& outputPath)
{
auto* fs = GetFileSystem();
auto* project = GetSubsystem<Project>();
ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/";
// Models go into "{resource_name}/" subfolder in cache directory.
ea::string outputDir = outputPath + GetFileNameAndExtension(inputFile) + "/";
fs->CreateDirsRecursive(outputDir);
ea::string output = tempPath + "Model.mdl";
ea::vector<ea::string> args{"model", input->GetResourcePath(), output};
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool())
args.emplace_back("-na");
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool())
args.emplace_back("-nm");
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool())
args.emplace_back("-nt");
if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool())
args.emplace_back("-nc");
if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool())
args.emplace_back("-nf");
args.emplace_back("-mb");
args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool()));
args.emplace_back("-f");
args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt()));
if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool())
args.emplace_back("-eao");
if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool())
args.emplace_back("-np");
int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args);
if (result != 0)
{
URHO3D_LOGERROR("Importing asset '{}' failed.", input->GetName());
return false;
}
ea::string byproductNameStart = input->GetName() + "/";
unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath());
ClearByproducts();
StringVector tmpByproducts;
fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true);
tmpByproducts.erase_first(".");
tmpByproducts.erase_first("..");
for (const ea::string& byproduct : tmpByproducts)
{
fs->SetLastModifiedTime(tempPath + byproduct, mtime);
ea::string moveTo = outputDir + byproduct;
if (fs->FileExists(moveTo))
fs->Delete(moveTo);
else if (fs->DirExists(moveTo))
fs->RemoveDir(moveTo, true);
fs->CreateDirsRecursive(GetPath(moveTo));
fs->Rename(tempPath + byproduct, moveTo);
fs->SetLastModifiedTime(moveTo, mtime);
AddByproduct(byproductNameStart + byproduct);
}
fs->RemoveDir(tempPath, true);
return true;
}
bool ModelImporter::Accepts(const ea::string& path) const
{
if (path.ends_with(".fbx"))
return true;
if (path.ends_with(".blend"))
return true;
return false;
}
}
<commit_msg>Editor: Remove file extension from model byproduct folders.<commit_after>//
// Copyright (c) 2017-2019 the rbfx 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.
//
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Core/ProcessUtils.h>
#include "Project.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Importers/ModelImporter.h"
namespace Urho3D
{
static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations";
static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials";
static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures";
static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color";
static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals";
static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones";
static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency";
static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion";
static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes";
ModelImporter::ModelImporter(Context* context)
: AssetImporter(context)
{
}
void ModelImporter::RegisterObject(Context* context)
{
context->RegisterFactory<ModelImporter>();
URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT);
URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT);
}
void ModelImporter::RenderInspector(const char* filter)
{
BaseClassName::RenderInspector(filter);
}
bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& inputFile, const ea::string& outputPath)
{
auto* fs = GetFileSystem();
auto* project = GetSubsystem<Project>();
ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/";
// Models go into "{resource_name}/" subfolder in cache directory.
ea::string outputDir = outputPath + GetFileName(inputFile) + "/";
fs->CreateDirsRecursive(outputDir);
ea::string output = tempPath + "Model.mdl";
ea::vector<ea::string> args{"model", input->GetResourcePath(), output};
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool())
args.emplace_back("-na");
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool())
args.emplace_back("-nm");
if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool())
args.emplace_back("-nt");
if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool())
args.emplace_back("-nc");
if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool())
args.emplace_back("-nf");
args.emplace_back("-mb");
args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool()));
args.emplace_back("-f");
args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt()));
if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool())
args.emplace_back("-eao");
if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool())
args.emplace_back("-np");
int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args);
if (result != 0)
{
URHO3D_LOGERROR("Importing asset '{}' failed.", input->GetName());
return false;
}
ea::string byproductNameStart = GetPath(input->GetName()) + GetFileName(input->GetName()) + "/"; // Strip file extension
unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath());
ClearByproducts();
StringVector tmpByproducts;
fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true);
tmpByproducts.erase_first(".");
tmpByproducts.erase_first("..");
for (const ea::string& byproduct : tmpByproducts)
{
fs->SetLastModifiedTime(tempPath + byproduct, mtime);
ea::string moveTo = outputDir + byproduct;
if (fs->FileExists(moveTo))
fs->Delete(moveTo);
else if (fs->DirExists(moveTo))
fs->RemoveDir(moveTo, true);
fs->CreateDirsRecursive(GetPath(moveTo));
fs->Rename(tempPath + byproduct, moveTo);
fs->SetLastModifiedTime(moveTo, mtime);
AddByproduct(byproductNameStart + byproduct);
}
fs->RemoveDir(tempPath, true);
return true;
}
bool ModelImporter::Accepts(const ea::string& path) const
{
if (path.ends_with(".fbx"))
return true;
if (path.ends_with(".blend"))
return true;
return false;
}
}
<|endoftext|> |
<commit_before>/**
* @file stringtable.hpp
* @author Robin Dietrich <me (at) invokr (dot) org>
* @version 1.0
*
* @par License
* Alice Replay Parser
* Copyright 2014 Robin Dietrich
*
* 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.
*
*/
#ifndef _DOTA_STRINGTABLE_HPP_
#define _DOTA_STRINGTABLE_HPP_
#include <string>
#include <unordered_map>
#include <alice/netmessages.pb.h>
#include <alice/exception.hpp>
#include <alice/multiindex.hpp>
/// Defines the maximum number of keys to keep a history of
///
/// Stringtables may require you to keep track of a number of recently added keys.
/// A substring of those is prepended to new keys in order to save bandwidth.
#define STRINGTABLE_KEY_HISTORY 32
/// Maximum length of a stringtable Key
///
/// This value is just an estimate.
#define STRINGTABLE_MAX_KEY_SIZE 0x400 // 1024
/// Maximum size of a stringtable Value
#define STRINGTABLE_MAX_VALUE_SIZE 0x4000 // 16384
/// The baselinetable, required for parsing entities
///
/// This is a special table which contains the default values for
/// a number of entities. It's used to generate a default state for said
/// entity in order to save bandwith. The baselineinstance maybe updated in order
/// to reflect state changes in those entities.
#define BASELINETABLE "instancebaseline"
namespace dota {
namespace detail {
/** Helper that pops the first element off a vector */
template<typename T>
void pop_front(std::vector<T>& vec) {
assert(!vec.empty());
vec.erase(vec.begin());
}
}
/// @defgroup EXCEPTIONS Exceptions
/// @{
/// Thrown when trying to access a stringtable directly via an invalid / non-existent key
CREATE_EXCEPTION( stringtableUnkownKey, "Trying to access stringtable via invalid key." )
/// Thrown when trying to access an unkown index
CREATE_EXCEPTION( stringtableUnkownIndex, "Trying to access stringtable via invalid index." )
/// Thrown when a stringtable is marked for a full update but doesn't provide a key
CREATE_EXCEPTION( stringtableKeyMissing, "Stringtable key missing in full update." )
/// Thrown when using the key history with a malformed string
CREATE_EXCEPTION( stringtableMalformedSubstring, "Trying to access recent keys with invalid specs." )
/// Thrown when reading a value would cause an overflow
CREATE_EXCEPTION( stringtableValueOverflow, "Trying to read large stringtable value." )
/// @}
// forward declaration
class bitstream;
/// @defgroup CORE Core
/// @{
/**
* Networked stringtable containing a set of keys and values.
*
* Stringtables seem to be used for multiple purposes in Source. They are basically values
* that the client needs which are not directly tied to properties and might not change very often,
* hence why they can be globaly accessed in the stringtable.
*
* These might be implemented in a different way in the source engine to provide facilities for
* writing and direct table access. We currently only know the meaning of a few tables, though this might
* change in the future.
*/
class stringtable {
public:
/** Type of multiindex container */
typedef multiindex<std::string, int32_t, std::string> storage;
/** Size type of said container */
typedef storage::size_type size_type;
/** Value type */
typedef storage::value_type value_type;
/** Type for an ordered iterator */
typedef storage::index_iterator iterator;
/** Constructor, initializes table from protobuf object */
stringtable(CSVCMsg_CreateStringTable* table);
/** Returns iterator pointed at the beginning of the stringtable entries */
inline iterator begin() const {
return db.beginIndex();
}
/** Returns iterator pointed at the end of the stringtable entries */
inline iterator end() const {
return db.endIndex();
}
/** Return number of elements stored in the stringtable */
inline size_type size() const {
return db.size();
}
/** Get element value by key */
inline const value_type& get(const std::string& key) const {
auto it = db.findKey(key);
if (it == db.end())
BOOST_THROW_EXCEPTION( stringtableUnkownKey()
<< EArg<1>::info(key)
);
return it->value;
}
/** Get element value by index */
inline const value_type& get(const int32_t& index) const {
auto it = db.findIndex(index);
if (it == db.endIndex())
BOOST_THROW_EXCEPTION( stringtableUnkownIndex()
<< (EArgT<1, int32_t>::info(index))
);
return it->value;
}
/** Returns name of this stringtable */
inline const std::string& getName() const {
return name;
}
/** Returns maximum number of entries for this table */
inline const uint32_t& getMaxEntries() const {
return maxEntries;
}
/** Returns whether the data read from updates has a fixed size */
inline const bool isSizeFixed() const {
return userDataFixed;
}
/** Returns data size in bits */
inline const uint32_t& getDataBits() const {
return userDataSizeBits;
}
/** Returns flags for this table */
inline const int32_t& getFlags() const {
return flags;
}
/** Update table from protobuf */
inline void update(CSVCMsg_UpdateStringTable* table) const {
update(table->num_changed_entries(), table->string_data());
}
private:
/** Name of this stringtable */
const std::string name;
/** Maximum number of entries */
const uint32_t maxEntries;
/** Whether the data read from updates has a fixed size */
const bool userDataFixed;
/** Size of data in bytes */
const uint32_t userDataSize;
/** Size of data in bits */
const uint32_t userDataSizeBits;
/** Flags for this table */
const int32_t flags;
/** List of stringtable entries */
mutable storage db;
/** Update table from raw data */
void update(const uint32_t& entries, const std::string& data) const;
};
/// @}
}
#endif /* _DOTA_STRINGTABLES_HPP_ */<commit_msg>Added set method to stringtable<commit_after>/**
* @file stringtable.hpp
* @author Robin Dietrich <me (at) invokr (dot) org>
* @version 1.0
*
* @par License
* Alice Replay Parser
* Copyright 2014 Robin Dietrich
*
* 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.
*
*/
#ifndef _DOTA_STRINGTABLE_HPP_
#define _DOTA_STRINGTABLE_HPP_
#include <string>
#include <unordered_map>
#include <alice/netmessages.pb.h>
#include <alice/exception.hpp>
#include <alice/multiindex.hpp>
/// Defines the maximum number of keys to keep a history of
///
/// Stringtables may require you to keep track of a number of recently added keys.
/// A substring of those is prepended to new keys in order to save bandwidth.
#define STRINGTABLE_KEY_HISTORY 32
/// Maximum length of a stringtable Key
///
/// This value is just an estimate.
#define STRINGTABLE_MAX_KEY_SIZE 0x400 // 1024
/// Maximum size of a stringtable Value
#define STRINGTABLE_MAX_VALUE_SIZE 0x4000 // 16384
/// The baselinetable, required for parsing entities
///
/// This is a special table which contains the default values for
/// a number of entities. It's used to generate a default state for said
/// entity in order to save bandwith. The baselineinstance maybe updated in order
/// to reflect state changes in those entities.
#define BASELINETABLE "instancebaseline"
namespace dota {
namespace detail {
/** Helper that pops the first element off a vector */
template<typename T>
void pop_front(std::vector<T>& vec) {
assert(!vec.empty());
vec.erase(vec.begin());
}
}
/// @defgroup EXCEPTIONS Exceptions
/// @{
/// Thrown when trying to access a stringtable directly via an invalid / non-existent key
CREATE_EXCEPTION( stringtableUnkownKey, "Trying to access stringtable via invalid key." )
/// Thrown when trying to access an unkown index
CREATE_EXCEPTION( stringtableUnkownIndex, "Trying to access stringtable via invalid index." )
/// Thrown when a stringtable is marked for a full update but doesn't provide a key
CREATE_EXCEPTION( stringtableKeyMissing, "Stringtable key missing in full update." )
/// Thrown when using the key history with a malformed string
CREATE_EXCEPTION( stringtableMalformedSubstring, "Trying to access recent keys with invalid specs." )
/// Thrown when reading a value would cause an overflow
CREATE_EXCEPTION( stringtableValueOverflow, "Trying to read large stringtable value." )
/// @}
// forward declaration
class bitstream;
/// @defgroup CORE Core
/// @{
/**
* Networked stringtable containing a set of keys and values.
*
* Stringtables seem to be used for multiple purposes in Source. They are basically values
* that the client needs which are not directly tied to properties and might not change very often,
* hence why they can be globaly accessed in the stringtable.
*
* These might be implemented in a different way in the source engine to provide facilities for
* writing and direct table access. We currently only know the meaning of a few tables, though this might
* change in the future.
*/
class stringtable {
public:
/** Type of multiindex container */
typedef multiindex<std::string, int32_t, std::string> storage;
/** Size type of said container */
typedef storage::size_type size_type;
/** Value type */
typedef storage::value_type value_type;
/** Type for an ordered iterator */
typedef storage::index_iterator iterator;
/** Constructor, initializes table from protobuf object */
stringtable(CSVCMsg_CreateStringTable* table);
/** Returns iterator pointed at the beginning of the stringtable entries */
inline iterator begin() const {
return db.beginIndex();
}
/** Returns iterator pointed at the end of the stringtable entries */
inline iterator end() const {
return db.endIndex();
}
/** Return number of elements stored in the stringtable */
inline size_type size() const {
return db.size();
}
/** Set value of key directly */
inline void set(const std::string& key, std::string value) const {
if (db.findKey(key) == db.end())
return;
db.set(key, std::move(value));
}
/** Get element value by key */
inline const value_type& get(const std::string& key) const {
auto it = db.findKey(key);
if (it == db.end())
BOOST_THROW_EXCEPTION( stringtableUnkownKey()
<< EArg<1>::info(key)
);
return it->value;
}
/** Get element value by index */
inline const value_type& get(const int32_t& index) const {
auto it = db.findIndex(index);
if (it == db.endIndex())
BOOST_THROW_EXCEPTION( stringtableUnkownIndex()
<< (EArgT<1, int32_t>::info(index))
);
return it->value;
}
/** Returns name of this stringtable */
inline const std::string& getName() const {
return name;
}
/** Returns maximum number of entries for this table */
inline const uint32_t& getMaxEntries() const {
return maxEntries;
}
/** Returns whether the data read from updates has a fixed size */
inline const bool isSizeFixed() const {
return userDataFixed;
}
/** Returns data size in bits */
inline const uint32_t& getDataBits() const {
return userDataSizeBits;
}
/** Returns flags for this table */
inline const int32_t& getFlags() const {
return flags;
}
/** Update table from protobuf */
inline void update(CSVCMsg_UpdateStringTable* table) const {
update(table->num_changed_entries(), table->string_data());
}
private:
/** Name of this stringtable */
const std::string name;
/** Maximum number of entries */
const uint32_t maxEntries;
/** Whether the data read from updates has a fixed size */
const bool userDataFixed;
/** Size of data in bytes */
const uint32_t userDataSize;
/** Size of data in bits */
const uint32_t userDataSizeBits;
/** Flags for this table */
const int32_t flags;
/** List of stringtable entries */
mutable storage db;
/** Update table from raw data */
void update(const uint32_t& entries, const std::string& data) const;
};
/// @}
}
#endif /* _DOTA_STRINGTABLES_HPP_ */<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "IncrementalJIT.h"
#include "IncrementalExecutor.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/Support/DynamicLibrary.h"
#ifdef __APPLE__
// Apple adds an extra '_'
# define MANGLE_PREFIX "_"
#else
# define MANGLE_PREFIX ""
#endif
using namespace llvm;
namespace {
// Forward cxa_atexit for global d'tors.
static void local_cxa_atexit(void (*func) (void*), void* arg, void* dso) {
cling::IncrementalExecutor* exe = (cling::IncrementalExecutor*)dso;
exe->AddAtExitFunc(func, arg);
}
///\brief Memory manager providing the lop-level link to the
/// IncrementalExecutor, handles missing or special / replaced symbols.
class ClingMemoryManager: public SectionMemoryManager {
cling::IncrementalExecutor& m_exe;
public:
ClingMemoryManager(cling::IncrementalExecutor& Exe):
m_exe(Exe) {}
///\brief Simply wraps the base class's function setting AbortOnFailure
/// to false and instead using the error handling mechanism to report it.
void* getPointerToNamedFunction(const std::string &Name,
bool /*AbortOnFailure*/ =true) override {
return SectionMemoryManager::getPointerToNamedFunction(Name, false);
}
};
class NotifyFinalizedT {
public:
NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {}
void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) {
m_JIT.RemoveUnfinalizedSection(H);
}
private:
cling::IncrementalJIT &m_JIT;
};
} // unnamed namespace
namespace cling {
///\brief Memory manager for the OrcJIT layers to resolve symbols from the
/// common IncrementalJIT. I.e. the master of the Orcs.
/// Each ObjectLayer instance has one Azog object.
class Azog: public RTDyldMemoryManager {
cling::IncrementalJIT& m_jit;
public:
Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {}
RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); }
uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
StringRef SectionName) override {
uint8_t *Addr =
getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName);
m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr);
return Addr;
}
uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName,
bool IsReadOnly) override {
uint8_t *Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID,
SectionName, IsReadOnly);
m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr);
return Addr;
}
void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
uintptr_t RODataSize, uint32_t RODataAlign,
uintptr_t RWDataSize, uint32_t RWDataAlign) override {
return getExeMM()->reserveAllocationSpace(CodeSize, CodeAlign, RODataSize,
RODataAlign, RWDataSize,
RWDataAlign);
}
bool needsToReserveAllocationSpace() override {
return getExeMM()->needsToReserveAllocationSpace();
}
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
size_t Size) override {
return getExeMM()->registerEHFrames(Addr, LoadAddr, Size);
}
void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
size_t Size) override {
return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size);
}
uint64_t getSymbolAddress(const std::string &Name) override {
return m_jit.getSymbolAddressWithoutMangling(Name,
true /*also use dlsym*/)
.getAddress();
}
void *getPointerToNamedFunction(const std::string &Name,
bool AbortOnFailure = true) override {
return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure);
}
using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded;
void notifyObjectLoaded(ExecutionEngine *EE,
const object::ObjectFile &O) override {
return getExeMM()->notifyObjectLoaded(EE, O);
}
bool finalizeMemory(std::string *ErrMsg = nullptr) override {
// Each set of objects loaded will be finalized exactly once, but since
// symbol lookup during relocation may recursively trigger the
// loading/relocation of other modules, and since we're forwarding all
// finalizeMemory calls to a single underlying memory manager, we need to
// defer forwarding the call on until all necessary objects have been
// loaded. Otherwise, during the relocation of a leaf object, we will end
// up finalizing memory, causing a crash further up the stack when we
// attempt to apply relocations to finalized memory.
// To avoid finalizing too early, look at how many objects have been
// loaded but not yet finalized. This is a bit of a hack that relies on
// the fact that we're lazily emitting object files: The only way you can
// get more than one set of objects loaded but not yet finalized is if
// they were loaded during relocation of another set.
if (m_jit.m_UnfinalizedSections.size() == 1)
return getExeMM()->finalizeMemory(ErrMsg);
return false;
};
}; // class Azog
IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe,
std::unique_ptr<TargetMachine> TM):
m_Parent(exe),
m_TM(std::move(TM)),
m_TMDataLayout(m_TM->createDataLayout()),
m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)),
m_NotifyObjectLoaded(*this),
m_ObjectLayer(m_NotifyObjectLoaded, NotifyFinalizedT(*this)),
m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)),
m_LazyEmitLayer(m_CompileLayer) {
// Enable JIT symbol resolution from the binary.
llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0);
// Make debug symbols available.
m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener();
// #if MCJIT
// llvm::EngineBuilder builder(std::move(m));
// std::string errMsg;
// builder.setErrorStr(&errMsg);
// builder.setOptLevel(llvm::CodeGenOpt::Less);
// builder.setEngineKind(llvm::EngineKind::JIT);
// std::unique_ptr<llvm::RTDyldMemoryManager>
// MemMan(new ClingMemoryManager(*this));
// builder.setMCJITMemoryManager(std::move(MemMan));
// // EngineBuilder uses default c'ted TargetOptions, too:
// llvm::TargetOptions TargetOpts;
// TargetOpts.NoFramePointerElim = 1;
// TargetOpts.JITEmitDebugInfo = 1;
// builder.setTargetOptions(TargetOpts);
// m_engine.reset(builder.create());
// assert(m_engine && "Cannot create module!");
// #endif
}
llvm::orc::JITSymbol
IncrementalJIT::getSymbolAddressWithoutMangling(llvm::StringRef Name,
bool AlsoInProcess) {
if (Name == MANGLE_PREFIX "__cxa_atexit") {
// Rewire __cxa_atexit to ~Interpreter(), thus also global destruction
// coming from the JIT.
return llvm::orc::JITSymbol((uint64_t)&local_cxa_atexit,
llvm::JITSymbolFlags::Exported);
} else if (Name == MANGLE_PREFIX "__dso_handle") {
// Provide IncrementalExecutor as the third argument to __cxa_atexit.
return llvm::orc::JITSymbol((uint64_t)&m_Parent,
llvm::JITSymbolFlags::Exported);
}
if (AlsoInProcess) {
if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name))
return llvm::orc::JITSymbol(SymInfo.getAddress(),
llvm::JITSymbolFlags::Exported);
}
auto SymMapI = m_SymbolMap.find(Name);
if (SymMapI != m_SymbolMap.end())
return SymMapI->second;
if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false))
return Sym;
return llvm::orc::JITSymbol(nullptr);
}
size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) {
// If this module doesn't have a DataLayout attached then attach the
// default.
for (auto&& mod: modules) {
mod->setDataLayout(m_TMDataLayout);
}
// LLVM MERGE FIXME: update this to use new interfaces.
auto Resolver = llvm::orc::createLambdaResolver(
[&](const std::string &Name) {
if (auto Sym = getSymbolAddressWithoutMangling(Name, true)
/*was: findSymbol(Name)*/)
return RuntimeDyld::SymbolInfo(Sym.getAddress(),
Sym.getFlags());
/// This method returns the address of the specified function or variable
/// that could not be resolved by getSymbolAddress() or by resolving
/// possible weak symbols by the ExecutionEngine.
/// It is used to resolve symbols during module linking.
std::string NameNoPrefix;
if (MANGLE_PREFIX[0]
&& !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX))
NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1);
else
NameNoPrefix = std::move(Name);
uint64_t addr
= (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix);
return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak);
},
[&](const std::string &S) {
auto SymMapI = m_SymbolMap.find(S);
if (SymMapI != m_SymbolMap.end()) {
llvm::orc::JITSymbol &Sym = SymMapI->second;
return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(),
Sym.getFlags());
}
return m_ExeMM->findSymbol(S);
} );
ModuleSetHandleT MSHandle
= m_LazyEmitLayer.addModuleSet(std::move(modules),
llvm::make_unique<Azog>(*this),
std::move(Resolver));
m_UnloadPoints.push_back(MSHandle);
return m_UnloadPoints.size() - 1;
}
// void* IncrementalJIT::finalizeMemory() {
// for (auto &P : UnfinalizedSections)
// if (P.second.count(LocalAddress))
// ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress);
// }
void IncrementalJIT::removeModules(size_t handle) {
if (handle == (size_t)-1)
return;
m_LazyEmitLayer.removeModuleSet(m_UnloadPoints[handle]);
}
}// end namespace cling
<commit_msg>Adapt to changed order of dlsym/JIT lambda in master.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "IncrementalJIT.h"
#include "IncrementalExecutor.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/Support/DynamicLibrary.h"
#ifdef __APPLE__
// Apple adds an extra '_'
# define MANGLE_PREFIX "_"
#else
# define MANGLE_PREFIX ""
#endif
using namespace llvm;
namespace {
// Forward cxa_atexit for global d'tors.
static void local_cxa_atexit(void (*func) (void*), void* arg, void* dso) {
cling::IncrementalExecutor* exe = (cling::IncrementalExecutor*)dso;
exe->AddAtExitFunc(func, arg);
}
///\brief Memory manager providing the lop-level link to the
/// IncrementalExecutor, handles missing or special / replaced symbols.
class ClingMemoryManager: public SectionMemoryManager {
cling::IncrementalExecutor& m_exe;
public:
ClingMemoryManager(cling::IncrementalExecutor& Exe):
m_exe(Exe) {}
///\brief Simply wraps the base class's function setting AbortOnFailure
/// to false and instead using the error handling mechanism to report it.
void* getPointerToNamedFunction(const std::string &Name,
bool /*AbortOnFailure*/ =true) override {
return SectionMemoryManager::getPointerToNamedFunction(Name, false);
}
};
class NotifyFinalizedT {
public:
NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {}
void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) {
m_JIT.RemoveUnfinalizedSection(H);
}
private:
cling::IncrementalJIT &m_JIT;
};
} // unnamed namespace
namespace cling {
///\brief Memory manager for the OrcJIT layers to resolve symbols from the
/// common IncrementalJIT. I.e. the master of the Orcs.
/// Each ObjectLayer instance has one Azog object.
class Azog: public RTDyldMemoryManager {
cling::IncrementalJIT& m_jit;
public:
Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {}
RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); }
uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
StringRef SectionName) override {
uint8_t *Addr =
getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName);
m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr);
return Addr;
}
uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName,
bool IsReadOnly) override {
uint8_t *Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID,
SectionName, IsReadOnly);
m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr);
return Addr;
}
void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
uintptr_t RODataSize, uint32_t RODataAlign,
uintptr_t RWDataSize, uint32_t RWDataAlign) override {
return getExeMM()->reserveAllocationSpace(CodeSize, CodeAlign, RODataSize,
RODataAlign, RWDataSize,
RWDataAlign);
}
bool needsToReserveAllocationSpace() override {
return getExeMM()->needsToReserveAllocationSpace();
}
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
size_t Size) override {
return getExeMM()->registerEHFrames(Addr, LoadAddr, Size);
}
void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr,
size_t Size) override {
return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size);
}
uint64_t getSymbolAddress(const std::string &Name) override {
return m_jit.getSymbolAddressWithoutMangling(Name,
true /*also use dlsym*/)
.getAddress();
}
void *getPointerToNamedFunction(const std::string &Name,
bool AbortOnFailure = true) override {
return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure);
}
using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded;
void notifyObjectLoaded(ExecutionEngine *EE,
const object::ObjectFile &O) override {
return getExeMM()->notifyObjectLoaded(EE, O);
}
bool finalizeMemory(std::string *ErrMsg = nullptr) override {
// Each set of objects loaded will be finalized exactly once, but since
// symbol lookup during relocation may recursively trigger the
// loading/relocation of other modules, and since we're forwarding all
// finalizeMemory calls to a single underlying memory manager, we need to
// defer forwarding the call on until all necessary objects have been
// loaded. Otherwise, during the relocation of a leaf object, we will end
// up finalizing memory, causing a crash further up the stack when we
// attempt to apply relocations to finalized memory.
// To avoid finalizing too early, look at how many objects have been
// loaded but not yet finalized. This is a bit of a hack that relies on
// the fact that we're lazily emitting object files: The only way you can
// get more than one set of objects loaded but not yet finalized is if
// they were loaded during relocation of another set.
if (m_jit.m_UnfinalizedSections.size() == 1)
return getExeMM()->finalizeMemory(ErrMsg);
return false;
};
}; // class Azog
IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe,
std::unique_ptr<TargetMachine> TM):
m_Parent(exe),
m_TM(std::move(TM)),
m_TMDataLayout(m_TM->createDataLayout()),
m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)),
m_NotifyObjectLoaded(*this),
m_ObjectLayer(m_NotifyObjectLoaded, NotifyFinalizedT(*this)),
m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)),
m_LazyEmitLayer(m_CompileLayer) {
// Enable JIT symbol resolution from the binary.
llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0);
// Make debug symbols available.
m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener();
// #if MCJIT
// llvm::EngineBuilder builder(std::move(m));
// std::string errMsg;
// builder.setErrorStr(&errMsg);
// builder.setOptLevel(llvm::CodeGenOpt::Less);
// builder.setEngineKind(llvm::EngineKind::JIT);
// std::unique_ptr<llvm::RTDyldMemoryManager>
// MemMan(new ClingMemoryManager(*this));
// builder.setMCJITMemoryManager(std::move(MemMan));
// // EngineBuilder uses default c'ted TargetOptions, too:
// llvm::TargetOptions TargetOpts;
// TargetOpts.NoFramePointerElim = 1;
// TargetOpts.JITEmitDebugInfo = 1;
// builder.setTargetOptions(TargetOpts);
// m_engine.reset(builder.create());
// assert(m_engine && "Cannot create module!");
// #endif
}
llvm::orc::JITSymbol
IncrementalJIT::getSymbolAddressWithoutMangling(llvm::StringRef Name,
bool AlsoInProcess) {
if (Name == MANGLE_PREFIX "__cxa_atexit") {
// Rewire __cxa_atexit to ~Interpreter(), thus also global destruction
// coming from the JIT.
return llvm::orc::JITSymbol((uint64_t)&local_cxa_atexit,
llvm::JITSymbolFlags::Exported);
} else if (Name == MANGLE_PREFIX "__dso_handle") {
// Provide IncrementalExecutor as the third argument to __cxa_atexit.
return llvm::orc::JITSymbol((uint64_t)&m_Parent,
llvm::JITSymbolFlags::Exported);
}
if (AlsoInProcess) {
if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name))
return llvm::orc::JITSymbol(SymInfo.getAddress(),
llvm::JITSymbolFlags::Exported);
}
auto SymMapI = m_SymbolMap.find(Name);
if (SymMapI != m_SymbolMap.end())
return SymMapI->second;
if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false))
return Sym;
return llvm::orc::JITSymbol(nullptr);
}
size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) {
// If this module doesn't have a DataLayout attached then attach the
// default.
for (auto&& mod: modules) {
mod->setDataLayout(m_TMDataLayout);
}
// LLVM MERGE FIXME: update this to use new interfaces.
auto Resolver = llvm::orc::createLambdaResolver(
[&](const std::string &S) {
auto SymMapI = m_SymbolMap.find(S);
if (SymMapI != m_SymbolMap.end()) {
llvm::orc::JITSymbol &Sym = SymMapI->second;
return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(),
Sym.getFlags());
}
return m_ExeMM->findSymbol(S);
},
[&](const std::string &Name) {
if (auto Sym = getSymbolAddressWithoutMangling(Name, true)
/*was: findSymbol(Name)*/)
return RuntimeDyld::SymbolInfo(Sym.getAddress(),
Sym.getFlags());
/// This method returns the address of the specified function or variable
/// that could not be resolved by getSymbolAddress() or by resolving
/// possible weak symbols by the ExecutionEngine.
/// It is used to resolve symbols during module linking.
std::string NameNoPrefix;
if (MANGLE_PREFIX[0]
&& !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX))
NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1);
else
NameNoPrefix = std::move(Name);
uint64_t addr
= (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix);
return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak);
});
ModuleSetHandleT MSHandle
= m_LazyEmitLayer.addModuleSet(std::move(modules),
llvm::make_unique<Azog>(*this),
std::move(Resolver));
m_UnloadPoints.push_back(MSHandle);
return m_UnloadPoints.size() - 1;
}
// void* IncrementalJIT::finalizeMemory() {
// for (auto &P : UnfinalizedSections)
// if (P.second.count(LocalAddress))
// ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress);
// }
void IncrementalJIT::removeModules(size_t handle) {
if (handle == (size_t)-1)
return;
m_LazyEmitLayer.removeModuleSet(m_UnloadPoints[handle]);
}
}// end namespace cling
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/speech/speech_recognition_request.h"
#include "app/l10n_util.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_status.h"
namespace {
const char* const kDefaultSpeechRecognitionUrl =
"http://www.google.com/speech-api/v1/recognize?client=chromium&";
const char* const kHypothesesString = "hypotheses";
const char* const kUtteranceString = "utterance";
const char* const kConfidenceString = "confidence";
bool ParseServerResponse(const std::string& response_body,
speech_input::SpeechInputResultArray* result) {
if (response_body.empty()) {
LOG(WARNING) << "ParseServerResponse: Response was empty.";
return false;
}
DVLOG(1) << "ParseServerResponse: Parsing response " << response_body;
// Parse the response, ignoring comments.
std::string error_msg;
scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError(
response_body, false, NULL, &error_msg));
if (response_value == NULL) {
LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg;
return false;
}
if (!response_value->IsType(Value::TYPE_DICTIONARY)) {
VLOG(1) << "ParseServerResponse: Unexpected response type "
<< response_value->GetType();
return false;
}
const DictionaryValue* response_object =
static_cast<DictionaryValue*>(response_value.get());
// Get the hypotheses
Value* hypotheses_value = NULL;
if (!response_object->Get(kHypothesesString, &hypotheses_value)) {
VLOG(1) << "ParseServerResponse: Missing hypotheses attribute.";
return false;
}
DCHECK(hypotheses_value);
if (!hypotheses_value->IsType(Value::TYPE_LIST)) {
VLOG(1) << "ParseServerResponse: Unexpected hypotheses type "
<< hypotheses_value->GetType();
return false;
}
const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value);
if (hypotheses_list->GetSize() == 0) {
VLOG(1) << "ParseServerResponse: hypotheses list is empty.";
return false;
}
size_t index = 0;
for (; index < hypotheses_list->GetSize(); ++index) {
Value* hypothesis = NULL;
if (!hypotheses_list->Get(index, &hypothesis)) {
LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value.";
break;
}
DCHECK(hypothesis);
if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) {
LOG(WARNING) << "ParseServerResponse: Unexpected value type "
<< hypothesis->GetType();
break;
}
const DictionaryValue* hypothesis_value =
static_cast<DictionaryValue*>(hypothesis);
string16 utterance;
if (!hypothesis_value->GetString(kUtteranceString, &utterance)) {
LOG(WARNING) << "ParseServerResponse: Missing utterance value.";
break;
}
// It is not an error if the 'confidence' field is missing.
double confidence = 0.0;
hypothesis_value->GetReal(kConfidenceString, &confidence);
result->push_back(speech_input::SpeechInputResultItem(utterance,
confidence));
}
if (index < hypotheses_list->GetSize()) {
result->clear();
return false;
}
return true;
}
} // namespace
namespace speech_input {
int SpeechRecognitionRequest::url_fetcher_id_for_tests = 0;
SpeechRecognitionRequest::SpeechRecognitionRequest(
URLRequestContextGetter* context, Delegate* delegate)
: url_context_(context),
delegate_(delegate) {
DCHECK(delegate);
}
SpeechRecognitionRequest::~SpeechRecognitionRequest() {}
bool SpeechRecognitionRequest::Send(const std::string& language,
const std::string& grammar,
const std::string& content_type,
const std::string& audio_data) {
DCHECK(!url_fetcher_.get());
std::vector<std::string> parts;
if (!language.empty()) {
parts.push_back("lang=" + EscapeQueryParamValue(language, true));
} else {
std::string app_locale = l10n_util::GetApplicationLocale("");
parts.push_back("lang=" + EscapeQueryParamValue(app_locale, true));
}
if (!grammar.empty())
parts.push_back("grammar=" + EscapeQueryParamValue(grammar, true));
GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&'));
url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests,
url,
URLFetcher::POST,
this));
url_fetcher_->set_upload_data(content_type, audio_data);
url_fetcher_->set_request_context(url_context_);
// The speech recognition API does not require user identification as part
// of requests, so we don't send cookies or auth data for these requests to
// prevent any accidental connection between users who are logged into the
// domain for other services (e.g. bookmark sync) with the speech requests.
url_fetcher_->set_load_flags(
net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
return true;
}
void SpeechRecognitionRequest::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
DCHECK_EQ(url_fetcher_.get(), source);
bool error = !status.is_success() || response_code != 200;
SpeechInputResultArray result;
if (!error)
error = !ParseServerResponse(data, &result);
url_fetcher_.reset();
DVLOG(1) << "SpeechRecognitionRequest: Invoking delegate with result.";
delegate_->SetRecognitionResult(error, result);
}
} // namespace speech_input
<commit_msg>In the current speech input implementation, the application locale is used as language in case that no language attribute is provided. For this, the l10n_util::GetApplicationLocale was used from the IO thread. However this is not valid since that function requires file access.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/speech/speech_recognition_request.h"
#include <vector>
#include "app/l10n_util.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_status.h"
namespace {
const char* const kDefaultSpeechRecognitionUrl =
"http://www.google.com/speech-api/v1/recognize?client=chromium&";
const char* const kHypothesesString = "hypotheses";
const char* const kUtteranceString = "utterance";
const char* const kConfidenceString = "confidence";
bool ParseServerResponse(const std::string& response_body,
speech_input::SpeechInputResultArray* result) {
if (response_body.empty()) {
LOG(WARNING) << "ParseServerResponse: Response was empty.";
return false;
}
DVLOG(1) << "ParseServerResponse: Parsing response " << response_body;
// Parse the response, ignoring comments.
std::string error_msg;
scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError(
response_body, false, NULL, &error_msg));
if (response_value == NULL) {
LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg;
return false;
}
if (!response_value->IsType(Value::TYPE_DICTIONARY)) {
VLOG(1) << "ParseServerResponse: Unexpected response type "
<< response_value->GetType();
return false;
}
const DictionaryValue* response_object =
static_cast<DictionaryValue*>(response_value.get());
// Get the hypotheses
Value* hypotheses_value = NULL;
if (!response_object->Get(kHypothesesString, &hypotheses_value)) {
VLOG(1) << "ParseServerResponse: Missing hypotheses attribute.";
return false;
}
DCHECK(hypotheses_value);
if (!hypotheses_value->IsType(Value::TYPE_LIST)) {
VLOG(1) << "ParseServerResponse: Unexpected hypotheses type "
<< hypotheses_value->GetType();
return false;
}
const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value);
if (hypotheses_list->GetSize() == 0) {
VLOG(1) << "ParseServerResponse: hypotheses list is empty.";
return false;
}
size_t index = 0;
for (; index < hypotheses_list->GetSize(); ++index) {
Value* hypothesis = NULL;
if (!hypotheses_list->Get(index, &hypothesis)) {
LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value.";
break;
}
DCHECK(hypothesis);
if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) {
LOG(WARNING) << "ParseServerResponse: Unexpected value type "
<< hypothesis->GetType();
break;
}
const DictionaryValue* hypothesis_value =
static_cast<DictionaryValue*>(hypothesis);
string16 utterance;
if (!hypothesis_value->GetString(kUtteranceString, &utterance)) {
LOG(WARNING) << "ParseServerResponse: Missing utterance value.";
break;
}
// It is not an error if the 'confidence' field is missing.
double confidence = 0.0;
hypothesis_value->GetReal(kConfidenceString, &confidence);
result->push_back(speech_input::SpeechInputResultItem(utterance,
confidence));
}
if (index < hypotheses_list->GetSize()) {
result->clear();
return false;
}
return true;
}
} // namespace
namespace speech_input {
int SpeechRecognitionRequest::url_fetcher_id_for_tests = 0;
SpeechRecognitionRequest::SpeechRecognitionRequest(
URLRequestContextGetter* context, Delegate* delegate)
: url_context_(context),
delegate_(delegate) {
DCHECK(delegate);
}
SpeechRecognitionRequest::~SpeechRecognitionRequest() {}
bool SpeechRecognitionRequest::Send(const std::string& language,
const std::string& grammar,
const std::string& content_type,
const std::string& audio_data) {
DCHECK(!url_fetcher_.get());
std::vector<std::string> parts;
std::string lang_param = language;
if (lang_param.empty() && url_context_) {
// If no language is provided then we use the first from the accepted
// language list. If this list is empty then it defaults to "en-US".
// Example of the contents of this list: "es,en-GB;q=0.8", ""
URLRequestContext* request_context = url_context_->GetURLRequestContext();
DCHECK(request_context);
std::string accepted_language_list = request_context->accept_language();
size_t separator = accepted_language_list.find_first_of(",;");
lang_param = accepted_language_list.substr(0, separator);
}
if (lang_param.empty())
lang_param = "en-US";
parts.push_back("lang=" + EscapeQueryParamValue(lang_param, true));
if (!grammar.empty())
parts.push_back("grammar=" + EscapeQueryParamValue(grammar, true));
GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&'));
url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests,
url,
URLFetcher::POST,
this));
url_fetcher_->set_upload_data(content_type, audio_data);
url_fetcher_->set_request_context(url_context_);
// The speech recognition API does not require user identification as part
// of requests, so we don't send cookies or auth data for these requests to
// prevent any accidental connection between users who are logged into the
// domain for other services (e.g. bookmark sync) with the speech requests.
url_fetcher_->set_load_flags(
net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
return true;
}
void SpeechRecognitionRequest::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
DCHECK_EQ(url_fetcher_.get(), source);
bool error = !status.is_success() || response_code != 200;
SpeechInputResultArray result;
if (!error)
error = !ParseServerResponse(data, &result);
url_fetcher_.reset();
DVLOG(1) << "SpeechRecognitionRequest: Invoking delegate with result.";
delegate_->SetRecognitionResult(error, result);
}
} // namespace speech_input
<|endoftext|> |
<commit_before>/**
* @allknn_test.cc
* Test file for AllkNN class
*/
#include "allknn.h"
#include <fastlib/base/test.h>
#include <fastlib/fx/io.h>
#include <armadillo>
using namespace mlpack::allknn;
namespace mlpack {
namespace allknn {
class TestAllkNN {
public:
void Init() {
//allknn_ = new AllkNN();
//naive_ = new AllkNN();
if(data::Load("test_data_3_1000.csv", data_for_tree_) != SUCCESS_PASS) {
IO::PrintFatal("Unable to load test dataset.");
exit(1);
}
}
void Destruct() {
delete allknn_;
delete naive_;
}
void TestDualTreeVsNaive1() {
Init();
arma::mat dual_query(data_for_tree_);
arma::mat dual_references(data_for_tree_);
arma::mat naive_query(data_for_tree_);
arma::mat naive_references(data_for_tree_);
allknn_ = new AllkNN(dual_query, dual_references, 20, 5);
naive_ = new AllkNN(naive_query, naive_references, 1 /* leaf_size ignored */,
5, AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::PrintNotify("AllkNN test 1 passed.");
Destruct();
}
void TestDualTreeVsNaive2() {
arma::mat dual_query(data_for_tree_);
arma::mat naive_query(data_for_tree_);
allknn_ = new AllkNN(dual_query, 20, 1);
naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */,
1, AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::PrintNotify("AllkNN test 2 passed.");
Destruct();
}
void TestSingleTreeVsNaive() {
arma::mat single_query(data_for_tree_);
arma::mat naive_query(data_for_tree_);
allknn_ = new AllkNN(single_query, 20, 5, AllkNN::MODE_SINGLE);
naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 5,
AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::PrintNotify("AllkNN test 3 passed.");
Destruct();
}
void TestAll() {
TestDualTreeVsNaive1();
TestDualTreeVsNaive2();
TestSingleTreeVsNaive();
}
private:
AllkNN *allknn_;
AllkNN *naive_;
arma::mat data_for_tree_;
};
}; // namespace allknn
}; // namespace mlpack
int main(int argc, char* argv[]) {
mlpack::IO::ParseCommandLine(argc, argv);
TestAllkNN test;
test.TestAll();
}
<commit_msg>Adapt to new IO output API.<commit_after>/**
* @allknn_test.cc
* Test file for AllkNN class
*/
#include "allknn.h"
#include <fastlib/base/test.h>
#include <fastlib/fx/io.h>
#include <armadillo>
using namespace mlpack::allknn;
namespace mlpack {
namespace allknn {
class TestAllkNN {
public:
void Init() {
//allknn_ = new AllkNN();
//naive_ = new AllkNN();
if(data::Load("test_data_3_1000.csv", data_for_tree_) != SUCCESS_PASS) {
IO::Fatal << "Unable to load test dataset." << std::endl;
exit(1);
}
}
void Destruct() {
delete allknn_;
delete naive_;
}
void TestDualTreeVsNaive1() {
Init();
arma::mat dual_query(data_for_tree_);
arma::mat dual_references(data_for_tree_);
arma::mat naive_query(data_for_tree_);
arma::mat naive_references(data_for_tree_);
allknn_ = new AllkNN(dual_query, dual_references, 20, 5);
naive_ = new AllkNN(naive_query, naive_references, 1 /* leaf_size ignored
*/,
5, AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::Info << "AllkNN test 1 passed." << std::endl;
Destruct();
}
void TestDualTreeVsNaive2() {
arma::mat dual_query(data_for_tree_);
arma::mat naive_query(data_for_tree_);
allknn_ = new AllkNN(dual_query, 20, 1);
naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */,
1, AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::Info << "AllkNN test 2 passed." << std::endl;
Destruct();
}
void TestSingleTreeVsNaive() {
arma::mat single_query(data_for_tree_);
arma::mat naive_query(data_for_tree_);
allknn_ = new AllkNN(single_query, 20, 5, AllkNN::MODE_SINGLE);
naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 5,
AllkNN::NAIVE);
arma::Col<index_t> resulting_neighbors_tree;
arma::vec distances_tree;
allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree);
arma::Col<index_t> resulting_neighbors_naive;
arma::vec distances_naive;
naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive);
for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) {
TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]);
TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5);
}
IO::Info << "AllkNN test 3 passed." << std::endl;
Destruct();
}
void TestAll() {
TestDualTreeVsNaive1();
TestDualTreeVsNaive2();
TestSingleTreeVsNaive();
}
private:
AllkNN *allknn_;
AllkNN *naive_;
arma::mat data_for_tree_;
};
}; // namespace allknn
}; // namespace mlpack
int main(int argc, char* argv[]) {
mlpack::IO::ParseCommandLine(argc, argv);
TestAllkNN test;
test.TestAll();
}
<|endoftext|> |
<commit_before>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CMetab.cpp,v $
$Revision: 1.75 $
$Name: $
$Author: ssahle $
$Date: 2005/03/17 10:13:43 $
End CVS Header */
#include <iostream>
#include <string>
#include <vector>
#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CCompartment.h"
#include "CModel.h"
#include "CMetab.h"
#include "CMetabNameInterface.h"
//static
const CCompartment * CMetab::mpParentCompartment = NULL;
//static
const std::string CMetab::StatusName[] =
{"fixed", "independent", "dependent", "unused", ""};
//static
const char * CMetab::XMLStatus[] =
{"fixed", "variable", "variable", "variable", NULL};
//static
void CMetab::setParentCompartment(const CCompartment * parentCompartment)
{mpParentCompartment = parentCompartment;}
CMetab::CMetab(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Metabolite",
CCopasiObject::Container |
CCopasiObject::ValueDbl |
CCopasiObject::NonUniqueName),
mKey(GlobalKeys.add("Metabolite", this)),
mConc(1.0),
mIConc(1.0),
mNumber(1.0),
mINumber(1.0),
mRate(0.0),
mTT(0.0),
mStatus(METAB_VARIABLE),
mpCompartment(NULL),
mpModel(NULL)
{
if (getObjectParent())
{
initModel();
initCompartment(NULL);
}
else
{
mpCompartment = NULL;
}
initObjects();
CONSTRUCTOR_TRACE;
}
CMetab::CMetab(const CMetab & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(GlobalKeys.add("Metabolite", this)),
mConc(src.mConc),
mIConc(src.mIConc),
mNumber(src.mNumber),
mINumber(src.mINumber),
mRate(src.mRate),
mTT(src.mTT),
mStatus(src.mStatus),
mpCompartment(NULL),
mpModel(NULL)
{
initModel();
initCompartment(src.mpCompartment);
initObjects();
CONSTRUCTOR_TRACE;
}
CMetab &CMetab::operator=(const CMetabOld &RHS)
{
setObjectName(RHS.getObjectName());
setInitialConcentration(RHS.mIConc);
setConcentration(RHS.mIConc);
mRate = 0.0;
mTT = 0.0;
mStatus = RHS.mStatus;
return *this; // Assignment operator returns left side.
}
CMetab::~CMetab()
{
GlobalKeys.remove(mKey);
DESTRUCTOR_TRACE;
}
void CMetab::cleanup() {}
void CMetab::initModel()
{
mpModel = dynamic_cast< CModel * >(getObjectAncestor("Model"));
if (!mpModel && CCopasiDataModel::Global) mpModel = CCopasiDataModel::Global->getModel();
}
void CMetab::initCompartment(const CCompartment * pCompartment)
{
mpCompartment = (const CCompartment *) getObjectAncestor("Compartment");
if (!mpCompartment) mpCompartment = pCompartment;
if (!mpCompartment) mpCompartment = mpParentCompartment;
}
const std::string & CMetab::getKey() const {return mKey;}
const C_FLOAT64 & CMetab::getConcentration() const {return mConc;}
const C_FLOAT64 & CMetab::getNumber() const {return mNumber;}
const C_FLOAT64 & CMetab::getInitialConcentration() const {return mIConc;}
const C_FLOAT64 & CMetab::getInitialNumber() const {return mINumber;}
const CMetab::Status & CMetab::getStatus() const {return mStatus;}
const CCompartment * CMetab::getCompartment() const {return mpCompartment;}
const CModel * CMetab::getModel() const {return mpModel;}
void CMetab::setTransitionTime(const C_FLOAT64 & transitionTime)
{mTT = transitionTime;}
const C_FLOAT64 & CMetab::getTransitionTime() const {return mTT;}
bool CMetab::setObjectParent(const CCopasiContainer * pParent)
{
CCopasiObject::setObjectParent(pParent);
initCompartment(NULL);
initModel();
return true;
}
// ***** set quantities ********
void CMetab::setConcentration(const C_FLOAT64 concentration)
{
mConc = concentration;
mNumber = concentration * mpCompartment->getVolume()
* mpModel->getQuantity2NumberFactor();
#ifdef COPASI_DEBUG
if (mStatus == METAB_FIXED)
std::cout << "warning: set the transient concentration on a fixed metab" << std::endl;
#endif
}
void CMetab::setInitialConcentration(const C_FLOAT64 initialConcentration)
{
mIConc = initialConcentration;
mINumber = initialConcentration * mpCompartment->getVolume()
* mpModel->getQuantity2NumberFactor();
if (mStatus == METAB_FIXED)
setConcentration(initialConcentration);
if (mpModel)
const_cast<CModel*>(mpModel)->updateMoietyValues();
}
void CMetab::setNumber(const C_FLOAT64 number)
{
mConc = number * mpCompartment->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
mNumber = number;
#ifdef COPASI_DEBUG
if (mStatus == METAB_FIXED)
std::cout << "warning: set the transient particle number on a fixed metab" << std::endl;
#endif
}
void CMetab::setInitialNumber(const C_FLOAT64 initialNumber)
{
mIConc = initialNumber * mpCompartment->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
mINumber = initialNumber;
if (mStatus == METAB_FIXED)
setNumber(initialNumber);
if (mpModel)
const_cast<CModel*>(mpModel)->updateMoietyValues();
}
// ******************
void CMetab::setStatus(const CMetab::Status & status)
{
mStatus = status;
if (mStatus == METAB_FIXED)
{
if (mpCompartment)
setNumber(getInitialNumber());
}
}
//void CMetab::setCompartment(const CCompartment * compartment)
//{mpCompartment = compartment;}
//void CMetab::setModel(CModel * model) {mpModel = model;}
void CMetab::initObjects()
{
addObjectReference("Concentration", mConc, CCopasiObject::ValueDbl);
addObjectReference("InitialConcentration", mIConc, CCopasiObject::ValueDbl);
addObjectReference("ParticleNumber", mNumber, CCopasiObject::ValueDbl);
addObjectReference("InitialParticleNumber", mINumber, CCopasiObject::ValueDbl);
addObjectReference("TransitionTime", mTT, CCopasiObject::ValueDbl);
}
// non-member
/*bool operator<(const CMetab &lhs, const CMetab &rhs)
{
// Do the comparison based on the name
if (lhs.getObjectName() < rhs.getObjectName())
{
return true;
}
else
{
return false;
}
}*/
/**
* Return rate of production of this metaboLite
*/
const C_FLOAT64 & CMetab::getConcentrationRate() const
{
return mRate;
}
C_FLOAT64 CMetab::getNumberRate() const
{
return mRate * getCompartment()->getVolume()
* mpModel->getQuantity2NumberFactor();
}
void CMetab::setNumberRate(const C_FLOAT64 & rate)
{
//converts particles/time to concentration/time
mRate = rate * getCompartment()->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
}
void CMetab::setConcentrationRate(const C_FLOAT64 & rate)
{mRate = rate;}
void * CMetab::getReference() const
{return const_cast<C_FLOAT64 *>(&mConc);}
std::ostream & operator<<(std::ostream &os, const CMetab & d)
{
os << " ++++CMetab: " << d.getObjectName() << std::endl;
os << " mConc " << d.mConc << " mIConc " << d.mIConc << std::endl;
os << " mNumber " << d.mNumber << " mINumber " << d.mINumber << std::endl;
os << " mRate " << d.mRate << " mTT " << d.mTT << " mStatus " << d.mStatus << std::endl;
if (d.mpCompartment)
os << " mpCompartment == " << d.mpCompartment << std::endl;
else
os << " mpCompartment == 0 " << std::endl;
if (d.mpModel)
os << " mpModel == " << d.mpModel << std::endl;
else
os << " mpModel == 0 " << std::endl;
os << " ----CMetab " << std::endl;
return os;
}
C_INT32 CMetab::load(CReadConfig &configbuffer)
{
C_INT32 Fail = 0;
std::string tmp;
Fail = configbuffer.getVariable("Metabolite", "string",
(void *) & tmp,
CReadConfig::SEARCH);
if (Fail)
return Fail;
setObjectName(tmp);
Fail = configbuffer.getVariable("InitialConcentration", "C_FLOAT64",
(void *) & mIConc);
setInitialConcentration(mIConc);
setConcentration(mIConc);
Fail = configbuffer.getVariable("Type", "C_INT16",
(void *) & mStatus);
if (Fail)
return Fail;
// sanity check
if ((mStatus < 0) || (mStatus > 7))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a non-existing type "
"for '%s'.\nReset to internal metabolite.",
getObjectName().c_str());
mStatus = CMetab::METAB_VARIABLE;
}
// sanity check
if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a negative concentration "
"for '%s'.\nReset to default.",
getObjectName().c_str());
mIConc = 1.0;
}
return Fail;
}
bool CMetab::setValueOfNamedReference(std::string name, C_FLOAT64 value)
{
bool updateMoities = false;
if (name == "InitialConcentration")
{
setInitialConcentration(value);
updateMoities = true;
}
else if (name == "InitialParticleNumber")
{
setInitialNumber(value);
updateMoities = true;
}
else if (name == "Concentration")
setConcentration(value);
else if (name == "ParticleNumber")
setNumber(value);
else
return CCopasiContainer::setValueOfNamedReference(name, value);
if (updateMoities)
{
/* We need to update the initial values for moieties */
CCopasiVectorN < CMoiety > & Moieties =
*const_cast< CCopasiVectorN < CMoiety > * >(&mpModel->getMoieties());
unsigned C_INT32 i, imax = Moieties.size();
for (i = 0; i < imax; i++)
Moieties[i]->setInitialValue();
}
return true;
}
std::string CMetab::getObjectDisplayName(bool regular, bool richtext) const
{
CModel* tmp = dynamic_cast<CModel*>(this->getObjectAncestor("Model"));
if (tmp)
{
return CMetabNameInterface::getDisplayName(tmp, *this);
}
return CCopasiObject::getObjectDisplayName(regular, richtext);
}
//******************* CMetabOld ***************************************************
CMetabOld::CMetabOld(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Old Metabolite"),
mIConc(1.0),
mStatus(CMetab::METAB_VARIABLE),
mCompartment()
{CONSTRUCTOR_TRACE;}
CMetabOld::CMetabOld(const CMetabOld & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mIConc(src.mIConc),
mStatus(src.mStatus),
mCompartment(src.mCompartment)
{CONSTRUCTOR_TRACE;}
CMetabOld::~CMetabOld() {DESTRUCTOR_TRACE;}
void CMetabOld::cleanup(){}
C_INT32 CMetabOld::load(CReadConfig &configbuffer)
{
C_INT32 Fail = 0;
std::string tmp;
Fail = configbuffer.getVariable("Metabolite", "string",
(void *) & tmp,
CReadConfig::SEARCH);
if (Fail)
return Fail;
setObjectName(tmp);
Fail = configbuffer.getVariable("Concentration", "C_FLOAT64",
(void *) & mIConc);
if (Fail)
return Fail;
Fail = configbuffer.getVariable("Compartment", "C_INT32",
(void *) & mCompartment);
if (Fail)
return Fail;
C_INT32 Status;
Fail = configbuffer.getVariable("Type", "C_INT32",
(void *) & Status);
mStatus = (CMetab::Status) Status;
// sanity check
if ((mStatus < 0) || (mStatus > 7))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a non-existing type "
"for '%s'.\nReset to internal metabolite.",
getObjectName().c_str());
mStatus = CMetab::METAB_VARIABLE;
}
// sanity check
if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a negative concentration "
"for '%s'.\nReset to default.",
getObjectName().c_str());
mIConc = 1.0;
}
return Fail;
}
C_INT32 CMetabOld::getIndex() const {return mCompartment;}
<commit_msg>Removed code in setValueOfNamedReference, which was made obsolete by Sven's enhancements od setIninitialConcentration and setIninitialNumber.<commit_after>/* Begin CVS Header
$Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CMetab.cpp,v $
$Revision: 1.76 $
$Name: $
$Author: shoops $
$Date: 2005/03/17 13:32:45 $
End CVS Header */
#include <iostream>
#include <string>
#include <vector>
#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/utility.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "CCompartment.h"
#include "CModel.h"
#include "CMetab.h"
#include "CMetabNameInterface.h"
//static
const CCompartment * CMetab::mpParentCompartment = NULL;
//static
const std::string CMetab::StatusName[] =
{"fixed", "independent", "dependent", "unused", ""};
//static
const char * CMetab::XMLStatus[] =
{"fixed", "variable", "variable", "variable", NULL};
//static
void CMetab::setParentCompartment(const CCompartment * parentCompartment)
{mpParentCompartment = parentCompartment;}
CMetab::CMetab(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Metabolite",
CCopasiObject::Container |
CCopasiObject::ValueDbl |
CCopasiObject::NonUniqueName),
mKey(GlobalKeys.add("Metabolite", this)),
mConc(1.0),
mIConc(1.0),
mNumber(1.0),
mINumber(1.0),
mRate(0.0),
mTT(0.0),
mStatus(METAB_VARIABLE),
mpCompartment(NULL),
mpModel(NULL)
{
if (getObjectParent())
{
initModel();
initCompartment(NULL);
}
else
{
mpCompartment = NULL;
}
initObjects();
CONSTRUCTOR_TRACE;
}
CMetab::CMetab(const CMetab & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mKey(GlobalKeys.add("Metabolite", this)),
mConc(src.mConc),
mIConc(src.mIConc),
mNumber(src.mNumber),
mINumber(src.mINumber),
mRate(src.mRate),
mTT(src.mTT),
mStatus(src.mStatus),
mpCompartment(NULL),
mpModel(NULL)
{
initModel();
initCompartment(src.mpCompartment);
initObjects();
CONSTRUCTOR_TRACE;
}
CMetab &CMetab::operator=(const CMetabOld &RHS)
{
setObjectName(RHS.getObjectName());
setInitialConcentration(RHS.mIConc);
setConcentration(RHS.mIConc);
mRate = 0.0;
mTT = 0.0;
mStatus = RHS.mStatus;
return *this; // Assignment operator returns left side.
}
CMetab::~CMetab()
{
GlobalKeys.remove(mKey);
DESTRUCTOR_TRACE;
}
void CMetab::cleanup() {}
void CMetab::initModel()
{
mpModel = dynamic_cast< CModel * >(getObjectAncestor("Model"));
if (!mpModel && CCopasiDataModel::Global) mpModel = CCopasiDataModel::Global->getModel();
}
void CMetab::initCompartment(const CCompartment * pCompartment)
{
mpCompartment = (const CCompartment *) getObjectAncestor("Compartment");
if (!mpCompartment) mpCompartment = pCompartment;
if (!mpCompartment) mpCompartment = mpParentCompartment;
}
const std::string & CMetab::getKey() const {return mKey;}
const C_FLOAT64 & CMetab::getConcentration() const {return mConc;}
const C_FLOAT64 & CMetab::getNumber() const {return mNumber;}
const C_FLOAT64 & CMetab::getInitialConcentration() const {return mIConc;}
const C_FLOAT64 & CMetab::getInitialNumber() const {return mINumber;}
const CMetab::Status & CMetab::getStatus() const {return mStatus;}
const CCompartment * CMetab::getCompartment() const {return mpCompartment;}
const CModel * CMetab::getModel() const {return mpModel;}
void CMetab::setTransitionTime(const C_FLOAT64 & transitionTime)
{mTT = transitionTime;}
const C_FLOAT64 & CMetab::getTransitionTime() const {return mTT;}
bool CMetab::setObjectParent(const CCopasiContainer * pParent)
{
CCopasiObject::setObjectParent(pParent);
initCompartment(NULL);
initModel();
return true;
}
// ***** set quantities ********
void CMetab::setConcentration(const C_FLOAT64 concentration)
{
mConc = concentration;
mNumber = concentration * mpCompartment->getVolume()
* mpModel->getQuantity2NumberFactor();
#ifdef COPASI_DEBUG
if (mStatus == METAB_FIXED)
std::cout << "warning: set the transient concentration on a fixed metab" << std::endl;
#endif
}
void CMetab::setInitialConcentration(const C_FLOAT64 initialConcentration)
{
mIConc = initialConcentration;
mINumber = initialConcentration * mpCompartment->getVolume()
* mpModel->getQuantity2NumberFactor();
if (mStatus == METAB_FIXED)
setConcentration(initialConcentration);
if (mpModel)
const_cast<CModel*>(mpModel)->updateMoietyValues();
}
void CMetab::setNumber(const C_FLOAT64 number)
{
mConc = number * mpCompartment->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
mNumber = number;
#ifdef COPASI_DEBUG
if (mStatus == METAB_FIXED)
std::cout << "warning: set the transient particle number on a fixed metab" << std::endl;
#endif
}
void CMetab::setInitialNumber(const C_FLOAT64 initialNumber)
{
mIConc = initialNumber * mpCompartment->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
mINumber = initialNumber;
if (mStatus == METAB_FIXED)
setNumber(initialNumber);
if (mpModel)
const_cast<CModel*>(mpModel)->updateMoietyValues();
}
// ******************
void CMetab::setStatus(const CMetab::Status & status)
{
mStatus = status;
if (mStatus == METAB_FIXED)
{
if (mpCompartment)
setNumber(getInitialNumber());
}
}
//void CMetab::setCompartment(const CCompartment * compartment)
//{mpCompartment = compartment;}
//void CMetab::setModel(CModel * model) {mpModel = model;}
void CMetab::initObjects()
{
addObjectReference("Concentration", mConc, CCopasiObject::ValueDbl);
addObjectReference("InitialConcentration", mIConc, CCopasiObject::ValueDbl);
addObjectReference("ParticleNumber", mNumber, CCopasiObject::ValueDbl);
addObjectReference("InitialParticleNumber", mINumber, CCopasiObject::ValueDbl);
addObjectReference("TransitionTime", mTT, CCopasiObject::ValueDbl);
}
// non-member
/*bool operator<(const CMetab &lhs, const CMetab &rhs)
{
// Do the comparison based on the name
if (lhs.getObjectName() < rhs.getObjectName())
{
return true;
}
else
{
return false;
}
}*/
/**
* Return rate of production of this metaboLite
*/
const C_FLOAT64 & CMetab::getConcentrationRate() const
{
return mRate;
}
C_FLOAT64 CMetab::getNumberRate() const
{
return mRate * getCompartment()->getVolume()
* mpModel->getQuantity2NumberFactor();
}
void CMetab::setNumberRate(const C_FLOAT64 & rate)
{
//converts particles/time to concentration/time
mRate = rate * getCompartment()->getVolumeInv()
* mpModel->getNumber2QuantityFactor();
}
void CMetab::setConcentrationRate(const C_FLOAT64 & rate)
{mRate = rate;}
void * CMetab::getReference() const
{return const_cast<C_FLOAT64 *>(&mConc);}
std::ostream & operator<<(std::ostream &os, const CMetab & d)
{
os << " ++++CMetab: " << d.getObjectName() << std::endl;
os << " mConc " << d.mConc << " mIConc " << d.mIConc << std::endl;
os << " mNumber " << d.mNumber << " mINumber " << d.mINumber << std::endl;
os << " mRate " << d.mRate << " mTT " << d.mTT << " mStatus " << d.mStatus << std::endl;
if (d.mpCompartment)
os << " mpCompartment == " << d.mpCompartment << std::endl;
else
os << " mpCompartment == 0 " << std::endl;
if (d.mpModel)
os << " mpModel == " << d.mpModel << std::endl;
else
os << " mpModel == 0 " << std::endl;
os << " ----CMetab " << std::endl;
return os;
}
C_INT32 CMetab::load(CReadConfig &configbuffer)
{
C_INT32 Fail = 0;
std::string tmp;
Fail = configbuffer.getVariable("Metabolite", "string",
(void *) & tmp,
CReadConfig::SEARCH);
if (Fail)
return Fail;
setObjectName(tmp);
Fail = configbuffer.getVariable("InitialConcentration", "C_FLOAT64",
(void *) & mIConc);
setInitialConcentration(mIConc);
setConcentration(mIConc);
Fail = configbuffer.getVariable("Type", "C_INT16",
(void *) & mStatus);
if (Fail)
return Fail;
// sanity check
if ((mStatus < 0) || (mStatus > 7))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a non-existing type "
"for '%s'.\nReset to internal metabolite.",
getObjectName().c_str());
mStatus = CMetab::METAB_VARIABLE;
}
// sanity check
if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a negative concentration "
"for '%s'.\nReset to default.",
getObjectName().c_str());
mIConc = 1.0;
}
return Fail;
}
bool CMetab::setValueOfNamedReference(std::string name, C_FLOAT64 value)
{
bool updateMoities = false;
if (name == "InitialConcentration")
setInitialConcentration(value);
else if (name == "InitialParticleNumber")
setInitialNumber(value);
else if (name == "Concentration")
setConcentration(value);
else if (name == "ParticleNumber")
setNumber(value);
else
return CCopasiContainer::setValueOfNamedReference(name, value);
return true;
}
std::string CMetab::getObjectDisplayName(bool regular, bool richtext) const
{
CModel* tmp = dynamic_cast<CModel*>(this->getObjectAncestor("Model"));
if (tmp)
{
return CMetabNameInterface::getDisplayName(tmp, *this);
}
return CCopasiObject::getObjectDisplayName(regular, richtext);
}
//******************* CMetabOld ***************************************************
CMetabOld::CMetabOld(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "Old Metabolite"),
mIConc(1.0),
mStatus(CMetab::METAB_VARIABLE),
mCompartment()
{CONSTRUCTOR_TRACE;}
CMetabOld::CMetabOld(const CMetabOld & src,
const CCopasiContainer * pParent):
CCopasiContainer(src, pParent),
mIConc(src.mIConc),
mStatus(src.mStatus),
mCompartment(src.mCompartment)
{CONSTRUCTOR_TRACE;}
CMetabOld::~CMetabOld() {DESTRUCTOR_TRACE;}
void CMetabOld::cleanup(){}
C_INT32 CMetabOld::load(CReadConfig &configbuffer)
{
C_INT32 Fail = 0;
std::string tmp;
Fail = configbuffer.getVariable("Metabolite", "string",
(void *) & tmp,
CReadConfig::SEARCH);
if (Fail)
return Fail;
setObjectName(tmp);
Fail = configbuffer.getVariable("Concentration", "C_FLOAT64",
(void *) & mIConc);
if (Fail)
return Fail;
Fail = configbuffer.getVariable("Compartment", "C_INT32",
(void *) & mCompartment);
if (Fail)
return Fail;
C_INT32 Status;
Fail = configbuffer.getVariable("Type", "C_INT32",
(void *) & Status);
mStatus = (CMetab::Status) Status;
// sanity check
if ((mStatus < 0) || (mStatus > 7))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a non-existing type "
"for '%s'.\nReset to internal metabolite.",
getObjectName().c_str());
mStatus = CMetab::METAB_VARIABLE;
}
// sanity check
if ((mStatus != METAB_MOIETY) && (mIConc < 0.0))
{
CCopasiMessage(CCopasiMessage::WARNING,
"The file specifies a negative concentration "
"for '%s'.\nReset to default.",
getObjectName().c_str());
mIConc = 1.0;
}
return Fail;
}
C_INT32 CMetabOld::getIndex() const {return mCompartment;}
<|endoftext|> |
<commit_before>// CSate.cpp
//
// (C) Stefan Hoops 2002
//
#include <typeinfo>
#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CState.h"
#include "CModel.h"
#include "CCompartment.h"
#include "utilities/CGlobals.h"
CState::CState(const CModel * model) :
mModel(model),
mVolumesSize(0),
mVolumes(NULL),
mNumbersSize(0),
mNumbersUpdated(0),
mNumbersInt(NULL),
mNumbersDbl(NULL)
{
if (mModel)
{
mVolumesSize = mModel->getCompartments().size();
mNumbersSize = mModel->getTotMetab();
mNumbersUpdated = mModel->getIntMetab();
mVolumes = new C_FLOAT64[mVolumesSize];
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
}
}
CState::CState(const CState & src) :
mModel(src.mModel),
mVolumesSize(src.mVolumesSize),
mVolumes(NULL),
mNumbersSize(src.mNumbersSize),
mNumbersUpdated(src.mNumbersUpdated),
mNumbersInt(NULL),
mNumbersDbl(NULL)
{
unsigned C_INT32 i;
if (mVolumesSize)
{
mVolumes = new C_FLOAT64[mVolumesSize];
for (i = 0; i < mVolumesSize; i++)
{
*(mVolumes + i) = *(src.mVolumes + i);
}
}
if (mNumbersSize)
{
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
for (i = 0; i < mNumbersSize; i++)
{
*(mNumbersInt + i) = *(src.mNumbersInt + i);
*(mNumbersDbl + i) = *(src.mNumbersDbl + i);
}
}
}
CState::~CState()
{
pdelete (mVolumes);
pdelete (mNumbersInt);
pdelete (mNumbersDbl);
}
void CState::setModel(const CModel * model)
{
pdelete (mVolumes);
pdelete (mNumbersInt);
pdelete (mNumbersDbl);
mModel = model;
if (mModel)
{
mVolumesSize = mModel->getCompartments().size();
mNumbersSize = mModel->getTotMetab();
mNumbersUpdated = mModel->getIntMetab();
mVolumes = new C_FLOAT64[mVolumesSize];
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
}
}
const unsigned C_INT32 & CState::getNumbersSize() const { return mNumbersSize; }
const unsigned C_INT32 & CState::getNumbersUpdated() const
{ return mNumbersUpdated; }
const unsigned C_INT32 & CState::getVolumesSize() const { return mVolumesSize; }
CState * CState::load(CReadConfig & configBuffer)
{
CState * pState = NULL;
string Tmp;
C_INT32 Size;
unsigned C_INT32 i;
configBuffer.getVariable("StateType", "string", &Tmp);
if (Tmp == "Full Model")
pState = new CState();
else if (Tmp == "Reduced Model")
pState = new CStateX();
else
fatalError();
configBuffer.getVariable("StateModel", "string", &Tmp);
if (Tmp == Copasi->Model->getTitle())
pState->mModel = Copasi->Model;
else
fatalError();
configBuffer.getVariable("StateTime", "C_FLOAT64", &pState->mTime);
configBuffer.getVariable("StateVolumesSize", "C_INT32", &Size);
pState->mVolumesSize = Size;
for (i = 0; i < pState->mVolumesSize; i++)
{
Tmp = StringPrint("StateVolumes[%d]", i);
configBuffer.getVariable("Tmp", "C_FLOAT64", & pState->mVolumes[i]);
}
configBuffer.getVariable("StateNumberdSize", "C_INT32", &Size);
pState->mNumbersSize = Size;
configBuffer.getVariable("StateNumberdUpdated", "C_INT32", &Size);
pState->mNumbersUpdated = Size;
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersInt[%d]", i);
configBuffer.getVariable("Tmp", "C_INT32", & pState->mNumbersInt[i]);
}
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersDbl[%d]", i);
configBuffer.getVariable("Tmp", "C_FLOAT64", & pState->mNumbersDbl[i]);
}
return pState;
}
void CState::save(CWriteConfig & configBuffer, const CState * pState)
{
string Tmp;
C_INT32 Size;
unsigned C_INT32 i;
if (typeid(*pState) == typeid(CState))
Tmp == "Full Model";
else if (typeid(*pState) == typeid(CStateX))
Tmp == "Reduced Model";
else
fatalError();
Tmp = pState->mModel->getTitle();
configBuffer.setVariable("StateModel", "string", &Tmp);
configBuffer.setVariable("StateType", "string", &Tmp);
configBuffer.setVariable("StateTime", "C_FLOAT64", &pState->mTime);
Size = pState->mVolumesSize;
configBuffer.setVariable("StateVolumesSize", "C_INT32", &Size);
for (i = 0; i < pState->mVolumesSize; i++)
{
Tmp = StringPrint("StateVolumes[%d]", i);
configBuffer.setVariable("Tmp", "C_FLOAT64", & pState->mVolumes[i]);
}
Size = pState->mNumbersSize;
configBuffer.setVariable("StateNumberdSize", "C_INT32", &Size);
Size = pState->mNumbersUpdated;
configBuffer.setVariable("StateNumberdUpdated", "C_INT32", &Size);
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersInt[%d]", i);
configBuffer.setVariable("Tmp", "C_INT32", & pState->mNumbersInt[i]);
}
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersDbl[%d]", i);
configBuffer.setVariable("Tmp", "C_FLOAT64", & pState->mNumbersDbl[i]);
}
return ;
}
CStateX::CStateX(const CModel * model) : CState(model)
{
if (model)
mNumbersUpdated = model->getIndMetab();
}
CStateX::CStateX(const CStateX & src) : CState(src) {}
CStateX::~CStateX() {}
void CStateX::setModel(const CModel * model)
{
CState::setModel(model);
mModel = model;
mNumbersUpdated = model->getIndMetab();
}
<commit_msg>Fixed problems in load() and save() method<commit_after>// CSate.cpp
//
// (C) Stefan Hoops 2002
//
#include <typeinfo>
#define COPASI_TRACE_CONSTRUCTION
#include "copasi.h"
#include "CState.h"
#include "CModel.h"
#include "CCompartment.h"
#include "utilities/CGlobals.h"
CState::CState(const CModel * model) :
mModel(model),
mVolumesSize(0),
mVolumes(NULL),
mNumbersSize(0),
mNumbersUpdated(0),
mNumbersInt(NULL),
mNumbersDbl(NULL)
{
if (mModel)
{
mVolumesSize = mModel->getCompartments().size();
mNumbersSize = mModel->getTotMetab();
mNumbersUpdated = mModel->getIntMetab();
mVolumes = new C_FLOAT64[mVolumesSize];
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
}
}
CState::CState(const CState & src) :
mModel(src.mModel),
mVolumesSize(src.mVolumesSize),
mVolumes(NULL),
mNumbersSize(src.mNumbersSize),
mNumbersUpdated(src.mNumbersUpdated),
mNumbersInt(NULL),
mNumbersDbl(NULL)
{
unsigned C_INT32 i;
if (mVolumesSize)
{
mVolumes = new C_FLOAT64[mVolumesSize];
for (i = 0; i < mVolumesSize; i++)
{
*(mVolumes + i) = *(src.mVolumes + i);
}
}
if (mNumbersSize)
{
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
for (i = 0; i < mNumbersSize; i++)
{
*(mNumbersInt + i) = *(src.mNumbersInt + i);
*(mNumbersDbl + i) = *(src.mNumbersDbl + i);
}
}
}
CState::~CState()
{
pdelete (mVolumes);
pdelete (mNumbersInt);
pdelete (mNumbersDbl);
}
void CState::setTime(const double & time)
{mTime = time; }
const double & CState::getTime() const
{ return mTime; }
void CState::setModel(const CModel * model)
{
pdelete (mVolumes);
pdelete (mNumbersInt);
pdelete (mNumbersDbl);
mModel = model;
if (mModel)
{
mVolumesSize = mModel->getCompartments().size();
mNumbersSize = mModel->getTotMetab();
mNumbersUpdated = mModel->getIntMetab();
mVolumes = new C_FLOAT64[mVolumesSize];
mNumbersInt = new C_INT32[mNumbersSize];
mNumbersDbl = new C_FLOAT64[mNumbersSize];
}
}
const unsigned C_INT32 & CState::getNumbersSize() const { return mNumbersSize; }
const unsigned C_INT32 & CState::getNumbersUpdated() const
{ return mNumbersUpdated; }
const unsigned C_INT32 & CState::getVolumesSize() const { return mVolumesSize; }
CState * CState::load(CReadConfig & configBuffer)
{
CState * pState = NULL;
string Tmp;
C_INT32 Size;
unsigned C_INT32 i;
configBuffer.getVariable("StateType", "string", &Tmp);
if (Tmp == "Full Model")
pState = new CState();
else if (Tmp == "Reduced Model")
pState = new CStateX();
else
fatalError();
configBuffer.getVariable("StateModel", "string", &Tmp);
if (Tmp == Copasi->Model->getTitle())
pState->mModel = Copasi->Model;
else
fatalError();
configBuffer.getVariable("StateTime", "C_FLOAT64", &pState->mTime);
configBuffer.getVariable("StateVolumesSize", "C_INT32", &Size);
pState->mVolumesSize = Size;
for (i = 0; i < pState->mVolumesSize; i++)
{
Tmp = StringPrint("StateVolumes[%d]", i);
configBuffer.getVariable(Tmp, "C_FLOAT64", & pState->mVolumes[i]);
}
configBuffer.getVariable("StateNumberSize", "C_INT32", &Size);
pState->mNumbersSize = Size;
configBuffer.getVariable("StateNumberUpdated", "C_INT32", &Size);
pState->mNumbersUpdated = Size;
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersInt[%d]", i);
configBuffer.getVariable(Tmp, "C_INT32", & pState->mNumbersInt[i]);
}
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersDbl[%d]", i);
configBuffer.getVariable(Tmp, "C_FLOAT64", & pState->mNumbersDbl[i]);
}
return pState;
}
void CState::save(CWriteConfig & configBuffer, const CState * pState)
{
string Tmp;
C_INT32 Size;
unsigned C_INT32 i;
Tmp = pState->mModel->getTitle();
configBuffer.setVariable("StateModel", "string", &Tmp);
if (typeid(*pState) == typeid(CState))
Tmp == "Full Model";
else if (typeid(*pState) == typeid(CStateX))
Tmp == "Reduced Model";
else
fatalError();
configBuffer.setVariable("StateType", "string", &Tmp);
configBuffer.setVariable("StateTime", "C_FLOAT64", &pState->mTime);
Size = pState->mVolumesSize;
configBuffer.setVariable("StateVolumesSize", "C_INT32", &Size);
for (i = 0; i < pState->mVolumesSize; i++)
{
Tmp = StringPrint("StateVolumes[%d]", i);
configBuffer.setVariable(Tmp, "C_FLOAT64", & pState->mVolumes[i]);
}
Size = pState->mNumbersSize;
configBuffer.setVariable("StateNumberSize", "C_INT32", &Size);
Size = pState->mNumbersUpdated;
configBuffer.setVariable("StateNumberUpdated", "C_INT32", &Size);
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersInt[%d]", i);
configBuffer.setVariable(Tmp, "C_INT32", & pState->mNumbersInt[i]);
}
for (i = 0; i < pState->mNumbersSize; i++)
{
Tmp = StringPrint("StateNumbersDbl[%d]", i);
configBuffer.setVariable(Tmp, "C_FLOAT64", & pState->mNumbersDbl[i]);
}
return;
}
CStateX::CStateX(const CModel * model) : CState(model)
{
if (model)
mNumbersUpdated = model->getIndMetab();
}
CStateX::CStateX(const CStateX & src) : CState(src) {}
CStateX::~CStateX() {}
void CStateX::setModel(const CModel * model)
{
CState::setModel(model);
mModel = model;
mNumbersUpdated = model->getIndMetab();
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "httprequest_service.h"
#include "service_manager.h"
#include "main/memory_stream.h"
#include "curl/curl.h"
#ifdef __EMSCRIPTEN__
extern "C"
{
extern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char* param, const char* additionalHeader, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);
}
#endif
static char errorBuffer[CURL_ERROR_SIZE];
const char * HTTP_REQUEST_SERVICE_QUEUE = "HTTPRequestServiceQueue";
HTTPRequestService::HTTPRequestService(const ServiceManager * manager)
: Service(manager)
, _curl(NULL)
, _taskQueueService(NULL)
{
}
HTTPRequestService::~HTTPRequestService()
{
}
bool HTTPRequestService::onInit()
{
_taskQueueService = _manager->findService<TaskQueueService>();
_taskQueueService->createQueue(HTTP_REQUEST_SERVICE_QUEUE);
#ifndef __EMSCRIPTEN__
_curl = curl_easy_init();
if (_curl)
{
curl_easy_setopt(_curl, CURLOPT_USERAGENT, gameplay::Game::getInstance()->getUserAgentString());
//curl_easy_setopt( _curl, CURLOPT_DNS_CACHE_TIMEOUT, -1 );
curl_easy_setopt(_curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(_curl, CURLOPT_TIMEOUT, 20);
curl_easy_setopt(_curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_easy_setopt(_curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(_curl, CURLOPT_TCP_NODELAY, 1); // make sure packets are sent immediately
curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, &writeFunction);
curl_easy_setopt(_curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, 0);
}
#endif
return true;
}
bool HTTPRequestService::onTick()
{
// service has no work to do every frame
return true;
}
bool HTTPRequestService::onShutdown()
{
if (_taskQueueService)
_taskQueueService->removeQueue(HTTP_REQUEST_SERVICE_QUEUE);
#ifndef __EMSCRIPTEN__
if (_curl)
curl_easy_cleanup(_curl);
#endif
return true;
}
int HTTPRequestService::makeRequestAsync(const Request& request, bool headOnly)
{
// note: request is copied by value
return _taskQueueService->addWorkItem(HTTP_REQUEST_SERVICE_QUEUE, std::bind(&HTTPRequestService::sendRequest, this, request, headOnly));
}
void HTTPRequestService::makeRequestSync(const Request& request, bool headOnly)
{
sendRequest(request, headOnly);
}
void HTTPRequestService::requestLoadCallback(unsigned, void * arg, void *buf, unsigned length)
{
Request * request = reinterpret_cast<Request *>(arg);
request->responseCallback(CURLE_OK, MemoryStream::create(buf, length), NULL, 200);
delete request;
}
void HTTPRequestService::requestErrorCallback(unsigned, void *arg, int errorCode, const char * status)
{
Request * request = reinterpret_cast<Request *>(arg);
GP_LOG("Failed to perform HTTP request to %s: error %d %s", request->url.c_str(), errorCode, status);
request->responseCallback(errorCode, NULL, status, errorCode);
delete request;
}
int progressFunction(void * userp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
{
HTTPRequestService::Request * request = reinterpret_cast<HTTPRequestService::Request *>(userp);
GP_ASSERT(request->progressCallback);
return request->progressCallback(static_cast<uint64_t>(dltotal), static_cast<uint64_t>(dlnow), static_cast<uint64_t>(ultotal), static_cast<uint64_t>(ulnow));
}
void HTTPRequestService::sendRequest(const Request& request, bool headOnly)
{
// make sure curl is used only for one thread in any moment
std::unique_lock<std::mutex> lock(_requestProcessingMutex);
#ifndef __EMSCRIPTEN__
MemoryStream * response = MemoryStream::create();
curl_easy_setopt(_curl, CURLOPT_URL, request.url.c_str());
curl_easy_setopt(_curl, CURLOPT_POSTFIELDS, request.postPayload.c_str());
curl_easy_setopt(_curl, CURLOPT_POST, request.postPayload.empty() ? 0 : 1);
curl_easy_setopt(_curl, CURLOPT_WRITEDATA, response);
curl_easy_setopt(_curl, CURLOPT_NOPROGRESS, request.progressCallback ? 0 : 1);
curl_easy_setopt(_curl, CURLOPT_XFERINFOFUNCTION, &progressFunction);
curl_easy_setopt(_curl, CURLOPT_XFERINFODATA, &request);
curl_easy_setopt(_curl, CURLOPT_HEADER, headOnly ? 1 : 0);
curl_easy_setopt(_curl, CURLOPT_NOBODY, headOnly ? 1 : 0);
struct curl_slist *list = NULL;
if (!request.headers.empty())
{
for (auto& h : request.headers)
list = curl_slist_append(list, (h.first + ": " + h.second).c_str());
}
curl_easy_setopt(_curl, CURLOPT_HTTPHEADER, list);
CURLcode res = curl_easy_perform(_curl);
curl_slist_free_all(list);
long httpResponseCode = 0;
curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &httpResponseCode);
if (res != CURLE_OK)
GP_LOG("Failed to perform HTTP request: error %d - %s", res, request.url.c_str());
// response is copied by value since callback is invoked on main thread
_taskQueueService->runOnMainThread(std::bind(request.responseCallback, res, response, curl_easy_strerror(res), httpResponseCode));
#else
std::string additionalHeaders; // headers in JSON format
if (!request.headers.empty())
{
additionalHeaders += "{";
for (auto& h : request.headers)
{
additionalHeaders += "\"";
additionalHeaders += h.first;
additionalHeaders += "\":\"";
additionalHeaders += h.second;
additionalHeaders += "\",";
}
additionalHeaders.pop_back();
additionalHeaders += "}";
}
Request * newRequest = new Request(request);
emscripten_async_wget3_data(request.url.c_str(), request.postPayload.empty() ? "GET" : "POST", request.postPayload.c_str(),
additionalHeaders.c_str(), newRequest, true, &HTTPRequestService::requestLoadCallback, &HTTPRequestService::requestErrorCallback, NULL);
#endif
}
size_t HTTPRequestService::writeFunction(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realSize = size * nmemb;
gameplay::Stream * response = reinterpret_cast<gameplay::Stream *>(userp);
response->write(contents, size, nmemb);
return realSize;
}
const char * HTTPRequestService::getTaskQueueName() const
{
return HTTP_REQUEST_SERVICE_QUEUE;
}<commit_msg>automatic deletion of response stream when it's no longer needed<commit_after>#include "pch.h"
#include "httprequest_service.h"
#include "service_manager.h"
#include "main/memory_stream.h"
#include "curl/curl.h"
#ifdef __EMSCRIPTEN__
extern "C"
{
extern int emscripten_async_wget3_data(const char* url, const char* requesttype, const char* param, const char* additionalHeader, void *arg, int free, em_async_wget2_data_onload_func onload, em_async_wget2_data_onerror_func onerror, em_async_wget2_data_onprogress_func onprogress);
}
#endif
static char errorBuffer[CURL_ERROR_SIZE];
const char * HTTP_REQUEST_SERVICE_QUEUE = "HTTPRequestServiceQueue";
HTTPRequestService::HTTPRequestService(const ServiceManager * manager)
: Service(manager)
, _curl(NULL)
, _taskQueueService(NULL)
{
}
HTTPRequestService::~HTTPRequestService()
{
}
bool HTTPRequestService::onInit()
{
_taskQueueService = _manager->findService<TaskQueueService>();
_taskQueueService->createQueue(HTTP_REQUEST_SERVICE_QUEUE);
#ifndef __EMSCRIPTEN__
_curl = curl_easy_init();
if (_curl)
{
curl_easy_setopt(_curl, CURLOPT_USERAGENT, gameplay::Game::getInstance()->getUserAgentString());
//curl_easy_setopt( _curl, CURLOPT_DNS_CACHE_TIMEOUT, -1 );
curl_easy_setopt(_curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(_curl, CURLOPT_TIMEOUT, 20);
curl_easy_setopt(_curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_easy_setopt(_curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(_curl, CURLOPT_TCP_NODELAY, 1); // make sure packets are sent immediately
curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, &writeFunction);
curl_easy_setopt(_curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, 0);
}
#endif
return true;
}
bool HTTPRequestService::onTick()
{
// service has no work to do every frame
return true;
}
bool HTTPRequestService::onShutdown()
{
if (_taskQueueService)
_taskQueueService->removeQueue(HTTP_REQUEST_SERVICE_QUEUE);
#ifndef __EMSCRIPTEN__
if (_curl)
curl_easy_cleanup(_curl);
#endif
return true;
}
int HTTPRequestService::makeRequestAsync(const Request& request, bool headOnly)
{
// note: request is copied by value
return _taskQueueService->addWorkItem(HTTP_REQUEST_SERVICE_QUEUE, std::bind(&HTTPRequestService::sendRequest, this, request, headOnly));
}
void HTTPRequestService::makeRequestSync(const Request& request, bool headOnly)
{
sendRequest(request, headOnly);
}
void HTTPRequestService::requestLoadCallback(unsigned, void * arg, void *buf, unsigned length)
{
Request * request = reinterpret_cast<Request *>(arg);
request->responseCallback(CURLE_OK, MemoryStream::create(buf, length), NULL, 200);
delete request;
}
void HTTPRequestService::requestErrorCallback(unsigned, void *arg, int errorCode, const char * status)
{
Request * request = reinterpret_cast<Request *>(arg);
GP_LOG("Failed to perform HTTP request to %s: error %d %s", request->url.c_str(), errorCode, status);
request->responseCallback(errorCode, NULL, status, errorCode);
delete request;
}
int progressFunction(void * userp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
{
HTTPRequestService::Request * request = reinterpret_cast<HTTPRequestService::Request *>(userp);
GP_ASSERT(request->progressCallback);
return request->progressCallback(static_cast<uint64_t>(dltotal), static_cast<uint64_t>(dlnow), static_cast<uint64_t>(ultotal), static_cast<uint64_t>(ulnow));
}
void HTTPRequestService::sendRequest(const Request& request, bool headOnly)
{
// make sure curl is used only for one thread in any moment
std::unique_lock<std::mutex> lock(_requestProcessingMutex);
#ifndef __EMSCRIPTEN__
MemoryStream * response = MemoryStream::create();
curl_easy_setopt(_curl, CURLOPT_URL, request.url.c_str());
curl_easy_setopt(_curl, CURLOPT_POSTFIELDS, request.postPayload.c_str());
curl_easy_setopt(_curl, CURLOPT_POST, request.postPayload.empty() ? 0 : 1);
curl_easy_setopt(_curl, CURLOPT_WRITEDATA, response);
curl_easy_setopt(_curl, CURLOPT_NOPROGRESS, request.progressCallback ? 0 : 1);
curl_easy_setopt(_curl, CURLOPT_XFERINFOFUNCTION, &progressFunction);
curl_easy_setopt(_curl, CURLOPT_XFERINFODATA, &request);
curl_easy_setopt(_curl, CURLOPT_HEADER, headOnly ? 1 : 0);
curl_easy_setopt(_curl, CURLOPT_NOBODY, headOnly ? 1 : 0);
struct curl_slist *list = NULL;
if (!request.headers.empty())
{
for (auto& h : request.headers)
list = curl_slist_append(list, (h.first + ": " + h.second).c_str());
}
curl_easy_setopt(_curl, CURLOPT_HTTPHEADER, list);
CURLcode res = curl_easy_perform(_curl);
curl_slist_free_all(list);
long httpResponseCode = 0;
curl_easy_getinfo(_curl, CURLINFO_RESPONSE_CODE, &httpResponseCode);
if (res != CURLE_OK)
GP_LOG("Failed to perform HTTP request: error %d - %s", res, request.url.c_str());
// response is copied by value since callback is invoked on main thread
_taskQueueService->runOnMainThread([=]() { request.responseCallback(res, response, curl_easy_strerror(res), httpResponseCode); delete response; });
#else
std::string additionalHeaders; // headers in JSON format
if (!request.headers.empty())
{
additionalHeaders += "{";
for (auto& h : request.headers)
{
additionalHeaders += "\"";
additionalHeaders += h.first;
additionalHeaders += "\":\"";
additionalHeaders += h.second;
additionalHeaders += "\",";
}
additionalHeaders.pop_back();
additionalHeaders += "}";
}
Request * newRequest = new Request(request);
emscripten_async_wget3_data(request.url.c_str(), request.postPayload.empty() ? "GET" : "POST", request.postPayload.c_str(),
additionalHeaders.c_str(), newRequest, true, &HTTPRequestService::requestLoadCallback, &HTTPRequestService::requestErrorCallback, NULL);
#endif
}
size_t HTTPRequestService::writeFunction(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realSize = size * nmemb;
gameplay::Stream * response = reinterpret_cast<gameplay::Stream *>(userp);
response->write(contents, size, nmemb);
return realSize;
}
const char * HTTPRequestService::getTaskQueueName() const
{
return HTTP_REQUEST_SERVICE_QUEUE;
}<|endoftext|> |
<commit_before>#include <diagnostic_msgs/DiagnosticArray.h>
#include <diagnostic_msgs/DiagnosticStatus.h>
#include <errno.h> // Error number definitions
#include <fcntl.h> // File control definitions
#include <motor_controller/ignition_control.h>
#include <motor_controller/speed.h>
#include <motor_controller/speed_steering.h>
#include <motor_controller/steering.h>
#include <robot_state/robot_state.h>
#include <robot_state/robot_state_constants.h>
#include <ros/console.h>
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Vector3.h>
#include <speech_engine/speech_request.h>
#include <std_msgs/Bool.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h> // time calls
#include <unistd.h> // UNIX standard function definitions
#include <iostream>
using namespace std;
const int JoyLinearAxisPositive = 1; // X
const int JoyLinearAxisNegative = 3; // Throttle
const int JoyRotationAxis = 0; // Y
const float MaximumSteeringAngle = 30.0f;
/// <summary>
/// Maximum forward travel speed in meters per second.
/// </summary>
const float MaximumSpeed = 100.0f;
class JoystickControllerCls {
public:
JoystickControllerCls();
private:
void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);
void joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag);
void Stop();
ros::NodeHandle nh_;
ros::Publisher motors_pub_;
ros::Subscriber joy_sub_;
ros::Subscriber joy_diag_sub_;
ros::Publisher speech_pub_;
};
void JoystickControllerCls::joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag)
{
if (diag->status.size() > 0)
{
if (diag->status[0].level != 0)
{
ROS_WARN("Joystick disconnected");
Stop();
}
//joy_ok = (diag->status[0].level == 0);
}
}
void JoystickControllerCls::Stop() {
geometry_msgs::Vector3 motors_message;
motors_message.x = 0;
motors_message.y = 0;
motors_message.z = 0;
motors_pub_.publish(motors_message);
ROS_INFO("Left: %d, Right %d", 0, 0);
}
JoystickControllerCls::JoystickControllerCls() {
speech_pub_ = nh_.advertise<speech_engine::speech_request>(
"speech_engine/speech_request", 1);
joy_sub_ = nh_.subscribe<sensor_msgs::Joy>(
"joy", 3, &JoystickControllerCls::joyCallback, this);
joy_diag_sub_ = nh_.subscribe<diagnostic_msgs::DiagnosticArray>(
"diagnostics", 3, &JoystickControllerCls::joyDiagCallback, this);
motors_pub_ = nh_.advertise<geometry_msgs::Vector3>("motors", 1);
}
void JoystickControllerCls::joyCallback(const sensor_msgs::Joy::ConstPtr& joy) {
float steering = joy->axes[JoyRotationAxis];
ROS_INFO("steering: %f", steering);
float steering_degree = steering * MaximumSteeringAngle;
float positive_speed = joy->axes[JoyLinearAxisPositive];
//ROS_INFO("positive_speed: %f", positive_speed);
float negative_speed = joy->axes[JoyLinearAxisNegative];
// Map from [1,-1] to [0,1]
negative_speed = -negative_speed;
ROS_INFO("negative_speed: %f", negative_speed);
int speed = MaximumSpeed*(positive_speed - negative_speed);
//ROS_INFO("speed: %f", speed);
geometry_msgs::Vector3 motors_message;
motors_message.x = speed;
motors_message.y = speed;
motors_message.z = 0;
motors_pub_.publish(motors_message);
ROS_INFO("Left: %d, Right %d", (int)motors_message.x, (int)motors_message.y);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "JoystickController");
JoystickControllerCls joystick_controller;
ros::spin();
}
<commit_msg>Joystick controller with turning.<commit_after>#include <diagnostic_msgs/DiagnosticArray.h>
#include <diagnostic_msgs/DiagnosticStatus.h>
#include <errno.h> // Error number definitions
#include <fcntl.h> // File control definitions
#include <geometry_msgs/Vector3.h>
#include <motor_controller/ignition_control.h>
#include <motor_controller/speed.h>
#include <motor_controller/speed_steering.h>
#include <motor_controller/steering.h>
#include <robot_state/robot_state.h>
#include <robot_state/robot_state_constants.h>
#include <ros/console.h>
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <speech_engine/speech_request.h>
#include <std_msgs/Bool.h>
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <termios.h> // POSIX terminal control definitions
#include <time.h> // time calls
#include <unistd.h> // UNIX standard function definitions
#include <iostream>
using namespace std;
const int JoyLinearAxisPositive = 1; // X
const int JoyLinearAxisNegative = 3; // Throttle
const int JoyRotationAxis = 0; // Y
const float MaximumSteeringAngle = 80.0f;
/// <summary>
/// Maximum forward travel speed where 255 is max motor speed ~4m/s.
/// </summary>
const float MaximumSpeed = 100.0f;
/// <summary>
/// Turning speed where 255 is max motor speed ~4m/s.
/// </summary>
const float TurningSpeed = 60.0f;
class JoystickControllerCls {
public:
JoystickControllerCls();
private:
void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);
void joyDiagCallback(const diagnostic_msgs::DiagnosticArray::ConstPtr& diag);
void Stop();
ros::NodeHandle nh_;
ros::Publisher motors_pub_;
ros::Subscriber joy_sub_;
ros::Subscriber joy_diag_sub_;
ros::Publisher speech_pub_;
};
void JoystickControllerCls::joyDiagCallback(
const diagnostic_msgs::DiagnosticArray::ConstPtr& diag) {
if (diag->status.size() > 0) {
if (diag->status[0].level != 0) {
ROS_WARN("Joystick disconnected");
Stop();
}
// joy_ok = (diag->status[0].level == 0);
}
}
void JoystickControllerCls::Stop() {
geometry_msgs::Vector3 motors_message;
motors_message.x = 0;
motors_message.y = 0;
motors_message.z = 0;
motors_pub_.publish(motors_message);
ROS_INFO("Left: %d, Right %d", 0, 0);
}
JoystickControllerCls::JoystickControllerCls() {
speech_pub_ = nh_.advertise<speech_engine::speech_request>(
"speech_engine/speech_request", 1);
joy_sub_ = nh_.subscribe<sensor_msgs::Joy>(
"joy", 3, &JoystickControllerCls::joyCallback, this);
joy_diag_sub_ = nh_.subscribe<diagnostic_msgs::DiagnosticArray>(
"diagnostics", 3, &JoystickControllerCls::joyDiagCallback, this);
motors_pub_ = nh_.advertise<geometry_msgs::Vector3>("motors", 1);
}
float DegreeToRadian(float degree) { return degree / 57.295779524f; }
void JoystickControllerCls::joyCallback(const sensor_msgs::Joy::ConstPtr& joy) {
float steering = joy->axes[JoyRotationAxis];
ROS_INFO("steering: %f", steering);
float steering_degree = steering * MaximumSteeringAngle;
float positive_speed = 0;//joy->axes[JoyLinearAxisPositive];
// ROS_INFO("positive_speed: %f", positive_speed);
float negative_speed = joy->axes[JoyLinearAxisNegative];
// Map from [1,-1] to [0,1]
negative_speed = -negative_speed;
int speed = MaximumSpeed * (positive_speed - negative_speed);
// ROS_INFO("speed: %f", speed);
geometry_msgs::Vector3 motors_message;
float steering_radian = DegreeToRadian(steering_degree);
motors_message.x = -sin(steering_radian) * TurningSpeed + speed;
motors_message.y = sin(steering_radian) * TurningSpeed + speed;
motors_message.z = 0;
motors_pub_.publish(motors_message);
ROS_INFO("Left: %d, Right %d", (int)motors_message.x, (int)motors_message.y);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "JoystickController");
JoystickControllerCls joystick_controller;
ros::spin();
}
<|endoftext|> |
<commit_before>#include "ex14_27_28_StrBlob.h"
#include <algorithm>
//==================================================================
//
// StrBlob - operators
//
//==================================================================
bool operator==(const StrBlob &lhs, const StrBlob &rhs)
{
return *lhs.data == *rhs.data;
}
bool operator!=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(lhs == rhs);
}
bool operator< (const StrBlob &lhs, const StrBlob &rhs)
{
return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end());
}
bool operator> (const StrBlob &lhs, const StrBlob &rhs)
{
return rhs < lhs;
}
bool operator<=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(lhs < rhs);
}
//================================================================
//
// StrBlobPtr - operators
//
//================================================================
bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs)
{
return !(lhs == rhs);
}
bool operator< (const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr < y.curr;
}
bool operator> (const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr > y.curr;
}
bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr <= y.curr;
}
bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr >= y.curr;
}
//================================================================
//
// ConstStrBlobPtr - operators
//
//================================================================
bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return !(lhs == rhs);
}
bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr < rhs.curr;
}
bool operator> (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr > rhs.curr;
}
bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr <= rhs.curr;
}
bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr >= rhs.curr;
}
//==================================================================
//
// copy assignment operator and move assignment operator.
//
//==================================================================
StrBlob& StrBlob::operator=(const StrBlob &lhs)
{
data = make_shared<vector<string>>(*lhs.data);
return *this;
}
StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT
{
if (this != &rhs) {
data = std::move(rhs.data);
rhs.data = nullptr;
}
return *this;
}
//==================================================================
//
// members
//
//==================================================================
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
ConstStrBlobPtr StrBlob::cbegin() const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::cend() const
{
return ConstStrBlobPtr(*this, data->size());
}
<commit_msg>Update ex14_27_28_StrBlob.cpp<commit_after>#include "ex14_27_28_StrBlob.h"
#include <algorithm>
//==================================================================
//
// StrBlob - operators
//
//==================================================================
bool operator==(const StrBlob &lhs, const StrBlob &rhs)
{
return *lhs.data == *rhs.data;
}
bool operator!=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(lhs == rhs);
}
bool operator< (const StrBlob &lhs, const StrBlob &rhs)
{
return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end());
}
bool operator> (const StrBlob &lhs, const StrBlob &rhs)
{
return rhs < lhs;
}
bool operator<=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrBlob &lhs, const StrBlob &rhs)
{
return !(lhs < rhs);
}
//================================================================
//
// StrBlobPtr - operators
//
//================================================================
bool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs)
{
return !(lhs == rhs);
}
bool operator< (const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr < y.curr;
}
bool operator>(const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr > y.curr;
}
bool operator<=(const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr <= y.curr;
}
bool operator>=(const StrBlobPtr &x, const StrBlobPtr &y)
{
return x.curr >= y.curr;
}
//================================================================
//
// ConstStrBlobPtr - operators
//
//================================================================
bool operator==(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return !(lhs == rhs);
}
bool operator< (const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr < rhs.curr;
}
bool operator>(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr > rhs.curr;
}
bool operator<=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr <= rhs.curr;
}
bool operator>=(const ConstStrBlobPtr &lhs, const ConstStrBlobPtr &rhs)
{
return lhs.curr >= rhs.curr;
}
//==================================================================
//
// copy assignment operator and move assignment operator.
//
//==================================================================
StrBlob& StrBlob::operator=(const StrBlob &lhs)
{
data = make_shared<vector<string>>(*lhs.data);
return *this;
}
StrBlob& StrBlob::operator=(StrBlob &&rhs) NOEXCEPT
{
if (this != &rhs) {
data = std::move(rhs.data);
rhs.data = nullptr;
}
return *this;
}
//==================================================================
//
// members
//
//==================================================================
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
ConstStrBlobPtr StrBlob::cbegin() const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::cend() const
{
return ConstStrBlobPtr(*this, data->size());
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQuadraturePointStatistics.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 "vtkQuadraturePointStatistics.h"
#include "vtkUnstructuredGrid.h"
#include "vtkTable.h"
#include "vtkType.h"
#include "vtkDoubleArray.h"
#include "vtkStringArray.h"
#include "vtkDataArray.h"
#include "vtkPointData.h"
#include "vtkFieldData.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkTableWriter.h"
#include "vtksys/ios/sstream"
using vtksys_ios::ostringstream;
#include "vtkstd/vector"
using vtkstd::vector;
#include "vtkstd/string"
using vtkstd::string;
#include "vtkQuadraturePointsUtilities.hxx"
//*****************************************************************************
void ComputeScalarStatistics(
vtkDoubleArray *input,
string name,
vector<vtkDoubleArray*> &stats)
{
const int nAtts=3;
stats.clear();
stats.push_back(vtkDoubleArray::New());
stats[0]->SetName(name.c_str());
stats[0]->SetNumberOfTuples(nAtts);
vtkIdType nTups=input->GetNumberOfTuples();
double *pV=input->GetPointer(0);
// initialize.
double min=pV[0];
double max=pV[0];
double mean=pV[0];
++pV;
// rest.
for (vtkIdType i=1; i<nTups; ++i)
{
mean+=pV[0];
min=pV[0]<min?pV[0]:min;
max=pV[0]>max?pV[0]:max;
++pV;
}
mean/=nTups;
stats[0]->SetValue(0,min);
stats[0]->SetValue(1,max);
stats[0]->SetValue(2,mean);
}
//*****************************************************************************
void ComputeVectorStatistics(
vtkDoubleArray *input,
string name,
vector<vtkDoubleArray*> &stats)
{
const int nAtts=3;
int nComps=input->GetNumberOfComponents();
vtkIdType nTups=input->GetNumberOfTuples();
double *pV=input->GetPointer(0);
double mod=sqrt(pV[0]*pV[0]+pV[1]*pV[1]+pV[2]*pV[2]);
double min[4]={mod,pV[0],pV[1],pV[2]};
double max[4]={mod,pV[0],pV[1],pV[2]};
double mean[4]={mod,pV[0],pV[1],pV[2]};
pV+=nComps;
for (vtkIdType i=1; i<nTups; ++i)
{
mod=sqrt(pV[0]*pV[0]+pV[1]*pV[1]+pV[2]*pV[2]);
//
min[0]=mod<min[0]?mod:min[0];
min[1]=pV[0]<min[1]?pV[0]:min[1];
min[2]=pV[1]<min[2]?pV[1]:min[2];
min[3]=pV[2]<min[3]?pV[2]:min[3];
//
max[0]=mod>max[0]?mod:max[0];
max[1]=pV[0]>max[1]?pV[0]:max[1];
max[2]=pV[1]>max[2]?pV[1]:max[2];
max[3]=pV[2]>max[3]?pV[2]:max[3];
//
mean[0]+=mod;
mean[1]+=pV[0];
mean[2]+=pV[1];
mean[3]+=pV[2];
pV+=nComps;
}
mean[0]/=nTups;
mean[1]/=nTups;
mean[2]/=nTups;
mean[3]/=nTups;
// add 4 arrays, 1 for the L2 norm, 3 for the comps.
stats.clear();
stats.resize(4);
//
ostringstream compM;
compM << "|" << name << "|";
stats[0]=vtkDoubleArray::New();
stats[0]->SetName(compM.str().c_str());
stats[0]->SetNumberOfTuples(nAtts);
stats[0]->SetValue(0,min[0]);
stats[0]->SetValue(1,max[0]);
stats[0]->SetValue(2,mean[0]);
//
ostringstream compX;
compX << name << "_X";
stats[1]=vtkDoubleArray::New();
stats[1]->SetName(compX.str().c_str());
stats[1]->SetNumberOfTuples(nAtts);
stats[1]->SetValue(0,min[1]);
stats[1]->SetValue(1,max[1]);
stats[1]->SetValue(2,mean[1]);
//
ostringstream compY;
compY << name << "_Y";
stats[2]=vtkDoubleArray::New();
stats[2]->SetName(compY.str().c_str());
stats[2]->SetNumberOfTuples(nAtts);
stats[2]->SetValue(0,min[2]);
stats[2]->SetValue(1,max[2]);
stats[2]->SetValue(2,mean[2]);
//
ostringstream compZ;
compZ << name << "_Z";
stats[3]=vtkDoubleArray::New();
stats[3]->SetName(compZ.str().c_str());
stats[3]->SetNumberOfTuples(nAtts);
stats[3]->SetValue(0,min[3]);
stats[3]->SetValue(1,max[3]);
stats[3]->SetValue(2,mean[3]);
}
vtkCxxRevisionMacro(vtkQuadraturePointStatistics, "1.2");
vtkStandardNewMacro(vtkQuadraturePointStatistics);
//-----------------------------------------------------------------------------
vtkQuadraturePointStatistics::vtkQuadraturePointStatistics()
{
this->Clear();
this->SetNumberOfInputPorts(1);
this->SetNumberOfOutputPorts(1);
}
//-----------------------------------------------------------------------------
vtkQuadraturePointStatistics::~vtkQuadraturePointStatistics()
{
this->Clear();
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::FillInputPortInformation(
int port,
vtkInformation *info)
{
switch (port)
{
case 0:
info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid");
break;
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::FillOutputPortInformation(
int port,
vtkInformation *info)
{
switch (port)
{
case 0:
info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkTable");
break;
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::RequestData(
vtkInformation *,
vtkInformationVector **input,
vtkInformationVector *output)
{
vtkDataObject *tmpDataObj;
// Get the inputs
tmpDataObj
= input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT());
vtkUnstructuredGrid *usgIn
= vtkUnstructuredGrid::SafeDownCast(tmpDataObj);
// Get the outputs
tmpDataObj
= output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT());
vtkTable *tabOut
= vtkTable::SafeDownCast(tmpDataObj);
// Quick sanity check.
if (usgIn==NULL || tabOut==NULL
|| usgIn->GetNumberOfCells()==0
|| usgIn->GetNumberOfPoints()==0
|| usgIn->GetPointData()->GetNumberOfArrays()==0)
{
vtkWarningMacro("Filter data has not been configured correctly. Aborting.");
return 1;
}
// Interpolate the data arrays, but no points. Results
// are stored in field data arrays.
this->ComputeStatistics(usgIn,tabOut);
return 1;
}
//-----------------------------------------------------------------------------
void vtkQuadraturePointStatistics::Clear()
{
// Nothing to do
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::ComputeStatistics(
vtkUnstructuredGrid *usgIn,
vtkTable *results)
{
// Each valid array on the input, produces one column for each of
// its components on the output.
vector<vector<vtkDoubleArray *> >columns;
// Look at the arrays in FieldData for fields interpolated to
// quadrature points.
int nArrays
= usgIn->GetPointData()->GetNumberOfArrays();
for (int arrayId=0; arrayId<nArrays; ++arrayId)
{
// Proccess it only if we have floating point data.
vtkDataArray *V=usgIn->GetPointData()->GetArray(arrayId);
int V_type=V->GetDataType();
if (! ((V_type==VTK_FLOAT)||(V_type==VTK_DOUBLE)))
{
continue;
}
vtkDataArray *tmpDa;
// Get the array with the interpolated values.
ostringstream interpolatedName;
interpolatedName << V->GetName() << "_QP_Interpolated";
tmpDa=usgIn->GetFieldData()->GetArray(interpolatedName.str().c_str());
vtkDoubleArray *interpolated=vtkDoubleArray::SafeDownCast(tmpDa);
// Not found, try next array.
if (!interpolated)
{
// cerr << "Skipping: " << V->GetName() << endl;
continue;
}
// Process arrays, by the number of components they
// have, because we want to name stuff like V_X,V_Y,V_Z
// If there are more than three components we'll have to do
// something else.
vector<vtkDoubleArray *> comps;
int nComps=interpolated->GetNumberOfComponents();
switch (nComps)
{
case 1:
ComputeScalarStatistics(interpolated,V->GetName(),comps);
break;
case 3:
ComputeVectorStatistics(interpolated,V->GetName(),comps);
break;
default:
vtkWarningMacro("Unsupported number of components.");
break;
}
// Gather the columns, they are added to the table when all input
// arrays have been processed.
columns.push_back(comps);
}
// Add the processed columns to the table.
if (columns.size())
{
vtkStringArray *rowLabels=vtkStringArray::New();
rowLabels->SetName(" ");
rowLabels->SetNumberOfTuples(3);
rowLabels->SetValue(0,"min");
rowLabels->SetValue(1,"max");
rowLabels->SetValue(2,"mean");
results->AddColumn(rowLabels);
rowLabels->Delete();
size_t nCols=columns.size();
for (size_t colId=0; colId<nCols; ++colId)
{
size_t nSubCols=columns[colId].size();
for (size_t subColId=0; subColId<nSubCols; ++subColId)
{
results->AddColumn(columns[colId][subColId]);
//cerr << "Adding " << columns[colId][subColId]->GetName() << " to table." << endl;
columns[colId][subColId]->Delete();
}
}
}
results->GetFieldData()->Initialize();
return static_cast<int>(columns.size());
}
//-----------------------------------------------------------------------------
void vtkQuadraturePointStatistics::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "No state." << endl;
}
<commit_msg><commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQuadraturePointStatistics.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 "vtkQuadraturePointStatistics.h"
#include "vtkUnstructuredGrid.h"
#include "vtkTable.h"
#include "vtkType.h"
#include "vtkDoubleArray.h"
#include "vtkStringArray.h"
#include "vtkDataArray.h"
#include "vtkPointData.h"
#include "vtkFieldData.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkTableWriter.h"
#include "vtksys/ios/sstream"
using vtksys_ios::ostringstream;
#include "vtkstd/vector"
using vtkstd::vector;
#include "vtkstd/string"
using vtkstd::string;
#include "vtkQuadraturePointsUtilities.hxx"
//*****************************************************************************
void ComputeScalarStatistics(
vtkDoubleArray *input,
string name,
vector<vtkDoubleArray*> &stats)
{
const int nAtts=3;
vtkDoubleArray *column=vtkDoubleArray::New();
column->SetName(name.c_str());
column->SetNumberOfTuples(nAtts);
vtkIdType nTups=input->GetNumberOfTuples();
double *pV=input->GetPointer(0);
// initialize.
double min=pV[0];
double max=pV[0];
double mean=pV[0];
++pV;
// rest.
for (vtkIdType i=1; i<nTups; ++i)
{
mean+=pV[0];
min=pV[0]<min?pV[0]:min;
max=pV[0]>max?pV[0]:max;
++pV;
}
mean/=nTups;
column->SetValue(0,min);
column->SetValue(1,max);
column->SetValue(2,mean);
stats.push_back(column);
}
//*****************************************************************************
void ComputeVectorStatistics(
vtkDoubleArray *input,
string name,
vector<vtkDoubleArray*> &stats)
{
const int nAtts=3;
int nComps=input->GetNumberOfComponents();
vtkIdType nTups=input->GetNumberOfTuples();
double *pV=input->GetPointer(0);
double mod=sqrt(pV[0]*pV[0]+pV[1]*pV[1]+pV[2]*pV[2]);
double min[4]={mod,pV[0],pV[1],pV[2]};
double max[4]={mod,pV[0],pV[1],pV[2]};
double mean[4]={mod,pV[0],pV[1],pV[2]};
pV+=nComps;
for (vtkIdType i=1; i<nTups; ++i)
{
mod=sqrt(pV[0]*pV[0]+pV[1]*pV[1]+pV[2]*pV[2]);
//
min[0]=mod<min[0]?mod:min[0];
min[1]=pV[0]<min[1]?pV[0]:min[1];
min[2]=pV[1]<min[2]?pV[1]:min[2];
min[3]=pV[2]<min[3]?pV[2]:min[3];
//
max[0]=mod>max[0]?mod:max[0];
max[1]=pV[0]>max[1]?pV[0]:max[1];
max[2]=pV[1]>max[2]?pV[1]:max[2];
max[3]=pV[2]>max[3]?pV[2]:max[3];
//
mean[0]+=mod;
mean[1]+=pV[0];
mean[2]+=pV[1];
mean[3]+=pV[2];
pV+=nComps;
}
mean[0]/=nTups;
mean[1]/=nTups;
mean[2]/=nTups;
mean[3]/=nTups;
// add 4 arrays, 1 for the L2 norm, 3 for the comps.
vtkDoubleArray *column;
ostringstream compM;
compM << "|" << name << "|";
column=vtkDoubleArray::New();
column->SetName(compM.str().c_str());
column->SetNumberOfTuples(nAtts);
column->SetValue(0,min[0]);
column->SetValue(1,max[0]);
column->SetValue(2,mean[0]);
stats.push_back(column);
//
ostringstream compX;
compX << name << "_X";
column=vtkDoubleArray::New();
column->SetName(compX.str().c_str());
column->SetNumberOfTuples(nAtts);
column->SetValue(0,min[1]);
column->SetValue(1,max[1]);
column->SetValue(2,mean[1]);
stats.push_back(column);
//
ostringstream compY;
compY << name << "_Y";
column=vtkDoubleArray::New();
column->SetName(compY.str().c_str());
column->SetNumberOfTuples(nAtts);
column->SetValue(0,min[2]);
column->SetValue(1,max[2]);
column->SetValue(2,mean[2]);
stats.push_back(column);
//
ostringstream compZ;
compZ << name << "_Z";
column=vtkDoubleArray::New();
column->SetName(compZ.str().c_str());
column->SetNumberOfTuples(nAtts);
column->SetValue(0,min[3]);
column->SetValue(1,max[3]);
column->SetValue(2,mean[3]);
stats.push_back(column);
}
vtkCxxRevisionMacro(vtkQuadraturePointStatistics, "1.3");
vtkStandardNewMacro(vtkQuadraturePointStatistics);
//-----------------------------------------------------------------------------
vtkQuadraturePointStatistics::vtkQuadraturePointStatistics()
{
this->Clear();
this->SetNumberOfInputPorts(1);
this->SetNumberOfOutputPorts(1);
}
//-----------------------------------------------------------------------------
vtkQuadraturePointStatistics::~vtkQuadraturePointStatistics()
{
this->Clear();
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::FillInputPortInformation(
int port,
vtkInformation *info)
{
switch (port)
{
case 0:
info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid");
break;
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::FillOutputPortInformation(
int port,
vtkInformation *info)
{
switch (port)
{
case 0:
info->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkTable");
break;
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::RequestData(
vtkInformation *,
vtkInformationVector **input,
vtkInformationVector *output)
{
vtkDataObject *tmpDataObj;
// Get the inputs
tmpDataObj
= input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT());
vtkUnstructuredGrid *usgIn
= vtkUnstructuredGrid::SafeDownCast(tmpDataObj);
// Get the outputs
tmpDataObj
= output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT());
vtkTable *tabOut
= vtkTable::SafeDownCast(tmpDataObj);
// Quick sanity check.
if (usgIn==NULL || tabOut==NULL
|| usgIn->GetNumberOfCells()==0
|| usgIn->GetNumberOfPoints()==0
|| usgIn->GetPointData()->GetNumberOfArrays()==0)
{
vtkWarningMacro("Filter data has not been configured correctly. Aborting.");
return 1;
}
// Interpolate the data arrays, but no points. Results
// are stored in field data arrays.
this->ComputeStatistics(usgIn,tabOut);
return 1;
}
//-----------------------------------------------------------------------------
void vtkQuadraturePointStatistics::Clear()
{
// Nothing to do
}
//-----------------------------------------------------------------------------
int vtkQuadraturePointStatistics::ComputeStatistics(
vtkUnstructuredGrid *usgIn,
vtkTable *results)
{
// Each valid array on the input, produces one column for each of
// its components on the output.
vector<vtkDoubleArray *> columns;
// Look at the arrays in FieldData for fields interpolated to
// quadrature points.
int nArrays
= usgIn->GetPointData()->GetNumberOfArrays();
for (int arrayId=0; arrayId<nArrays; ++arrayId)
{
// Proccess it only if we have floating point data.
vtkDataArray *V=usgIn->GetPointData()->GetArray(arrayId);
int V_type=V->GetDataType();
if (! ((V_type==VTK_FLOAT)||(V_type==VTK_DOUBLE)))
{
continue;
}
vtkDataArray *tmpDa;
// Get the array with the interpolated values.
ostringstream interpolatedName;
interpolatedName << V->GetName() << "_QP_Interpolated";
tmpDa=usgIn->GetFieldData()->GetArray(interpolatedName.str().c_str());
vtkDoubleArray *interpolated=vtkDoubleArray::SafeDownCast(tmpDa);
// Not found, try next array.
if (!interpolated)
{
// cerr << "Skipping: " << V->GetName() << endl;
continue;
}
// Process arrays, by the number of components they
// have, because we want to name stuff like V_X,V_Y,V_Z
// If there are more than three components we'll have to do
// something else.
int nComps=interpolated->GetNumberOfComponents();
switch (nComps)
{
case 1:
ComputeScalarStatistics(interpolated,V->GetName(),columns);
break;
case 3:
ComputeVectorStatistics(interpolated,V->GetName(),columns);
break;
default:
vtkWarningMacro("Unsupported number of components.");
break;
}
}
// Add the processed columns to the table.
if (columns.size())
{
vtkStringArray *rowLabels=vtkStringArray::New();
rowLabels->SetName(" ");
rowLabels->SetNumberOfTuples(3);
rowLabels->SetValue(0,"min");
rowLabels->SetValue(1,"max");
rowLabels->SetValue(2,"mean");
results->AddColumn(rowLabels);
rowLabels->Delete();
size_t nCols=columns.size();
for (size_t colId=0; colId<nCols; ++colId)
{
results->AddColumn(columns[colId]);
//cerr << "Adding " << columns[colId]->GetName() << " to table." << endl;
columns[colId]->Delete();
}
}
// Clean out garbage that is added by default.
results->GetFieldData()->Initialize();
return static_cast<int>(columns.size());
}
//-----------------------------------------------------------------------------
void vtkQuadraturePointStatistics::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "No state." << endl;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Markus Fasel *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTEMCALSTURawDigitMaker.h"
#include "AliCaloConstants.h"
#include "AliCaloRawAnalyzerFactory.h"
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloRawStreamV3.h"
#include "AliDAQ.h"
#include "AliEMCALTriggerSTUDCSConfig.h"
#include "AliEMCALTriggerData.h"
#include "AliEMCALTriggerRawDigit.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALGeometry.h"
#include "AliRawEquipmentHeader.h"
#include "AliRawEvent.h"
#include "AliRawReader.h"
#include "AliRawVEquipment.h"
ClassImp(AliHLTEMCALSTURawDigitMaker)
AliHLTEMCALSTURawDigitMaker::AliHLTEMCALSTURawDigitMaker() :
TObject(),
AliHLTLogging(),
fkGeometryPtr(NULL),
fDCSConfigSTU(NULL),
fTriggerData(NULL),
fNRawDigits(0)
{
fDCSConfigSTU = new AliEMCALTriggerSTUDCSConfig;
fTriggerData = new AliEMCALTriggerData;
for (Int_t i=0; i<fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
}
AliHLTEMCALSTURawDigitMaker::~AliHLTEMCALSTURawDigitMaker() {
if(fDCSConfigSTU) delete fDCSConfigSTU;
if(fTriggerData) delete fTriggerData;
}
void AliHLTEMCALSTURawDigitMaker::ProcessSTUStream(AliEMCALTriggerSTURawStream *stustream, Int_t detector){
HLTDebug("Start post processing the raw digit maker");
Int_t idx;
AliHLTCaloTriggerRawDigitDataStruct *hltdig(NULL);
if (stustream && stustream->ReadPayLoad()) {
fTriggerData->SetL1DataDecoded(1);
for (int i = 0; i < 2; i++) {
fTriggerData->SetL1GammaThreshold(i, stustream->GetL1GammaThreshold(i));
fTriggerData->SetL1JetThreshold( i, stustream->GetL1JetThreshold(i) );
}
Int_t v0[2] = { static_cast<Int_t>(stustream->GetV0A()), static_cast<Int_t>(stustream->GetV0C())};
// Modify DCS config from STU payload content
for(Int_t i = 0; i < 3; i++){
for(Int_t j = 0; j < 2; j++){
fDCSConfigSTU->SetG(i, j, stustream->GetG(i, j));
fDCSConfigSTU->SetJ(i, j, stustream->GetJ(i, j));
}
}
fDCSConfigSTU->SetRawData(stustream->GetRawData());
fDCSConfigSTU->SetRegion(stustream->GetRegionEnable());
fDCSConfigSTU->SetFw(stustream->GetFwVersion());
fTriggerData->SetL1FrameMask(stustream->GetFrameReceived());
fTriggerData->SetL1V0(v0);
Int_t type[15] =
{
static_cast<Int_t>(stustream->GetG(0, 0)),
static_cast<Int_t>(stustream->GetG(1, 0)),
static_cast<Int_t>(stustream->GetG(2, 0)),
static_cast<Int_t>(stustream->GetJ(0, 0)),
static_cast<Int_t>(stustream->GetJ(1, 0)),
static_cast<Int_t>(stustream->GetJ(2, 0)),
static_cast<Int_t>(stustream->GetG(0, 1)),
static_cast<Int_t>(stustream->GetG(1, 1)),
static_cast<Int_t>(stustream->GetG(2, 1)),
static_cast<Int_t>(stustream->GetJ(0, 1)),
static_cast<Int_t>(stustream->GetJ(1, 1)),
static_cast<Int_t>(stustream->GetJ(2, 1)),
static_cast<Int_t>(stustream->GetRawData()),
static_cast<Int_t>(stustream->GetRegionEnable()),
static_cast<Int_t>(stustream->GetFwVersion())
};
fTriggerData->SetL1TriggerType(type);
fTriggerData->SetL1RawData(stustream->GetRawData());
Int_t iTRU, jTRU, x, y, jADC;
TVector2 sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch;
fDCSConfigSTU->GetSegmentation(sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch);
if (stustream->GetRawData()) {
HLTDebug("| STU => TRU raw data are there!\n");
//Int_t nTRU = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU();
Int_t nTRU = detector == 0 ? 32 : 14;
for (Int_t i = 0; i < nTRU; i++) {
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(i, detector);
UInt_t adc[96]; for (Int_t j = 0; j < 96; j++) adc[j] = 0;
stustream->GetADC(i, adc);
for (Int_t j = 0; j < 96; j++) {
if (adc[j] <= 0) continue;
HLTDebug("| STU => TRU# %2d raw data: ADC# %2d: %d\n", iTRU, j, adc[j]);
if(fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1){
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(iTRU, j, idx);
} else {
fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(i, j, jTRU, jADC, detector);
//printf("Detector %d, iTRU %d (%d), jTRU %d, iADC %d, jADC %d\n", detector, i, iTRU, jTRU, j, jADC);
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(jTRU, jADC, idx);
}
SetL1TimeSum(GetRawDigit(idx), adc[j]);
}
}
}
// List of patches in EMCal coordinate system
for (Int_t i = 0; i < stustream->GetNL0GammaPatch(); i++) {
stustream->GetL0GammaPatch(i, iTRU, x);
//if(iTRU >= 32) iTRU -= 32;
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);
const Int_t sizePatchL0 = 4;
HLTDebug("| STU => Found L0 patch id: %2d in TRU# %2d\n", x, iTRU);
Int_t idFastOR[4];
for (Int_t j = 0; j < 4; j++) idFastOR[j] = -1;
if (fkGeometryPtr->GetGeometryPtr()->GetFastORIndexFromL0Index(iTRU, x, idFastOR, sizePatchL0)) {
idx = idFastOR[1];
Int_t px, py;
if (fkGeometryPtr->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(idx, px, py)){
HLTDebug("| STU => Add L0 patch at (%2d , %2d)\n", px, py);
SetTriggerBit(GetRawDigit(idx), kL0, 1);
}
}
}
Int_t vx, vy, lphi;
for (int ithr = 0; ithr < 2; ithr++) {
for (Int_t i = 0; i < stustream->GetNL1GammaPatch(ithr); i++) {
if (stustream->GetL1GammaPatch(i, ithr, iTRU, x, y)) { // col (0..23), row (0..3)
if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
// Run 1
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);
HLTDebug("| STU => Found L1 gamma patch at (%2d , %2d) in TRU# %2d\n", x, y, iTRU);
vx = 23 - x;
vy = y + 4 * int(iTRU / 2); // Position in EMCal frame
if (iTRU % 2) vx += 24; // C side
vx = vx - int(sizeL1gsubr.X()) * int(sizeL1gpatch.X()) + 1;
lphi = 64;
if (vx >= 0 && vy < lphi) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
HLTDebug("| STU => Add L1 gamma [%d] patch at (%2d , %2d)\n", ithr, vx, vy);
SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
}
}
} else {
// Run 2
fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(iTRU, x, y, jTRU, vx, vy, detector);
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInTRU(jTRU, vx, vy, idx);
SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
}
}
}
for (Int_t i = 0; i < stustream->GetNL1JetPatch(ithr); i++) {
if (stustream->GetL1JetPatch(i, ithr, x, y)) { // col (0,15), row (0,11)
HLTDebug("| STU => Found L1 jet [%d] patch at (%2d , %2d)\n", ithr, x, y);
if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
vx = 11 - y - int(sizeL1jpatch.X()) + 1;
vy = 15 - x - int(sizeL1jpatch.Y()) + 1;
}
else {
vx = y;
vy = x;
}
vx *= int(sizeL1jsubr.X());
vy *= int(sizeL1jsubr.Y());
if (vx >= 0 && vy >= 0) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
HLTDebug("| STU => Add L1 jet patch at (%2d , %2d)\n", vx, vy);
SetTriggerBit(GetRawDigit(idx), kL1JetHigh + ithr, 1);
}
}
}
}
}
if (detector == 1) {
UInt_t sregion[36] = {0};
stustream->GetPHOSSubregion(sregion);
for (int isr=0;isr<36;isr++) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPHOSSubregion(isr, idx)) {
SetL1SubRegion(GetRawDigit(idx), sregion[isr]);
}
}
}
}
/*
for(int idig = 0; idig < fNRawDigits; idig++){
PrintRawDigit(fRawDigitBuffer[idig]);
}
*/
}
Int_t AliHLTEMCALSTURawDigitMaker::WriteRawDigitsBuffer(AliHLTCaloTriggerRawDigitDataStruct *bufferptr, AliHLTUInt32_t &availableSize) const {
Int_t outputsize = 0;
for(Int_t idig = 0; idig < fNRawDigits; idig++){
if(availableSize < sizeof(AliHLTCaloTriggerRawDigitDataStruct)){
HLTWarning("Buffer exceeded after %d digits", idig);
break;
}
if (fRawDigitBuffer[idig].fID < 0 || fRawDigitBuffer[idig].fID >= fgkNRawDigits)
{
HLTWarning("Invalid TRU Index in Output %d", fRawDigitBuffer[idig].fID);
continue;
}
*bufferptr = fRawDigitBuffer[idig];
bufferptr++;
outputsize += sizeof(AliHLTCaloTriggerRawDigitDataStruct);
availableSize -= sizeof(AliHLTCaloTriggerRawDigitDataStruct);
}
return outputsize;
}
void AliHLTEMCALSTURawDigitMaker::Reset() {
for (Int_t i = 0; i < fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
fNRawDigits = 0;
fTriggerData->Reset();
}
AliHLTCaloTriggerRawDigitDataStruct &AliHLTEMCALSTURawDigitMaker::GetRawDigit(Int_t index){
if (index < 0){
HLTWarning("Invalid STU Index %d", index);
AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fgkNRawDigits - 1];
InitializeRawDigit(dig);
return dig;
}
if(fRawDigitIndex[index] >= 0){
return fRawDigitBuffer[fRawDigitIndex[index]];
}
fRawDigitIndex[index] = fNRawDigits;
AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fNRawDigits];
InitializeRawDigit(dig);
SetRawDigitID(dig, index);
fNRawDigits++;
return dig;
}
<commit_msg>Fix EGA patch position according to git commit 12bdd61e04aa5cb5f8ec157fc8796e64b8cf332a<commit_after>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: Markus Fasel *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliHLTEMCALSTURawDigitMaker.h"
#include "AliCaloConstants.h"
#include "AliCaloRawAnalyzerFactory.h"
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloRawStreamV3.h"
#include "AliDAQ.h"
#include "AliEMCALTriggerSTUDCSConfig.h"
#include "AliEMCALTriggerData.h"
#include "AliEMCALTriggerRawDigit.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALGeometry.h"
#include "AliRawEquipmentHeader.h"
#include "AliRawEvent.h"
#include "AliRawReader.h"
#include "AliRawVEquipment.h"
ClassImp(AliHLTEMCALSTURawDigitMaker)
AliHLTEMCALSTURawDigitMaker::AliHLTEMCALSTURawDigitMaker() :
TObject(),
AliHLTLogging(),
fkGeometryPtr(NULL),
fDCSConfigSTU(NULL),
fTriggerData(NULL),
fNRawDigits(0)
{
fDCSConfigSTU = new AliEMCALTriggerSTUDCSConfig;
fTriggerData = new AliEMCALTriggerData;
for (Int_t i=0; i<fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
}
AliHLTEMCALSTURawDigitMaker::~AliHLTEMCALSTURawDigitMaker() {
if(fDCSConfigSTU) delete fDCSConfigSTU;
if(fTriggerData) delete fTriggerData;
}
void AliHLTEMCALSTURawDigitMaker::ProcessSTUStream(AliEMCALTriggerSTURawStream *stustream, Int_t detector){
HLTDebug("Start post processing the raw digit maker");
Int_t idx;
AliHLTCaloTriggerRawDigitDataStruct *hltdig(NULL);
if (stustream && stustream->ReadPayLoad()) {
fTriggerData->SetL1DataDecoded(1);
for (int i = 0; i < 2; i++) {
fTriggerData->SetL1GammaThreshold(i, stustream->GetL1GammaThreshold(i));
fTriggerData->SetL1JetThreshold( i, stustream->GetL1JetThreshold(i) );
}
Int_t v0[2] = { static_cast<Int_t>(stustream->GetV0A()), static_cast<Int_t>(stustream->GetV0C())};
// Modify DCS config from STU payload content
for(Int_t i = 0; i < 3; i++){
for(Int_t j = 0; j < 2; j++){
fDCSConfigSTU->SetG(i, j, stustream->GetG(i, j));
fDCSConfigSTU->SetJ(i, j, stustream->GetJ(i, j));
}
}
fDCSConfigSTU->SetRawData(stustream->GetRawData());
fDCSConfigSTU->SetRegion(stustream->GetRegionEnable());
fDCSConfigSTU->SetFw(stustream->GetFwVersion());
fTriggerData->SetL1FrameMask(stustream->GetFrameReceived());
fTriggerData->SetL1V0(v0);
Int_t type[15] =
{
static_cast<Int_t>(stustream->GetG(0, 0)),
static_cast<Int_t>(stustream->GetG(1, 0)),
static_cast<Int_t>(stustream->GetG(2, 0)),
static_cast<Int_t>(stustream->GetJ(0, 0)),
static_cast<Int_t>(stustream->GetJ(1, 0)),
static_cast<Int_t>(stustream->GetJ(2, 0)),
static_cast<Int_t>(stustream->GetG(0, 1)),
static_cast<Int_t>(stustream->GetG(1, 1)),
static_cast<Int_t>(stustream->GetG(2, 1)),
static_cast<Int_t>(stustream->GetJ(0, 1)),
static_cast<Int_t>(stustream->GetJ(1, 1)),
static_cast<Int_t>(stustream->GetJ(2, 1)),
static_cast<Int_t>(stustream->GetRawData()),
static_cast<Int_t>(stustream->GetRegionEnable()),
static_cast<Int_t>(stustream->GetFwVersion())
};
fTriggerData->SetL1TriggerType(type);
fTriggerData->SetL1RawData(stustream->GetRawData());
Int_t iTRU, jTRU, x, y, jADC;
TVector2 sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch;
fDCSConfigSTU->GetSegmentation(sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch);
if (stustream->GetRawData()) {
HLTDebug("| STU => TRU raw data are there!\n");
//Int_t nTRU = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU();
Int_t nTRU = detector == 0 ? 32 : 14;
for (Int_t i = 0; i < nTRU; i++) {
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(i, detector);
UInt_t adc[96]; for (Int_t j = 0; j < 96; j++) adc[j] = 0;
stustream->GetADC(i, adc);
for (Int_t j = 0; j < 96; j++) {
if (adc[j] <= 0) continue;
HLTDebug("| STU => TRU# %2d raw data: ADC# %2d: %d\n", iTRU, j, adc[j]);
if(fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1){
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(iTRU, j, idx);
} else {
fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(i, j, jTRU, jADC, detector);
//printf("Detector %d, iTRU %d (%d), jTRU %d, iADC %d, jADC %d\n", detector, i, iTRU, jTRU, j, jADC);
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(jTRU, jADC, idx);
}
SetL1TimeSum(GetRawDigit(idx), adc[j]);
}
}
}
// List of patches in EMCal coordinate system
for (Int_t i = 0; i < stustream->GetNL0GammaPatch(); i++) {
stustream->GetL0GammaPatch(i, iTRU, x);
//if(iTRU >= 32) iTRU -= 32;
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);
const Int_t sizePatchL0 = 4;
HLTDebug("| STU => Found L0 patch id: %2d in TRU# %2d\n", x, iTRU);
Int_t idFastOR[4];
for (Int_t j = 0; j < 4; j++) idFastOR[j] = -1;
if (fkGeometryPtr->GetGeometryPtr()->GetFastORIndexFromL0Index(iTRU, x, idFastOR, sizePatchL0)) {
idx = idFastOR[1];
Int_t px, py;
if (fkGeometryPtr->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(idx, px, py)){
HLTDebug("| STU => Add L0 patch at (%2d , %2d)\n", px, py);
SetTriggerBit(GetRawDigit(idx), kL0, 1);
}
}
}
Int_t vx, vy, lphi;
for (int ithr = 0; ithr < 2; ithr++) {
for (Int_t i = 0; i < stustream->GetNL1GammaPatch(ithr); i++) {
if (stustream->GetL1GammaPatch(i, ithr, iTRU, x, y)) { // col (0..23), row (0..3)
iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);
if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
// Run 1
HLTDebug("| STU => Found L1 gamma patch at (%2d , %2d) in TRU# %2d\n", x, y, iTRU);
vx = 23 - x;
vy = y + 4 * int(iTRU / 2); // Position in EMCal frame
if (iTRU % 2) vx += 24; // C side
vx = vx - int(sizeL1gsubr.X()) * int(sizeL1gpatch.X()) + 1;
lphi = 64;
if (vx >= 0 && vy < lphi) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
HLTDebug("| STU => Add L1 gamma [%d] patch at (%2d , %2d)\n", ithr, vx, vy);
SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
}
}
} else {
// Run 2
// fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(iTRU, x, y, jTRU, vx, vy, detector);
fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInTRU(iTRU, x, y, idx);
SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
}
}
}
for (Int_t i = 0; i < stustream->GetNL1JetPatch(ithr); i++) {
if (stustream->GetL1JetPatch(i, ithr, x, y)) { // col (0,15), row (0,11)
HLTDebug("| STU => Found L1 jet [%d] patch at (%2d , %2d)\n", ithr, x, y);
if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
vx = 11 - y - int(sizeL1jpatch.X()) + 1;
vy = 15 - x - int(sizeL1jpatch.Y()) + 1;
}
else {
vx = y;
vy = x;
}
vx *= int(sizeL1jsubr.X());
vy *= int(sizeL1jsubr.Y());
if (vx >= 0 && vy >= 0) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
HLTDebug("| STU => Add L1 jet patch at (%2d , %2d)\n", vx, vy);
SetTriggerBit(GetRawDigit(idx), kL1JetHigh + ithr, 1);
}
}
}
}
}
if (detector == 1) {
UInt_t sregion[36] = {0};
stustream->GetPHOSSubregion(sregion);
for (int isr=0;isr<36;isr++) {
if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPHOSSubregion(isr, idx)) {
SetL1SubRegion(GetRawDigit(idx), sregion[isr]);
}
}
}
}
/*
for(int idig = 0; idig < fNRawDigits; idig++){
PrintRawDigit(fRawDigitBuffer[idig]);
}
*/
}
Int_t AliHLTEMCALSTURawDigitMaker::WriteRawDigitsBuffer(AliHLTCaloTriggerRawDigitDataStruct *bufferptr, AliHLTUInt32_t &availableSize) const {
Int_t outputsize = 0;
for(Int_t idig = 0; idig < fNRawDigits; idig++){
if(availableSize < sizeof(AliHLTCaloTriggerRawDigitDataStruct)){
HLTWarning("Buffer exceeded after %d digits", idig);
break;
}
if (fRawDigitBuffer[idig].fID < 0 || fRawDigitBuffer[idig].fID >= fgkNRawDigits)
{
HLTWarning("Invalid TRU Index in Output %d", fRawDigitBuffer[idig].fID);
continue;
}
*bufferptr = fRawDigitBuffer[idig];
bufferptr++;
outputsize += sizeof(AliHLTCaloTriggerRawDigitDataStruct);
availableSize -= sizeof(AliHLTCaloTriggerRawDigitDataStruct);
}
return outputsize;
}
void AliHLTEMCALSTURawDigitMaker::Reset() {
for (Int_t i = 0; i < fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
fNRawDigits = 0;
fTriggerData->Reset();
}
AliHLTCaloTriggerRawDigitDataStruct &AliHLTEMCALSTURawDigitMaker::GetRawDigit(Int_t index){
if (index < 0){
HLTWarning("Invalid STU Index %d", index);
AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fgkNRawDigits - 1];
InitializeRawDigit(dig);
return dig;
}
if(fRawDigitIndex[index] >= 0){
return fRawDigitBuffer[fRawDigitIndex[index]];
}
fRawDigitIndex[index] = fNRawDigits;
AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fNRawDigits];
InitializeRawDigit(dig);
SetRawDigitID(dig, index);
fNRawDigits++;
return dig;
}
<|endoftext|> |
<commit_before>#include "commands.hpp"
#include "TaskSignals.hpp"
#include <rtos.h>
#include <Console.hpp>
#include <logger.hpp>
/**
* Initializes the console
*/
void Task_SerialConsole(void const* args)
{
// Store the thread's ID
osThreadId threadID = Thread::gettid();
// Store our priority so we know what to reset it to after running a command
osPriority threadPriority;
if (threadID != NULL)
threadPriority = osThreadGetPriority(threadID);
else
threadPriority = (osPriority)NULL;
// We wait here until until main tells us we can continue.
// This is to prevent any startup logging output from getting jumbled in with the console's serial data
osSignalWait(CONSOLE_TASK_START_SIGNAL, osWaitForever);
// Initalize the console buffer and save the char buffer's starting address
Console::Init();
Console::changeUser(git_head_author);
// Let everyone know we're ok
LOG(INIT, "Serial console ready!\r\n Thread ID:\t%u\r\n Priority:\t%d", threadID, threadPriority);
// Print out the header to show the user we're ready for input
Console::PrintHeader();
while (true) {
// Check console communications, currently does nothing
Console::ConComCheck();
// Execute any active iterative command
executeIterativeCommand();
// If there is a new command to handle, parse and process it
if (Console::CommandReady() == true) {
// Increase the thread's priority first so we can make sure the scheduler will select it to run
if (osThreadSetPriority(threadID, osPriorityAboveNormal) == osOK) {
// Disable UART interrupts & execute the command
NVIC_DisableIRQ(UART0_IRQn);
executeLine(Console::rxBufferPtr());
// Now, reset the priority of the thread to its idle state
if (osThreadSetPriority(threadID, threadPriority) == osOK) {
Console::CommandHandled(true);
}
// Enable UART interrupts again
NVIC_EnableIRQ(UART0_IRQn);
}
}
// Check if a system stop is requested
if (Console::IsSystemStopRequested() == true)
break;
// Yield to other threads when not needing to execute anything
Thread::yield();
}
// Terminate the thread if the while loop is ever broken out of
osThreadTerminate(threadID);
}
<commit_msg>removing NULL from ConsoleTask<commit_after>#include "commands.hpp"
#include "TaskSignals.hpp"
#include <rtos.h>
#include <Console.hpp>
#include <logger.hpp>
/**
* Initializes the console
*/
void Task_SerialConsole(void const* args)
{
// Store the thread's ID
osThreadId threadID = Thread::gettid();
// Store our priority so we know what to reset it to after running a command
osPriority threadPriority;
if (threadID != nullptr)
threadPriority = osThreadGetPriority(threadID);
else
threadPriority = osPriorityIdle;
// We wait here until until main tells us we can continue.
// This is to prevent any startup logging output from getting jumbled in with the console's serial data
osSignalWait(CONSOLE_TASK_START_SIGNAL, osWaitForever);
// Initalize the console buffer and save the char buffer's starting address
Console::Init();
Console::changeUser(git_head_author);
// Let everyone know we're ok
LOG(INIT, "Serial console ready!\r\n Thread ID:\t%u\r\n Priority:\t%d", threadID, threadPriority);
// Print out the header to show the user we're ready for input
Console::PrintHeader();
while (true) {
// Check console communications, currently does nothing
Console::ConComCheck();
// Execute any active iterative command
executeIterativeCommand();
// If there is a new command to handle, parse and process it
if (Console::CommandReady() == true) {
// Increase the thread's priority first so we can make sure the scheduler will select it to run
if (osThreadSetPriority(threadID, osPriorityAboveNormal) == osOK) {
// Disable UART interrupts & execute the command
NVIC_DisableIRQ(UART0_IRQn);
executeLine(Console::rxBufferPtr());
// Now, reset the priority of the thread to its idle state
if (osThreadSetPriority(threadID, threadPriority) == osOK) {
Console::CommandHandled(true);
}
// Enable UART interrupts again
NVIC_EnableIRQ(UART0_IRQn);
}
}
// Check if a system stop is requested
if (Console::IsSystemStopRequested() == true)
break;
// Yield to other threads when not needing to execute anything
Thread::yield();
}
// Terminate the thread if the while loop is ever broken out of
osThreadTerminate(threadID);
}
<|endoftext|> |
<commit_before>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QDomDocument>
#include <QDomElement>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
CCB_BEGIN()
namespace correlation {
// Load count.
static unsigned int instances(0);
// Correlation object.
static misc::shared_ptr<multiplexing::hooker> obj;
/**
* Module deinitialization routine.
*/
void module_deinit() {
// Decrement instance number.
if (!--correlation::instances) {
// Unregister correlation object.
multiplexing::engine::instance().unhook(*correlation::obj);
correlation::obj.clear();
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void module_init(void const* arg) {
// Increment instance number.
if (!correlation::instances++) {
// Check that correlation is enabled.
config::state const& cfg(*static_cast<config::state const*>(arg));
bool loaded(false);
QMap<QString, QString>::const_iterator
it(cfg.params().find("correlation"));
if (it != cfg.params().end()) {
// Parameters.
QString correlation_file;
QString retention_file;
// Parse XML.
QDomDocument d;
if (d.setContent(it.value())) {
// Browse first-level elements.
QDomElement root(d.documentElement());
QDomNodeList level1(root.childNodes());
for (int i = 0, len = level1.size(); i < len; ++i) {
QDomElement elem(level1.item(i).toElement());
if (!elem.isNull()) {
QString name(elem.tagName());
if (name == "file")
correlation_file = elem.text();
else if (name == "retention")
retention_file = elem.text();
}
}
}
// File exists, load it.
if (!correlation_file.isEmpty()) {
// Create and register correlation object.
misc::shared_ptr<correlation::correlator>
crltr(new correlation::correlator);
try {
crltr->load(correlation_file, retention_file);
correlation::obj = crltr.staticCast<multiplexing::hooker>();
multiplexing::engine::instance().hook(*correlation::obj);
loaded = true;
}
catch (std::exception const& e) {
logging::config(logging::high) << "correlation: " \
"configuration loading error: " << e.what();
}
catch (...) {
logging::config(logging::high) << "correlation: " \
"configuration loading error";
}
}
}
if (!loaded)
logging::config(logging::high) << "correlation: invalid " \
"correlation configuration, correlation engine is NOT loaded";
}
return ;
}
}
CCB_END()
extern "C" {
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
correlation::module_deinit();
return ;
}
/**
* Module initialization routine redirector.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
correlation::module_init(arg);
return ;
}
/**
* Module update routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_update(void const* arg) {
if (!correlation::obj.isNull())
correlation::obj->stopping();
correlation::module_deinit();
correlation::module_init(arg);
correlation::obj->starting();
return ;
}
}
<commit_msg>correlation: fix a crash that arise when module is loaded but not the engine. This fixes #4282.<commit_after>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QDomDocument>
#include <QDomElement>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
CCB_BEGIN()
namespace correlation {
// Load count.
static unsigned int instances(0);
// Correlation object.
static misc::shared_ptr<multiplexing::hooker> obj;
/**
* Module deinitialization routine.
*/
void module_deinit() {
// Decrement instance number.
if (!--correlation::instances) {
// Unregister correlation object.
multiplexing::engine::instance().unhook(*correlation::obj);
correlation::obj.clear();
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void module_init(void const* arg) {
// Increment instance number.
if (!correlation::instances++) {
// Check that correlation is enabled.
config::state const& cfg(*static_cast<config::state const*>(arg));
bool loaded(false);
QMap<QString, QString>::const_iterator
it(cfg.params().find("correlation"));
if (it != cfg.params().end()) {
// Parameters.
QString correlation_file;
QString retention_file;
// Parse XML.
QDomDocument d;
if (d.setContent(it.value())) {
// Browse first-level elements.
QDomElement root(d.documentElement());
QDomNodeList level1(root.childNodes());
for (int i = 0, len = level1.size(); i < len; ++i) {
QDomElement elem(level1.item(i).toElement());
if (!elem.isNull()) {
QString name(elem.tagName());
if (name == "file")
correlation_file = elem.text();
else if (name == "retention")
retention_file = elem.text();
}
}
}
// File exists, load it.
if (!correlation_file.isEmpty()) {
// Create and register correlation object.
misc::shared_ptr<correlation::correlator>
crltr(new correlation::correlator);
try {
crltr->load(correlation_file, retention_file);
correlation::obj = crltr.staticCast<multiplexing::hooker>();
multiplexing::engine::instance().hook(*correlation::obj);
loaded = true;
}
catch (std::exception const& e) {
logging::config(logging::high) << "correlation: " \
"configuration loading error: " << e.what();
}
catch (...) {
logging::config(logging::high) << "correlation: " \
"configuration loading error";
}
}
}
if (!loaded)
logging::config(logging::high) << "correlation: invalid " \
"correlation configuration, correlation engine is NOT loaded";
}
return ;
}
}
CCB_END()
extern "C" {
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
correlation::module_deinit();
return ;
}
/**
* Module initialization routine redirector.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
correlation::module_init(arg);
return ;
}
/**
* Module update routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_update(void const* arg) {
if (!correlation::obj.isNull())
correlation::obj->stopping();
correlation::module_deinit();
correlation::module_init(arg);
if (!correlation::obj.isNull())
correlation::obj->starting();
return ;
}
}
<|endoftext|> |
<commit_before>#include "trikKitInterpreterPlugin.h"
#include <QtWidgets/QApplication>
#include <commonTwoDModel/engine/twoDModelEngineFacade.h>
#include "src/trikTwoDModelConfigurer.h"
using namespace trikKitInterpreter;
using namespace qReal;
Id const robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
Id const subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");
TrikKitInterpreterPlugin::TrikKitInterpreterPlugin()
: mTwoDRobotModelV4(mRealRobotModelV4)
, mTwoDRobotModelV6(mRealRobotModelV6)
, mBlocksFactory(new blocks::TrikBlocksFactory)
, mAdditionalPreferences(new TrikAdditionalPreferences({ mRealRobotModelV4.name(), mRealRobotModelV6.name() }))
{
mAppTranslator.load(":/trikKitInterpreter_" + QLocale::system().name());
QApplication::installTranslator(&mAppTranslator);
auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModelV4
, new TrikTwoDModelConfigurer("M1", "JM3"));
mTwoDRobotModelV4.setEngine(modelEngine->engine());
mTwoDModelV4.reset(modelEngine);
modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModelV6
, new TrikTwoDModelConfigurer("JM3", "JM4"));
mTwoDRobotModelV6.setEngine(modelEngine->engine());
mTwoDModelV6.reset(modelEngine);
mTwoDModelV4->devicesConfigurationProvider().connectDevicesConfigurationProvider(
&mTwoDModelV6->devicesConfigurationProvider());
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mRealRobotModelV4, &robotModel::real::RealRobotModelV4::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mRealRobotModelV6, &robotModel::real::RealRobotModelV6::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mTwoDRobotModelV4, &robotModel::twoD::TwoDRobotModel::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mTwoDRobotModelV6, &robotModel::twoD::TwoDRobotModel::rereadSettings);
}
void TrikKitInterpreterPlugin::init(interpreterBase::EventsForKitPluginInterface const &eventsForKitPlugin
, SystemEventsInterface const &systemEvents
, interpreterBase::InterpreterControlInterface &interpreterControl)
{
connect(&eventsForKitPlugin
, &interpreterBase::EventsForKitPluginInterface::robotModelChanged
, [this](QString const &modelName) { mCurrentlySelectedModelName = modelName; });
connect(&systemEvents, &qReal::SystemEventsInterface::activeTabChanged
, this, &TrikKitInterpreterPlugin::onActiveTabChanged);
mTwoDModelV4->init(eventsForKitPlugin, systemEvents, interpreterControl);
mTwoDModelV6->init(eventsForKitPlugin, systemEvents, interpreterControl);
}
QString TrikKitInterpreterPlugin::kitId() const
{
return "trikKit";
}
QString TrikKitInterpreterPlugin::friendlyKitName() const
{
return tr("TRIK");
}
QList<interpreterBase::robotModel::RobotModelInterface *> TrikKitInterpreterPlugin::robotModels()
{
return {/*&mRealRobotModelV4, */&mRealRobotModelV6/*, &mTwoDRobotModelV4*/, &mTwoDRobotModelV6};
}
interpreterBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPlugin::blocksFactoryFor(
interpreterBase::robotModel::RobotModelInterface const *model)
{
Q_UNUSED(model);
return mBlocksFactory;
}
interpreterBase::robotModel::RobotModelInterface *TrikKitInterpreterPlugin::defaultRobotModel()
{
return &mTwoDRobotModelV6;
}
interpreterBase::AdditionalPreferences *TrikKitInterpreterPlugin::settingsWidget()
{
return mAdditionalPreferences;
}
QList<qReal::ActionInfo> TrikKitInterpreterPlugin::customActions()
{
return { /* mTwoDModelV4->showTwoDModelWidgetActionInfo(), */mTwoDModelV6->showTwoDModelWidgetActionInfo() };
}
QList<HotKeyActionInfo> TrikKitInterpreterPlugin::hotKeyActions()
{
mTwoDModelV4->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
mTwoDModelV6->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
HotKeyActionInfo d2V4ModelActionInfo("Interpreter.Show2dModelForTrikV4", tr("Show 2d model for TRIK v4")
, mTwoDModelV4->showTwoDModelWidgetActionInfo().action());
HotKeyActionInfo d2V6ModelActionInfo("Interpreter.Show2dModelForTrikV6", tr("Show 2d model for TRIK v6")
, mTwoDModelV6->showTwoDModelWidgetActionInfo().action());
return { d2V4ModelActionInfo, d2V6ModelActionInfo };
}
QIcon TrikKitInterpreterPlugin::iconForFastSelector(
interpreterBase::robotModel::RobotModelInterface const &robotModel) const
{
/// @todo: draw icons for v4 and v6
return &robotModel == &mRealRobotModelV4 || &robotModel == &mRealRobotModelV6
? QIcon(":/icons/switch-real-trik.svg")
: &robotModel == &mTwoDRobotModelV4 || &robotModel == &mTwoDRobotModelV6
? QIcon(":/icons/switch-2d.svg")
: QIcon();
}
interpreterBase::DevicesConfigurationProvider *TrikKitInterpreterPlugin::devicesConfigurationProvider()
{
return &mTwoDModelV4->devicesConfigurationProvider();
}
void TrikKitInterpreterPlugin::onActiveTabChanged(Id const &rootElementId)
{
bool enabled = rootElementId.type() == robotDiagramType || rootElementId.type() == subprogramDiagramType;
bool v4Enabled = enabled && mCurrentlySelectedModelName == mTwoDRobotModelV4.name();
bool v6Enabled = enabled && mCurrentlySelectedModelName == mTwoDRobotModelV6.name();
mTwoDModelV4->showTwoDModelWidgetActionInfo().action()->setVisible(v4Enabled);
mTwoDModelV6->showTwoDModelWidgetActionInfo().action()->setVisible(v6Enabled);
}
<commit_msg>Fixed untranslated Trik additional settings<commit_after>#include "trikKitInterpreterPlugin.h"
#include <QtWidgets/QApplication>
#include <commonTwoDModel/engine/twoDModelEngineFacade.h>
#include "src/trikTwoDModelConfigurer.h"
using namespace trikKitInterpreter;
using namespace qReal;
Id const robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
Id const subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");
TrikKitInterpreterPlugin::TrikKitInterpreterPlugin()
: mTwoDRobotModelV4(mRealRobotModelV4)
, mTwoDRobotModelV6(mRealRobotModelV6)
, mBlocksFactory(new blocks::TrikBlocksFactory)
{
mAppTranslator.load(":/trikKitInterpreter_" + QLocale::system().name());
QApplication::installTranslator(&mAppTranslator);
mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModelV4.name(), mRealRobotModelV6.name() });
auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModelV4
, new TrikTwoDModelConfigurer("M1", "JM3"));
mTwoDRobotModelV4.setEngine(modelEngine->engine());
mTwoDModelV4.reset(modelEngine);
modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModelV6
, new TrikTwoDModelConfigurer("JM3", "JM4"));
mTwoDRobotModelV6.setEngine(modelEngine->engine());
mTwoDModelV6.reset(modelEngine);
mTwoDModelV4->devicesConfigurationProvider().connectDevicesConfigurationProvider(
&mTwoDModelV6->devicesConfigurationProvider());
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mRealRobotModelV4, &robotModel::real::RealRobotModelV4::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mRealRobotModelV6, &robotModel::real::RealRobotModelV6::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mTwoDRobotModelV4, &robotModel::twoD::TwoDRobotModel::rereadSettings);
connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged
, &mTwoDRobotModelV6, &robotModel::twoD::TwoDRobotModel::rereadSettings);
}
void TrikKitInterpreterPlugin::init(interpreterBase::EventsForKitPluginInterface const &eventsForKitPlugin
, SystemEventsInterface const &systemEvents
, interpreterBase::InterpreterControlInterface &interpreterControl)
{
connect(&eventsForKitPlugin
, &interpreterBase::EventsForKitPluginInterface::robotModelChanged
, [this](QString const &modelName) { mCurrentlySelectedModelName = modelName; });
connect(&systemEvents, &qReal::SystemEventsInterface::activeTabChanged
, this, &TrikKitInterpreterPlugin::onActiveTabChanged);
mTwoDModelV4->init(eventsForKitPlugin, systemEvents, interpreterControl);
mTwoDModelV6->init(eventsForKitPlugin, systemEvents, interpreterControl);
}
QString TrikKitInterpreterPlugin::kitId() const
{
return "trikKit";
}
QString TrikKitInterpreterPlugin::friendlyKitName() const
{
return tr("TRIK");
}
QList<interpreterBase::robotModel::RobotModelInterface *> TrikKitInterpreterPlugin::robotModels()
{
return {/*&mRealRobotModelV4, */&mRealRobotModelV6/*, &mTwoDRobotModelV4*/, &mTwoDRobotModelV6};
}
interpreterBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPlugin::blocksFactoryFor(
interpreterBase::robotModel::RobotModelInterface const *model)
{
Q_UNUSED(model);
return mBlocksFactory;
}
interpreterBase::robotModel::RobotModelInterface *TrikKitInterpreterPlugin::defaultRobotModel()
{
return &mTwoDRobotModelV6;
}
interpreterBase::AdditionalPreferences *TrikKitInterpreterPlugin::settingsWidget()
{
return mAdditionalPreferences;
}
QList<qReal::ActionInfo> TrikKitInterpreterPlugin::customActions()
{
return { /* mTwoDModelV4->showTwoDModelWidgetActionInfo(), */mTwoDModelV6->showTwoDModelWidgetActionInfo() };
}
QList<HotKeyActionInfo> TrikKitInterpreterPlugin::hotKeyActions()
{
mTwoDModelV4->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
mTwoDModelV6->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
HotKeyActionInfo d2V4ModelActionInfo("Interpreter.Show2dModelForTrikV4", tr("Show 2d model for TRIK v4")
, mTwoDModelV4->showTwoDModelWidgetActionInfo().action());
HotKeyActionInfo d2V6ModelActionInfo("Interpreter.Show2dModelForTrikV6", tr("Show 2d model for TRIK v6")
, mTwoDModelV6->showTwoDModelWidgetActionInfo().action());
return { d2V4ModelActionInfo, d2V6ModelActionInfo };
}
QIcon TrikKitInterpreterPlugin::iconForFastSelector(
interpreterBase::robotModel::RobotModelInterface const &robotModel) const
{
/// @todo: draw icons for v4 and v6
return &robotModel == &mRealRobotModelV4 || &robotModel == &mRealRobotModelV6
? QIcon(":/icons/switch-real-trik.svg")
: &robotModel == &mTwoDRobotModelV4 || &robotModel == &mTwoDRobotModelV6
? QIcon(":/icons/switch-2d.svg")
: QIcon();
}
interpreterBase::DevicesConfigurationProvider *TrikKitInterpreterPlugin::devicesConfigurationProvider()
{
return &mTwoDModelV4->devicesConfigurationProvider();
}
void TrikKitInterpreterPlugin::onActiveTabChanged(Id const &rootElementId)
{
bool enabled = rootElementId.type() == robotDiagramType || rootElementId.type() == subprogramDiagramType;
bool v4Enabled = enabled && mCurrentlySelectedModelName == mTwoDRobotModelV4.name();
bool v6Enabled = enabled && mCurrentlySelectedModelName == mTwoDRobotModelV6.name();
mTwoDModelV4->showTwoDModelWidgetActionInfo().action()->setVisible(v4Enabled);
mTwoDModelV6->showTwoDModelWidgetActionInfo().action()->setVisible(v6Enabled);
}
<|endoftext|> |
<commit_before>/*
* avs2wav main.cpp
* extract audio data as RIFF WAV format, from avs file
* Copyright (C) 2010 janus_wel<[email protected]>
* see LICENSE for redistributing, modifying, and so on.
* */
#include "../../include/avsutil.hpp"
#include "avs2wav.hpp"
#include "../../helper/tconv.hpp"
#include "../../helper/elapsed.hpp"
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>
#include <vector>
#include <stdexcept>
#include <memory> // fot std::auto_ptr
#ifdef _MSC_VER
# include <io.h> // for _isatty(1), _setmode(2)
# include <fcntl.h> // for _setmode(2)
# include <stdio.h> // for _fileno(1)
#else
# include <unistd.h> // for fileno(1)
# include <stdio.h> // for isatty(1)
#endif
// using namespaces
using namespace std;
using namespace avsutil;
// global object
// progresss is abbr of "progress stream"
// this stream is used in progress_cl()
// streambuf is stdout fow now
ostream progresss(cout.rdbuf());
// type converter routing through std::string;
util::string::tconv conv(locale::classic());
// forward declarations
// return true if redirected to file or connected to pipe
bool is_connected(void);
// set stdout to binary mode
void set_stdout_binary(void);
// callback function for Audio::write()
void progress_cl(const unsigned __int64, const unsigned __int64);
// output audio informations
ostream& operator <<(ostream&, const AudioInfo&);
int main(const unsigned int argc, const char* argv[]) {
// set global locale to use non-ascii characters for filenames
locale::global(locale(""));
// constants
const unsigned int header_width = 24;
const unsigned int buf_samples_def = 4096;
const unsigned int buf_size_def = 4096;
const unsigned int buf_samples_min = 1;
const unsigned int buf_size_min = 2;
// analyze options
string inputfile;
string outputfile;
unsigned int buf_samples = buf_samples_def;
unsigned int buf_size = buf_size_def;
for (unsigned int i = 1; i < argc; ++i) {
const string arg(argv[i]);
if (arg == "-h" || arg == "--help") {
usage(cout);
return OK;
}
else if (arg == "-v" || arg == "--version") {
version_license(cout);
return OK;
}
else if (arg == "-b" || arg == "--buffers") {
buf_size = conv.strto<unsigned int>(argv[++i]);
if (buf_size < buf_size_min) {
cerr << "Size of buffers for output is required at least: "
<< buf_size_min << endl
<< "Check the argument with \"-b\" option." << endl;
return BAD_ARG;
}
}
else if (arg == "-s" || arg == "--samples") {
buf_samples = conv.strto<unsigned int>(argv[++i]);
if (buf_samples < buf_samples_min) {
cerr << "A number of samples processed at one time is required at least: "
<< buf_samples_min << endl
<< "Check the argument with \"-s\" option." << endl;
return BAD_ARG;
}
}
else if (arg == "-o" || arg == "--output") {
outputfile = argv[++i];
}
else if (arg[0] == '-') {
cerr << "Unknown option: \"" << arg << '"' << endl;
usage(cerr);
return BAD_ARG;
}
else {
inputfile = arg;
break;
}
}
if (inputfile.empty()) {
cerr << "Specify <inputfile>." << endl;
usage(cerr);
return BAD_ARG;
}
try {
// read in avs file
auto_ptr<Avs> avs(CreateAvsObj(inputfile.c_str()));
if (!avs->is_fine()) {
cerr << avs->errmsg() << endl;
return BAD_AVS;
}
// get audio stream
auto_ptr<Audio> audio(avs->audio());
AudioInfo ai = audio->info();
if (!ai.exists) {
cerr << "no audio in the file: " << inputfile << endl;
return BAD_AVS;
}
// preparations
// output and information stream (to stdout for now)
ostream outputs(cout.rdbuf());
ostream infos(cout.rdbuf());
// apply manipulators to form data
progresss << right << fixed << setprecision(2);
infos << left;
// settings for infos, outputs and progresss
// this is true if redirected to file or connected to pipe
if (!is_connected()) {
// if output to file
// set output filename if it isn't decided still
if (outputfile.empty()) outputfile.assign(inputfile).append(".wav");
// create filebuf and set it output stream
filebuf* fbuf = new filebuf;
fbuf->open(outputfile.c_str(), ios::out | ios::binary | ios::trunc);
if (!fbuf->is_open()) {
cerr << "Can't open file to write: " << outputfile << endl;
return UNKNOWN;
}
// set filebuf to output stream
outputs.rdbuf(fbuf);
}
else {
// if output to stdout
// only to show
outputfile.assign("stdout");
// use stderr to show a progress of the process and informations of avs
progresss.rdbuf(cerr.rdbuf());
infos.rdbuf(cerr.rdbuf());
// set stdout to binary mode (Windows only)
set_stdout_binary();
}
infos
<< setw(header_width) << "source:" << inputfile << endl
<< setw(header_width) << "destination:" << outputfile << endl
<< setw(header_width) << "buffers for output:" << buf_size << " bytes" << endl
<< setw(header_width) << "processed at one time:" << buf_samples << " samples" << endl
<< ai;
// allocate buffer
std::vector<char> internalbuf(buf_size);
outputs.rdbuf()->pubsetbuf(&internalbuf[0], buf_size);
// set values to Audio
audio->buf_samples(buf_samples);
audio->progress_callback(progress_cl);
// do it
outputs << audio.get();
infos
<< endl
<< endl
<< "done." << endl
<< endl;
}
catch (exception& ex) {
cerr << endl << ex.what() << endl;
return UNKNOWN;
}
return OK;
}
// definitions of functions
bool inline is_connected(void) {
#ifdef _MSC_VER
return !_isatty(_fileno(stdout));
#else
return !isatty(fileno(stdout));
#endif
}
void inline set_stdout_binary(void) {
#ifdef _MSC_VER
_setmode(_fileno(stdout), _O_BINARY);
#endif
}
void progress_cl(const unsigned __int64 processed, const unsigned __int64 max) {
static util::time::elapsed elapsed_time;
float percentage = (static_cast<float>(processed) / static_cast<float>(max)) * 100;
progresss
<< "\r"
<< setw(10) << processed << "/" << max << " samples"
<< " (" << setw(6) << percentage << "%)"
<< " elapsed time " << elapsed_time() << " sec";
}
ostream& operator <<(ostream& out, const AudioInfo& ai) {
// constants
static const unsigned int header_width = 18;
// preparations
string channels;
switch (ai.channels) {
case 1: channels = "mono"; break;
case 2: channels = "stereo"; break;
case 6: channels = "5.1ch"; break;
default:
channels.assign(conv.strfrom(ai.channels)).append("ch");
break;
}
float sampling_rate = static_cast<float>(ai.sampling_rate) / 1000;
// instantiate new ostream object and set streambuf of "out" to it
// in order to save the formattings of "out"
ostream o(out.rdbuf());
o << left << setfill('.')
<< "\n"
<< setw(header_width) << "bit depth " << ' ' << ai.bit_depth << "bit\n"
<< setw(header_width) << "channels " << ' ' << channels << "\n"
<< setw(header_width) << "sampling rate " << ' ' << sampling_rate << "kHz\n"
<< endl;
return out;
}
<commit_msg>Fix the signature of main function<commit_after>/*
* avs2wav main.cpp
* extract audio data as RIFF WAV format, from avs file
* Copyright (C) 2010 janus_wel<[email protected]>
* see LICENSE for redistributing, modifying, and so on.
* */
#include "../../include/avsutil.hpp"
#include "avs2wav.hpp"
#include "../../helper/tconv.hpp"
#include "../../helper/elapsed.hpp"
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>
#include <vector>
#include <stdexcept>
#include <memory> // fot std::auto_ptr
#ifdef _MSC_VER
# include <io.h> // for _isatty(1), _setmode(2)
# include <fcntl.h> // for _setmode(2)
# include <stdio.h> // for _fileno(1)
#else
# include <unistd.h> // for fileno(1)
# include <stdio.h> // for isatty(1)
#endif
// using namespaces
using namespace std;
using namespace avsutil;
// global object
// progresss is abbr of "progress stream"
// this stream is used in progress_cl()
// streambuf is stdout fow now
ostream progresss(cout.rdbuf());
// type converter routing through std::string;
util::string::tconv conv(locale::classic());
// forward declarations
// return true if redirected to file or connected to pipe
bool is_connected(void);
// set stdout to binary mode
void set_stdout_binary(void);
// callback function for Audio::write()
void progress_cl(const unsigned __int64, const unsigned __int64);
// output audio informations
ostream& operator <<(ostream&, const AudioInfo&);
int main(const int argc, const char* argv[]) {
// set global locale to use non-ascii characters for filenames
locale::global(locale(""));
// constants
const unsigned int header_width = 24;
const unsigned int buf_samples_def = 4096;
const unsigned int buf_size_def = 4096;
const unsigned int buf_samples_min = 1;
const unsigned int buf_size_min = 2;
// analyze options
string inputfile;
string outputfile;
unsigned int buf_samples = buf_samples_def;
unsigned int buf_size = buf_size_def;
for (int i = 1; i < argc; ++i) {
const string arg(argv[i]);
if (arg == "-h" || arg == "--help") {
usage(cout);
return OK;
}
else if (arg == "-v" || arg == "--version") {
version_license(cout);
return OK;
}
else if (arg == "-b" || arg == "--buffers") {
buf_size = conv.strto<unsigned int>(argv[++i]);
if (buf_size < buf_size_min) {
cerr << "Size of buffers for output is required at least: "
<< buf_size_min << endl
<< "Check the argument with \"-b\" option." << endl;
return BAD_ARG;
}
}
else if (arg == "-s" || arg == "--samples") {
buf_samples = conv.strto<unsigned int>(argv[++i]);
if (buf_samples < buf_samples_min) {
cerr << "A number of samples processed at one time is required at least: "
<< buf_samples_min << endl
<< "Check the argument with \"-s\" option." << endl;
return BAD_ARG;
}
}
else if (arg == "-o" || arg == "--output") {
outputfile = argv[++i];
}
else if (arg[0] == '-') {
cerr << "Unknown option: \"" << arg << '"' << endl;
usage(cerr);
return BAD_ARG;
}
else {
inputfile = arg;
break;
}
}
if (inputfile.empty()) {
cerr << "Specify <inputfile>." << endl;
usage(cerr);
return BAD_ARG;
}
try {
// read in avs file
auto_ptr<Avs> avs(CreateAvsObj(inputfile.c_str()));
if (!avs->is_fine()) {
cerr << avs->errmsg() << endl;
return BAD_AVS;
}
// get audio stream
auto_ptr<Audio> audio(avs->audio());
AudioInfo ai = audio->info();
if (!ai.exists) {
cerr << "no audio in the file: " << inputfile << endl;
return BAD_AVS;
}
// preparations
// output and information stream (to stdout for now)
ostream outputs(cout.rdbuf());
ostream infos(cout.rdbuf());
// apply manipulators to form data
progresss << right << fixed << setprecision(2);
infos << left;
// settings for infos, outputs and progresss
// this is true if redirected to file or connected to pipe
if (!is_connected()) {
// if output to file
// set output filename if it isn't decided still
if (outputfile.empty()) outputfile.assign(inputfile).append(".wav");
// create filebuf and set it output stream
filebuf* fbuf = new filebuf;
fbuf->open(outputfile.c_str(), ios::out | ios::binary | ios::trunc);
if (!fbuf->is_open()) {
cerr << "Can't open file to write: " << outputfile << endl;
return UNKNOWN;
}
// set filebuf to output stream
outputs.rdbuf(fbuf);
}
else {
// if output to stdout
// only to show
outputfile.assign("stdout");
// use stderr to show a progress of the process and informations of avs
progresss.rdbuf(cerr.rdbuf());
infos.rdbuf(cerr.rdbuf());
// set stdout to binary mode (Windows only)
set_stdout_binary();
}
infos
<< setw(header_width) << "source:" << inputfile << endl
<< setw(header_width) << "destination:" << outputfile << endl
<< setw(header_width) << "buffers for output:" << buf_size << " bytes" << endl
<< setw(header_width) << "processed at one time:" << buf_samples << " samples" << endl
<< ai;
// allocate buffer
std::vector<char> internalbuf(buf_size);
outputs.rdbuf()->pubsetbuf(&internalbuf[0], buf_size);
// set values to Audio
audio->buf_samples(buf_samples);
audio->progress_callback(progress_cl);
// do it
outputs << audio.get();
infos
<< endl
<< endl
<< "done." << endl
<< endl;
}
catch (exception& ex) {
cerr << endl << ex.what() << endl;
return UNKNOWN;
}
return OK;
}
// definitions of functions
bool inline is_connected(void) {
#ifdef _MSC_VER
return !_isatty(_fileno(stdout));
#else
return !isatty(fileno(stdout));
#endif
}
void inline set_stdout_binary(void) {
#ifdef _MSC_VER
_setmode(_fileno(stdout), _O_BINARY);
#endif
}
void progress_cl(const unsigned __int64 processed, const unsigned __int64 max) {
static util::time::elapsed elapsed_time;
float percentage = (static_cast<float>(processed) / static_cast<float>(max)) * 100;
progresss
<< "\r"
<< setw(10) << processed << "/" << max << " samples"
<< " (" << setw(6) << percentage << "%)"
<< " elapsed time " << elapsed_time() << " sec";
}
ostream& operator <<(ostream& out, const AudioInfo& ai) {
// constants
static const unsigned int header_width = 18;
// preparations
string channels;
switch (ai.channels) {
case 1: channels = "mono"; break;
case 2: channels = "stereo"; break;
case 6: channels = "5.1ch"; break;
default:
channels.assign(conv.strfrom(ai.channels)).append("ch");
break;
}
float sampling_rate = static_cast<float>(ai.sampling_rate) / 1000;
// instantiate new ostream object and set streambuf of "out" to it
// in order to save the formattings of "out"
ostream o(out.rdbuf());
o << left << setfill('.')
<< "\n"
<< setw(header_width) << "bit depth " << ' ' << ai.bit_depth << "bit\n"
<< setw(header_width) << "channels " << ' ' << channels << "\n"
<< setw(header_width) << "sampling rate " << ' ' << sampling_rate << "kHz\n"
<< endl;
return out;
}
<|endoftext|> |
<commit_before>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->Add(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
if (wrapper != nullptr)
{
_browserWrappers->Remove(wrapper->BrowserId);
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObject != nullptr)
{
auto window = context->GetGlobal();
wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);
wrapper->JavascriptRootObjectWrapper->V8Value = window;
wrapper->JavascriptRootObjectWrapper->Bind();
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObjectWrapper != nullptr)
{
delete wrapper->JavascriptRootObjectWrapper;
wrapper->JavascriptRootObjectWrapper = nullptr;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserId = browser->GetIdentifier();
auto browserWrapper = FindBrowserWrapper(browserId, false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest)
{
//If we can't find the browser wrapper then we'll just ignore this
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success;
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
CefRefPtr<CefProcessMessage> response;
//both messages have the callbackid stored at index 1
int64 callbackId = GetInt64(argList, 1);
if (name == kEvaluateJavascriptRequest)
{
auto frameId = GetInt64(argList, 0);
auto script = argList->GetString(2);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
try
{
if (context.get() && context->Enter())
{
success = context->Eval(script, result, exception);
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
//we need to do this here to be able to store the v8context
if (success)
{
auto argList = response->GetArgumentList();
SerializeV8Object(result, argList, 2, browserWrapper->CallbackRegistry);
}
}
}
finally
{
context->Exit();
}
}
else
{
//TODO handle error
}
}
else
{
auto jsCallbackId = GetInt64(argList, 0);
auto parameterList = argList->GetList(2);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
auto callbackRegistry = browserWrapper->CallbackRegistry;
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
try
{
if (context.get() && context->Enter())
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
}
else
{
exception = value->GetException();
}
}
}
finally
{
context->Exit();
}
}
if (response.get())
{
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, exception->GetMessage());
}
browser->SendProcessMessage(sourceProcessId, response);
}
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 1);
browserWrapper->CallbackRegistry->Deregister(jsCallbackId);
handled = true;
}
return handled;
};
}<commit_msg>Add more detail to NOTE Call GetIdentifier() directly rather than allocating browserId<commit_after>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->Add(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
if (wrapper != nullptr)
{
_browserWrappers->Remove(wrapper->BrowserId);
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObject != nullptr)
{
auto window = context->GetGlobal();
wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);
wrapper->JavascriptRootObjectWrapper->V8Value = window;
wrapper->JavascriptRootObjectWrapper->Bind();
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
if (wrapper->JavascriptRootObjectWrapper != nullptr)
{
delete wrapper->JavascriptRootObjectWrapper;
wrapper->JavascriptRootObjectWrapper = nullptr;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest)
{
//If we can't find the browser wrapper then we'll just
//ignore this as it's likely already been disposed of
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success;
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
CefRefPtr<CefProcessMessage> response;
//both messages have the callbackid stored at index 1
int64 callbackId = GetInt64(argList, 1);
if (name == kEvaluateJavascriptRequest)
{
auto frameId = GetInt64(argList, 0);
auto script = argList->GetString(2);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
try
{
if (context.get() && context->Enter())
{
success = context->Eval(script, result, exception);
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
//we need to do this here to be able to store the v8context
if (success)
{
auto argList = response->GetArgumentList();
SerializeV8Object(result, argList, 2, browserWrapper->CallbackRegistry);
}
}
}
finally
{
context->Exit();
}
}
else
{
//TODO handle error
}
}
else
{
auto jsCallbackId = GetInt64(argList, 0);
auto parameterList = argList->GetList(2);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
auto callbackRegistry = browserWrapper->CallbackRegistry;
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
try
{
if (context.get() && context->Enter())
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);
}
else
{
exception = value->GetException();
}
}
}
finally
{
context->Exit();
}
}
if (response.get())
{
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, exception->GetMessage());
}
browser->SendProcessMessage(sourceProcessId, response);
}
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 1);
browserWrapper->CallbackRegistry->Deregister(jsCallbackId);
handled = true;
}
return handled;
};
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* 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 HEADER
#include "ktx-loader.h"
// EXTERNAL INCLUDES
#include <memory.h>
#include <stdio.h>
#include <stdint.h>
#include <dali/integration-api/debug.h>
#include <dali/devel-api/adaptor-framework/file-stream.h>
namespace PbrDemo
{
struct KtxFileHeader
{
char identifier[12];
uint32_t endianness;
uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
uint32_t glTypeSize;
uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
/**
* Convert KTX format to Dali::Pixel::Format
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
{
switch( ktxPixelFormat )
{
case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4_KHR
{
format = Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
break;
}
case 0x881B:// GL_RGB16F
{
format = Dali::Pixel::RGB16F;
break;
}
case 0x8815: // GL_RGB32F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8C3A: // GL_R11F_G11F_B10F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8D7C: // GL_RGBA8UI
{
format = Dali::Pixel::RGBA8888;
break;
}
case 0x8D7D: // GL_RGB8UI
{
format = Dali::Pixel::RGB888;
break;
}
default:
{
return false;
}
}
return true;
}
bool LoadCubeMapFromKtxFile( const std::string& path, CubeData& cubedata )
{
Dali::FileStream fileStream( path, Dali::FileStream::READ | Dali::FileStream::BINARY );
FILE* fp = fileStream.GetFile();
if( NULL == fp )
{
return false;
}
KtxFileHeader header;
int result = fread(&header,1,sizeof(KtxFileHeader),fp);
if( 0 == result )
{
return false;
}
long lSize = 0;
// Skip the key-values:
const long int imageSizeOffset = sizeof(KtxFileHeader) + header.bytesOfKeyValueData;
if( fseek(fp, 0, SEEK_END) )
{
return false;
}
lSize = ftell(fp);
if( lSize == -1L )
{
return false;
}
lSize -= imageSizeOffset;
rewind(fp);
if( fseek(fp, imageSizeOffset, SEEK_SET) )
{
return false;
}
cubedata.img.resize(header.numberOfFaces);
for(unsigned int face=0; face < header.numberOfFaces; ++face) //array_element must be 0 or 1
{
cubedata.img[face].resize(header.numberOfMipmapLevels);
}
unsigned char* buffer= reinterpret_cast<unsigned char*>( malloc( lSize ) );
unsigned char* img[6];
unsigned int imgSize[6];
unsigned char* imgPointer = buffer;
result = fread(buffer,1,lSize,fp);
if( 0 == result )
{
free( buffer );
return false;
}
if( 0 == header.numberOfMipmapLevels )
{
header.numberOfMipmapLevels = 1u;
}
if( 0 == header.numberOfArrayElements )
{
header.numberOfArrayElements = 1u;
}
if( 0 == header.pixelDepth )
{
header.pixelDepth = 1u;
}
if( 0 == header.pixelHeight )
{
header.pixelHeight = 1u;
}
Dali::Pixel::Format daliformat = Pixel::RGB888;
ConvertPixelFormat(header.glInternalFormat, daliformat);
for( unsigned int mipmapLevel = 0; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel )
{
long int byteSize = 0;
int imageSize;
memcpy(&imageSize,imgPointer,sizeof(unsigned int));
imgPointer += 4u;
for(unsigned int arrayElement=0; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1
{
for(unsigned int face=0; face < header.numberOfFaces; ++face)
{
byteSize = imageSize;
if(byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
img[face] = reinterpret_cast<unsigned char*>( malloc( byteSize ) ); // resources will be freed when the PixelData is destroyed.
memcpy(img[face],imgPointer,byteSize);
imgSize[face] = byteSize;
imgPointer += byteSize;
cubedata.img[face][mipmapLevel] = PixelData::New( img[face], imgSize[face], header.pixelWidth , header.pixelHeight , daliformat, PixelData::FREE );
}
}
header.pixelHeight/=2u;
header.pixelWidth/=2u;
}
free(buffer);
return true;
}
} // namespace PbrDemo
<commit_msg>Fixed SVACE issues in ktx-loader.cpp + general maintenance.<commit_after>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* 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 HEADER
#include "ktx-loader.h"
// EXTERNAL INCLUDES
#include <memory.h>
#include <stdio.h>
#include <stdint.h>
#include <dali/integration-api/debug.h>
#include <dali/devel-api/adaptor-framework/file-stream.h>
namespace PbrDemo
{
struct KtxFileHeader
{
char identifier[12];
uint32_t endianness;
uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
uint32_t glTypeSize;
uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
/**
* Convert KTX format to Dali::Pixel::Format
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
{
switch( ktxPixelFormat )
{
case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4_KHR
{
format = Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
break;
}
case 0x881B:// GL_RGB16F
{
format = Dali::Pixel::RGB16F;
break;
}
case 0x8815: // GL_RGB32F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8C3A: // GL_R11F_G11F_B10F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8D7C: // GL_RGBA8UI
{
format = Dali::Pixel::RGBA8888;
break;
}
case 0x8D7D: // GL_RGB8UI
{
format = Dali::Pixel::RGB888;
break;
}
default:
{
return false;
}
}
return true;
}
bool LoadCubeMapFromKtxFile( const std::string& path, CubeData& cubedata )
{
std::unique_ptr<FILE, void(*)(FILE*)> fp(fopen(path.c_str(), "rb"), [](FILE* fp) {
if (fp)
{
fclose(fp);
}
});
if (!fp)
{
return false;
}
KtxFileHeader header;
int result = fread(&header, sizeof(KtxFileHeader), 1u, fp.get());
if (0 == result)
{
return false;
}
// Skip the key-values:
if (fseek(fp.get(), header.bytesOfKeyValueData, SEEK_CUR))
{
return false;
}
cubedata.img.resize(header.numberOfFaces);
for (unsigned int face = 0; face < header.numberOfFaces; ++face) //array_element must be 0 or 1
{
cubedata.img[face].resize(header.numberOfMipmapLevels);
}
if (0 == header.numberOfMipmapLevels)
{
header.numberOfMipmapLevels = 1u;
}
if (0 == header.numberOfArrayElements)
{
header.numberOfArrayElements = 1u;
}
if (0 == header.pixelDepth)
{
header.pixelDepth = 1u;
}
if (0 == header.pixelHeight)
{
header.pixelHeight = 1u;
}
Dali::Pixel::Format daliformat = Pixel::RGB888;
ConvertPixelFormat(header.glInternalFormat, daliformat);
for (unsigned int mipmapLevel = 0; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
{
uint32_t byteSize = 0;
if (fread(&byteSize, sizeof(byteSize), 1u, fp.get()) != 1)
{
return false;
}
if (0 != byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
for (unsigned int arrayElement = 0; arrayElement < header.numberOfArrayElements; ++arrayElement) // arrayElement must be 0 or 1
{
for (unsigned int face = 0; face < header.numberOfFaces; ++face)
{
std::unique_ptr<uint8_t, void(*)(void*)> img(static_cast<unsigned char*>(malloc(byteSize)), free); // resources will be freed when the PixelData is destroyed.
if (fread(img.get(), byteSize, 1u, fp.get()) != 1)
{
return false;
}
cubedata.img[face][mipmapLevel] = PixelData::New(img.release(), byteSize, header.pixelWidth, header.pixelHeight, daliformat, PixelData::FREE);
}
}
header.pixelHeight /= 2u;
header.pixelWidth /= 2u;
}
return true;
}
} // namespace PbrDemo
<|endoftext|> |
<commit_before>#ifndef FSLUTIL##NAMESPACE_NAME!##_##CLASS_NAME!##_HPP
#define FSLUTIL##NAMESPACE_NAME!##_##CLASS_NAME!##_HPP
/****************************************************************************************************************************************************
* Copyright (c) 2016 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the Freescale Semiconductor, 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 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.
*
****************************************************************************************************************************************************/
// ##AG_TOOL_STATEMENT##
// Auto generation template based on RapidOpenCL https://github.com/Unarmed1000/RapidOpenCL with permission.
#include <FslUtil##NAMESPACE_NAME##/Common.hpp>
#include <FslUtil##NAMESPACE_NAME##/CustomTypes.hpp>
#include <FslUtil##NAMESPACE_NAME##/Util.hpp>##ADDITIONAL_INCLUDES##
#include <FslBase/Attributes.hpp>
#include <CL/cl.h>
#include <cassert>
namespace Fsl
{
namespace OpenCL
{
// This object is movable so it can be thought of as behaving in the same was as a unique_ptr and is compatible with std containers
class ##CLASS_NAME##
{##CLASS_ADDITIONAL_MEMBER_VARIABLES##
##RESOURCE_TYPE## ##RESOURCE_MEMBER_NAME##;
public:
##CLASS_NAME##(const ##CLASS_NAME##&) = delete;
##CLASS_NAME##& operator=(const ##CLASS_NAME##&) = delete;
//! @brief Move assignment operator
##CLASS_NAME##& operator=(##CLASS_NAME##&& other)
{
if (this != &other)
{
// Free existing resources then transfer the content of other to this one and fill other with default values
if (IsValid())
Reset();
// Claim ownership here##MOVE_ASSIGNMENT_CLAIM_MEMBERS##
// Remove the data from other##MOVE_ASSIGNMENT_INVALIDATE_MEMBERS##
}
return *this;
}
//! @brief Move constructor
##CLASS_NAME##(##CLASS_NAME##&& other)##MOVE_CONSTRUCTOR_MEMBER_INITIALIZATION##
{
// Remove the data from other##MOVE_CONSTRUCTOR_INVALIDATE_MEMBERS##
}
//! @brief Create a 'invalid' instance (use Reset to populate it)
##CLASS_NAME##()##DEFAULT_CONSTRUCTOR_MEMBER_INITIALIZATION##
{
}
//! @brief Assume control of the ##CLASS_NAME## (this object becomes responsible for releasing it)
explicit ##CLASS_NAME##(##MEMBER_PARAMETERS##)
: ##CLASS_NAME##()
{
Reset(##MEMBER_PARAMETER_NAMES##);
}
##CLASS_EXTRA_CONSTRUCTORS_HEADER##
~##CLASS_NAME##()
{
Reset();
}
//! @brief returns the managed handle and releases the ownership.
##RESOURCE_TYPE## Release() FSL_FUNC_POSTFIX_WARN_UNUSED_RESULT
{
const auto resource = ##RESOURCE_MEMBER_NAME##;##RESET_INVALIDATE_MEMBERS##
return resource;
}
//! @brief Destroys any owned resources and resets the object to its default state.
void Reset()
{
if (! IsValid())
return;
##RESET_MEMBER_ASSERTIONS##
##DESTROY_FUNCTION##(##DESTROY_FUNCTION_ARGUMENTS##);##RESET_INVALIDATE_MEMBERS##
}
//! @brief Destroys any owned resources and assume control of the ##CLASS_NAME## (this object becomes responsible for releasing it)
void Reset(##MEMBER_PARAMETERS##)
{
if (IsValid())
Reset();
##RESET_SET_MEMBERS_NORMAL##
}
##CLASS_EXTRA_RESET_METHODS_HEADER####CLASS_ADDITIONAL_GET_MEMBER_VARIABLE_METHODS##
//! @brief Get the associated resource handle
##RESOURCE_TYPE## Get() const
{
return ##RESOURCE_MEMBER_NAME##;
}
//! @brief Get a pointer to the associated resource handle
const ##RESOURCE_TYPE##* GetPointer() const
{
return &##RESOURCE_MEMBER_NAME##;
}
//! @brief Check if this object contains a valid resource
inline bool IsValid() const
{
return ##RESOURCE_MEMBER_NAME## != ##DEFAULT_VALUE##;
}
};
}
}
#endif
<commit_msg>Removed unnecessary spaces from template.<commit_after>#ifndef FSLUTIL##NAMESPACE_NAME!##_##CLASS_NAME!##_HPP
#define FSLUTIL##NAMESPACE_NAME!##_##CLASS_NAME!##_HPP
/****************************************************************************************************************************************************
* Copyright (c) 2016 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the Freescale Semiconductor, 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 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.
*
****************************************************************************************************************************************************/
// ##AG_TOOL_STATEMENT##
// Auto generation template based on RapidOpenCL https://github.com/Unarmed1000/RapidOpenCL with permission.
#include <FslUtil##NAMESPACE_NAME##/Common.hpp>
#include <FslUtil##NAMESPACE_NAME##/CustomTypes.hpp>
#include <FslUtil##NAMESPACE_NAME##/Util.hpp>##ADDITIONAL_INCLUDES##
#include <FslBase/Attributes.hpp>
#include <CL/cl.h>
#include <cassert>
namespace Fsl
{
namespace OpenCL
{
// This object is movable so it can be thought of as behaving in the same was as a unique_ptr and is compatible with std containers
class ##CLASS_NAME##
{##CLASS_ADDITIONAL_MEMBER_VARIABLES##
##RESOURCE_TYPE## ##RESOURCE_MEMBER_NAME##;
public:
##CLASS_NAME##(const ##CLASS_NAME##&) = delete;
##CLASS_NAME##& operator=(const ##CLASS_NAME##&) = delete;
//! @brief Move assignment operator
##CLASS_NAME##& operator=(##CLASS_NAME##&& other)
{
if (this != &other)
{
// Free existing resources then transfer the content of other to this one and fill other with default values
if (IsValid())
Reset();
// Claim ownership here##MOVE_ASSIGNMENT_CLAIM_MEMBERS##
// Remove the data from other##MOVE_ASSIGNMENT_INVALIDATE_MEMBERS##
}
return *this;
}
//! @brief Move constructor
##CLASS_NAME##(##CLASS_NAME##&& other)##MOVE_CONSTRUCTOR_MEMBER_INITIALIZATION##
{
// Remove the data from other##MOVE_CONSTRUCTOR_INVALIDATE_MEMBERS##
}
//! @brief Create a 'invalid' instance (use Reset to populate it)
##CLASS_NAME##()##DEFAULT_CONSTRUCTOR_MEMBER_INITIALIZATION##
{
}
//! @brief Assume control of the ##CLASS_NAME## (this object becomes responsible for releasing it)
explicit ##CLASS_NAME##(##MEMBER_PARAMETERS##)
: ##CLASS_NAME##()
{
Reset(##MEMBER_PARAMETER_NAMES##);
}
##CLASS_EXTRA_CONSTRUCTORS_HEADER##
~##CLASS_NAME##()
{
Reset();
}
//! @brief returns the managed handle and releases the ownership.
##RESOURCE_TYPE## Release() FSL_FUNC_POSTFIX_WARN_UNUSED_RESULT
{
const auto resource = ##RESOURCE_MEMBER_NAME##;##RESET_INVALIDATE_MEMBERS##
return resource;
}
//! @brief Destroys any owned resources and resets the object to its default state.
void Reset()
{
if (! IsValid())
return;
##RESET_MEMBER_ASSERTIONS##
##DESTROY_FUNCTION##(##DESTROY_FUNCTION_ARGUMENTS##);##RESET_INVALIDATE_MEMBERS##
}
//! @brief Destroys any owned resources and assume control of the ##CLASS_NAME## (this object becomes responsible for releasing it)
void Reset(##MEMBER_PARAMETERS##)
{
if (IsValid())
Reset();
##RESET_SET_MEMBERS_NORMAL##
}
##CLASS_EXTRA_RESET_METHODS_HEADER####CLASS_ADDITIONAL_GET_MEMBER_VARIABLE_METHODS##
//! @brief Get the associated resource handle
##RESOURCE_TYPE## Get() const
{
return ##RESOURCE_MEMBER_NAME##;
}
//! @brief Get a pointer to the associated resource handle
const ##RESOURCE_TYPE##* GetPointer() const
{
return &##RESOURCE_MEMBER_NAME##;
}
//! @brief Check if this object contains a valid resource
inline bool IsValid() const
{
return ##RESOURCE_MEMBER_NAME## != ##DEFAULT_VALUE##;
}
};
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(ENABLE_GPU)
#include "content/common/gpu/image_transport_surface_linux.h"
// This conflicts with the defines in Xlib.h and must come first.
#include "content/common/gpu/gpu_messages.h"
#include <map>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include "base/callback.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "gpu/command_buffer/service/gpu_scheduler.h"
#include "third_party/angle/include/EGL/egl.h"
#include "third_party/angle/include/EGL/eglext.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/gfx/gl/gl_surface_glx.h"
#include "ui/gfx/surface/accelerated_surface_linux.h"
#if !defined(GL_DEPTH24_STENCIL8)
#define GL_DEPTH24_STENCIL8 0x88F0
#endif
namespace {
// We are backed by an Pbuffer offscreen surface for the purposes of creating a
// context, but use FBOs to render to X Pixmap backed EGLImages.
class EGLImageTransportSurface : public ImageTransportSurface,
public gfx::PbufferGLSurfaceEGL {
public:
explicit EGLImageTransportSurface(GpuCommandBufferStub* stub);
// GLSurface implementation
virtual bool Initialize() OVERRIDE;
virtual void Destroy() OVERRIDE;
virtual bool IsOffscreen() OVERRIDE;
virtual bool SwapBuffers() OVERRIDE;
virtual gfx::Size GetSize() OVERRIDE;
virtual void OnMakeCurrent(gfx::GLContext* context) OVERRIDE;
virtual unsigned int GetBackingFrameBufferObject() OVERRIDE;
protected:
// ImageTransportSurface implementation
virtual void OnSetSurfaceACK(uint64 surface_id) OVERRIDE;
virtual void OnBuffersSwappedACK() OVERRIDE;
virtual void Resize(gfx::Size size) OVERRIDE;
private:
virtual ~EGLImageTransportSurface() OVERRIDE;
void ReleaseSurface(scoped_refptr<AcceleratedSurface>& surface);
uint32 fbo_id_;
uint32 depth_id_;
uint32 stencil_id_;
gfx::Size buffer_size_;
bool depth24_stencil8_supported_;
scoped_refptr<AcceleratedSurface> back_surface_;
scoped_refptr<AcceleratedSurface> front_surface_;
DISALLOW_COPY_AND_ASSIGN(EGLImageTransportSurface);
};
// We are backed by an Pbuffer offscreen surface for the purposes of creating a
// context, but use FBOs to render to X Pixmap backed EGLImages.
class GLXImageTransportSurface : public ImageTransportSurface,
public gfx::NativeViewGLSurfaceGLX {
public:
explicit GLXImageTransportSurface(GpuCommandBufferStub* stub);
// gfx::GLSurface implementation:
virtual bool Initialize() OVERRIDE;
virtual void Destroy() OVERRIDE;
virtual bool SwapBuffers() OVERRIDE;
virtual gfx::Size GetSize() OVERRIDE;
protected:
// ImageTransportSurface implementation:
void OnSetSurfaceACK(uint64 surface_id) OVERRIDE;
void OnBuffersSwappedACK() OVERRIDE;
void Resize(gfx::Size size) OVERRIDE;
private:
virtual ~GLXImageTransportSurface();
// Tell the browser to release the surface.
void ReleaseSurface();
XID dummy_parent_;
gfx::Size size_;
// Whether or not the image has been bound on the browser side.
bool bound_;
DISALLOW_COPY_AND_ASSIGN(GLXImageTransportSurface);
};
EGLImageTransportSurface::EGLImageTransportSurface(GpuCommandBufferStub* stub)
: ImageTransportSurface(stub),
gfx::PbufferGLSurfaceEGL(false, gfx::Size(1, 1)),
fbo_id_(0),
depth_id_(0),
stencil_id_(0),
depth24_stencil8_supported_(false) {
}
EGLImageTransportSurface::~EGLImageTransportSurface() {
}
bool EGLImageTransportSurface::Initialize() {
if (!ImageTransportSurface::Initialize())
return false;
return PbufferGLSurfaceEGL::Initialize();
}
void EGLImageTransportSurface::Destroy() {
if (depth_id_) {
glDeleteRenderbuffersEXT(1, &depth_id_);
depth_id_ = 0;
}
if (stencil_id_) {
glDeleteRenderbuffersEXT(1, &stencil_id_);
stencil_id_ = 0;
}
if (back_surface_.get())
ReleaseSurface(back_surface_);
if (front_surface_.get())
ReleaseSurface(front_surface_);
ImageTransportSurface::Destroy();
PbufferGLSurfaceEGL::Destroy();
}
bool EGLImageTransportSurface::IsOffscreen() {
return false;
}
void EGLImageTransportSurface::OnMakeCurrent(gfx::GLContext* context) {
if (fbo_id_)
return;
depth24_stencil8_supported_ =
context->HasExtension("GL_OES_packed_depth_stencil");
glGenFramebuffersEXT(1, &fbo_id_);
glBindFramebufferEXT(GL_FRAMEBUFFER, fbo_id_);
Resize(gfx::Size(1, 1));
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOG(ERROR) << "Framebuffer incomplete.";
}
}
unsigned int EGLImageTransportSurface::GetBackingFrameBufferObject() {
return fbo_id_;
}
void EGLImageTransportSurface::ReleaseSurface(
scoped_refptr<AcceleratedSurface>& surface) {
if (surface.get()) {
GpuHostMsg_AcceleratedSurfaceRelease_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.identifier = back_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
surface = NULL;
}
}
void EGLImageTransportSurface::Resize(gfx::Size size) {
if (back_surface_.get())
ReleaseSurface(back_surface_);
if (depth_id_ && buffer_size_ != size) {
glDeleteRenderbuffersEXT(1, &depth_id_);
if (stencil_id_)
glDeleteRenderbuffersEXT(1, &stencil_id_);
depth_id_ = stencil_id_ = 0;
}
if (!depth_id_) {
if (depth24_stencil8_supported_) {
glGenRenderbuffersEXT(1, &depth_id_);
glBindRenderbufferEXT(GL_RENDERBUFFER, depth_id_);
glRenderbufferStorageEXT(GL_RENDERBUFFER,
GL_DEPTH24_STENCIL8,
size.width(),
size.height());
} else {
glGenRenderbuffersEXT(1, &depth_id_);
glBindRenderbufferEXT(GL_RENDERBUFFER, depth_id_);
glRenderbufferStorageEXT(GL_RENDERBUFFER,
GL_DEPTH_COMPONENT16,
size.width(),
size.height());
glGenRenderbuffersEXT(1, &stencil_id_);
glBindRenderbufferEXT(GL_RENDERBUFFER, stencil_id_);
glRenderbufferStorageEXT(GL_RENDERBUFFER,
GL_STENCIL_INDEX8,
size.width(),
size.height());
}
glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER,
depth_id_);
if (stencil_id_)
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER,
stencil_id_);
buffer_size_ = size;
}
back_surface_ = new AcceleratedSurface(size);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
back_surface_->texture(),
0);
glFlush();
GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.width = size.width();
params.height = size.height();
params.identifier = back_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceSetIOSurface(params));
scheduler()->SetScheduled(false);
}
bool EGLImageTransportSurface::SwapBuffers() {
front_surface_.swap(back_surface_);
DCHECK_NE(front_surface_.get(), static_cast<AcceleratedSurface*>(NULL));
glFlush();
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.surface_id = front_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
gfx::Size expected_size = front_surface_->size();
if (!back_surface_.get() || back_surface_->size() != expected_size) {
Resize(expected_size);
} else {
glFramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
back_surface_->texture(),
0);
}
scheduler()->SetScheduled(false);
return true;
}
gfx::Size EGLImageTransportSurface::GetSize() {
return back_surface_->size();
}
void EGLImageTransportSurface::OnSetSurfaceACK(
uint64 surface_id) {
DCHECK_EQ(back_surface_->pixmap(), surface_id);
scheduler()->SetScheduled(true);
}
void EGLImageTransportSurface::OnBuffersSwappedACK() {
scheduler()->SetScheduled(true);
}
GLXImageTransportSurface::GLXImageTransportSurface(GpuCommandBufferStub* stub)
: ImageTransportSurface(stub),
gfx::NativeViewGLSurfaceGLX(),
dummy_parent_(0),
size_(1, 1),
bound_(false) {
}
GLXImageTransportSurface::~GLXImageTransportSurface() {
}
bool GLXImageTransportSurface::Initialize() {
// Create a dummy window to host the real window.
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XSetWindowAttributes swa;
swa.event_mask = StructureNotifyMask;
swa.override_redirect = True;
dummy_parent_ = XCreateWindow(
dpy,
RootWindow(dpy, DefaultScreen(dpy)), // parent
-100, -100, 1, 1,
0, // border width
CopyFromParent, // depth
InputOutput,
CopyFromParent, // visual
CWEventMask | CWOverrideRedirect, &swa);
XMapWindow(dpy, dummy_parent_);
swa.event_mask = StructureNotifyMask;
swa.override_redirect = false;
window_ = XCreateWindow(dpy,
dummy_parent_,
0, 0, size_.width(), size_.height(),
0, // border width
CopyFromParent, // depth
InputOutput,
CopyFromParent, // visual
CWEventMask, &swa);
XMapWindow(dpy, window_);
while (1) {
XEvent event;
XNextEvent(dpy, &event);
if (event.type == MapNotify && event.xmap.window == window_)
break;
}
// Manual setting must be used to avoid unnecessary rendering by server.
XCompositeRedirectWindow(dpy, window_, CompositeRedirectManual);
Resize(size_);
if (!ImageTransportSurface::Initialize())
return false;
return gfx::NativeViewGLSurfaceGLX::Initialize();
}
void GLXImageTransportSurface::Destroy() {
if (bound_)
ReleaseSurface();
if (window_) {
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XDestroyWindow(dpy, window_);
XDestroyWindow(dpy, dummy_parent_);
}
ImageTransportSurface::Destroy();
gfx::NativeViewGLSurfaceGLX::Destroy();
}
void GLXImageTransportSurface::ReleaseSurface() {
DCHECK(bound_);
GpuHostMsg_AcceleratedSurfaceRelease_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.identifier = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
}
void GLXImageTransportSurface::Resize(gfx::Size size) {
size_ = size;
if (bound_) {
ReleaseSurface();
bound_ = false;
}
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XResizeWindow(dpy, window_, size_.width(), size_.height());
XFlush(dpy);
GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.width = size_.width();
params.height = size_.height();
params.identifier = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceSetIOSurface(params));
scheduler()->SetScheduled(false);
}
bool GLXImageTransportSurface::SwapBuffers() {
gfx::NativeViewGLSurfaceGLX::SwapBuffers();
glFlush();
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.surface_id = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return true;
}
gfx::Size GLXImageTransportSurface::GetSize() {
return size_;
}
void GLXImageTransportSurface::OnSetSurfaceACK(
uint64 surface_id) {
DCHECK(!bound_);
bound_ = true;
scheduler()->SetScheduled(true);
}
void GLXImageTransportSurface::OnBuffersSwappedACK() {
}
} // namespace
ImageTransportSurface::ImageTransportSurface(GpuCommandBufferStub* stub)
: stub_(stub) {
GpuChannelManager* gpu_channel_manager
= stub_->channel()->gpu_channel_manager();
route_id_ = gpu_channel_manager->GenerateRouteID();
gpu_channel_manager->AddRoute(route_id_, this);
}
ImageTransportSurface::~ImageTransportSurface() {
GpuChannelManager* gpu_channel_manager
= stub_->channel()->gpu_channel_manager();
gpu_channel_manager->RemoveRoute(route_id_);
}
bool ImageTransportSurface::Initialize() {
scheduler()->SetResizeCallback(
NewCallback(this, &ImageTransportSurface::Resize));
return true;
}
void ImageTransportSurface::Destroy() {
scheduler()->SetResizeCallback(NULL);
}
bool ImageTransportSurface::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ImageTransportSurface, message)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_SetSurfaceACK,
OnSetSurfaceACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_BuffersSwappedACK,
OnBuffersSwappedACK)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool ImageTransportSurface::Send(IPC::Message* message) {
GpuChannelManager* gpu_channel_manager =
stub_->channel()->gpu_channel_manager();
return gpu_channel_manager->Send(message);
}
gpu::GpuScheduler* ImageTransportSurface::scheduler() {
return stub_->scheduler();
}
// static
scoped_refptr<gfx::GLSurface> ImageTransportSurface::CreateSurface(
GpuCommandBufferStub* stub) {
scoped_refptr<gfx::GLSurface> surface;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationDesktopGL:
surface = new GLXImageTransportSurface(stub);
break;
case gfx::kGLImplementationEGLGLES2:
surface = new EGLImageTransportSurface(stub);
break;
default:
NOTREACHED();
return NULL;
}
if (surface->Initialize())
return surface;
else
return NULL;
}
#endif // defined(USE_GPU)
<commit_msg>Get rid of unused depth and stencil buffers.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(ENABLE_GPU)
#include "content/common/gpu/image_transport_surface_linux.h"
// This conflicts with the defines in Xlib.h and must come first.
#include "content/common/gpu/gpu_messages.h"
#include <map>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include "base/callback.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "gpu/command_buffer/service/gpu_scheduler.h"
#include "third_party/angle/include/EGL/egl.h"
#include "third_party/angle/include/EGL/eglext.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/gfx/gl/gl_surface_glx.h"
#include "ui/gfx/surface/accelerated_surface_linux.h"
namespace {
// We are backed by an Pbuffer offscreen surface for the purposes of creating a
// context, but use FBOs to render to X Pixmap backed EGLImages.
class EGLImageTransportSurface : public ImageTransportSurface,
public gfx::PbufferGLSurfaceEGL {
public:
explicit EGLImageTransportSurface(GpuCommandBufferStub* stub);
// GLSurface implementation
virtual bool Initialize() OVERRIDE;
virtual void Destroy() OVERRIDE;
virtual bool IsOffscreen() OVERRIDE;
virtual bool SwapBuffers() OVERRIDE;
virtual gfx::Size GetSize() OVERRIDE;
virtual void OnMakeCurrent(gfx::GLContext* context) OVERRIDE;
virtual unsigned int GetBackingFrameBufferObject() OVERRIDE;
protected:
// ImageTransportSurface implementation
virtual void OnSetSurfaceACK(uint64 surface_id) OVERRIDE;
virtual void OnBuffersSwappedACK() OVERRIDE;
virtual void Resize(gfx::Size size) OVERRIDE;
private:
virtual ~EGLImageTransportSurface() OVERRIDE;
void ReleaseSurface(scoped_refptr<AcceleratedSurface>& surface);
uint32 fbo_id_;
scoped_refptr<AcceleratedSurface> back_surface_;
scoped_refptr<AcceleratedSurface> front_surface_;
DISALLOW_COPY_AND_ASSIGN(EGLImageTransportSurface);
};
// We are backed by an Pbuffer offscreen surface for the purposes of creating a
// context, but use FBOs to render to X Pixmap backed EGLImages.
class GLXImageTransportSurface : public ImageTransportSurface,
public gfx::NativeViewGLSurfaceGLX {
public:
explicit GLXImageTransportSurface(GpuCommandBufferStub* stub);
// gfx::GLSurface implementation:
virtual bool Initialize() OVERRIDE;
virtual void Destroy() OVERRIDE;
virtual bool SwapBuffers() OVERRIDE;
virtual gfx::Size GetSize() OVERRIDE;
protected:
// ImageTransportSurface implementation:
void OnSetSurfaceACK(uint64 surface_id) OVERRIDE;
void OnBuffersSwappedACK() OVERRIDE;
void Resize(gfx::Size size) OVERRIDE;
private:
virtual ~GLXImageTransportSurface();
// Tell the browser to release the surface.
void ReleaseSurface();
XID dummy_parent_;
gfx::Size size_;
// Whether or not the image has been bound on the browser side.
bool bound_;
DISALLOW_COPY_AND_ASSIGN(GLXImageTransportSurface);
};
EGLImageTransportSurface::EGLImageTransportSurface(GpuCommandBufferStub* stub)
: ImageTransportSurface(stub),
gfx::PbufferGLSurfaceEGL(false, gfx::Size(1, 1)),
fbo_id_(0) {
}
EGLImageTransportSurface::~EGLImageTransportSurface() {
}
bool EGLImageTransportSurface::Initialize() {
if (!ImageTransportSurface::Initialize())
return false;
return PbufferGLSurfaceEGL::Initialize();
}
void EGLImageTransportSurface::Destroy() {
if (back_surface_.get())
ReleaseSurface(back_surface_);
if (front_surface_.get())
ReleaseSurface(front_surface_);
ImageTransportSurface::Destroy();
PbufferGLSurfaceEGL::Destroy();
}
bool EGLImageTransportSurface::IsOffscreen() {
return false;
}
void EGLImageTransportSurface::OnMakeCurrent(gfx::GLContext* context) {
if (fbo_id_)
return;
glGenFramebuffersEXT(1, &fbo_id_);
glBindFramebufferEXT(GL_FRAMEBUFFER, fbo_id_);
Resize(gfx::Size(1, 1));
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOG(ERROR) << "Framebuffer incomplete.";
}
}
unsigned int EGLImageTransportSurface::GetBackingFrameBufferObject() {
return fbo_id_;
}
void EGLImageTransportSurface::ReleaseSurface(
scoped_refptr<AcceleratedSurface>& surface) {
if (surface.get()) {
GpuHostMsg_AcceleratedSurfaceRelease_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.identifier = back_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
surface = NULL;
}
}
void EGLImageTransportSurface::Resize(gfx::Size size) {
if (back_surface_.get())
ReleaseSurface(back_surface_);
back_surface_ = new AcceleratedSurface(size);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
back_surface_->texture(),
0);
glFlush();
GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.width = size.width();
params.height = size.height();
params.identifier = back_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceSetIOSurface(params));
scheduler()->SetScheduled(false);
}
bool EGLImageTransportSurface::SwapBuffers() {
front_surface_.swap(back_surface_);
DCHECK_NE(front_surface_.get(), static_cast<AcceleratedSurface*>(NULL));
glFlush();
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.surface_id = front_surface_->pixmap();
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
gfx::Size expected_size = front_surface_->size();
if (!back_surface_.get() || back_surface_->size() != expected_size) {
Resize(expected_size);
} else {
glFramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
back_surface_->texture(),
0);
}
scheduler()->SetScheduled(false);
return true;
}
gfx::Size EGLImageTransportSurface::GetSize() {
return back_surface_->size();
}
void EGLImageTransportSurface::OnSetSurfaceACK(
uint64 surface_id) {
DCHECK_EQ(back_surface_->pixmap(), surface_id);
scheduler()->SetScheduled(true);
}
void EGLImageTransportSurface::OnBuffersSwappedACK() {
scheduler()->SetScheduled(true);
}
GLXImageTransportSurface::GLXImageTransportSurface(GpuCommandBufferStub* stub)
: ImageTransportSurface(stub),
gfx::NativeViewGLSurfaceGLX(),
dummy_parent_(0),
size_(1, 1),
bound_(false) {
}
GLXImageTransportSurface::~GLXImageTransportSurface() {
}
bool GLXImageTransportSurface::Initialize() {
// Create a dummy window to host the real window.
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XSetWindowAttributes swa;
swa.event_mask = StructureNotifyMask;
swa.override_redirect = True;
dummy_parent_ = XCreateWindow(
dpy,
RootWindow(dpy, DefaultScreen(dpy)), // parent
-100, -100, 1, 1,
0, // border width
CopyFromParent, // depth
InputOutput,
CopyFromParent, // visual
CWEventMask | CWOverrideRedirect, &swa);
XMapWindow(dpy, dummy_parent_);
swa.event_mask = StructureNotifyMask;
swa.override_redirect = false;
window_ = XCreateWindow(dpy,
dummy_parent_,
0, 0, size_.width(), size_.height(),
0, // border width
CopyFromParent, // depth
InputOutput,
CopyFromParent, // visual
CWEventMask, &swa);
XMapWindow(dpy, window_);
while (1) {
XEvent event;
XNextEvent(dpy, &event);
if (event.type == MapNotify && event.xmap.window == window_)
break;
}
// Manual setting must be used to avoid unnecessary rendering by server.
XCompositeRedirectWindow(dpy, window_, CompositeRedirectManual);
Resize(size_);
if (!ImageTransportSurface::Initialize())
return false;
return gfx::NativeViewGLSurfaceGLX::Initialize();
}
void GLXImageTransportSurface::Destroy() {
if (bound_)
ReleaseSurface();
if (window_) {
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XDestroyWindow(dpy, window_);
XDestroyWindow(dpy, dummy_parent_);
}
ImageTransportSurface::Destroy();
gfx::NativeViewGLSurfaceGLX::Destroy();
}
void GLXImageTransportSurface::ReleaseSurface() {
DCHECK(bound_);
GpuHostMsg_AcceleratedSurfaceRelease_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.identifier = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
}
void GLXImageTransportSurface::Resize(gfx::Size size) {
size_ = size;
if (bound_) {
ReleaseSurface();
bound_ = false;
}
Display* dpy = gfx::GLSurfaceGLX::GetDisplay();
XResizeWindow(dpy, window_, size_.width(), size_.height());
XFlush(dpy);
GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.width = size_.width();
params.height = size_.height();
params.identifier = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceSetIOSurface(params));
scheduler()->SetScheduled(false);
}
bool GLXImageTransportSurface::SwapBuffers() {
gfx::NativeViewGLSurfaceGLX::SwapBuffers();
glFlush();
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.renderer_id = stub()->renderer_id();
params.render_view_id = stub()->render_view_id();
params.surface_id = window_;
params.route_id = route_id();
Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return true;
}
gfx::Size GLXImageTransportSurface::GetSize() {
return size_;
}
void GLXImageTransportSurface::OnSetSurfaceACK(
uint64 surface_id) {
DCHECK(!bound_);
bound_ = true;
scheduler()->SetScheduled(true);
}
void GLXImageTransportSurface::OnBuffersSwappedACK() {
}
} // namespace
ImageTransportSurface::ImageTransportSurface(GpuCommandBufferStub* stub)
: stub_(stub) {
GpuChannelManager* gpu_channel_manager
= stub_->channel()->gpu_channel_manager();
route_id_ = gpu_channel_manager->GenerateRouteID();
gpu_channel_manager->AddRoute(route_id_, this);
}
ImageTransportSurface::~ImageTransportSurface() {
GpuChannelManager* gpu_channel_manager
= stub_->channel()->gpu_channel_manager();
gpu_channel_manager->RemoveRoute(route_id_);
}
bool ImageTransportSurface::Initialize() {
scheduler()->SetResizeCallback(
NewCallback(this, &ImageTransportSurface::Resize));
return true;
}
void ImageTransportSurface::Destroy() {
scheduler()->SetResizeCallback(NULL);
}
bool ImageTransportSurface::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ImageTransportSurface, message)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_SetSurfaceACK,
OnSetSurfaceACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_BuffersSwappedACK,
OnBuffersSwappedACK)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool ImageTransportSurface::Send(IPC::Message* message) {
GpuChannelManager* gpu_channel_manager =
stub_->channel()->gpu_channel_manager();
return gpu_channel_manager->Send(message);
}
gpu::GpuScheduler* ImageTransportSurface::scheduler() {
return stub_->scheduler();
}
// static
scoped_refptr<gfx::GLSurface> ImageTransportSurface::CreateSurface(
GpuCommandBufferStub* stub) {
scoped_refptr<gfx::GLSurface> surface;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationDesktopGL:
surface = new GLXImageTransportSurface(stub);
break;
case gfx::kGLImplementationEGLGLES2:
surface = new EGLImageTransportSurface(stub);
break;
default:
NOTREACHED();
return NULL;
}
if (surface->Initialize())
return surface;
else
return NULL;
}
#endif // defined(USE_GPU)
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/render_widget_fullscreen_pepper.h"
#include "base/message_loop.h"
#include "content/common/view_messages.h"
#include "content/renderer/gpu/gpu_channel_host.h"
#include "content/renderer/pepper_platform_context_3d_impl.h"
#include "content/renderer/render_thread.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;
namespace {
// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
public:
PepperWidget(webkit::ppapi::PluginInstance* plugin,
RenderWidgetFullscreenPepper* widget)
: plugin_(plugin),
widget_(widget),
cursor_(WebCursorInfo::TypePointer) {
}
virtual ~PepperWidget() {}
// WebWidget API
virtual void close() {
delete this;
}
virtual WebSize size() {
return size_;
}
virtual void willStartLiveResize() {
}
virtual void resize(const WebSize& size) {
size_ = size;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->ViewChanged(plugin_rect, plugin_rect);
widget_->Invalidate();
}
virtual void willEndLiveResize() {
}
#ifndef WEBWIDGET_HAS_ANIMATE_CHANGES
virtual void animate() {
}
#else
virtual void animate(double frameBeginTime) {
}
#endif
virtual void layout() {
}
virtual void paint(WebCanvas* canvas, const WebRect& rect) {
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->Paint(canvas, plugin_rect, rect);
}
virtual void composite(bool finish) {
RendererGLContext* context = widget_->context();
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = context->GetImplementation();
unsigned int texture = plugin_->GetBackingTextureId();
gl->BindTexture(GL_TEXTURE_2D, texture);
gl->DrawArrays(GL_TRIANGLES, 0, 3);
widget_->SwapBuffers();
}
virtual void themeChanged() {
NOTIMPLEMENTED();
}
virtual bool handleInputEvent(const WebInputEvent& event) {
bool result = plugin_->HandleInputEvent(event, &cursor_);
// For normal web pages, WebViewImpl does input event translations and
// generates context menu events. Since we don't have a WebView, we need to
// do the necessary translation ourselves.
if (WebInputEvent::isMouseEventType(event.type)) {
const WebMouseEvent& mouse_event =
reinterpret_cast<const WebMouseEvent&>(event);
bool send_context_menu_event = false;
// On Mac/Linux, we handle it on mouse down.
// On Windows, we handle it on mouse up.
#if defined(OS_WIN)
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseUp &&
mouse_event.button == WebMouseEvent::ButtonRight;
#elif defined(OS_MACOSX)
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseDown &&
(mouse_event.button == WebMouseEvent::ButtonRight ||
(mouse_event.button == WebMouseEvent::ButtonLeft &&
mouse_event.modifiers & WebMouseEvent::ControlKey));
#else
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseDown &&
mouse_event.button == WebMouseEvent::ButtonRight;
#endif
if (send_context_menu_event) {
WebMouseEvent context_menu_event(mouse_event);
context_menu_event.type = WebInputEvent::ContextMenu;
plugin_->HandleInputEvent(context_menu_event, &cursor_);
}
}
return result;
}
virtual void mouseCaptureLost() {
NOTIMPLEMENTED();
}
virtual void setFocus(bool focus) {
NOTIMPLEMENTED();
}
// TODO(piman): figure out IME and implement these if necessary.
virtual bool setComposition(
const WebString& text,
const WebVector<WebCompositionUnderline>& underlines,
int selectionStart,
int selectionEnd) {
return false;
}
virtual bool confirmComposition() {
return false;
}
virtual bool compositionRange(size_t* location, size_t* length) {
return false;
}
virtual bool confirmComposition(const WebString& text) {
return false;
}
virtual WebTextInputType textInputType() {
return WebKit::WebTextInputTypeNone;
}
virtual WebRect caretOrSelectionBounds() {
return WebRect();
}
virtual bool selectionRange(WebPoint& start, WebPoint& end) const {
return false;
}
virtual bool caretOrSelectionRange(size_t* location, size_t* length) {
return false;
}
virtual void setTextDirection(WebTextDirection) {
}
virtual bool isAcceleratedCompositingActive() const {
return widget_->context() && (plugin_->GetBackingTextureId() != 0);
}
private:
scoped_refptr<webkit::ppapi::PluginInstance> plugin_;
RenderWidgetFullscreenPepper* widget_;
WebSize size_;
WebCursorInfo cursor_;
DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};
void DestroyContext(RendererGLContext* context, GLuint program, GLuint buffer) {
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = context->GetImplementation();
if (program)
gl->DeleteProgram(program);
if (buffer)
gl->DeleteBuffers(1, &buffer);
delete context;
}
} // anonymous namespace
// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
int32 opener_id, RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin,
const GURL& active_url) {
DCHECK_NE(MSG_ROUTING_NONE, opener_id);
scoped_refptr<RenderWidgetFullscreenPepper> widget(
new RenderWidgetFullscreenPepper(render_thread, plugin, active_url));
widget->Init(opener_id);
return widget.release();
}
RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin,
const GURL& active_url)
: RenderWidgetFullscreen(render_thread),
active_url_(active_url),
plugin_(plugin),
context_(NULL),
buffer_(0),
program_(0) {
}
RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
if (context_)
DestroyContext(context_, program_, buffer_);
}
void RenderWidgetFullscreenPepper::Invalidate() {
InvalidateRect(gfx::Rect(size_.width(), size_.height()));
}
void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didInvalidateRect(rect);
}
}
void RenderWidgetFullscreenPepper::ScrollRect(
int dx, int dy, const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didScrollRect(dx, dy, rect);
}
}
void RenderWidgetFullscreenPepper::Destroy() {
// This function is called by the plugin instance as it's going away, so reset
// plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
plugin_ = NULL;
Send(new ViewHostMsg_Close(routing_id_));
}
webkit::ppapi::PluginDelegate::PlatformContext3D*
RenderWidgetFullscreenPepper::CreateContext3D() {
if (!context_) {
CreateContext();
}
if (!context_)
return NULL;
return new PlatformContext3DImpl(context_);
}
void RenderWidgetFullscreenPepper::DidInitiatePaint() {
if (plugin_)
plugin_->ViewInitiatedPaint();
}
void RenderWidgetFullscreenPepper::DidFlushPaint() {
if (plugin_)
plugin_->ViewFlushedPaint();
}
void RenderWidgetFullscreenPepper::Close() {
// If the fullscreen window is closed (e.g. user pressed escape), reset to
// normal mode.
if (plugin_)
plugin_->SetFullscreen(false, false);
}
webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
const gfx::Rect& paint_bounds,
TransportDIB** dib,
gfx::Rect* location,
gfx::Rect* clip) {
if (plugin_ &&
plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
location, clip))
return plugin_;
return NULL;
}
void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size,
const gfx::Rect& resizer_rect) {
if (context_) {
gpu::gles2::GLES2Implementation* gl = context_->GetImplementation();
#if defined(OS_MACOSX)
context_->ResizeOnscreen(size);
#else
gl->ResizeCHROMIUM(size.width(), size.height());
#endif
gl->Viewport(0, 0, size.width(), size.height());
}
RenderWidget::OnResize(size, resizer_rect);
}
WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
return new PepperWidget(plugin_, this);
}
bool RenderWidgetFullscreenPepper::SupportsAsynchronousSwapBuffers() {
return context_ != NULL;
}
void RenderWidgetFullscreenPepper::CreateContext() {
DCHECK(!context_);
RenderThread* render_thread = RenderThread::current();
DCHECK(render_thread);
GpuChannelHost* host = render_thread->EstablishGpuChannelSync(
content::CAUSE_FOR_GPU_LAUNCH_RENDERWIDGETFULLSCREENPEPPER_CREATECONTEXT);
if (!host)
return;
const int32 attribs[] = {
RendererGLContext::ALPHA_SIZE, 8,
RendererGLContext::DEPTH_SIZE, 0,
RendererGLContext::STENCIL_SIZE, 0,
RendererGLContext::SAMPLES, 0,
RendererGLContext::SAMPLE_BUFFERS, 0,
RendererGLContext::NONE,
};
context_ = RendererGLContext::CreateViewContext(
host,
routing_id(),
"GL_OES_packed_depth_stencil GL_OES_depth24",
attribs,
active_url_);
if (!context_)
return;
if (!InitContext()) {
DestroyContext(context_, program_, buffer_);
context_ = NULL;
return;
}
context_->SetSwapBuffersCallback(
NewCallback(this,
&RenderWidgetFullscreenPepper::
OnSwapBuffersCompleteByRendererGLContext));
context_->SetContextLostCallback(
NewCallback(this, &RenderWidgetFullscreenPepper::OnLostContext));
}
namespace {
const char kVertexShader[] =
"attribute vec2 in_tex_coord;\n"
"varying vec2 tex_coord;\n"
"void main() {\n"
" gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n"
" in_tex_coord.y * 2. - 1.,\n"
" 0.,\n"
" 1.);\n"
" tex_coord = vec2(in_tex_coord.x, in_tex_coord.y);\n"
"}\n";
const char kFragmentShader[] =
"precision mediump float;\n"
"varying vec2 tex_coord;\n"
"uniform sampler2D in_texture;\n"
"void main() {\n"
" gl_FragColor = texture2D(in_texture, tex_coord);\n"
"}\n";
GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl,
GLenum type,
const char* source) {
GLuint shader = gl->CreateShader(type);
gl->ShaderSource(shader, 1, &source, NULL);
gl->CompileShader(shader);
int status = GL_FALSE;
gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
int size = 0;
gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetShaderInfoLog(shader, size, NULL, log.get());
DLOG(ERROR) << "Compilation failed: " << log.get();
gl->DeleteShader(shader);
shader = 0;
}
return shader;
}
const float kTexCoords[] = {
0.f, 0.f,
0.f, 2.f,
2.f, 0.f,
};
} // anonymous namespace
bool RenderWidgetFullscreenPepper::InitContext() {
gpu::gles2::GLES2Implementation* gl = context_->GetImplementation();
program_ = gl->CreateProgram();
GLuint vertex_shader =
CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader);
if (!vertex_shader)
return false;
gl->AttachShader(program_, vertex_shader);
gl->DeleteShader(vertex_shader);
GLuint fragment_shader =
CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader);
if (!fragment_shader)
return false;
gl->AttachShader(program_, fragment_shader);
gl->DeleteShader(fragment_shader);
gl->BindAttribLocation(program_, 0, "in_tex_coord");
gl->LinkProgram(program_);
int status = GL_FALSE;
gl->GetProgramiv(program_, GL_LINK_STATUS, &status);
if (!status) {
int size = 0;
gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetProgramInfoLog(program_, size, NULL, log.get());
DLOG(ERROR) << "Link failed: " << log.get();
return false;
}
gl->UseProgram(program_);
int texture_location = gl->GetUniformLocation(program_, "in_texture");
gl->Uniform1i(texture_location, 0);
gl->GenBuffers(1, &buffer_);
gl->BindBuffer(GL_ARRAY_BUFFER, buffer_);
gl->BufferData(GL_ARRAY_BUFFER,
sizeof(kTexCoords),
kTexCoords,
GL_STATIC_DRAW);
gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
gl->EnableVertexAttribArray(0);
return true;
}
bool RenderWidgetFullscreenPepper::CheckCompositing() {
bool compositing = webwidget_->isAcceleratedCompositingActive();
if (compositing != is_accelerated_compositing_active_) {
didActivateAcceleratedCompositing(compositing);
}
return compositing;
}
void RenderWidgetFullscreenPepper::SwapBuffers() {
DCHECK(context_);
OnSwapBuffersPosted();
context_->SwapBuffers();
}
void RenderWidgetFullscreenPepper::OnLostContext(
RendererGLContext::ContextLostReason) {
if (!context_)
return;
// Destroy the context later, in case we got called from InitContext for
// example. We still need to reset context_ now so that a new context gets
// created when the plugin recreates its own.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableFunction(DestroyContext, context_, program_, buffer_));
context_ = NULL;
program_ = 0;
buffer_ = 0;
OnSwapBuffersAborted();
}
void RenderWidgetFullscreenPepper::OnSwapBuffersCompleteByRendererGLContext() {
OnSwapBuffersComplete();
}
<commit_msg>Avoid leaking WebWidget instance when closing RenderWidgetFullscreenPepper.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/render_widget_fullscreen_pepper.h"
#include "base/message_loop.h"
#include "content/common/view_messages.h"
#include "content/renderer/gpu/gpu_channel_host.h"
#include "content/renderer/pepper_platform_context_3d_impl.h"
#include "content/renderer/render_thread.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebPoint;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;
namespace {
// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
public:
PepperWidget(webkit::ppapi::PluginInstance* plugin,
RenderWidgetFullscreenPepper* widget)
: plugin_(plugin),
widget_(widget),
cursor_(WebCursorInfo::TypePointer) {
}
virtual ~PepperWidget() {}
// WebWidget API
virtual void close() {
delete this;
}
virtual WebSize size() {
return size_;
}
virtual void willStartLiveResize() {
}
virtual void resize(const WebSize& size) {
size_ = size;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->ViewChanged(plugin_rect, plugin_rect);
widget_->Invalidate();
}
virtual void willEndLiveResize() {
}
#ifndef WEBWIDGET_HAS_ANIMATE_CHANGES
virtual void animate() {
}
#else
virtual void animate(double frameBeginTime) {
}
#endif
virtual void layout() {
}
virtual void paint(WebCanvas* canvas, const WebRect& rect) {
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->Paint(canvas, plugin_rect, rect);
}
virtual void composite(bool finish) {
RendererGLContext* context = widget_->context();
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = context->GetImplementation();
unsigned int texture = plugin_->GetBackingTextureId();
gl->BindTexture(GL_TEXTURE_2D, texture);
gl->DrawArrays(GL_TRIANGLES, 0, 3);
widget_->SwapBuffers();
}
virtual void themeChanged() {
NOTIMPLEMENTED();
}
virtual bool handleInputEvent(const WebInputEvent& event) {
bool result = plugin_->HandleInputEvent(event, &cursor_);
// For normal web pages, WebViewImpl does input event translations and
// generates context menu events. Since we don't have a WebView, we need to
// do the necessary translation ourselves.
if (WebInputEvent::isMouseEventType(event.type)) {
const WebMouseEvent& mouse_event =
reinterpret_cast<const WebMouseEvent&>(event);
bool send_context_menu_event = false;
// On Mac/Linux, we handle it on mouse down.
// On Windows, we handle it on mouse up.
#if defined(OS_WIN)
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseUp &&
mouse_event.button == WebMouseEvent::ButtonRight;
#elif defined(OS_MACOSX)
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseDown &&
(mouse_event.button == WebMouseEvent::ButtonRight ||
(mouse_event.button == WebMouseEvent::ButtonLeft &&
mouse_event.modifiers & WebMouseEvent::ControlKey));
#else
send_context_menu_event =
mouse_event.type == WebInputEvent::MouseDown &&
mouse_event.button == WebMouseEvent::ButtonRight;
#endif
if (send_context_menu_event) {
WebMouseEvent context_menu_event(mouse_event);
context_menu_event.type = WebInputEvent::ContextMenu;
plugin_->HandleInputEvent(context_menu_event, &cursor_);
}
}
return result;
}
virtual void mouseCaptureLost() {
NOTIMPLEMENTED();
}
virtual void setFocus(bool focus) {
NOTIMPLEMENTED();
}
// TODO(piman): figure out IME and implement these if necessary.
virtual bool setComposition(
const WebString& text,
const WebVector<WebCompositionUnderline>& underlines,
int selectionStart,
int selectionEnd) {
return false;
}
virtual bool confirmComposition() {
return false;
}
virtual bool compositionRange(size_t* location, size_t* length) {
return false;
}
virtual bool confirmComposition(const WebString& text) {
return false;
}
virtual WebTextInputType textInputType() {
return WebKit::WebTextInputTypeNone;
}
virtual WebRect caretOrSelectionBounds() {
return WebRect();
}
virtual bool selectionRange(WebPoint& start, WebPoint& end) const {
return false;
}
virtual bool caretOrSelectionRange(size_t* location, size_t* length) {
return false;
}
virtual void setTextDirection(WebTextDirection) {
}
virtual bool isAcceleratedCompositingActive() const {
return widget_->context() && (plugin_->GetBackingTextureId() != 0);
}
private:
scoped_refptr<webkit::ppapi::PluginInstance> plugin_;
RenderWidgetFullscreenPepper* widget_;
WebSize size_;
WebCursorInfo cursor_;
DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};
void DestroyContext(RendererGLContext* context, GLuint program, GLuint buffer) {
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = context->GetImplementation();
if (program)
gl->DeleteProgram(program);
if (buffer)
gl->DeleteBuffers(1, &buffer);
delete context;
}
} // anonymous namespace
// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
int32 opener_id, RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin,
const GURL& active_url) {
DCHECK_NE(MSG_ROUTING_NONE, opener_id);
scoped_refptr<RenderWidgetFullscreenPepper> widget(
new RenderWidgetFullscreenPepper(render_thread, plugin, active_url));
widget->Init(opener_id);
return widget.release();
}
RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin,
const GURL& active_url)
: RenderWidgetFullscreen(render_thread),
active_url_(active_url),
plugin_(plugin),
context_(NULL),
buffer_(0),
program_(0) {
}
RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
if (context_)
DestroyContext(context_, program_, buffer_);
}
void RenderWidgetFullscreenPepper::Invalidate() {
InvalidateRect(gfx::Rect(size_.width(), size_.height()));
}
void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didInvalidateRect(rect);
}
}
void RenderWidgetFullscreenPepper::ScrollRect(
int dx, int dy, const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didScrollRect(dx, dy, rect);
}
}
void RenderWidgetFullscreenPepper::Destroy() {
// This function is called by the plugin instance as it's going away, so reset
// plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
plugin_ = NULL;
Send(new ViewHostMsg_Close(routing_id_));
}
webkit::ppapi::PluginDelegate::PlatformContext3D*
RenderWidgetFullscreenPepper::CreateContext3D() {
if (!context_) {
CreateContext();
}
if (!context_)
return NULL;
return new PlatformContext3DImpl(context_);
}
void RenderWidgetFullscreenPepper::DidInitiatePaint() {
if (plugin_)
plugin_->ViewInitiatedPaint();
}
void RenderWidgetFullscreenPepper::DidFlushPaint() {
if (plugin_)
plugin_->ViewFlushedPaint();
}
void RenderWidgetFullscreenPepper::Close() {
// If the fullscreen window is closed (e.g. user pressed escape), reset to
// normal mode.
if (plugin_)
plugin_->SetFullscreen(false, false);
// Call Close on the base class to destroy the WebWidget instance.
RenderWidget::Close();
}
webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
const gfx::Rect& paint_bounds,
TransportDIB** dib,
gfx::Rect* location,
gfx::Rect* clip) {
if (plugin_ &&
plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
location, clip))
return plugin_;
return NULL;
}
void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size,
const gfx::Rect& resizer_rect) {
if (context_) {
gpu::gles2::GLES2Implementation* gl = context_->GetImplementation();
#if defined(OS_MACOSX)
context_->ResizeOnscreen(size);
#else
gl->ResizeCHROMIUM(size.width(), size.height());
#endif
gl->Viewport(0, 0, size.width(), size.height());
}
RenderWidget::OnResize(size, resizer_rect);
}
WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
return new PepperWidget(plugin_, this);
}
bool RenderWidgetFullscreenPepper::SupportsAsynchronousSwapBuffers() {
return context_ != NULL;
}
void RenderWidgetFullscreenPepper::CreateContext() {
DCHECK(!context_);
RenderThread* render_thread = RenderThread::current();
DCHECK(render_thread);
GpuChannelHost* host = render_thread->EstablishGpuChannelSync(
content::CAUSE_FOR_GPU_LAUNCH_RENDERWIDGETFULLSCREENPEPPER_CREATECONTEXT);
if (!host)
return;
const int32 attribs[] = {
RendererGLContext::ALPHA_SIZE, 8,
RendererGLContext::DEPTH_SIZE, 0,
RendererGLContext::STENCIL_SIZE, 0,
RendererGLContext::SAMPLES, 0,
RendererGLContext::SAMPLE_BUFFERS, 0,
RendererGLContext::NONE,
};
context_ = RendererGLContext::CreateViewContext(
host,
routing_id(),
"GL_OES_packed_depth_stencil GL_OES_depth24",
attribs,
active_url_);
if (!context_)
return;
if (!InitContext()) {
DestroyContext(context_, program_, buffer_);
context_ = NULL;
return;
}
context_->SetSwapBuffersCallback(
NewCallback(this,
&RenderWidgetFullscreenPepper::
OnSwapBuffersCompleteByRendererGLContext));
context_->SetContextLostCallback(
NewCallback(this, &RenderWidgetFullscreenPepper::OnLostContext));
}
namespace {
const char kVertexShader[] =
"attribute vec2 in_tex_coord;\n"
"varying vec2 tex_coord;\n"
"void main() {\n"
" gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n"
" in_tex_coord.y * 2. - 1.,\n"
" 0.,\n"
" 1.);\n"
" tex_coord = vec2(in_tex_coord.x, in_tex_coord.y);\n"
"}\n";
const char kFragmentShader[] =
"precision mediump float;\n"
"varying vec2 tex_coord;\n"
"uniform sampler2D in_texture;\n"
"void main() {\n"
" gl_FragColor = texture2D(in_texture, tex_coord);\n"
"}\n";
GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl,
GLenum type,
const char* source) {
GLuint shader = gl->CreateShader(type);
gl->ShaderSource(shader, 1, &source, NULL);
gl->CompileShader(shader);
int status = GL_FALSE;
gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
int size = 0;
gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetShaderInfoLog(shader, size, NULL, log.get());
DLOG(ERROR) << "Compilation failed: " << log.get();
gl->DeleteShader(shader);
shader = 0;
}
return shader;
}
const float kTexCoords[] = {
0.f, 0.f,
0.f, 2.f,
2.f, 0.f,
};
} // anonymous namespace
bool RenderWidgetFullscreenPepper::InitContext() {
gpu::gles2::GLES2Implementation* gl = context_->GetImplementation();
program_ = gl->CreateProgram();
GLuint vertex_shader =
CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader);
if (!vertex_shader)
return false;
gl->AttachShader(program_, vertex_shader);
gl->DeleteShader(vertex_shader);
GLuint fragment_shader =
CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader);
if (!fragment_shader)
return false;
gl->AttachShader(program_, fragment_shader);
gl->DeleteShader(fragment_shader);
gl->BindAttribLocation(program_, 0, "in_tex_coord");
gl->LinkProgram(program_);
int status = GL_FALSE;
gl->GetProgramiv(program_, GL_LINK_STATUS, &status);
if (!status) {
int size = 0;
gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetProgramInfoLog(program_, size, NULL, log.get());
DLOG(ERROR) << "Link failed: " << log.get();
return false;
}
gl->UseProgram(program_);
int texture_location = gl->GetUniformLocation(program_, "in_texture");
gl->Uniform1i(texture_location, 0);
gl->GenBuffers(1, &buffer_);
gl->BindBuffer(GL_ARRAY_BUFFER, buffer_);
gl->BufferData(GL_ARRAY_BUFFER,
sizeof(kTexCoords),
kTexCoords,
GL_STATIC_DRAW);
gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
gl->EnableVertexAttribArray(0);
return true;
}
bool RenderWidgetFullscreenPepper::CheckCompositing() {
bool compositing = webwidget_->isAcceleratedCompositingActive();
if (compositing != is_accelerated_compositing_active_) {
didActivateAcceleratedCompositing(compositing);
}
return compositing;
}
void RenderWidgetFullscreenPepper::SwapBuffers() {
DCHECK(context_);
OnSwapBuffersPosted();
context_->SwapBuffers();
}
void RenderWidgetFullscreenPepper::OnLostContext(
RendererGLContext::ContextLostReason) {
if (!context_)
return;
// Destroy the context later, in case we got called from InitContext for
// example. We still need to reset context_ now so that a new context gets
// created when the plugin recreates its own.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableFunction(DestroyContext, context_, program_, buffer_));
context_ = NULL;
program_ = 0;
buffer_ = 0;
OnSwapBuffersAborted();
}
void RenderWidgetFullscreenPepper::OnSwapBuffersCompleteByRendererGLContext() {
OnSwapBuffersComplete();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlDataSourceSetting.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2005-03-10 16:39:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBA_XMLDATASOURCESETTING_HXX
#include "xmlDataSourceSetting.hxx"
#endif
#ifndef DBA_XMLDATASOURCE_HXX
#include "xmlDataSource.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
namespace dbaxml
{
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
OXMLDataSourceSetting::OXMLDataSourceSetting( ODBFilter& rImport
,sal_uInt16 nPrfx
,const OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,OXMLDataSource& _rParent
,OXMLDataSourceSetting* _pContainer) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_rParent(_rParent)
,m_pContainer(_pContainer)
,m_bIsList(sal_False)
{
m_aPropType = ::getVoidCppuType();
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetDataSourceInfoElemTokenMap();
sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
OUString sLocalName;
rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING_IS_LIST:
m_bIsList = sValue.equalsAscii("true");
break;
case XML_TOK_DATA_SOURCE_SETTING_TYPE:
{
// needs to be translated into a ::com::sun::star::uno::Type
DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Type, MapString2Type );
static MapString2Type s_aTypeNameMap;
if (!s_aTypeNameMap.size())
{
s_aTypeNameMap[GetXMLToken( XML_BOOLEAN)] = ::getBooleanCppuType();
s_aTypeNameMap[GetXMLToken( XML_FLOAT)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_STRING)] = ::getCppuType( static_cast< ::rtl::OUString* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_INT)] = ::getCppuType( static_cast< sal_Int32* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_SHORT)] = ::getCppuType( static_cast< sal_Int16* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_VOID)] = ::getVoidCppuType();
}
const ConstMapString2TypeIterator aTypePos = s_aTypeNameMap.find(sValue);
OSL_ENSURE(s_aTypeNameMap.end() != aTypePos, "OXMLDataSourceSetting::OXMLDataSourceSetting: invalid type!");
if (s_aTypeNameMap.end() != aTypePos)
m_aPropType = aTypePos->second;
}
break;
case XML_TOK_DATA_SOURCE_SETTING_NAME:
m_aSetting.Name = sValue;
break;
}
}
}
// -----------------------------------------------------------------------------
OXMLDataSourceSetting::~OXMLDataSourceSetting()
{
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLDataSourceSetting::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDataSourceInfoElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent);
break;
case XML_TOK_DATA_SOURCE_SETTING_VALUE:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent,this );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::EndElement()
{
if ( m_aSetting.Name.getLength() )
{
if ( m_bIsList && !m_aInfoSequence.getLength() )
m_aSetting.Value <<= m_aInfoSequence;
m_rParent.addInfo(m_aSetting);
}
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::Characters( const ::rtl::OUString& rChars )
{
if ( m_pContainer )
m_pContainer->addValue(rChars);
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::addValue(const ::rtl::OUString& _sValue)
{
Any aValue;
if( TypeClass_VOID != m_aPropType.getTypeClass() )
aValue = convertString(m_aPropType, _sValue);
if ( !m_bIsList )
m_aSetting.Value = aValue;
else
{
sal_Int32 nPos = m_aInfoSequence.getLength();
m_aInfoSequence.realloc(nPos+1);
m_aInfoSequence[nPos] = aValue;
}
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDataSourceSetting::GetOwnImport()
{
return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
Any OXMLDataSourceSetting::convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters)
{
ODBFilter& rImporter = GetOwnImport();
Any aReturn;
switch (_rExpectedType.getTypeClass())
{
case TypeClass_BOOLEAN: // sal_Bool
{
sal_Bool bValue;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertBool(bValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a boolean!"));
aReturn <<= bValue;
}
break;
case TypeClass_SHORT: // sal_Int16
case TypeClass_LONG: // sal_Int32
{ // it's a real int32/16 property
sal_Int32 nValue(0);
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertNumber(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into an integer!"));
if (TypeClass_SHORT == _rExpectedType.getTypeClass())
aReturn <<= (sal_Int16)nValue;
else
aReturn <<= (sal_Int32)nValue;
break;
}
case TypeClass_HYPER:
{
OSL_ENSURE(sal_False, "OXMLDataSourceSetting::convertString: 64-bit integers not implemented yet!");
}
break;
case TypeClass_DOUBLE:
{
double nValue = 0.0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a double!"));
aReturn <<= (double)nValue;
}
break;
case TypeClass_STRING:
aReturn <<= _rReadCharacters;
break;
default:
OSL_ENSURE(sal_False, "OXMLDataSourceSetting::convertString: invalid type class!");
}
return aReturn;
}
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.104); FILE MERGED 2005/09/05 17:32:49 rt 1.5.104.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlDataSourceSetting.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:03:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBA_XMLDATASOURCESETTING_HXX
#include "xmlDataSourceSetting.hxx"
#endif
#ifndef DBA_XMLDATASOURCE_HXX
#include "xmlDataSource.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
namespace dbaxml
{
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
OXMLDataSourceSetting::OXMLDataSourceSetting( ODBFilter& rImport
,sal_uInt16 nPrfx
,const OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,OXMLDataSource& _rParent
,OXMLDataSourceSetting* _pContainer) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_rParent(_rParent)
,m_pContainer(_pContainer)
,m_bIsList(sal_False)
{
m_aPropType = ::getVoidCppuType();
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetDataSourceInfoElemTokenMap();
sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
OUString sLocalName;
rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING_IS_LIST:
m_bIsList = sValue.equalsAscii("true");
break;
case XML_TOK_DATA_SOURCE_SETTING_TYPE:
{
// needs to be translated into a ::com::sun::star::uno::Type
DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Type, MapString2Type );
static MapString2Type s_aTypeNameMap;
if (!s_aTypeNameMap.size())
{
s_aTypeNameMap[GetXMLToken( XML_BOOLEAN)] = ::getBooleanCppuType();
s_aTypeNameMap[GetXMLToken( XML_FLOAT)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_STRING)] = ::getCppuType( static_cast< ::rtl::OUString* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_INT)] = ::getCppuType( static_cast< sal_Int32* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_SHORT)] = ::getCppuType( static_cast< sal_Int16* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_VOID)] = ::getVoidCppuType();
}
const ConstMapString2TypeIterator aTypePos = s_aTypeNameMap.find(sValue);
OSL_ENSURE(s_aTypeNameMap.end() != aTypePos, "OXMLDataSourceSetting::OXMLDataSourceSetting: invalid type!");
if (s_aTypeNameMap.end() != aTypePos)
m_aPropType = aTypePos->second;
}
break;
case XML_TOK_DATA_SOURCE_SETTING_NAME:
m_aSetting.Name = sValue;
break;
}
}
}
// -----------------------------------------------------------------------------
OXMLDataSourceSetting::~OXMLDataSourceSetting()
{
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLDataSourceSetting::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDataSourceInfoElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent);
break;
case XML_TOK_DATA_SOURCE_SETTING_VALUE:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent,this );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::EndElement()
{
if ( m_aSetting.Name.getLength() )
{
if ( m_bIsList && !m_aInfoSequence.getLength() )
m_aSetting.Value <<= m_aInfoSequence;
m_rParent.addInfo(m_aSetting);
}
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::Characters( const ::rtl::OUString& rChars )
{
if ( m_pContainer )
m_pContainer->addValue(rChars);
}
// -----------------------------------------------------------------------------
void OXMLDataSourceSetting::addValue(const ::rtl::OUString& _sValue)
{
Any aValue;
if( TypeClass_VOID != m_aPropType.getTypeClass() )
aValue = convertString(m_aPropType, _sValue);
if ( !m_bIsList )
m_aSetting.Value = aValue;
else
{
sal_Int32 nPos = m_aInfoSequence.getLength();
m_aInfoSequence.realloc(nPos+1);
m_aInfoSequence[nPos] = aValue;
}
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDataSourceSetting::GetOwnImport()
{
return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
Any OXMLDataSourceSetting::convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters)
{
ODBFilter& rImporter = GetOwnImport();
Any aReturn;
switch (_rExpectedType.getTypeClass())
{
case TypeClass_BOOLEAN: // sal_Bool
{
sal_Bool bValue;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertBool(bValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a boolean!"));
aReturn <<= bValue;
}
break;
case TypeClass_SHORT: // sal_Int16
case TypeClass_LONG: // sal_Int32
{ // it's a real int32/16 property
sal_Int32 nValue(0);
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertNumber(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into an integer!"));
if (TypeClass_SHORT == _rExpectedType.getTypeClass())
aReturn <<= (sal_Int16)nValue;
else
aReturn <<= (sal_Int32)nValue;
break;
}
case TypeClass_HYPER:
{
OSL_ENSURE(sal_False, "OXMLDataSourceSetting::convertString: 64-bit integers not implemented yet!");
}
break;
case TypeClass_DOUBLE:
{
double nValue = 0.0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLDataSourceSetting::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a double!"));
aReturn <<= (double)nValue;
}
break;
case TypeClass_STRING:
aReturn <<= _rReadCharacters;
break;
default:
OSL_ENSURE(sal_False, "OXMLDataSourceSetting::convertString: invalid type class!");
}
return aReturn;
}
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "VideoSessionWidget.h"
#include "UiDefines.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
namespace CommunicationUI
{
VideoSessionWidget::VideoSessionWidget(QWidget *parent, Communication::VoiceSessionInterface *video_session, QString &my_name, QString &his_name)
: QWidget(parent),
video_session_(video_session),
my_name_(my_name),
his_name_(his_name),
internal_widget_(0),
internal_v_layout_(0),
internal_h_layout_(0),
internal_v_layout_local_(0),
internal_v_layout_remote_(0),
local_video_(0),
remote_video_(0),
controls_local_widget_(new QWidget(this)),
controls_remote_widget_(new QWidget(this)),
main_view_visible_(false)
{
// Init all ui elements
video_session_ui_.setupUi(this);
controls_local_ui_.setupUi(controls_local_widget_);
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color:red"));
controls_local_ui_.horizontalLayout->insertSpacerItem(2, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_local_widget_->hide();
controls_remote_ui_.setupUi(controls_remote_widget_);
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color:red"));
controls_remote_ui_.horizontalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_remote_ui_.audioCheckBox->setEnabled(false);
controls_remote_ui_.videoCheckBox->setEnabled(false);
controls_remote_widget_->hide();
// Update widget states
SessionStateChanged(video_session_->GetState());
AudioStreamStateChanged(video_session_->GetAudioStreamState());
VideoStreamStateChanged(video_session_->GetVideoStreamState());
UpdateLocalVideoControls(video_session_->IsSendingVideoData());
UpdateLocalAudioControls(video_session_->IsSendingAudioData());
UpdateRemoteVideoControls(video_session_->IsReceivingVideoData());
UpdateRemoteAudioControls(video_session_->IsReceivingAudioData());
// CLOSE TAB
connect(video_session_ui_.closePushButton, SIGNAL( clicked() ),
this, SLOT( CloseSession() ));
// CONNECTION AND STREAM STATES
connect(video_session_, SIGNAL( StateChanged(Communication::VoiceSessionInterface::State) ),
this, SLOT( SessionStateChanged(Communication::VoiceSessionInterface::State) ));
connect(video_session_, SIGNAL( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
connect(video_session_, SIGNAL( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
// AUDIO / VIDEO STATES
connect(video_session_, SIGNAL( SendingVideoData(bool) ),
this, SLOT( UpdateLocalVideoControls(bool) ));
connect(video_session_, SIGNAL( SendingAudioData(bool) ),
this, SLOT( UpdateLocalAudioControls(bool) ));
connect(video_session_, SIGNAL( ReceivingVideoData(bool) ),
this, SLOT( UpdateRemoteVideoControls(bool) ));
connect(video_session_, SIGNAL( ReceivingAudioData(bool) ),
this, SLOT( UpdateRemoteAudioControls(bool) ));
}
VideoSessionWidget::~VideoSessionWidget()
{
ClearContent();
}
void VideoSessionWidget::ClearContent()
{
if (internal_v_layout_local_ && local_video_)
{
local_video_->close();
internal_v_layout_local_->removeWidget(local_video_);
local_video_->setParent(0);
local_video_ = 0;
}
if (internal_v_layout_remote_ && remote_video_)
{
remote_video_->close();
internal_v_layout_remote_->removeWidget(remote_video_);
remote_video_->setParent(0);
remote_video_ = 0;
}
SAFE_DELETE(internal_widget_);
}
void VideoSessionWidget::SessionStateChanged(Communication::VoiceSessionInterface::State new_state)
{
ClearContent();
main_view_visible_ = false;
switch (new_state)
{
case Communication::VoiceSessionInterface::STATE_OPEN:
{
video_session_ui_.mainVerticalLayout->setAlignment(video_session_ui_.horizontalLayout, Qt::AlignTop);
ShowVideoWidgets();
main_view_visible_ = true;
video_session_ui_.connectionStatus->setText("Open");
break;
}
case Communication::VoiceSessionInterface::STATE_CLOSED:
{
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("This coversation has been closed");
break;
}
case Communication::VoiceSessionInterface::STATE_ERROR:
{
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("Connection failed");
break;
}
case Communication::VoiceSessionInterface::STATE_INITIALIZING:
{
video_session_ui_.mainVerticalLayout->setAlignment(video_session_ui_.horizontalLayout, Qt::AlignBottom);
video_session_ui_.connectionStatus->setText("Initializing...");
break;
}
case Communication::VoiceSessionInterface::STATE_RINGING_LOCAL:
{
ShowConfirmationWidget();
video_session_ui_.connectionStatus->setText("Waiting for your confirmation...");
break;
}
case Communication::VoiceSessionInterface::STATE_RINGING_REMOTE:
{
video_session_ui_.connectionStatus->setText(QString("Waiting confirmation from %1").arg(his_name_));
break;
}
}
}
void VideoSessionWidget::AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.audioStatus->setText("Connecting");
controls_local_ui_.audioCheckBox->setText("Requesting Audio");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.audioStatus->setText("Connected");
controls_local_ui_.audioCheckBox->setText("Audio");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.audioStatus->setText("Disconnected");
controls_local_ui_.audioCheckBox->setText("Audio");
break;
}
}
void VideoSessionWidget::VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.videoStatus->setText("Connecting");
controls_local_ui_.videoCheckBox->setText("Requesting Video");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.videoStatus->setText("Connected");
controls_local_ui_.videoCheckBox->setText("Video");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.videoStatus->setText("Disconnected");
controls_local_ui_.videoCheckBox->setText("Video");
break;
}
}
void VideoSessionWidget::LocalVideoStateChange(int state)
{
if (main_view_visible_)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendVideoData(enabled);
UpdateLocalVideoControls(enabled);
}
}
void VideoSessionWidget::UpdateLocalVideoControls(bool state)
{
if (main_view_visible_)
{
controls_local_ui_.videoCheckBox->setChecked(state);
if (state)
{
if (local_video_ && local_status_label_)
{
if (video_session_->GetVideoStreamState() == Communication::VoiceSessionInterface::SS_CONNECTED)
local_status_label_->setText("Sending video");
else if (video_session_->GetVideoStreamState() == Communication::VoiceSessionInterface::SS_CONNECTING)
local_status_label_->setText("Requesting video...");
else
local_status_label_->setText("Could not open video stream");
}
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
}
else
{
if (local_video_ && local_status_label_)
local_status_label_->setText("Preview of captured video");
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
}
}
void VideoSessionWidget::LocalAudioStateChange(int state)
{
if (main_view_visible_)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendAudioData(enabled);
}
}
void VideoSessionWidget::UpdateLocalAudioControls(bool state)
{
if (main_view_visible_)
{
controls_local_ui_.audioCheckBox->setChecked(state);
if (state)
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
}
void VideoSessionWidget::UpdateRemoteVideoControls(bool state)
{
if (main_view_visible_)
{
controls_remote_ui_.videoCheckBox->setChecked(state);
if (state)
{
if (remote_video_ && remote_status_label_)
remote_status_label_->setText("Receiving video");
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
}
else
{
if (remote_video_ && remote_status_label_)
remote_status_label_->setText("Friend is currently not sending video");
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
}
}
void VideoSessionWidget::UpdateRemoteAudioControls(bool state)
{
if (main_view_visible_)
{
controls_remote_ui_.audioCheckBox->setChecked(state);
if (state)
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
}
void VideoSessionWidget::ShowConfirmationWidget()
{
// Init widgets
internal_widget_ = new QWidget();
internal_v_layout_ = new QVBoxLayout(internal_widget_);
internal_h_layout_ = new QHBoxLayout();
QLabel *question_label = new QLabel(QString("%1 wants to start a video conversation with you").arg(his_name_));
QPushButton *accept_button = new QPushButton("Accept", internal_widget_);
QPushButton *decline_button = new QPushButton("Decline", internal_widget_);
// Stylesheets for background and text color
internal_widget_->setObjectName("confirmationWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#confirmationWidget { background-color: rgba(255,255,255,0); } QLabel { color: rgb(0,0,0); }"));
// Add widgets to layouts
internal_h_layout_->setSpacing(6);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_h_layout_->addWidget(question_label);
internal_h_layout_->addWidget(accept_button);
internal_h_layout_->addWidget(decline_button);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
internal_v_layout_->addLayout(internal_h_layout_);
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
// Add bottom layout to widget, insert widget at top of parent widgets layout
internal_widget_->setLayout(internal_v_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Connect signals
connect(accept_button, SIGNAL( clicked() ), video_session_, SLOT( Accept() ));
connect(decline_button, SIGNAL( clicked() ), video_session_, SLOT( Reject() ));
}
void VideoSessionWidget::ShowVideoWidgets()
{
// Init widgets
internal_widget_ = new QWidget();
internal_h_layout_ = new QHBoxLayout(internal_widget_);
internal_v_layout_local_ = new QVBoxLayout();
internal_v_layout_remote_ = new QVBoxLayout();
// Local video and controls
local_video_ = (QWidget *)(video_session_->GetLocallyCapturedVideo());
controls_local_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
local_status_label_ = new QLabel("Preview of captured video", this);
local_status_label_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
local_status_label_->setAlignment(Qt::AlignCenter);
local_status_label_->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
local_status_label_->setMaximumHeight(20);
internal_v_layout_local_->addWidget(local_status_label_);
if (local_video_)
internal_v_layout_local_->addWidget(local_video_);
internal_v_layout_local_->addWidget(controls_local_widget_);
// Remote video and contols
remote_video_ = (QWidget *)(video_session_->GetReceivedVideo());
controls_remote_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
remote_status_label_ = new QLabel("Friend is currently not sending video", this);
remote_status_label_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
remote_status_label_->setAlignment(Qt::AlignCenter);
remote_status_label_->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
remote_status_label_->setMaximumHeight(20);
internal_v_layout_remote_->addWidget(remote_status_label_);
if (remote_video_)
internal_v_layout_remote_->addWidget(remote_video_);
internal_v_layout_remote_->addWidget(controls_remote_widget_);
// But our video containers to the main horizontal layout
internal_h_layout_->setSpacing(6);
internal_h_layout_->addLayout(internal_v_layout_local_);
internal_h_layout_->addLayout(internal_v_layout_remote_);
// Add to main widgets layout
internal_widget_->setLayout(internal_h_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
video_session_ui_.mainVerticalLayout->setStretch(0, 1);
// Some stylesheets for consistent color theme
// otherwise this will inherit transparent background from parent widget
internal_widget_->setObjectName("videoSessionWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#videoSessionWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
controls_local_widget_->show();
controls_remote_widget_->show();
// Connect checkboxes to control video and audio sending
connect(controls_local_ui_.videoCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalVideoStateChange(int) ));
connect(controls_local_ui_.audioCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalAudioStateChange(int) ));
}
void VideoSessionWidget::CloseSession()
{
ClearContent();
video_session_->Close();
emit Closed(his_name_);
}
}<commit_msg>* State changing crash fix<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "VideoSessionWidget.h"
#include "UiDefines.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
namespace CommunicationUI
{
VideoSessionWidget::VideoSessionWidget(QWidget *parent, Communication::VoiceSessionInterface *video_session, QString &my_name, QString &his_name)
: QWidget(parent),
video_session_(video_session),
my_name_(my_name),
his_name_(his_name),
internal_widget_(0),
internal_v_layout_(0),
internal_h_layout_(0),
internal_v_layout_local_(0),
internal_v_layout_remote_(0),
local_video_(0),
remote_video_(0),
controls_local_widget_(new QWidget(this)),
controls_remote_widget_(new QWidget(this)),
main_view_visible_(false)
{
// Init all ui elements
video_session_ui_.setupUi(this);
controls_local_ui_.setupUi(controls_local_widget_);
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color:red"));
controls_local_ui_.horizontalLayout->insertSpacerItem(2, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_local_widget_->hide();
controls_remote_ui_.setupUi(controls_remote_widget_);
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color:red"));
controls_remote_ui_.horizontalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_remote_ui_.audioCheckBox->setEnabled(false);
controls_remote_ui_.videoCheckBox->setEnabled(false);
controls_remote_widget_->hide();
// Update widget states
SessionStateChanged(video_session_->GetState());
AudioStreamStateChanged(video_session_->GetAudioStreamState());
VideoStreamStateChanged(video_session_->GetVideoStreamState());
UpdateLocalVideoControls(video_session_->IsSendingVideoData());
UpdateLocalAudioControls(video_session_->IsSendingAudioData());
UpdateRemoteVideoControls(video_session_->IsReceivingVideoData());
UpdateRemoteAudioControls(video_session_->IsReceivingAudioData());
// CLOSE TAB
connect(video_session_ui_.closePushButton, SIGNAL( clicked() ),
this, SLOT( CloseSession() ));
// CONNECTION AND STREAM STATES
connect(video_session_, SIGNAL( StateChanged(Communication::VoiceSessionInterface::State) ),
this, SLOT( SessionStateChanged(Communication::VoiceSessionInterface::State) ));
connect(video_session_, SIGNAL( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
connect(video_session_, SIGNAL( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
// AUDIO / VIDEO STATES
connect(video_session_, SIGNAL( SendingVideoData(bool) ),
this, SLOT( UpdateLocalVideoControls(bool) ));
connect(video_session_, SIGNAL( SendingAudioData(bool) ),
this, SLOT( UpdateLocalAudioControls(bool) ));
connect(video_session_, SIGNAL( ReceivingVideoData(bool) ),
this, SLOT( UpdateRemoteVideoControls(bool) ));
connect(video_session_, SIGNAL( ReceivingAudioData(bool) ),
this, SLOT( UpdateRemoteAudioControls(bool) ));
}
VideoSessionWidget::~VideoSessionWidget()
{
ClearContent();
}
void VideoSessionWidget::ClearContent()
{
if (internal_v_layout_local_ && local_video_)
{
local_video_->close();
internal_v_layout_local_->removeWidget(local_video_);
local_video_->setParent(0);
local_video_ = 0;
}
if (internal_v_layout_remote_ && remote_video_)
{
remote_video_->close();
internal_v_layout_remote_->removeWidget(remote_video_);
remote_video_->setParent(0);
remote_video_ = 0;
}
SAFE_DELETE(internal_widget_);
}
void VideoSessionWidget::SessionStateChanged(Communication::VoiceSessionInterface::State new_state)
{
ClearContent();
main_view_visible_ = false;
switch (new_state)
{
case Communication::VoiceSessionInterface::STATE_OPEN:
{
video_session_ui_.mainVerticalLayout->setAlignment(video_session_ui_.horizontalLayout, Qt::AlignTop);
ShowVideoWidgets();
main_view_visible_ = true;
video_session_ui_.connectionStatus->setText("Open");
break;
}
case Communication::VoiceSessionInterface::STATE_CLOSED:
{
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("This coversation has been closed");
break;
}
case Communication::VoiceSessionInterface::STATE_ERROR:
{
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("Connection failed");
break;
}
case Communication::VoiceSessionInterface::STATE_INITIALIZING:
{
video_session_ui_.mainVerticalLayout->setAlignment(video_session_ui_.horizontalLayout, Qt::AlignBottom);
video_session_ui_.connectionStatus->setText("Initializing...");
break;
}
case Communication::VoiceSessionInterface::STATE_RINGING_LOCAL:
{
ShowConfirmationWidget();
video_session_ui_.connectionStatus->setText("Waiting for your confirmation...");
break;
}
case Communication::VoiceSessionInterface::STATE_RINGING_REMOTE:
{
video_session_ui_.connectionStatus->setText(QString("Waiting confirmation from %1").arg(his_name_));
break;
}
}
}
void VideoSessionWidget::AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
if (main_view_visible_)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.audioStatus->setText("Connecting");
controls_local_ui_.audioCheckBox->setText("Requesting Audio");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.audioStatus->setText("Connected");
controls_local_ui_.audioCheckBox->setText("Audio");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.audioStatus->setText("Disconnected");
controls_local_ui_.audioCheckBox->setText("Audio");
break;
}
}
}
void VideoSessionWidget::VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
if (main_view_visible_)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.videoStatus->setText("Connecting");
controls_local_ui_.videoCheckBox->setText("Requesting Video");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.videoStatus->setText("Connected");
controls_local_ui_.videoCheckBox->setText("Video");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.videoStatus->setText("Disconnected");
controls_local_ui_.videoCheckBox->setText("Video");
break;
}
}
}
void VideoSessionWidget::LocalVideoStateChange(int state)
{
if (main_view_visible_)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendVideoData(enabled);
UpdateLocalVideoControls(enabled);
}
}
void VideoSessionWidget::UpdateLocalVideoControls(bool state)
{
if (main_view_visible_)
{
controls_local_ui_.videoCheckBox->setChecked(state);
if (state)
{
if (local_video_ && local_status_label_)
{
if (video_session_->GetVideoStreamState() == Communication::VoiceSessionInterface::SS_CONNECTED)
local_status_label_->setText("Sending video");
else if (video_session_->GetVideoStreamState() == Communication::VoiceSessionInterface::SS_CONNECTING)
local_status_label_->setText("Requesting video...");
else
local_status_label_->setText("Could not open video stream");
}
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
}
else
{
if (local_video_ && local_status_label_)
local_status_label_->setText("Preview of captured video");
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
}
}
void VideoSessionWidget::LocalAudioStateChange(int state)
{
if (main_view_visible_)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendAudioData(enabled);
}
}
void VideoSessionWidget::UpdateLocalAudioControls(bool state)
{
if (main_view_visible_)
{
controls_local_ui_.audioCheckBox->setChecked(state);
if (state)
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
}
void VideoSessionWidget::UpdateRemoteVideoControls(bool state)
{
if (main_view_visible_)
{
controls_remote_ui_.videoCheckBox->setChecked(state);
if (state)
{
if (remote_video_ && remote_status_label_)
remote_status_label_->setText("Receiving video");
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
}
else
{
if (remote_video_ && remote_status_label_)
remote_status_label_->setText("Friend is currently not sending video");
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
}
}
void VideoSessionWidget::UpdateRemoteAudioControls(bool state)
{
if (main_view_visible_)
{
controls_remote_ui_.audioCheckBox->setChecked(state);
if (state)
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
}
void VideoSessionWidget::ShowConfirmationWidget()
{
// Init widgets
internal_widget_ = new QWidget();
internal_v_layout_ = new QVBoxLayout(internal_widget_);
internal_h_layout_ = new QHBoxLayout();
QLabel *question_label = new QLabel(QString("%1 wants to start a video conversation with you").arg(his_name_));
QPushButton *accept_button = new QPushButton("Accept", internal_widget_);
QPushButton *decline_button = new QPushButton("Decline", internal_widget_);
// Stylesheets for background and text color
internal_widget_->setObjectName("confirmationWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#confirmationWidget { background-color: rgba(255,255,255,0); } QLabel { color: rgb(0,0,0); }"));
// Add widgets to layouts
internal_h_layout_->setSpacing(6);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_h_layout_->addWidget(question_label);
internal_h_layout_->addWidget(accept_button);
internal_h_layout_->addWidget(decline_button);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
internal_v_layout_->addLayout(internal_h_layout_);
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
// Add bottom layout to widget, insert widget at top of parent widgets layout
internal_widget_->setLayout(internal_v_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Connect signals
connect(accept_button, SIGNAL( clicked() ), video_session_, SLOT( Accept() ));
connect(decline_button, SIGNAL( clicked() ), video_session_, SLOT( Reject() ));
}
void VideoSessionWidget::ShowVideoWidgets()
{
// Init widgets
internal_widget_ = new QWidget();
internal_h_layout_ = new QHBoxLayout(internal_widget_);
internal_v_layout_local_ = new QVBoxLayout();
internal_v_layout_remote_ = new QVBoxLayout();
// Local video and controls
local_video_ = (QWidget *)(video_session_->GetLocallyCapturedVideo());
controls_local_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
local_status_label_ = new QLabel("Preview of captured video", this);
local_status_label_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
local_status_label_->setAlignment(Qt::AlignCenter);
local_status_label_->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
local_status_label_->setMaximumHeight(20);
internal_v_layout_local_->addWidget(local_status_label_);
if (local_video_)
internal_v_layout_local_->addWidget(local_video_);
internal_v_layout_local_->addWidget(controls_local_widget_);
// Remote video and contols
remote_video_ = (QWidget *)(video_session_->GetReceivedVideo());
controls_remote_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
remote_status_label_ = new QLabel("Friend is currently not sending video", this);
remote_status_label_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
remote_status_label_->setAlignment(Qt::AlignCenter);
remote_status_label_->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
remote_status_label_->setMaximumHeight(20);
internal_v_layout_remote_->addWidget(remote_status_label_);
if (remote_video_)
internal_v_layout_remote_->addWidget(remote_video_);
internal_v_layout_remote_->addWidget(controls_remote_widget_);
// But our video containers to the main horizontal layout
internal_h_layout_->setSpacing(6);
internal_h_layout_->addLayout(internal_v_layout_local_);
internal_h_layout_->addLayout(internal_v_layout_remote_);
// Add to main widgets layout
internal_widget_->setLayout(internal_h_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
video_session_ui_.mainVerticalLayout->setStretch(0, 1);
// Some stylesheets for consistent color theme
// otherwise this will inherit transparent background from parent widget
internal_widget_->setObjectName("videoSessionWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#videoSessionWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
controls_local_widget_->show();
controls_remote_widget_->show();
// Connect checkboxes to control video and audio sending
connect(controls_local_ui_.videoCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalVideoStateChange(int) ));
connect(controls_local_ui_.audioCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalAudioStateChange(int) ));
}
void VideoSessionWidget::CloseSession()
{
ClearContent();
video_session_->Close();
emit Closed(his_name_);
}
}<|endoftext|> |
<commit_before>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "debughelper.h"
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtGui/QApplication>
#include <QVariant>
using namespace GluonCore;
template<> GLUON_CORE_EXPORT GluonObjectFactory* Singleton<GluonObjectFactory>::m_instance = 0;
QStringList
GluonObjectFactory::objectTypeNames() const
{
QStringList theNames;
QHash<QString, GluonObject*>::const_iterator i;
for (i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i)
theNames << i.key();
return theNames;
}
QHash< QString, GluonObject* >
GluonObjectFactory::objectTypes() const
{
return m_objectTypes;
}
const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
return m_objectTypeIDs;
}
QStringList
GluonObjectFactory::objectMimeTypes() const
{
return m_mimeTypes.keys();
}
void
GluonObjectFactory::registerObjectType(GluonObject * newObjectType, int typeID)
{
DEBUG_BLOCK
if(newObjectType)
{
DEBUG_TEXT(QString("Registering object type %1 with typeID %2").arg(newObjectType->metaObject()->className()).arg(typeID));
m_objectTypes[newObjectType->metaObject()->className()] = newObjectType;
m_objectTypeIDs[newObjectType->metaObject()->className()] = typeID;
foreach(const QString &mimetype, newObjectType->supportedMimeTypes())
{
DEBUG_TEXT(QString("Adding mimetype %1 to the index").arg(mimetype));
m_mimeTypes[mimetype] = newObjectType->metaObject()->className();
}
}
else
DEBUG_TEXT(QString("Attempted to register a NULL object type"));
}
GluonObject *
GluonObjectFactory::instantiateObjectByName(const QString& objectTypeName)
{
DEBUG_BLOCK
QString fullObjectTypeName(objectTypeName);
if(!objectTypeName.contains("::"))
fullObjectTypeName = QString("Gluon::") + fullObjectTypeName;
if(m_objectTypes.keys().indexOf(fullObjectTypeName) > -1)
return m_objectTypes[fullObjectTypeName]->instantiate();
DEBUG_TEXT(QString("Object type name not found in factory!"));
return 0;
}
GluonObject*
GluonObjectFactory::instantiateObjectByMimetype(const QString& objectMimeType)
{
return instantiateObjectByName(m_mimeTypes[objectMimeType]);
}
QVariant
GluonObjectFactory::wrapObject(const QVariant& original, GluonObject* newValue)
{
QString type = original.typeName();
type = type.left(type.length() - 1);
return m_objectTypes[type]->toVariant(newValue);
}
void
GluonObjectFactory::loadPlugins()
{
DEBUG_FUNC_NAME
QList<QDir> pluginDirs;
QDir pluginDir(QApplication::applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginDir.dirName().tolower() == "debug" || pluginDir.dirName().tolower() == "release")
pluginDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginDir.dirName() == "MacOS")
{
pluginDir.cdUp();
pluginDir.cdUp();
pluginDir.cdUp();
}
#endif
if(pluginDir.cd("plugins"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib64"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib64/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/local/lib/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd(QDir::homePath() + "/gluonplugins"))
pluginDirs.append(pluginDir);
DEBUG_TEXT(QString("Number of plugin locations: %1").arg(pluginDirs.count()));
foreach(const QDir &theDir, pluginDirs)
{
DEBUG_TEXT(QString("Looking for pluggable components in %1").arg(theDir.absolutePath()));
DEBUG_TEXT(QString("Found %1 potential plugins. Attempting to load...").arg(theDir.count() - 2));
foreach (QString fileName, theDir.entryList(QDir::Files))
{
// Don't attempt to load non-gluon_plugin prefixed libraries
if(!fileName.contains("gluon"))
continue;
// Don't attempt to load non-libraries
if(!QLibrary::isLibrary(theDir.absoluteFilePath(fileName)))
continue;
QPluginLoader loader(theDir.absoluteFilePath(fileName));
loader.load();
if(!loader.isLoaded())
{
DEBUG_TEXT(loader.errorString());
}
}
}
}
#include "gluonobjectfactory.moc"
<commit_msg>Attempt to fix the problems with install prefixes other than /usr and /usr/local Not a fix-all, but hopefully it'll work<commit_after>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "debughelper.h"
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtGui/QApplication>
#include <QVariant>
using namespace GluonCore;
template<> GLUON_CORE_EXPORT GluonObjectFactory* Singleton<GluonObjectFactory>::m_instance = 0;
QStringList
GluonObjectFactory::objectTypeNames() const
{
QStringList theNames;
QHash<QString, GluonObject*>::const_iterator i;
for (i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i)
theNames << i.key();
return theNames;
}
QHash< QString, GluonObject* >
GluonObjectFactory::objectTypes() const
{
return m_objectTypes;
}
const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
return m_objectTypeIDs;
}
QStringList
GluonObjectFactory::objectMimeTypes() const
{
return m_mimeTypes.keys();
}
void
GluonObjectFactory::registerObjectType(GluonObject * newObjectType, int typeID)
{
DEBUG_BLOCK
if(newObjectType)
{
DEBUG_TEXT(QString("Registering object type %1 with typeID %2").arg(newObjectType->metaObject()->className()).arg(typeID));
m_objectTypes[newObjectType->metaObject()->className()] = newObjectType;
m_objectTypeIDs[newObjectType->metaObject()->className()] = typeID;
foreach(const QString &mimetype, newObjectType->supportedMimeTypes())
{
DEBUG_TEXT(QString("Adding mimetype %1 to the index").arg(mimetype));
m_mimeTypes[mimetype] = newObjectType->metaObject()->className();
}
}
else
DEBUG_TEXT(QString("Attempted to register a NULL object type"));
}
GluonObject *
GluonObjectFactory::instantiateObjectByName(const QString& objectTypeName)
{
DEBUG_BLOCK
QString fullObjectTypeName(objectTypeName);
if(!objectTypeName.contains("::"))
fullObjectTypeName = QString("Gluon::") + fullObjectTypeName;
if(m_objectTypes.keys().indexOf(fullObjectTypeName) > -1)
return m_objectTypes[fullObjectTypeName]->instantiate();
DEBUG_TEXT(QString("Object type name not found in factory!"));
return 0;
}
GluonObject*
GluonObjectFactory::instantiateObjectByMimetype(const QString& objectMimeType)
{
return instantiateObjectByName(m_mimeTypes[objectMimeType]);
}
QVariant
GluonObjectFactory::wrapObject(const QVariant& original, GluonObject* newValue)
{
QString type = original.typeName();
type = type.left(type.length() - 1);
return m_objectTypes[type]->toVariant(newValue);
}
void
GluonObjectFactory::loadPlugins()
{
DEBUG_FUNC_NAME
QList<QDir> pluginDirs;
QDir pluginDir(QApplication::applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginDir.dirName().tolower() == "debug" || pluginDir.dirName().tolower() == "release")
pluginDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginDir.dirName() == "MacOS")
{
pluginDir.cdUp();
pluginDir.cdUp();
pluginDir.cdUp();
}
#endif
if(pluginDir.cd("plugins"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib64"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib64/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/local/lib/gluon"))
pluginDirs.append(pluginDir);
if(QCoreApplication::applicationDirPath() != QString("/usr/bin"))
{
if(pluginDir.cd(QCoreApplication::applicationDirPath() + "../lib"))
pluginDirs.append(pluginDir);
if(pluginDir.cd(QCoreApplication::applicationDirPath() + "../lib64"))
pluginDirs.append(pluginDir);
if(pluginDir.cd(QCoreApplication::applicationDirPath() + "../lib/gluon"))
pluginDirs.append(pluginDir);
if(pluginDir.cd(QCoreApplication::applicationDirPath() + "../lib64/gluon"))
pluginDirs.append(pluginDir);
}
if(pluginDir.cd(QDir::homePath() + "/gluonplugins"))
pluginDirs.append(pluginDir);
DEBUG_TEXT(QString("Number of plugin locations: %1").arg(pluginDirs.count()));
foreach(const QDir &theDir, pluginDirs)
{
DEBUG_TEXT(QString("Looking for pluggable components in %1").arg(theDir.absolutePath()));
DEBUG_TEXT(QString("Found %1 potential plugins. Attempting to load...").arg(theDir.count() - 2));
foreach (QString fileName, theDir.entryList(QDir::Files))
{
// Don't attempt to load non-gluon_plugin prefixed libraries
if(!fileName.contains("gluon"))
continue;
// Don't attempt to load non-libraries
if(!QLibrary::isLibrary(theDir.absoluteFilePath(fileName)))
continue;
QPluginLoader loader(theDir.absoluteFilePath(fileName));
loader.load();
if(!loader.isLoaded())
{
DEBUG_TEXT(loader.errorString());
}
}
}
}
#include "gluonobjectfactory.moc"
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "WorkerThread.h"
namespace avg {
using namespace std;
#ifdef linux
void printAffinityMask(cpu_set_t& mask)
{
for (int i=0; i<32; ++i) {
cerr << int(CPU_ISSET(i, &mask));
}
cerr << endl;
}
#endif
void setAffinityMask(bool bIsMainThread)
{
// The main thread gets the first processor to itself. All other threads share the
// rest of the processors available, unless, of course, there is only one processor
// in the machine.
#ifdef linux
static cpu_set_t allProcessors;
static bool bInitialized = false;
if (!bInitialized) {
int rc = sched_getaffinity(0, sizeof(allProcessors), &allProcessors);
AVG_ASSERT(rc == 0);
// cerr << "All processors: ";
// printAffinityMask(allProcessors);
bInitialized = true;
}
cpu_set_t mask;
if (bIsMainThread) {
CPU_ZERO(&mask);
CPU_SET(0, &mask);
// cerr << "Main Thread: ";
} else {
mask = allProcessors;
if (CPU_COUNT(&mask) > 1) {
CPU_CLR(0, &mask);
}
// cerr << "Aux Thread: ";
}
// printAffinityMask(mask);
int rc = sched_setaffinity(0, sizeof(mask), &mask);
AVG_ASSERT(rc == 0);
#endif
}
}
<commit_msg>Added thread affinity support for windows.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "WorkerThread.h"
#include "OSHelper.h"
#ifdef _WIN32
#include <Windows.h>
#endif
namespace avg {
using namespace std;
#ifdef linux
void printAffinityMask(cpu_set_t& mask)
{
for (int i=0; i<32; ++i) {
cerr << int(CPU_ISSET(i, &mask));
}
cerr << endl;
}
#endif
unsigned getLowestBitSet(unsigned val)
{
AVG_ASSERT(val != 0); // Doh
unsigned pos = 0;
while (!(val & 1)) {
val >>= 1;
++pos;
}
return pos;
}
void setAffinityMask(bool bIsMainThread)
{
// The main thread gets the first processor to itself. All other threads share the
// rest of the processors available, unless, of course, there is only one processor
// in the machine.
#ifdef linux
static cpu_set_t allProcessors;
static bool bInitialized = false;
if (!bInitialized) {
int rc = sched_getaffinity(0, sizeof(allProcessors), &allProcessors);
AVG_ASSERT(rc == 0);
// cerr << "All processors: ";
// printAffinityMask(allProcessors);
bInitialized = true;
}
cpu_set_t mask;
if (bIsMainThread) {
CPU_ZERO(&mask);
CPU_SET(0, &mask);
// cerr << "Main Thread: ";
} else {
mask = allProcessors;
if (CPU_COUNT(&mask) > 1) {
CPU_CLR(0, &mask);
}
// cerr << "Aux Thread: ";
}
// printAffinityMask(mask);
int rc = sched_setaffinity(0, sizeof(mask), &mask);
AVG_ASSERT(rc == 0);
#elif defined _WIN32
DWORD processAffinityMask;
DWORD systemAffinityMask;
BOOL rc = GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask,
&systemAffinityMask);
AVG_ASSERT(rc == TRUE);
DWORD mainThreadMask = 1 << getLowestBitSet(processAffinityMask);
DWORD mask;
if (bIsMainThread) {
mask = mainThreadMask;
} else {
mask = processAffinityMask & ~mainThreadMask;
}
DWORD_PTR pPrevMask = SetThreadAffinityMask(GetCurrentThread(), mainThreadMask);
AVG_ASSERT_MSG(pPrevMask != 0, getWinErrMsg(GetLastError()).c_str());
#endif
}
}
<|endoftext|> |
<commit_before>#pragma once
// `krbn::console_user_server::components_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "chrono_utility.hpp"
#include "components_manager_killer.hpp"
#include "constants.hpp"
#include "grabber_client.hpp"
#include "launchctl_utility.hpp"
#include "logger.hpp"
#include "menu_process_manager.hpp"
#include "monitor/configuration_monitor.hpp"
#include "monitor/version_monitor.hpp"
#include "updater_process_manager.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/frontmost_application_monitor.hpp>
#include <pqrs/osx/input_source_monitor.hpp>
#include <pqrs/osx/input_source_selector.hpp>
#include <pqrs/osx/input_source_selector/extra/nlohmann_json.hpp>
#include <pqrs/osx/json_file_monitor.hpp>
#include <pqrs/osx/session.hpp>
#include <pqrs/osx/system_preferences_monitor.hpp>
#include <pqrs/shell.hpp>
#include <thread>
namespace krbn {
namespace console_user_server {
class components_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
components_manager(const components_manager&) = delete;
components_manager(void) : dispatcher_client() {
//
// version_monitor_
//
version_monitor_ = std::make_unique<krbn::version_monitor>(krbn::constants::get_version_file_path());
version_monitor_->changed.connect([](auto&& version) {
if (auto killer = components_manager_killer::get_shared_components_manager_killer()) {
killer->async_kill();
}
});
//
// session_monitor_
//
session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_);
session_monitor_->on_console_changed.connect([this](auto&& on_console) {
if (!on_console) {
stop_grabber_client();
} else {
version_monitor_->async_manual_check();
pqrs::filesystem::create_directory_with_intermediate_directories(
constants::get_user_configuration_directory(),
0700);
stop_grabber_client();
start_grabber_client();
}
});
}
virtual ~components_manager(void) {
detach_from_dispatcher([this] {
stop_grabber_client();
session_monitor_ = nullptr;
version_monitor_ = nullptr;
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
version_monitor_->async_start();
session_monitor_->async_start(std::chrono::milliseconds(1000));
});
}
private:
std::filesystem::path grabber_client_socket_directory_path(void) const {
return fmt::format("{0}/grabber_client",
constants::get_system_user_directory(geteuid()).string());
}
std::filesystem::path grabber_client_socket_file_path(void) const {
return fmt::format("{0}/{1:x}.sock",
grabber_client_socket_directory_path().string(),
chrono_utility::nanoseconds_since_epoch());
}
void start_grabber_client(void) {
if (grabber_client_) {
return;
}
// Remove old socket files.
{
auto directory_path = grabber_client_socket_directory_path();
std::error_code ec;
std::filesystem::remove_all(directory_path, ec);
std::filesystem::create_directory(directory_path, ec);
}
grabber_client_ = std::make_shared<grabber_client>(grabber_client_socket_file_path());
grabber_client_->connected.connect([this] {
version_monitor_->async_manual_check();
if (grabber_client_) {
grabber_client_->async_connect_console_user_server();
}
stop_child_components();
start_child_components();
});
grabber_client_->connect_failed.connect([this](auto&& error_code) {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->closed.connect([this] {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->received.connect([this](auto&& buffer, auto&& sender_endpoint) {
if (buffer) {
if (buffer->empty()) {
return;
}
try {
nlohmann::json json = nlohmann::json::from_msgpack(*buffer);
switch (json.at("operation_type").get<operation_type>()) {
case operation_type::select_input_source: {
using specifiers_t = std::vector<pqrs::osx::input_source_selector::specifier>;
auto specifiers = json.at("input_source_specifiers").get<specifiers_t>();
if (input_source_selector_) {
input_source_selector_->async_select(std::make_shared<specifiers_t>(specifiers));
}
break;
}
case operation_type::shell_command_execution: {
auto shell_command = json.at("shell_command").get<std::string>();
auto background_shell_command = pqrs::shell::make_background_command_string(shell_command);
system(background_shell_command.c_str());
break;
}
default:
break;
}
return;
} catch (std::exception& e) {
logger::get_logger()->error("received data is corrupted");
}
}
});
grabber_client_->async_start();
}
void stop_grabber_client(void) {
grabber_client_ = nullptr;
stop_child_components();
}
void start_child_components(void) {
configuration_monitor_ = std::make_shared<configuration_monitor>(constants::get_user_core_configuration_file_path(),
geteuid());
// menu_process_manager_
menu_process_manager_ = std::make_unique<menu_process_manager>(configuration_monitor_);
// Restart NotificationWindow
launchctl_utility::restart_notification_window();
// Run MultitouchExtension
application_launcher::launch_multitouch_extension(true);
// updater_process_manager_
updater_process_manager_ = std::make_unique<updater_process_manager>(configuration_monitor_);
// system_preferences_monitor_
system_preferences_monitor_ = std::make_unique<pqrs::osx::system_preferences_monitor>(weak_dispatcher_);
system_preferences_monitor_->system_preferences_changed.connect([this](auto&& properties_ptr) {
if (grabber_client_) {
grabber_client_->async_system_preferences_updated(properties_ptr);
}
});
system_preferences_monitor_->async_start(std::chrono::milliseconds(3000));
// frontmost_application_monitor_
frontmost_application_monitor_ = std::make_unique<pqrs::osx::frontmost_application_monitor::monitor>(weak_dispatcher_);
frontmost_application_monitor_->frontmost_application_changed.connect([this](auto&& application_ptr) {
if (application_ptr) {
if (application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner.EventViewer" ||
application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner-EventViewer") {
return;
}
if (grabber_client_) {
grabber_client_->async_frontmost_application_changed(application_ptr);
}
}
});
frontmost_application_monitor_->async_start();
// input_source_monitor_
input_source_monitor_ = std::make_unique<pqrs::osx::input_source_monitor>(
pqrs::dispatcher::extra::get_shared_dispatcher());
input_source_monitor_->input_source_changed.connect([this](auto&& input_source_ptr) {
if (input_source_ptr && grabber_client_) {
auto properties = std::make_shared<pqrs::osx::input_source::properties>(*input_source_ptr);
grabber_client_->async_input_source_changed(properties);
}
});
input_source_monitor_->async_start();
// input_source_selector_
input_source_selector_ = std::make_unique<pqrs::osx::input_source_selector::selector>(weak_dispatcher_);
// Start configuration_monitor_
configuration_monitor_->async_start();
}
void stop_child_components(void) {
menu_process_manager_ = nullptr;
updater_process_manager_ = nullptr;
system_preferences_monitor_ = nullptr;
frontmost_application_monitor_ = nullptr;
input_source_monitor_ = nullptr;
input_source_selector_ = nullptr;
configuration_monitor_ = nullptr;
}
// Core components
std::unique_ptr<version_monitor> version_monitor_;
std::unique_ptr<pqrs::osx::session::monitor> session_monitor_;
std::shared_ptr<grabber_client> grabber_client_;
// Child components
std::shared_ptr<configuration_monitor> configuration_monitor_;
std::unique_ptr<menu_process_manager> menu_process_manager_;
std::unique_ptr<updater_process_manager> updater_process_manager_;
std::unique_ptr<pqrs::osx::system_preferences_monitor> system_preferences_monitor_;
// `frontmost_application_monitor` does not work properly in karabiner_grabber after fast user switching.
// Therefore, we have to use `frontmost_application_monitor` in `console_user_server`.
std::unique_ptr<pqrs::osx::frontmost_application_monitor::monitor> frontmost_application_monitor_;
std::unique_ptr<pqrs::osx::input_source_monitor> input_source_monitor_;
std::unique_ptr<pqrs::osx::input_source_selector::selector> input_source_selector_;
};
} // namespace console_user_server
} // namespace krbn
<commit_msg>Call prepare_grabber_client_socket_directory in connect_failed<commit_after>#pragma once
// `krbn::console_user_server::components_manager` can be used safely in a multi-threaded environment.
#include "application_launcher.hpp"
#include "chrono_utility.hpp"
#include "components_manager_killer.hpp"
#include "constants.hpp"
#include "grabber_client.hpp"
#include "launchctl_utility.hpp"
#include "logger.hpp"
#include "menu_process_manager.hpp"
#include "monitor/configuration_monitor.hpp"
#include "monitor/version_monitor.hpp"
#include "updater_process_manager.hpp"
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/frontmost_application_monitor.hpp>
#include <pqrs/osx/input_source_monitor.hpp>
#include <pqrs/osx/input_source_selector.hpp>
#include <pqrs/osx/input_source_selector/extra/nlohmann_json.hpp>
#include <pqrs/osx/json_file_monitor.hpp>
#include <pqrs/osx/session.hpp>
#include <pqrs/osx/system_preferences_monitor.hpp>
#include <pqrs/shell.hpp>
#include <thread>
namespace krbn {
namespace console_user_server {
class components_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
components_manager(const components_manager&) = delete;
components_manager(void) : dispatcher_client() {
//
// version_monitor_
//
version_monitor_ = std::make_unique<krbn::version_monitor>(krbn::constants::get_version_file_path());
version_monitor_->changed.connect([](auto&& version) {
if (auto killer = components_manager_killer::get_shared_components_manager_killer()) {
killer->async_kill();
}
});
//
// session_monitor_
//
session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_);
session_monitor_->on_console_changed.connect([this](auto&& on_console) {
if (!on_console) {
stop_grabber_client();
} else {
version_monitor_->async_manual_check();
pqrs::filesystem::create_directory_with_intermediate_directories(
constants::get_user_configuration_directory(),
0700);
stop_grabber_client();
start_grabber_client();
}
});
}
virtual ~components_manager(void) {
detach_from_dispatcher([this] {
stop_grabber_client();
session_monitor_ = nullptr;
version_monitor_ = nullptr;
});
}
void async_start(void) {
enqueue_to_dispatcher([this] {
version_monitor_->async_start();
session_monitor_->async_start(std::chrono::milliseconds(1000));
});
}
private:
std::filesystem::path grabber_client_socket_directory_path(void) const {
return constants::get_system_user_directory(geteuid()) / "grabber_client";
}
std::filesystem::path grabber_client_socket_file_path(void) const {
return fmt::format("{0}/{1:x}.sock",
grabber_client_socket_directory_path().string(),
chrono_utility::nanoseconds_since_epoch());
}
void prepare_grabber_client_socket_directory(void) {
//
// Remove old socket files.
//
auto directory_path = grabber_client_socket_directory_path();
std::error_code ec;
std::filesystem::remove_all(directory_path, ec);
//
// Create directory.
//
std::filesystem::create_directory(directory_path, ec);
}
void start_grabber_client(void) {
if (grabber_client_) {
return;
}
prepare_grabber_client_socket_directory();
grabber_client_ = std::make_shared<grabber_client>(grabber_client_socket_file_path());
grabber_client_->connected.connect([this] {
version_monitor_->async_manual_check();
if (grabber_client_) {
grabber_client_->async_connect_console_user_server();
}
stop_child_components();
start_child_components();
});
grabber_client_->connect_failed.connect([this](auto&& error_code) {
version_monitor_->async_manual_check();
stop_child_components();
// connect_failed will be triggered if grabber_client_socket_directory does not exist
// due to the parent directory (system_user_directory) is not ready.
// For this case, we have to create grabber_client_socket_directory each time.
prepare_grabber_client_socket_directory();
});
grabber_client_->closed.connect([this] {
version_monitor_->async_manual_check();
stop_child_components();
});
grabber_client_->received.connect([this](auto&& buffer, auto&& sender_endpoint) {
if (buffer) {
if (buffer->empty()) {
return;
}
try {
nlohmann::json json = nlohmann::json::from_msgpack(*buffer);
switch (json.at("operation_type").get<operation_type>()) {
case operation_type::select_input_source: {
using specifiers_t = std::vector<pqrs::osx::input_source_selector::specifier>;
auto specifiers = json.at("input_source_specifiers").get<specifiers_t>();
if (input_source_selector_) {
input_source_selector_->async_select(std::make_shared<specifiers_t>(specifiers));
}
break;
}
case operation_type::shell_command_execution: {
auto shell_command = json.at("shell_command").get<std::string>();
auto background_shell_command = pqrs::shell::make_background_command_string(shell_command);
system(background_shell_command.c_str());
break;
}
default:
break;
}
return;
} catch (std::exception& e) {
logger::get_logger()->error("received data is corrupted");
}
}
});
grabber_client_->async_start();
}
void stop_grabber_client(void) {
grabber_client_ = nullptr;
stop_child_components();
}
void start_child_components(void) {
configuration_monitor_ = std::make_shared<configuration_monitor>(constants::get_user_core_configuration_file_path(),
geteuid());
// menu_process_manager_
menu_process_manager_ = std::make_unique<menu_process_manager>(configuration_monitor_);
// Restart NotificationWindow
launchctl_utility::restart_notification_window();
// Run MultitouchExtension
application_launcher::launch_multitouch_extension(true);
// updater_process_manager_
updater_process_manager_ = std::make_unique<updater_process_manager>(configuration_monitor_);
// system_preferences_monitor_
system_preferences_monitor_ = std::make_unique<pqrs::osx::system_preferences_monitor>(weak_dispatcher_);
system_preferences_monitor_->system_preferences_changed.connect([this](auto&& properties_ptr) {
if (grabber_client_) {
grabber_client_->async_system_preferences_updated(properties_ptr);
}
});
system_preferences_monitor_->async_start(std::chrono::milliseconds(3000));
// frontmost_application_monitor_
frontmost_application_monitor_ = std::make_unique<pqrs::osx::frontmost_application_monitor::monitor>(weak_dispatcher_);
frontmost_application_monitor_->frontmost_application_changed.connect([this](auto&& application_ptr) {
if (application_ptr) {
if (application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner.EventViewer" ||
application_ptr->get_bundle_identifier() == "org.pqrs.Karabiner-EventViewer") {
return;
}
if (grabber_client_) {
grabber_client_->async_frontmost_application_changed(application_ptr);
}
}
});
frontmost_application_monitor_->async_start();
// input_source_monitor_
input_source_monitor_ = std::make_unique<pqrs::osx::input_source_monitor>(
pqrs::dispatcher::extra::get_shared_dispatcher());
input_source_monitor_->input_source_changed.connect([this](auto&& input_source_ptr) {
if (input_source_ptr && grabber_client_) {
auto properties = std::make_shared<pqrs::osx::input_source::properties>(*input_source_ptr);
grabber_client_->async_input_source_changed(properties);
}
});
input_source_monitor_->async_start();
// input_source_selector_
input_source_selector_ = std::make_unique<pqrs::osx::input_source_selector::selector>(weak_dispatcher_);
// Start configuration_monitor_
configuration_monitor_->async_start();
}
void stop_child_components(void) {
menu_process_manager_ = nullptr;
updater_process_manager_ = nullptr;
system_preferences_monitor_ = nullptr;
frontmost_application_monitor_ = nullptr;
input_source_monitor_ = nullptr;
input_source_selector_ = nullptr;
configuration_monitor_ = nullptr;
}
// Core components
std::unique_ptr<version_monitor> version_monitor_;
std::unique_ptr<pqrs::osx::session::monitor> session_monitor_;
std::shared_ptr<grabber_client> grabber_client_;
// Child components
std::shared_ptr<configuration_monitor> configuration_monitor_;
std::unique_ptr<menu_process_manager> menu_process_manager_;
std::unique_ptr<updater_process_manager> updater_process_manager_;
std::unique_ptr<pqrs::osx::system_preferences_monitor> system_preferences_monitor_;
// `frontmost_application_monitor` does not work properly in karabiner_grabber after fast user switching.
// Therefore, we have to use `frontmost_application_monitor` in `console_user_server`.
std::unique_ptr<pqrs::osx::frontmost_application_monitor::monitor> frontmost_application_monitor_;
std::unique_ptr<pqrs::osx::input_source_monitor> input_source_monitor_;
std::unique_ptr<pqrs::osx::input_source_selector::selector> input_source_selector_;
};
} // namespace console_user_server
} // namespace krbn
<|endoftext|> |
<commit_before>// @(#)root/meta:$Id$
// Author: Rene Brun 04/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons . *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// // //
// Basic data type descriptor (datatype information is obtained from //
// CINT). This class describes the attributes of type definitions //
// (typedef's). The TROOT class contains a list of all currently //
// defined types (accessible via TROOT::GetListOfTypes()). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TDataType.h"
#include "TInterpreter.h"
#include "TCollection.h"
#ifdef R__SOLARIS
#include <typeinfo>
#endif
ClassImp(TDataType)
TDataType* TDataType::fgBuiltins[kNumDataTypes] = {0};
//______________________________________________________________________________
TDataType::TDataType(TypedefInfo_t *info) : TDictionary()
{
// Default TDataType ctor. TDataTypes are constructed in TROOT via
// a call to TCint::UpdateListOfTypes().
fInfo = info;
if (fInfo) {
SetName(gCint->TypedefInfo_Name(fInfo));
SetTitle(gCint->TypedefInfo_Title(fInfo));
SetType(gCint->TypedefInfo_TrueName(fInfo));
fProperty = gCint->TypedefInfo_Property(fInfo);
fSize = gCint->TypedefInfo_Size(fInfo);
} else {
SetTitle("Builtin basic type");
fProperty = 0;
fSize = 0;
fType = kNoType_t;
}
}
//______________________________________________________________________________
TDataType::TDataType(const char *typenam) : fInfo(0), fProperty(kIsFundamental)
{
// Constructor for basic data types, like "char", "unsigned char", etc.
fInfo = 0;
SetName(typenam);
SetTitle("Builtin basic type");
SetType(fName.Data());
}
//______________________________________________________________________________
TDataType::TDataType(const TDataType& dt) :
TDictionary(dt),
fInfo(gCint->TypedefInfo_FactoryCopy(dt.fInfo)),
fSize(dt.fSize),
fType(dt.fType),
fProperty(dt.fProperty),
fTrueName(dt.fTrueName)
{
//copy constructor
}
//______________________________________________________________________________
TDataType& TDataType::operator=(const TDataType& dt)
{
//assignement operator
if(this!=&dt) {
TDictionary::operator=(dt);
gCint->TypedefInfo_Delete(fInfo);
fInfo=gCint->TypedefInfo_FactoryCopy(dt.fInfo);
fSize=dt.fSize;
fType=dt.fType;
fProperty=dt.fProperty;
fTrueName=dt.fTrueName;
}
return *this;
}
//______________________________________________________________________________
TDataType::~TDataType()
{
// TDataType dtor deletes adopted CINT TypedefInfo object.
gCint->TypedefInfo_Delete(fInfo);
}
//______________________________________________________________________________
const char *TDataType::GetTypeName(EDataType type)
{
// Return the name of the type.
switch (type) {
case 1: return "Char_t";
case 2: return "Short_t";
case 3: return "Int_t";
case 4: return "Long_t";
case 5: return "Float_t";
case 6: return "Int_t";
case 7: return "char*";
case 8: return "Double_t";
case 9: return "Double32_t";
case 11: return "UChar_t";
case 12: return "UShort_t";
case 13: return "UInt_t";
case 14: return "ULong_t";
case 15: return "UInt_t";
case 16: return "Long64_t";
case 17: return "ULong64_t";
case 18: return "Bool_t";
case 19: return "Float16_t";
case kVoid_t: return "void";
case kDataTypeAliasUnsigned_t: return "UInt_t";
case kOther_t: return "";
case kNoType_t: return "";
case kchar: return "Char_t";
default: return "";
}
return ""; // to silence compilers
}
//______________________________________________________________________________
const char *TDataType::GetTypeName() const
{
// Get basic type of typedef, e,g.: "class TDirectory*" -> "TDirectory".
// Result needs to be used or copied immediately.
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
return gInterpreter->TypeName(fTrueName.Data());
} else {
return fName.Data();
}
}
//______________________________________________________________________________
const char *TDataType::GetFullTypeName() const
{
// Get full type description of typedef, e,g.: "class TDirectory*".
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
return fTrueName;
} else {
return fName.Data();
}
}
//______________________________________________________________________________
EDataType TDataType::GetType(const type_info &typeinfo)
{
// Set type id depending on name.
EDataType retType = kOther_t;
if (!strcmp(typeid(unsigned int).name(), typeinfo.name())) {
retType = kUInt_t;
} else if (!strcmp(typeid(int).name(), typeinfo.name())) {
retType = kInt_t;
} else if (!strcmp(typeid(unsigned long).name(), typeinfo.name())) {
retType = kULong_t;
} else if (!strcmp(typeid(long).name(), typeinfo.name())) {
retType = kLong_t;
} else if (!strcmp(typeid(ULong64_t).name(), typeinfo.name())) {
retType = kULong64_t;
} else if (!strcmp(typeid(Long64_t).name(), typeinfo.name())) {
retType = kLong64_t;
} else if (!strcmp(typeid(unsigned short).name(), typeinfo.name())) {
retType = kUShort_t;
} else if (!strcmp(typeid(short).name(), typeinfo.name())) {
retType = kShort_t;
} else if (!strcmp(typeid(unsigned char).name(), typeinfo.name())) {
retType = kUChar_t;
} else if (!strcmp(typeid(char).name(), typeinfo.name())) {
retType = kChar_t;
} else if (!strcmp(typeid(bool).name(), typeinfo.name())) {
retType = kBool_t;
} else if (!strcmp(typeid(float).name(), typeinfo.name())) {
retType = kFloat_t;
} else if (!strcmp(typeid(Float16_t).name(), typeinfo.name())) {
retType = kFloat16_t;
} else if (!strcmp(typeid(double).name(), typeinfo.name())) {
retType = kDouble_t;
} else if (!strcmp(typeid(Double32_t).name(), typeinfo.name())) {
retType = kDouble32_t;
} else if (!strcmp(typeid(char*).name(), typeinfo.name())) {
retType = kCharStar;
}
return retType;
}
//______________________________________________________________________________
const char *TDataType::AsString(void *buf) const
{
// Return string containing value in buffer formatted according to
// the basic data type. The result needs to be used or copied immediately.
static TString line(81);
const char *name;
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
name = fTrueName;
} else {
name = fName.Data();
}
line[0] = 0;
if (!strcmp("unsigned int", name))
line.Form( "%u", *(unsigned int *)buf);
else if (!strcmp("unsigned", name))
line.Form( "%u", *(unsigned int *)buf);
else if (!strcmp("int", name))
line.Form( "%d", *(int *)buf);
else if (!strcmp("unsigned long", name))
line.Form( "%lu", *(unsigned long *)buf);
else if (!strcmp("long", name))
line.Form( "%ld", *(long *)buf);
else if (!strcmp("unsigned long long", name))
line.Form( "%llu", *(ULong64_t *)buf);
else if (!strcmp("long long", name))
line.Form( "%lld", *(Long64_t *)buf);
else if (!strcmp("unsigned short", name))
line.Form( "%hu", *(unsigned short *)buf);
else if (!strcmp("short", name))
line.Form( "%hd", *(short *)buf);
else if (!strcmp("bool", name))
line.Form( "%s", *(bool *)buf ? "true" : "false");
else if (!strcmp("unsigned char", name) || !strcmp("char", name) ) {
line = (char*)buf;
} else if (!strcmp("float", name))
line.Form( "%g", *(float *)buf);
else if (!strcmp("double", name))
line.Form( "%g", *(double *)buf);
else if (!strcmp("char*", name))
line.Form( "%s", *(char**)buf);
return line;
}
//______________________________________________________________________________
Long_t TDataType::Property() const
{
// Get property description word. For meaning of bits see EProperty.
if (fInfo) (const_cast<TDataType*>(this))->CheckInfo();
return fProperty;
}
//______________________________________________________________________________
void TDataType::SetType(const char *name)
{
// Set type id depending on name.
fTrueName = name;
fType = kOther_t;
fSize = 0;
if (!strcmp("unsigned int", name)) {
fType = kUInt_t;
fSize = sizeof(UInt_t);
} else if (!strcmp("unsigned", name)) {
fType = kUInt_t;
fSize = sizeof(UInt_t);
} else if (!strcmp("int", name)) {
fType = kInt_t;
fSize = sizeof(Int_t);
} else if (!strcmp("unsigned long", name)) {
fType = kULong_t;
fSize = sizeof(ULong_t);
} else if (!strcmp("long", name)) {
fType = kLong_t;
fSize = sizeof(Long_t);
} else if (!strcmp("unsigned long long", name)) {
fType = kULong64_t;
fSize = sizeof(ULong64_t);
} else if (!strcmp("long long", name)) {
fType = kLong64_t;
fSize = sizeof(Long64_t);
} else if (!strcmp("unsigned short", name)) {
fType = kUShort_t;
fSize = sizeof(UShort_t);
} else if (!strcmp("short", name)) {
fType = kShort_t;
fSize = sizeof(Short_t);
} else if (!strcmp("unsigned char", name)) {
fType = kUChar_t;
fSize = sizeof(UChar_t);
} else if (!strcmp("char", name)) {
fType = kChar_t;
fSize = sizeof(Char_t);
} else if (!strcmp("bool", name)) {
fType = kBool_t;
fSize = sizeof(Bool_t);
} else if (!strcmp("float", name)) {
fType = kFloat_t;
fSize = sizeof(Float_t);
} else if (!strcmp("double", name)) {
fType = kDouble_t;
fSize = sizeof(Double_t);
}
if (!strcmp("Float16_t", fName.Data())) {
fType = kFloat16_t;
}
if (!strcmp("Double32_t", fName.Data())) {
fType = kDouble32_t;
}
if (!strcmp("char*",fName.Data())) {
fType = kCharStar;
}
// kCounter = 6, kBits = 15
}
//______________________________________________________________________________
Int_t TDataType::Size() const
{
// Get size of basic typedef'ed type.
if (fInfo) (const_cast<TDataType*>(this))->CheckInfo();
return fSize;
}
//______________________________________________________________________________
void TDataType::CheckInfo()
{
// Refresh the underlying information.
// This can be needed if the library defining this typedef was loaded after
// another library and that this other library is unloaded (in which case
// things can get renumbered inside CINT).
if (!fInfo) return;
// This intentionally cast the constness away so that
// we can call CheckInfo from const data members.
if (!gCint->TypedefInfo_IsValid(fInfo) ||
strcmp(gCint->TypedefInfo_Name(fInfo),fName.Data())!=0) {
// The fInfo is invalid or does not
// point to this typedef anymore, let's
// refresh it
gCint->TypedefInfo_Init(fInfo, fName.Data());
if (!gCint->TypedefInfo_IsValid(fInfo)) return;
SetTitle(gCint->TypedefInfo_Title(fInfo));
SetType(gCint->TypedefInfo_TrueName(fInfo));
fProperty = gCint->TypedefInfo_Property(fInfo);
fSize = gCint->TypedefInfo_Size(fInfo);
}
}
//______________________________________________________________________________
void TDataType::AddBuiltins(TCollection* types)
{
// Create the TDataType objects for builtins.
if (fgBuiltins[kChar_t] == 0) {
// Add also basic types (like a identity typedef "typedef int int")
fgBuiltins[kChar_t] = new TDataType("char");
fgBuiltins[kUChar_t] = new TDataType("unsigned char");
fgBuiltins[kShort_t] = new TDataType("short");
fgBuiltins[kUShort_t] = new TDataType("unsigned short");
fgBuiltins[kInt_t] = new TDataType("int");
fgBuiltins[kUInt_t] = new TDataType("unsigned int");
fgBuiltins[kLong_t] = new TDataType("long");
fgBuiltins[kULong_t] = new TDataType("unsigned long");
fgBuiltins[kLong64_t] = new TDataType("long long");
fgBuiltins[kULong64_t] = new TDataType("unsigned long long");
fgBuiltins[kFloat_t] = new TDataType("float");
fgBuiltins[kDouble_t] = new TDataType("double");
fgBuiltins[kVoid_t] = new TDataType("void");
fgBuiltins[kBool_t] = new TDataType("bool");
fgBuiltins[kCharStar] = new TDataType("char*");
fgBuiltins[kDataTypeAliasUnsigned_t] = new TDataType("unsigned");
}
for (Int_t i = 0; i < (Int_t)kNumDataTypes; ++i) {
if (fgBuiltins[i]) types->Add(fgBuiltins[i]);
}
}
//______________________________________________________________________________
TDataType* TDataType::GetDataType(EDataType type)
{
// Given a EDataType type, get the TDataType* that represents it.
if (type == kOther_t) return 0;
return fgBuiltins[(int)type];
}
<commit_msg>avoid null pointer deref (cov 35892)<commit_after>// @(#)root/meta:$Id$
// Author: Rene Brun 04/02/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons . *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// // //
// Basic data type descriptor (datatype information is obtained from //
// CINT). This class describes the attributes of type definitions //
// (typedef's). The TROOT class contains a list of all currently //
// defined types (accessible via TROOT::GetListOfTypes()). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TDataType.h"
#include "TInterpreter.h"
#include "TCollection.h"
#ifdef R__SOLARIS
#include <typeinfo>
#endif
ClassImp(TDataType)
TDataType* TDataType::fgBuiltins[kNumDataTypes] = {0};
//______________________________________________________________________________
TDataType::TDataType(TypedefInfo_t *info) : TDictionary()
{
// Default TDataType ctor. TDataTypes are constructed in TROOT via
// a call to TCint::UpdateListOfTypes().
fInfo = info;
if (fInfo) {
SetName(gCint->TypedefInfo_Name(fInfo));
SetTitle(gCint->TypedefInfo_Title(fInfo));
SetType(gCint->TypedefInfo_TrueName(fInfo));
fProperty = gCint->TypedefInfo_Property(fInfo);
fSize = gCint->TypedefInfo_Size(fInfo);
} else {
SetTitle("Builtin basic type");
fProperty = 0;
fSize = 0;
fType = kNoType_t;
}
}
//______________________________________________________________________________
TDataType::TDataType(const char *typenam) : fInfo(0), fProperty(kIsFundamental)
{
// Constructor for basic data types, like "char", "unsigned char", etc.
fInfo = 0;
SetName(typenam);
SetTitle("Builtin basic type");
SetType(fName.Data());
}
//______________________________________________________________________________
TDataType::TDataType(const TDataType& dt) :
TDictionary(dt),
fInfo(gCint->TypedefInfo_FactoryCopy(dt.fInfo)),
fSize(dt.fSize),
fType(dt.fType),
fProperty(dt.fProperty),
fTrueName(dt.fTrueName)
{
//copy constructor
}
//______________________________________________________________________________
TDataType& TDataType::operator=(const TDataType& dt)
{
//assignement operator
if(this!=&dt) {
TDictionary::operator=(dt);
gCint->TypedefInfo_Delete(fInfo);
fInfo=gCint->TypedefInfo_FactoryCopy(dt.fInfo);
fSize=dt.fSize;
fType=dt.fType;
fProperty=dt.fProperty;
fTrueName=dt.fTrueName;
}
return *this;
}
//______________________________________________________________________________
TDataType::~TDataType()
{
// TDataType dtor deletes adopted CINT TypedefInfo object.
gCint->TypedefInfo_Delete(fInfo);
}
//______________________________________________________________________________
const char *TDataType::GetTypeName(EDataType type)
{
// Return the name of the type.
switch (type) {
case 1: return "Char_t";
case 2: return "Short_t";
case 3: return "Int_t";
case 4: return "Long_t";
case 5: return "Float_t";
case 6: return "Int_t";
case 7: return "char*";
case 8: return "Double_t";
case 9: return "Double32_t";
case 11: return "UChar_t";
case 12: return "UShort_t";
case 13: return "UInt_t";
case 14: return "ULong_t";
case 15: return "UInt_t";
case 16: return "Long64_t";
case 17: return "ULong64_t";
case 18: return "Bool_t";
case 19: return "Float16_t";
case kVoid_t: return "void";
case kDataTypeAliasUnsigned_t: return "UInt_t";
case kOther_t: return "";
case kNoType_t: return "";
case kchar: return "Char_t";
default: return "";
}
return ""; // to silence compilers
}
//______________________________________________________________________________
const char *TDataType::GetTypeName() const
{
// Get basic type of typedef, e,g.: "class TDirectory*" -> "TDirectory".
// Result needs to be used or copied immediately.
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
return gInterpreter->TypeName(fTrueName.Data());
} else {
return fName.Data();
}
}
//______________________________________________________________________________
const char *TDataType::GetFullTypeName() const
{
// Get full type description of typedef, e,g.: "class TDirectory*".
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
return fTrueName;
} else {
return fName.Data();
}
}
//______________________________________________________________________________
EDataType TDataType::GetType(const type_info &typeinfo)
{
// Set type id depending on name.
EDataType retType = kOther_t;
if (!strcmp(typeid(unsigned int).name(), typeinfo.name())) {
retType = kUInt_t;
} else if (!strcmp(typeid(int).name(), typeinfo.name())) {
retType = kInt_t;
} else if (!strcmp(typeid(unsigned long).name(), typeinfo.name())) {
retType = kULong_t;
} else if (!strcmp(typeid(long).name(), typeinfo.name())) {
retType = kLong_t;
} else if (!strcmp(typeid(ULong64_t).name(), typeinfo.name())) {
retType = kULong64_t;
} else if (!strcmp(typeid(Long64_t).name(), typeinfo.name())) {
retType = kLong64_t;
} else if (!strcmp(typeid(unsigned short).name(), typeinfo.name())) {
retType = kUShort_t;
} else if (!strcmp(typeid(short).name(), typeinfo.name())) {
retType = kShort_t;
} else if (!strcmp(typeid(unsigned char).name(), typeinfo.name())) {
retType = kUChar_t;
} else if (!strcmp(typeid(char).name(), typeinfo.name())) {
retType = kChar_t;
} else if (!strcmp(typeid(bool).name(), typeinfo.name())) {
retType = kBool_t;
} else if (!strcmp(typeid(float).name(), typeinfo.name())) {
retType = kFloat_t;
} else if (!strcmp(typeid(Float16_t).name(), typeinfo.name())) {
retType = kFloat16_t;
} else if (!strcmp(typeid(double).name(), typeinfo.name())) {
retType = kDouble_t;
} else if (!strcmp(typeid(Double32_t).name(), typeinfo.name())) {
retType = kDouble32_t;
} else if (!strcmp(typeid(char*).name(), typeinfo.name())) {
retType = kCharStar;
}
return retType;
}
//______________________________________________________________________________
const char *TDataType::AsString(void *buf) const
{
// Return string containing value in buffer formatted according to
// the basic data type. The result needs to be used or copied immediately.
static TString line(81);
const char *name;
if (fInfo) {
(const_cast<TDataType*>(this))->CheckInfo();
name = fTrueName;
} else {
name = fName.Data();
}
line[0] = 0;
if (!strcmp("unsigned int", name))
line.Form( "%u", *(unsigned int *)buf);
else if (!strcmp("unsigned", name))
line.Form( "%u", *(unsigned int *)buf);
else if (!strcmp("int", name))
line.Form( "%d", *(int *)buf);
else if (!strcmp("unsigned long", name))
line.Form( "%lu", *(unsigned long *)buf);
else if (!strcmp("long", name))
line.Form( "%ld", *(long *)buf);
else if (!strcmp("unsigned long long", name))
line.Form( "%llu", *(ULong64_t *)buf);
else if (!strcmp("long long", name))
line.Form( "%lld", *(Long64_t *)buf);
else if (!strcmp("unsigned short", name))
line.Form( "%hu", *(unsigned short *)buf);
else if (!strcmp("short", name))
line.Form( "%hd", *(short *)buf);
else if (!strcmp("bool", name))
line.Form( "%s", *(bool *)buf ? "true" : "false");
else if (!strcmp("unsigned char", name) || !strcmp("char", name) ) {
line = (char*)buf;
} else if (!strcmp("float", name))
line.Form( "%g", *(float *)buf);
else if (!strcmp("double", name))
line.Form( "%g", *(double *)buf);
else if (!strcmp("char*", name))
line.Form( "%s", *(char**)buf);
return line;
}
//______________________________________________________________________________
Long_t TDataType::Property() const
{
// Get property description word. For meaning of bits see EProperty.
if (fInfo) (const_cast<TDataType*>(this))->CheckInfo();
return fProperty;
}
//______________________________________________________________________________
void TDataType::SetType(const char *name)
{
// Set type id depending on name.
fTrueName = name;
fType = kOther_t;
fSize = 0;
if (name==0) {
return;
} else if (!strcmp("unsigned int", name)) {
fType = kUInt_t;
fSize = sizeof(UInt_t);
} else if (!strcmp("unsigned", name)) {
fType = kUInt_t;
fSize = sizeof(UInt_t);
} else if (!strcmp("int", name)) {
fType = kInt_t;
fSize = sizeof(Int_t);
} else if (!strcmp("unsigned long", name)) {
fType = kULong_t;
fSize = sizeof(ULong_t);
} else if (!strcmp("long", name)) {
fType = kLong_t;
fSize = sizeof(Long_t);
} else if (!strcmp("unsigned long long", name)) {
fType = kULong64_t;
fSize = sizeof(ULong64_t);
} else if (!strcmp("long long", name)) {
fType = kLong64_t;
fSize = sizeof(Long64_t);
} else if (!strcmp("unsigned short", name)) {
fType = kUShort_t;
fSize = sizeof(UShort_t);
} else if (!strcmp("short", name)) {
fType = kShort_t;
fSize = sizeof(Short_t);
} else if (!strcmp("unsigned char", name)) {
fType = kUChar_t;
fSize = sizeof(UChar_t);
} else if (!strcmp("char", name)) {
fType = kChar_t;
fSize = sizeof(Char_t);
} else if (!strcmp("bool", name)) {
fType = kBool_t;
fSize = sizeof(Bool_t);
} else if (!strcmp("float", name)) {
fType = kFloat_t;
fSize = sizeof(Float_t);
} else if (!strcmp("double", name)) {
fType = kDouble_t;
fSize = sizeof(Double_t);
}
if (!strcmp("Float16_t", fName.Data())) {
fType = kFloat16_t;
}
if (!strcmp("Double32_t", fName.Data())) {
fType = kDouble32_t;
}
if (!strcmp("char*",fName.Data())) {
fType = kCharStar;
}
// kCounter = 6, kBits = 15
}
//______________________________________________________________________________
Int_t TDataType::Size() const
{
// Get size of basic typedef'ed type.
if (fInfo) (const_cast<TDataType*>(this))->CheckInfo();
return fSize;
}
//______________________________________________________________________________
void TDataType::CheckInfo()
{
// Refresh the underlying information.
// This can be needed if the library defining this typedef was loaded after
// another library and that this other library is unloaded (in which case
// things can get renumbered inside CINT).
if (!fInfo) return;
// This intentionally cast the constness away so that
// we can call CheckInfo from const data members.
if (!gCint->TypedefInfo_IsValid(fInfo) ||
strcmp(gCint->TypedefInfo_Name(fInfo),fName.Data())!=0) {
// The fInfo is invalid or does not
// point to this typedef anymore, let's
// refresh it
gCint->TypedefInfo_Init(fInfo, fName.Data());
if (!gCint->TypedefInfo_IsValid(fInfo)) return;
SetTitle(gCint->TypedefInfo_Title(fInfo));
SetType(gCint->TypedefInfo_TrueName(fInfo));
fProperty = gCint->TypedefInfo_Property(fInfo);
fSize = gCint->TypedefInfo_Size(fInfo);
}
}
//______________________________________________________________________________
void TDataType::AddBuiltins(TCollection* types)
{
// Create the TDataType objects for builtins.
if (fgBuiltins[kChar_t] == 0) {
// Add also basic types (like a identity typedef "typedef int int")
fgBuiltins[kChar_t] = new TDataType("char");
fgBuiltins[kUChar_t] = new TDataType("unsigned char");
fgBuiltins[kShort_t] = new TDataType("short");
fgBuiltins[kUShort_t] = new TDataType("unsigned short");
fgBuiltins[kInt_t] = new TDataType("int");
fgBuiltins[kUInt_t] = new TDataType("unsigned int");
fgBuiltins[kLong_t] = new TDataType("long");
fgBuiltins[kULong_t] = new TDataType("unsigned long");
fgBuiltins[kLong64_t] = new TDataType("long long");
fgBuiltins[kULong64_t] = new TDataType("unsigned long long");
fgBuiltins[kFloat_t] = new TDataType("float");
fgBuiltins[kDouble_t] = new TDataType("double");
fgBuiltins[kVoid_t] = new TDataType("void");
fgBuiltins[kBool_t] = new TDataType("bool");
fgBuiltins[kCharStar] = new TDataType("char*");
fgBuiltins[kDataTypeAliasUnsigned_t] = new TDataType("unsigned");
}
for (Int_t i = 0; i < (Int_t)kNumDataTypes; ++i) {
if (fgBuiltins[i]) types->Add(fgBuiltins[i]);
}
}
//______________________________________________________________________________
TDataType* TDataType::GetDataType(EDataType type)
{
// Given a EDataType type, get the TDataType* that represents it.
if (type == kOther_t) return 0;
return fgBuiltins[(int)type];
}
<|endoftext|> |
<commit_before>#include "ctextparser.h"
#include <set>
inline int priority(TextFragment::Delimiter delimiter)
{
return delimiter;
}
std::vector<TextFragment> CTextParser::parse(const QString& text)
{
struct Delimiter {
QChar delimiterCharacter;
TextFragment::Delimiter delimiterType;
inline bool operator< (const Delimiter& other) const {
return delimiterCharacter < other.delimiterCharacter;
}
};
static const std::set<Delimiter> delimiters {
{' ', TextFragment::Space},
{'.', TextFragment::Point},
{':', TextFragment::Colon},
{';', TextFragment::Semicolon},
{',', TextFragment::Comma},
// TODO: dash should be ignored unless it has an adjacent space!
{'-', TextFragment::Dash},
{0x2014, TextFragment::Dash},
// TODO:
// {"...", TextFragment::Ellipsis},
{0x2026, TextFragment::Ellipsis},
{'!', TextFragment::ExclamationMark},
{'\n', TextFragment::Newline},
{'?', TextFragment::QuestionMark},
{'\"', TextFragment::Quote},
{')', TextFragment::Bracket},
{'(', TextFragment::Bracket},
{'[', TextFragment::Bracket},
{']', TextFragment::Bracket},
{'{', TextFragment::Bracket},
{'}', TextFragment::Bracket}
};
_fragments.clear();
for (QChar ch: text)
{
if (ch == '\r')
continue;
const auto it = delimiters.find({ch, TextFragment::NoDelimiter});
if (it == delimiters.end()) // Not a delimiter
{
if (_wordEnded) // This is the first letter of a new word
finalizeFragment();
_lastDelimiter = TextFragment::NoDelimiter;
_wordBuffer += ch;
}
else // This is a delimiter. Append it to the current word.
{
// The opening quote is not a delimiter; the closing one is.
if (it->delimiterType == TextFragment::Quote)
{
_quoteOpened = !_quoteOpened;
if (_quoteOpened) // This is an opening quote! Dump the previously accumulated fragment and assign this quote to the new one.
{
finalizeFragment();
_wordBuffer += ch;
}
else // Business as usual
{
// Don't let space, newline and quote in e. g. ", " override other punctuation marks
if (priority(it->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = it->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
else
{
// Don't let space, newline and quote in e. g. ", " override other punctuation marks
if (priority(it->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = it->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
}
finalizeFragment();
return _fragments;
}
void CTextParser::setAddEmptyFragmentAfterSentence(bool add)
{
_addEmptyFragmentAfterSentenceEnd = add;
}
void CTextParser::finalizeFragment()
{
_delimitersBuffer = _delimitersBuffer.trimmed();
if (!_delimitersBuffer.isEmpty() || !_wordBuffer.isEmpty())
{
TextFragment fragment(_wordBuffer, _delimitersBuffer, _lastDelimiter);
if (_addEmptyFragmentAfterSentenceEnd && fragment.isEndOfSentence())
{
_fragments.emplace_back(_wordBuffer, _delimitersBuffer, TextFragment::Comma);
// Moving the end-of-sentence delimiter off to a dummy fragment with no text - just so that we can fade the text out and hold the screen empty for a bit
_fragments.emplace_back(QString::null, QString::null, _lastDelimiter);
}
else
_fragments.push_back(fragment);
}
_wordEnded = false;
_delimitersBuffer.clear();
_wordBuffer.clear();
}
<commit_msg>Partial fix for #31<commit_after>#include "ctextparser.h"
#include <set>
inline int priority(TextFragment::Delimiter delimiter)
{
return delimiter;
}
std::vector<TextFragment> CTextParser::parse(const QString& text)
{
struct Delimiter {
QChar delimiterCharacter;
TextFragment::Delimiter delimiterType;
inline bool operator< (const Delimiter& other) const {
return delimiterCharacter < other.delimiterCharacter;
}
};
QString fixedText = text;
fixedText
.replace(QChar(0x00A0), ' ') // Non-breaking space -> regular space
.replace(". . .", QChar(0x2026)) // 3 space-separated dots -> ellipsis // TODO: regexp
.replace("...", QChar(0x2026)); // 3 dots -> ellipsis // TODO: regexp
static const std::set<Delimiter> delimiters {
{' ', TextFragment::Space},
{'.', TextFragment::Point},
{':', TextFragment::Colon},
{';', TextFragment::Semicolon},
{',', TextFragment::Comma},
// TODO: dash should be ignored unless it has an adjacent space!
{'-', TextFragment::Dash},
{0x2014, TextFragment::Dash},
// TODO:
// {"...", TextFragment::Ellipsis},
{0x2026, TextFragment::Ellipsis},
{'!', TextFragment::ExclamationMark},
{'\n', TextFragment::Newline},
{'?', TextFragment::QuestionMark},
{'\"', TextFragment::Quote},
{')', TextFragment::Bracket},
{'(', TextFragment::Bracket},
{'[', TextFragment::Bracket},
{']', TextFragment::Bracket},
{'{', TextFragment::Bracket},
{'}', TextFragment::Bracket}
};
_fragments.clear();
for (QChar ch: fixedText)
{
if (ch == '\r')
continue;
const auto it = delimiters.find({ch, TextFragment::NoDelimiter});
if (it == delimiters.end()) // Not a delimiter
{
if (_wordEnded) // This is the first letter of a new word
finalizeFragment();
_lastDelimiter = TextFragment::NoDelimiter;
_wordBuffer += ch;
}
else // This is a delimiter. Append it to the current word.
{
// The opening quote is not a delimiter; the closing one is.
if (it->delimiterType == TextFragment::Quote)
{
_quoteOpened = !_quoteOpened;
if (_quoteOpened) // This is an opening quote! Dump the previously accumulated fragment and assign this quote to the new one.
{
finalizeFragment();
_wordBuffer += ch;
}
else // Business as usual
{
// Don't let space, newline and quote in e. g. ", " override other punctuation marks
if (priority(it->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = it->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
else
{
// Don't let space, newline and quote in e. g. ", " override other punctuation marks
if (priority(it->delimiterType) >= priority(_lastDelimiter))
_lastDelimiter = it->delimiterType;
_wordEnded = true;
_delimitersBuffer += ch;
}
}
}
finalizeFragment();
return _fragments;
}
void CTextParser::setAddEmptyFragmentAfterSentence(bool add)
{
_addEmptyFragmentAfterSentenceEnd = add;
}
void CTextParser::finalizeFragment()
{
_delimitersBuffer = _delimitersBuffer.trimmed();
if (!_delimitersBuffer.isEmpty() || !_wordBuffer.isEmpty())
{
TextFragment fragment(_wordBuffer, _delimitersBuffer, _lastDelimiter);
if (_addEmptyFragmentAfterSentenceEnd && fragment.isEndOfSentence())
{
_fragments.emplace_back(_wordBuffer, _delimitersBuffer, TextFragment::Comma);
// Moving the end-of-sentence delimiter off to a dummy fragment with no text - just so that we can fade the text out and hold the screen empty for a bit
_fragments.emplace_back(QString::null, QString::null, _lastDelimiter);
}
else
_fragments.push_back(fragment);
}
_wordEnded = false;
_delimitersBuffer.clear();
_wordBuffer.clear();
}
<|endoftext|> |
<commit_before>/*
** Copyright 2009-2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QWriteLocker>
#include "com/centreon/broker/logging/defines.hh"
#include "com/centreon/broker/logging/internal.hh"
#include "com/centreon/broker/logging/logging.hh"
using namespace com::centreon::broker;
/**************************************
* *
* Internal Objects *
* *
**************************************/
// List of registered backends.
QHash<QSharedPointer<logging::backend>,
QPair<unsigned int, logging::level> >
logging::backends;
QReadWriteLock logging::backendsm;
/**************************************
* *
* Global Objects *
* *
**************************************/
logging::logger logging::config(CONFIG);
#ifdef NDEBUG
logging::void_logger logging::debug;
#else
logging::logger logging::debug(DEBUG);
#endif /* NDEBUG */
logging::logger logging::error(ERROR);
logging::logger logging::info(INFO);
/**
* Clear the list of logging objects.
*/
void logging::clear() {
backends.clear();
}
/**
* @brief Add or remove a log backend.
*
* If either types or min_priority is 0, the backend will be removed.
*
* @param[in] b Backend.
* @param[in] types Log types to store on this backend. Bitwise OR of
* multiple logging::type.
* @param[in] min_priority Minimal priority of messages to be logged.
*/
void logging::log_on(QSharedPointer<backend> b,
unsigned int types,
level min_priority) {
QWriteLocker lock(&backendsm);
if (types && min_priority) {
backends[b].first = types;
backends[b].second = min_priority;
}
else
backends.remove(b);
return ;
}
<commit_msg>Added missing hash function for the logging backend storage object.<commit_after>/*
** Copyright 2009-2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QWriteLocker>
#include "com/centreon/broker/logging/defines.hh"
#include "com/centreon/broker/logging/internal.hh"
#include "com/centreon/broker/logging/logging.hh"
using namespace com::centreon::broker;
/**************************************
* *
* Internal Objects *
* *
**************************************/
// Hash function.
static uint qHash(QSharedPointer<logging::backend> const& b) {
return ((uint)(unsigned long long)b.data());
}
// List of registered backends.
QHash<QSharedPointer<logging::backend>,
QPair<unsigned int, logging::level> >
logging::backends;
QReadWriteLock logging::backendsm;
/**************************************
* *
* Global Objects *
* *
**************************************/
logging::logger logging::config(CONFIG);
#ifdef NDEBUG
logging::void_logger logging::debug;
#else
logging::logger logging::debug(DEBUG);
#endif /* NDEBUG */
logging::logger logging::error(ERROR);
logging::logger logging::info(INFO);
/**
* Clear the list of logging objects.
*/
void logging::clear() {
backends.clear();
}
/**
* @brief Add or remove a log backend.
*
* If either types or min_priority is 0, the backend will be removed.
*
* @param[in] b Backend.
* @param[in] types Log types to store on this backend. Bitwise OR of
* multiple logging::type.
* @param[in] min_priority Minimal priority of messages to be logged.
*/
void logging::log_on(QSharedPointer<backend> b,
unsigned int types,
level min_priority) {
QWriteLocker lock(&backendsm);
if (types && min_priority) {
backends[b].first = types;
backends[b].second = min_priority;
}
else
backends.remove(b);
return ;
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.