commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
94070ee5e088685477a004f073ebb20bc973ad5d
|
main.cpp
|
main.cpp
|
/* Copyright (C) 2014 INRA
*
* 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 "io.hpp"
#include "model.hpp"
#include "solver.hpp"
#include "print.hpp"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <cstdlib>
#include <cstring>
namespace {
void usage() noexcept
{
std::cout << "efyj [-h|--help] [-s|--stress [number]] [files...]\n\n"
<< "Options:\n"
<< " -h, --help This help message\n"
<< " -s, --stress [int] Stress mode (check all solver/cache)\n"
<< " If no argument, the default"
" make 100000 run\n"
<< " [files...] DEXi file to run\n"
<< std::endl;
}
void process(const std::string& filepath)
{
efyj::dexi dexi_data;
std::ifstream is(filepath);
if (not is)
throw std::invalid_argument(
efyj::stringf("unknown file %s", filepath.c_str()));
efyj::read(is, dexi_data);
}
void generate_new_options(std::vector <std::uint8_t>& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
for (std::size_t i = 0, e = options.size(); i != e; ++i)
options[i] = distribution(rng) % high_level[i];
}
void generate_new_options(std::string& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
options.assign(high_level.size(), '0');
for (std::size_t i = 0, e = high_level.size(); i != e; ++i)
options[i] += (distribution(rng) % high_level[i]);
}
void generate_new_options(std::size_t& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
options = 0;
std::size_t indice = 0;
for (std::size_t i = 0, e = high_level.size(); i != e; ++i) {
options += ((distribution(rng) % high_level[i]) << indice);
indice += std::floor(std::log2(high_level[i]) + 1);
}
}
void process_stress_test(const std::string& filepath,
unsigned long run_number)
{
std::vector <std::chrono::duration <double>> time_result(6);
std::chrono::time_point <std::chrono::system_clock> start;
efyj::dexi model;
{
start = std::chrono::system_clock::now();
std::ifstream is(filepath);
if (not is)
throw std::invalid_argument(
efyj::stringf("unknown file %s", filepath.c_str()));
efyj::read(is, model);
time_result[0] = std::chrono::system_clock::now() - start;
}
std::vector <std::size_t> high_level(model.basic_scale_number);
int i = 0;
for (const auto& att : model.attributes)
if (att.children.empty())
high_level[i++] = att.scale_size();
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_basic si(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
si.solve(options);
}
time_result[1] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_hash sh(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sh.solve(options);
}
time_result[2] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::string options('0', model.basic_scale_number);
efyj::solver_hash sh(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sh.solve(options);
}
time_result[3] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_bigmem sbm(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sbm.solve(options);
}
time_result[4] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::size_t options;
efyj::solver_bigmem sbm(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sbm.solve(options);
}
time_result[5] = std::chrono::system_clock::now() - start;
}
auto min_max = std::minmax_element(time_result.begin() + 1, time_result.end(),
[](std::chrono::duration <double>& a,
std::chrono::duration <double>& b)
{
return a.count() < b.count();
});
std::cout << "Time elapsed to:\n"
<< "- read model........ : " << time_result[0].count() << "s\n"
<< "- get response for random " << run_number << " options:\n"
<< " - basic solver.............. : "
<< ((time_result[1].count() == min_max.first->count()) ? dCYAN : ((time_result[1].count() == min_max.second->count()) ? dRED : ""))
<< time_result[1].count() << "s (" << (run_number / (1000000 * time_result[1].count())) << " million op/s)\n" << dNORMAL
<< " - hash cache................ : "
<< ((time_result[2].count() == min_max.first->count()) ? dCYAN : ((time_result[2].count() == min_max.second->count()) ? dRED : ""))
<< time_result[2].count() << "s (" << (run_number / (1000000 * time_result[2].count())) << " million op/s)\n" << dNORMAL
<< " - hash cache (string)....... : "
<< ((time_result[3].count() == min_max.first->count()) ? dCYAN : ((time_result[3].count() == min_max.second->count()) ? dRED : ""))
<< time_result[3].count() << "s (" << (run_number / (1000000 * time_result[3].count())) << " million op/s)\n" << dNORMAL
<< " - big memory cache.......... : "
<< ((time_result[4].count() == min_max.first->count()) ? dCYAN : ((time_result[4].count() == min_max.second->count()) ? dRED : ""))
<< time_result[4].count() << "s (" << (run_number / (1000000 * time_result[4].count())) << " million op/s)\n" << dNORMAL
<< " - big memory cache (binary). : "
<< ((time_result[5].count() == min_max.first->count()) ? dCYAN : ((time_result[5].count() == min_max.second->count()) ? dRED : ""))
<< time_result[5].count() << "s (" << (run_number / (1000000 * time_result[5].count())) << " million op/s)\n" << dNORMAL
<< "\n";
}
}
int main(int argc, char *argv[])
{
#if defined NDEBUG
std::ios_base::sync_with_stdio(false);
#endif
bool stress_test = false;
unsigned long stress_test_number = 100000;
int ret = EXIT_SUCCESS;
int i = 1;
while (i < argc) {
if (not std::strcmp(argv[i], "--stress") or
not std::strcmp(argv[i], "-s")) {
stress_test = true;
i++;
if (i < argc) {
unsigned long nb = std::strtoul(argv[i], nullptr, 10);
if (nb == 0 or errno)
i--;
else
stress_test_number = nb;
}
std::cout << "- run stress mode for " << stress_test_number << " random run\n";
i++;
continue;
}
if (not std::strcmp(argv[i], "--help") or
not std::strcmp(argv[i], "-h")) {
usage();
break;
}
std::cout << "Processing [" << dYELLOW << argv[i] << dNORMAL << "] \n";
try {
if (stress_test)
process_stress_test(argv[i], stress_test_number);
else
process(argv[i]);
std::cout << "\n";
} catch (const std::bad_alloc& e) {
std::cerr << dRED << "fail to allocate memory: " << dNORMAL << e.what()
<< std::endl;
ret = EXIT_FAILURE;
} catch (const std::invalid_argument& e) {
std::cerr << dRED << "bad argument: " << dNORMAL << e.what() <<
std::endl;
ret = EXIT_FAILURE;
} catch (const efyj::xml_parse_error& e) {
std::cerr << dRED << "fail to parse file " << argv[i] << " in ("
<< e.line << " << " << e.column << "): " << dNORMAL << e.what()
<< std::endl;
ret = EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << dRED << "unknown failure: " << dNORMAL << e.what() <<
std::endl;
ret = EXIT_FAILURE;
}
i++;
}
return ret;
}
|
/* Copyright (C) 2014 INRA
*
* 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 "io.hpp"
#include "model.hpp"
#include "solver.hpp"
#include "print.hpp"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <cstdlib>
#include <cstring>
namespace {
void usage() noexcept
{
std::cout << "efyj [-h|--help] [-s|--stress [number]] [files...]\n\n"
<< "Options:\n"
<< " -h, --help This help message\n"
<< " -s, --stress [int] Stress mode (check all solver/cache)\n"
<< " If no argument, the default"
" make 100000 run\n"
<< " [files...] DEXi file to run\n"
<< std::endl;
}
void show_model(const efyj::dexi& model)
{
std::cout << "(attribute: " << model.attributes.size()
<< ", basic attribute: " << model.basic_scale_number
<< ", problem size: " << model.problem_size
<< ")" << std::endl;
}
void process(const std::string& filepath)
{
efyj::dexi dexi_data;
std::ifstream is(filepath);
if (not is)
throw std::invalid_argument(
efyj::stringf("unknown file %s", filepath.c_str()));
efyj::read(is, dexi_data);
show_model(dexi_data);
}
void generate_new_options(std::vector <std::uint8_t>& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
for (std::size_t i = 0, e = options.size(); i != e; ++i)
options[i] = distribution(rng) % high_level[i];
}
void generate_new_options(std::string& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
options.assign(high_level.size(), '0');
for (std::size_t i = 0, e = high_level.size(); i != e; ++i)
options[i] += (distribution(rng) % high_level[i]);
}
void generate_new_options(std::size_t& options,
const std::vector <std::size_t>& high_level,
std::mt19937& rng)
{
std::uniform_int_distribution<int> distribution(0, 9);
options = 0;
std::size_t indice = 0;
for (std::size_t i = 0, e = high_level.size(); i != e; ++i) {
options += ((distribution(rng) % high_level[i]) << indice);
indice += std::floor(std::log2(high_level[i]) + 1);
}
}
void process_stress_test(const std::string& filepath,
unsigned long run_number)
{
std::vector <std::chrono::duration <double>> time_result(6);
std::chrono::time_point <std::chrono::system_clock> start;
efyj::dexi model;
{
start = std::chrono::system_clock::now();
std::ifstream is(filepath);
if (not is)
throw std::invalid_argument(
efyj::stringf("unknown file %s", filepath.c_str()));
efyj::read(is, model);
time_result[0] = std::chrono::system_clock::now() - start;
}
show_model(model);
std::vector <std::size_t> high_level(model.basic_scale_number);
int i = 0;
for (const auto& att : model.attributes)
if (att.children.empty())
high_level[i++] = att.scale_size();
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_basic si(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
si.solve(options);
}
time_result[1] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_hash sh(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sh.solve(options);
}
time_result[2] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::string options('0', model.basic_scale_number);
efyj::solver_hash sh(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sh.solve(options);
}
time_result[3] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::vector <std::uint8_t> options(model.basic_scale_number, 0u);
efyj::solver_bigmem sbm(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sbm.solve(options);
}
time_result[4] = std::chrono::system_clock::now() - start;
}
{
start = std::chrono::system_clock::now();
std::size_t options;
efyj::solver_bigmem sbm(model);
std::mt19937 generator;
for (unsigned long i = 0; i < run_number; ++i) {
::generate_new_options(options, high_level, generator);
sbm.solve(options);
}
time_result[5] = std::chrono::system_clock::now() - start;
}
auto min_max = std::minmax_element(time_result.begin() + 1, time_result.end(),
[](std::chrono::duration <double>& a,
std::chrono::duration <double>& b)
{
return a.count() < b.count();
});
std::cout << "Time elapsed to:\n"
<< "- read model........ : " << time_result[0].count() << "s\n"
<< "- get response for random " << run_number << " options:\n"
<< " - basic solver.............. : "
<< ((time_result[1].count() == min_max.first->count()) ? dCYAN : ((time_result[1].count() == min_max.second->count()) ? dRED : ""))
<< time_result[1].count() << "s (" << (run_number / (1000000 * time_result[1].count())) << " million op/s)\n" << dNORMAL
<< " - hash cache................ : "
<< ((time_result[2].count() == min_max.first->count()) ? dCYAN : ((time_result[2].count() == min_max.second->count()) ? dRED : ""))
<< time_result[2].count() << "s (" << (run_number / (1000000 * time_result[2].count())) << " million op/s)\n" << dNORMAL
<< " - hash cache (string)....... : "
<< ((time_result[3].count() == min_max.first->count()) ? dCYAN : ((time_result[3].count() == min_max.second->count()) ? dRED : ""))
<< time_result[3].count() << "s (" << (run_number / (1000000 * time_result[3].count())) << " million op/s)\n" << dNORMAL
<< " - big memory cache.......... : "
<< ((time_result[4].count() == min_max.first->count()) ? dCYAN : ((time_result[4].count() == min_max.second->count()) ? dRED : ""))
<< time_result[4].count() << "s (" << (run_number / (1000000 * time_result[4].count())) << " million op/s)\n" << dNORMAL
<< " - big memory cache (binary). : "
<< ((time_result[5].count() == min_max.first->count()) ? dCYAN : ((time_result[5].count() == min_max.second->count()) ? dRED : ""))
<< time_result[5].count() << "s (" << (run_number / (1000000 * time_result[5].count())) << " million op/s)\n" << dNORMAL
<< "\n";
}
}
int main(int argc, char *argv[])
{
#if defined NDEBUG
std::ios_base::sync_with_stdio(false);
#endif
bool stress_test = false;
unsigned long stress_test_number = 100000;
int ret = EXIT_SUCCESS;
int i = 1;
while (i < argc) {
if (not std::strcmp(argv[i], "--stress") or
not std::strcmp(argv[i], "-s")) {
stress_test = true;
i++;
if (i < argc) {
unsigned long nb = std::strtoul(argv[i], nullptr, 10);
if (nb == 0 or errno)
i--;
else
stress_test_number = nb;
}
std::cout << "- run stress mode for " << stress_test_number << " random run\n";
i++;
continue;
}
if (not std::strcmp(argv[i], "--help") or
not std::strcmp(argv[i], "-h")) {
usage();
break;
}
std::cout << "Processing [" << dYELLOW << argv[i] << dNORMAL << "] \n";
try {
if (stress_test)
process_stress_test(argv[i], stress_test_number);
else
process(argv[i]);
std::cout << "\n";
} catch (const std::bad_alloc& e) {
std::cerr << dRED << "fail to allocate memory: " << dNORMAL << e.what()
<< std::endl;
ret = EXIT_FAILURE;
} catch (const std::invalid_argument& e) {
std::cerr << dRED << "bad argument: " << dNORMAL << e.what() <<
std::endl;
ret = EXIT_FAILURE;
} catch (const efyj::xml_parse_error& e) {
std::cerr << dRED << "fail to parse file " << argv[i] << " in ("
<< e.line << " << " << e.column << "): " << dNORMAL << e.what()
<< std::endl;
ret = EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << dRED << "unknown failure: " << dNORMAL << e.what() <<
std::endl;
ret = EXIT_FAILURE;
}
i++;
}
return ret;
}
|
add DEX information
|
main: add DEX information
Before starting stress mode, we show basic information from the input
problem file.
|
C++
|
mit
|
quesnel/efyj,quesnel/efyj,quesnel/efyj
|
075ca5185dccc0e82041e09de59a5ef2c32f67e7
|
main.cpp
|
main.cpp
|
// 2006-2008 (c) Viva64.com Team
// 2008-2016 (c) OOO "Program Verification Systems"
#include "comments.h"
#include "encoding.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <filesystem>
using namespace std;
static bool IsSourceFile(const filesystem::path &path)
{
static const vector<string> sourceExtensions = {
".c"
, ".cc"
, ".cpp"
, ".cp"
, ".cxx"
, ".c++"
, ".cs"
, ".java"
};
string ext = path.extension().string();
transform(ext.begin(), ext.end(), ext.begin(), [](char ch){return tolower(ch);});
return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}
class ProgramOptions
{
ProgramOptions() = default;
ProgramOptions(const ProgramOptions& root) = delete;
ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
size_t m_commentType = -1;
vector<string> m_files;
bool m_multiline = false;
bool m_readSymlinks = false;
static ProgramOptions& Instance()
{
static ProgramOptions programOptions;
return programOptions;
}
};
void WriteComment(const filesystem::path &path,
const string &comment,
const string &source,
bool isUnixLineEnding,
Encoding enc,
size_t bomLen)
{
ofstream osrc(path, ios::binary);
if (!osrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
if (bomLen != 0)
{
osrc.write(source.c_str(), bomLen);
}
ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}
static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
if (!IsSourceFile(path))
return;
cout << "+ " << path << endl;
ifstream isrc(path, ios::binary);
if (!isrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
string str;
isrc.seekg(0, ios::end);
str.reserve(isrc.tellg());
isrc.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
isrc.close();
string source = str;
Encoding enc;
size_t bomLen;
ConvertEncoding(str, enc, bomLen);
bool isUnixLineEnding = true;
size_t idx = str.find('\n');
if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
isUnixLineEnding = false;
PvsStudioFreeComments::CommentsParser parser;
auto itFreeComment = parser.readFreeComment(source.c_str());
const char *beg = parser.freeCommentBegin();
const char *end = parser.freeCommentEnd();
if (itFreeComment != PvsStudioFreeComments::Comments.end())
{
bool needToChangeComment = (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
|| (options.m_multiline && beg[0] == '/' && beg[1] == '/')
|| itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
if (needToChangeComment)
{
source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
else
{
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
if (options.m_readSymlinks && filesystem::is_symlink(path))
{
std::error_code error;
path = filesystem::canonical(filesystem::read_symlink(path), error);
if (error != std::error_code())
{
return;
}
}
if (filesystem::is_regular_file(path))
{
AddCommentsToFile(path, comment, options);
}
}
static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
auto fsPath = filesystem::canonical(path);
if (!filesystem::exists(fsPath))
{
cerr << "File not exists: " << path << endl;
return;
}
if (filesystem::is_directory(fsPath))
{
filesystem::directory_options symlink_flag = options.m_readSymlinks
? filesystem::directory_options::follow_directory_symlink
: filesystem::directory_options::none;
for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
{
ProcessFile(p.path(), comment, options);
}
}
else
{
ProcessFile(fsPath, comment, options);
}
}
static string Format(const string &comment, bool multiline)
{
ostringstream ostream;
istringstream stream(comment);
string line;
if (multiline)
{
ostream << "/*" << endl;
while (getline(stream, line))
{
ostream << "* " << line << endl;
}
ostream << "*/" << endl;
}
else
{
while (getline(stream, line))
{
ostream << "// " << line << endl;
}
}
return ostream.str();
}
static const char Help[] = R"HELP(How to use PVS-Studio for FREE?
You can use PVS-Studio code analyzer for free, if you add special comments
to your source code. Available options are provided below.
Usage:
how-to-use-pvs-studio-free -c <1|2|3> [-m] [-s] [-h] <strings> ...
Options:
-c <1|2|3>, /c <1|2|3>, --comment <1|2|3>
(required) Type of comment prepended to the source file.
-m, /m, --multiline
Use multi-line comments instead of single-line.
-s, /s, --symlinks
Follow the symbolic links and add comment to the files to which symbolic links point (files and directories).
-h, /?, --help
Display usage information and exit.
<string> (accepted multiple times)
(required) Files or directories.
Description:
The utility will add comments to the files located in the specified folders
and subfolders. The comments are added to the beginning of the files with the
extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
header files. If you use files with other extensions, you can customize this
utility for your needs.
Options of comments that will be added to the code (-c NUMBER):
1. Personal academic project;
2. Open source non-commercial project;
3. Independent project of an individual developer.
If you are using PVS-Studio as a Visual Studio plugin, then enter the
following license key:
Name: PVS-Studio Free
Key: FREE-FREE-FREE-FREE
If you are using PVS-Studio for Linux, you do not need to do anything else
besides adding comments to the source code. Just check your code.
In case none of the options suits you, we suggest considering a purchase of a
commercial license for PVS-Studio. We are ready to discuss this and other
questions via e-mail: [email protected].
You can find more details about the free version of PVS-Studio
here: https://www.viva64.com/en/b/0457/
)HELP";
void help()
{
cout << Help;
}
struct Option
{
vector<string> names;
bool hasArg;
function<void(string&&)> found;
};
struct ProgramOptionsError {};
typedef vector<Option> ParsedOptions;
static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
auto findOpt = [&options](const string& arg) {
return find_if(begin(options), end(options), [arg](const Option &o) {
return find(o.names.begin(), o.names.end(), arg) != o.names.end();
});
};
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
auto it = findOpt(arg);
if (it == end(options))
{
found(move(arg));
}
else if (it->hasArg)
{
++i;
if (i == argc)
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
string val = argv[i];
auto itNext = findOpt(val);
if (itNext != end(options))
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
it->found(move(val));
}
else
{
it->found(string());
}
}
}
int main(int argc, const char *argv[])
{
auto &progOptions = ProgramOptions::Instance();
ParsedOptions options = {
{ { "-c", "/c", "--comment" }, true, [&](string &&arg) { progOptions.m_commentType = stoull(arg); } },
{ { "-m", "/m", "--multiline" }, false, [&](string &&) { progOptions.m_multiline = true; } },
{ { "-s", "/s", "--symlinks" }, false, [&](string &&) { progOptions.m_readSymlinks = true; } },
{ { "-h", "/?", "--help" }, false, [&](string &&) { throw ProgramOptionsError(); } },
};
try
{
ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});
unsigned long long n = progOptions.m_commentType;
if (n == 0 || n > PvsStudioFreeComments::Comments.size())
{
throw invalid_argument("");
}
string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
for (const string &file : progOptions.m_files)
{
AddComments(file, comment, progOptions);
}
}
catch (ProgramOptionsError &)
{
help();
return 1;
}
catch (invalid_argument &)
{
cout << "Invalid comment type specified" << endl;
help();
return 1;
}
return 0;
}
|
// 2006-2008 (c) Viva64.com Team
// 2008-2016 (c) OOO "Program Verification Systems"
#include "comments.h"
#include "encoding.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <filesystem>
using namespace std;
static bool IsSourceFile(const filesystem::path &path)
{
static const vector<string> sourceExtensions = {
".c"
, ".cc"
, ".cpp"
, ".cp"
, ".cxx"
, ".c++"
, ".cs"
, ".java"
};
string ext = path.extension().string();
transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char ch) { return static_cast<decltype(ext)::value_type>(tolower(ch)); });
return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}
class ProgramOptions
{
ProgramOptions() = default;
ProgramOptions(const ProgramOptions& root) = delete;
ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
size_t m_commentType = static_cast<size_t>(-1);
vector<string> m_files;
bool m_multiline = false;
bool m_readSymlinks = false;
static ProgramOptions& Instance()
{
static ProgramOptions programOptions;
return programOptions;
}
};
void WriteComment(const filesystem::path &path,
const string &comment,
const string &source,
bool isUnixLineEnding,
Encoding enc,
size_t bomLen)
{
ofstream osrc(path, ios::binary);
if (!osrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
if (bomLen != 0)
{
osrc.write(source.c_str(), bomLen);
}
ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}
static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
if (!IsSourceFile(path))
return;
cout << "+ " << path << endl;
ifstream isrc(path, ios::binary);
if (!isrc.is_open())
{
cerr << "Error: Couldn't open " << path << endl;
return;
}
string str;
isrc.seekg(0, ios::end);
str.reserve(isrc.tellg());
isrc.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
isrc.close();
string source = str;
Encoding enc;
size_t bomLen;
ConvertEncoding(str, enc, bomLen);
bool isUnixLineEnding = true;
size_t idx = str.find('\n');
if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
isUnixLineEnding = false;
PvsStudioFreeComments::CommentsParser parser;
auto itFreeComment = parser.readFreeComment(source.c_str());
const char *beg = parser.freeCommentBegin();
const char *end = parser.freeCommentEnd();
if (itFreeComment != PvsStudioFreeComments::Comments.end())
{
bool needToChangeComment = (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
|| (options.m_multiline && beg[0] == '/' && beg[1] == '/')
|| itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
if (needToChangeComment)
{
source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
else
{
WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
}
}
static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
if (options.m_readSymlinks && filesystem::is_symlink(path))
{
std::error_code error;
path = filesystem::canonical(filesystem::read_symlink(path), error);
if (error != std::error_code())
{
return;
}
}
if (filesystem::is_regular_file(path))
{
AddCommentsToFile(path, comment, options);
}
}
static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
auto fsPath = filesystem::canonical(path);
if (!filesystem::exists(fsPath))
{
cerr << "File not exists: " << path << endl;
return;
}
if (filesystem::is_directory(fsPath))
{
filesystem::directory_options symlink_flag = options.m_readSymlinks
? filesystem::directory_options::follow_directory_symlink
: filesystem::directory_options::none;
for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
{
ProcessFile(p.path(), comment, options);
}
}
else
{
ProcessFile(fsPath, comment, options);
}
}
static string Format(const string &comment, bool multiline)
{
ostringstream ostream;
istringstream stream(comment);
string line;
if (multiline)
{
ostream << "/*" << endl;
while (getline(stream, line))
{
ostream << "* " << line << endl;
}
ostream << "*/" << endl;
}
else
{
while (getline(stream, line))
{
ostream << "// " << line << endl;
}
}
return ostream.str();
}
static const char Help[] = R"HELP(How to use PVS-Studio for FREE?
You can use PVS-Studio code analyzer for free, if you add special comments
to your source code. Available options are provided below.
Usage:
how-to-use-pvs-studio-free -c <1|2|3> [-m] [-s] [-h] <strings> ...
Options:
-c <1|2|3>, /c <1|2|3>, --comment <1|2|3>
(required) Type of comment prepended to the source file.
-m, /m, --multiline
Use multi-line comments instead of single-line.
-s, /s, --symlinks
Follow the symbolic links and add comment to the files to which symbolic links point (files and directories).
-h, /?, --help
Display usage information and exit.
<string> (accepted multiple times)
(required) Files or directories.
Description:
The utility will add comments to the files located in the specified folders
and subfolders. The comments are added to the beginning of the files with the
extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
header files. If you use files with other extensions, you can customize this
utility for your needs.
Options of comments that will be added to the code (-c NUMBER):
1. Personal academic project;
2. Open source non-commercial project;
3. Independent project of an individual developer.
If you are using PVS-Studio as a Visual Studio plugin, then enter the
following license key:
Name: PVS-Studio Free
Key: FREE-FREE-FREE-FREE
If you are using PVS-Studio for Linux, you do not need to do anything else
besides adding comments to the source code. Just check your code.
In case none of the options suits you, we suggest considering a purchase of a
commercial license for PVS-Studio. We are ready to discuss this and other
questions via e-mail: [email protected].
You can find more details about the free version of PVS-Studio
here: https://www.viva64.com/en/b/0457/
)HELP";
void help()
{
cout << Help;
}
struct Option
{
vector<string> names;
bool hasArg;
function<void(string&&)> found;
};
struct ProgramOptionsError {};
typedef vector<Option> ParsedOptions;
static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
auto findOpt = [&options](const string& arg) {
return find_if(begin(options), end(options), [arg](const Option &o) {
return find(o.names.begin(), o.names.end(), arg) != o.names.end();
});
};
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
auto it = findOpt(arg);
if (it == end(options))
{
found(move(arg));
}
else if (it->hasArg)
{
++i;
if (i == argc)
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
string val = argv[i];
auto itNext = findOpt(val);
if (itNext != end(options))
{
cout << "No argument specified for " << arg << endl;
throw ProgramOptionsError();
}
it->found(move(val));
}
else
{
it->found(string());
}
}
}
int main(int argc, const char *argv[])
{
auto &progOptions = ProgramOptions::Instance();
ParsedOptions options = {
{ { "-c", "/c", "--comment" }, true, [&](string &&arg) { progOptions.m_commentType = stoull(arg); } },
{ { "-m", "/m", "--multiline" }, false, [&](string &&) { progOptions.m_multiline = true; } },
{ { "-s", "/s", "--symlinks" }, false, [&](string &&) { progOptions.m_readSymlinks = true; } },
{ { "-h", "/?", "--help" }, false, [&](string &&) { throw ProgramOptionsError(); } },
};
try
{
ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});
unsigned long long n = progOptions.m_commentType;
if (n == 0 || n > PvsStudioFreeComments::Comments.size())
{
throw invalid_argument("");
}
string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
for (const string &file : progOptions.m_files)
{
AddComments(file, comment, progOptions);
}
}
catch (ProgramOptionsError &)
{
help();
return 1;
}
catch (invalid_argument &)
{
cout << "Invalid comment type specified" << endl;
help();
return 1;
}
return 0;
}
|
fix MSVC compiler warnings (implicit casts).
|
fix MSVC compiler warnings (implicit casts).
|
C++
|
apache-2.0
|
viva64/how-to-use-pvs-studio-free,viva64/how-to-use-pvs-studio-free
|
7cf5ca7ee29fce1656f1d3eaba6816d2a85594bb
|
main.cpp
|
main.cpp
|
8428c335-ad59-11e7-8da2-ac87a332f658
|
84d3b119-ad59-11e7-9282-ac87a332f658
|
fix for the previous fix
|
fix for the previous fix
|
C++
|
mit
|
justinhyou/GestureRecognition-CNN,justinhyou/GestureRecognition-CNN
|
fdd57d2e29d2eeddd86bfe7a8561c7967da1ccbe
|
main.cpp
|
main.cpp
|
3548c857-2748-11e6-8e1d-e0f84713e7b8
|
355663f8-2748-11e6-8f8d-e0f84713e7b8
|
Fix that bug where things didn't work but now they should
|
Fix that bug where things didn't work but now they should
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
0a6a166e25bf36c21cf341bde3c12e908c95df58
|
main.cpp
|
main.cpp
|
de382f21-2747-11e6-8aa5-e0f84713e7b8
|
de46524f-2747-11e6-b15a-e0f84713e7b8
|
Fix that bug where things didn't work but now they should
|
Fix that bug where things didn't work but now they should
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
549977cc3bf053a89cf6a5704449a4a91e96505d
|
main.cpp
|
main.cpp
|
#include <OpenGL/GL.h>
#include <OpenGL/GLU.h>
#include <GLUT/GLUT.h>
#include <iostream>
#include "loader.h"
#include "camera.h"
#define BUFSIZE 512
void initOpenGL();
void loadModel(const char * path);
void display();
void keyboard(unsigned char key, int x, int y);
void mouse(int button, int state, int x, int y);
void passiveMotionFunc(int x, int y);
void processHits(GLint hits, GLuint buffer[]);
obj::mesh mesh;
obj::camera * camera;
int width = 800, height = 600;
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutInitWindowPosition(0, 0);
glutCreateWindow("OBJ Viewer");
initOpenGL();
loadModel(argv[1]);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutPassiveMotionFunc(passiveMotionFunc);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
void initOpenGL() {
glClearColor(.0, .79, .31, 0);
glClearDepth(1.0);
GLfloat light_position[] = { 10.0, 1.0, 1.0, .0 };
GLfloat light_specular[] = { 1.0, 1.0, .0, 1.0 };
GLfloat light_diffuse[] = { .5, .5, .5, 1.0 };
glShadeModel (GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
camera = new obj::camera(90);
camera->reset_view(width, height);
}
void loadModel(const char * path) {
obj::loader(path).load(&mesh);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(.86, .98, .36);
mesh.render();
glutSwapBuffers();
glFlush();
}
void keyboard(unsigned char key, int x, int y) {
if (key == 'q' || key == 'Q') {
exit(0);
} else {
switch(key) {
case 'a':
case 'A':
camera->move_side(1); break;
case 's':
case 'S':
camera->move(-1); break;
case 'd':
case 'D':
camera->move_side(-1); break;
case 'w':
case 'W':
camera->move(1); break;
}
glutPostRedisplay();
}
}
void passiveMotionFunc(int x, int y) {
float y2 = (height - y) / (float) height;
if (y2 != 0.5 || x != width / 2) {
if(y2 != 0.5) {
camera->set_direction_y(y2 - 0.5);
}
if(x != width/2) {
camera->change_angle((x - width / 2) / 10);
}
glutWarpPointer(width / 2, height / 2);
glutPostRedisplay();
}
}
void mouse(int button, int state, int x, int y) {
if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN) return;
GLuint select_buf[BUFSIZE];
GLint hits;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glSelectBuffer(BUFSIZE, select_buf);
(void) glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix (x, viewport[3] - y, 5.0, 5.0, viewport);
gluPerspective(45.0, width / (double) height, 0.2, 200.0);
mesh.render();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glFlush();
hits = glRenderMode(GL_RENDER);
if (hits != 0) processHits(hits, select_buf);
glutPostRedisplay();
}
void processHits(GLint hits, GLuint buffer[]) {
GLuint names, *ptr, min_z, *ptr_names;
ptr = (GLuint *) buffer;
min_z = 0xffffffff;
for (unsigned int i = 0; i < hits; i++) {
names = *ptr;
ptr++;
if (*ptr < min_z) {
min_z = *ptr;
ptr_names = ptr + 2;
}
ptr += names + 2;
}
mesh.group_at(*ptr_names)->hide();
}
|
#include <OpenGL/GL.h>
#include <OpenGL/GLU.h>
#include <GLUT/GLUT.h>
#include <iostream>
#include "loader.h"
#include "camera.h"
#define BUFSIZE 512
void initOpenGL();
void loadModel(const char * path);
void display();
void keyboard(unsigned char key, int x, int y);
void mouse(int button, int state, int x, int y);
void passiveMotionFunc(int x, int y);
void processHits(GLint hits, GLuint buffer[]);
obj::mesh mesh;
obj::camera * camera;
int width = 800, height = 600;
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutInitWindowPosition(0, 0);
glutCreateWindow("OBJ Viewer");
initOpenGL();
loadModel(argv[1]);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutPassiveMotionFunc(passiveMotionFunc);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
void initOpenGL() {
glClearColor(.0, .79, .31, 0);
glClearDepth(1.0);
GLfloat light_position[] = { 10.0, 1.0, 1.0, .0 };
GLfloat light_specular[] = { 1.0, 1.0, .0, 1.0 };
GLfloat light_diffuse[] = { .5, .5, .5, 1.0 };
glShadeModel (GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
camera = new obj::camera(90);
camera->reset_view(width, height);
}
void loadModel(const char * path) {
obj::loader(path).load(&mesh);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(.86, .98, .36);
mesh.render();
glutSwapBuffers();
glFlush();
}
void keyboard(unsigned char key, int x, int y) {
if (key == 'q' || key == 'Q') {
exit(0);
} else {
switch(key) {
case 'a':
case 'A':
camera->move_side(1); break;
case 's':
case 'S':
camera->move(-1); break;
case 'd':
case 'D':
camera->move_side(-1); break;
case 'w':
case 'W':
camera->move(1); break;
}
glutPostRedisplay();
}
}
void passiveMotionFunc(int x, int y) {
float y2 = (height - y) / (float) height;
if (y2 != 0.5 || x != width / 2) {
if(y2 != 0.5) {
camera->set_direction_y(y2 - 0.5);
}
if(x != width/2) {
camera->change_angle((x - width / 2) / 10);
}
glutWarpPointer(width / 2, height / 2);
glutPostRedisplay();
}
}
void mouse(int button, int state, int x, int y) {
if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN) return;
GLuint select_buf[BUFSIZE];
GLint hits;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glSelectBuffer(BUFSIZE, select_buf);
(void) glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix (x, viewport[3] - y, 5.0, 5.0, viewport);
gluPerspective(45.0, width / (double) height, 0.2, 200.0);
mesh.render();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glFlush();
hits = glRenderMode(GL_RENDER);
if (hits != 0) processHits(hits, select_buf);
glutPostRedisplay();
}
void processHits(GLint hits, GLuint buffer[]) {
GLuint names, *ptr, min_z, *ptr_names;
ptr = (GLuint *) buffer;
min_z = 0xffffffff;
for (unsigned int i = 0; i < hits; i++) {
names = *ptr;
ptr++;
if (*ptr < min_z) {
min_z = *ptr;
ptr_names = ptr + 2;
}
ptr += names + 2;
}
mesh.group_at(*ptr_names)->hide();
}
|
Enable GL_COLOR_MATERIAL
|
Enable GL_COLOR_MATERIAL
|
C++
|
mit
|
fuadsaud/objviewer
|
bef87238cb15decee7dc5733644a8609557ad3ef
|
main.cpp
|
main.cpp
|
0c7d205e-2748-11e6-bc2c-e0f84713e7b8
|
0c907405-2748-11e6-87da-e0f84713e7b8
|
Add a beter commit message
|
TODO: Add a beter commit message
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
a8e7a2b203e5219b08707662bafca0a6fc43a580
|
main.cpp
|
main.cpp
|
/******************************************************************************
SBS to XML simple converter.
Author: Przemyslaw Wirkus
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C"
{
struct yy_buffer_state;
int yylex(void);
int yyparse ();
yy_buffer_state* yy_create_buffer(FILE*, int);
void yy_switch_to_buffer(yy_buffer_state*);
void yyerror(const char* str)
{
printf("%s", str);
}
extern int yydebug;
char* strip_string_quotes(char* str)
{
const int len = strlen(str);
str[len - 1] = '\0';
return str + 1;
}
// Creates a copy of the string with unescaped strings (backslashes removed).
char* process_string_literal(const char* str)
{
char* output = (char*) malloc(strlen(str)+1);
const char* inPtr = str;
char* outPtr = output;
// Skip the initial "
if (*inPtr == '\"') {
++inPtr;
}
while (*inPtr != '\0')
{
// If we encounter a backslash and we're not at the end of the string:
// skip it and blindly write the character directly after it
if ( (*inPtr == '\\') && (*(inPtr+1) != '\0') ) {
++inPtr;
}
// Copy the char
*outPtr++ = *inPtr++;
}
// Remove the final "
if ( (outPtr > output) && (*(outPtr-1) == '\"') ) {
--outPtr;
}
// Terminate the modified string.
*outPtr = '\0';
return output;
}
void print_xml_special_characters(const char* str)
{
const int len = strlen(str);
for (int i = 0; i < len; i++)
{
const char c = str[i];
switch (c)
{
case '"': printf("""); break;
case '&': printf("&"); break;
case '\'': printf("'"); break;
case '<': printf("<"); break;
case '>': printf(">"); break;
default: printf("%c", c);
}
}
}
void print_text_element(const char* element, const char* content) {
char* unescapedStr = process_string_literal(content);
printf("<%s>", element);
print_xml_special_characters(unescapedStr);
printf("</%s>\n", element);
free(unescapedStr);
}
// Creates new string with prefix
char* string_add_front(const char* prefix, const char* delimiter, char* str)
{
const int total_len = strlen(prefix) + strlen(str) + strlen(delimiter) + 1;
char* result = (char*)malloc(total_len * sizeof(char));
strcpy(result, prefix);
strcat(result, delimiter);
strcat(result, str);
return result;
}
}
int main(int argc, char *argv[])
{
int ret = yyparse();
return ret;
}
|
/******************************************************************************
SBS to XML simple converter.
Author: Przemyslaw Wirkus
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C"
{
struct yy_buffer_state;
int yylex(void);
int yyparse ();
yy_buffer_state* yy_create_buffer(FILE*, int);
void yy_switch_to_buffer(yy_buffer_state*);
void yyerror(const char* str)
{
printf("%s", str);
}
extern int yydebug;
char* strip_string_quotes(char* str)
{
const int len = strlen(str);
str[len - 1] = '\0';
return str + 1;
}
// Creates a copy of the string with unescaped strings (backslashes removed).
char* process_string_literal(const char* str)
{
size_t len = strlen(str);
char* output = (char*) malloc(len+1);
const char* inPtr = str;
char* outPtr = output;
// Skip the initial "
if (*inPtr == '\"') {
++inPtr;
}
while (*inPtr != '\0')
{
// If we encounter a backslash and we're not at the end of the string:
// skip it and blindly write the character directly after it to allow
// escaping the backslash itself with "\\"
if ( (*inPtr == '\\') && (*(inPtr+1) != '\0') ) {
++inPtr;
}
// Rhapsody 8 spreads strings that are too long (>800 chars)
// over several lines. When it does, it uses the special sequence:
// 0x01 0x02 0x03 0x0D 0xA (1 2 3 CR LF)
// Skip it when/if we encounter it. Also do the same with 1 2 3 LF
// because the parser may be converting the CR LF to LF automatically
// (it is at least the case under Windows).
if ( (*inPtr == 0x1)
&& (*(inPtr+1) == 0x2)
&& (*(inPtr+2) == 0x3)
&& ( (*(inPtr+3) == 0xD) || (*(inPtr+3) == 0xA) )
&& ( (*(inPtr+4) == 0xA) || (*(inPtr+3) == 0xA) )
) {
if (*(inPtr+3) == 0xA) {
inPtr += 4;
} else {
inPtr += 5;
}
continue;
}
// Copy the char
*outPtr++ = *inPtr++;
}
// Remove the final "
if ( (outPtr > output) && (*(outPtr-1) == '\"') ) {
--outPtr;
}
// Terminate the modified string.
*outPtr = '\0';
return output;
}
void print_xml_special_characters(const char* str)
{
const int len = strlen(str);
for (int i = 0; i < len; i++)
{
const char c = str[i];
switch (c)
{
case '"': printf("""); break;
case '&': printf("&"); break;
case '\'': printf("'"); break;
case '<': printf("<"); break;
case '>': printf(">"); break;
default: printf("%c", c);
}
}
}
void print_text_element(const char* element, const char* content) {
char* unescapedStr = process_string_literal(content);
printf("<%s>", element);
print_xml_special_characters(unescapedStr);
printf("</%s>\n", element);
free(unescapedStr);
}
// Creates new string with prefix
char* string_add_front(const char* prefix, const char* delimiter, char* str)
{
const int total_len = strlen(prefix) + strlen(str) + strlen(delimiter) + 1;
char* result = (char*)malloc(total_len * sizeof(char));
strcpy(result, prefix);
strcat(result, delimiter);
strcat(result, str);
return result;
}
}
int main(int argc, char *argv[])
{
int ret = yyparse();
return ret;
}
|
Support for Rhapsody 8's line breaking mechanism
|
Support for Rhapsody 8's line breaking mechanism
|
C++
|
mit
|
jruffin/sbs2xml-conv
|
adc57dc95a665f49de9e0dda0b77b041ad6a5071
|
main.cpp
|
main.cpp
|
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#include "include/logging/enumCvType.hpp"
#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"
void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect);
double distance(cv::Point one, cv::Point two);
void drawBoundedRects(cv::Mat& src, int thresh)
{
cv::Mat threshold_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// Convert src to gray format
cv::cvtColor(src, threshold_output, CV_BGR2GRAY);
// Detect edges using Threshold
cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
// Find contours
cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// Get the moments
std::vector<cv::Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
// Approximate contours to rotated rectangles and ellipses
std::vector<cv::RotatedRect> minRect( contours.size());
for(int i = 0; i < contours.size(); i++)
{
minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
}
// Draw polygonal contour + bounding rects
cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
for(int i = 0; i < contours.size(); i++)
{
//cv::Scalar color = cv::Scalar(0, 255, 255);
//cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
cv::Point2f rect_points[4];
minRect[i].points(rect_points);
for(int j = 0; j < 4; j++)
{
//cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
}
}
// Bounded rectangle is the one at the 0th index
if (minRect.size() > 0)
calculateDistance(drawing, minRect[0]);
// Calculate the area with the moments 00 and compare with the result of the OpenCV function
// printf("\t Info: Area and Contour Length \n");
for( int i = 0; i < contours.size(); i++ )
{
// printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
// printf("Contour[%2d] - Length: %4.2f\n", i, arcLength( contours[i], true ) );
//cv::Scalar color = cv::Scalar(0, 255, 0);
//cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
}
// Show in a window
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::imshow("Contours", drawing);
}
double distance(cv::Point one, cv::Point two)
{
return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}
void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect)
{
double focalLen = 675.0;
// 20 inches real width
double wReal = 20;
double wPixel = 0;
double d = 180;
double theta = 0;
const double TOWER_HEIGHT = 7.1;
const double PI = 3.14159265;
cv::Point2f vert[4];
boundedRect.points(vert);
cv::line(image, vert[0], vert[3], cv::Scalar (255, 0, 0));
wPixel = distance(vert[0], vert[3]);
// focalLen = (wPixel * d) / wReal;
d = (wReal * focalLen) / wPixel;
theta = asin(TOWER_HEIGHT / (d / 12)) * 180 / PI;
char str[50];
sprintf(str, "Line Length = %4.2f", wPixel);
cv::putText(image, str, cv::Point(10, 400), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Focal Length = %4.2f", focalLen);
cv::putText(image, str, cv::Point(10, 420), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Distance = %4.2f", d);
cv::putText(image, str, cv::Point(10, 440), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Vert Angle = %4.2f", theta);
cv::putText(image, str, cv::Point(10, 460), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
}
int main( int argc, char *argv[])
{
// Parameters for selecting which filters to apply
int blur = 0;
int color = 0;
int dilate_erode = 0;
int edge = 0;
int laplacian = 0;
int hough = 0;
int depth_dist = 0;
int merge = 0;
// Parameters for applying filters even if windows are closed
int apply_blur = 1;
int apply_color = 1;
int apply_dilate_erode = 0;
int apply_edge = 1;
int apply_laplacian = 0;
int apply_hough = 0;
int apply_depth_dist = 0;
int apply_merge = 1;
// gaussianBlur parameters
int blur_ksize = 7;
int sigmaX = 10;
int sigmaY = 10;
// hsvColorThreshold parameters
int hMin = 120;
int hMax = 200;
int sMin = 0;
int sMax = 40;
int vMin = 80;
int vMax = 100;
int debugMode = 0;
// 0 is none, 1 is bitAnd between h, s, and v
int bitAnd = 1;
// dilateErode parameters
int holes = 0;
int noise = 0;
int size = 1;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * size + 1, 2 * size + 1),
cv::Point(size, size) );
// cannyEdgeDetect parameters
int threshLow = 100;
int threshHigh = 300;
// laplacianSharpen parameters
int laplacian_ksize = 3;
// optional scale value added to image
int scale = 1;
// optional delta value added to image
int delta = 0;
int ddepth = CV_16S;
// houghLines parameters
int rho = 1;
int theta = 180;
int threshold = 50;
int lineMin = 50;
int maxGap = 10;
// mergeFinal parameters
int weight1 = 100;
int weight2 = 100;
// contour parameters
int contours = 120;
std::cout << "\n";
std::cout << " =========== FILTER LIST =========== " << "\n";
std::cout << "| |" << "\n";
std::cout << "| (0) No Filter |" << "\n";
std::cout << "| (1) Gaussian Blur Filter |" << "\n";
std::cout << "| (2) HSV Color Filter |" << "\n";
std::cout << "| (3) Dilate and Erode Filter |" << "\n";
std::cout << "| (4) Canny Edge Detection Filter |" << "\n";
std::cout << "| (5) Laplacian Sharpen Filter |" << "\n";
std::cout << "| (6) Hough Lines Filter |" << "\n";
std::cout << "| (7) Merge Final Outputs |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
std::cout << "\n";
std::cout << " ============== NOTICE ============= " << "\n";
std::cout << "| |" << "\n";
std::cout << "| Press 'q' to quit without saving |" << "\n";
std::cout << "| Press ' ' to pause |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
int port = 0;
cv::VideoCapture camera;
do
{
std::cout << "Enter the port number of the camera (-1 to quit): ";
std::cin >> port;
// Reprompt if user enters invalid input
if (port <= 10 && port >= 0)
{
camera = cv::VideoCapture (port);
if(!camera.isOpened())
{
std::cout << "\nUnable to open camera at Port " << port << "\n\n";
}
}
}
while (port != -1);
if (port == -1)
return -1;
// Matrices for holding image data
cv::Mat rgb, rgb_orig;
cv::Mat image;
// Press q to quit the program
char kill = ' ';
while ((kill != 'q') && (kill != 's'))
{
// Press space to pause program, then any key to resume
if (kill == ' ')
{
cv::waitKey(0);
}
selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
// Use images
if (argc > 2)
{
rgb = cv::imread(argv[1]);
// No data
if (!rgb.data)
{
std::cout << "No image data" << std::endl;
return -1;
}
}
else
{
camera >> rgb;
}
cv::imshow("BGR Feed", rgb);
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::createTrackbar("Contours Threshold:", "Contours", &contours, 255);
rgb.copyTo(image);
// Filters are only applied if last parameter is true, otherwise their windows are destroyed
gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
drawBoundedRects(image, contours);
cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
mergeFinalWindows(rgb, image, weight1, weight2, apply_merge, merge);
kill = cv::waitKey(5);
}
return 0;
}
|
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#include "include/logging/enumCvType.hpp"
#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"
double calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect);
double distance(cv::Point one, cv::Point two);
std::vector<cv::Point> corners (std::vector<cv::Point> pts, cv::Mat& img);
void calcHorizAngle(cv::Mat& image, double dStraight, std::vector<cv::Point> c);
void drawBoundedRects(cv::Mat& src, int thresh)
{
cv::Mat threshold_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// Convert src to gray format
cv::cvtColor(src, threshold_output, CV_BGR2GRAY);
// Detect edges using Threshold
cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
// Find contours
cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// Get the moments
std::vector<cv::Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
// Approximate contours to rotated rectangles and ellipses
std::vector<cv::RotatedRect> minRect( contours.size());
for(int i = 0; i < contours.size(); i++)
{
minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
}
// Draw polygonal contour + bounding rects
cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
for(int i = 0; i < contours.size(); i++)
{
//cv::Scalar color = cv::Scalar(0, 255, 255);
//cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
cv::Point2f rect_points[4];
minRect[i].points(rect_points);
for(int j = 0; j < 4; j++)
{
//cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
}
}
double d = 0;
std::vector<cv::Point> c;
// Bounded rectangle is the one at the 0th index
if (minRect.size() > 0)
d = calculateDistance(drawing, minRect[0]);
if (contours.size() > 0)
{
c = corners(contours[0], drawing);
calcHorizAngle(drawing, d, c);
}
for (int i = 0; i < c.size(); i++)
{
cv::circle(drawing, c[i], 5, cv::Scalar(0, 255, 0));
}
// Calculate the area with the moments 00 and compare with the result of the OpenCV function
// printf("\t Info: Area and Contour Length \n");
for (int i = 0; i < contours.size(); i++)
{
// printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
// printf("Contour[%2d] - Length: %4.2f\n", i, arcLength( contours[i], true ) );
cv::Scalar color = cv::Scalar(0, 255, 0);
if (i == 0)
{
cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
}
}
// Show in a window
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::imshow("Contours", drawing);
}
double distance(cv::Point one, cv::Point two)
{
return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}
// Returns the two dimensional distance between the components of two points
double distance2D(double comp1, double comp2)
{
return std::abs(comp2 - comp1);
}
std::vector<cv::Point> corners (std::vector<cv::Point> pts, cv::Mat& img)
{
cv::Point tLeft = cv::Point (0, 0);
cv::Point tRight = cv::Point (0, img.cols);
cv::Point bLeft = cv::Point (img.rows, 0);
cv::Point bRight = cv::Point (img.rows, img.cols);
double tLeftD = 0;
double tRightD = 0;
double bLeftD = 0;
double bRightD = 0;
std::vector<cv::Point> c;
c.push_back(bLeft);
c.push_back(tLeft);
c.push_back(tRight);
c.push_back(bRight);
for (int i = 0; i < pts.size(); i++)
{
if (distance(pts[i], bLeft) > bLeftD)
{
bLeftD = distance(pts[i], bLeft);
c.at(0) = pts[i];
}
if (distance(pts[i], tLeft) > tLeftD)
{
tLeftD = distance(pts[i], tLeft);
c.at(1) = pts[i];
}
if (distance(pts[i], tRight) > tRightD)
{
tRightD = distance(pts[i], tRight);
c.at(2) = pts[i];
}
if (distance(pts[i], bRight) > bRightD)
{
bRightD = distance(pts[i], bRight);
c.at(3) = pts[i];
}
}
return c;
}
void calcHorizAngle(cv::Mat& image, double dStraight, std::vector<cv::Point> c)
{
dStraight = 180;
const double PI = 3.14159265;
// Calibration phase
double hStraight = distance2D(c[0].y, c[1].y);
// Note: dStraight may need to be calibrated too
double center = image.cols / 2;
double hLeft = distance2D(c[0].y, c[1].y);
double hRight = distance2D(c[2].y, c[3].y);
double wPixel = distance2D(c[0].x, c[3].x);
double hAvg = (hLeft + hRight) / 2;
double yTrans = c[0].x - center;
double alpha = std::atan(yTrans / dStraight) * 180 / PI;
double beta = std::atan((yTrans * (hStraight - hRight)) / (dStraight * (hStraight + hAvg))) * 180 / PI;
char str[50];
sprintf(str, "Alpha = %4.2f", alpha);
cv::putText(image, str, cv::Point(10, 380), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Beta = %4.2f", beta);
cv::putText(image, str, cv::Point(10, 400), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
}
double calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect)
{
double focalLen = 675.0;
// 20 inches real width
double wReal = 20;
double wPixel = 0;
double d = 180;
double theta = 0;
const double TOWER_HEIGHT = 7.1;
const double PI = 3.14159265;
cv::Point2f vert[4];
boundedRect.points(vert);
cv::line(image, vert[0], vert[3], cv::Scalar (255, 0, 0));
wPixel = distance(vert[0], vert[3]);
// focalLen = (wPixel * d) / wReal;
d = (wReal * focalLen) / wPixel;
theta = asin(TOWER_HEIGHT / (d / 12)) * 180 / PI;
char str[50];
//sprintf(str, "Line Length = %4.2f", wPixel);
//cv::putText(image, str, cv::Point(10, 400), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Focal Length = %4.2f", focalLen);
cv::putText(image, str, cv::Point(10, 420), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Distance = %4.2f", d);
cv::putText(image, str, cv::Point(10, 440), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
//sprintf(str, "Vert Angle = %4.2f", theta);
//cv::putText(image, str, cv::Point(10, 460), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
return d;
}
int main( int argc, char *argv[])
{
// Parameters for selecting which filters to apply
int blur = 0;
int color = 0;
int dilate_erode = 0;
int edge = 0;
int laplacian = 0;
int hough = 0;
int depth_dist = 0;
int merge = 0;
// Parameters for applying filters even if windows are closed
int apply_blur = 1;
int apply_color = 1;
int apply_dilate_erode = 0;
int apply_edge = 1;
int apply_laplacian = 0;
int apply_hough = 0;
int apply_depth_dist = 0;
int apply_merge = 1;
// gaussianBlur parameters
int blur_ksize = 7;
int sigmaX = 10;
int sigmaY = 10;
// hsvColorThreshold parameters
int hMin = 120;
int hMax = 200;
int sMin = 0;
int sMax = 40;
int vMin = 80;
int vMax = 100;
int debugMode = 0;
// 0 is none, 1 is bitAnd between h, s, and v
int bitAnd = 1;
// dilateErode parameters
int holes = 0;
int noise = 0;
int size = 1;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * size + 1, 2 * size + 1),
cv::Point(size, size) );
// cannyEdgeDetect parameters
int threshLow = 100;
int threshHigh = 300;
// laplacianSharpen parameters
int laplacian_ksize = 3;
// optional scale value added to image
int scale = 1;
// optional delta value added to image
int delta = 0;
int ddepth = CV_16S;
// houghLines parameters
int rho = 1;
int theta = 180;
int threshold = 50;
int lineMin = 50;
int maxGap = 10;
// mergeFinal parameters
int weight1 = 100;
int weight2 = 100;
// contour parameters
int contours = 120;
std::cout << "\n";
std::cout << " =========== FILTER LIST =========== " << "\n";
std::cout << "| |" << "\n";
std::cout << "| (0) No Filter |" << "\n";
std::cout << "| (1) Gaussian Blur Filter |" << "\n";
std::cout << "| (2) HSV Color Filter |" << "\n";
std::cout << "| (3) Dilate and Erode Filter |" << "\n";
std::cout << "| (4) Canny Edge Detection Filter |" << "\n";
std::cout << "| (5) Laplacian Sharpen Filter |" << "\n";
std::cout << "| (6) Hough Lines Filter |" << "\n";
std::cout << "| (7) Merge Final Outputs |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
std::cout << "\n";
std::cout << " ============== NOTICE ============= " << "\n";
std::cout << "| |" << "\n";
std::cout << "| Press 'q' to quit without saving |" << "\n";
std::cout << "| Press ' ' to pause |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
int port = 0;
cv::VideoCapture camera;
do
{
std::cout << "Enter the port number of the camera (-1 to quit): ";
std::cin >> port;
// Reprompt if user enters invalid input
if (port <= 10 && port >= 0)
{
camera = cv::VideoCapture (port);
if(!camera.isOpened())
{
std::cout << "\nUnable to open camera at Port " << port << "\n\n";
}
}
}
while (port != -1 && !camera.isOpened());
if (port == -1)
return -1;
// Matrices for holding image data
cv::Mat rgb, rgb_orig;
cv::Mat image;
// Press q to quit the program
char kill = ' ';
while ((kill != 'q') && (kill != 's'))
{
// Press space to pause program, then any key to resume
if (kill == ' ')
{
cv::waitKey(0);
}
selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
// Use images
if (argc > 2)
{
rgb = cv::imread(argv[1]);
// No data
if (!rgb.data)
{
std::cout << "No image data" << std::endl;
return -1;
}
}
else
{
camera >> rgb;
}
cv::imshow("BGR Feed", rgb);
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::createTrackbar("Contours Threshold:", "Contours", &contours, 255);
rgb.copyTo(image);
// Filters are only applied if last parameter is true, otherwise their windows are destroyed
gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
drawBoundedRects(image, contours);
cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
mergeFinalWindows(rgb, image, weight1, weight2, apply_merge, merge);
kill = cv::waitKey(5);
}
return 0;
}
|
Add in horizontal angle and corner detections code
|
Add in horizontal angle and corner detections code
Former-commit-id: ce924b5382f3e5cc4f647936f0551dc04c041233
|
C++
|
bsd-2-clause
|
valkyrierobotics/vision2017,valkyrierobotics/vision2017,valkyrierobotics/vision2017
|
9931db9ed94ad429f63763d5805fb24a16cb4a94
|
main.cpp
|
main.cpp
|
60448321-2749-11e6-99ba-e0f84713e7b8
|
60577e80-2749-11e6-98d2-e0f84713e7b8
|
Put the thingie in the thingie
|
Put the thingie in the thingie
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
f82c9e8804caea33381868ba0e8efd074d75ffe2
|
main.cpp
|
main.cpp
|
#include <QApplication>
#include <QCompleter>
#include <QKeySequence>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageLogger>
#include <QShortcut>
#include <QStandardPaths>
#include <QStringListModel>
#include <QVBoxLayout>
#include <QWebEngineFullScreenRequest>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWebEngineView>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <qtwebengineglobal.h>
#define HOMEPAGE "http://google.com"
#define SEARCH_ENGINE "http://google.com/search?q=%1"
#define HTTPS_FRAME_COLOR "#00ff00"
#define HTTPS_ERROR_FRAME_COLOR "#ff0000"
#define DEFAULT_FRAME_COLOR "#808080"
#define SHORTCUT_META (Qt::CTRL)
#define SHORTCUT_FORWARD {SHORTCUT_META + Qt::Key_I}
#define SHORTCUT_BACK {SHORTCUT_META + Qt::Key_O}
#define SHORTCUT_BAR {SHORTCUT_META + Qt::Key_Colon}
#define SHORTCUT_FIND {SHORTCUT_META + Qt::Key_Slash}
#define SHORTCUT_ESCAPE {SHORTCUT_META + Qt::Key_BracketLeft}
#define SHORTCUT_DOWN {SHORTCUT_META + Qt::Key_J}
#define SHORTCUT_UP {SHORTCUT_META + Qt::Key_K}
#define SHORTCUT_LEFT {SHORTCUT_META + Qt::Key_H}
#define SHORTCUT_RIGHT {SHORTCUT_META + Qt::Key_L}
#define SHORTCUT_TOP {SHORTCUT_META + Qt::Key_G, SHORTCUT_META + Qt::Key_G}
#define SHORTCUT_BOTTOM {SHORTCUT_META + Qt::SHIFT + Qt::Key_G}
#define SHORTCUT_ZOOMIN {SHORTCUT_META + Qt::Key_Plus}
#define SHORTCUT_ZOOMOUT {SHORTCUT_META + Qt::Key_Minus}
#define SCROLL_STEP_X 20
#define SCROLL_STEP_Y 20
#define ZOOM_STEP 0.1
QMessageLogger logger;
enum QueryType {
URLWithScheme,
URLWithoutScheme,
SearchWithScheme,
SearchWithoutScheme,
InSiteSearch
};
QueryType GuessQueryType(const QString &str) {
static const QRegExp hasScheme("^[a-zA-Z0-9]+://");
static const QRegExp address("^[^/]+(\\.[^/]+|:[0-9]+)");
if (str.startsWith("search:"))
return SearchWithScheme;
else if (str.startsWith("find:"))
return InSiteSearch;
else if (hasScheme.indexIn(str) != -1)
return URLWithScheme;
else if (address.indexIn(str) != -1)
return URLWithoutScheme;
else
return SearchWithoutScheme;
}
class TortaDatabase {
private:
QSqlDatabase db;
QSqlQuery append;
QSqlQuery search;
public:
TortaDatabase() : db(QSqlDatabase::addDatabase("QSQLITE")), append(db), search(db) {
db.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/db");
db.open();
db.exec("CREATE TABLE IF NOT EXISTS history \
(timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \
scheme TEXT NOT NULL, \
url TEXT NOT NULL)");
db.exec("CREATE VIEW IF NOT EXISTS recently AS \
SELECT MAX(timestamp) last_access, \
COUNT(timestamp) count, \
scheme, \
url \
FROM history \
GROUP BY scheme || url \
ORDER BY MAX(timestamp) DESC");
db.commit();
append.prepare("INSERT INTO history (scheme, url) VALUES (?, ?)");
append.setForwardOnly(true);
search.prepare("SELECT scheme || ':' || url \
FROM recently \
WHERE url LIKE ? \
ORDER BY count DESC");
search.setForwardOnly(true);
}
~TortaDatabase() {
db.close();
}
void appendHistory(const QUrl &url) {
append.bindValue(0, url.scheme());
append.bindValue(1, url.url().right(url.url().length() - url.scheme().length() - 1));
append.exec();
db.commit();
append.clear();
}
QStringList searchHistory(QString query) {
search.bindValue(0, "%%" + query.replace("%%", "\\%%") + "%%");
search.exec();
QStringList r;
while (search.next())
r << search.value(0).toString();
return r;
}
};
class TortaCompleter : public QCompleter {
Q_OBJECT
private:
QStringListModel model;
TortaDatabase &db;
public:
TortaCompleter(QLineEdit *line, TortaDatabase &db, QObject *parent=Q_NULLPTR)
: QCompleter(parent), db(db) {
setModel(&model);
setCompletionMode(QCompleter::UnfilteredPopupCompletion);
setModelSorting(QCompleter::CaseInsensitivelySortedModel);
setCaseSensitivity(Qt::CaseInsensitive);
connect(line, &QLineEdit::textChanged, this, &TortaCompleter::update);
}
signals:
private slots:
void update(const QString &word) {
const QueryType type(GuessQueryType(word));
QStringList list;
if (type == SearchWithoutScheme)
list << "find:" + word << "http://" + word;
else if (type == URLWithoutScheme)
list << "search:" + word << "find:" + word;
list << db.searchHistory(word);
model.setStringList(list);
}
};
class TortaPage : public QWebEnginePage {
Q_OBJECT
protected:
virtual bool certificateError(const QWebEngineCertificateError &error) override {
logger.warning(("ssl error: " + error.errorDescription()).toStdString().c_str());
emit sslError();
return true;
}
public:
TortaPage(QObject *parent=Q_NULLPTR) : QWebEnginePage(parent) {
profile()->setHttpUserAgent("DobosTorta");
}
signals:
void sslError();
};
class DobosTorta : public QMainWindow {
Q_OBJECT
private:
QLineEdit bar;
QWebEngineView view;
TortaDatabase db;
template<class Func>
void addShortcut(QKeySequence key,
const typename QtPrivate::FunctionPointer<Func>::Object *receiver,
Func method) {
connect(new QShortcut(key, this), &QShortcut::activated, receiver, method);
}
template<class Func> void addShortcut(QKeySequence key, Func functor) {
connect(new QShortcut(key, this), &QShortcut::activated, functor);
}
void setupShortcuts() {
addShortcut(SHORTCUT_FORWARD, &view, &QWebEngineView::forward);
addShortcut({Qt::ALT + Qt::Key_Right}, &view, &QWebEngineView::forward);
addShortcut(SHORTCUT_BACK, &view, &QWebEngineView::back);
addShortcut({Qt::ALT + Qt::Key_Left}, &view, &QWebEngineView::back);
addShortcut(SHORTCUT_BAR, this, &DobosTorta::toggleBar);
addShortcut(SHORTCUT_FIND, this, &DobosTorta::toggleFind);
addShortcut(SHORTCUT_ESCAPE, this, &DobosTorta::escapeBar);
addShortcut({Qt::Key_Escape}, this, &DobosTorta::escapeBar);
addShortcut(SHORTCUT_DOWN, [&]{ scroll(0, SCROLL_STEP_Y); });
addShortcut({Qt::Key_Down}, [&]{ scroll(0, SCROLL_STEP_Y); });
addShortcut(SHORTCUT_UP, [&]{ scroll(0, -SCROLL_STEP_Y); });
addShortcut({Qt::Key_Up}, [&]{ scroll(0, -SCROLL_STEP_Y); });
addShortcut(SHORTCUT_RIGHT, [&]{ scroll(SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_Right}, [&]{ scroll(SCROLL_STEP_X, 0); });
addShortcut(SHORTCUT_LEFT, [&]{ scroll(-SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_Left}, [&]{ scroll(-SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_PageDown}, [&]{
view.page()->runJavaScript("window.scrollBy(0, window.innerHeight / 2)");
});
addShortcut({Qt::Key_PageUp}, [&]{
view.page()->runJavaScript("window.scrollBy(0, -window.innerHeight / 2)");
});
addShortcut(SHORTCUT_TOP, [&]{
view.page()->runJavaScript("window.scrollTo(0, 0);");
});
addShortcut({Qt::Key_Home}, [&]{
view.page()->runJavaScript("window.scrollTo(0, 0);");
});
addShortcut(SHORTCUT_BOTTOM, [&]{
view.page()->runJavaScript("window.scrollTo(0, document.body.scrollHeight);");
});
addShortcut({Qt::Key_End}, [&]{
view.page()->runJavaScript("window.scrollTo(0, document.body.scrollHeight);");
});
addShortcut(SHORTCUT_ZOOMIN, [&]{ view.setZoomFactor(view.zoomFactor() + ZOOM_STEP); });
addShortcut(SHORTCUT_ZOOMOUT, [&]{ view.setZoomFactor(view.zoomFactor() - ZOOM_STEP); });
}
void setupBar() {
connect(&bar, &QLineEdit::textChanged, this, &DobosTorta::barChanged);
connect(&bar, &QLineEdit::returnPressed, this, &DobosTorta::executeBar);
bar.setCompleter(new TortaCompleter(&bar, db, this));
bar.setVisible(false);
setMenuWidget(&bar);
}
void setupView() {
auto page = new TortaPage();
view.setPage(page);
connect(&view, &QWebEngineView::titleChanged, this, &QWidget::setWindowTitle);
connect(&view, &QWebEngineView::urlChanged, this, &DobosTorta::urlChanged);
connect(view.page(), &QWebEnginePage::linkHovered, this, &DobosTorta::linkHovered);
connect(view.page(), &QWebEnginePage::iconChanged, this, &DobosTorta::setWindowIcon);
connect(page, &TortaPage::sslError, [&]{
setStyleSheet("QMainWindow { background-color: " HTTPS_ERROR_FRAME_COLOR "; }");
});
view.load(QUrl(HOMEPAGE));
setCentralWidget(&view);
}
void scroll(int x, int y) {
view.page()->runJavaScript(QString("window.scrollBy(%1, %2)").arg(x).arg(y));
}
public:
DobosTorta() : bar(HOMEPAGE, this), view(this) {
setupBar();
setupView();
setupShortcuts();
setContentsMargins(2, 2, 2, 2);
setStyleSheet("QMainWindow { background-color: " DEFAULT_FRAME_COLOR "; }");
}
signals:
private slots:
void executeBar() {
static const QString search(SEARCH_ENGINE);
const QString query(bar.text());
switch (GuessQueryType(query)) {
case URLWithScheme:
view.load(query);
bar.setVisible(false);
break;
case URLWithoutScheme:
view.load("http://" + query);
bar.setVisible(false);
break;
case SearchWithScheme:
view.load(search.arg(query.right(query.length() - 7)));
bar.setVisible(false);
break;
case SearchWithoutScheme:
view.load(search.arg(query));
bar.setVisible(false);
break;
case InSiteSearch:
view.page()->findText(query.right(query.length() - 5));
break;
}
}
void barChanged() {
const QString query(bar.text());
if (GuessQueryType(query) == InSiteSearch)
view.findText(query.right(query.length() - 5));
else
view.findText("");
}
void linkHovered(const QUrl &url) {
const QString str(url.toDisplayString());
if (str.length() == 0)
setWindowTitle(view.title());
else
setWindowTitle(str);
}
void urlChanged(const QUrl &u) {
db.appendHistory(u);
if (u.scheme() == "https")
setStyleSheet("QMainWindow { background-color: " HTTPS_FRAME_COLOR "; }");
else
setStyleSheet("QMainWindow { background-color: " DEFAULT_FRAME_COLOR "; }");
}
void toggleBar() {
if (!bar.hasFocus()) {
bar.setVisible(true);
bar.setText(view.url().toDisplayString());
bar.setFocus(Qt::ShortcutFocusReason);
} else if (GuessQueryType(bar.text()) == InSiteSearch) {
view.findText("");
bar.setText(bar.text().right(bar.text().length() - 5));
bar.selectAll();
} else {
escapeBar();
}
}
void toggleFind() {
if (!bar.hasFocus()) {
bar.setVisible(true);
bar.setFocus(Qt::ShortcutFocusReason);
bar.setText("find:");
} else if (GuessQueryType(bar.text()) != InSiteSearch) {
bar.setText("find:" + bar.text());
bar.setSelection(5, bar.text().length());
} else {
escapeBar();
}
}
void escapeBar() {
if (bar.hasFocus()) {
view.findText("");
view.setFocus(Qt::ShortcutFocusReason);
bar.setVisible(false);
}
}
void toggleFullScreen(QWebEngineFullScreenRequest r) {
if (r.toggleOn())
showFullScreen();
else
showNormal();
if (isFullScreen() == r.toggleOn())
r.accept();
else
r.reject();
}
};
int main(int argc, char **argv) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QtWebEngine::initialize();
QWebEngineSettings::defaultSettings()->setAttribute(
QWebEngineSettings::FullScreenSupportEnabled, true);
DobosTorta window;
window.show();
return app.exec();
}
#include "main.moc"
|
#include <QApplication>
#include <QCompleter>
#include <QKeySequence>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageLogger>
#include <QShortcut>
#include <QStandardPaths>
#include <QStringListModel>
#include <QVBoxLayout>
#include <QWebEngineFullScreenRequest>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWebEngineView>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <qtwebengineglobal.h>
#define HOMEPAGE "http://google.com"
#define SEARCH_ENGINE "http://google.com/search?q=%1"
#define HTTPS_FRAME_COLOR "#00ff00"
#define HTTPS_ERROR_FRAME_COLOR "#ff0000"
#define DEFAULT_FRAME_COLOR "#808080"
#define SHORTCUT_META (Qt::CTRL)
#define SHORTCUT_FORWARD {SHORTCUT_META + Qt::Key_I}
#define SHORTCUT_BACK {SHORTCUT_META + Qt::Key_O}
#define SHORTCUT_BAR {SHORTCUT_META + Qt::Key_Colon}
#define SHORTCUT_FIND {SHORTCUT_META + Qt::Key_Slash}
#define SHORTCUT_ESCAPE {SHORTCUT_META + Qt::Key_BracketLeft}
#define SHORTCUT_DOWN {SHORTCUT_META + Qt::Key_J}
#define SHORTCUT_UP {SHORTCUT_META + Qt::Key_K}
#define SHORTCUT_LEFT {SHORTCUT_META + Qt::Key_H}
#define SHORTCUT_RIGHT {SHORTCUT_META + Qt::Key_L}
#define SHORTCUT_TOP {SHORTCUT_META + Qt::Key_G, SHORTCUT_META + Qt::Key_G}
#define SHORTCUT_BOTTOM {SHORTCUT_META + Qt::SHIFT + Qt::Key_G}
#define SHORTCUT_ZOOMIN {SHORTCUT_META + Qt::Key_Plus}
#define SHORTCUT_ZOOMOUT {SHORTCUT_META + Qt::Key_Minus}
#define SCROLL_STEP_X 20
#define SCROLL_STEP_Y 20
#define ZOOM_STEP 0.1
QMessageLogger logger;
enum QueryType {
URLWithScheme,
URLWithoutScheme,
SearchWithScheme,
SearchWithoutScheme,
InSiteSearch
};
QueryType GuessQueryType(const QString &str) {
static const QRegExp hasScheme("^[a-zA-Z0-9]+://");
static const QRegExp address("^[^/]+(\\.[^/]+|:[0-9]+)");
if (str.startsWith("search:"))
return SearchWithScheme;
else if (str.startsWith("find:"))
return InSiteSearch;
else if (hasScheme.indexIn(str) != -1)
return URLWithScheme;
else if (address.indexIn(str) != -1)
return URLWithoutScheme;
else
return SearchWithoutScheme;
}
class TortaDatabase {
private:
QSqlDatabase db;
QSqlQuery append;
QSqlQuery search;
public:
TortaDatabase() : db(QSqlDatabase::addDatabase("QSQLITE")), append(db), search(db) {
db.setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/db");
db.open();
db.exec("CREATE TABLE IF NOT EXISTS history \
(timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \
scheme TEXT NOT NULL, \
url TEXT NOT NULL)");
db.exec("CREATE VIEW IF NOT EXISTS recently AS \
SELECT MAX(timestamp) last_access, \
COUNT(timestamp) count, \
scheme, \
url \
FROM history \
GROUP BY scheme || url \
ORDER BY MAX(timestamp) DESC");
db.commit();
append.prepare("INSERT INTO history (scheme, url) VALUES (?, ?)");
append.setForwardOnly(true);
search.prepare("SELECT scheme || ':' || url \
FROM recently \
WHERE url LIKE ? \
ORDER BY count DESC");
search.setForwardOnly(true);
}
~TortaDatabase() {
db.close();
}
void appendHistory(const QUrl &url) {
append.bindValue(0, url.scheme());
append.bindValue(1, url.url().right(url.url().length() - url.scheme().length() - 1));
append.exec();
db.commit();
append.clear();
}
QStringList searchHistory(QString query) {
search.bindValue(0, "%%" + query.replace("%%", "\\%%") + "%%");
search.exec();
QStringList r;
while (search.next())
r << search.value(0).toString();
return r;
}
};
class TortaCompleter : public QCompleter {
Q_OBJECT
private:
QStringListModel model;
TortaDatabase &db;
public:
TortaCompleter(QLineEdit *line, TortaDatabase &db, QObject *parent=Q_NULLPTR)
: QCompleter(parent), db(db) {
setModel(&model);
setCompletionMode(QCompleter::UnfilteredPopupCompletion);
setModelSorting(QCompleter::CaseInsensitivelySortedModel);
setCaseSensitivity(Qt::CaseInsensitive);
connect(line, &QLineEdit::textChanged, this, &TortaCompleter::update);
}
signals:
private slots:
void update(const QString &word) {
const QueryType type(GuessQueryType(word));
QStringList list;
if (type == SearchWithoutScheme)
list << "find:" + word << "http://" + word;
else if (type == URLWithoutScheme)
list << "search:" + word << "find:" + word;
list << db.searchHistory(word);
model.setStringList(list);
}
};
class TortaPage : public QWebEnginePage {
Q_OBJECT
protected:
virtual bool certificateError(const QWebEngineCertificateError &error) override {
logger.warning(("ssl error: " + error.errorDescription()).toStdString().c_str());
emit sslError();
return true;
}
public:
TortaPage(QObject *parent=Q_NULLPTR) : QWebEnginePage(parent) {
profile()->setHttpUserAgent("DobosTorta");
}
signals:
void sslError();
};
class DobosTorta : public QMainWindow {
Q_OBJECT
private:
QLineEdit bar;
QWebEngineView view;
TortaDatabase db;
template<class Func>
void addShortcut(QKeySequence key,
const typename QtPrivate::FunctionPointer<Func>::Object *receiver,
Func method) {
connect(new QShortcut(key, this), &QShortcut::activated, receiver, method);
}
template<class Func> void addShortcut(QKeySequence key, Func functor) {
connect(new QShortcut(key, this), &QShortcut::activated, functor);
}
void setupShortcuts() {
addShortcut(SHORTCUT_FORWARD, &view, &QWebEngineView::forward);
addShortcut({Qt::ALT + Qt::Key_Right}, &view, &QWebEngineView::forward);
addShortcut(SHORTCUT_BACK, &view, &QWebEngineView::back);
addShortcut({Qt::ALT + Qt::Key_Left}, &view, &QWebEngineView::back);
addShortcut(SHORTCUT_BAR, this, &DobosTorta::toggleBar);
addShortcut(SHORTCUT_FIND, this, &DobosTorta::toggleFind);
addShortcut(SHORTCUT_ESCAPE, this, &DobosTorta::escapeBar);
addShortcut({Qt::Key_Escape}, this, &DobosTorta::escapeBar);
addShortcut(SHORTCUT_DOWN, [&]{ scroll(0, SCROLL_STEP_Y); });
addShortcut({Qt::Key_Down}, [&]{ scroll(0, SCROLL_STEP_Y); });
addShortcut(SHORTCUT_UP, [&]{ scroll(0, -SCROLL_STEP_Y); });
addShortcut({Qt::Key_Up}, [&]{ scroll(0, -SCROLL_STEP_Y); });
addShortcut(SHORTCUT_RIGHT, [&]{ scroll(SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_Right}, [&]{ scroll(SCROLL_STEP_X, 0); });
addShortcut(SHORTCUT_LEFT, [&]{ scroll(-SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_Left}, [&]{ scroll(-SCROLL_STEP_X, 0); });
addShortcut({Qt::Key_PageDown}, [&]{
view.page()->runJavaScript("window.scrollBy(0, window.innerHeight / 2)");
});
addShortcut({Qt::Key_PageUp}, [&]{
view.page()->runJavaScript("window.scrollBy(0, -window.innerHeight / 2)");
});
addShortcut(SHORTCUT_TOP, [&]{
view.page()->runJavaScript("window.scrollTo(0, 0);");
});
addShortcut({Qt::Key_Home}, [&]{
view.page()->runJavaScript("window.scrollTo(0, 0);");
});
addShortcut(SHORTCUT_BOTTOM, [&]{
view.page()->runJavaScript("window.scrollTo(0, document.body.scrollHeight);");
});
addShortcut({Qt::Key_End}, [&]{
view.page()->runJavaScript("window.scrollTo(0, document.body.scrollHeight);");
});
addShortcut(SHORTCUT_ZOOMIN, [&]{ view.setZoomFactor(view.zoomFactor() + ZOOM_STEP); });
addShortcut(SHORTCUT_ZOOMOUT, [&]{ view.setZoomFactor(view.zoomFactor() - ZOOM_STEP); });
}
void setupBar() {
connect(&bar, &QLineEdit::textChanged, this, &DobosTorta::barChanged);
connect(&bar, &QLineEdit::returnPressed, this, &DobosTorta::executeBar);
bar.setCompleter(new TortaCompleter(&bar, db, this));
bar.setVisible(false);
setMenuWidget(&bar);
}
void setupView() {
auto page = new TortaPage();
view.setPage(page);
connect(&view, &QWebEngineView::titleChanged, this, &QWidget::setWindowTitle);
connect(&view, &QWebEngineView::urlChanged, this, &DobosTorta::urlChanged);
connect(view.page(), &QWebEnginePage::linkHovered, this, &DobosTorta::linkHovered);
connect(view.page(), &QWebEnginePage::iconChanged, this, &DobosTorta::setWindowIcon);
connect(page, &TortaPage::sslError, [&]{
setStyleSheet("QMainWindow { background-color: " HTTPS_ERROR_FRAME_COLOR "; }");
});
view.load(QUrl(HOMEPAGE));
setCentralWidget(&view);
}
void scroll(int x, int y) {
view.page()->runJavaScript(QString("window.scrollBy(%1, %2)").arg(x).arg(y));
}
void openBar(QString prefix, QString content) {
bar.setText(prefix + content);
bar.setVisible(true);
bar.setFocus(Qt::ShortcutFocusReason);
bar.setSelection(prefix.length(), content.length());
}
public:
DobosTorta() : bar(HOMEPAGE, this), view(this) {
setupBar();
setupView();
setupShortcuts();
setContentsMargins(2, 2, 2, 2);
setStyleSheet("QMainWindow { background-color: " DEFAULT_FRAME_COLOR "; }");
}
signals:
private slots:
void executeBar() {
static const QString search(SEARCH_ENGINE);
const QString query(bar.text());
switch (GuessQueryType(query)) {
case URLWithScheme:
view.load(query);
bar.setVisible(false);
break;
case URLWithoutScheme:
view.load("http://" + query);
bar.setVisible(false);
break;
case SearchWithScheme:
view.load(search.arg(query.right(query.length() - 7)));
bar.setVisible(false);
break;
case SearchWithoutScheme:
view.load(search.arg(query));
bar.setVisible(false);
break;
case InSiteSearch:
view.page()->findText(query.right(query.length() - 5));
break;
}
}
void barChanged() {
const QString query(bar.text());
if (GuessQueryType(query) == InSiteSearch)
view.findText(query.right(query.length() - 5));
else
view.findText("");
}
void linkHovered(const QUrl &url) {
const QString str(url.toDisplayString());
if (str.length() == 0)
setWindowTitle(view.title());
else
setWindowTitle(str);
}
void urlChanged(const QUrl &u) {
db.appendHistory(u);
if (u.scheme() == "https")
setStyleSheet("QMainWindow { background-color: " HTTPS_FRAME_COLOR "; }");
else
setStyleSheet("QMainWindow { background-color: " DEFAULT_FRAME_COLOR "; }");
}
void toggleBar() {
if (!bar.hasFocus())
openBar("", view.url().toDisplayString());
else if (GuessQueryType(bar.text()) == InSiteSearch)
openBar("", bar.text().right(bar.text().length() - 5));
else
escapeBar();
}
void toggleFind() {
if (!bar.hasFocus())
openBar("find:", "");
else if (GuessQueryType(bar.text()) != InSiteSearch)
openBar("find:", bar.text());
else
escapeBar();
}
void escapeBar() {
if (bar.hasFocus()) {
view.findText("");
view.setFocus(Qt::ShortcutFocusReason);
bar.setVisible(false);
}
}
void toggleFullScreen(QWebEngineFullScreenRequest r) {
if (r.toggleOn())
showFullScreen();
else
showNormal();
if (isFullScreen() == r.toggleOn())
r.accept();
else
r.reject();
}
};
int main(int argc, char **argv) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QtWebEngine::initialize();
QWebEngineSettings::defaultSettings()->setAttribute(
QWebEngineSettings::FullScreenSupportEnabled, true);
DobosTorta window;
window.show();
return app.exec();
}
#include "main.moc"
|
Refactor about focus handling of bar
|
Refactor about focus handling of bar
|
C++
|
mit
|
macrat/dobostorta
|
b7a628cb9ff4eac94507791b84445bc437339eef
|
main.cpp
|
main.cpp
|
//
// main.cpp
// screenshot - Take a screenshot for all of the active displays.
//
// Created by Leopold O'Donnell on 3/18/13.
// MIT-LIcense Copyright (c) 2013 Leo O'Donnell.
//
#include <stdio.h>
#include <stddef.h>
#include "screen_shooter.h"
int main(int argc, const char * argv[])
{
if (argc < 2) {
fprintf(stderr, "Error - Usage: screenshooter [-c compression] <filename.[jpg, png, tiff, gif, bmp]>\n");
return 1;
}
const char* filename = "";
float compression = 1.0;
CFStringRef format;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-c") == 0) {
compression = ::atof(argv[++i]);
}
else {
filename = argv[i];
}
}
if (strcasestr(filename, ".jpg")) {
format = kUTTypeJPEG2000;
}
else if (strcasestr(filename, ".png")) {
format = kUTTypePNG;
}
else if (strcasestr(filename, ".tiff")) {
format = kUTTypeTIFF;
}
else if (strcasestr(filename, ".gif")) {
format = kUTTypeGIF;
}
else if (strcasestr(filename, ".bmp")) {
format = kUTTypeBMP;
}
else {
fprintf(stderr, "Error filetype for %s is not supported: Try one of [jpg, png, tiff, gif, bmp]\n", filename);
return 1;
}
ScreenShooter shooter;
Screenshot* screenshot = shooter.take_screenshot(format, compression);
screenshot->write_png(filename);
delete screenshot;
return 0;
}
|
//
// main.cpp
// screenshot - Take a screenshot for all of the active displays.
//
// Created by Leopold O'Donnell on 3/18/13.
// MIT-LIcense Copyright (c) 2013 Leo O'Donnell.
//
#include <stdio.h>
#include <stddef.h>
#include "screen_shooter.h"
int main(int argc, const char * argv[])
{
if (argc < 2) {
fprintf(stderr, "Error - Usage: screenshooter [-c compression] <filename.[jpg, jp2, png, tiff, gif, bmp]>\n");
return 1;
}
const char* filename = "";
float compression = 1.0;
CFStringRef format;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-c") == 0) {
compression = ::atof(argv[++i]);
}
else {
filename = argv[i];
}
}
if (strcasestr(filename, ".jpg")) {
format = kUTTypeJPEG;
}
else if (strcasestr(filename, ".jp2")) {
format = kUTTypeJPEG2000;
}
else if (strcasestr(filename, ".png")) {
format = kUTTypePNG;
}
else if (strcasestr(filename, ".tiff")) {
format = kUTTypeTIFF;
}
else if (strcasestr(filename, ".gif")) {
format = kUTTypeGIF;
}
else if (strcasestr(filename, ".bmp")) {
format = kUTTypeBMP;
}
else {
fprintf(stderr, "Error filetype for %s is not supported: Try one of [jpg, jp2, png, tiff, gif, bmp]\n", filename);
return 1;
}
ScreenShooter shooter;
Screenshot* screenshot = shooter.take_screenshot(format, compression);
screenshot->write_png(filename);
delete screenshot;
return 0;
}
|
Support jpeg and jpeg 2000
|
Support jpeg and jpeg 2000
|
C++
|
mit
|
leopoldodonnell/screenshot
|
3b670b324f47c746230ad42beb1fe625beeadce4
|
main.cpp
|
main.cpp
|
addd10f8-4b02-11e5-a687-28cfe9171a43
|
adeb0a30-4b02-11e5-9831-28cfe9171a43
|
add file
|
add file
|
C++
|
apache-2.0
|
haosdent/jcgroup,haosdent/jcgroup
|
7dc6f76eb9243ef7a185c710deb9ca3cfcdd7353
|
maybe.hh
|
maybe.hh
|
#ifndef MAYBE_HH
#define MAYBE_HH
#include <cassert>
#include <new>
#include <memory>
#include <type_traits>
template<typename T>
struct maybe {
maybe() noexcept : is_init(false) {}
maybe(const T &other) noexcept(std::is_nothrow_copy_constructible<T>::value) : is_init(false) {
new (&memory) T(other);
is_init = true;
}
maybe(T &&other) noexcept(std::is_nothrow_move_constructible<T>::value) : is_init(false) {
new (&memory) T(std::move(other));
is_init = true;
}
maybe(const maybe &other) noexcept(std::is_nothrow_copy_constructible<T>::value) : is_init(false) {
if (other.is_init) {
new (&memory) T(*other.as_ptr());
is_init = other.is_init;
}
}
maybe(maybe &&other) noexcept(std::is_nothrow_move_constructible<T>::value) : is_init(false) {
if (other.is_init) {
new (&memory) T(std::move(*other.as_ptr()));
other.is_init = false;
is_init = true;
}
}
maybe &operator=(const maybe &other) {
if (this != &other && other.is_init) {
if (is_init) {
*as_ptr() = *other.as_ptr();
} else {
new (&memory) T(*other.as_ptr());
is_init = true;
}
} else {
clear();
}
return *this;
}
maybe &operator=(maybe &&other) {
assert(this != &other);
if (other.is_init) {
other.is_init = false;
if (is_init) {
*as_ptr() = std::move(*other.as_ptr());
} else {
new (&memory) T(std::move(*other.as_ptr()));
is_init = true;
}
} else {
clear();
}
return *this;
}
~maybe() {
if (is_init) {
as_ptr()->~T();
}
}
explicit operator bool() const noexcept {
return is_init;
}
T &operator*() noexcept {
assert(is_init);
return *as_ptr();
}
const T &operator*() const noexcept {
assert(is_init);
return *as_ptr();
}
T *operator->() noexcept {
assert(is_init);
return as_ptr();
}
const T *operator->() const noexcept {
assert(is_init);
return as_ptr();
}
T *get() noexcept {
return is_init ? as_ptr() : nullptr;
}
const T *get() const noexcept {
return is_init ? as_ptr() : nullptr;
}
T const &get_value_or(T const &v) const noexcept {
return is_init ? *as_ptr() : v;
}
void clear() {
if (is_init) {
as_ptr()->~T();
is_init = false;
}
}
private:
T *as_ptr() { return reinterpret_cast<T *>(&memory); }
const T *as_ptr() const { return reinterpret_cast<const T *>(&memory); }
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type memory;
bool is_init;
};
#endif
|
#ifndef MAYBE_HH
#define MAYBE_HH
#include <cassert>
#include <new>
#include <memory>
#include <type_traits>
template<typename T>
struct maybe {
maybe() noexcept : is_init(false) {}
maybe(const T &other) noexcept(std::is_nothrow_copy_constructible<T>::value) : is_init(false) {
new (&memory) T(other);
is_init = true;
}
maybe(T &&other) noexcept(std::is_nothrow_move_constructible<T>::value) : is_init(false) {
new (&memory) T(std::move(other));
is_init = true;
}
maybe(const maybe &other) noexcept(std::is_nothrow_copy_constructible<T>::value) : is_init(false) {
if (other.is_init) {
new (&memory) T(*other.as_ptr());
is_init = other.is_init;
}
}
maybe(maybe &&other) noexcept(std::is_nothrow_move_constructible<T>::value) : is_init(false) {
if (other.is_init) {
new (&memory) T(std::move(*other.as_ptr()));
other.is_init = false;
is_init = true;
}
}
maybe &operator=(const maybe &other) {
if (this != &other && other.is_init) {
if (is_init) {
*as_ptr() = *other.as_ptr();
} else {
new (&memory) T(*other.as_ptr());
is_init = true;
}
} else {
clear();
}
return *this;
}
maybe &operator=(maybe &&other) {
assert(this != &other);
if (other.is_init) {
other.is_init = false;
if (is_init) {
*as_ptr() = std::move(*other.as_ptr());
} else {
new (&memory) T(std::move(*other.as_ptr()));
is_init = true;
}
} else {
clear();
}
return *this;
}
~maybe() {
if (is_init) {
as_ptr()->~T();
}
}
explicit operator bool() const noexcept {
return is_init;
}
T &operator*() noexcept {
assert(is_init);
return *as_ptr();
}
const T &operator*() const noexcept {
assert(is_init);
return *as_ptr();
}
T *operator->() noexcept {
assert(is_init);
return as_ptr();
}
const T *operator->() const noexcept {
assert(is_init);
return as_ptr();
}
T *get() noexcept {
return is_init ? as_ptr() : nullptr;
}
const T *get() const noexcept {
return is_init ? as_ptr() : nullptr;
}
T const &get_value_or(T const &v) const noexcept {
return is_init ? *as_ptr() : v;
}
void clear() noexcept(std::is_nothrow_destructible<T>::value) {
if (is_init) {
as_ptr()->~T();
is_init = false;
}
}
private:
T *as_ptr() { return reinterpret_cast<T *>(&memory); }
const T *as_ptr() const { return reinterpret_cast<const T *>(&memory); }
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type memory;
bool is_init;
};
#endif
|
add noexcept spec to clear method
|
maybe.hh: add noexcept spec to clear method
|
C++
|
mit
|
thestinger/util,thestinger/util
|
700833268dabae5594ee0cb712bf8db430b9bfaa
|
main.cpp
|
main.cpp
|
f2ca0e68-2747-11e6-8351-e0f84713e7b8
|
f2dc9eae-2747-11e6-a489-e0f84713e7b8
|
Put the thingie in the thingie
|
Put the thingie in the thingie
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
1b163e06f4f0e8ac9b6571a2d1cfcff6171dd81a
|
main.cpp
|
main.cpp
|
#include <random>
#include "FATFileSystem.h"
#include "SDBlockDevice.h"
#include "mbed.h"
#include "stdio.h"
#include "uTensor_util.hpp"
#include "tensor.hpp"
#include "tensorIdxImporterTests.hpp"
//#include "deep_mnist_mlp.hpp"
Serial pc(USBTX, USBRX, 115200);
SDBlockDevice bd(MBED_CONF_APP_SD_MOSI, MBED_CONF_APP_SD_MISO,
MBED_CONF_APP_SD_CLK, MBED_CONF_APP_SD_CS);
FATFileSystem fs("fs");
int main(int argc, char** argv) {
ON_ERR(bd.init(), "SDBlockDevice init ");
ON_ERR(fs.mount(&bd), "Mounting the filesystem on \"/fs\". ");
printf("Deep MLP on Mbed (Trained with Tensorflow)\r\n\r\n");
printf("running deep-mlp...\r\n");
// int prediction = runMLP("/fs/testData/deep_mlp/import-Placeholder_0.idx");
// printf("prediction: %d\r\n", prediction);
idxImporterTest idxTest;
idxTest.runAll();
idxTest.printSummary();
//In [24]: tf.get_default_graph().get_tensor_by_name("import/y_pred:0").eval(feed_dict={x: mnist.test.images[0:1]})
//Out[24]: array([7])
ON_ERR(fs.unmount(), "fs unmount ");
ON_ERR(bd.deinit(), "SDBlockDevice de-init ");
}
|
#include <random>
#include "FATFileSystem.h"
#include "SDBlockDevice.h"
#include "mbed.h"
#include "stdio.h"
#include "uTensor_util.hpp"
#include "tensor.hpp"
#include "tensorIdxImporterTests.hpp"
//#include "deep_mnist_mlp.hpp"
Serial pc(USBTX, USBRX, 115200);
SDBlockDevice bd(MBED_CONF_APP_SD_MOSI, MBED_CONF_APP_SD_MISO,
MBED_CONF_APP_SD_CLK, MBED_CONF_APP_SD_CS);
FATFileSystem fs("fs");
int main(int argc, char** argv) {
ON_ERR(bd.init(), "SDBlockDevice init ");
ON_ERR(fs.mount(&bd), "Mounting the filesystem on \"/fs\". ");
printf("Deep MLP on Mbed (Trained with Tensorflow)\r\n\r\n");
printf("running deep-mlp...\r\n");
// int prediction = runMLP("/fs/testData/deep_mlp/import-Placeholder_0.idx");
// printf("prediction: %d\r\n", prediction);
idxImporterTest idxTest;
idxTest.runAll();
printf("running matrix test ...\r\n");
// matrixOpsTest matrixTests;
// matrixTests.runAll();
printf("IDX import:\r\n");
idxTest.printSummary();
printf("Matrix: \r\n");
// matrixTests.printSummary();
//In [24]: tf.get_default_graph().get_tensor_by_name("import/y_pred:0").eval(feed_dict={x: mnist.test.images[0:1]})
//Out[24]: array([7])
ON_ERR(fs.unmount(), "fs unmount ");
ON_ERR(bd.deinit(), "SDBlockDevice de-init ");
}
|
revise main for test idx and matrixops
|
revise main for test idx and matrixops
|
C++
|
apache-2.0
|
neil-tan/uTensor,neil-tan/uTensor
|
171f30a58f6483efb660a95f3c6bf587cbebbc84
|
main.cpp
|
main.cpp
|
#include <omp.h>
#include "evaluate_circuit.h"
// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
// grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/bristlecone_48_1-40-1_0.txt \
// ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
// Reading input.
if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
int current_arg = 1;
qflex::QflexInput input;
input.I = atoi(argv[current_arg++]);
input.J = atoi(argv[current_arg++]);
input.K = atoi(argv[current_arg++]);
input.fidelity = atof(argv[current_arg++]);
// Creating streams for input files.
std::string circuit_filename = std::string(argv[current_arg++]);
auto circuit_data = std::ifstream(circuit_filename);
if (!circuit_data.good()) {
std::cout << "Cannot open circuit data file: " << circuit_filename
<< std::endl;
assert(circuit_data.good());
}
input.circuit_data = &circuit_data;
std::string ordering_filename = std::string(argv[current_arg++]);
auto ordering_data = std::ifstream(ordering_filename);
if (!ordering_data.good()) {
std::cout << "Cannot open ordering data file: " << ordering_filename
<< std::endl;
assert(ordering_data.good());
}
input.ordering_data = &ordering_data;
std::string grid_filename = std::string(argv[current_arg++]);
auto grid_data = std::ifstream(grid_filename);
if (!grid_data.good()) {
std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
assert(grid_data.good());
}
input.grid_data = &grid_data;
// Setting initial and final circuit states.
if (argc > current_arg) {
input.initial_state = std::string(argv[current_arg++]);
}
if (argc > current_arg) {
input.final_state_A = std::string(argv[current_arg++]);
}
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
qflex::EvaluateCircuit(&input);
// Printing output.
for (int c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
return 0;
}
|
#include <omp.h>
#include "evaluate_circuit.h"
// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
// grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/bristlecone_48_1-40-1_0.txt \
// ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
//
int main(int argc, char** argv) {
// Reading input.
if (argc < 8) {
std::cerr << "\n\tUsage: qflex I J K fidelity circuit_filename ordering_filename grid_filename [initial_conf] [final_conf]\n\n";
throw std::logic_error("ERROR: Not enough arguments.");
}
int current_arg = 1;
qflex::QflexInput input;
input.I = atoi(argv[current_arg++]);
input.J = atoi(argv[current_arg++]);
input.K = atoi(argv[current_arg++]);
input.fidelity = atof(argv[current_arg++]);
// Creating streams for input files.
std::string circuit_filename = std::string(argv[current_arg++]);
auto circuit_data = std::ifstream(circuit_filename);
if (!circuit_data.good()) {
std::cout << "Cannot open circuit data file: " << circuit_filename
<< std::endl;
assert(circuit_data.good());
}
input.circuit_data = &circuit_data;
std::string ordering_filename = std::string(argv[current_arg++]);
auto ordering_data = std::ifstream(ordering_filename);
if (!ordering_data.good()) {
std::cout << "Cannot open ordering data file: " << ordering_filename
<< std::endl;
assert(ordering_data.good());
}
input.ordering_data = &ordering_data;
std::string grid_filename = std::string(argv[current_arg++]);
auto grid_data = std::ifstream(grid_filename);
if (!grid_data.good()) {
std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
assert(grid_data.good());
}
input.grid_data = &grid_data;
// Setting initial and final circuit states.
if (argc > current_arg) {
input.initial_state = std::string(argv[current_arg++]);
}
if (argc > current_arg) {
input.final_state_A = std::string(argv[current_arg++]);
}
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
qflex::EvaluateCircuit(&input);
// Printing output.
for (int c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
return 0;
}
|
Print simple help.
|
Print simple help.
|
C++
|
apache-2.0
|
ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex
|
d7471eb215d54705098fb7a020eb8dfef9db9558
|
main.cpp
|
main.cpp
|
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>
#include "protocolparser.h"
#include "xmllinelocator.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName( "Protogen" );
QCoreApplication::setApplicationVersion(ProtocolParser::genVersion);
QCommandLineParser argParser;
argParser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
argParser.setApplicationDescription("Protocol generation tool");
argParser.addHelpOption();
argParser.addVersionOption();
argParser.addPositionalArgument("input", "Protocol defintion file, .xml");
argParser.addPositionalArgument("outputpath", "Path for generated protocol files (default = current working directory)");
argParser.addOption({{"d", "docs"}, "Path for generated documentation files (default = outputpath)", "docpath"});
argParser.addOption({"license", "Path to license template file which will be prepended to each generated file", "license"});
argParser.addOption({"show-hidden-items", "Show all items in documentation even if they are marked as 'hidden'"});
argParser.addOption({"latex", "Enable extra documentation output required for LaTeX integration"});
argParser.addOption({{"l", "latex-header-level"}, "LaTeX header level", "latexlevel"});
argParser.addOption({"no-doxygen", "Skip generation of developer-level documentation"});
argParser.addOption({"no-markdown", "Skip generation of user-level documentation"});
argParser.addOption({"no-about-section", "Skip generation of \"About this ICD\" section in documentation output"});
argParser.addOption({"no-helper-files", "Skip creation of helper files not directly specifed by protocol .xml file"});
argParser.addOption({{"s", "style"}, "Specify a css file to override the default style for HTML documentation", "cssfile"});
argParser.addOption({"no-css", "Skip generation of any css data in documentation files"});
argParser.addOption({"no-unrecognized-warnings", "Suppress warnings for unrecognized xml tags"});
argParser.process(a);
ProtocolParser parser;
// Process the positional arguments
QStringList args = argParser.positionalArguments();
QStringList otherfiles;
QString filename, path;
for(int i = 0; i < args.count(); i++)
{
QString argument = args.at(i);
// The first ".xml" argument is the main file, but you can
// have more xml files after that if you want.
if(argument.endsWith(".xml", Qt::CaseInsensitive))
{
if(filename.isEmpty())
filename = argument;
else
otherfiles.append(argument);
}
else if(!argument.isEmpty())
path = argument;
}
if(filename.isEmpty())
{
std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
return 2; // no input file
}
// License template file
QString licenseTemplate = argParser.value("license");
if (!licenseTemplate.isEmpty())
{
licenseTemplate = QDir().absoluteFilePath(licenseTemplate);
QFile licenseFile(licenseTemplate);
if (licenseFile.exists())
{
if (licenseFile.open(QIODevice::ReadOnly) && licenseFile.isOpen() && licenseFile.isReadable())
{
QString licenseText = licenseFile.readAll();
parser.setLicenseText(licenseText);
}
else
{
std::cerr << "error: could not open license file '" << licenseTemplate.toStdString() << "'" << std::endl;
}
}
else
{
std::cerr << "error: license file '" << licenseTemplate.toStdString() << "' does not exist" << std::endl;
}
}
// Documentation directory
QString docs = argParser.value("docs");
if (!docs.isEmpty() && !argParser.isSet("no-markdown"))
{
docs = ProtocolFile::sanitizePath(docs);
if (QDir(docs).exists() || QDir::current().mkdir(docs))
{
parser.setDocsPath(docs);
}
}
// Process the optional arguments
parser.disableDoxygen(argParser.isSet("no-doxygen"));
parser.disableMarkdown(argParser.isSet("no-markdown"));
parser.disableHelperFiles(argParser.isSet("no-helper-files"));
parser.disableAboutSection(argParser.isSet("no-about-section"));
parser.showHiddenItems(argParser.isSet("show-hidden-items"));
parser.disableUnrecognizedWarnings(argParser.isSet("no-unrecognized-warnings"));
parser.setLaTeXSupport(argParser.isSet("latex"));
parser.disableCSS(argParser.isSet("no-css"));
QString latexLevel = argParser.value("latex-header-level");
if (!latexLevel.isEmpty())
{
bool ok = false;
int lvl = latexLevel.toInt(&ok);
if (ok)
{
parser.setLaTeXLevel(lvl);
}
else
{
std::cerr << "warning: -latex-header-level argument '" << latexLevel.toStdString() << "' is invalid.";
}
}
QString css = argParser.value("style");
if (!css.isEmpty() && css.endsWith(".css", Qt::CaseInsensitive))
{
// First attempt to open the file
QFile file(css);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
parser.setInlineCSS(file.readAll());
file.close();
}
else
{
std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(css).toStdString() << ", using default css" << std::endl;
}
}
if (parser.parse(filename, path, otherfiles))
{
// Normal exit
return 0;
}
else
{
// Input file in error
return 1;
}
}
|
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>
#include "protocolparser.h"
#include "xmllinelocator.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName( "Protogen" );
QCoreApplication::setApplicationVersion(ProtocolParser::genVersion);
QCommandLineParser argParser;
argParser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
argParser.setApplicationDescription("Protocol generation tool");
argParser.addHelpOption();
argParser.addVersionOption();
argParser.addPositionalArgument("input", "Protocol defintion file, .xml");
argParser.addPositionalArgument("outputpath", "Path for generated protocol files (default = current working directory)");
argParser.addOption({{"d", "docs"}, "Path for generated documentation files (default = outputpath)", "docpath"});
argParser.addOption({"license", "Path to license template file which will be prepended to each generated file", "license"});
argParser.addOption({"show-hidden-items", "Show all items in documentation even if they are marked as 'hidden'"});
argParser.addOption({"latex", "Enable extra documentation output required for LaTeX integration"});
argParser.addOption({{"l", "latex-header-level"}, "LaTeX header level", "latexlevel"});
argParser.addOption({"no-doxygen", "Skip generation of developer-level documentation"});
argParser.addOption({"no-markdown", "Skip generation of user-level documentation"});
argParser.addOption({"no-about-section", "Skip generation of \"About this ICD\" section in documentation output"});
argParser.addOption({"no-helper-files", "Skip creation of helper files not directly specifed by protocol .xml file"});
argParser.addOption({{"s", "style"}, "Specify a css file to override the default style for HTML documentation", "cssfile"});
argParser.addOption({"no-css", "Skip generation of any css data in documentation files"});
argParser.addOption({"no-unrecognized-warnings", "Suppress warnings for unrecognized xml tags"});
argParser.process(a);
ProtocolParser parser;
// Process the positional arguments
QStringList args = argParser.positionalArguments();
QStringList otherfiles;
QString filename, path;
for(int i = 0; i < args.count(); i++)
{
QString argument = args.at(i);
// The first ".xml" argument is the main file, but you can
// have more xml files after that if you want.
if(argument.endsWith(".xml", Qt::CaseInsensitive))
{
if(filename.isEmpty())
filename = argument;
else
otherfiles.append(argument);
}
else if(!argument.isEmpty())
path = argument;
}
if(filename.isEmpty())
{
std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
return 2; // no input file
}
// License template file
QString licenseTemplate = argParser.value("license");
if (!licenseTemplate.isEmpty())
{
licenseTemplate = QDir().absoluteFilePath(licenseTemplate);
QFile licenseFile(licenseTemplate);
if (licenseFile.exists())
{
if (licenseFile.open(QIODevice::ReadOnly) && licenseFile.isOpen() && licenseFile.isReadable())
{
QString licenseText = licenseFile.readAll();
licenseText = licenseText.replace("\r\n", "\n");
parser.setLicenseText(licenseText);
}
else
{
std::cerr << "error: could not open license file '" << licenseTemplate.toStdString() << "'" << std::endl;
}
}
else
{
std::cerr << "error: license file '" << licenseTemplate.toStdString() << "' does not exist" << std::endl;
}
}
// Documentation directory
QString docs = argParser.value("docs");
if (!docs.isEmpty() && !argParser.isSet("no-markdown"))
{
docs = ProtocolFile::sanitizePath(docs);
if (QDir(docs).exists() || QDir::current().mkdir(docs))
{
parser.setDocsPath(docs);
}
}
// Process the optional arguments
parser.disableDoxygen(argParser.isSet("no-doxygen"));
parser.disableMarkdown(argParser.isSet("no-markdown"));
parser.disableHelperFiles(argParser.isSet("no-helper-files"));
parser.disableAboutSection(argParser.isSet("no-about-section"));
parser.showHiddenItems(argParser.isSet("show-hidden-items"));
parser.disableUnrecognizedWarnings(argParser.isSet("no-unrecognized-warnings"));
parser.setLaTeXSupport(argParser.isSet("latex"));
parser.disableCSS(argParser.isSet("no-css"));
QString latexLevel = argParser.value("latex-header-level");
if (!latexLevel.isEmpty())
{
bool ok = false;
int lvl = latexLevel.toInt(&ok);
if (ok)
{
parser.setLaTeXLevel(lvl);
}
else
{
std::cerr << "warning: -latex-header-level argument '" << latexLevel.toStdString() << "' is invalid.";
}
}
QString css = argParser.value("style");
if (!css.isEmpty() && css.endsWith(".css", Qt::CaseInsensitive))
{
// First attempt to open the file
QFile file(css);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
parser.setInlineCSS(file.readAll());
file.close();
}
else
{
std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(css).toStdString() << ", using default css" << std::endl;
}
}
if (parser.parse(filename, path, otherfiles))
{
// Normal exit
return 0;
}
else
{
// Input file in error
return 1;
}
}
|
Enforce standard line-endings
|
Enforce standard line-endings
|
C++
|
mit
|
jefffisher/ProtoGen,billvaglienti/ProtoGen,jefffisher/ProtoGen,billvaglienti/ProtoGen,jefffisher/ProtoGen,billvaglienti/ProtoGen
|
d7be0f2c58199603671d3198c87463ff3433eea0
|
src/osx_window_capture.cpp
|
src/osx_window_capture.cpp
|
#include "osx_window_capture.h"
// remove the window title bar which we are not interested in
#define OSX_WINDOW_TITLE_BAR_HEIGHT 22
OSXWindowCapture::OSXWindowCapture(const string& windowName)
:name(windowName), winId(0)
{
Update(true);
}
void OSXWindowCapture::Update(bool forced) {
if(forced || updateTimer.hasExpired(OSX_UPDATE_WINDOW_DATA_INTERVAL)) {
winId = FindWindow(name);
rect = GetWindowRect(winId);
updateTimer.restart();
}
}
bool OSXWindowCapture::WindowFound() {
Update();
return winId != 0;
}
int OSXWindowCapture::GetWidth() {
Update();
return CGRectGetWidth(rect);
}
int OSXWindowCapture::GetHeight() {
Update();
int height = CGRectGetHeight(rect);
return IsFullscreen() ? height : max<int>(height - OSX_WINDOW_TITLE_BAR_HEIGHT, 0);
}
QPixmap OSXWindowCapture::Capture(int x, int y, int w, int h) {
Update();
if(!w) w = GetWidth();
if(!w) h = GetHeight();
CGRect captureRect = CGRectMake(x + CGRectGetMinX(rect),
y + CGRectGetMinY(rect) + (IsFullscreen() ? 0 : OSX_WINDOW_TITLE_BAR_HEIGHT),
w,
h);
CGImageRef image = CGWindowListCreateImage(captureRect,
kCGWindowListOptionIncludingWindow,
winId,
kCGWindowImageNominalResolution | kCGWindowImageBoundsIgnoreFraming);
QPixmap pixmap = QPixmap::fromMacCGImageRef(image);
CGImageRelease(image);
return pixmap;
}
bool OSXWindowCapture::IsFullscreen() {
// this is not the most elegant solution, but I couldn't find a better way
return CGRectGetMinX(rect) == 0.0f &&
CGRectGetMinY(rect) == 0.0f &&
(int(CGRectGetHeight(rect)) & OSX_WINDOW_TITLE_BAR_HEIGHT) != OSX_WINDOW_TITLE_BAR_HEIGHT;
}
int OSXWindowCapture::FindWindow(const string& name) {
int winId = 0;
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CFIndex numWindows = CFArrayGetCount(windowList);
CFStringRef nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name.c_str(), kCFStringEncodingMacRoman);
for( int i = 0; i < (int)numWindows; i++ ) {
CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);
CFStringRef thisWindowName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowName);
CFStringRef thisWindowOwnerName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowOwnerName);
CFNumberRef thisWindowNumber = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowNumber);
if(thisWindowOwnerName && CFStringCompare(thisWindowOwnerName, nameRef, 0) == kCFCompareEqualTo) {
if(thisWindowName && CFStringCompare(thisWindowName, nameRef, 0) == kCFCompareEqualTo) {
CFNumberGetValue(thisWindowNumber, kCFNumberIntType, &winId);
break;
}
}
}
CFRelease(nameRef);
return winId;
}
CGRect OSXWindowCapture::GetWindowRect(int windowId) {
CGRect rect = CGRectMake(0, 0, 0, 0);
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, windowId);
CFIndex numWindows = CFArrayGetCount(windowList);
if( numWindows > 0 ) {
CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, 0);
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)CFDictionaryGetValue(info, kCGWindowBounds), &rect);
}
return rect;
}
|
#include "osx_window_capture.h"
// remove the window title bar which we are not interested in
#define OSX_WINDOW_TITLE_BAR_HEIGHT 22
OSXWindowCapture::OSXWindowCapture(const string& windowName)
:name(windowName), winId(0)
{
Update(true);
}
void OSXWindowCapture::Update(bool forced) {
if(forced || updateTimer.hasExpired(OSX_UPDATE_WINDOW_DATA_INTERVAL)) {
winId = FindWindow(name);
rect = GetWindowRect(winId);
updateTimer.restart();
}
}
bool OSXWindowCapture::WindowFound() {
Update();
return winId != 0;
}
int OSXWindowCapture::GetWidth() {
Update();
return CGRectGetWidth(rect);
}
int OSXWindowCapture::GetHeight() {
Update();
int height = CGRectGetHeight(rect);
return IsFullscreen() ? height : max<int>(height - OSX_WINDOW_TITLE_BAR_HEIGHT, 0);
}
QPixmap OSXWindowCapture::Capture(int x, int y, int w, int h) {
Update();
if(!w) w = GetWidth();
if(!w) h = GetHeight();
CGRect captureRect = CGRectMake(x + CGRectGetMinX(rect),
y + CGRectGetMinY(rect) + (IsFullscreen() ? 0 : OSX_WINDOW_TITLE_BAR_HEIGHT),
w,
h);
CGImageRef image = CGWindowListCreateImage(captureRect,
kCGWindowListOptionIncludingWindow,
winId,
kCGWindowImageNominalResolution | kCGWindowImageBoundsIgnoreFraming);
QPixmap pixmap = QPixmap::fromMacCGImageRef(image);
CGImageRelease(image);
return pixmap;
}
bool OSXWindowCapture::IsFullscreen() {
// this is not the most elegant solution, but I couldn't find a better way
return CGRectGetMinX(rect) == 0.0f &&
CGRectGetMinY(rect) == 0.0f &&
(int(CGRectGetHeight(rect)) & OSX_WINDOW_TITLE_BAR_HEIGHT) != OSX_WINDOW_TITLE_BAR_HEIGHT;
}
int OSXWindowCapture::FindWindow(const string& name) {
int winId = 0;
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CFIndex numWindows = CFArrayGetCount(windowList);
CFStringRef nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name.c_str(), kCFStringEncodingMacRoman);
for( int i = 0; i < (int)numWindows; i++ ) {
CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);
CFStringRef thisWindowName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowName);
CFStringRef thisWindowOwnerName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowOwnerName);
CFNumberRef thisWindowNumber = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowNumber);
if(thisWindowOwnerName && CFStringCompare(thisWindowOwnerName, nameRef, 0) == kCFCompareEqualTo) {
if(thisWindowName && CFStringCompare(thisWindowName, nameRef, 0) == kCFCompareEqualTo) {
CFNumberGetValue(thisWindowNumber, kCFNumberIntType, &winId);
break;
}
}
}
CFRelease(nameRef);
CFRelease(windowList);
return winId;
}
CGRect OSXWindowCapture::GetWindowRect(int windowId) {
CGRect rect = CGRectMake(0, 0, 0, 0);
CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, windowId);
CFIndex numWindows = CFArrayGetCount(windowList);
if( numWindows > 0 ) {
CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, 0);
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)CFDictionaryGetValue(info, kCGWindowBounds), &rect);
}
CFRelease(windowList);
return rect;
}
|
fix memory leaks
|
fix memory leaks
|
C++
|
lgpl-2.1
|
bencart/track-o-bot,elzoido/track-o-bot,stevschmid/track-o-bot,bencart/track-o-bot,stevschmid/track-o-bot,BOSSoNe0013/track-o-bot,BOSSoNe0013/track-o-bot,elzoido/track-o-bot,elzoido/track-o-bot,bencart/track-o-bot
|
00908e6131682858413b45b1dd75d70e167e1465
|
src/physics/diff_physics.C
|
src/physics/diff_physics.C
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/diff_context.h"
#include "libmesh/diff_physics.h"
#include "libmesh/system.h"
namespace libMesh
{
DifferentiablePhysics::~DifferentiablePhysics()
{
DifferentiablePhysics::clear_physics();
}
void DifferentiablePhysics::clear_physics ()
{
_time_evolving.resize(0);
}
void DifferentiablePhysics::init_physics (const System& sys)
{
// give us flags for every variable that might be time evolving
_time_evolving.resize(sys.n_vars(), false);
}
bool DifferentiablePhysics::nonlocal_mass_residual(bool request_jacobian,
DiffContext &c)
{
FEMContext &context = libmesh_cast_ref<FEMContext&>(c);
for (unsigned int var = 0; var != context.n_vars(); ++var)
{
if (!this->is_time_evolving(var))
continue;
if (c.get_system().variable(var).type().family != SCALAR)
continue;
const std::vector<dof_id_type>& dof_indices =
context.get_dof_indices(var);
const std::size_t n_dofs = dof_indices.size();
DenseSubVector<Number> &Fs = context.get_elem_residual(var);
DenseSubMatrix<Number> &Kss = context.get_elem_jacobian( var, var );
for (std::size_t i=0; i != n_dofs; ++i)
{
Number s = c.get_system().current_solution(dof_indices[i]);
Fs(i) += s;
if (request_jacobian && context.elem_solution_derivative)
{
libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);
Kss(i,i) += 1;
}
}
}
return request_jacobian;
}
bool DifferentiablePhysics::_eulerian_time_deriv (bool request_jacobian,
DiffContext &context)
{
// For any problem we need time derivative terms
request_jacobian =
this->element_time_derivative(request_jacobian, context);
// For a moving mesh problem we may need the pseudoconvection term too
return this->eulerian_residual(request_jacobian, context) &&
request_jacobian;
}
} // namespace libMesh
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "libmesh/diff_context.h"
#include "libmesh/diff_physics.h"
#include "libmesh/system.h"
namespace libMesh
{
DifferentiablePhysics::~DifferentiablePhysics()
{
DifferentiablePhysics::clear_physics();
}
void DifferentiablePhysics::clear_physics ()
{
_time_evolving.resize(0);
}
void DifferentiablePhysics::init_physics (const System& sys)
{
// give us flags for every variable that might be time evolving
_time_evolving.resize(sys.n_vars(), false);
}
bool DifferentiablePhysics::nonlocal_mass_residual(bool request_jacobian,
DiffContext &c)
{
FEMContext &context = libmesh_cast_ref<FEMContext&>(c);
for (unsigned int var = 0; var != context.n_vars(); ++var)
{
if (!this->is_time_evolving(var))
continue;
if (c.get_system().variable(var).type().family != SCALAR)
continue;
const std::vector<dof_id_type>& dof_indices =
context.get_dof_indices(var);
const std::size_t n_dofs = dof_indices.size();
DenseSubVector<Number> &Fs = context.get_elem_residual(var);
DenseSubMatrix<Number> &Kss = context.get_elem_jacobian( var, var );
const libMesh::DenseSubVector<libMesh::Number> &Us =
context.get_elem_solution(var);
for (std::size_t i=0; i != n_dofs; ++i)
{
Fs(i) += Us(i);
if (request_jacobian && context.elem_solution_derivative)
{
libmesh_assert_equal_to (context.elem_solution_derivative, 1.0);
Kss(i,i) += 1;
}
}
}
return request_jacobian;
}
bool DifferentiablePhysics::_eulerian_time_deriv (bool request_jacobian,
DiffContext &context)
{
// For any problem we need time derivative terms
request_jacobian =
this->element_time_derivative(request_jacobian, context);
// For a moving mesh problem we may need the pseudoconvection term too
return this->eulerian_residual(request_jacobian, context) &&
request_jacobian;
}
} // namespace libMesh
|
Fix default nonlocal_mass_residual
|
Fix default nonlocal_mass_residual
TimeSolvers are going to use elem_solution to store time derivatives
so we can't just pull scalars directly from current_solution()
|
C++
|
lgpl-2.1
|
cahaynes/libmesh,coreymbryant/libmesh,dmcdougall/libmesh,capitalaslash/libmesh,salazardetroya/libmesh,jwpeterson/libmesh,Mbewu/libmesh,vikramvgarg/libmesh,dschwen/libmesh,Mbewu/libmesh,libMesh/libmesh,friedmud/libmesh,balborian/libmesh,coreymbryant/libmesh,hrittich/libmesh,giorgiobornia/libmesh,karpeev/libmesh,jiangwen84/libmesh,aeslaughter/libmesh,salazardetroya/libmesh,Mbewu/libmesh,balborian/libmesh,libMesh/libmesh,balborian/libmesh,balborian/libmesh,roystgnr/libmesh,salazardetroya/libmesh,roystgnr/libmesh,cahaynes/libmesh,90jrong/libmesh,coreymbryant/libmesh,coreymbryant/libmesh,permcody/libmesh,salazardetroya/libmesh,permcody/libmesh,pbauman/libmesh,permcody/libmesh,jiangwen84/libmesh,dschwen/libmesh,cahaynes/libmesh,roystgnr/libmesh,jiangwen84/libmesh,BalticPinguin/libmesh,karpeev/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,dknez/libmesh,90jrong/libmesh,hrittich/libmesh,hrittich/libmesh,pbauman/libmesh,libMesh/libmesh,svallaghe/libmesh,friedmud/libmesh,cahaynes/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,benkirk/libmesh,dschwen/libmesh,vikramvgarg/libmesh,jwpeterson/libmesh,friedmud/libmesh,vikramvgarg/libmesh,dschwen/libmesh,giorgiobornia/libmesh,hrittich/libmesh,karpeev/libmesh,hrittich/libmesh,friedmud/libmesh,pbauman/libmesh,dschwen/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,dknez/libmesh,hrittich/libmesh,hrittich/libmesh,aeslaughter/libmesh,svallaghe/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,dknez/libmesh,pbauman/libmesh,Mbewu/libmesh,jiangwen84/libmesh,cahaynes/libmesh,90jrong/libmesh,90jrong/libmesh,cahaynes/libmesh,90jrong/libmesh,friedmud/libmesh,BalticPinguin/libmesh,dknez/libmesh,90jrong/libmesh,balborian/libmesh,karpeev/libmesh,permcody/libmesh,benkirk/libmesh,benkirk/libmesh,roystgnr/libmesh,karpeev/libmesh,giorgiobornia/libmesh,benkirk/libmesh,libMesh/libmesh,aeslaughter/libmesh,capitalaslash/libmesh,salazardetroya/libmesh,permcody/libmesh,Mbewu/libmesh,karpeev/libmesh,dschwen/libmesh,capitalaslash/libmesh,Mbewu/libmesh,benkirk/libmesh,Mbewu/libmesh,karpeev/libmesh,friedmud/libmesh,balborian/libmesh,dschwen/libmesh,dmcdougall/libmesh,benkirk/libmesh,vikramvgarg/libmesh,svallaghe/libmesh,salazardetroya/libmesh,aeslaughter/libmesh,90jrong/libmesh,jiangwen84/libmesh,svallaghe/libmesh,jwpeterson/libmesh,vikramvgarg/libmesh,jiangwen84/libmesh,salazardetroya/libmesh,BalticPinguin/libmesh,svallaghe/libmesh,capitalaslash/libmesh,capitalaslash/libmesh,permcody/libmesh,balborian/libmesh,vikramvgarg/libmesh,friedmud/libmesh,aeslaughter/libmesh,capitalaslash/libmesh,benkirk/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,coreymbryant/libmesh,roystgnr/libmesh,dschwen/libmesh,dmcdougall/libmesh,salazardetroya/libmesh,dmcdougall/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,libMesh/libmesh,roystgnr/libmesh,dknez/libmesh,jwpeterson/libmesh,pbauman/libmesh,pbauman/libmesh,libMesh/libmesh,dknez/libmesh,svallaghe/libmesh,aeslaughter/libmesh,balborian/libmesh,libMesh/libmesh,Mbewu/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,pbauman/libmesh,giorgiobornia/libmesh,dknez/libmesh,benkirk/libmesh,permcody/libmesh,cahaynes/libmesh,dmcdougall/libmesh,90jrong/libmesh,dknez/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,dmcdougall/libmesh,dmcdougall/libmesh,balborian/libmesh,balborian/libmesh,libMesh/libmesh,roystgnr/libmesh,hrittich/libmesh,capitalaslash/libmesh,jiangwen84/libmesh,cahaynes/libmesh,jiangwen84/libmesh,hrittich/libmesh,svallaghe/libmesh,benkirk/libmesh,coreymbryant/libmesh,BalticPinguin/libmesh,dmcdougall/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,karpeev/libmesh,friedmud/libmesh,friedmud/libmesh,permcody/libmesh,90jrong/libmesh,Mbewu/libmesh,jwpeterson/libmesh,pbauman/libmesh,pbauman/libmesh,giorgiobornia/libmesh
|
9f3cf19c2d11fe139a8fd9e65264c54b4116e1d2
|
src/platform/qt/Window.cpp
|
src/platform/qt/Window.cpp
|
#include "Window.h"
#include <QFileDialog>
#include <QKeyEvent>
#include <QKeySequence>
#include <QMenuBar>
#include "GDBWindow.h"
#include "GDBController.h"
using namespace QGBA;
Window::Window(QWidget* parent)
: QMainWindow(parent)
#ifdef USE_GDB_STUB
, m_gdbController(nullptr)
#endif
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMinimumSize(240, 160);
m_controller = new GameController(this);
m_display = new Display();
setCentralWidget(m_display);
connect(m_controller, SIGNAL(audioDeviceAvailable(GBAAudio*)), this, SLOT(setupAudio(GBAAudio*)));
connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
connect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);
connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
setupMenu(menuBar());
}
GBAKey Window::mapKey(int qtKey) {
switch (qtKey) {
case Qt::Key_Z:
return GBA_KEY_A;
break;
case Qt::Key_X:
return GBA_KEY_B;
break;
case Qt::Key_A:
return GBA_KEY_L;
break;
case Qt::Key_S:
return GBA_KEY_R;
break;
case Qt::Key_Return:
return GBA_KEY_START;
break;
case Qt::Key_Backspace:
return GBA_KEY_SELECT;
break;
case Qt::Key_Up:
return GBA_KEY_UP;
break;
case Qt::Key_Down:
return GBA_KEY_DOWN;
break;
case Qt::Key_Left:
return GBA_KEY_LEFT;
break;
case Qt::Key_Right:
return GBA_KEY_RIGHT;
break;
default:
return GBA_KEY_NONE;
}
}
void Window::selectROM() {
QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"));
if (!filename.isEmpty()) {
m_controller->loadGame(filename);
}
}
#ifdef USE_GDB_STUB
void Window::gdbOpen() {
if (!m_gdbController) {
m_gdbController = new GDBController(m_controller, this);
}
GDBWindow* window = new GDBWindow(m_gdbController);
window->show();
}
#endif
void Window::keyPressEvent(QKeyEvent* event) {
if (event->isAutoRepeat()) {
QWidget::keyPressEvent(event);
return;
}
GBAKey key = mapKey(event->key());
if (key == GBA_KEY_NONE) {
QWidget::keyPressEvent(event);
return;
}
m_controller->keyPressed(key);
event->accept();
}
void Window::keyReleaseEvent(QKeyEvent* event) {
if (event->isAutoRepeat()) {
QWidget::keyReleaseEvent(event);
return;
}
GBAKey key = mapKey(event->key());
if (key == GBA_KEY_NONE) {
QWidget::keyPressEvent(event);
return;
}
m_controller->keyReleased(key);
event->accept();
}
void Window::closeEvent(QCloseEvent* event) {
emit shutdown();
QMainWindow::closeEvent(event);
}
void Window::gameStarted(GBAThread* context) {
emit startDrawing(m_controller->drawContext(), context);
foreach (QAction* action, m_gameActions) {
action->setDisabled(false);
}
}
void Window::setupAudio(GBAAudio* audio) {
AudioThread* thread = new AudioThread(this);
thread->setInput(audio);
thread->start(QThread::HighPriority);
connect(this, SIGNAL(shutdown()), thread, SLOT(shutdown()));
}
void Window::setupMenu(QMenuBar* menubar) {
menubar->clear();
QMenu* fileMenu = menubar->addMenu(tr("&File"));
fileMenu->addAction(tr("Load &ROM"), this, SLOT(selectROM()), QKeySequence::Open);
QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
QAction* pause = new QAction(tr("&Pause"), 0);
pause->setChecked(false);
pause->setCheckable(true);
pause->setShortcut(tr("Ctrl+P"));
pause->setDisabled(true);
connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
m_gameActions.append(pause);
emulationMenu->addAction(pause);
QAction* frameAdvance = new QAction(tr("&Next frame"), 0);
frameAdvance->setShortcut(tr("Ctrl+N"));
frameAdvance->setDisabled(true);
connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
m_gameActions.append(frameAdvance);
emulationMenu->addAction(frameAdvance);
QMenu* debuggingMenu = menubar->addMenu(tr("&Debugging"));
#ifdef USE_GDB_STUB
QAction* gdbWindow = new QAction(tr("Start &GDB server"), nullptr);
connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
debuggingMenu->addAction(gdbWindow);
#endif
}
|
#include "Window.h"
#include <QFileDialog>
#include <QKeyEvent>
#include <QKeySequence>
#include <QMenuBar>
#include "GDBWindow.h"
#include "GDBController.h"
using namespace QGBA;
Window::Window(QWidget* parent)
: QMainWindow(parent)
#ifdef USE_GDB_STUB
, m_gdbController(nullptr)
#endif
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMinimumSize(240, 160);
m_controller = new GameController(this);
m_display = new Display();
setCentralWidget(m_display);
connect(m_controller, SIGNAL(audioDeviceAvailable(GBAAudio*)), this, SLOT(setupAudio(GBAAudio*)));
connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
connect(this, SIGNAL(startDrawing(const uint32_t*, GBAThread*)), m_display, SLOT(startDrawing(const uint32_t*, GBAThread*)), Qt::QueuedConnection);
connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
setupMenu(menuBar());
}
GBAKey Window::mapKey(int qtKey) {
switch (qtKey) {
case Qt::Key_Z:
return GBA_KEY_A;
break;
case Qt::Key_X:
return GBA_KEY_B;
break;
case Qt::Key_A:
return GBA_KEY_L;
break;
case Qt::Key_S:
return GBA_KEY_R;
break;
case Qt::Key_Return:
return GBA_KEY_START;
break;
case Qt::Key_Backspace:
return GBA_KEY_SELECT;
break;
case Qt::Key_Up:
return GBA_KEY_UP;
break;
case Qt::Key_Down:
return GBA_KEY_DOWN;
break;
case Qt::Key_Left:
return GBA_KEY_LEFT;
break;
case Qt::Key_Right:
return GBA_KEY_RIGHT;
break;
default:
return GBA_KEY_NONE;
}
}
void Window::selectROM() {
QString filename = QFileDialog::getOpenFileName(this, tr("Select ROM"));
if (!filename.isEmpty()) {
m_controller->loadGame(filename);
}
}
#ifdef USE_GDB_STUB
void Window::gdbOpen() {
if (!m_gdbController) {
m_gdbController = new GDBController(m_controller, this);
}
GDBWindow* window = new GDBWindow(m_gdbController);
window->show();
}
#endif
void Window::keyPressEvent(QKeyEvent* event) {
if (event->isAutoRepeat()) {
QWidget::keyPressEvent(event);
return;
}
GBAKey key = mapKey(event->key());
if (key == GBA_KEY_NONE) {
QWidget::keyPressEvent(event);
return;
}
m_controller->keyPressed(key);
event->accept();
}
void Window::keyReleaseEvent(QKeyEvent* event) {
if (event->isAutoRepeat()) {
QWidget::keyReleaseEvent(event);
return;
}
GBAKey key = mapKey(event->key());
if (key == GBA_KEY_NONE) {
QWidget::keyPressEvent(event);
return;
}
m_controller->keyReleased(key);
event->accept();
}
void Window::closeEvent(QCloseEvent* event) {
emit shutdown();
QMainWindow::closeEvent(event);
}
void Window::gameStarted(GBAThread* context) {
emit startDrawing(m_controller->drawContext(), context);
foreach (QAction* action, m_gameActions) {
action->setDisabled(false);
}
}
void Window::setupAudio(GBAAudio* audio) {
AudioThread* thread = new AudioThread(this);
thread->setInput(audio);
thread->start(QThread::HighPriority);
connect(this, SIGNAL(shutdown()), thread, SLOT(shutdown()));
}
void Window::setupMenu(QMenuBar* menubar) {
menubar->clear();
QMenu* fileMenu = menubar->addMenu(tr("&File"));
fileMenu->addAction(tr("Load &ROM..."), this, SLOT(selectROM()), QKeySequence::Open);
QMenu* emulationMenu = menubar->addMenu(tr("&Emulation"));
QAction* pause = new QAction(tr("&Pause"), 0);
pause->setChecked(false);
pause->setCheckable(true);
pause->setShortcut(tr("Ctrl+P"));
pause->setDisabled(true);
connect(pause, SIGNAL(triggered(bool)), m_controller, SLOT(setPaused(bool)));
m_gameActions.append(pause);
emulationMenu->addAction(pause);
QAction* frameAdvance = new QAction(tr("&Next frame"), 0);
frameAdvance->setShortcut(tr("Ctrl+N"));
frameAdvance->setDisabled(true);
connect(frameAdvance, SIGNAL(triggered()), m_controller, SLOT(frameAdvance()));
m_gameActions.append(frameAdvance);
emulationMenu->addAction(frameAdvance);
QMenu* debuggingMenu = menubar->addMenu(tr("&Debugging"));
#ifdef USE_GDB_STUB
QAction* gdbWindow = new QAction(tr("Start &GDB server..."), nullptr);
connect(gdbWindow, SIGNAL(triggered()), this, SLOT(gdbOpen()));
debuggingMenu->addAction(gdbWindow);
#endif
}
|
Add missing ellipses for menu items that open windows
|
Add missing ellipses for menu items that open windows
|
C++
|
mpl-2.0
|
jeremyherbert/mgba,Touched/mgba,MerryMage/mgba,matthewbauer/mgba,zerofalcon/mgba,libretro/mgba,Anty-Lemon/mgba,askotx/mgba,jeremyherbert/mgba,libretro/mgba,sergiobenrocha2/mgba,Iniquitatis/mgba,Anty-Lemon/mgba,jeremyherbert/mgba,bentley/mgba,iracigt/mgba,sergiobenrocha2/mgba,iracigt/mgba,cassos/mgba,fr500/mgba,Anty-Lemon/mgba,askotx/mgba,iracigt/mgba,mgba-emu/mgba,zerofalcon/mgba,cassos/mgba,libretro/mgba,libretro/mgba,nattthebear/mgba,Iniquitatis/mgba,cassos/mgba,Touched/mgba,MerryMage/mgba,bentley/mgba,zerofalcon/mgba,sergiobenrocha2/mgba,sergiobenrocha2/mgba,mgba-emu/mgba,matthewbauer/mgba,fr500/mgba,askotx/mgba,AdmiralCurtiss/mgba,sergiobenrocha2/mgba,fr500/mgba,MerryMage/mgba,Anty-Lemon/mgba,libretro/mgba,iracigt/mgba,AdmiralCurtiss/mgba,Iniquitatis/mgba,nattthebear/mgba,mgba-emu/mgba,askotx/mgba,mgba-emu/mgba,fr500/mgba,AdmiralCurtiss/mgba,Touched/mgba,Iniquitatis/mgba,jeremyherbert/mgba
|
4864324f4dd9b08a4255c68f22fe3b9bfa5f3049
|
src/player/VideoWriter.cpp
|
src/player/VideoWriter.cpp
|
//
// 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 "VideoWriter.h"
#include "OffscreenCanvas.h"
#include "Player.h"
#include "SDLDisplayEngine.h"
#include "../graphics/FBO.h"
#include "../graphics/GPURGB2YUVFilter.h"
#include "../graphics/Filterfill.h"
#include "../base/StringHelper.h"
#include <boost/bind.hpp>
#include <fcntl.h>
#include <stdio.h>
using namespace std;
using namespace boost;
namespace avg {
VideoWriter::VideoWriter(CanvasPtr pCanvas, const string& sOutFileName, int frameRate,
int qMin, int qMax, bool bSyncToPlayback)
: m_pCanvas(pCanvas),
m_sOutFileName(sOutFileName),
m_FrameRate(frameRate),
m_QMin(qMin),
m_QMax(qMax),
m_bHasValidData(false),
m_bSyncToPlayback(bSyncToPlayback),
m_bPaused(false),
m_PauseTime(0),
m_bStopped(false),
m_CurFrame(0),
m_StartTime(-1),
m_bFramePending(false)
{
m_FrameSize = m_pCanvas->getSize();
#ifdef WIN32
int fd = _open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
#else
int fd = open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, S_IRWXU);
#endif
if (fd == -1) {
throw Exception(AVG_ERR_VIDEO_INIT_FAILED,
string("Could not open output file '") + m_sOutFileName + "'. Reason: " +
strerror(errno));
}
#ifdef WIN32
_close(fd);
#else
close(fd);
#endif
remove(m_sOutFileName.c_str());
CanvasPtr pMainCanvas = Player::get()->getMainCanvas();
if (pMainCanvas != m_pCanvas) {
m_pFBO = dynamic_pointer_cast<OffscreenCanvas>(m_pCanvas)->getFBO();
if (GLContext::getCurrent()->isUsingShaders()) {
m_pFilter = GPURGB2YUVFilterPtr(new GPURGB2YUVFilter(m_FrameSize));
}
}
VideoWriterThread writer(m_CmdQueue, m_sOutFileName, m_FrameSize, m_FrameRate,
qMin, qMax);
m_pThread = new boost::thread(writer);
m_pCanvas->registerPlaybackEndListener(this);
m_pCanvas->registerFrameEndListener(this);
}
VideoWriter::~VideoWriter()
{
stop();
m_pThread->join();
delete m_pThread;
}
void VideoWriter::stop()
{
if (!m_bStopped) {
getFrameFromPBO();
if (!m_bHasValidData) {
writeDummyFrame();
}
m_bStopped = true;
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::stop, _1));
m_pCanvas->unregisterFrameEndListener(this);
m_pCanvas->unregisterPlaybackEndListener(this);
}
}
void VideoWriter::pause()
{
if (m_bPaused) {
throw Exception(AVG_ERR_UNSUPPORTED, "VideoWriter::pause() called when paused.");
}
if (m_bStopped) {
throw Exception(AVG_ERR_UNSUPPORTED, "VideoWriter::pause() called when stopped.");
}
m_bPaused = true;
m_PauseStartTime = Player::get()->getFrameTime();
}
void VideoWriter::play()
{
if (!m_bPaused) {
throw Exception(AVG_ERR_UNSUPPORTED,
"VideoWriter::play() called when not paused.");
}
m_bPaused = false;
m_PauseTime += (Player::get()->getFrameTime() - m_PauseStartTime);
}
std::string VideoWriter::getFileName() const
{
return m_sOutFileName;
}
int VideoWriter::getFramerate() const
{
return m_FrameRate;
}
int VideoWriter::getQMin() const
{
return m_QMin;
}
int VideoWriter::getQMax() const
{
return m_QMax;
}
void VideoWriter::onFrameEnd()
{
// The VideoWriter handles OffscreenCanvas and MainCanvas differently:
// For MainCanvas, it simply does a screenshot onFrameEnd and sends that to the
// VideoWriterThread immediately.
// For OffscreenCanvas, an asynchronous PBO readback is started in onFrameEnd.
// In the next frame's onFrameEnd, the data is read into a bitmap and sent to
// the VideoWriterThread.
if (m_pFBO) {
// Read last frame's bitmap.
getFrameFromPBO();
}
if (m_StartTime == -1) {
m_StartTime = Player::get()->getFrameTime();
}
if (!m_bPaused) {
if (m_bSyncToPlayback) {
getFrameFromFBO();
} else {
long long movieTime = Player::get()->getFrameTime() - m_StartTime
- m_PauseTime;
double timePerFrame = 1000./m_FrameRate;
int wantedFrame = int(movieTime/timePerFrame+0.1);
if (wantedFrame > m_CurFrame) {
getFrameFromFBO();
if (wantedFrame > m_CurFrame + 1) {
m_CurFrame = wantedFrame - 1;
}
}
}
}
if (!m_pFBO) {
getFrameFromPBO();
}
}
void VideoWriter::getFrameFromFBO()
{
if (m_pFBO) {
if (m_pFilter) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
m_pFilter->apply(m_pFBO->getTex());
FBOPtr pYUVFBO = m_pFilter->getFBO();
pYUVFBO->moveToPBO();
glPopMatrix();
} else {
m_pFBO->moveToPBO();
}
m_bFramePending = true;
} else {
BitmapPtr pBmp = Player::get()->getDisplayEngine()->screenshot(GL_BACK);
sendFrameToEncoder(pBmp);
}
}
void VideoWriter::getFrameFromPBO()
{
if (m_bFramePending) {
BitmapPtr pBmp;
if (m_pFilter) {
pBmp = m_pFilter->getFBO()->getImageFromPBO();
} else {
pBmp = m_pFBO->getImageFromPBO();
}
sendFrameToEncoder(pBmp);
m_bFramePending = false;
}
}
void VideoWriter::sendFrameToEncoder(BitmapPtr pBitmap)
{
m_CurFrame++;
m_bHasValidData = true;
if (m_pFilter) {
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeYUVFrame, _1, pBitmap));
} else {
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeFrame, _1, pBitmap));
}
}
void VideoWriter::onPlaybackEnd()
{
stop();
}
void VideoWriter::writeDummyFrame()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(m_FrameSize, B8G8R8X8));
FilterFill<Pixel32>(Pixel32(0,0,0,255)).applyInPlace(pBmp);
sendFrameToEncoder(pBmp);
}
}
|
//
// 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 "VideoWriter.h"
#include "OffscreenCanvas.h"
#include "Player.h"
#include "SDLDisplayEngine.h"
#include "../graphics/FBO.h"
#include "../graphics/GPURGB2YUVFilter.h"
#include "../graphics/Filterfill.h"
#include "../base/StringHelper.h"
#include <boost/bind.hpp>
#include <fcntl.h>
#include <stdio.h>
using namespace std;
using namespace boost;
namespace avg {
VideoWriter::VideoWriter(CanvasPtr pCanvas, const string& sOutFileName, int frameRate,
int qMin, int qMax, bool bSyncToPlayback)
: m_pCanvas(pCanvas),
m_sOutFileName(sOutFileName),
m_FrameRate(frameRate),
m_QMin(qMin),
m_QMax(qMax),
m_bHasValidData(false),
m_bSyncToPlayback(bSyncToPlayback),
m_bPaused(false),
m_PauseTime(0),
m_bStopped(false),
m_CurFrame(0),
m_StartTime(-1),
m_bFramePending(false)
{
m_FrameSize = m_pCanvas->getSize();
#ifdef WIN32
int fd = _open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
#elif defined linux
int fd = open64(m_sOutFileName.c_str(), O_RDWR | O_CREAT, S_IRWXU);
#else
int fd = open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, S_IRWXU);
#endif
if (fd == -1) {
throw Exception(AVG_ERR_VIDEO_INIT_FAILED,
string("Could not open output file '") + m_sOutFileName + "'. Reason: " +
strerror(errno));
}
#ifdef WIN32
_close(fd);
#else
close(fd);
#endif
remove(m_sOutFileName.c_str());
CanvasPtr pMainCanvas = Player::get()->getMainCanvas();
if (pMainCanvas != m_pCanvas) {
m_pFBO = dynamic_pointer_cast<OffscreenCanvas>(m_pCanvas)->getFBO();
if (GLContext::getCurrent()->isUsingShaders()) {
m_pFilter = GPURGB2YUVFilterPtr(new GPURGB2YUVFilter(m_FrameSize));
}
}
VideoWriterThread writer(m_CmdQueue, m_sOutFileName, m_FrameSize, m_FrameRate,
qMin, qMax);
m_pThread = new boost::thread(writer);
m_pCanvas->registerPlaybackEndListener(this);
m_pCanvas->registerFrameEndListener(this);
}
VideoWriter::~VideoWriter()
{
stop();
m_pThread->join();
delete m_pThread;
}
void VideoWriter::stop()
{
if (!m_bStopped) {
getFrameFromPBO();
if (!m_bHasValidData) {
writeDummyFrame();
}
m_bStopped = true;
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::stop, _1));
m_pCanvas->unregisterFrameEndListener(this);
m_pCanvas->unregisterPlaybackEndListener(this);
}
}
void VideoWriter::pause()
{
if (m_bPaused) {
throw Exception(AVG_ERR_UNSUPPORTED, "VideoWriter::pause() called when paused.");
}
if (m_bStopped) {
throw Exception(AVG_ERR_UNSUPPORTED, "VideoWriter::pause() called when stopped.");
}
m_bPaused = true;
m_PauseStartTime = Player::get()->getFrameTime();
}
void VideoWriter::play()
{
if (!m_bPaused) {
throw Exception(AVG_ERR_UNSUPPORTED,
"VideoWriter::play() called when not paused.");
}
m_bPaused = false;
m_PauseTime += (Player::get()->getFrameTime() - m_PauseStartTime);
}
std::string VideoWriter::getFileName() const
{
return m_sOutFileName;
}
int VideoWriter::getFramerate() const
{
return m_FrameRate;
}
int VideoWriter::getQMin() const
{
return m_QMin;
}
int VideoWriter::getQMax() const
{
return m_QMax;
}
void VideoWriter::onFrameEnd()
{
// The VideoWriter handles OffscreenCanvas and MainCanvas differently:
// For MainCanvas, it simply does a screenshot onFrameEnd and sends that to the
// VideoWriterThread immediately.
// For OffscreenCanvas, an asynchronous PBO readback is started in onFrameEnd.
// In the next frame's onFrameEnd, the data is read into a bitmap and sent to
// the VideoWriterThread.
if (m_pFBO) {
// Read last frame's bitmap.
getFrameFromPBO();
}
if (m_StartTime == -1) {
m_StartTime = Player::get()->getFrameTime();
}
if (!m_bPaused) {
if (m_bSyncToPlayback) {
getFrameFromFBO();
} else {
long long movieTime = Player::get()->getFrameTime() - m_StartTime
- m_PauseTime;
double timePerFrame = 1000./m_FrameRate;
int wantedFrame = int(movieTime/timePerFrame+0.1);
if (wantedFrame > m_CurFrame) {
getFrameFromFBO();
if (wantedFrame > m_CurFrame + 1) {
m_CurFrame = wantedFrame - 1;
}
}
}
}
if (!m_pFBO) {
getFrameFromPBO();
}
}
void VideoWriter::getFrameFromFBO()
{
if (m_pFBO) {
if (m_pFilter) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
m_pFilter->apply(m_pFBO->getTex());
FBOPtr pYUVFBO = m_pFilter->getFBO();
pYUVFBO->moveToPBO();
glPopMatrix();
} else {
m_pFBO->moveToPBO();
}
m_bFramePending = true;
} else {
BitmapPtr pBmp = Player::get()->getDisplayEngine()->screenshot(GL_BACK);
sendFrameToEncoder(pBmp);
}
}
void VideoWriter::getFrameFromPBO()
{
if (m_bFramePending) {
BitmapPtr pBmp;
if (m_pFilter) {
pBmp = m_pFilter->getFBO()->getImageFromPBO();
} else {
pBmp = m_pFBO->getImageFromPBO();
}
sendFrameToEncoder(pBmp);
m_bFramePending = false;
}
}
void VideoWriter::sendFrameToEncoder(BitmapPtr pBitmap)
{
m_CurFrame++;
m_bHasValidData = true;
if (m_pFilter) {
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeYUVFrame, _1, pBitmap));
} else {
m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeFrame, _1, pBitmap));
}
}
void VideoWriter::onPlaybackEnd()
{
stop();
}
void VideoWriter::writeDummyFrame()
{
BitmapPtr pBmp = BitmapPtr(new Bitmap(m_FrameSize, B8G8R8X8));
FilterFill<Pixel32>(Pixel32(0,0,0,255)).applyInPlace(pBmp);
sendFrameToEncoder(pBmp);
}
}
|
use open64() instead of open() on linux systems (fixes #279)
|
VideoWriter: use open64() instead of open() on linux systems (fixes #279)
svn path=/trunk/libavg/; revision=6905
|
C++
|
lgpl-2.1
|
hoodie/libavg,scotty007/libavg,th3infinity/libavg,scotty007/libavg,yyd01245/libavg,libavg/libavg,hoodie/libavg,th3infinity/libavg,yyd01245/libavg,hoodie/libavg,yyd01245/libavg,libavg/libavg,yyd01245/libavg,th3infinity/libavg,scotty007/libavg,scotty007/libavg,th3infinity/libavg,libavg/libavg,libavg/libavg,hoodie/libavg
|
126f1e92d9720436c2857397199f01c100993460
|
src/propertycalculator.cpp
|
src/propertycalculator.cpp
|
/***************************************************************************
* Copyright © 2003 Unai Garro <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "propertycalculator.h"
#include <cmath> // For fabs()
#include <kdebug.h>
#include "backends/recipedb.h"
#include "datablocks/elementlist.h"
#include "datablocks/ingredientpropertylist.h"
#include "datablocks/recipe.h"
bool autoConvert( RecipeDB* database, const Ingredient &from, const Ingredient &to, Ingredient &result )
{
RecipeDB::ConversionStatus status = database->convertIngredientUnits( from, to.units, result );
bool converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted ) // There is a ratio
{
double ratio = result.amount / from.amount;
if ( ratio > 1 ) // Convert to unit 1, since unit1 is bigger
{
result.units = from.units;
result.amount = from.amount + to.amount / ratio;
}
else { //Convert to unit2, since unit2 is bigger (just add, units are now correct)
result.amount += to.amount;
}
return true;
}
else
return false;
}
/*
** Version with database I/O. DB must be provided
*/
void calculateProperties( Recipe& recipe, RecipeDB* database )
{
recipe.properties.clear();
// Note that recipePropertyList is not attached to any ingredient. It's just the total of the recipe
IngredientPropertyList ingredientPropertyList; // property list for each ingredient
int ingredientNo = 1;
for ( IngredientList::const_iterator ing_it = recipe.ingList.begin(); ing_it != recipe.ingList.end(); ++ing_it ) {
database->loadProperties( &ingredientPropertyList, ( *ing_it ).ingredientID );
ingredientPropertyList.divide( recipe.yield.amount ); // calculates properties per yield unit
addPropertyToList( database, &recipe.properties, ingredientPropertyList, *ing_it, ingredientNo );
ingredientNo++;
}
}
void addPropertyToList( RecipeDB *database, IngredientPropertyList *recipePropertyList, IngredientPropertyList &ingPropertyList, const Ingredient &ing, int /*ingredientNo*/ )
{
QMap<int,double> ratioCache; //unit->ratio
IngredientPropertyList::const_iterator prop_it;
for ( prop_it = ingPropertyList.begin(); prop_it != ingPropertyList.end(); ++prop_it ) {
// Find if property was listed before
int pos = recipePropertyList->findIndex( *prop_it );
if ( pos >= 0 ) //Exists. Add to it
{
Ingredient result;
bool converted;
QMap<int,double>::const_iterator cache_it = ratioCache.constFind((*prop_it).perUnit.id);
if ( cache_it == ratioCache.constEnd() ) {
RecipeDB::ConversionStatus status = database->convertIngredientUnits( ing, (*prop_it).perUnit, result );
converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted )
ratioCache.insert((*prop_it).perUnit.id,result.amount / ing.amount);
else
ratioCache.insert((*prop_it).perUnit.id,-1);
}
else {
result.units = (*prop_it).perUnit;
result.amount = ing.amount * (*cache_it);
converted = result.amount > 0;
}
if ( converted ) // Could convert units to perUnit
(*recipePropertyList)[pos].amount += ( (*prop_it).amount ) * result.amount;
}
else // Append new property
{
IngredientProperty property;
property.id = (*prop_it).id;
property.name = (*prop_it).name;
property.perUnit.id = -1; // It's not per unit, it's total sum of the recipe
property.perUnit.name = QString::null; // "
property.units = (*prop_it).units;
Ingredient result;
bool converted;
QMap<int,double>::const_iterator cache_it = ratioCache.constFind((*prop_it).perUnit.id);
if ( cache_it == ratioCache.constEnd() ) {
RecipeDB::ConversionStatus status = database->convertIngredientUnits( ing, (*prop_it).perUnit, result );
converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted )
ratioCache.insert((*prop_it).perUnit.id,result.amount / ing.amount);
else
ratioCache.insert((*prop_it).perUnit.id,-1);
}
else {
result.units = (*prop_it).perUnit;
result.amount = ing.amount * (*cache_it);
converted = result.amount > 0;
}
if ( converted ) // Could convert units to perUnit
{
property.amount = ( (*prop_it).amount ) * result.amount;
recipePropertyList->append( property );
}
}
}
}
|
/***************************************************************************
* Copyright © 2003 Unai Garro <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "propertycalculator.h"
#include <cmath> // For fabs()
#include <kdebug.h>
#include "backends/recipedb.h"
#include "datablocks/elementlist.h"
#include "datablocks/ingredientpropertylist.h"
#include "datablocks/recipe.h"
bool autoConvert( RecipeDB* database, const Ingredient &from, const Ingredient &to, Ingredient &result )
{
RecipeDB::ConversionStatus status = database->convertIngredientUnits( from, to.units, result );
bool converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted ) // There is a ratio
{
double ratio = result.amount / from.amount;
if ( ratio > 1 ) // Convert to unit 1, since unit1 is bigger
{
result.units = from.units;
result.amount = from.amount + to.amount / ratio;
}
else { //Convert to unit2, since unit2 is bigger (just add, units are now correct)
result.amount += to.amount;
}
return true;
}
else
return false;
}
/*
** Version with database I/O. DB must be provided
*/
void calculateProperties( Recipe& recipe, RecipeDB* database )
{
recipe.properties.clear();
// Note that recipePropertyList is not attached to any ingredient. It's just the total of the recipe
IngredientPropertyList ingredientPropertyList; // property list for each ingredient
int ingredientNo = 1;
for ( IngredientList::const_iterator ing_it = recipe.ingList.begin(); ing_it != recipe.ingList.end(); ++ing_it ) {
database->loadProperties( &ingredientPropertyList, ( *ing_it ).ingredientID );
ingredientPropertyList.divide( recipe.yield.amount ); // calculates properties per yield unit
addPropertyToList( database, &recipe.properties, ingredientPropertyList, *ing_it, ingredientNo );
ingredientNo++;
}
}
void addPropertyToList( RecipeDB *database, IngredientPropertyList *recipePropertyList, IngredientPropertyList &ingPropertyList, const Ingredient &ing, int /*ingredientNo*/ )
{
QMap<int,double> ratioCache; //unit->ratio
IngredientPropertyList::const_iterator prop_it;
for ( prop_it = ingPropertyList.begin(); prop_it != ingPropertyList.end(); ++prop_it ) {
// Find if property was listed before
int pos = recipePropertyList->findIndex( *prop_it );
if ( pos >= 0 ) //Exists. Add to it
{
Ingredient result;
bool converted;
QMap<int,double>::const_iterator cache_it = ratioCache.constFind((*prop_it).perUnit.id);
if ( cache_it == ratioCache.constEnd() ) {
RecipeDB::ConversionStatus status = database->convertIngredientUnits( ing, (*prop_it).perUnit, result );
converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted )
ratioCache.insert((*prop_it).perUnit.id,result.amount / ing.amount);
else
ratioCache.insert((*prop_it).perUnit.id,-1);
}
else {
result.units = (*prop_it).perUnit;
result.amount = ing.amount * (*cache_it);
converted = result.amount > 0;
}
if ( converted ) // Could convert units to perUnit
(*recipePropertyList)[pos].amount += ( (*prop_it).amount ) * result.amount;
}
else // Append new property
{
IngredientProperty property;
property.id = (*prop_it).id;
property.name = (*prop_it).name;
property.perUnit.id = -1; // It's not per unit, it's total sum of the recipe
property.perUnit.name.clear(); // "
property.units = (*prop_it).units;
Ingredient result;
bool converted;
QMap<int,double>::const_iterator cache_it = ratioCache.constFind((*prop_it).perUnit.id);
if ( cache_it == ratioCache.constEnd() ) {
RecipeDB::ConversionStatus status = database->convertIngredientUnits( ing, (*prop_it).perUnit, result );
converted = status == RecipeDB::Success || status == RecipeDB::MismatchedPrepMethodUsingApprox;
if ( converted )
ratioCache.insert((*prop_it).perUnit.id,result.amount / ing.amount);
else
ratioCache.insert((*prop_it).perUnit.id,-1);
}
else {
result.units = (*prop_it).perUnit;
result.amount = ing.amount * (*cache_it);
converted = result.amount > 0;
}
if ( converted ) // Could convert units to perUnit
{
property.amount = ( (*prop_it).amount ) * result.amount;
recipePropertyList->append( property );
}
}
}
}
|
Fix Krazy warnings: nullstrassign - src/propertycalculator.cpp
|
Fix Krazy warnings: nullstrassign - src/propertycalculator.cpp
svn path=/trunk/extragear/utils/krecipes/; revision=1119800
|
C++
|
lgpl-2.1
|
eliovir/krecipes,eliovir/krecipes,eliovir/krecipes,eliovir/krecipes
|
e0af1b3ed6a799664d26d5b3e41b75305d681dc8
|
src/qt/addressbookpage.cpp
|
src/qt/addressbookpage.cpp
|
#include "addressbookpage.h"
#include "ui_addressbookpage.h"
#include "addresstablemodel.h"
#include "optionsmodel.h"
#include "bitcoingui.h"
#include "editaddressdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"
#ifdef USE_QRCODE
#include "qrcodedialog.h"
#endif
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
optionsModel(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddressButton->setIcon(QIcon());
ui->copyToClipboard->setIcon(QIcon());
ui->deleteButton->setIcon(QIcon());
#endif
#ifndef USE_QRCODE
ui->showQRCode->setVisible(false);
#endif
switch(mode)
{
case ForSending:
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
break;
case ForEditing:
ui->buttonBox->setVisible(false);
break;
}
switch(tab)
{
case SendingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
ui->signMessage->setVisible(false);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you."));
ui->deleteAddress->setVisible(false);
ui->signMessage->setVisible(true);
break;
}
// Context menu actions
QAction *copyAddressAction = new QAction(ui->copyAddress->text(), this);
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *editAction = new QAction(tr("&Edit"), this);
QAction *sendCoinsAction = new QAction(tr("Send &Coins"), this);
QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this);
QAction *signMessageAction = new QAction(ui->signMessage->text(), this);
QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if(tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
if(tab == SendingTab)
contextMenu->addAction(sendCoinsAction);
#ifdef USE_QRCODE
contextMenu->addAction(showQRCodeAction);
#endif
if(tab == ReceivingTab)
contextMenu->addAction(signMessageAction);
else if(tab == SendingTab)
contextMenu->addAction(verifyMessageAction);
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(onSendCoinsAction()));
connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
// Pass through accept action from button box
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
switch(tab)
{
case ReceivingTab:
// Receive filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Receive);
break;
case SendingTab:
// Send filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
break;
}
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void AddressBookPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_signMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit signMessage(address);
}
}
void AddressBookPage::on_verifyMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit verifyMessage(address);
}
}
void AddressBookPage::onSendCoinsAction()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit sendCoins(address);
}
}
void AddressBookPage::on_newAddress_clicked()
{
if(!model)
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
switch(tab)
{
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
ui->signMessage->setEnabled(false);
ui->signMessage->setVisible(false);
ui->verifyMessage->setEnabled(true);
ui->verifyMessage->setVisible(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
ui->signMessage->setEnabled(true);
ui->signMessage->setVisible(true);
ui->verifyMessage->setEnabled(false);
ui->verifyMessage->setVisible(false);
break;
}
ui->copyAddress->setEnabled(true);
ui->showQRCode->setEnabled(true);
}
else
{
ui->deleteAddress->setEnabled(false);
ui->showQRCode->setEnabled(false);
ui->copyAddress->setEnabled(false);
ui->signMessage->setEnabled(false);
ui->verifyMessage->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// When this is a tab/widget and not a model dialog, ignore "done"
if(mode == ForEditing)
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Address Book Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void AddressBookPage::on_showQRCode_clicked()
{
#ifdef USE_QRCODE
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
QString label = index.sibling(index.row(), 0).data(Qt::EditRole).toString();
QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this);
dialog->setModel(optionsModel);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
#endif
}
void AddressBookPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
|
#include "addressbookpage.h"
#include "ui_addressbookpage.h"
#include "addresstablemodel.h"
#include "optionsmodel.h"
#include "bitcoingui.h"
#include "editaddressdialog.h"
#include "csvmodelwriter.h"
#include "guiutil.h"
#ifdef USE_QRCODE
#include "qrcodedialog.h"
#endif
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
optionsModel(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->verifyMessage->setIcon(QIcon());
ui->signMessage->setIcon(QIcon());
#endif
#ifndef USE_QRCODE
ui->showQRCode->setVisible(false);
#endif
switch(mode)
{
case ForSending:
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
break;
case ForEditing:
ui->buttonBox->setVisible(false);
break;
}
switch(tab)
{
case SendingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
ui->signMessage->setVisible(false);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you."));
ui->deleteAddress->setVisible(false);
ui->signMessage->setVisible(true);
break;
}
// Context menu actions
QAction *copyAddressAction = new QAction(ui->copyAddress->text(), this);
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *editAction = new QAction(tr("&Edit"), this);
QAction *sendCoinsAction = new QAction(tr("Send &Coins"), this);
QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this);
QAction *signMessageAction = new QAction(ui->signMessage->text(), this);
QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if(tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
if(tab == SendingTab)
contextMenu->addAction(sendCoinsAction);
#ifdef USE_QRCODE
contextMenu->addAction(showQRCodeAction);
#endif
if(tab == ReceivingTab)
contextMenu->addAction(signMessageAction);
else if(tab == SendingTab)
contextMenu->addAction(verifyMessageAction);
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(onSendCoinsAction()));
connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
// Pass through accept action from button box
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
switch(tab)
{
case ReceivingTab:
// Receive filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Receive);
break;
case SendingTab:
// Send filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
break;
}
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void AddressBookPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_signMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit signMessage(address);
}
}
void AddressBookPage::on_verifyMessage_clicked()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit verifyMessage(address);
}
}
void AddressBookPage::onSendCoinsAction()
{
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
emit sendCoins(address);
}
}
void AddressBookPage::on_newAddress_clicked()
{
if(!model)
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
switch(tab)
{
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
ui->signMessage->setEnabled(false);
ui->signMessage->setVisible(false);
ui->verifyMessage->setEnabled(true);
ui->verifyMessage->setVisible(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
ui->signMessage->setEnabled(true);
ui->signMessage->setVisible(true);
ui->verifyMessage->setEnabled(false);
ui->verifyMessage->setVisible(false);
break;
}
ui->copyAddress->setEnabled(true);
ui->showQRCode->setEnabled(true);
}
else
{
ui->deleteAddress->setEnabled(false);
ui->showQRCode->setEnabled(false);
ui->copyAddress->setEnabled(false);
ui->signMessage->setEnabled(false);
ui->verifyMessage->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// When this is a tab/widget and not a model dialog, ignore "done"
if(mode == ForEditing)
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Address Book Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void AddressBookPage::on_showQRCode_clicked()
{
#ifdef USE_QRCODE
QTableView *table = ui->tableView;
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QString address = index.data().toString();
QString label = index.sibling(index.row(), 0).data(Qt::EditRole).toString();
QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this);
dialog->setModel(optionsModel);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
#endif
}
void AddressBookPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
|
fix mac specific button modification on addressbookpage
|
fix mac specific button modification on addressbookpage
- continue the mac behavior of clearing button icons (because it's unusual on mac apps)
- fix: new button variable names, new buttons (verifyMessage, signMessage)
Signed-off-by: Jonas Schnelli <[email protected]>
|
C++
|
mit
|
howardrya/AcademicCoin,thormuller/yescoin2,martindale/elements,KaSt/equikoin,greencoin-dev/digitalcoin,drwasho/bitcoinxt,magacoin/magacoin,DMDcoin/Diamond,bdelzell/creditcoin-org-creditcoin,fullcoins/fullcoin,StarbuckBG/BTCGPU,jnewbery/bitcoin,presstab/PIVX,prark/bitcoinxt,jamesob/bitcoin,wederw/bitcoin,karek314/bitcoin,WorldcoinGlobal/WorldcoinLegacy,domob1812/namecore,JeremyRand/bitcoin,jimmykiselak/lbrycrd,5mil/Tradecoin,Kore-Core/kore,cainca/liliucoin,koharjidan/dogecoin,midnight-miner/LasVegasCoin,elliotolds/bitcoin,ixcoinofficialpage/master,skaht/bitcoin,40thoughts/Coin-QualCoin,tedlz123/Bitcoin,credits-currency/credits,brishtiteveja/truthcoin-cpp,zcoinofficial/zcoin,drwasho/bitcoinxt,haobtc/bitcoin,nvmd/bitcoin,PIVX-Project/PIVX,janko33bd/bitcoin,Lucky7Studio/bitcoin,Kcoin-project/kcoin,llamasoft/ProtoShares_Cycle,IlfirinIlfirin/shavercoin,sipa/elements,Megacoin2/Megacoin,Kogser/bitcoin,slingcoin/sling-market,osuyuushi/laughingmancoin,bcpki/testblocks,pouta/bitcoin,LIMXTEC/DMDv3,mrtexaznl/mediterraneancoin,madman5844/poundkoin,IlfirinCano/shavercoin,jlopp/statoshi,tedlz123/Bitcoin,cryptoprojects/ultimateonlinecash,netswift/vertcoin,DigitalPandacoin/pandacoin,slingcoin/sling-market,meighti/bitcoin,gjhiggins/vcoin0.8zeta-dev,bitcoinknots/bitcoin,collapsedev/circlecash,jtimon/bitcoin,JeremyRand/namecore,aciddude/Feathercoin,vertcoin/eyeglass,Vector2000/bitcoin,pascalguru/florincoin,ArgonToken/ArgonToken,Bitcoin-com/BUcash,cmgustavo/bitcoin,ShadowMyst/creativechain-core,lakepay/lake,capitalDIGI/litecoin,Flurbos/Flurbo,coinkeeper/2015-06-22_18-56_megacoin,funkshelper/woodcore,szlaozhu/twister-core,jaromil/faircoin2,CryptArc/bitcoin,fussl/elements,zcoinofficial/zcoin,CryptArc/bitcoinxt,truthcoin/blocksize-market,nvmd/bitcoin,coinwarp/dogecoin,kazcw/bitcoin,tjth/lotterycoin,coinkeeper/2015-06-22_18-46_razor,apoelstra/elements,bitpagar/bitpagar,vcoin-project/vcoincore,borgcoin/Borgcoin.rar,GlobalBoost/GlobalBoost,lakepay/lake,zemrys/vertcoin,ClusterCoin/ClusterCoin,starwels/starwels,bitpagar/bitpagar,mitchellcash/bitcoin,fsb4000/bitcoin,unsystemizer/bitcoin,razor-coin/razor,keesdewit82/LasVegasCoin,cinnamoncoin/groupcoin-1,borgcoin/Borgcoin.rar,OmniLayer/omnicore,chaincoin/chaincoin,putinclassic/putic,cculianu/bitcoin-abc,CTRoundTable/Encrypted.Cash,Ziftr/bitcoin,experiencecoin/experiencecoin,franko-org/franko,metrocoins/metrocoin,psionin/smartcoin,okinc/bitcoin,sdaftuar/bitcoin,ajtowns/bitcoin,MasterX1582/bitcoin-becoin,bitcoinclassic/bitcoinclassic,bitcoin/bitcoin,maraoz/proofcoin,scippio/bitcoin,gzuser01/zetacoin-bitcoin,tjth/lotterycoin,coinerd/krugercoin,HeliumGas/helium,monacoinproject/monacoin,trippysalmon/bitcoin,Jcing95/iop-hd,n1bor/bitcoin,hg5fm/nexuscoin,bitbrazilcoin-project/bitbrazilcoin,gameunits/gameunits,CodeShark/bitcoin,thormuller/yescoin2,coinkeeper/anoncoin_20150330_fixes,Cloudsy/bitcoin,pascalguru/florincoin,scamcoinz/scamcoin,zenywallet/bitzeny,p2peace/oliver-twister-core,habibmasuro/bitcoinxt,aburan28/elements,biblepay/biblepay,BTCfork/hardfork_prototype_1_mvf-core,bdelzell/creditcoin-org-creditcoin,koharjidan/dogecoin,Litecoindark/LTCD,daveperkins-github/bitcoin-dev,ardsu/bitcoin,omefire/bitcoin,deadalnix/bitcoin,unsystemizer/bitcoin,butterflypay/bitcoin,brishtiteveja/sherlockholmescoin,BitcoinPOW/BitcoinPOW,genavarov/lamacoin,world-bank/unpay-core,sbellem/bitcoin,ticclassic/ic,gwangjin2/gwangcoin-core,Richcoin-Project/RichCoin,aspanta/bitcoin,putinclassic/putic,cddjr/BitcoinUnlimited,uphold/bitcoin,dcousens/bitcoin,earthcoinproject/earthcoin,jonghyeopkim/bitcoinxt,Tetcoin/tetcoin,ericshawlinux/bitcoin,iosdevzone/bitcoin,vericoin/vericoin-core,Alex-van-der-Peet/bitcoin,roques/bitcoin,ftrader-bitcoinabc/bitcoin-abc,knolza/gamblr,vlajos/bitcoin,alecalve/bitcoin,metacoin/florincoin,morcos/bitcoin,torresalyssa/bitcoin,wcwu/bitcoin,PIVX-Project/PIVX,upgradeadvice/MUE-Src,FarhanHaque/bitcoin,BlockchainTechLLC/3dcoin,aciddude/Feathercoin,biblepay/biblepay,riecoin/riecoin,OfficialTitcoin/titcoin-wallet,EthanHeilman/bitcoin,daveperkins-github/bitcoin-dev,viacoin/viacoin,coinkeeper/2015-06-22_18-31_bitcoin,bcpki/nonce2testblocks,slingcoin/sling-market,IlfirinCano/shavercoin,ctwiz/stardust,scamcoinz/scamcoin,tripmode/pxlcoin,maaku/bitcoin,Dinarcoin/dinarcoin,langerhans/dogecoin,greencoin-dev/greencoin-dev,UFOCoins/ufo,jrick/bitcoin,jameshilliard/bitcoin,vertcoin/eyeglass,Krellan/bitcoin,DGCDev/digitalcoin,deuscoin/deuscoin,myriadcoin/myriadcoin,JeremyRand/namecore,shurcoin/shurcoin,florincoin/florincoin,Litecoindark/LTCD,rnicoll/bitcoin,Jeff88Ho/bitcoin,tecnovert/particl-core,NunoEdgarGub1/elements,TheBlueMatt/bitcoin,ivansib/sib16,xieta/mincoin,Anoncoin/anoncoin,sugruedes/bitcoinxt,genavarov/ladacoin,Metronotes/bitcoin,Bitcoin-ABC/bitcoin-abc,NunoEdgarGub1/elements,BlockchainTechLLC/3dcoin,welshjf/bitcoin,MarcoFalke/bitcoin,anditto/bitcoin,RazorLove/cloaked-octo-spice,Mrs-X/PIVX,coinkeeper/megacoin_20150410_fixes,martindale/elements,funbucks/notbitcoinxt,Richcoin-Project/RichCoin,Dinarcoin/dinarcoin,gjhiggins/vcoin0.8zeta-dev,pastday/bitcoinproject,ppcoin/ppcoin,antcheck/antcoin,UdjinM6/dash,TierNolan/bitcoin,Har01d/bitcoin,hophacker/bitcoin_malleability,lbrtcoin/albertcoin,mincoin-project/mincoin,instagibbs/bitcoin,dobbscoin/dobbscoin-source,Rav3nPL/doubloons-0.10,sdaftuar/bitcoin,rawodb/bitcoin,CodeShark/bitcoin,gandrewstone/BitcoinUnlimited,HeliumGas/helium,jimblasko/UnbreakableCoin-master,nmarley/dash,faircoin/faircoin,tropa/axecoin,FeatherCoin/Feathercoin,taenaive/zetacoin,Mrs-X/Darknet,aspirecoin/aspire,alejandromgk/Lunar,bitpay/bitcoin,Thracky/monkeycoin,BTCfork/hardfork_prototype_1_mvf-core,Megacoin2/Megacoin,achow101/bitcoin,jonasnick/bitcoin,sbaks0820/bitcoin,my-first/octocoin,peacedevelop/peacecoin,nmarley/dash,phelix/bitcoin,adpg211/bitcoin-master,icook/vertcoin,senadmd/coinmarketwatch,biblepay/biblepay,isle2983/bitcoin,CoinProjects/AmsterdamCoin-v4,braydonf/bitcoin,roques/bitcoin,mm-s/bitcoin,namecoin/namecore,Domer85/dogecoin,ArgonToken/ArgonToken,razor-coin/razor,StarbuckBG/BTCGPU,jambolo/bitcoin,laudaa/bitcoin,funkshelper/woodcore,elecoin/elecoin,TheBlueMatt/bitcoin,masterbraz/dg,megacoin/megacoin,butterflypay/bitcoin,sipa/elements,untrustbank/litecoin,ahmedbodi/temp_vert,GroundRod/anoncoin,dexX7/mastercore,barcoin-project/nothingcoin,phelix/namecore,diggcoin/diggcoin,ionux/freicoin,domob1812/bitcoin,ohac/sha1coin,accraze/bitcoin,Earlz/dobbscoin-source,applecoin-official/fellatio,arruah/ensocoin,Cocosoft/bitcoin,MazaCoin/maza,KaSt/equikoin,core-bitcoin/bitcoin,ixcoinofficialpage/master,chaincoin/chaincoin,sarielsaz/sarielsaz,JeremyRand/namecore,jonghyeopkim/bitcoinxt,gravio-net/graviocoin,ftrader-bitcoinabc/bitcoin-abc,BitzenyCoreDevelopers/bitzeny,UASF/bitcoin,koharjidan/dogecoin,koharjidan/bitcoin,anditto/bitcoin,HashUnlimited/Einsteinium-Unlimited,Checkcoin/checkcoin,Kore-Core/kore,dashpay/dash,JeremyRand/namecoin-core,Chancoin-core/CHANCOIN,kirkalx/bitcoin,achow101/bitcoin,pinkevich/dash,cerebrus29301/crowncoin,untrustbank/litecoin,haraldh/bitcoin,WorldcoinGlobal/WorldcoinLegacy,nightlydash/darkcoin,SoreGums/bitcoinxt,dogecoin/dogecoin,rnicoll/dogecoin,droark/elements,48thct2jtnf/P,erqan/twister-core,kazcw/bitcoin,gameunits/gameunits,jameshilliard/bitcoin,starwalkerz/fincoin-fork,Bitcoin-ABC/bitcoin-abc,OmniLayer/omnicore,Earlz/renamedcoin,BigBlueCeiling/augmentacoin,jameshilliard/bitcoin,saydulk/Feathercoin,tecnovert/particl-core,Darknet-Crypto/Darknet,jimmysong/bitcoin,micryon/GPUcoin,aburan28/elements,oleganza/bitcoin-duo,mincoin-project/mincoin,GroestlCoin/bitcoin,degenorate/Deftcoin,cheehieu/bitcoin,dobbscoin/dobbscoin-source,RazorLove/cloaked-octo-spice,KaSt/equikoin,PandaPayProject/PandaPay,rjshaver/bitcoin,oklink-dev/bitcoin,greenaddress/bitcoin,RazorLove/cloaked-octo-spice,21E14/bitcoin,chrisfranko/aiden,SoreGums/bitcoinxt,fedoracoin-dev/fedoracoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,Flowdalic/bitcoin,Bushstar/UFO-Project,howardrya/AcademicCoin,11755033isaprimenumber/Feathercoin,bitcoinxt/bitcoinxt,coinkeeper/anoncoin_20150330_fixes,vmp32k/litecoin,PRabahy/bitcoin,applecoin-official/fellatio,BigBlueCeiling/augmentacoin,bitcoinclassic/bitcoinclassic,MazaCoin/mazacoin-new,koharjidan/dogecoin,sirk390/bitcoin,TrainMAnB/vcoincore,aspirecoin/aspire,pelorusjack/BlockDX,Friedbaumer/litecoin,BitcoinUnlimited/BitcoinUnlimited,vbernabe/freicoin,wellenreiter01/Feathercoin,haobtc/bitcoin,zebrains/Blotter,litecoin-project/bitcoinomg,cybermatatu/bitcoin,Carrsy/PoundCoin,spiritlinxl/BTCGPU,peercoin/peercoin,Kixunil/keynescoin,jlopp/statoshi,ppcoin/ppcoin,bitjson/hivemind,martindale/elements,elecoin/elecoin,imharrywu/fastcoin,webdesignll/coin,jrick/bitcoin,nikkitan/bitcoin,afk11/bitcoin,sstone/bitcoin,ohac/sakuracoin,cinnamoncoin/groupcoin-1,kallewoof/elements,wbchen99/bitcoin-hnote0,cainca/liliucoin,coinkeeper/2015-06-22_18-37_dogecoin,nigeriacoin/nigeriacoin,constantine001/bitcoin,instagibbs/bitcoin,wederw/bitcoin,compasscoin/compasscoin,cinnamoncoin/Feathercoin,jlopp/statoshi,GroundRod/anoncoin,GroestlCoin/GroestlCoin,marlengit/BitcoinUnlimited,terracoin/terracoin,gwillen/elements,destenson/bitcoin--bitcoin,jonasschnelli/bitcoin,CryptArc/bitcoinxt,metacoin/florincoin,shaulkf/bitcoin,DigiByte-Team/digibyte,deeponion/deeponion,koharjidan/dogecoin,haobtc/bitcoin,dashpay/dash,KaSt/ekwicoin,dannyperez/bolivarcoin,dcousens/bitcoin,Domer85/dogecoin,ANCompany/birdcoin-dev,langerhans/dogecoin,welshjf/bitcoin,destenson/bitcoin--bitcoin,droark/elements,arruah/ensocoin,kbccoin/kbc,ahmedbodi/temp_vert,spiritlinxl/BTCGPU,steakknife/bitcoin-qt,hophacker/bitcoin_malleability,bitshares/bitshares-pts,RyanLucchese/energi,domob1812/bitcoin,privatecoin/privatecoin,simonmulser/bitcoin,wtogami/bitcoin,habibmasuro/bitcoin,jtimon/bitcoin,kryptokredyt/ProjektZespolowyCoin,lbrtcoin/albertcoin,bcpki/nonce2,phplaboratory/psiacoin,CarpeDiemCoin/CarpeDiemLaunch,RibbitFROG/ribbitcoin,segwit/atbcoin-insight,FrictionlessCoin/iXcoin,coinkeeper/2015-06-22_19-07_digitalcoin,simdeveloper/bitcoin,tjps/bitcoin,jaromil/faircoin2,shouhuas/bitcoin,basicincome/unpcoin-core,dev1972/Satellitecoin,segwit/atbcoin-insight,renatolage/wallets-BRCoin,peerdb/cors,jrmithdobbs/bitcoin,rdqw/sscoin,rsdevgun16e/energi,ekankyesme/bitcoinxt,syscoin/syscoin2,scamcoinz/scamcoin,segwit/atbcoin-insight,bitgoldcoin-project/bitgoldcoin,octocoin-project/octocoin,multicoins/marycoin,BitcoinPOW/BitcoinPOW,marscoin/marscoin,UFOCoins/ufo,Flurbos/Flurbo,zotherstupidguy/bitcoin,andres-root/bitcoinxt,kleetus/bitcoin,bickojima/bitzeny,MitchellMintCoins/AutoCoin,2XL/bitcoin,Jcing95/iop-hd,FeatherCoin/Feathercoin,josephbisch/namecoin-core,brandonrobertz/namecoin-core,se3000/bitcoin,zottejos/merelcoin,ccoin-project/ccoin,mockcoin/mockcoin,ixcoinofficialpage/master,crowning2/dash,StarbuckBG/BTCGPU,afk11/bitcoin,privatecoin/privatecoin,btcdrak/bitcoin,ashleyholman/bitcoin,bitbrazilcoin-project/bitbrazilcoin,ticclassic/ic,Rav3nPL/bitcoin,ionomy/ion,elliotolds/bitcoin,andres-root/bitcoinxt,brishtiteveja/sherlockcoin,WorldLeadCurrency/WLC,bitcoin-hivemind/hivemind,mikehearn/bitcoinxt,tuaris/bitcoin,antcheck/antcoin,Dajackal/Ronpaulcoin,vertcoin/vertcoin,bitbrazilcoin-project/bitbrazilcoin,Mrs-X/PIVX,likecoin-dev/bitcoin,raasakh/bardcoin.exe,fussl/elements,MikeAmy/bitcoin,blood2/bloodcoin-0.9,gcc64/bitcoin,funkshelper/woodcoin-b,yenliangl/bitcoin,bankonmecoin/bitcoin,enlighter/Feathercoin,GroestlCoin/GroestlCoin,domob1812/bitcoin,genavarov/lamacoin,micryon/GPUcoin,schildbach/bitcoin,upgradeadvice/MUE-Src,jambolo/bitcoin,joulecoin/joulecoin,irvingruan/bitcoin,ShwoognationHQ/bitcoin,Enticed87/Decipher,zander/bitcoinclassic,FrictionlessCoin/iXcoin,Mrs-X/Darknet,dgarage/bc2,Friedbaumer/litecoin,coinkeeper/2015-06-22_18-51_vertcoin,karek314/bitcoin,genavarov/brcoin,practicalswift/bitcoin,keesdewit82/LasVegasCoin,GwangJin/gwangmoney-core,welshjf/bitcoin,Rav3nPL/doubloons-0.10,Climbee/artcoin,ptschip/bitcoinxt,rnicoll/dogecoin,argentumproject/argentum,domob1812/huntercore,xuyangcn/opalcoin,world-bank/unpay-core,crowning-/dash,wbchen99/bitcoin-hnote0,zixan/bitcoin,plncoin/PLNcoin_Core,majestrate/twister-core,keesdewit82/LasVegasCoin,REAP720801/bitcoin,core-bitcoin/bitcoin,21E14/bitcoin,coinkeeper/2015-06-22_18-30_anoncoin,simonmulser/bitcoin,x-kalux/bitcoin_WiG-B,krzysztofwos/BitcoinUnlimited,npccoin/npccoin,ravenbyron/phtevencoin,mammix2/ccoin-dev,worldbit/worldbit,kseistrup/twister-core,Justaphf/BitcoinUnlimited,Coinfigli/coinfigli,megacoin/megacoin,kbccoin/kbc,gazbert/bitcoin,rjshaver/bitcoin,pouta/bitcoin,phelix/namecore,funbucks/notbitcoinxt,senadmd/coinmarketwatch,schildbach/bitcoin,Bloom-Project/Bloom,OfficialTitcoin/titcoin-wallet,pinheadmz/bitcoin,vcoin-project/vcoin0.8zeta-dev,constantine001/bitcoin,UFOCoins/ufo,Rav3nPL/bitcoin,uphold/bitcoin,Bitcoin-ABC/bitcoin-abc,tensaix2j/bananacoin,jonasschnelli/bitcoin,Horrorcoin/horrorcoin,gandrewstone/bitcoinxt,dmrtsvetkov/flowercoin,bootycoin-project/bootycoin,Enticed87/Decipher,mincoin-project/mincoin,destenson/bitcoin--bitcoin,jlopp/statoshi,shelvenzhou/BTCGPU,jrick/bitcoin,JeremyRubin/bitcoin,instagibbs/bitcoin,meighti/bitcoin,morcos/bitcoin,upgradeadvice/MUE-Src,genavarov/lamacoin,jameshilliard/bitcoin,sdaftuar/bitcoin,czr5014iph/bitcoin4e,Bitcoin-ABC/bitcoin-abc,gapcoin/gapcoin,dobbscoin/dobbscoin-source,metrocoins/metrocoin,antonio-fr/bitcoin,dexX7/bitcoin,thormuller/yescoin2,keisercoin-official/keisercoin,Vector2000/bitcoin,cdecker/bitcoin,n1bor/bitcoin,nvmd/bitcoin,cddjr/BitcoinUnlimited,sifcoin/sifcoin,ediston/energi,48thct2jtnf/P,rebroad/bitcoin,ionux/freicoin,btc1/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,svost/bitcoin,zenywallet/bitzeny,argentumproject/argentum,koharjidan/dogecoin,ahmedbodi/terracoin,cyrixhero/bitcoin,sifcoin/sifcoin,sirk390/bitcoin,jeromewu/bitcoin-opennet,bcpki/nonce2,constantine001/bitcoin,mastercoin-MSC/mastercore,andres-root/bitcoinxt,jtimon/bitcoin,UdjinM6/dash,mammix2/ccoin-dev,dgarage/bc3,goldcoin/Goldcoin-GLD,romanornr/viacoin,KillerByte/memorypool,isle2983/bitcoin,Metronotes/bitcoin,IlfirinIlfirin/shavercoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,cqtenq/Feathercoin,bittylicious/bitcoin,janko33bd/bitcoin,tripmode/pxlcoin,cryptocoins4all/zcoin,dpayne9000/Rubixz-Coin,ekankyesme/bitcoinxt,vtafaucet/virtacoin,oklink-dev/bitcoin_block,hasanatkazmi/bitcoin,randy-waterhouse/bitcoin,Vsync-project/Vsync,zcoinofficial/zcoin,majestrate/twister-core,misdess/bitcoin,shaolinfry/litecoin,rsdevgun16e/energi,ardsu/bitcoin,earthcoinproject/earthcoin,Christewart/bitcoin,CrimeaCoin/crimeacoin,sipa/bitcoin,sirk390/bitcoin,MitchellMintCoins/MortgageCoin,nanocoins/mycoin,qubitcoin-project/QubitCoinQ2C,pinkevich/dash,maraoz/proofcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,dgarage/bc2,jakeva/bitcoin-pwcheck,jtimon/elements,fanquake/bitcoin,gzuser01/zetacoin-bitcoin,DigiByte-Team/digibyte,shelvenzhou/BTCGPU,lbrtcoin/albertcoin,kevcooper/bitcoin,BitcoinUnlimited/BitcoinUnlimited,qreatora/worldcoin-v0.8,braydonf/bitcoin,2XL/bitcoin,cculianu/bitcoin-abc,stamhe/litecoin,coinkeeper/2015-06-22_18-52_viacoin,emc2foundation/einsteinium,constantine001/bitcoin,gazbert/bitcoin,Kenwhite23/litecoin,GroestlCoin/bitcoin,174high/bitcoin,brightcoin/brightcoin,isocolsky/bitcoinxt,bitgoldcoin-project/bitgoldcoin,nbenoit/bitcoin,scippio/bitcoin,HashUnlimited/Einsteinium-Unlimited,rebroad/bitcoin,Bitcoin-ABC/bitcoin-abc,borgcoin/Borgcoin.rar,ptschip/bitcoinxt,tjth/lotterycoin,appop/bitcoin,dperel/bitcoin,inutoshi/inutoshi,litecoin-project/litecoin,dgenr8/bitcoinxt,mruddy/bitcoin,cinnamoncoin/Feathercoin,nigeriacoin/nigeriacoin,reddink/reddcoin,ppcoin/ppcoin,dgarage/bc3,antonio-fr/bitcoin,pinheadmz/bitcoin,cryptocoins4all/zcoin,borgcoin/Borgcoin1,sifcoin/sifcoin,tjth/lotterycoin,koharjidan/bitcoin,CryptArc/bitcoinxt,Tetpay/bitcoin,gravio-net/graviocoin,webdesignll/coin,cyrixhero/bitcoin,Bloom-Project/Bloom,whatrye/twister-core,ekankyesme/bitcoinxt,marklai9999/Taiwancoin,rnicoll/dogecoin,schinzelh/dash,dscotese/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,gmaxwell/bitcoin,multicoins/marycoin,zottejos/merelcoin,sickpig/BitcoinUnlimited,mincoin-project/mincoin,Michagogo/bitcoin,Coinfigli/coinfigli,TierNolan/bitcoin,Bitcoin-com/BUcash,fullcoins/fullcoin,jrick/bitcoin,r8921039/bitcoin,jimmykiselak/lbrycrd,bankonmecoin/bitcoin,wtogami/bitcoin,czr5014iph/bitcoin4e,Kcoin-project/kcoin,GreenParhelia/bitcoin,chrisfranko/aiden,gravio-net/graviocoin,aspirecoin/aspire,coinkeeper/2015-06-22_19-19_worldcoin,shouhuas/bitcoin,wangxinxi/litecoin,oklink-dev/bitcoin,inkvisit/sarmacoins,marcusdiaz/BitcoinUnlimited,masterbraz/dg,Rav3nPL/PLNcoin,jmgilbert2/energi,worldbit/worldbit,tdudz/elements,Anfauglith/iop-hd,rnicoll/bitcoin,blocktrail/bitcoin,ClusterCoin/ClusterCoin,multicoins/marycoin,hg5fm/nexuscoin,ohac/sakuracoin,parvez3019/bitcoin,sugruedes/bitcoinxt,superjudge/bitcoin,Kangmo/bitcoin,gjhiggins/vcoincore,benosa/bitcoin,bitpay/bitcoin,upgradeadvice/MUE-Src,manuel-zulian/CoMoNet,gapcoin/gapcoin,jonasschnelli/bitcoin,GroestlCoin/GroestlCoin,TGDiamond/Diamond,gjhiggins/vcoin09,nsacoin/nsacoin,theuni/bitcoin,hasanatkazmi/bitcoin,DynamicCoinOrg/DMC,ryanxcharles/bitcoin,MikeAmy/bitcoin,habibmasuro/bitcoinxt,litecoin-project/litecore-litecoin,coinkeeper/2015-06-22_18-37_dogecoin,jmcorgan/bitcoin,shomeser/bitcoin,terracoin/terracoin,sipsorcery/bitcoin,alecalve/bitcoin,benma/bitcoin,brettwittam/geocoin,Exgibichi/statusquo,dannyperez/bolivarcoin,mastercoin-MSC/mastercore,funbucks/notbitcoinxt,skaht/bitcoin,x-kalux/bitcoin_WiG-B,zzkt/solarcoin,randy-waterhouse/bitcoin,rsdevgun16e/energi,netswift/vertcoin,safecoin/safecoin,tjps/bitcoin,Bitcoinsulting/bitcoinxt,marlengit/BitcoinUnlimited,rustyrussell/bitcoin,koharjidan/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,djpnewton/bitcoin,jiangyonghang/bitcoin,isle2983/bitcoin,applecoin-official/applecoin,grumpydevelop/singularity,skaht/bitcoin,mikehearn/bitcoin,wbchen99/bitcoin-hnote0,Electronic-Gulden-Foundation/egulden,kazcw/bitcoin,DrCrypto/darkcoin,ahmedbodi/terracoin,vcoin-project/vcoin0.8zeta-dev,vmp32k/litecoin,Anoncoin/anoncoin,dmrtsvetkov/flowercoin,ahmedbodi/vertcoin,manuel-zulian/accumunet,jarymoth/dogecoin,vbernabe/freicoin,goldcoin/goldcoin,MikeAmy/bitcoin,peercoin/peercoin,goldcoin/goldcoin,kallewoof/elements,cerebrus29301/crowncoin,emc2foundation/einsteinium,NunoEdgarGub1/elements,Rav3nPL/bitcoin,Exceltior/dogecoin,BTCTaras/bitcoin,chrisfranko/aiden,atgreen/bitcoin,xieta/mincoin,Tetpay/bitcoin,theuni/bitcoin,puticcoin/putic,presstab/PIVX,namecoin/namecore,isle2983/bitcoin,worldcoinproject/worldcoin-v0.8,Vector2000/bitcoin,GlobalBoost/GlobalBoost,jmcorgan/bitcoin,Czarcoin/czarcoin,MasterX1582/bitcoin-becoin,uphold/bitcoin,cainca/liliucoin,matlongsi/micropay,Rav3nPL/doubloons-0.10,sebrandon1/bitcoin,globaltoken/globaltoken,world-bank/unpay-core,odemolliens/bitcoinxt,Mirobit/bitcoin,xieta/mincoin,Petr-Economissa/gvidon,digideskio/namecoin,Bitcoinsulting/bitcoinxt,shouhuas/bitcoin,cculianu/bitcoin-abc,mammix2/ccoin-dev,atgreen/bitcoin,nailtaras/nailcoin,namecoin/namecore,matlongsi/micropay,TierNolan/bitcoin,scippio/bitcoin,Bitcoin-ABC/bitcoin-abc,jaromil/faircoin2,spiritlinxl/BTCGPU,tensaix2j/bananacoin,biblepay/biblepay,mrtexaznl/mediterraneancoin,gjhiggins/vcoin0.8zeta-dev,martindale/elements,ravenbyron/phtevencoin,gavinandresen/bitcoin-git,gjhiggins/vcoincore,sbaks0820/bitcoin,alexandrcoin/vertcoin,diggcoin/diggcoin,zotherstupidguy/bitcoin,erqan/twister-core,razor-coin/razor,KillerByte/memorypool,bitjson/hivemind,brightcoin/brightcoin,compasscoin/compasscoin,FinalHashLLC/namecore,ticclassic/ic,mruddy/bitcoin,Megacoin2/Megacoin,Mrs-X/PIVX,ingresscoin/ingresscoin,pouta/bitcoin,glv2/peerunity,omefire/bitcoin,myriadteam/myriadcoin,nsacoin/nsacoin,sarielsaz/sarielsaz,metrocoins/metrocoin,cryptodev35/icash,Electronic-Gulden-Foundation/egulden,botland/bitcoin,gravio-net/graviocoin,nathan-at-least/zcash,maraoz/proofcoin,CryptArc/bitcoin,gjhiggins/fuguecoin,ShadowMyst/creativechain-core,xeddmc/twister-core,hsavit1/bitcoin,OfficialTitcoin/titcoin-wallet,BitcoinUnlimited/BitcoinUnlimited,biblepay/biblepay,ingresscoin/ingresscoin,isocolsky/bitcoinxt,ingresscoin/ingresscoin,meighti/bitcoin,LIMXTEC/DMDv3,Anoncoin/anoncoin,pstratem/elements,credits-currency/credits,collapsedev/cashwatt,TeamBitBean/bitcoin-core,jtimon/bitcoin,domob1812/huntercore,presstab/PIVX,daliwangi/bitcoin,ivansib/sibcoin,llluiop/bitcoin,alecalve/bitcoin,RongxinZhang/bitcoinxt,1185/starwels,bittylicious/bitcoin,nvmd/bitcoin,misdess/bitcoin,megacoin/megacoin,gmaxwell/bitcoin,bitcoinsSG/zcash,ahmedbodi/terracoin,elecoin/elecoin,tripmode/pxlcoin,shapiroisme/datadollar,haobtc/bitcoin,tensaix2j/bananacoin,SartoNess/BitcoinUnlimited,Anfauglith/iop-hd,fanquake/bitcoin,karek314/bitcoin,pataquets/namecoin-core,pastday/bitcoinproject,my-first/octocoin,jlopp/statoshi,SoreGums/bitcoinxt,alecalve/bitcoin,shurcoin/shurcoin,mooncoin-project/mooncoin-landann,HeliumGas/helium,cryptcoins/cryptcoin,thormuller/yescoin2,compasscoin/compasscoin,iQcoin/iQcoin,TGDiamond/Diamond,shelvenzhou/BTCGPU,Rav3nPL/PLNcoin,experiencecoin/experiencecoin,rdqw/sscoin,loxal/zcash,zetacoin/zetacoin,coinkeeper/2015-06-22_18-30_anoncoin,Checkcoin/checkcoin,randy-waterhouse/bitcoin,Ziftr/litecoin,litecoin-project/litecore-litecoin,reddink/reddcoin,cryptoprojects/ultimateonlinecash,peacedevelop/peacecoin,mapineda/litecoin,kallewoof/bitcoin,wcwu/bitcoin,miguelfreitas/twister-core,szlaozhu/twister-core,bitcoinplusorg/xbcwalletsource,scippio/bitcoin,kallewoof/elements,cerebrus29301/crowncoin,bdelzell/creditcoin-org-creditcoin,kaostao/bitcoin,romanornr/viacoin,digibyte/digibyte,and2099/twister-core,litecoin-project/litecore-litecoin,Vsync-project/Vsync,zenywallet/bitzeny,phplaboratory/psiacoin,taenaive/zetacoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,WorldcoinGlobal/WorldcoinLegacy,emc2foundation/einsteinium,Erkan-Yilmaz/twister-core,wangxinxi/litecoin,SoreGums/bitcoinxt,crowning-/dash,ronpaulcoin/ronpaulcoin,paveljanik/bitcoin,millennial83/bitcoin,bootycoin-project/bootycoin,marlengit/hardfork_prototype_1_mvf-bu,BTCfork/hardfork_prototype_1_mvf-bu,gwangjin2/gwangcoin-core,donaloconnor/bitcoin,litecoin-project/litecoin,metacoin/florincoin,nomnombtc/bitcoin,btcdrak/bitcoin,initaldk/bitcoin,Mirobit/bitcoin,neuroidss/bitcoin,Litecoindark/LTCD,freelion93/mtucicoin,TierNolan/bitcoin,brishtiteveja/truthcoin-cpp,Kangmo/bitcoin,supcoin/supcoin,5mil/Tradecoin,fujicoin/fujicoin,wiggi/huntercore,reddink/reddcoin,glv2/peerunity,DynamicCoinOrg/DMC,qreatora/worldcoin-v0.8,n1bor/bitcoin,npccoin/npccoin,joulecoin/joulecoin,achow101/bitcoin,UdjinM6/dash,shaolinfry/litecoin,sickpig/BitcoinUnlimited,themusicgod1/bitcoin,ionux/freicoin,phelix/namecore,majestrate/twister-core,coinkeeper/2015-06-22_18-39_feathercoin,tdudz/elements,adpg211/bitcoin-master,GIJensen/bitcoin,Cocosoft/bitcoin,Diapolo/bitcoin,sdaftuar/bitcoin,vericoin/vericoin-core,likecoin-dev/bitcoin,Vector2000/bitcoin,united-scrypt-coin-project/unitedscryptcoin,marklai9999/Taiwancoin,Kore-Core/kore,bcpki/testblocks,manuel-zulian/CoMoNet,iQcoin/iQcoin,plncoin/PLNcoin_Core,ediston/energi,GroestlCoin/bitcoin,coinkeeper/2015-06-22_19-13_florincoin,digibyte/digibyte,brishtiteveja/sherlockcoin,Theshadow4all/ShadowCoin,arnuschky/bitcoin,funkshelper/woodcore,dan-mi-sun/bitcoin,ticclassic/ic,keo/bitcoin,sickpig/BitcoinUnlimited,daveperkins-github/bitcoin-dev,Ziftr/litecoin,174high/bitcoin,iQcoin/iQcoin,KibiCoin/kibicoin,goldmidas/goldmidas,zenywallet/bitzeny,fullcoins/fullcoin,cqtenq/feathercoin_core,FeatherCoin/Feathercoin,brightcoin/brightcoin,1185/starwels,ShwoognationHQ/bitcoin,viacoin/viacoin,goldcoin/Goldcoin-GLD,kryptokredyt/ProjektZespolowyCoin,cainca/liliucoin,error10/bitcoin,andres-root/bitcoinxt,kevin-cantwell/crunchcoin,balajinandhu/bitcoin,error10/bitcoin,bitgoldcoin-project/bitgoldcoin,isghe/bitcoinxt,mrbandrews/bitcoin,marlengit/BitcoinUnlimited,zsulocal/bitcoin,balajinandhu/bitcoin,bitcoinsSG/bitcoin,ashleyholman/bitcoin,royosherove/bitcoinxt,haobtc/bitcoin,TheBlueMatt/bitcoin,Justaphf/BitcoinUnlimited,antonio-fr/bitcoin,cheehieu/bitcoin,dpayne9000/Rubixz-Coin,TrainMAnB/vcoincore,litecoin-project/litecore-litecoin,coinerd/krugercoin,RazorLove/cloaked-octo-spice,szlaozhu/twister-core,earonesty/bitcoin,bitcoinxt/bitcoinxt,appop/bitcoin,nathaniel-mahieu/bitcoin,wellenreiter01/Feathercoin,48thct2jtnf/P,and2099/twister-core,WorldcoinGlobal/WorldcoinLegacy,kryptokredyt/ProjektZespolowyCoin,Bloom-Project/Bloom,simdeveloper/bitcoin,dperel/bitcoin,Flurbos/Flurbo,bitcoin/bitcoin,Rav3nPL/polcoin,truthcoin/truthcoin-cpp,qreatora/worldcoin-v0.8,krzysztofwos/BitcoinUnlimited,btc1/bitcoin,shaulkf/bitcoin,Climbee/artcoin,ctwiz/stardust,wellenreiter01/Feathercoin,kleetus/bitcoinxt,imton/bitcoin,lateminer/bitcoin,Christewart/bitcoin,bcpki/nonce2,Kogser/bitcoin,vtafaucet/virtacoin,Mrs-X/PIVX,lateminer/bitcoin,rat4/bitcoin,viacoin/viacoin,mycointest/owncoin,marcusdiaz/BitcoinUnlimited,reddcoin-project/reddcoin,collapsedev/circlecash,compasscoin/compasscoin,marlengit/hardfork_prototype_1_mvf-bu,gjhiggins/vcoin0.8zeta-dev,litecoin-project/bitcoinomg,jl2012/litecoin,shapiroisme/datadollar,KibiCoin/kibicoin,llluiop/bitcoin,world-bank/unpay-core,tropa/axecoin,simdeveloper/bitcoin,multicoins/marycoin,monacoinproject/monacoin,sugruedes/bitcoinxt,habibmasuro/bitcoin,stevemyers/bitcoinxt,AkioNak/bitcoin,Electronic-Gulden-Foundation/egulden,cerebrus29301/crowncoin,genavarov/ladacoin,reddcoin-project/reddcoin,Horrorcoin/horrorcoin,truthcoin/blocksize-market,multicoins/marycoin,KibiCoin/kibicoin,howardrya/AcademicCoin,BitcoinHardfork/bitcoin,BTCTaras/bitcoin,174high/bitcoin,bitjson/hivemind,kleetus/bitcoinxt,starwels/starwels,Bluejudy/worldcoin,ohac/sha1coin,coinkeeper/2015-06-22_19-13_florincoin,brishtiteveja/truthcoin-cpp,sbaks0820/bitcoin,rnicoll/bitcoin,okinc/bitcoin,Alonzo-Coeus/bitcoin,phelix/bitcoin,lclc/bitcoin,CoinProjects/AmsterdamCoin-v4,nathaniel-mahieu/bitcoin,kfitzgerald/titcoin,terracoin/terracoin,bcpki/nonce2,JeremyRand/namecoin-core,vtafaucet/virtacoin,tmagik/catcoin,oklink-dev/bitcoin_block,MonetaryUnit/MUE-Src,dannyperez/bolivarcoin,pelorusjack/BlockDX,GlobalBoost/GlobalBoost,bitjson/hivemind,crowning2/dash,dexX7/bitcoin,skaht/bitcoin,guncoin/guncoin,BenjaminsCrypto/Benjamins-1,starwels/starwels,cqtenq/feathercoin_core,2XL/bitcoin,dexX7/bitcoin,MazaCoin/maza,ryanxcharles/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,Kenwhite23/litecoin,putinclassic/putic,marlengit/hardfork_prototype_1_mvf-bu,borgcoin/Borgcoin.rar,StarbuckBG/BTCGPU,daveperkins-github/bitcoin-dev,pelorusjack/BlockDX,Friedbaumer/litecoin,bitpay/bitcoin,safecoin/safecoin,worldcoinproject/worldcoin-v0.8,Anoncoin/anoncoin,CodeShark/bitcoin,sirk390/bitcoin,ravenbyron/phtevencoin,40thoughts/Coin-QualCoin,sbaks0820/bitcoin,btcdrak/bitcoin,morcos/bitcoin,manuel-zulian/CoMoNet,wangxinxi/litecoin,n1bor/bitcoin,icook/vertcoin,misdess/bitcoin,gjhiggins/vcoincore,goku1997/bitcoin,kleetus/bitcoinxt,kevin-cantwell/crunchcoin,qubitcoin-project/QubitCoinQ2C,likecoin-dev/bitcoin,midnightmagic/bitcoin,cryptocoins4all/zcoin,markf78/dollarcoin,21E14/bitcoin,theuni/bitcoin,marlengit/BitcoinUnlimited,inutoshi/inutoshi,namecoin/namecoin-core,pataquets/namecoin-core,ryanofsky/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,totallylegitbiz/totallylegitcoin,vertcoin/vertcoin,inkvisit/sarmacoins,KibiCoin/kibicoin,sugruedes/bitcoin,Kixunil/keynescoin,mb300sd/bitcoin,safecoin/safecoin,truthcoin/truthcoin-cpp,nikkitan/bitcoin,lateminer/bitcoin,PRabahy/bitcoin,Vsync-project/Vsync,micryon/GPUcoin,Darknet-Crypto/Darknet,dogecoin/dogecoin,anditto/bitcoin,OfficialTitcoin/titcoin-wallet,joshrabinowitz/bitcoin,lclc/bitcoin,midnight-miner/LasVegasCoin,morcos/bitcoin,botland/bitcoin,DMDcoin/Diamond,coinkeeper/anoncoin_20150330_fixes,Petr-Economissa/gvidon,JeremyRubin/bitcoin,parvez3019/bitcoin,globaltoken/globaltoken,deadalnix/bitcoin,ahmedbodi/vertcoin,maaku/bitcoin,Petr-Economissa/gvidon,vericoin/vericoin-core,iosdevzone/bitcoin,elliotolds/bitcoin,pataquets/namecoin-core,Krellan/bitcoin,haraldh/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,taenaive/zetacoin,ionux/freicoin,sstone/bitcoin,jimmysong/bitcoin,jonasschnelli/bitcoin,sdaftuar/bitcoin,MonetaryUnit/MUE-Src,zsulocal/bitcoin,ClusterCoin/ClusterCoin,qtumproject/qtum,EthanHeilman/bitcoin,KaSt/ekwicoin,sipa/elements,basicincome/unpcoin-core,shurcoin/shurcoin,segsignal/bitcoin,greenaddress/bitcoin,REAP720801/bitcoin,steakknife/bitcoin-qt,mikehearn/bitcoinxt,tdudz/elements,gandrewstone/BitcoinUnlimited,bitcoin/bitcoin,jnewbery/bitcoin,pstratem/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,dgenr8/bitcoin,chrisfranko/aiden,mooncoin-project/mooncoin-landann,CTRoundTable/Encrypted.Cash,theuni/bitcoin,thelazier/dash,awemany/BitcoinUnlimited,error10/bitcoin,Kore-Core/kore,phelixbtc/bitcoin,millennial83/bitcoin,ixcoinofficialpage/master,jambolo/bitcoin,Horrorcoin/horrorcoin,Chancoin-core/CHANCOIN,Har01d/bitcoin,vmp32k/litecoin,Krellan/bitcoin,wiggi/huntercore,cmgustavo/bitcoin,zander/bitcoinclassic,dgarage/bc3,kevin-cantwell/crunchcoin,marcusdiaz/BitcoinUnlimited,brightcoin/brightcoin,NateBrune/bitcoin-nate,ShwoognationHQ/bitcoin,sugruedes/bitcoin,dan-mi-sun/bitcoin,lbrtcoin/albertcoin,xurantju/bitcoin,nanocoins/mycoin,cannabiscoindev/cannabiscoin420,Cloudsy/bitcoin,r8921039/bitcoin,goldcoin/Goldcoin-GLD,antonio-fr/bitcoin,hg5fm/nexuscoin,patricklodder/dogecoin,mruddy/bitcoin,leofidus/glowing-octo-ironman,jimmysong/bitcoin,ivansib/sib16,laudaa/bitcoin,Petr-Economissa/gvidon,AllanDoensen/BitcoinUnlimited,nailtaras/nailcoin,myriadteam/myriadcoin,jimblasko/UnbreakableCoin-master,totallylegitbiz/totallylegitcoin,goldmidas/goldmidas,ANCompany/birdcoin-dev,ZiftrCOIN/ziftrcoin,Sjors/bitcoin,kallewoof/bitcoin,nomnombtc/bitcoin,pouta/bitcoin,xeddmc/twister-core,ajtowns/bitcoin,fsb4000/bitcoin,laudaa/bitcoin,razor-coin/razor,ardsu/bitcoin,shurcoin/shurcoin,benma/bitcoin,Jcing95/iop-hd,genavarov/brcoin,Diapolo/bitcoin,NateBrune/bitcoin-fio,RHavar/bitcoin,shaulkf/bitcoin,cdecker/bitcoin,omefire/bitcoin,brandonrobertz/namecoin-core,tjps/bitcoin,dpayne9000/Rubixz-Coin,mapineda/litecoin,midnight-miner/LasVegasCoin,howardrya/AcademicCoin,mycointest/owncoin,antcheck/antcoin,Checkcoin/checkcoin,AdrianaDinca/bitcoin,slingcoin/sling-market,psionin/smartcoin,psionin/smartcoin,segsignal/bitcoin,nsacoin/nsacoin,cannabiscoindev/cannabiscoin420,brettwittam/geocoin,nightlydash/darkcoin,amaivsimau/bitcoin,hg5fm/nexuscoin,afk11/bitcoin,untrustbank/litecoin,svost/bitcoin,dogecoin/dogecoin,daliwangi/bitcoin,Horrorcoin/horrorcoin,Exgibichi/statusquo,zetacoin/zetacoin,jonghyeopkim/bitcoinxt,globaltoken/globaltoken,zcoinofficial/zcoin,shea256/bitcoin,RyanLucchese/energi,dmrtsvetkov/flowercoin,TGDiamond/Diamond,joulecoin/joulecoin,kryptokredyt/ProjektZespolowyCoin,psionin/smartcoin,bitcoin-hivemind/hivemind,PIVX-Project/PIVX,BitcoinHardfork/bitcoin,jarymoth/dogecoin,djpnewton/bitcoin,segsignal/bitcoin,karek314/bitcoin,kallewoof/bitcoin,Ziftr/bitcoin,mrbandrews/bitcoin,isocolsky/bitcoinxt,rebroad/bitcoin,tjps/bitcoin,josephbisch/namecoin-core,imton/bitcoin,NateBrune/bitcoin-fio,karek314/bitcoin,apoelstra/elements,GlobalBoost/GlobalBoost,janko33bd/bitcoin,droark/bitcoin,novaexchange/EAC,djpnewton/bitcoin,cyrixhero/bitcoin,Carrsy/PoundCoin,phplaboratory/psiacoin,FarhanHaque/bitcoin,gravio-net/graviocoin,madman5844/poundkoin,globaltoken/globaltoken,sstone/bitcoin,r8921039/bitcoin,florincoin/florincoin,djpnewton/bitcoin,welshjf/bitcoin,capitalDIGI/litecoin,phplaboratory/psiacoin,cryptocoins4all/zcoin,kevcooper/bitcoin,jgarzik/bitcoin,langerhans/dogecoin,starwalkerz/fincoin-fork,zetacoin/zetacoin,therealaltcoin/altcoin,dexX7/mastercore,xieta/mincoin,jl2012/litecoin,superjudge/bitcoin,KnCMiner/bitcoin,coinkeeper/2015-06-22_19-19_worldcoin,BitzenyCoreDevelopers/bitzeny,JeremyRand/bitcoin,meighti/bitcoin,bitcoin-hivemind/hivemind,untrustbank/litecoin,UASF/bitcoin,zenywallet/bitzeny,DynamicCoinOrg/DMC,gandrewstone/bitcoinxt,Checkcoin/checkcoin,dperel/bitcoin,gazbert/bitcoin,jonghyeopkim/bitcoinxt,zestcoin/ZESTCOIN,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,ahmedbodi/vertcoin,truthcoin/truthcoin-cpp,elliotolds/bitcoin,Carrsy/PoundCoin,drwasho/bitcoinxt,raasakh/bardcoin,schinzelh/dash,KnCMiner/bitcoin,isghe/bitcoinxt,faircoin/faircoin,particl/particl-core,petertodd/bitcoin,droark/elements,zotherstupidguy/bitcoin,cyrixhero/bitcoin,Rav3nPL/doubloons-08,Cancercoin/Cancercoin,benma/bitcoin,yenliangl/bitcoin,shadowoneau/ozcoin,2XL/bitcoin,bitcoinec/bitcoinec,vlajos/bitcoin,webdesignll/coin,rebroad/bitcoin,manuel-zulian/CoMoNet,zottejos/merelcoin,jtimon/elements,experiencecoin/experiencecoin,gjhiggins/vcoincore,steakknife/bitcoin-qt,gavinandresen/bitcoin-git,benzmuircroft/REWIRE.io,Rav3nPL/PLNcoin,BenjaminsCrypto/Benjamins-1,dgarage/bc2,CrimeaCoin/crimeacoin,174high/bitcoin,zetacoin/zetacoin,richo/dongcoin,coinkeeper/2015-06-22_18-30_anoncoin,robvanbentem/bitcoin,Litecoindark/LTCD,shapiroisme/datadollar,EthanHeilman/bitcoin,mincoin-project/mincoin,fanquake/bitcoin,gcc64/bitcoin,bitpay/bitcoin,r8921039/bitcoin,zzkt/solarcoin,ravenbyron/phtevencoin,Adaryian/E-Currency,dogecoin/dogecoin,aniemerg/zcash,mobicoins/mobicoin-core,grumpydevelop/singularity,atgreen/bitcoin,barcoin-project/nothingcoin,domob1812/bitcoin,jmgilbert2/energi,xuyangcn/opalcoin,pdrobek/Polcoin-1-3,vericoin/vericoin-core,shea256/bitcoin,octocoin-project/octocoin,worldcoinproject/worldcoin-v0.8,matlongsi/micropay,DigiByte-Team/digibyte,tripmode/pxlcoin,czr5014iph/bitcoin4e,antcheck/antcoin,syscoin/syscoin,ftrader-bitcoinabc/bitcoin-abc,dannyperez/bolivarcoin,coinkeeper/2015-06-22_19-13_florincoin,irvingruan/bitcoin,faircoin/faircoin,coinkeeper/2015-06-22_18-37_dogecoin,mobicoins/mobicoin-core,manuel-zulian/accumunet,Petr-Economissa/gvidon,borgcoin/Borgcoin1,dperel/bitcoin,Erkan-Yilmaz/twister-core,Chancoin-core/CHANCOIN,JeremyRubin/bitcoin,AkioNak/bitcoin,nightlydash/darkcoin,OmniLayer/omnicore,adpg211/bitcoin-master,DrCrypto/darkcoin,dan-mi-sun/bitcoin,randy-waterhouse/bitcoin,HeliumGas/helium,sugruedes/bitcoinxt,bitcoinknots/bitcoin,Climbee/artcoin,LIMXTEC/DMDv3,tedlz123/Bitcoin,DGCDev/argentum,puticcoin/putic,isghe/bitcoinxt,Theshadow4all/ShadowCoin,drwasho/bitcoinxt,pstratem/elements,truthcoin/blocksize-market,misdess/bitcoin,vlajos/bitcoin,hophacker/bitcoin_malleability,FinalHashLLC/namecore,Cancercoin/Cancercoin,ajtowns/bitcoin,Alex-van-der-Peet/bitcoin,Jcing95/iop-hd,Jcing95/iop-hd,sarielsaz/sarielsaz,jgarzik/bitcoin,ANCompany/birdcoin-dev,alexandrcoin/vertcoin,Czarcoin/czarcoin,ronpaulcoin/ronpaulcoin,peerdb/cors,faircoin/faircoin2,nikkitan/bitcoin,Carrsy/PoundCoin,Kenwhite23/litecoin,prusnak/bitcoin,rawodb/bitcoin,KaSt/equikoin,crowning2/dash,AkioNak/bitcoin,neutrinofoundation/neutrino-digital-currency,isghe/bitcoinxt,Tetpay/bitcoin,jakeva/bitcoin-pwcheck,xuyangcn/opalcoin,jtimon/bitcoin,simdeveloper/bitcoin,RibbitFROG/ribbitcoin,RazorLove/cloaked-octo-spice,Friedbaumer/litecoin,tdudz/elements,skaht/bitcoin,m0gliE/fastcoin-cli,jnewbery/bitcoin,rdqw/sscoin,coinkeeper/2015-06-22_18-56_megacoin,micryon/GPUcoin,LIMXTEC/DMDv3,robvanbentem/bitcoin,lbrtcoin/albertcoin,ivansib/sib16,neuroidss/bitcoin,stamhe/bitcoin,jarymoth/dogecoin,diggcoin/diggcoin,hsavit1/bitcoin,cddjr/BitcoinUnlimited,franko-org/franko,ravenbyron/phtevencoin,Mrs-X/PIVX,gameunits/gameunits,metrocoins/metrocoin,vtafaucet/virtacoin,nathan-at-least/zcash,aspanta/bitcoin,vcoin-project/vcoincore,majestrate/twister-core,BTCDDev/bitcoin,ryanxcharles/bitcoin,x-kalux/bitcoin_WiG-B,mockcoin/mockcoin,osuyuushi/laughingmancoin,habibmasuro/bitcoin,Metronotes/bitcoin,GreenParhelia/bitcoin,xeddmc/twister-core,collapsedev/circlecash,denverl/bitcoin,BTCDDev/bitcoin,ionomy/ion,Vsync-project/Vsync,shaulkf/bitcoin,Czarcoin/czarcoin,gmaxwell/bitcoin,ColossusCoinXT/ColossusCoinXT,segsignal/bitcoin,ivansib/sib16,balajinandhu/bitcoin,pdrobek/Polcoin-1-3,PRabahy/bitcoin,OmniLayer/omnicore,robvanbentem/bitcoin,kfitzgerald/titcoin,taenaive/zetacoin,midnightmagic/bitcoin,mikehearn/bitcoinxt,richo/dongcoin,Earlz/renamedcoin,RHavar/bitcoin,marscoin/marscoin,droark/bitcoin,Cancercoin/Cancercoin,itmanagerro/tresting,cannabiscoindev/cannabiscoin420,ludbb/bitcoin,cyrixhero/bitcoin,UASF/bitcoin,syscoin/syscoin2,Bitcoin-com/BUcash,millennial83/bitcoin,ravenbyron/phtevencoin,alejandromgk/Lunar,vertcoin/eyeglass,paveljanik/bitcoin,PRabahy/bitcoin,world-bank/unpay-core,p2peace/oliver-twister-core,nathan-at-least/zcash,nomnombtc/bitcoin,earonesty/bitcoin,gjhiggins/vcoincore,xawksow/GroestlCoin,acid1789/bitcoin,bcpki/testblocks,wangliu/bitcoin,GlobalBoost/GlobalBoost,faircoin/faircoin2,JeremyRand/namecore,Christewart/bitcoin,habibmasuro/bitcoinxt,CarpeDiemCoin/CarpeDiemLaunch,DogTagRecon/Still-Leraning,ingresscoin/ingresscoin,bitcoinknots/bitcoin,richo/dongcoin,saydulk/Feathercoin,ppcoin/ppcoin,brishtiteveja/sherlockcoin,Bitcoin-com/BUcash,keisercoin-official/keisercoin,kirkalx/bitcoin,chaincoin/chaincoin,syscoin/syscoin,jonghyeopkim/bitcoinxt,laudaa/bitcoin,pelorusjack/BlockDX,romanornr/viacoin,bitcoin-hivemind/hivemind,x-kalux/bitcoin_WiG-B,theuni/bitcoin,particl/particl-core,cryptodev35/icash,meighti/bitcoin,bitcoinplusorg/xbcwalletsource,zsulocal/bitcoin,dan-mi-sun/bitcoin,prusnak/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,razor-coin/razor,jrmithdobbs/bitcoin,bitreserve/bitcoin,ElementsProject/elements,Kcoin-project/kcoin,gjhiggins/fuguecoin,brishtiteveja/truthcoin-cpp,ElementsProject/elements,scmorse/bitcoin,stamhe/bitcoin,FrictionlessCoin/iXcoin,miguelfreitas/twister-core,cybermatatu/bitcoin,cculianu/bitcoin-abc,BlockchainTechLLC/3dcoin,tecnovert/particl-core,shomeser/bitcoin,gandrewstone/bitcoinxt,Gazer022/bitcoin,MeshCollider/bitcoin,gwillen/elements,NicolasDorier/bitcoin,jaromil/faircoin2,bittylicious/bitcoin,paveljanik/bitcoin,nmarley/dash,and2099/twister-core,pataquets/namecoin-core,kallewoof/elements,bitcoinplusorg/xbcwalletsource,daliwangi/bitcoin,vtafaucet/virtacoin,Alex-van-der-Peet/bitcoin,jiffe/cosinecoin,digibyte/digibyte,ShadowMyst/creativechain-core,cinnamoncoin/groupcoin-1,shomeser/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,oklink-dev/bitcoin,haisee/dogecoin,btc1/bitcoin,pastday/bitcoinproject,h4x3rotab/BTCGPU,cdecker/bitcoin,Dinarcoin/dinarcoin,brandonrobertz/namecoin-core,rustyrussell/bitcoin,capitalDIGI/litecoin,supcoin/supcoin,kleetus/bitcoinxt,ShwoognationHQ/bitcoin,marscoin/marscoin,Earlz/dobbscoin-source,mycointest/owncoin,KaSt/equikoin,Cocosoft/bitcoin,netswift/vertcoin,brandonrobertz/namecoin-core,presstab/PIVX,neutrinofoundation/neutrino-digital-currency,koharjidan/bitcoin,phelixbtc/bitcoin,s-matthew-english/bitcoin,Kogser/bitcoin,kevcooper/bitcoin,millennial83/bitcoin,GroundRod/anoncoin,Flurbos/Flurbo,cryptodev35/icash,qtumproject/qtum,plncoin/PLNcoin_Core,robvanbentem/bitcoin,plankton12345/litecoin,KnCMiner/bitcoin,blocktrail/bitcoin,terracoin/terracoin,daliwangi/bitcoin,nanocoins/mycoin,RyanLucchese/energi,error10/bitcoin,IlfirinCano/shavercoin,therealaltcoin/altcoin,kseistrup/twister-core,bespike/litecoin,ludbb/bitcoin,ahmedbodi/test2,CryptArc/bitcoinxt,memorycoin/memorycoin,Flowdalic/bitcoin,tensaix2j/bananacoin,wcwu/bitcoin,jaromil/faircoin2,szlaozhu/twister-core,coinwarp/dogecoin,cinnamoncoin/Feathercoin,cqtenq/Feathercoin,cannabiscoindev/cannabiscoin420,GIJensen/bitcoin,111t8e/bitcoin,11755033isaprimenumber/Feathercoin,KillerByte/memorypool,syscoin/syscoin,droark/elements,axelxod/braincoin,48thct2jtnf/P,genavarov/brcoin,cotner/bitcoin,putinclassic/putic,Chancoin-core/CHANCOIN,djpnewton/bitcoin,KnCMiner/bitcoin,Rav3nPL/bitcoin,osuyuushi/laughingmancoin,coinkeeper/2015-06-22_18-46_razor,matlongsi/micropay,sickpig/BitcoinUnlimited,odemolliens/bitcoinxt,imton/bitcoin,benma/bitcoin,ShadowMyst/creativechain-core,achow101/bitcoin,anditto/bitcoin,BlockchainTechLLC/3dcoin,sifcoin/sifcoin,se3000/bitcoin,Climbee/artcoin,irvingruan/bitcoin,gameunits/gameunits,MeshCollider/bitcoin,TierNolan/bitcoin,jeromewu/bitcoin-opennet,Diapolo/bitcoin,Checkcoin/checkcoin,coinkeeper/2015-06-22_18-52_viacoin,pstratem/bitcoin,dakk/soundcoin,11755033isaprimenumber/Feathercoin,fsb4000/bitcoin,argentumproject/argentum,imton/bitcoin,joroob/reddcoin,Jeff88Ho/bitcoin,111t8e/bitcoin,jarymoth/dogecoin,XertroV/bitcoin-nulldata,vbernabe/freicoin,m0gliE/fastcoin-cli,Adaryian/E-Currency,BTCfork/hardfork_prototype_1_mvf-bu,botland/bitcoin,my-first/octocoin,Xekyo/bitcoin,UASF/bitcoin,stevemyers/bitcoinxt,fanquake/bitcoin,xurantju/bitcoin,bitcoinec/bitcoinec,brishtiteveja/truthcoin-cpp,simdeveloper/bitcoin,midnight-miner/LasVegasCoin,steakknife/bitcoin-qt,brishtiteveja/sherlockholmescoin,nathaniel-mahieu/bitcoin,afk11/bitcoin,tjth/lotterycoin,dev1972/Satellitecoin,phplaboratory/psiacoin,superjudge/bitcoin,keo/bitcoin,mb300sd/bitcoin,syscoin/syscoin,CrimeaCoin/crimeacoin,elliotolds/bitcoin,dev1972/Satellitecoin,gandrewstone/BitcoinUnlimited,GroestlCoin/bitcoin,kaostao/bitcoin,ftrader-bitcoinabc/bitcoin-abc,cryptcoins/cryptcoin,guncoin/guncoin,MarcoFalke/bitcoin,alejandromgk/Lunar,llamasoft/ProtoShares_Cycle,jn2840/bitcoin,lbrtcoin/albertcoin,matlongsi/micropay,bitreserve/bitcoin,kazcw/bitcoin,ShwoognationHQ/bitcoin,itmanagerro/tresting,bdelzell/creditcoin-org-creditcoin,litecoin-project/bitcoinomg,haraldh/bitcoin,practicalswift/bitcoin,saydulk/Feathercoin,rustyrussell/bitcoin,segwit/atbcoin-insight,Enticed87/Decipher,unsystemizer/bitcoin,miguelfreitas/twister-core,amaivsimau/bitcoin,constantine001/bitcoin,qtumproject/qtum,jamesob/bitcoin,thrasher-/litecoin,aspanta/bitcoin,mm-s/bitcoin,jn2840/bitcoin,gwangjin2/gwangcoin-core,ludbb/bitcoin,11755033isaprimenumber/Feathercoin,deeponion/deeponion,Rav3nPL/polcoin,mb300sd/bitcoin,dexX7/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,EthanHeilman/bitcoin,coinkeeper/anoncoin_20150330_fixes,arruah/ensocoin,elecoin/elecoin,oleganza/bitcoin-duo,gwillen/elements,coinerd/krugercoin,dscotese/bitcoin,accraze/bitcoin,ahmedbodi/temp_vert,Rav3nPL/doubloons-08,karek314/bitcoin,marcusdiaz/BitcoinUnlimited,bitcoinsSG/bitcoin,namecoin/namecoin-core,TBoehm/greedynode,ctwiz/stardust,zemrys/vertcoin,tuaris/bitcoin,bmp02050/ReddcoinUpdates,LIMXTEC/DMDv3,benosa/bitcoin,leofidus/glowing-octo-ironman,torresalyssa/bitcoin,florincoin/florincoin,truthcoin/blocksize-market,netswift/vertcoin,jtimon/elements,JeremyRand/bitcoin,bcpki/nonce2testblocks,cyrixhero/bitcoin,llluiop/bitcoin,ryanofsky/bitcoin,scmorse/bitcoin,mrbandrews/bitcoin,TGDiamond/Diamond,cqtenq/feathercoin_core,ClusterCoin/ClusterCoin,coinkeeper/2015-06-22_19-07_digitalcoin,maaku/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,Sjors/bitcoin,tuaris/bitcoin,jiffe/cosinecoin,goldcoin/goldcoin,franko-org/franko,oleganza/bitcoin-duo,EntropyFactory/creativechain-core,gwangjin2/gwangcoin-core,senadmd/coinmarketwatch,dgarage/bc3,UFOCoins/ufo,bcpki/nonce2testblocks,111t8e/bitcoin,inutoshi/inutoshi,stamhe/bitcoin,dmrtsvetkov/flowercoin,peercoin/peercoin,Mirobit/bitcoin,imharrywu/fastcoin,kfitzgerald/titcoin,40thoughts/Coin-QualCoin,bitcoinec/bitcoinec,kaostao/bitcoin,icook/vertcoin,grumpydevelop/singularity,jtimon/bitcoin,GIJensen/bitcoin,raasakh/bardcoin,bcpki/nonce2,neutrinofoundation/neutrino-digital-currency,practicalswift/bitcoin,schinzelh/dash,isle2983/bitcoin,nathaniel-mahieu/bitcoin,pastday/bitcoinproject,peerdb/cors,xurantju/bitcoin,deuscoin/deuscoin,Lucky7Studio/bitcoin,Darknet-Crypto/Darknet,mastercoin-MSC/mastercore,nsacoin/nsacoin,lakepay/lake,awemany/BitcoinUnlimited,goldmidas/goldmidas,joshrabinowitz/bitcoin,rromanchuk/bitcoinxt,NateBrune/bitcoin-nate,dexX7/bitcoin,richo/dongcoin,zixan/bitcoin,elecoin/elecoin,atgreen/bitcoin,projectinterzone/ITZ,sugruedes/bitcoin,neutrinofoundation/neutrino-digital-currency,sipsorcery/bitcoin,bcpki/nonce2testblocks,midnightmagic/bitcoin,KibiCoin/kibicoin,coinkeeper/2015-06-22_18-39_feathercoin,jiangyonghang/bitcoin,cybermatatu/bitcoin,fujicoin/fujicoin,denverl/bitcoin,omefire/bitcoin,RyanLucchese/energi,TierNolan/bitcoin,jambolo/bitcoin,projectinterzone/ITZ,domob1812/i0coin,Rav3nPL/polcoin,dcousens/bitcoin,DGCDev/digitalcoin,ghostlander/Feathercoin,Lucky7Studio/bitcoin,TripleSpeeder/bitcoin,neuroidss/bitcoin,rdqw/sscoin,BitcoinPOW/BitcoinPOW,ivansib/sib16,sebrandon1/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,coinkeeper/2015-06-22_18-46_razor,inkvisit/sarmacoins,coinkeeper/megacoin_20150410_fixes,renatolage/wallets-BRCoin,XertroV/bitcoin-nulldata,Michagogo/bitcoin,BenjaminsCrypto/Benjamins-1,zebrains/Blotter,kleetus/bitcoin,Kenwhite23/litecoin,brettwittam/geocoin,totallylegitbiz/totallylegitcoin,nmarley/dash,knolza/gamblr,PIVX-Project/PIVX,miguelfreitas/twister-core,GroundRod/anoncoin,gavinandresen/bitcoin-git,hyperwang/bitcoin,worldcoinproject/worldcoin-v0.8,mammix2/ccoin-dev,oklink-dev/bitcoin,qubitcoin-project/QubitCoinQ2C,cryptodev35/icash,Ziftr/litecoin,CTRoundTable/Encrypted.Cash,BTCTaras/bitcoin,Rav3nPL/polcoin,gavinandresen/bitcoin-git,butterflypay/bitcoin,Kangmo/bitcoin,stevemyers/bitcoinxt,droark/bitcoin,faircoin/faircoin,plncoin/PLNcoin_Core,dagurval/bitcoinxt,gzuser01/zetacoin-bitcoin,apoelstra/elements,p2peace/oliver-twister-core,zestcoin/ZESTCOIN,joshrabinowitz/bitcoin,united-scrypt-coin-project/unitedscryptcoin,marcusdiaz/BitcoinUnlimited,tuaris/bitcoin,and2099/twister-core,irvingruan/bitcoin,gmaxwell/bitcoin,ixcoinofficialpage/master,DGCDev/digitalcoin,earthcoinproject/earthcoin,aniemerg/zcash,Krellan/bitcoin,riecoin/riecoin,metacoin/florincoin,Bitcoin-ABC/bitcoin-abc,KaSt/ekwicoin,MitchellMintCoins/MortgageCoin,xawksow/GroestlCoin,droark/bitcoin,themusicgod1/bitcoin,ediston/energi,segsignal/bitcoin,nailtaras/nailcoin,donaloconnor/bitcoin,raasakh/bardcoin.exe,apoelstra/bitcoin,11755033isaprimenumber/Feathercoin,Thracky/monkeycoin,ahmedbodi/vertcoin,Rav3nPL/doubloons-08,markf78/dollarcoin,greencoin-dev/digitalcoin,ahmedbodi/test2,nailtaras/nailcoin,acid1789/bitcoin,faircoin/faircoin2,mycointest/owncoin,cdecker/bitcoin,anditto/bitcoin,kryptokredyt/ProjektZespolowyCoin,Richcoin-Project/RichCoin,qreatora/worldcoin-v0.8,WorldLeadCurrency/WLC,applecoin-official/applecoin,cotner/bitcoin,initaldk/bitcoin,koharjidan/bitcoin,mockcoin/mockcoin,marlengit/hardfork_prototype_1_mvf-bu,nathan-at-least/zcash,marlengit/BitcoinUnlimited,jameshilliard/bitcoin,kseistrup/twister-core,chaincoin/chaincoin,ohac/sha1coin,Bushstar/UFO-Project,rnicoll/bitcoin,s-matthew-english/bitcoin,cdecker/bitcoin,practicalswift/bitcoin,marklai9999/Taiwancoin,zsulocal/bitcoin,cannabiscoindev/cannabiscoin420,roques/bitcoin,AdrianaDinca/bitcoin,ahmedbodi/terracoin,cqtenq/Feathercoin,freelion93/mtucicoin,whatrye/twister-core,balajinandhu/bitcoin,cotner/bitcoin,nanocoins/mycoin,axelxod/braincoin,iosdevzone/bitcoin,DogTagRecon/Still-Leraning,ArgonToken/ArgonToken,butterflypay/bitcoin,robvanbentem/bitcoin,zemrys/vertcoin,pstratem/bitcoin,starwels/starwels,DGCDev/digitalcoin,netswift/vertcoin,kseistrup/twister-core,HashUnlimited/Einsteinium-Unlimited,prusnak/bitcoin,mrtexaznl/mediterraneancoin,jmcorgan/bitcoin,pstratem/bitcoin,fullcoins/fullcoin,tuaris/bitcoin,tensaix2j/bananacoin,m0gliE/fastcoin-cli,wekuiz/wekoin,okinc/litecoin,ZiftrCOIN/ziftrcoin,111t8e/bitcoin,Mirobit/bitcoin,sickpig/BitcoinUnlimited,pinkevich/dash,rjshaver/bitcoin,EntropyFactory/creativechain-core,borgcoin/Borgcoin1,paveljanik/bitcoin,projectinterzone/ITZ,supcoin/supcoin,senadmd/coinmarketwatch,Erkan-Yilmaz/twister-core,wiggi/huntercore,knolza/gamblr,ColossusCoinXT/ColossusCoinXT,amaivsimau/bitcoin,hsavit1/bitcoin,DGCDev/argentum,bespike/litecoin,EntropyFactory/creativechain-core,phelixbtc/bitcoin,JeremyRand/namecore,gwillen/elements,48thct2jtnf/P,simonmulser/bitcoin,sbaks0820/bitcoin,fujicoin/fujicoin,rawodb/bitcoin,Flowdalic/bitcoin,pstratem/elements,thesoftwarejedi/bitcoin,marscoin/marscoin,TeamBitBean/bitcoin-core,bitpay/bitcoin,zander/bitcoinclassic,schildbach/bitcoin,joulecoin/joulecoin,zander/bitcoinclassic,h4x3rotab/BTCGPU,martindale/elements,freelion93/mtucicoin,btc1/bitcoin,mapineda/litecoin,hsavit1/bitcoin,sebrandon1/bitcoin,ericshawlinux/bitcoin,aniemerg/zcash,destenson/bitcoin--bitcoin,ryanxcharles/bitcoin,ghostlander/Feathercoin,habibmasuro/bitcoinxt,ElementsProject/elements,namecoin/namecore,chaincoin/chaincoin,tmagik/catcoin,bitreserve/bitcoin,scamcoinz/scamcoin,ftrader-bitcoinabc/bitcoin-abc,dagurval/bitcoinxt,Ziftr/litecoin,oklink-dev/litecoin_block,dpayne9000/Rubixz-Coin,UASF/bitcoin,gapcoin/gapcoin,afk11/bitcoin,Megacoin2/Megacoin,syscoin/syscoin,oklink-dev/bitcoin_block,raasakh/bardcoin.exe,thesoftwarejedi/bitcoin,CoinProjects/AmsterdamCoin-v4,sipsorcery/bitcoin,putinclassic/putic,funkshelper/woodcoin-b,cqtenq/feathercoin_core,erqan/twister-core,TrainMAnB/vcoincore,practicalswift/bitcoin,degenorate/Deftcoin,sipsorcery/bitcoin,aburan28/elements,MikeAmy/bitcoin,steakknife/bitcoin-qt,jimmysong/bitcoin,denverl/bitcoin,Kixunil/keynescoin,simonmulser/bitcoin,cryptohelper/premine,thelazier/dash,destenson/bitcoin--bitcoin,starwels/starwels,RHavar/bitcoin,scippio/bitcoin,my-first/octocoin,schinzelh/dash,DSPay/DSPay,midnight-miner/LasVegasCoin,Anfauglith/iop-hd,neuroidss/bitcoin,NunoEdgarGub1/elements,bankonmecoin/bitcoin,aniemerg/zcash,myriadteam/myriadcoin,cryptcoins/cryptcoin,Erkan-Yilmaz/twister-core,raasakh/bardcoin.exe,Ziftr/bitcoin,sipsorcery/bitcoin,nigeriacoin/nigeriacoin,npccoin/npccoin,Sjors/bitcoin,slingcoin/sling-market,apoelstra/elements,jonasnick/bitcoin,dev1972/Satellitecoin,Electronic-Gulden-Foundation/egulden,GIJensen/bitcoin,JeremyRand/bitcoin,bitpagar/bitpagar,habibmasuro/bitcoin,phelix/namecore,bitcoinec/bitcoinec,sipa/bitcoin,shomeser/bitcoin,coinkeeper/2015-06-22_18-41_ixcoin,Xekyo/bitcoin,shelvenzhou/BTCGPU,OfficialTitcoin/titcoin-wallet,uphold/bitcoin,GwangJin/gwangmoney-core,biblepay/biblepay,zcoinofficial/zcoin,bankonmecoin/bitcoin,sbellem/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,dcousens/bitcoin,gapcoin/gapcoin,nbenoit/bitcoin,hyperwang/bitcoin,BTCGPU/BTCGPU,BitcoinHardfork/bitcoin,Coinfigli/coinfigli,freelion93/mtucicoin,BitzenyCoreDevelopers/bitzeny,janko33bd/bitcoin,acid1789/bitcoin,experiencecoin/experiencecoin,mm-s/bitcoin,BTCGPU/BTCGPU,antcheck/antcoin,hophacker/bitcoin_malleability,DigitalPandacoin/pandacoin,mitchellcash/bitcoin,cryptodev35/icash,Dinarcoin/dinarcoin,superjudge/bitcoin,Kixunil/keynescoin,vcoin-project/vcoincore,appop/bitcoin,truthcoin/blocksize-market,ohac/sakuracoin,sipa/elements,mruddy/bitcoin,ahmedbodi/test2,mooncoin-project/mooncoin-landann,xawksow/GroestlCoin,willwray/dash,jimblasko/UnbreakableCoin-master,bdelzell/creditcoin-org-creditcoin,tecnovert/particl-core,xeddmc/twister-core,cculianu/bitcoin-abc,ptschip/bitcoin,butterflypay/bitcoin,gazbert/bitcoin,capitalDIGI/DIGI-v-0-10-4,ripper234/bitcoin,ixcoinofficialpage/master,shapiroisme/datadollar,IlfirinIlfirin/shavercoin,FarhanHaque/bitcoin,jrmithdobbs/bitcoin,Exgibichi/statusquo,40thoughts/Coin-QualCoin,phelix/bitcoin,Bushstar/UFO-Project,Chancoin-core/CHANCOIN,MasterX1582/bitcoin-becoin,bittylicious/bitcoin,jlopp/statoshi,jrmithdobbs/bitcoin,domob1812/namecore,brightcoin/brightcoin,plankton12345/litecoin,jimmykiselak/lbrycrd,CodeShark/bitcoin,cqtenq/Feathercoin,fsb4000/bitcoin,majestrate/twister-core,svost/bitcoin,bitcoinsSG/zcash,coinkeeper/2015-06-22_19-00_ziftrcoin,applecoin-official/fellatio,dgenr8/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,nsacoin/nsacoin,cryptoprojects/ultimateonlinecash,cryptoprojects/ultimateonlinecash,my-first/octocoin,MeshCollider/bitcoin,namecoin/namecore,shadowoneau/ozcoin,btc1/bitcoin,Litecoindark/LTCD,funbucks/notbitcoinxt,particl/particl-core,Darknet-Crypto/Darknet,sdaftuar/bitcoin,zetacoin/zetacoin,DSPay/DSPay,markf78/dollarcoin,jl2012/litecoin,OstlerDev/florincoin,Justaphf/BitcoinUnlimited,blood2/bloodcoin-0.9,bitcoinxt/bitcoinxt,coinkeeper/2015-06-22_18-41_ixcoin,kallewoof/elements,digibyte/digibyte,n1bor/bitcoin,digibyte/digibyte,sipa/bitcoin,Vsync-project/Vsync,nikkitan/bitcoin,maaku/bitcoin,zottejos/merelcoin,zsulocal/bitcoin,metrocoins/metrocoin,gzuser01/zetacoin-bitcoin,memorycoin/memorycoin,guncoin/guncoin,haisee/dogecoin,donaloconnor/bitcoin,rat4/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,RyanLucchese/energi,BitcoinHardfork/bitcoin,keesdewit82/LasVegasCoin,jgarzik/bitcoin,royosherove/bitcoinxt,reddink/reddcoin,bitcoinsSG/bitcoin,bitcoinplusorg/xbcwalletsource,SocialCryptoCoin/SocialCoin,thrasher-/litecoin,Cloudsy/bitcoin,haisee/dogecoin,dgenr8/bitcoin,NunoEdgarGub1/elements,reorder/viacoin,lbryio/lbrycrd,xeddmc/twister-core,Flowdalic/bitcoin,gandrewstone/bitcoinxt,maraoz/proofcoin,jamesob/bitcoin,ArgonToken/ArgonToken,bitcoinsSG/zcash,bitbrazilcoin-project/bitbrazilcoin,balajinandhu/bitcoin,Rav3nPL/bitcoin,gjhiggins/fuguecoin,oleganza/bitcoin-duo,Rav3nPL/doubloons-08,mikehearn/bitcoin,kfitzgerald/titcoin,Alonzo-Coeus/bitcoin,cinnamoncoin/groupcoin-1,SoreGums/bitcoinxt,m0gliE/fastcoin-cli,josephbisch/namecoin-core,TrainMAnB/vcoincore,kirkalx/bitcoin,dashpay/dash,BigBlueCeiling/augmentacoin,kazcw/bitcoin,cerebrus29301/crowncoin,jakeva/bitcoin-pwcheck,ptschip/bitcoin,Dajackal/Ronpaulcoin,dscotese/bitcoin,llamasoft/ProtoShares_Cycle,Justaphf/BitcoinUnlimited,DMDcoin/Diamond,GroestlCoin/GroestlCoin,hyperwang/bitcoin,bitcoinsSG/zcash,torresalyssa/bitcoin,ohac/sha1coin,Anfauglith/iop-hd,markf78/dollarcoin,ahmedbodi/temp_vert,manuel-zulian/accumunet,domob1812/i0coin,Bitcoin-ABC/bitcoin-abc,coinkeeper/2015-06-22_18-52_viacoin,tripmode/pxlcoin,Metronotes/bitcoin,cmgustavo/bitcoin,vmp32k/litecoin,Christewart/bitcoin,safecoin/safecoin,greencoin-dev/digitalcoin,axelxod/braincoin,BTCDDev/bitcoin,okinc/bitcoin,ahmedbodi/test2,prusnak/bitcoin,supcoin/supcoin,benzmuircroft/REWIRE.io,BTCTaras/bitcoin,metacoin/florincoin,aniemerg/zcash,nmarley/dash,xuyangcn/opalcoin,ftrader-bitcoinabc/bitcoin-abc,faircoin/faircoin2,DSPay/DSPay,denverl/bitcoin,prark/bitcoinxt,NateBrune/bitcoin-nate,stamhe/litecoin,Chancoin-core/CHANCOIN,domob1812/i0coin,wcwu/bitcoin,ronpaulcoin/ronpaulcoin,anditto/bitcoin,ftrader-bitcoinabc/bitcoin-abc,monacoinproject/monacoin,ekankyesme/bitcoinxt,starwalkerz/fincoin-fork,Kogser/bitcoin,achow101/bitcoin,united-scrypt-coin-project/unitedscryptcoin,bespike/litecoin,mm-s/bitcoin,ronpaulcoin/ronpaulcoin,Coinfigli/coinfigli,OstlerDev/florincoin,Har01d/bitcoin,shea256/bitcoin,rjshaver/bitcoin,earonesty/bitcoin,plankton12345/litecoin,BlockchainTechLLC/3dcoin,EthanHeilman/bitcoin,donaloconnor/bitcoin,likecoin-dev/bitcoin,bitcoin/bitcoin,apoelstra/bitcoin,cryptohelper/premine,Czarcoin/czarcoin,ptschip/bitcoin,Kogser/bitcoin,erqan/twister-core,MazaCoin/mazacoin-new,jimblasko/2015_UNB_Wallets,ArgonToken/ArgonToken,freelion93/mtucicoin,FrictionlessCoin/iXcoin,cinnamoncoin/groupcoin-1,Mirobit/bitcoin,mikehearn/bitcoin,xawksow/GroestlCoin,schildbach/bitcoin,guncoin/guncoin,mm-s/bitcoin,pastday/bitcoinproject,sipa/elements,deadalnix/bitcoin,bitjson/hivemind,Cocosoft/bitcoin,Horrorcoin/horrorcoin,CoinProjects/AmsterdamCoin-v4,BenjaminsCrypto/Benjamins-1,dgarage/bc2,psionin/smartcoin,Lucky7Studio/bitcoin,ediston/energi,kirkalx/bitcoin,szlaozhu/twister-core,OstlerDev/florincoin,AllanDoensen/BitcoinUnlimited,greencoin-dev/digitalcoin,manuel-zulian/CoMoNet,ghostlander/Feathercoin,coinkeeper/2015-06-22_19-19_worldcoin,oklink-dev/litecoin_block,blood2/bloodcoin-0.9,h4x3rotab/BTCGPU,practicalswift/bitcoin,174high/bitcoin,hasanatkazmi/bitcoin,ericshawlinux/bitcoin,therealaltcoin/altcoin,m0gliE/fastcoin-cli,fedoracoin-dev/fedoracoin,ColossusCoinXT/ColossusCoinXT,keisercoin-official/keisercoin,petertodd/bitcoin,nathaniel-mahieu/bitcoin,apoelstra/elements,Flurbos/Flurbo,coinkeeper/2015-06-22_18-31_bitcoin,bootycoin-project/bootycoin,phelix/bitcoin,oklink-dev/litecoin_block,genavarov/ladacoin,dan-mi-sun/bitcoin,okinc/litecoin,gwangjin2/gwangcoin-core,awemany/BitcoinUnlimited,domob1812/namecore,coinkeeper/2015-06-22_18-51_vertcoin,BTCTaras/bitcoin,barcoin-project/nothingcoin,MazaCoin/maza,coinkeeper/2015-06-22_18-41_ixcoin,megacoin/megacoin,marlengit/hardfork_prototype_1_mvf-bu,PIVX-Project/PIVX,m0gliE/fastcoin-cli,WorldLeadCurrency/WLC,stevemyers/bitcoinxt,vericoin/vericoin-core,marcusdiaz/BitcoinUnlimited,ccoin-project/ccoin,wangliu/bitcoin,Mrs-X/Darknet,cerebrus29301/crowncoin,marlengit/hardfork_prototype_1_mvf-bu,UdjinM6/dash,mitchellcash/bitcoin,isocolsky/bitcoinxt,trippysalmon/bitcoin,mm-s/bitcoin,nmarley/dash,Bluejudy/worldcoin,rdqw/sscoin,x-kalux/bitcoin_WiG-B,ajweiss/bitcoin,gjhiggins/vcoin0.8zeta-dev,Cocosoft/bitcoin,Exgibichi/statusquo,litecoin-project/litecoin,MitchellMintCoins/AutoCoin,jmcorgan/bitcoin,upgradeadvice/MUE-Src,taenaive/zetacoin,rjshaver/bitcoin,Bitcoin-ABC/bitcoin-abc,rnicoll/dogecoin,czr5014iph/bitcoin4e,denverl/bitcoin,Bushstar/UFO-Project,willwray/dash,111t8e/bitcoin,btc1/bitcoin,argentumproject/argentum,PandaPayProject/PandaPay,kevcooper/bitcoin,FeatherCoin/Feathercoin,Xekyo/bitcoin,kleetus/bitcoinxt,keo/bitcoin,bitcoinec/bitcoinec,bitcoinclassic/bitcoinclassic,saydulk/Feathercoin,DigitalPandacoin/pandacoin,viacoin/viacoin,Flurbos/Flurbo,Bluejudy/worldcoin,genavarov/brcoin,peerdb/cors,funkshelper/woodcore,spiritlinxl/BTCGPU,pastday/bitcoinproject,rjshaver/bitcoin,shaolinfry/litecoin,dogecoin/dogecoin,MazaCoin/mazacoin-new,Darknet-Crypto/Darknet,willwray/dash,koharjidan/bitcoin,ColossusCoinXT/ColossusCoinXT,fanquake/bitcoin,MikeAmy/bitcoin,gandrewstone/bitcoinxt,pouta/bitcoin,gjhiggins/fuguecoin,genavarov/ladacoin,whatrye/twister-core,ccoin-project/ccoin,TBoehm/greedynode,bmp02050/ReddcoinUpdates,fujicoin/fujicoin,Kore-Core/kore,shaolinfry/litecoin,IlfirinCano/shavercoin,wangliu/bitcoin,leofidus/glowing-octo-ironman,benosa/bitcoin,manuel-zulian/accumunet,majestrate/twister-core,Rav3nPL/PLNcoin,nomnombtc/bitcoin,Jeff88Ho/bitcoin,unsystemizer/bitcoin,se3000/bitcoin,braydonf/bitcoin,DigiByte-Team/digibyte,coinkeeper/2015-06-22_18-37_dogecoin,trippysalmon/bitcoin,thelazier/dash,totallylegitbiz/totallylegitcoin,diggcoin/diggcoin,sarielsaz/sarielsaz,privatecoin/privatecoin,octocoin-project/octocoin,core-bitcoin/bitcoin,aspanta/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,benzmuircroft/REWIRE.io,BitzenyCoreDevelopers/bitzeny,krzysztofwos/BitcoinUnlimited,kseistrup/twister-core,keisercoin-official/keisercoin,accraze/bitcoin,zotherstupidguy/bitcoin,bitbrazilcoin-project/bitbrazilcoin,gzuser01/zetacoin-bitcoin,applecoin-official/fellatio,sipsorcery/bitcoin,SartoNess/BitcoinUnlimited,earonesty/bitcoin,florincoin/florincoin,fedoracoin-dev/fedoracoin,rawodb/bitcoin,likecoin-dev/bitcoin,marklai9999/Taiwancoin,BigBlueCeiling/augmentacoin,nathan-at-least/zcash,Bushstar/UFO-Project,BitcoinUnlimited/BitcoinUnlimited,RongxinZhang/bitcoinxt,Kogser/bitcoin,5mil/Tradecoin,Bushstar/UFO-Project,JeremyRand/bitcoin,ccoin-project/ccoin,petertodd/bitcoin,BitcoinPOW/BitcoinPOW,reorder/viacoin,ediston/energi,bootycoin-project/bootycoin,MitchellMintCoins/AutoCoin,misdess/bitcoin,digideskio/namecoin,sugruedes/bitcoin,masterbraz/dg,habibmasuro/bitcoin,zixan/bitcoin,GroestlCoin/GroestlCoin,174high/bitcoin,qtumproject/qtum,gavinandresen/bitcoin-git,coinkeeper/2015-06-22_18-51_vertcoin,DynamicCoinOrg/DMC,joroob/reddcoin,scippio/bitcoin,ahmedbodi/temp_vert,amaivsimau/bitcoin,ludbb/bitcoin,mikehearn/bitcoinxt,pdrobek/Polcoin-1-3,bankonmecoin/bitcoin,jn2840/bitcoin,JeremyRand/namecoin-core,icook/vertcoin,greencoin-dev/greencoin-dev,faircoin/faircoin,GreenParhelia/bitcoin,coinkeeper/2015-06-22_19-13_florincoin,BTCfork/hardfork_prototype_1_mvf-core,elliotolds/bitcoin,DGCDev/argentum,faircoin/faircoin,prusnak/bitcoin,apoelstra/bitcoin,lbrtcoin/albertcoin,jakeva/bitcoin-pwcheck,ionomy/ion,nanocoins/mycoin,Gazer022/bitcoin,XertroV/bitcoin-nulldata,Christewart/bitcoin,Alonzo-Coeus/bitcoin,sugruedes/bitcoin,trippysalmon/bitcoin,saydulk/Feathercoin,wederw/bitcoin,nlgcoin/guldencoin-official,aburan28/elements,jeromewu/bitcoin-opennet,bespike/litecoin,droark/bitcoin,vcoin-project/vcoin0.8zeta-dev,jimmykiselak/lbrycrd,kaostao/bitcoin,multicoins/marycoin,czr5014iph/bitcoin4e,bitcoinec/bitcoinec,40thoughts/Coin-QualCoin,ANCompany/birdcoin-dev,DSPay/DSPay,janko33bd/bitcoin,jakeva/bitcoin-pwcheck,vmp32k/litecoin,spiritlinxl/BTCGPU,applecoin-official/fellatio,brandonrobertz/namecoin-core,1185/starwels,willwray/dash,biblepay/biblepay,madman5844/poundkoin,enlighter/Feathercoin,vlajos/bitcoin,Metronotes/bitcoin,degenorate/Deftcoin,kfitzgerald/titcoin,ajweiss/bitcoin,tjth/lotterycoin,MazaCoin/mazacoin-new,hyperwang/bitcoin,Gazer022/bitcoin,nikkitan/bitcoin,Mrs-X/PIVX,thesoftwarejedi/bitcoin,metacoin/florincoin,mb300sd/bitcoin,goku1997/bitcoin,NateBrune/bitcoin-fio,Kcoin-project/kcoin,vertcoin/vertcoin,wcwu/bitcoin,GwangJin/gwangmoney-core,cculianu/bitcoin-abc,bitshares/bitshares-pts,schinzelh/dash,basicincome/unpcoin-core,OstlerDev/florincoin,capitalDIGI/DIGI-v-0-10-4,shadowoneau/ozcoin,llluiop/bitcoin,sstone/bitcoin,riecoin/riecoin,bitcoinknots/bitcoin,accraze/bitcoin,isocolsky/bitcoinxt,majestrate/twister-core,patricklodder/dogecoin,JeremyRubin/bitcoin,RHavar/bitcoin,Kore-Core/kore,jimblasko/UnbreakableCoin-master,thesoftwarejedi/bitcoin,puticcoin/putic,digideskio/namecoin,kaostao/bitcoin,jeromewu/bitcoin-opennet,tjps/bitcoin,pelorusjack/BlockDX,martindale/elements,Gazer022/bitcoin,dexX7/bitcoin,putinclassic/putic,BTCfork/hardfork_prototype_1_mvf-core,kevcooper/bitcoin,pinheadmz/bitcoin,parvez3019/bitcoin,dcousens/bitcoin,ivansib/sibcoin,namecoin/namecore,REAP720801/bitcoin,Tetcoin/tetcoin,deeponion/deeponion,faircoin/faircoin2,jnewbery/bitcoin,coinkeeper/megacoin_20150410_fixes,patricklodder/dogecoin,collapsedev/circlecash,cddjr/BitcoinUnlimited,KaSt/ekwicoin,1185/starwels,truthcoin/truthcoin-cpp,CoinProjects/AmsterdamCoin-v4,manuel-zulian/accumunet,TheBlueMatt/bitcoin,terracoin/terracoin,webdesignll/coin,oklink-dev/bitcoin_block,NicolasDorier/bitcoin,coinkeeper/2015-06-22_18-51_vertcoin,oklink-dev/litecoin_block,ashleyholman/bitcoin,pinkevich/dash,nigeriacoin/nigeriacoin,UdjinM6/dash,plncoin/PLNcoin_Core,RibbitFROG/ribbitcoin,jimblasko/UnbreakableCoin-master,bitshares/bitshares-pts,btcdrak/bitcoin,shouhuas/bitcoin,and2099/twister-core,rustyrussell/bitcoin,dgarage/bc2,midnightmagic/bitcoin,Erkan-Yilmaz/twister-core,IlfirinIlfirin/shavercoin,bitcoinxt/bitcoinxt,cinnamoncoin/Feathercoin,wellenreiter01/Feathercoin,aspirecoin/aspire,osuyuushi/laughingmancoin,Dajackal/Ronpaulcoin,presstab/PIVX,pascalguru/florincoin,domob1812/namecore,lclc/bitcoin,ryanxcharles/bitcoin,ionomy/ion,supcoin/supcoin,itmanagerro/tresting,Ziftr/bitcoin,prark/bitcoinxt,daliwangi/bitcoin,cculianu/bitcoin-abc,JeremyRand/bitcoin,vbernabe/freicoin,ekankyesme/bitcoinxt,lbrtcoin/albertcoin,goku1997/bitcoin,tmagik/catcoin,dgenr8/bitcoinxt,MasterX1582/bitcoin-becoin,pdrobek/Polcoin-1-3,xawksow/GroestlCoin,TeamBitBean/bitcoin-core,domob1812/bitcoin,Jeff88Ho/bitcoin,crowning-/dash,leofidus/glowing-octo-ironman,dperel/bitcoin,cheehieu/bitcoin,fedoracoin-dev/fedoracoin,alecalve/bitcoin,iQcoin/iQcoin,StarbuckBG/BTCGPU,leofidus/glowing-octo-ironman,bcpki/testblocks,lbrtcoin/albertcoin,dpayne9000/Rubixz-Coin,credits-currency/credits,ArgonToken/ArgonToken,cmgustavo/bitcoin,nlgcoin/guldencoin-official,worldbit/worldbit,JeremyRubin/bitcoin,fanquake/bitcoin,coinwarp/dogecoin,DigitalPandacoin/pandacoin,zzkt/solarcoin,coinkeeper/2015-06-22_18-30_anoncoin,blocktrail/bitcoin,iosdevzone/bitcoin,experiencecoin/experiencecoin,habibmasuro/bitcoinxt,sebrandon1/bitcoin,keisercoin-official/keisercoin,namecoin/namecoin-core,RongxinZhang/bitcoinxt,alecalve/bitcoin,HeliumGas/helium,XertroV/bitcoin-nulldata,pstratem/elements,syscoin/syscoin2,reorder/viacoin,coinkeeper/2015-06-22_19-19_worldcoin,pinheadmz/bitcoin,djpnewton/bitcoin,haraldh/bitcoin,21E14/bitcoin,goldcoin/Goldcoin-GLD,basicincome/unpcoin-core,MeshCollider/bitcoin,sbellem/bitcoin,AllanDoensen/BitcoinUnlimited,vbernabe/freicoin,jimblasko/2015_UNB_Wallets,myriadcoin/myriadcoin,Har01d/bitcoin,collapsedev/cashwatt,petertodd/bitcoin,enlighter/Feathercoin,botland/bitcoin,greencoin-dev/greencoin-dev,Friedbaumer/litecoin,inkvisit/sarmacoins,langerhans/dogecoin,FeatherCoin/Feathercoin,ivansib/sibcoin,MasterX1582/bitcoin-becoin,simonmulser/bitcoin,webdesignll/coin,Rav3nPL/PLNcoin,applecoin-official/applecoin,AllanDoensen/BitcoinUnlimited,wiggi/huntercore,xuyangcn/opalcoin,UASF/bitcoin,hasanatkazmi/bitcoin,PIVX-Project/PIVX,irvingruan/bitcoin,therealaltcoin/altcoin,Dinarcoin/dinarcoin,bmp02050/ReddcoinUpdates,aciddude/Feathercoin,Tetpay/bitcoin,CTRoundTable/Encrypted.Cash,pascalguru/florincoin,wekuiz/wekoin,MonetaryUnit/MUE-Src,krzysztofwos/BitcoinUnlimited,itmanagerro/tresting,RongxinZhang/bitcoinxt,Michagogo/bitcoin,Alonzo-Coeus/bitcoin,novaexchange/EAC,ohac/sha1coin,qreatora/worldcoin-v0.8,shea256/bitcoin,jimmysong/bitcoin,Domer85/dogecoin,Adaryian/E-Currency,mobicoins/mobicoin-core,gavinandresen/bitcoin-git,sugruedes/bitcoinxt,mooncoin-project/mooncoin-landann,reorder/viacoin,Gazer022/bitcoin,kbccoin/kbc,cculianu/bitcoin-abc,privatecoin/privatecoin,gmaxwell/bitcoin,TripleSpeeder/bitcoin,sstone/bitcoin,krzysztofwos/BitcoinUnlimited,novaexchange/EAC,ludbb/bitcoin,collapsedev/cashwatt,peerdb/cors,renatolage/wallets-BRCoin,bitcoinsSG/bitcoin,coinkeeper/2015-06-22_18-46_razor,ClusterCoin/ClusterCoin,mammix2/ccoin-dev,kirkalx/bitcoin,simonmulser/bitcoin,atgreen/bitcoin,dagurval/bitcoinxt,nlgcoin/guldencoin-official,Lucky7Studio/bitcoin,thrasher-/litecoin,ryanofsky/bitcoin,Exceltior/dogecoin,KaSt/ekwicoin,Electronic-Gulden-Foundation/egulden,HashUnlimited/Einsteinium-Unlimited,droark/elements,Mirobit/bitcoin,inutoshi/inutoshi,NateBrune/bitcoin-fio,XX-net/twister-core,unsystemizer/bitcoin,crowning-/dash,cdecker/bitcoin,capitalDIGI/litecoin,pascalguru/florincoin,ajweiss/bitcoin,Erkan-Yilmaz/twister-core,langerhans/dogecoin,bitcoin/bitcoin,Exgibichi/statusquo,mincoin-project/mincoin,GlobalBoost/GlobalBoost,guncoin/guncoin,rawodb/bitcoin,ddombrowsky/radioshares,dashpay/dash,Bitcoinsulting/bitcoinxt,joroob/reddcoin,aspirecoin/aspire,octocoin-project/octocoin,nathan-at-least/zcash,antonio-fr/bitcoin,memorycoin/memorycoin,lbryio/lbrycrd,goldcoin/goldcoin,genavarov/lamacoin,crowning-/dash,dgenr8/bitcoinxt,TrainMAnB/vcoincore,capitalDIGI/DIGI-v-0-10-4,coinkeeper/megacoin_20150410_fixes,destenson/bitcoin--bitcoin,DynamicCoinOrg/DMC,bitreserve/bitcoin,bcpki/nonce2testblocks,bitcoin-hivemind/hivemind,Rav3nPL/doubloons-08,zcoinofficial/zcoin,Kangmo/bitcoin,okinc/bitcoin,jeromewu/bitcoin-opennet,bitjson/hivemind,wederw/bitcoin,SocialCryptoCoin/SocialCoin,zebrains/Blotter,janko33bd/bitcoin,h4x3rotab/BTCGPU,bitcoinclassic/bitcoinclassic,BigBlueCeiling/augmentacoin,gandrewstone/bitcoinxt,mycointest/owncoin,pinkevich/dash,barcoin-project/nothingcoin,sipa/bitcoin,sipa/elements,myriadcoin/myriadcoin,gjhiggins/fuguecoin,ZiftrCOIN/ziftrcoin,FarhanHaque/bitcoin,nigeriacoin/nigeriacoin,Rav3nPL/polcoin,aniemerg/zcash,JeremyRand/namecoin-core,kevin-cantwell/crunchcoin,TGDiamond/Diamond,bitcoin/bitcoin,zebrains/Blotter,imharrywu/fastcoin,goldcoin/Goldcoin-GLD,axelxod/braincoin,dgenr8/bitcoin,DogTagRecon/Still-Leraning,npccoin/npccoin,goku1997/bitcoin,funkshelper/woodcoin-b,ashleyholman/bitcoin,wtogami/bitcoin,aciddude/Feathercoin,habibmasuro/bitcoin,ptschip/bitcoin,funkshelper/woodcoin-b,jmgilbert2/energi,Earlz/dobbscoin-source,goku1997/bitcoin,syscoin/syscoin,Alonzo-Coeus/bitcoin,ekankyesme/bitcoinxt,mobicoins/mobicoin-core,elecoin/elecoin,crowning2/dash,ajtowns/bitcoin,rromanchuk/bitcoinxt,degenorate/Deftcoin,Rav3nPL/doubloons-0.10,koharjidan/litecoin,cotner/bitcoin,cryptcoins/cryptcoin,REAP720801/bitcoin,dannyperez/bolivarcoin,jamesob/bitcoin,botland/bitcoin,reddcoin-project/reddcoin,phelix/namecore,zestcoin/ZESTCOIN,wbchen99/bitcoin-hnote0,pouta/bitcoin,romanornr/viacoin,bitjson/hivemind,novaexchange/EAC,blocktrail/bitcoin,bitreserve/bitcoin,Har01d/bitcoin,loxal/zcash,ajweiss/bitcoin,rat4/bitcoin,OstlerDev/florincoin,btcdrak/bitcoin,dogecoin/dogecoin,odemolliens/bitcoinxt,masterbraz/dg,EntropyFactory/creativechain-core,llluiop/bitcoin,core-bitcoin/bitcoin,osuyuushi/laughingmancoin,lbrtcoin/albertcoin,collapsedev/cashwatt,rebroad/bitcoin,shaolinfry/litecoin,rawodb/bitcoin,mycointest/owncoin,jl2012/litecoin,MitchellMintCoins/MortgageCoin,domob1812/bitcoin,kevcooper/bitcoin,XX-net/twister-core,coinkeeper/2015-06-22_19-07_digitalcoin,bankonmecoin/bitcoin,Bitcoin-ABC/bitcoin-abc,Kogser/bitcoin,torresalyssa/bitcoin,bootycoin-project/bootycoin,Exgibichi/statusquo,PIVX-Project/PIVX,Dajackal/Ronpaulcoin,BTCDDev/bitcoin,REAP720801/bitcoin,totallylegitbiz/totallylegitcoin,litecoin-project/litecore-litecoin,ardsu/bitcoin,WorldcoinGlobal/WorldcoinLegacy,keo/bitcoin,Jeff88Ho/bitcoin,goldmidas/goldmidas,parvez3019/bitcoin,wbchen99/bitcoin-hnote0,Carrsy/PoundCoin,zander/bitcoinclassic,itmanagerro/tresting,mb300sd/bitcoin,Anoncoin/anoncoin,slingcoin/sling-market,patricklodder/dogecoin,coinkeeper/2015-06-22_18-31_bitcoin,fussl/elements,dgenr8/bitcoinxt,peercoin/peercoin,ftrader-bitcoinabc/bitcoin-abc,BlockchainTechLLC/3dcoin,coinkeeper/2015-06-22_18-37_dogecoin,enlighter/Feathercoin,coinkeeper/2015-06-22_18-30_anoncoin,Cloudsy/bitcoin,Kixunil/keynescoin,SocialCryptoCoin/SocialCoin,uphold/bitcoin,nailtaras/nailcoin,Exceltior/dogecoin,s-matthew-english/bitcoin,DogTagRecon/Still-Leraning,untrustbank/litecoin,jamesob/bitcoin,axelxod/braincoin,Bitcoin-com/BUcash,dagurval/bitcoinxt,denverl/bitcoin,lbrtcoin/albertcoin,FinalHashLLC/namecore,ryanofsky/bitcoin,gazbert/bitcoin,dperel/bitcoin,accraze/bitcoin,111t8e/bitcoin,haisee/dogecoin,roques/bitcoin,nbenoit/bitcoin,zander/bitcoinclassic,mitchellcash/bitcoin,knolza/gamblr,hyperwang/bitcoin,misdess/bitcoin,syscoin/syscoin2,sugruedes/bitcoinxt,Gazer022/bitcoin,FarhanHaque/bitcoin,dgarage/bc3,Vector2000/bitcoin,tropa/axecoin,earthcoinproject/earthcoin,Theshadow4all/ShadowCoin,ludbb/bitcoin,cainca/liliucoin,starwalkerz/fincoin-fork,AdrianaDinca/bitcoin,fullcoins/fullcoin,Vector2000/bitcoin,Justaphf/BitcoinUnlimited,dobbscoin/dobbscoin-source,Bitcoinsulting/bitcoinxt,vertcoin/vertcoin,madman5844/poundkoin,ptschip/bitcoin,ftrader-bitcoinabc/bitcoin-abc,arnuschky/bitcoin,amaivsimau/bitcoin,monacoinproject/monacoin,peercoin/peercoin,BTCDDev/bitcoin,ptschip/bitcoinxt,ahmedbodi/test2,dagurval/bitcoinxt,qtumproject/qtum,CryptArc/bitcoin,s-matthew-english/bitcoin,Tetpay/bitcoin,genavarov/lamacoin,rnicoll/bitcoin,starwels/starwels,AllanDoensen/BitcoinUnlimited,DSPay/DSPay,Bloom-Project/Bloom,error10/bitcoin,pataquets/namecoin-core,octocoin-project/octocoin,mruddy/bitcoin,NateBrune/bitcoin-nate,sarielsaz/sarielsaz,brishtiteveja/truthcoin-cpp,kleetus/bitcoin,nvmd/bitcoin,domob1812/i0coin,PandaPayProject/PandaPay,drwasho/bitcoinxt,NateBrune/bitcoin-nate,Kogser/bitcoin,vmp32k/litecoin,domob1812/huntercore,NateBrune/bitcoin-fio,dashpay/dash,lclc/bitcoin,knolza/gamblr,BitzenyCoreDevelopers/bitzeny,XX-net/twister-core,EntropyFactory/creativechain-core,TBoehm/greedynode,jiangyonghang/bitcoin,tdudz/elements,Bitcoin-ABC/bitcoin-abc,Cocosoft/bitcoin,chaincoin/chaincoin,riecoin/riecoin,fedoracoin-dev/fedoracoin,cddjr/BitcoinUnlimited,marscoin/marscoin,vcoin-project/vcoincore,ashleyholman/bitcoin,wellenreiter01/Feathercoin,gcc64/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,Anfauglith/iop-hd,braydonf/bitcoin,reorder/viacoin,h4x3rotab/BTCGPU,yenliangl/bitcoin,arnuschky/bitcoin,XertroV/bitcoin-nulldata,keo/bitcoin,andreaskern/bitcoin,kallewoof/bitcoin,EthanHeilman/bitcoin,hasanatkazmi/bitcoin,szlaozhu/twister-core,mrbandrews/bitcoin,dmrtsvetkov/flowercoin,koharjidan/litecoin,greenaddress/bitcoin,litecoin-project/litecoin,koharjidan/litecoin,Flowdalic/bitcoin,renatolage/wallets-BRCoin,oklink-dev/bitcoin,dgenr8/bitcoin,wtogami/bitcoin,brishtiteveja/sherlockholmescoin,UFOCoins/ufo,cannabiscoindev/cannabiscoin420,cryptohelper/premine,Thracky/monkeycoin,kallewoof/bitcoin,prark/bitcoinxt,NicolasDorier/bitcoin,greenaddress/bitcoin,HeliumGas/helium,Mrs-X/Darknet,FarhanHaque/bitcoin,vbernabe/freicoin,kseistrup/twister-core,zottejos/merelcoin,parvez3019/bitcoin,zsulocal/bitcoin,ryanofsky/bitcoin,MazaCoin/maza,jambolo/bitcoin,domob1812/i0coin,lbryio/lbrycrd,ptschip/bitcoinxt,PIVX-Project/PIVX,jmgilbert2/energi,coinkeeper/2015-06-22_19-07_digitalcoin,ohac/sakuracoin,Justaphf/BitcoinUnlimited,capitalDIGI/litecoin,nbenoit/bitcoin,CrimeaCoin/crimeacoin,gjhiggins/vcoincore,midnightmagic/bitcoin,kallewoof/elements,oklink-dev/litecoin_block,scmorse/bitcoin,genavarov/brcoin,parvez3019/bitcoin,zebrains/Blotter,funkshelper/woodcore,andreaskern/bitcoin,GroestlCoin/GroestlCoin,sbellem/bitcoin,Kogser/bitcoin,greencoin-dev/digitalcoin,npccoin/npccoin,MazaCoin/mazacoin-new,lakepay/lake,dpayne9000/Rubixz-Coin,BTCGPU/BTCGPU,itmanagerro/tresting,JeremyRand/namecoin-core,pstratem/elements,jiffe/cosinecoin,thelazier/dash,kirkalx/bitcoin,ajweiss/bitcoin,ColossusCoinXT/ColossusCoinXT,bitshares/bitshares-pts,czr5014iph/bitcoin4e,coinkeeper/2015-06-22_18-52_viacoin,lateminer/bitcoin,vertcoin/eyeglass,capitalDIGI/litecoin,cryptocoins4all/zcoin,bickojima/bitzeny,plankton12345/litecoin,worldcoinproject/worldcoin-v0.8,coinkeeper/2015-06-22_18-56_megacoin,NunoEdgarGub1/elements,gandrewstone/BitcoinUnlimited,mastercoin-MSC/mastercore,willwray/dash,Adaryian/E-Currency,ahmedbodi/temp_vert,sstone/bitcoin,ardsu/bitcoin,NateBrune/bitcoin-fio,jiangyonghang/bitcoin,xawksow/GroestlCoin,sarielsaz/sarielsaz,haraldh/bitcoin,RongxinZhang/bitcoinxt,sickpig/BitcoinUnlimited,coinkeeper/2015-06-22_18-46_razor,thormuller/yescoin2,accraze/bitcoin,tdudz/elements,bickojima/bitzeny,se3000/bitcoin,ghostlander/Feathercoin,senadmd/coinmarketwatch,brishtiteveja/sherlockholmescoin,dev1972/Satellitecoin,myriadteam/myriadcoin,fullcoins/fullcoin,wiggi/huntercore,alejandromgk/Lunar,grumpydevelop/singularity,cryptoprojects/ultimateonlinecash,brishtiteveja/sherlockholmescoin,svost/bitcoin,coinkeeper/2015-06-22_18-56_megacoin,bittylicious/bitcoin,blood2/bloodcoin-0.9,maraoz/proofcoin,jtimon/elements,gameunits/gameunits,riecoin/riecoin,core-bitcoin/bitcoin,bitpay/bitcoin,Diapolo/bitcoin,zixan/bitcoin,acid1789/bitcoin,imharrywu/fastcoin,fussl/elements,bittylicious/bitcoin,magacoin/magacoin,joulecoin/joulecoin,AdrianaDinca/bitcoin,borgcoin/Borgcoin.rar,DynamicCoinOrg/DMC,bitbrazilcoin-project/bitbrazilcoin,argentumproject/argentum,40thoughts/Coin-QualCoin,manuel-zulian/accumunet,peercoin/peercoin,jrick/bitcoin,MarcoFalke/bitcoin,vlajos/bitcoin,zcoinofficial/zcoin,scmorse/bitcoin,MeshCollider/bitcoin,goku1997/bitcoin,odemolliens/bitcoinxt,Dajackal/Ronpaulcoin,rromanchuk/bitcoinxt,credits-currency/credits,namecoin/namecoin-core,Coinfigli/coinfigli,TheBlueMatt/bitcoin,jaromil/faircoin2,ryanofsky/bitcoin,nailtaras/nailcoin,WorldLeadCurrency/WLC,OmniLayer/omnicore,aburan28/elements,dakk/soundcoin,CryptArc/bitcoin,coinkeeper/megacoin_20150410_fixes,amaivsimau/bitcoin,initaldk/bitcoin,capitalDIGI/DIGI-v-0-10-4,segsignal/bitcoin,hsavit1/bitcoin,bitpagar/bitpagar,jakeva/bitcoin-pwcheck,Diapolo/bitcoin,mrtexaznl/mediterraneancoin,zemrys/vertcoin,benosa/bitcoin,OmniLayer/omnicore,namecoin/namecoin-core,cheehieu/bitcoin,NicolasDorier/bitcoin,pstratem/bitcoin,pdrobek/Polcoin-1-3,rsdevgun16e/energi,genavarov/brcoin,StarbuckBG/BTCGPU,funbucks/notbitcoinxt,domob1812/huntercore,biblepay/biblepay,ElementsProject/elements,royosherove/bitcoinxt,zestcoin/ZESTCOIN,Richcoin-Project/RichCoin,ryanxcharles/bitcoin,meighti/bitcoin,whatrye/twister-core,cybermatatu/bitcoin,TeamBitBean/bitcoin-core,peacedevelop/peacecoin,stamhe/bitcoin,Vsync-project/Vsync,ANCompany/birdcoin-dev,ericshawlinux/bitcoin,petertodd/bitcoin,pinheadmz/bitcoin,gravio-net/graviocoin,ptschip/bitcoin,matlongsi/micropay,cybermatatu/bitcoin,isghe/bitcoinxt,magacoin/magacoin,collapsedev/cashwatt,WorldLeadCurrency/WLC,wbchen99/bitcoin-hnote0,lclc/bitcoin,segwit/atbcoin-insight,coinkeeper/2015-06-22_18-41_ixcoin,p2peace/oliver-twister-core,arruah/ensocoin,KillerByte/memorypool,zottejos/merelcoin,ElementsProject/elements,jgarzik/bitcoin,WorldLeadCurrency/WLC,grumpydevelop/singularity,lateminer/bitcoin,KillerByte/memorypool,therealaltcoin/altcoin,mobicoins/mobicoin-core,TripleSpeeder/bitcoin,okinc/litecoin,laudaa/bitcoin,bitcoinclassic/bitcoinclassic,loxal/zcash,enlighter/Feathercoin,sipa/bitcoin,Sjors/bitcoin,Bitcoinsulting/bitcoinxt,Theshadow4all/ShadowCoin,PandaPayProject/PandaPay,oleganza/bitcoin-duo,kleetus/bitcoin,bickojima/bitzeny,nbenoit/bitcoin,fujicoin/fujicoin,BTCGPU/BTCGPU,magacoin/magacoin,maaku/bitcoin,jiangyonghang/bitcoin,emc2foundation/einsteinium,coinkeeper/2015-06-22_18-51_vertcoin,se3000/bitcoin,bitcoinsSG/zcash,gcc64/bitcoin,mikehearn/bitcoin,FrictionlessCoin/iXcoin,nlgcoin/guldencoin-official,ionux/freicoin,mb300sd/bitcoin,Kangmo/bitcoin,ripper234/bitcoin,Krellan/bitcoin,zcoinofficial/zcoin,torresalyssa/bitcoin,earonesty/bitcoin,keesdewit82/LasVegasCoin,daveperkins-github/bitcoin-dev,brandonrobertz/namecoin-core,pinkevich/dash,xurantju/bitcoin,thrasher-/litecoin,richo/dongcoin,Bitcoin-com/BUcash,collapsedev/circlecash,droark/elements,rromanchuk/bitcoinxt,schinzelh/dash,raasakh/bardcoin,ptschip/bitcoinxt,Exceltior/dogecoin,tmagik/catcoin,nlgcoin/guldencoin-official,braydonf/bitcoin,Michagogo/bitcoin,Theshadow4all/ShadowCoin,joshrabinowitz/bitcoin,ohac/sakuracoin,projectinterzone/ITZ,ShwoognationHQ/bitcoin,hasanatkazmi/bitcoin,brishtiteveja/sherlockcoin,nvmd/bitcoin,BTCTaras/bitcoin,pinheadmz/bitcoin,rebroad/bitcoin,wekuiz/wekoin,psionin/smartcoin,haisee/dogecoin,stamhe/litecoin,ZiftrCOIN/ziftrcoin,BitcoinUnlimited/BitcoinUnlimited,dexX7/mastercore,ddombrowsky/radioshares,RHavar/bitcoin,rromanchuk/bitcoinxt,sirk390/bitcoin,kazcw/bitcoin,Earlz/renamedcoin,micryon/GPUcoin,sbellem/bitcoin,ahmedbodi/vertcoin,coinkeeper/2015-06-22_18-36_darkcoin,GroestlCoin/bitcoin,kbccoin/kbc,FinalHashLLC/namecore,reddcoin-project/reddcoin,rat4/bitcoin,glv2/peerunity,Michagogo/bitcoin,shelvenzhou/BTCGPU,mikehearn/bitcoinxt,AkioNak/bitcoin,BTCGPU/BTCGPU,jonghyeopkim/bitcoinxt,CTRoundTable/Encrypted.Cash,gcc64/bitcoin,jonasschnelli/bitcoin,Rav3nPL/doubloons-0.10,x-kalux/bitcoin_WiG-B,antonio-fr/bitcoin,funkshelper/woodcoin-b,xieta/mincoin,bitcoinplusorg/xbcwalletsource,Domer85/dogecoin,arruah/ensocoin,CTRoundTable/Encrypted.Cash,dakk/soundcoin,zzkt/solarcoin,BTCDDev/bitcoin,dakk/soundcoin,mastercoin-MSC/mastercore,gmaxwell/bitcoin,zcoinofficial/zcoin,jameshilliard/bitcoin,Earlz/renamedcoin,Sjors/bitcoin,particl/particl-core,ivansib/sibcoin,Cloudsy/bitcoin,shomeser/bitcoin,vcoin-project/vcoin0.8zeta-dev,Bloom-Project/Bloom,spiritlinxl/BTCGPU,rustyrussell/bitcoin,MarcoFalke/bitcoin,AkioNak/bitcoin,cheehieu/bitcoin,Erkan-Yilmaz/twister-core,renatolage/wallets-BRCoin,benzmuircroft/REWIRE.io,themusicgod1/bitcoin,reorder/viacoin,jmcorgan/bitcoin,phelixbtc/bitcoin,willwray/dash,MazaCoin/mazacoin-new,shaolinfry/litecoin,morcos/bitcoin,TrainMAnB/vcoincore,syscoin/syscoin,langerhans/dogecoin,mrbandrews/bitcoin,andreaskern/bitcoin,alexandrcoin/vertcoin,neuroidss/bitcoin,loxal/zcash,isocolsky/bitcoinxt,vlajos/bitcoin,qubitcoin-project/QubitCoinQ2C,SocialCryptoCoin/SocialCoin,xurantju/bitcoin,RibbitFROG/ribbitcoin,digideskio/namecoin,apoelstra/bitcoin,borgcoin/Borgcoin1,shouhuas/bitcoin,and2099/twister-core,ajtowns/bitcoin,blocktrail/bitcoin,CoinProjects/AmsterdamCoin-v4,genavarov/ladacoin,Earlz/dobbscoin-source,cinnamoncoin/Feathercoin,BTCfork/hardfork_prototype_1_mvf-bu,domob1812/namecore,ZiftrCOIN/ziftrcoin,coinkeeper/anoncoin_20150330_fixes,emc2foundation/einsteinium,braydonf/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,ediston/energi,goldmidas/goldmidas,cinnamoncoin/groupcoin-1,bitcoinxt/bitcoinxt,instagibbs/bitcoin,cqtenq/Feathercoin,Climbee/artcoin,lakepay/lake,jimmykiselak/lbrycrd,Kogser/bitcoin,stamhe/bitcoin,nikkitan/bitcoin,TeamBitBean/bitcoin-core,odemolliens/bitcoinxt,MazaCoin/maza,haobtc/bitcoin,fsb4000/bitcoin,REAP720801/bitcoin,botland/bitcoin,wederw/bitcoin,faircoin/faircoin2,shaulkf/bitcoin,iQcoin/iQcoin,Rav3nPL/PLNcoin,marscoin/marscoin,puticcoin/putic,FeatherCoin/Feathercoin,dakk/soundcoin,syscoin/syscoin2,alejandromgk/Lunar,MonetaryUnit/MUE-Src,Bluejudy/worldcoin,ColossusCoinXT/ColossusCoinXT,raasakh/bardcoin.exe,superjudge/bitcoin,Ziftr/bitcoin,truthcoin/truthcoin-cpp,qtumproject/qtum,MitchellMintCoins/AutoCoin,magacoin/magacoin,bitshares/bitshares-pts,tjps/bitcoin,adpg211/bitcoin-master,thelazier/dash,GroestlCoin/bitcoin,XX-net/twister-core,coinwarp/dogecoin,applecoin-official/applecoin,mockcoin/mockcoin,RHavar/bitcoin,Ziftr/litecoin,MarcoFalke/bitcoin,joulecoin/joulecoin,coinkeeper/2015-06-22_18-56_megacoin,blocktrail/bitcoin,thesoftwarejedi/bitcoin,degenorate/Deftcoin,Thracky/monkeycoin,1185/starwels,Theshadow4all/ShadowCoin,dagurval/bitcoinxt,Thracky/monkeycoin,bitcoinsSG/bitcoin,nightlydash/darkcoin,PIVX-Project/PIVX,argentumproject/argentum,robvanbentem/bitcoin,scmorse/bitcoin,netswift/vertcoin,dev1972/Satellitecoin,prusnak/bitcoin,icook/vertcoin,bitcoinplusorg/xbcwalletsource,mikehearn/bitcoin,BitcoinUnlimited/BitcoinUnlimited,GIJensen/bitcoin,apoelstra/elements,Kogser/bitcoin,barcoin-project/nothingcoin,magacoin/magacoin,tuaris/bitcoin,jonasnick/bitcoin,mitchellcash/bitcoin,keo/bitcoin,cybermatatu/bitcoin,vertcoin/vertcoin,deeponion/deeponion,diggcoin/diggcoin,h4x3rotab/BTCGPU,NicolasDorier/bitcoin,Tetcoin/tetcoin,megacoin/megacoin,BTCfork/hardfork_prototype_1_mvf-bu,jl2012/litecoin,RibbitFROG/ribbitcoin,xeddmc/twister-core,dscotese/bitcoin,welshjf/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,monacoinproject/monacoin,Diapolo/bitcoin,Kangmo/bitcoin,theuni/bitcoin,stevemyers/bitcoinxt,phelixbtc/bitcoin,okinc/bitcoin,ionomy/ion,wcwu/bitcoin,paveljanik/bitcoin,bitcoin-hivemind/hivemind,llamasoft/ProtoShares_Cycle,coinkeeper/2015-06-22_18-36_darkcoin,wangliu/bitcoin,MitchellMintCoins/MortgageCoin,funbucks/notbitcoinxt,cotner/bitcoin,Megacoin2/Megacoin,PandaPayProject/PandaPay,aspanta/bitcoin,jimmykiselak/lbrycrd,rnicoll/bitcoin,deadalnix/bitcoin,Xekyo/bitcoin,masterbraz/dg,bitgoldcoin-project/bitgoldcoin,TBoehm/greedynode,constantine001/bitcoin,sebrandon1/bitcoin,zemrys/vertcoin,odemolliens/bitcoinxt,zemrys/vertcoin,ivansib/sibcoin,Exceltior/dogecoin,deuscoin/deuscoin,mockcoin/mockcoin,Krellan/bitcoin,jnewbery/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,Rav3nPL/bitcoin,kleetus/bitcoinxt,ericshawlinux/bitcoin,Electronic-Gulden-Foundation/egulden,DrCrypto/darkcoin,rnicoll/dogecoin,andreaskern/bitcoin,bitcoinsSG/zcash,kevin-cantwell/crunchcoin,vcoin-project/vcoincore,franko-org/franko,svost/bitcoin,benma/bitcoin,donaloconnor/bitcoin,wekuiz/wekoin,brishtiteveja/sherlockcoin,acid1789/bitcoin,tropa/axecoin,phelix/bitcoin,jmcorgan/bitcoin,viacoin/viacoin,nomnombtc/bitcoin,jl2012/litecoin,nlgcoin/guldencoin-official,wederw/bitcoin,grumpydevelop/singularity,senadmd/coinmarketwatch,deadalnix/bitcoin,Friedbaumer/litecoin,aciddude/Feathercoin,myriadteam/myriadcoin,48thct2jtnf/P,welshjf/bitcoin,2XL/bitcoin,loxal/zcash,GlobalBoost/GlobalBoost,syscoin/syscoin2,fujicoin/fujicoin,gzuser01/zetacoin-bitcoin,stamhe/bitcoin,reddink/reddcoin,Earlz/renamedcoin,vericoin/vericoin-core,zestcoin/ZESTCOIN,Enticed87/Decipher,FinalHashLLC/namecore,andreaskern/bitcoin,DigiByte-Team/digibyte,cryptohelper/premine,ajweiss/bitcoin,okinc/litecoin,adpg211/bitcoin-master,united-scrypt-coin-project/unitedscryptcoin,kleetus/bitcoin,prark/bitcoinxt,DMDcoin/Diamond,bitgoldcoin-project/bitgoldcoin,Mrs-X/Darknet,xieta/mincoin,shouhuas/bitcoin,cddjr/BitcoinUnlimited,s-matthew-english/bitcoin,ticclassic/ic,ddombrowsky/radioshares,zetacoin/zetacoin,novaexchange/EAC,superjudge/bitcoin,worldbit/worldbit,borgcoin/Borgcoin1,Flowdalic/bitcoin,rustyrussell/bitcoin,SartoNess/BitcoinUnlimited,whatrye/twister-core,deuscoin/deuscoin,credits-currency/credits,iosdevzone/bitcoin,ctwiz/stardust,initaldk/bitcoin,myriadteam/myriadcoin,drwasho/bitcoinxt,jrick/bitcoin,truthcoin/blocksize-market,jn2840/bitcoin,IlfirinIlfirin/shavercoin,droark/bitcoin,tropa/axecoin,Petr-Economissa/gvidon,morcos/bitcoin,puticcoin/putic,npccoin/npccoin,paveljanik/bitcoin,mrbandrews/bitcoin,shurcoin/shurcoin,MarcoFalke/bitcoin,btcdrak/bitcoin,CodeShark/bitcoin,globaltoken/globaltoken,XertroV/bitcoin-nulldata,arnuschky/bitcoin,vtafaucet/virtacoin,JeremyRubin/bitcoin,tropa/axecoin,CryptArc/bitcoinxt,coinkeeper/2015-06-22_18-39_feathercoin,qubitcoin-project/QubitCoinQ2C,manuel-zulian/CoMoNet,ripper234/bitcoin,namecoin/namecoin-core,oleganza/bitcoin-duo,greencoin-dev/greencoin-dev,keesdewit82/LasVegasCoin,sebrandon1/bitcoin,marlengit/BitcoinUnlimited,fsb4000/bitcoin,TripleSpeeder/bitcoin,shea256/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,roques/bitcoin,ingresscoin/ingresscoin,gameunits/gameunits,Bluejudy/worldcoin,lbryio/lbrycrd,Cancercoin/Cancercoin,oklink-dev/bitcoin,wangxinxi/litecoin,domob1812/i0coin,bdelzell/creditcoin-org-creditcoin,GIJensen/bitcoin,trippysalmon/bitcoin,yenliangl/bitcoin,Kogser/bitcoin,dannyperez/bolivarcoin,PRabahy/bitcoin,bespike/litecoin,cmgustavo/bitcoin,schildbach/bitcoin,DogTagRecon/Still-Leraning,TeamBitBean/bitcoin-core,jiffe/cosinecoin,coinwarp/dogecoin,2XL/bitcoin,DrCrypto/darkcoin,coinkeeper/2015-04-19_21-20_litecoindark,arnuschky/bitcoin,DGCDev/argentum,midnight-miner/LasVegasCoin,sbellem/bitcoin,initaldk/bitcoin,KnCMiner/bitcoin,SartoNess/BitcoinUnlimited,mapineda/litecoin,zotherstupidguy/bitcoin,litecoin-project/litecoin,privatecoin/privatecoin,koharjidan/litecoin,qtumproject/qtum,truthcoin/truthcoin-cpp,cryptohelper/premine,mooncoin-project/mooncoin-landann,jimblasko/2015_UNB_Wallets,benzmuircroft/REWIRE.io,shelvenzhou/BTCGPU,unsystemizer/bitcoin,XX-net/twister-core,digibyte/digibyte,tedlz123/Bitcoin,CryptArc/bitcoin,jarymoth/dogecoin,svost/bitcoin,yenliangl/bitcoin,DigitalPandacoin/pandacoin,daveperkins-github/bitcoin-dev,Thracky/monkeycoin,rsdevgun16e/energi,safecoin/safecoin,hyperwang/bitcoin,wellenreiter01/Feathercoin,coinkeeper/2015-04-19_21-20_litecoindark,raasakh/bardcoin,emc2foundation/einsteinium,TheBlueMatt/bitcoin,awemany/BitcoinUnlimited,manuel-zulian/CoMoNet,PandaPayProject/PandaPay,deadalnix/bitcoin,dexX7/mastercore,MikeAmy/bitcoin,isle2983/bitcoin,AdrianaDinca/bitcoin,united-scrypt-coin-project/unitedscryptcoin,thrasher-/litecoin,joshrabinowitz/bitcoin,DGCDev/argentum,Tetcoin/tetcoin,gandrewstone/BitcoinUnlimited,Tetcoin/tetcoin,reddcoin-project/reddcoin,atgreen/bitcoin,zixan/bitcoin,OstlerDev/florincoin,brettwittam/geocoin,BTCfork/hardfork_prototype_1_mvf-core,segwit/atbcoin-insight,ElementsProject/elements,Alonzo-Coeus/bitcoin,andres-root/bitcoinxt,cryptoprojects/ultimateonlinecash,bickojima/bitzeny,p2peace/oliver-twister-core,shapiroisme/datadollar,vertcoin/eyeglass,jmgilbert2/energi,ronpaulcoin/ronpaulcoin,core-bitcoin/bitcoin,supcoin/supcoin,Earlz/dobbscoin-source,balajinandhu/bitcoin,s-matthew-english/bitcoin,jn2840/bitcoin,stevemyers/bitcoinxt,ashleyholman/bitcoin,pascalguru/florincoin,gjhiggins/vcoin09,pstratem/elements,prark/bitcoinxt,memorycoin/memorycoin,GwangJin/gwangmoney-core,ftrader-bitcoinabc/bitcoin-abc,Kenwhite23/litecoin,AllanDoensen/BitcoinUnlimited,ahmedbodi/terracoin,XX-net/twister-core,Har01d/bitcoin,royosherove/bitcoinxt,Mrs-X/Darknet,wtogami/bitcoin,sifcoin/sifcoin,KibiCoin/kibicoin,Kcoin-project/kcoin,Xekyo/bitcoin,aspirecoin/aspire,ionux/freicoin,puticcoin/putic,phplaboratory/psiacoin,cqtenq/feathercoin_core,ddombrowsky/radioshares,josephbisch/namecoin-core,rromanchuk/bitcoinxt,ardsu/bitcoin,litecoin-project/litecore-litecoin,capitalDIGI/DIGI-v-0-10-4,jonasnick/bitcoin,shadowoneau/ozcoin,coinerd/krugercoin,scamcoinz/scamcoin,deuscoin/deuscoin,bcpki/testblocks,florincoin/florincoin,ajtowns/bitcoin,ingresscoin/ingresscoin,zcoinofficial/zcoin,guncoin/guncoin,myriadcoin/myriadcoin,josephbisch/namecoin-core,arnuschky/bitcoin,kbccoin/kbc,ghostlander/Feathercoin,ShadowMyst/creativechain-core,digideskio/namecoin,rat4/bitcoin,greencoin-dev/greencoin-dev,projectinterzone/ITZ,lclc/bitcoin,capitalDIGI/DIGI-v-0-10-4,MitchellMintCoins/MortgageCoin,donaloconnor/bitcoin,erqan/twister-core,memorycoin/memorycoin,ddombrowsky/radioshares,MitchellMintCoins/AutoCoin,cmgustavo/bitcoin,tedlz123/Bitcoin,chrisfranko/aiden,mitchellcash/bitcoin,plankton12345/litecoin,mikehearn/bitcoinxt,florincoin/florincoin,andreaskern/bitcoin,jn2840/bitcoin,roques/bitcoin,themusicgod1/bitcoin,omefire/bitcoin,ripper234/bitcoin,butterflypay/bitcoin,diggcoin/diggcoin,simdeveloper/bitcoin,Enticed87/Decipher,erqan/twister-core,myriadcoin/myriadcoin,aspanta/bitcoin,domob1812/huntercore,okinc/bitcoin,jmgilbert2/energi,haraldh/bitcoin,r8921039/bitcoin,monacoinproject/monacoin,MazaCoin/maza,mapineda/litecoin,Bitcoin-ABC/bitcoin-abc,Anfauglith/iop-hd,bitcoinxt/bitcoinxt,joroob/reddcoin,okinc/litecoin,octocoin-project/octocoin,TripleSpeeder/bitcoin,lbryio/lbrycrd,bitcoin-hivemind/hivemind,nomnombtc/bitcoin,zzkt/solarcoin,appop/bitcoin,jonasnick/bitcoin,jimblasko/2015_UNB_Wallets,jtimon/elements,miguelfreitas/twister-core,whatrye/twister-core,Bloom-Project/Bloom,apoelstra/bitcoin,gwillen/elements,bitreserve/bitcoin,Adaryian/E-Currency,krzysztofwos/BitcoinUnlimited,imharrywu/fastcoin,patricklodder/dogecoin,r8921039/bitcoin,Earlz/dobbscoin-source,benzmuircroft/REWIRE.io,mapineda/litecoin,nightlydash/darkcoin,mrtexaznl/mediterraneancoin,p2peace/oliver-twister-core,antcheck/antcoin,loxal/zcash,bitcoinsSG/bitcoin,awemany/BitcoinUnlimited,arruah/ensocoin,bitcoinknots/bitcoin,Rav3nPL/doubloons-0.10,pataquets/namecoin-core,RyanLucchese/energi,lbryio/lbrycrd,jambolo/bitcoin,ahmedbodi/vertcoin,stamhe/litecoin,wiggi/huntercore,adpg211/bitcoin-master,shadowoneau/ozcoin,bmp02050/ReddcoinUpdates,trippysalmon/bitcoin,rsdevgun16e/energi,bespike/litecoin,viacoin/viacoin,DMDcoin/Diamond,PRabahy/bitcoin,phelix/namecore,DGCDev/digitalcoin,scmorse/bitcoin,terracoin/terracoin,goldcoin/Goldcoin-GLD,wangxinxi/litecoin,kleetus/bitcoin,myriadcoin/myriadcoin,coinkeeper/2015-06-22_19-13_florincoin,jimblasko/2015_UNB_Wallets,franko-org/franko,presstab/PIVX,applecoin-official/applecoin,RibbitFROG/ribbitcoin,Czarcoin/czarcoin,romanornr/viacoin,vcoin-project/vcoin0.8zeta-dev,franko-org/franko,oklink-dev/bitcoin_block,rdqw/sscoin,lateminer/bitcoin,SartoNess/BitcoinUnlimited,joshrabinowitz/bitcoin,mockcoin/mockcoin,Cancercoin/Cancercoin,ShadowMyst/creativechain-core,phelix/bitcoin,koharjidan/litecoin,Alex-van-der-Peet/bitcoin,lbrtcoin/albertcoin,CryptArc/bitcoinxt,Richcoin-Project/RichCoin,randy-waterhouse/bitcoin,argentumproject/argentum,benosa/bitcoin,HashUnlimited/Einsteinium-Unlimited,jamesob/bitcoin,dexX7/bitcoin,torresalyssa/bitcoin,habibmasuro/bitcoinxt,shaulkf/bitcoin,basicincome/unpcoin-core,axelxod/braincoin,GreenParhelia/bitcoin,plncoin/PLNcoin_Core,coinkeeper/2015-06-22_19-00_ziftrcoin,mruddy/bitcoin,Kcoin-project/kcoin,jgarzik/bitcoin,gjhiggins/vcoin09,glv2/peerunity,Christewart/bitcoin,dobbscoin/dobbscoin-source,MonetaryUnit/MUE-Src,koharjidan/litecoin,dobbscoin/dobbscoin-source,raasakh/bardcoin,brettwittam/geocoin,uphold/bitcoin,AkioNak/bitcoin,isghe/bitcoinxt,coinkeeper/2015-06-22_18-52_viacoin,SocialCryptoCoin/SocialCoin,KnCMiner/bitcoin,GroundRod/anoncoin,BitcoinHardfork/bitcoin,21E14/bitcoin,appop/bitcoin,jrmithdobbs/bitcoin,omefire/bitcoin,DigitalPandacoin/pandacoin,my-first/octocoin,CryptArc/bitcoin,gjhiggins/vcoin09,alejandromgk/Lunar,gwillen/elements,millennial83/bitcoin,wekuiz/wekoin,ctwiz/stardust,howardrya/AcademicCoin,ripper234/bitcoin,NateBrune/bitcoin-nate,1185/starwels,dan-mi-sun/bitcoin,crowning-/dash,CodeShark/bitcoin,SartoNess/BitcoinUnlimited,knolza/gamblr,se3000/bitcoin,crowning2/dash,jrmithdobbs/bitcoin,IlfirinCano/shavercoin,peerdb/cors,GreenParhelia/bitcoin,dgarage/bc2,hsavit1/bitcoin,bitcoinclassic/bitcoinclassic,BigBlueCeiling/augmentacoin,lbryio/lbrycrd,litecoin-project/bitcoinomg,ticclassic/ic,BitcoinPOW/BitcoinPOW,deeponion/deeponion,midnightmagic/bitcoin,thrasher-/litecoin,royosherove/bitcoinxt,genavarov/ladacoin,Jeff88Ho/bitcoin,reddcoin-project/reddcoin,fussl/elements,lakepay/lake,jiangyonghang/bitcoin,tmagik/catcoin,upgradeadvice/MUE-Src,RongxinZhang/bitcoinxt,nbenoit/bitcoin,goldcoin/goldcoin,inkvisit/sarmacoins,MonetaryUnit/MUE-Src,ionomy/ion,gjhiggins/vcoin09,bmp02050/ReddcoinUpdates,Xekyo/bitcoin,fedoracoin-dev/fedoracoin,peacedevelop/peacecoin,wangxinxi/litecoin,hophacker/bitcoin_malleability,aburan28/elements,zixan/bitcoin,NicolasDorier/bitcoin,Rav3nPL/polcoin,n1bor/bitcoin,inkvisit/sarmacoins,dscotese/bitcoin,DigiByte-Team/digibyte,markf78/dollarcoin,instagibbs/bitcoin,ptschip/bitcoinxt,goldcoin/goldcoin,5mil/Tradecoin,appop/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,romanornr/viacoin,neuroidss/bitcoin,worldbit/worldbit,maaku/bitcoin,Lucky7Studio/bitcoin,dmrtsvetkov/flowercoin,ivansib/sib16,domob1812/namecore,imharrywu/fastcoin,freelion93/mtucicoin,MasterX1582/bitcoin-becoin,untrustbank/litecoin,CrimeaCoin/crimeacoin,SoreGums/bitcoinxt,error10/bitcoin,alexandrcoin/vertcoin,awemany/BitcoinUnlimited,dscotese/bitcoin,nmarley/dash,josephbisch/namecoin-core,jimmysong/bitcoin,DMDcoin/Diamond,AdrianaDinca/bitcoin,syscoin/syscoin,hg5fm/nexuscoin,nathaniel-mahieu/bitcoin,instagibbs/bitcoin,sugruedes/bitcoin,pelorusjack/BlockDX,BitcoinHardfork/bitcoin,xuyangcn/opalcoin,BTCfork/hardfork_prototype_1_mvf-bu,ctwiz/stardust,themusicgod1/bitcoin,coinkeeper/2015-06-22_18-41_ixcoin,SartoNess/BitcoinUnlimited,blood2/bloodcoin-0.9,Bitcoinsulting/bitcoinxt,21E14/bitcoin,randy-waterhouse/bitcoin,achow101/bitcoin,greenaddress/bitcoin,Alex-van-der-Peet/bitcoin,deeponion/deeponion,millennial83/bitcoin,UFOCoins/ufo,LIMXTEC/DMDv3,tecnovert/particl-core,laudaa/bitcoin,joroob/reddcoin,peacedevelop/peacecoin,Cloudsy/bitcoin,ahmedbodi/test2,earonesty/bitcoin,vertcoin/vertcoin,jtimon/elements,apoelstra/bitcoin,5mil/Tradecoin,tecnovert/particl-core,litecoin-project/litecoin,afk11/bitcoin,wangliu/bitcoin,Jcing95/iop-hd,ahmedbodi/terracoin,rat4/bitcoin,coinkeeper/2015-06-22_19-19_worldcoin,particl/particl-core,xurantju/bitcoin,initaldk/bitcoin,ivansib/sibcoin,gandrewstone/BitcoinUnlimited,kallewoof/bitcoin,sbaks0820/bitcoin,particl/particl-core,earthcoinproject/earthcoin,Kenwhite23/litecoin,BitcoinPOW/BitcoinPOW,yenliangl/bitcoin,andres-root/bitcoinxt,worldbit/worldbit,zotherstupidguy/bitcoin,raasakh/bardcoin.exe,ericshawlinux/bitcoin,cheehieu/bitcoin,genavarov/lamacoin,Michagogo/bitcoin,EntropyFactory/creativechain-core,Darknet-Crypto/Darknet,thesoftwarejedi/bitcoin,llluiop/bitcoin,globaltoken/globaltoken,gazbert/bitcoin,manuel-zulian/accumunet,GreenParhelia/bitcoin,vcoin-project/vcoincore,experiencecoin/experiencecoin,cryptcoins/cryptcoin,Alex-van-der-Peet/bitcoin,daliwangi/bitcoin,pstratem/bitcoin,acid1789/bitcoin,MeshCollider/bitcoin,fussl/elements,dcousens/bitcoin,Bitcoin-ABC/bitcoin-abc,iosdevzone/bitcoin,BTCGPU/BTCGPU,compasscoin/compasscoin,royosherove/bitcoinxt,domob1812/huntercore,BitzenyCoreDevelopers/bitzeny,dgarage/bc3,oklink-dev/bitcoin_block,imton/bitcoin,HashUnlimited/Einsteinium-Unlimited,irvingruan/bitcoin,raasakh/bardcoin,memorycoin/memorycoin
|
c4b7628d0fc77f4c2937914da148e978486ab41c
|
chrome/common/sqlite_utils.cc
|
chrome/common/sqlite_utils.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/sqlite_utils.h"
#include <list>
#include "base/at_exit.h"
#include "base/file_path.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/stl_util-inl.h"
#include "base/string16.h"
// The vanilla error handler implements the common fucntionality for all the
// error handlers. Specialized error handlers are expected to only override
// the Handler() function.
class VanillaSQLErrorHandler : public SQLErrorHandler {
public:
VanillaSQLErrorHandler() : error_(SQLITE_OK) {
}
virtual int GetLastError() const {
return error_;
}
protected:
int error_;
};
class DebugSQLErrorHandler: public VanillaSQLErrorHandler {
public:
virtual int HandleError(int error, sqlite3* db) {
error_ = error;
NOTREACHED() << "sqlite error " << error
<< " db " << static_cast<void*>(db);
return error;
}
};
class ReleaseSQLErrorHandler : public VanillaSQLErrorHandler {
public:
virtual int HandleError(int error, sqlite3* db) {
error_ = error;
// TOD(cpu): Remove this code once it has a few days of air time.
if (error == SQLITE_INTERNAL ||
error == SQLITE_NOMEM ||
error == SQLITE_CORRUPT ||
error == SQLITE_IOERR ||
error == SQLITE_CONSTRAINT ||
error == SQLITE_NOTADB)
CHECK(false) << "sqlite fatal error " << error;
return error;
}
};
// The default error handler factory is also in charge of managing the
// lifetime of the error objects. This object is multi-thread safe.
class DefaultSQLErrorHandlerFactory : public SQLErrorHandlerFactory {
public:
~DefaultSQLErrorHandlerFactory() {
STLDeleteContainerPointers(errors_.begin(), errors_.end());
}
virtual SQLErrorHandler* Make() {
SQLErrorHandler* handler;
#ifndef NDEBUG
handler = new DebugSQLErrorHandler;
#else
handler = new ReleaseSQLErrorHandler;
#endif // NDEBUG
AddHandler(handler);
return handler;
}
private:
void AddHandler(SQLErrorHandler* handler) {
AutoLock lock(lock_);
errors_.push_back(handler);
}
typedef std::list<SQLErrorHandler*> ErrorList;
ErrorList errors_;
Lock lock_;
};
SQLErrorHandlerFactory* GetErrorHandlerFactory() {
// TODO(cpu): Testing needs to override the error handler.
// Destruction of DefaultSQLErrorHandlerFactory handled by at_exit manager.
return Singleton<DefaultSQLErrorHandlerFactory>::get();
}
int OpenSqliteDb(const FilePath& filepath, sqlite3** database) {
#if defined(OS_WIN)
// We want the default encoding to always be UTF-8, so we use the
// 8-bit version of open().
return sqlite3_open(WideToUTF8(filepath.value()).c_str(), database);
#elif defined(OS_POSIX)
return sqlite3_open(filepath.value().c_str(), database);
#endif
}
bool DoesSqliteTableExist(sqlite3* db,
const char* db_name,
const char* table_name) {
// sqlite doesn't allow binding parameters as table names, so we have to
// manually construct the sql
std::string sql("SELECT name FROM ");
if (db_name && db_name[0]) {
sql.append(db_name);
sql.push_back('.');
}
sql.append("sqlite_master WHERE type='table' AND name=?");
SQLStatement statement;
if (statement.prepare(db, sql.c_str()) != SQLITE_OK)
return false;
if (statement.bind_text(0, table_name) != SQLITE_OK)
return false;
// we only care about if this matched a row, not the actual data
return sqlite3_step(statement.get()) == SQLITE_ROW;
}
bool DoesSqliteColumnExist(sqlite3* db,
const char* database_name,
const char* table_name,
const char* column_name,
const char* column_type) {
SQLStatement s;
std::string sql;
sql.append("PRAGMA ");
if (database_name && database_name[0]) {
// optional database name specified
sql.append(database_name);
sql.push_back('.');
}
sql.append("TABLE_INFO(");
sql.append(table_name);
sql.append(")");
if (s.prepare(db, sql.c_str()) != SQLITE_OK)
return false;
while (s.step() == SQLITE_ROW) {
if (!s.column_string(1).compare(column_name)) {
if (column_type && column_type[0])
return !s.column_string(2).compare(column_type);
return true;
}
}
return false;
}
bool DoesSqliteTableHaveRow(sqlite3* db, const char* table_name) {
SQLStatement s;
std::string b;
b.append("SELECT * FROM ");
b.append(table_name);
if (s.prepare(db, b.c_str()) != SQLITE_OK)
return false;
return s.step() == SQLITE_ROW;
}
SQLTransaction::SQLTransaction(sqlite3* db) : db_(db), began_(false) {
}
SQLTransaction::~SQLTransaction() {
if (began_) {
Rollback();
}
}
int SQLTransaction::BeginCommand(const char* command) {
int rv = SQLITE_ERROR;
if (!began_ && db_) {
rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv == SQLITE_OK);
}
return rv;
}
int SQLTransaction::EndCommand(const char* command) {
int rv = SQLITE_ERROR;
if (began_ && db_) {
rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv != SQLITE_OK);
}
return rv;
}
SQLNestedTransactionSite::~SQLNestedTransactionSite() {
DCHECK(!top_transaction_);
}
void SQLNestedTransactionSite::SetTopTransaction(SQLNestedTransaction* top) {
DCHECK(!top || !top_transaction_);
top_transaction_ = top;
}
SQLNestedTransaction::SQLNestedTransaction(SQLNestedTransactionSite* site)
: SQLTransaction(site->GetSqlite3DB()),
needs_rollback_(false),
site_(site) {
DCHECK(site);
if (site->GetTopTransaction() == NULL) {
site->SetTopTransaction(this);
}
}
SQLNestedTransaction::~SQLNestedTransaction() {
if (began_) {
Rollback();
}
if (site_->GetTopTransaction() == this) {
site_->SetTopTransaction(NULL);
}
}
int SQLNestedTransaction::BeginCommand(const char* command) {
DCHECK(db_);
DCHECK(site_ && site_->GetTopTransaction());
if (!db_ || began_) {
return SQLITE_ERROR;
}
if (site_->GetTopTransaction() == this) {
int rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv == SQLITE_OK);
if (began_) {
site_->OnBegin();
}
return rv;
} else {
if (site_->GetTopTransaction()->needs_rollback_) {
return SQLITE_ERROR;
}
began_ = true;
return SQLITE_OK;
}
}
int SQLNestedTransaction::EndCommand(const char* command) {
DCHECK(db_);
DCHECK(site_ && site_->GetTopTransaction());
if (!db_ || !began_) {
return SQLITE_ERROR;
}
if (site_->GetTopTransaction() == this) {
if (needs_rollback_) {
sqlite3_exec(db_, "ROLLBACK", NULL, NULL, NULL);
began_ = false; // reset so we don't try to rollback or call
// OnRollback() again
site_->OnRollback();
return SQLITE_ERROR;
} else {
int rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv != SQLITE_OK);
if (strcmp(command, "ROLLBACK") == 0) {
began_ = false; // reset so we don't try to rollbck or call
// OnRollback() again
site_->OnRollback();
} else {
DCHECK(strcmp(command, "COMMIT") == 0);
if (rv == SQLITE_OK) {
site_->OnCommit();
}
}
return rv;
}
} else {
if (strcmp(command, "ROLLBACK") == 0) {
site_->GetTopTransaction()->needs_rollback_ = true;
}
began_ = false;
return SQLITE_OK;
}
}
int SQLStatement::prepare(sqlite3* db, const char* sql, int sql_len) {
DCHECK(!stmt_);
int rv = sqlite3_prepare_v2(db, sql, sql_len, &stmt_, NULL);
if (rv != SQLITE_OK) {
SQLErrorHandler* error_handler = GetErrorHandlerFactory()->Make();
return error_handler->HandleError(rv, db_handle());
}
return rv;
}
int SQLStatement::step() {
DCHECK(stmt_);
int status = sqlite3_step(stmt_);
if ((status == SQLITE_ROW) || (status == SQLITE_DONE))
return status;
// We got a problem.
SQLErrorHandler* error_handler = GetErrorHandlerFactory()->Make();
return error_handler->HandleError(status, db_handle());
}
int SQLStatement::reset() {
DCHECK(stmt_);
return sqlite3_reset(stmt_);
}
sqlite_int64 SQLStatement::last_insert_rowid() {
DCHECK(stmt_);
return sqlite3_last_insert_rowid(db_handle());
}
int SQLStatement::changes() {
DCHECK(stmt_);
return sqlite3_changes(db_handle());
}
sqlite3* SQLStatement::db_handle() {
DCHECK(stmt_);
return sqlite3_db_handle(stmt_);
}
int SQLStatement::bind_parameter_count() {
DCHECK(stmt_);
return sqlite3_bind_parameter_count(stmt_);
}
int SQLStatement::bind_blob(int index, std::vector<unsigned char>* blob) {
if (blob) {
const void* value = &(*blob)[0];
int len = static_cast<int>(blob->size());
return bind_blob(index, value, len);
} else {
return bind_null(index);
}
}
int SQLStatement::bind_blob(int index, const void* value, int value_len) {
return bind_blob(index, value, value_len, SQLITE_TRANSIENT);
}
int SQLStatement::bind_blob(int index, const void* value, int value_len,
Function dtor) {
DCHECK(stmt_);
return sqlite3_bind_blob(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_double(int index, double value) {
DCHECK(stmt_);
return sqlite3_bind_double(stmt_, index + 1, value);
}
int SQLStatement::bind_bool(int index, bool value) {
DCHECK(stmt_);
return sqlite3_bind_int(stmt_, index + 1, value);
}
int SQLStatement::bind_int(int index, int value) {
DCHECK(stmt_);
return sqlite3_bind_int(stmt_, index + 1, value);
}
int SQLStatement::bind_int64(int index, sqlite_int64 value) {
DCHECK(stmt_);
return sqlite3_bind_int64(stmt_, index + 1, value);
}
int SQLStatement::bind_null(int index) {
DCHECK(stmt_);
return sqlite3_bind_null(stmt_, index + 1);
}
int SQLStatement::bind_text(int index, const char* value, int value_len,
Function dtor) {
DCHECK(stmt_);
return sqlite3_bind_text(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_text16(int index, const char16* value, int value_len,
Function dtor) {
DCHECK(stmt_);
value_len *= sizeof(char16);
return sqlite3_bind_text16(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_value(int index, const sqlite3_value* value) {
DCHECK(stmt_);
return sqlite3_bind_value(stmt_, index + 1, value);
}
int SQLStatement::column_count() {
DCHECK(stmt_);
return sqlite3_column_count(stmt_);
}
int SQLStatement::column_type(int index) {
DCHECK(stmt_);
return sqlite3_column_type(stmt_, index);
}
const void* SQLStatement::column_blob(int index) {
DCHECK(stmt_);
return sqlite3_column_blob(stmt_, index);
}
bool SQLStatement::column_blob_as_vector(int index,
std::vector<unsigned char>* blob) {
DCHECK(stmt_);
const void* p = column_blob(index);
size_t len = column_bytes(index);
blob->resize(len);
if (blob->size() != len) {
return false;
}
if (len > 0)
memcpy(&(blob->front()), p, len);
return true;
}
bool SQLStatement::column_blob_as_string(int index, std::string* blob) {
DCHECK(stmt_);
const void* p = column_blob(index);
size_t len = column_bytes(index);
blob->resize(len);
if (blob->size() != len) {
return false;
}
blob->assign(reinterpret_cast<const char*>(p), len);
return true;
}
int SQLStatement::column_bytes(int index) {
DCHECK(stmt_);
return sqlite3_column_bytes(stmt_, index);
}
int SQLStatement::column_bytes16(int index) {
DCHECK(stmt_);
return sqlite3_column_bytes16(stmt_, index);
}
double SQLStatement::column_double(int index) {
DCHECK(stmt_);
return sqlite3_column_double(stmt_, index);
}
bool SQLStatement::column_bool(int index) {
DCHECK(stmt_);
return sqlite3_column_int(stmt_, index) ? true : false;
}
int SQLStatement::column_int(int index) {
DCHECK(stmt_);
return sqlite3_column_int(stmt_, index);
}
sqlite_int64 SQLStatement::column_int64(int index) {
DCHECK(stmt_);
return sqlite3_column_int64(stmt_, index);
}
const char* SQLStatement::column_text(int index) {
DCHECK(stmt_);
return reinterpret_cast<const char*>(sqlite3_column_text(stmt_, index));
}
bool SQLStatement::column_string(int index, std::string* str) {
DCHECK(stmt_);
DCHECK(str);
const char* s = column_text(index);
str->assign(s ? s : std::string());
return s != NULL;
}
std::string SQLStatement::column_string(int index) {
std::string str;
column_string(index, &str);
return str;
}
const char16* SQLStatement::column_text16(int index) {
DCHECK(stmt_);
return static_cast<const char16*>(sqlite3_column_text16(stmt_, index));
}
bool SQLStatement::column_wstring(int index, std::wstring* str) {
DCHECK(stmt_);
DCHECK(str);
const char* s = column_text(index);
str->assign(s ? UTF8ToWide(s) : std::wstring());
return (s != NULL);
}
std::wstring SQLStatement::column_wstring(int index) {
std::wstring wstr;
column_wstring(index, &wstr);
return wstr;
}
#if defined(USE_SYSTEM_SQLITE)
// This function is a local change to sqlite3 which doesn't exist when one is
// using the system sqlite library. Thus, we stub it out here.
int sqlite3Preload(sqlite3* db) {
return 0;
}
#endif
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/sqlite_utils.h"
#include <list>
#include "base/at_exit.h"
#include "base/file_path.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/stl_util-inl.h"
#include "base/string16.h"
// The vanilla error handler implements the common fucntionality for all the
// error handlers. Specialized error handlers are expected to only override
// the Handler() function.
class VanillaSQLErrorHandler : public SQLErrorHandler {
public:
VanillaSQLErrorHandler() : error_(SQLITE_OK) {
}
virtual int GetLastError() const {
return error_;
}
protected:
int error_;
};
class DebugSQLErrorHandler: public VanillaSQLErrorHandler {
public:
virtual int HandleError(int error, sqlite3* db) {
error_ = error;
NOTREACHED() << "sqlite error " << error
<< " db " << static_cast<void*>(db);
return error;
}
};
class ReleaseSQLErrorHandler : public VanillaSQLErrorHandler {
public:
virtual int HandleError(int error, sqlite3* db) {
error_ = error;
// Used to have a CHECK here. Got lots of crashes.
return error;
}
};
// The default error handler factory is also in charge of managing the
// lifetime of the error objects. This object is multi-thread safe.
class DefaultSQLErrorHandlerFactory : public SQLErrorHandlerFactory {
public:
~DefaultSQLErrorHandlerFactory() {
STLDeleteContainerPointers(errors_.begin(), errors_.end());
}
virtual SQLErrorHandler* Make() {
SQLErrorHandler* handler;
#ifndef NDEBUG
handler = new DebugSQLErrorHandler;
#else
handler = new ReleaseSQLErrorHandler;
#endif // NDEBUG
AddHandler(handler);
return handler;
}
private:
void AddHandler(SQLErrorHandler* handler) {
AutoLock lock(lock_);
errors_.push_back(handler);
}
typedef std::list<SQLErrorHandler*> ErrorList;
ErrorList errors_;
Lock lock_;
};
SQLErrorHandlerFactory* GetErrorHandlerFactory() {
// TODO(cpu): Testing needs to override the error handler.
// Destruction of DefaultSQLErrorHandlerFactory handled by at_exit manager.
return Singleton<DefaultSQLErrorHandlerFactory>::get();
}
int OpenSqliteDb(const FilePath& filepath, sqlite3** database) {
#if defined(OS_WIN)
// We want the default encoding to always be UTF-8, so we use the
// 8-bit version of open().
return sqlite3_open(WideToUTF8(filepath.value()).c_str(), database);
#elif defined(OS_POSIX)
return sqlite3_open(filepath.value().c_str(), database);
#endif
}
bool DoesSqliteTableExist(sqlite3* db,
const char* db_name,
const char* table_name) {
// sqlite doesn't allow binding parameters as table names, so we have to
// manually construct the sql
std::string sql("SELECT name FROM ");
if (db_name && db_name[0]) {
sql.append(db_name);
sql.push_back('.');
}
sql.append("sqlite_master WHERE type='table' AND name=?");
SQLStatement statement;
if (statement.prepare(db, sql.c_str()) != SQLITE_OK)
return false;
if (statement.bind_text(0, table_name) != SQLITE_OK)
return false;
// we only care about if this matched a row, not the actual data
return sqlite3_step(statement.get()) == SQLITE_ROW;
}
bool DoesSqliteColumnExist(sqlite3* db,
const char* database_name,
const char* table_name,
const char* column_name,
const char* column_type) {
SQLStatement s;
std::string sql;
sql.append("PRAGMA ");
if (database_name && database_name[0]) {
// optional database name specified
sql.append(database_name);
sql.push_back('.');
}
sql.append("TABLE_INFO(");
sql.append(table_name);
sql.append(")");
if (s.prepare(db, sql.c_str()) != SQLITE_OK)
return false;
while (s.step() == SQLITE_ROW) {
if (!s.column_string(1).compare(column_name)) {
if (column_type && column_type[0])
return !s.column_string(2).compare(column_type);
return true;
}
}
return false;
}
bool DoesSqliteTableHaveRow(sqlite3* db, const char* table_name) {
SQLStatement s;
std::string b;
b.append("SELECT * FROM ");
b.append(table_name);
if (s.prepare(db, b.c_str()) != SQLITE_OK)
return false;
return s.step() == SQLITE_ROW;
}
SQLTransaction::SQLTransaction(sqlite3* db) : db_(db), began_(false) {
}
SQLTransaction::~SQLTransaction() {
if (began_) {
Rollback();
}
}
int SQLTransaction::BeginCommand(const char* command) {
int rv = SQLITE_ERROR;
if (!began_ && db_) {
rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv == SQLITE_OK);
}
return rv;
}
int SQLTransaction::EndCommand(const char* command) {
int rv = SQLITE_ERROR;
if (began_ && db_) {
rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv != SQLITE_OK);
}
return rv;
}
SQLNestedTransactionSite::~SQLNestedTransactionSite() {
DCHECK(!top_transaction_);
}
void SQLNestedTransactionSite::SetTopTransaction(SQLNestedTransaction* top) {
DCHECK(!top || !top_transaction_);
top_transaction_ = top;
}
SQLNestedTransaction::SQLNestedTransaction(SQLNestedTransactionSite* site)
: SQLTransaction(site->GetSqlite3DB()),
needs_rollback_(false),
site_(site) {
DCHECK(site);
if (site->GetTopTransaction() == NULL) {
site->SetTopTransaction(this);
}
}
SQLNestedTransaction::~SQLNestedTransaction() {
if (began_) {
Rollback();
}
if (site_->GetTopTransaction() == this) {
site_->SetTopTransaction(NULL);
}
}
int SQLNestedTransaction::BeginCommand(const char* command) {
DCHECK(db_);
DCHECK(site_ && site_->GetTopTransaction());
if (!db_ || began_) {
return SQLITE_ERROR;
}
if (site_->GetTopTransaction() == this) {
int rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv == SQLITE_OK);
if (began_) {
site_->OnBegin();
}
return rv;
} else {
if (site_->GetTopTransaction()->needs_rollback_) {
return SQLITE_ERROR;
}
began_ = true;
return SQLITE_OK;
}
}
int SQLNestedTransaction::EndCommand(const char* command) {
DCHECK(db_);
DCHECK(site_ && site_->GetTopTransaction());
if (!db_ || !began_) {
return SQLITE_ERROR;
}
if (site_->GetTopTransaction() == this) {
if (needs_rollback_) {
sqlite3_exec(db_, "ROLLBACK", NULL, NULL, NULL);
began_ = false; // reset so we don't try to rollback or call
// OnRollback() again
site_->OnRollback();
return SQLITE_ERROR;
} else {
int rv = sqlite3_exec(db_, command, NULL, NULL, NULL);
began_ = (rv != SQLITE_OK);
if (strcmp(command, "ROLLBACK") == 0) {
began_ = false; // reset so we don't try to rollbck or call
// OnRollback() again
site_->OnRollback();
} else {
DCHECK(strcmp(command, "COMMIT") == 0);
if (rv == SQLITE_OK) {
site_->OnCommit();
}
}
return rv;
}
} else {
if (strcmp(command, "ROLLBACK") == 0) {
site_->GetTopTransaction()->needs_rollback_ = true;
}
began_ = false;
return SQLITE_OK;
}
}
int SQLStatement::prepare(sqlite3* db, const char* sql, int sql_len) {
DCHECK(!stmt_);
int rv = sqlite3_prepare_v2(db, sql, sql_len, &stmt_, NULL);
if (rv != SQLITE_OK) {
SQLErrorHandler* error_handler = GetErrorHandlerFactory()->Make();
return error_handler->HandleError(rv, db_handle());
}
return rv;
}
int SQLStatement::step() {
DCHECK(stmt_);
int status = sqlite3_step(stmt_);
if ((status == SQLITE_ROW) || (status == SQLITE_DONE))
return status;
// We got a problem.
SQLErrorHandler* error_handler = GetErrorHandlerFactory()->Make();
return error_handler->HandleError(status, db_handle());
}
int SQLStatement::reset() {
DCHECK(stmt_);
return sqlite3_reset(stmt_);
}
sqlite_int64 SQLStatement::last_insert_rowid() {
DCHECK(stmt_);
return sqlite3_last_insert_rowid(db_handle());
}
int SQLStatement::changes() {
DCHECK(stmt_);
return sqlite3_changes(db_handle());
}
sqlite3* SQLStatement::db_handle() {
DCHECK(stmt_);
return sqlite3_db_handle(stmt_);
}
int SQLStatement::bind_parameter_count() {
DCHECK(stmt_);
return sqlite3_bind_parameter_count(stmt_);
}
int SQLStatement::bind_blob(int index, std::vector<unsigned char>* blob) {
if (blob) {
const void* value = &(*blob)[0];
int len = static_cast<int>(blob->size());
return bind_blob(index, value, len);
} else {
return bind_null(index);
}
}
int SQLStatement::bind_blob(int index, const void* value, int value_len) {
return bind_blob(index, value, value_len, SQLITE_TRANSIENT);
}
int SQLStatement::bind_blob(int index, const void* value, int value_len,
Function dtor) {
DCHECK(stmt_);
return sqlite3_bind_blob(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_double(int index, double value) {
DCHECK(stmt_);
return sqlite3_bind_double(stmt_, index + 1, value);
}
int SQLStatement::bind_bool(int index, bool value) {
DCHECK(stmt_);
return sqlite3_bind_int(stmt_, index + 1, value);
}
int SQLStatement::bind_int(int index, int value) {
DCHECK(stmt_);
return sqlite3_bind_int(stmt_, index + 1, value);
}
int SQLStatement::bind_int64(int index, sqlite_int64 value) {
DCHECK(stmt_);
return sqlite3_bind_int64(stmt_, index + 1, value);
}
int SQLStatement::bind_null(int index) {
DCHECK(stmt_);
return sqlite3_bind_null(stmt_, index + 1);
}
int SQLStatement::bind_text(int index, const char* value, int value_len,
Function dtor) {
DCHECK(stmt_);
return sqlite3_bind_text(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_text16(int index, const char16* value, int value_len,
Function dtor) {
DCHECK(stmt_);
value_len *= sizeof(char16);
return sqlite3_bind_text16(stmt_, index + 1, value, value_len, dtor);
}
int SQLStatement::bind_value(int index, const sqlite3_value* value) {
DCHECK(stmt_);
return sqlite3_bind_value(stmt_, index + 1, value);
}
int SQLStatement::column_count() {
DCHECK(stmt_);
return sqlite3_column_count(stmt_);
}
int SQLStatement::column_type(int index) {
DCHECK(stmt_);
return sqlite3_column_type(stmt_, index);
}
const void* SQLStatement::column_blob(int index) {
DCHECK(stmt_);
return sqlite3_column_blob(stmt_, index);
}
bool SQLStatement::column_blob_as_vector(int index,
std::vector<unsigned char>* blob) {
DCHECK(stmt_);
const void* p = column_blob(index);
size_t len = column_bytes(index);
blob->resize(len);
if (blob->size() != len) {
return false;
}
if (len > 0)
memcpy(&(blob->front()), p, len);
return true;
}
bool SQLStatement::column_blob_as_string(int index, std::string* blob) {
DCHECK(stmt_);
const void* p = column_blob(index);
size_t len = column_bytes(index);
blob->resize(len);
if (blob->size() != len) {
return false;
}
blob->assign(reinterpret_cast<const char*>(p), len);
return true;
}
int SQLStatement::column_bytes(int index) {
DCHECK(stmt_);
return sqlite3_column_bytes(stmt_, index);
}
int SQLStatement::column_bytes16(int index) {
DCHECK(stmt_);
return sqlite3_column_bytes16(stmt_, index);
}
double SQLStatement::column_double(int index) {
DCHECK(stmt_);
return sqlite3_column_double(stmt_, index);
}
bool SQLStatement::column_bool(int index) {
DCHECK(stmt_);
return sqlite3_column_int(stmt_, index) ? true : false;
}
int SQLStatement::column_int(int index) {
DCHECK(stmt_);
return sqlite3_column_int(stmt_, index);
}
sqlite_int64 SQLStatement::column_int64(int index) {
DCHECK(stmt_);
return sqlite3_column_int64(stmt_, index);
}
const char* SQLStatement::column_text(int index) {
DCHECK(stmt_);
return reinterpret_cast<const char*>(sqlite3_column_text(stmt_, index));
}
bool SQLStatement::column_string(int index, std::string* str) {
DCHECK(stmt_);
DCHECK(str);
const char* s = column_text(index);
str->assign(s ? s : std::string());
return s != NULL;
}
std::string SQLStatement::column_string(int index) {
std::string str;
column_string(index, &str);
return str;
}
const char16* SQLStatement::column_text16(int index) {
DCHECK(stmt_);
return static_cast<const char16*>(sqlite3_column_text16(stmt_, index));
}
bool SQLStatement::column_wstring(int index, std::wstring* str) {
DCHECK(stmt_);
DCHECK(str);
const char* s = column_text(index);
str->assign(s ? UTF8ToWide(s) : std::wstring());
return (s != NULL);
}
std::wstring SQLStatement::column_wstring(int index) {
std::wstring wstr;
column_wstring(index, &wstr);
return wstr;
}
#if defined(USE_SYSTEM_SQLITE)
// This function is a local change to sqlite3 which doesn't exist when one is
// using the system sqlite library. Thus, we stub it out here.
int sqlite3Preload(sqlite3* db) {
return 0;
}
#endif
|
Remove the CHECK() when SQLite is corrupt.
|
Remove the CHECK() when SQLite is corrupt.
Got plenty of crashes in 4.0.211.4
BUG=11908
TEST=none
TBR=bretw
Review URL: http://codereview.chromium.org/217007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@26767 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
timopulkkinen/BubbleFish,M4sse/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,Chilledheart/chromium,keishi/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,Just-D/chromium-1,M4sse/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,rogerwang/chromium,keishi/chromium,markYoungH/chromium.src,rogerwang/chromium,ltilve/chromium,keishi/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ltilve/chromium,patrickm/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,keishi/chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,keishi/chromium,Chilledheart/chromium,M4sse/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,keishi/chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,keishi/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,ltilve/chromium,rogerwang/chromium,zcbenz/cefode-chromium,anirudhSK/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,keishi/chromium,anirudhSK/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,rogerwang/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,robclark/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,hujiajie/pa-chromium,robclark/chromium,timopulkkinen/BubbleFish,rogerwang/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,hujiajie/pa-chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,M4sse/chromium.src,robclark/chromium,zcbenz/cefode-chromium,littlstar/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,zcbenz/cefode-chromium,anirudhSK/chromium,anirudhSK/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,Chilledheart/chromium,jaruba/chromium.src,littlstar/chromium.src,Chilledheart/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,robclark/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,anirudhSK/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,robclark/chromium,dednal/chromium.src,hgl888/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,keishi/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,robclark/chromium
|
1fd3e342d018ad001f693ac65708cdd1871d9025
|
include/distortos/scheduler/ThreadControlBlock.hpp
|
include/distortos/scheduler/ThreadControlBlock.hpp
|
/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-01-12
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"
#include "distortos/architecture/Stack.hpp"
#include "distortos/SchedulingPolicy.hpp"
#include <functional>
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \return effective priority of ThreadControlBlock
*/
uint8_t getEffectivePriority() const
{
return std::max(priority_, boostedPriority_);
}
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return const reference to internal storage for list link
*/
const Link& getLink() const
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return const reference to internal RoundRobinQuantum object
*/
const RoundRobinQuantum& getRoundRobinQuantum() const
{
return roundRobinQuantum_;
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return schedulingPolicy_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return const reference to internal Stack object
*/
const architecture::Stack& getStack() const
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
* protocol) that blocks this thread
*/
void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
priorityInheritanceMutexControlBlock)
{
priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
/**
* \brief Updates boosted priority of the thread.
*
* This function should be called after all operations involving this thread and a mutex with enabled priority
* protocol.
*
* \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
* is about to be blocked on a mutex owned by this thread, default - 0
*/
void updateBoostedPriority(uint8_t boostedPriority = {});
protected:
/**
* \brief ThreadControlBlock constructor.
*
* This constructor is meant for MainThreadControlBlock.
*
* \param [in] stack is an rvalue reference to stack of main()
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock()
{
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief Repositions the thread on the list it's currently on.
*
* This function should be called when thread's effective priority changes.
*
* \attention list_ must not be nullptr
*
* \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
* priority is raised!):
* - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
* temporarily boosting effective priority by 1,
* - false - the thread is moved to the tail of the group of threads with the new priority.
*/
void reposition(bool loweringBefore);
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// list of mutex control blocks with enabled priority protocol owned by this thread
MutexControlBlockList ownedProtocolMutexControlBlocksList_;
/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// scheduling policy of the thread
SchedulingPolicy schedulingPolicy_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
|
/**
* \file
* \brief ThreadControlBlock class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-01-22
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"
#include "distortos/architecture/Stack.hpp"
#include "distortos/SchedulingPolicy.hpp"
#include <functional>
namespace distortos
{
namespace scheduler
{
class ThreadControlBlockList;
/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:
/// state of the thread
enum class State : uint8_t
{
/// state in which thread is created, before being added to Scheduler
New,
/// thread is runnable
Runnable,
/// thread is sleeping
Sleeping,
/// thread is blocked on Semaphore
BlockedOnSemaphore,
/// thread is suspended
Suspended,
/// thread is terminated
Terminated,
/// thread is blocked on Mutex
BlockedOnMutex,
/// thread is blocked on ConditionVariable
BlockedOnConditionVariable,
};
/// reason of thread unblocking
enum class UnblockReason : uint8_t
{
/// explicit request to unblock the thread - normal unblock
UnblockRequest,
/// timeout - unblock via software timer
Timeout,
};
/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;
/**
* \brief ThreadControlBlock constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \return effective priority of ThreadControlBlock
*/
uint8_t getEffectivePriority() const
{
return std::max(priority_, boostedPriority_);
}
/**
* \return iterator to the element on the list, valid only when list_ != nullptr
*/
ThreadControlBlockListIterator getIterator() const
{
return iterator_;
}
/**
* \return reference to internal storage for list link
*/
Link& getLink()
{
return link_;
}
/**
* \return const reference to internal storage for list link
*/
const Link& getLink() const
{
return link_;
}
/**
* \return pointer to list that has this object
*/
ThreadControlBlockList* getList() const
{
return list_;
}
/**
* \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread
*/
const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const
{
return ownedProtocolMutexControlBlocksList_;
}
/**
* \return priority of ThreadControlBlock
*/
uint8_t getPriority() const
{
return priority_;
}
/**
* \return reference to internal RoundRobinQuantum object
*/
RoundRobinQuantum& getRoundRobinQuantum()
{
return roundRobinQuantum_;
}
/**
* \return const reference to internal RoundRobinQuantum object
*/
const RoundRobinQuantum& getRoundRobinQuantum() const
{
return roundRobinQuantum_;
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return schedulingPolicy_;
}
/**
* \return reference to internal Stack object
*/
architecture::Stack& getStack()
{
return stack_;
}
/**
* \return const reference to internal Stack object
*/
const architecture::Stack& getStack() const
{
return stack_;
}
/**
* \return current state of object
*/
State getState() const
{
return state_;
}
/**
* \brief Sets the iterator to the element on the list.
*
* \param [in] iterator is an iterator to the element on the list
*/
void setIterator(const ThreadControlBlockListIterator iterator)
{
iterator_ = iterator;
}
/**
* \brief Sets the list that has this object.
*
* \param [in] list is a pointer to list that has this object
*/
void setList(ThreadControlBlockList* const list)
{
list_ = list;
}
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(uint8_t priority, bool alwaysBehind = {});
/**
* \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
* protocol) that blocks this thread
*/
void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
priorityInheritanceMutexControlBlock)
{
priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);
/**
* \param [in] state is the new state of object
*/
void setState(const State state)
{
state_ = state;
}
/**
* \brief Termination hook function of thread
*
* \attention This function should be called only by Scheduler::remove().
*/
void terminationHook()
{
terminationHook_();
}
/**
* \brief Updates boosted priority of the thread.
*
* This function should be called after all operations involving this thread and a mutex with enabled priority
* protocol.
*
* \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
* is about to be blocked on a mutex owned by this thread, default - 0
*/
void updateBoostedPriority(uint8_t boostedPriority = {});
protected:
/**
* \brief ThreadControlBlock constructor.
*
* This constructor is meant for MainThreadControlBlock.
*
* \param [in] stack is an rvalue reference to stack of main()
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
*/
ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);
/**
* \brief ThreadControlBlock's destructor
*
* \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
*/
~ThreadControlBlock()
{
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
*/
static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));
/**
* \brief Repositions the thread on the list it's currently on.
*
* This function should be called when thread's effective priority changes.
*
* \attention list_ must not be nullptr
*
* \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
* priority is raised!):
* - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
* temporarily boosting effective priority by 1,
* - false - the thread is moved to the tail of the group of threads with the new priority.
*/
void reposition(bool loweringBefore);
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes.
*
* This should be overridden by derived classes.
*/
virtual void terminationHook_() = 0;
/// internal stack object
architecture::Stack stack_;
/// storage for list link
Link link_;
/// list of mutex control blocks with enabled priority protocol owned by this thread
MutexControlBlockList ownedProtocolMutexControlBlocksList_;
/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;
/// pointer to list that has this object
ThreadControlBlockList* list_;
/// iterator to the element on the list, valid only when list_ != nullptr
ThreadControlBlockListIterator iterator_;
/// thread's priority, 0 - lowest, UINT8_MAX - highest
uint8_t priority_;
/// thread's boosted priority, 0 - no boosting
uint8_t boostedPriority_;
/// round-robin quantum
RoundRobinQuantum roundRobinQuantum_;
/// scheduling policy of the thread
SchedulingPolicy schedulingPolicy_;
/// current state of object
State state_;
};
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
|
add ThreadControlBlock::UnblockReason enum class
|
ThreadControlBlock: add ThreadControlBlock::UnblockReason enum class
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos
|
baa1f4191f8b5c8e9ef1b1cf609990cead994d63
|
src/rmp/src/blifParser.cpp
|
src/rmp/src/blifParser.cpp
|
#include "rmp/blifParser.h"
#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/define_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_alternative.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace blif_parser {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
using boost::fusion::at_c;
using boost::spirit::ascii::space_type;
using boost::spirit::ascii::string;
using boost::spirit::qi::lit;
using qi::lexeme;
using ascii::char_;
using ascii::space;
using phoenix::ref;
using qi::double_;
using qi::int_;
void setNewInput(std::string input, rmp::BlifParser* parser)
{
if (input != "\\")
parser->addInput(input);
}
void setNewOutput(std::string output, rmp::BlifParser* parser)
{
if (output != "\\")
parser->addOutput(output);
}
void setNewClock(std::string clock, rmp::BlifParser* parser)
{
if (clock != "\\")
parser->addClock(clock);
}
void setNewInstanceType(std::string type, rmp::BlifParser* parser)
{
parser->addNewInstanceType(type);
}
void setNewGate(std::string gate, rmp::BlifParser* parser)
{
parser->addNewGate(gate);
}
void setGateNets(std::string net, rmp::BlifParser* parser)
{
parser->addConnection(net);
}
void endParser(std::string end, rmp::BlifParser* parser)
{
parser->endParser();
}
template <typename Iterator>
bool parse(Iterator first, Iterator last, rmp::BlifParser* parser)
{
qi::rule<Iterator, std::string(), ascii::space_type> _string;
_string %= lexeme[+(char_ - (' ' | qi::eol))];
qi::rule<std::string::iterator, space_type> rule
= (lit(".model") >> _string >> lit(".inputs")
>> +(!(&lit(".outputs"))
>> _string[boost::bind(&setNewInput, _1, parser)])
>> lit(".outputs")
>> +(!(&lit(".gate")) >> !(&lit(".clock"))
>> _string[boost::bind(&setNewOutput, _1, parser)])
>> -(lit(".clock")
>> +(!(&lit(".gate"))
>> _string[boost::bind(&setNewClock, _1, parser)]))
>> +((lit(".gate")[boost::bind(&setNewInstanceType, "gate", parser)]
| lit(".mlatch")[boost::bind(
&setNewInstanceType, "mlatch", parser)])
>> _string[boost::bind(&setNewGate, _1, parser)]
>> +(!(&lit(".gate")) >> !(&lit(".mlatch")) >> !(&lit(".end"))
>> _string[boost::bind(&setGateNets, _1, parser)]))
>> string(".end")[boost::bind(&endParser, _1, parser)]);
bool valid = qi::phrase_parse(first, last, rule, space);
return valid;
}
} // namespace blif_parser
namespace rmp {
BlifParser::BlifParser()
{
combCount_ = 0;
flopCount_ = 0;
currentInstanceType_ = GateType::None;
currentGate_ = "";
}
void BlifParser::addInput(const std::string& input)
{
inputs_.push_back(input);
}
void BlifParser::addOutput(const std::string& output)
{
outputs_.push_back(output);
}
void BlifParser::addClock(const std::string& clock)
{
clocks_.push_back(clock);
}
void BlifParser::addNewInstanceType(const std::string& type)
{
if (currentInstanceType_ != GateType::None) {
gates_.push_back(
Gate(currentInstanceType_, currentGate_, currentConnections_));
}
currentInstanceType_
= (type == "mlatch")
? GateType::Mlatch
: ((type == "gate") ? GateType::Gate : GateType::None);
if (currentInstanceType_ == GateType::Mlatch)
flopCount_++;
else if (currentInstanceType_ == GateType::Gate)
combCount_++;
currentConnections_.clear();
}
void BlifParser::addNewGate(const std::string& cell_name)
{
currentGate_ = cell_name;
}
void BlifParser::addConnection(const std::string& connection)
{
currentConnections_.push_back(connection);
}
void BlifParser::endParser()
{
if (currentInstanceType_ != GateType::None) {
gates_.push_back(
Gate(currentInstanceType_, currentGate_, currentConnections_));
}
}
const std::vector<std::string>& BlifParser::getInputs() const
{
return inputs_;
}
const std::vector<std::string>& BlifParser::getOutputs() const
{
return outputs_;
}
const std::vector<std::string>& BlifParser::getClocks() const
{
return clocks_;
}
const std::vector<Gate>& BlifParser::getGates() const
{
return gates_;
}
int BlifParser::getCombGateCount() const
{
return combCount_;
}
int BlifParser::getFlopCount() const
{
return flopCount_;
}
// Parsing blif format according to the following spec:
// https://course.ece.cmu.edu/~ee760/760docs/blif.pdf
bool BlifParser::parse(std::string& file_contents)
{
return blif_parser::parse(file_contents.begin(), file_contents.end(), this);
}
} // namespace rmp
|
#include "rmp/blifParser.h"
#include <boost/bind.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/define_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_alternative.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace blif_parser {
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
using boost::fusion::at_c;
using boost::spirit::ascii::space_type;
using boost::spirit::ascii::string;
using boost::spirit::qi::lit;
using qi::lexeme;
using ascii::char_;
using ascii::space;
using phoenix::ref;
using qi::double_;
using qi::int_;
void setNewInput(std::string input, rmp::BlifParser* parser)
{
if (input != "\\")
parser->addInput(input);
}
void setNewOutput(std::string output, rmp::BlifParser* parser)
{
if (output != "\\")
parser->addOutput(output);
}
void setNewClock(std::string clock, rmp::BlifParser* parser)
{
if (clock != "\\")
parser->addClock(clock);
}
void setNewInstanceType(std::string type, rmp::BlifParser* parser)
{
parser->addNewInstanceType(type);
}
void setNewGate(std::string gate, rmp::BlifParser* parser)
{
parser->addNewGate(gate);
}
void setGateNets(std::string net, rmp::BlifParser* parser)
{
parser->addConnection(net);
}
void endParser(std::string end, rmp::BlifParser* parser)
{
parser->endParser();
}
bool parse(std::string::iterator first, std::string::iterator last, rmp::BlifParser* parser)
{
qi::rule<std::string::iterator, std::string(), ascii::space_type> _string;
_string %= lexeme[+(char_ - (' ' | qi::eol))];
qi::rule<std::string::iterator, space_type> rule
= (lit(".model") >> _string >> lit(".inputs")
>> +(!(&lit(".outputs"))
>> _string[boost::bind(&setNewInput, _1, parser)])
>> lit(".outputs")
>> +(!(&lit(".gate")) >> !(&lit(".clock"))
>> _string[boost::bind(&setNewOutput, _1, parser)])
>> -(lit(".clock")
>> +(!(&lit(".gate"))
>> _string[boost::bind(&setNewClock, _1, parser)]))
>> +((lit(".gate")[boost::bind(&setNewInstanceType, "gate", parser)]
| lit(".mlatch")[boost::bind(
&setNewInstanceType, "mlatch", parser)])
>> _string[boost::bind(&setNewGate, _1, parser)]
>> +(!(&lit(".gate")) >> !(&lit(".mlatch")) >> !(&lit(".end"))
>> _string[boost::bind(&setGateNets, _1, parser)]))
>> string(".end")[boost::bind(&endParser, _1, parser)]);
bool valid = qi::phrase_parse(first, last, rule, space);
return valid;
}
} // namespace blif_parser
namespace rmp {
BlifParser::BlifParser()
{
combCount_ = 0;
flopCount_ = 0;
currentInstanceType_ = GateType::None;
currentGate_ = "";
}
void BlifParser::addInput(const std::string& input)
{
inputs_.push_back(input);
}
void BlifParser::addOutput(const std::string& output)
{
outputs_.push_back(output);
}
void BlifParser::addClock(const std::string& clock)
{
clocks_.push_back(clock);
}
void BlifParser::addNewInstanceType(const std::string& type)
{
if (currentInstanceType_ != GateType::None) {
gates_.push_back(
Gate(currentInstanceType_, currentGate_, currentConnections_));
}
currentInstanceType_
= (type == "mlatch")
? GateType::Mlatch
: ((type == "gate") ? GateType::Gate : GateType::None);
if (currentInstanceType_ == GateType::Mlatch)
flopCount_++;
else if (currentInstanceType_ == GateType::Gate)
combCount_++;
currentConnections_.clear();
}
void BlifParser::addNewGate(const std::string& cell_name)
{
currentGate_ = cell_name;
}
void BlifParser::addConnection(const std::string& connection)
{
currentConnections_.push_back(connection);
}
void BlifParser::endParser()
{
if (currentInstanceType_ != GateType::None) {
gates_.push_back(
Gate(currentInstanceType_, currentGate_, currentConnections_));
}
}
const std::vector<std::string>& BlifParser::getInputs() const
{
return inputs_;
}
const std::vector<std::string>& BlifParser::getOutputs() const
{
return outputs_;
}
const std::vector<std::string>& BlifParser::getClocks() const
{
return clocks_;
}
const std::vector<Gate>& BlifParser::getGates() const
{
return gates_;
}
int BlifParser::getCombGateCount() const
{
return combCount_;
}
int BlifParser::getFlopCount() const
{
return flopCount_;
}
// Parsing blif format according to the following spec:
// https://course.ece.cmu.edu/~ee760/760docs/blif.pdf
bool BlifParser::parse(std::string& file_contents)
{
return blif_parser::parse(file_contents.begin(), file_contents.end(), this);
}
} // namespace rmp
|
replace template iterator in blif parser
|
replace template iterator in blif parser
|
C++
|
bsd-3-clause
|
QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD
|
ee9c3d8e6358b609464717aad1e3583fd51d9521
|
ash/content_support/inject.cc
|
ash/content_support/inject.cc
|
// Copyright 2014 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 "ash/content_support/inject.h"
#include "ash/content_support/gpu_support_impl.h"
#include "ash/shell.h"
namespace ash {
void InitContentSupport() {
scoped_ptr<GPUSupportImpl> gpu_support(new GPUSupportImpl);
Shell::GetInstance()->SetGPUSupport(gpu_support.Pass());
}
} // namespace ash
|
// Copyright 2014 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 "ash/content_support/inject.h"
#include "ash/content_support/gpu_support_impl.h"
#include "ash/shell.h"
#include "base/memory/scoped_ptr.h"
namespace ash {
void InitContentSupport() {
scoped_ptr<GPUSupportImpl> gpu_support(new GPUSupportImpl);
Shell::GetInstance()->SetGPUSupport(gpu_support.Pass());
}
} // namespace ash
|
Add include
|
Add include
[email protected]
Review URL: https://codereview.chromium.org/134173003
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@245012 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
markYoungH/chromium.src,jaruba/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,jaruba/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,dednal/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,patrickm/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,Chilledheart/chromium,ltilve/chromium,anirudhSK/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,ltilve/chromium,Just-D/chromium-1,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,dushu1203/chromium.src,ltilve/chromium,markYoungH/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Just-D/chromium-1,jaruba/chromium.src,anirudhSK/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,patrickm/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,M4sse/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,ondra-novak/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk
|
5bf567f5f6ad6250ef0e3b5101fafe0c0bb5e98f
|
tools/driver/swift_symbolgraph_extract_main.cpp
|
tools/driver/swift_symbolgraph_extract_main.cpp
|
//===--- swift_indent_main.cpp - Swift code formatting tool ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// Extracts a Symbol Graph from a .swiftmodule file.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/Version.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/SymbolGraphGen/SymbolGraphGen.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using namespace llvm::opt;
namespace options {
static llvm::cl::OptionCategory Category("swift-symbolgraph-extract Options");
static llvm::cl::opt<std::string>
ModuleName("module-name", llvm::cl::desc("Name of the module to extract (Required)"), llvm::cl::cat(Category));
static llvm::cl::list<std::string>
FrameworkSearchPaths("F", llvm::cl::desc("Add a directory to the framework search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
SystemFrameworkSearchPaths("Fsystem", llvm::cl::desc("Add directory to system framework search path"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
LibrarySearchPaths("L", llvm::cl::desc("Add a directory to the library search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
ImportSearchPaths("I", llvm::cl::desc("Add directory to the import search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
ModuleCachePath("module-cache-path", llvm::cl::desc("Specifies a path to cache modules"), llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
SDK("sdk", llvm::cl::desc("Path to the SDK"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
Target("target", llvm::cl::desc("Target triple (Required)"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
SwiftVersion("swift-version", llvm::cl::desc("Interpret input according to a specific Swift language version number"), llvm::cl::cat(Category));
static llvm::cl::opt<bool>
PrettyPrint("pretty-print", llvm::cl::desc("Pretty-print the resulting Symbol Graph JSON"), llvm::cl::cat(Category));
static llvm::cl::opt<bool>
SkipSynthesizedMembers("skip-synthesized-members",
llvm::cl::desc("Skip members inherited through classes or default implementations"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
MinimumAccessLevel("minimum-access-level", llvm::cl::desc("Include symbols with this access level or more"), llvm::cl::cat(Category));
static llvm::cl::list<std::string>
Xcc("Xcc", llvm::cl::desc("Pass the following command-line flag to Clang"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
ResourceDir("resource-dir",
llvm::cl::desc("Override the directory that holds the compiler resource files"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
OutputDir("output-dir", llvm::cl::desc("Symbol Graph JSON Output Directory (Required)"), llvm::cl::cat(Category));
} // end namespace options
static bool argumentsAreValid() {
bool Valid = true;
if (options::Target.empty()) {
llvm::errs() << "Required -target option is missing\n";
Valid = false;
}
if (options::ModuleName.empty()) {
llvm::errs() << "Required -module-name argument is missing\n";
Valid = false;
}
if (options::OutputDir.empty()) {
llvm::errs() << "Required -output-dir argument is missing\n";
Valid = false;
}
return Valid;
}
int swift_symbolgraph_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr) {
INITIALIZE_LLVM();
llvm::cl::HideUnrelatedOptions(options::Category);
// LLVM Command Line expects to trim off argv[0].
SmallVector<const char *, 8> ArgsWithArgv0 { Argv0 };
ArgsWithArgv0.append(Args.begin(), Args.end());
if (Args.empty()) {
ArgsWithArgv0.push_back("-help");
}
llvm::cl::ParseCommandLineOptions(ArgsWithArgv0.size(),
llvm::makeArrayRef(ArgsWithArgv0).data(),
"Swift Symbol Graph Extractor\n");
if (!argumentsAreValid()) {
llvm::cl::PrintHelpMessage();
return EXIT_FAILURE;
}
if (!llvm::sys::fs::is_directory(options::OutputDir)) {
llvm::errs() << "-output-dir argument '" << options::OutputDir
<< " does not exist or is not a directory\n";
return EXIT_FAILURE;
}
CompilerInvocation Invocation;
Invocation.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
Invocation.setModuleName("swift_symbolgraph_extract");
if (!options::ResourceDir.empty()) {
Invocation.setRuntimeResourcePath(options::ResourceDir);
}
Invocation.setSDKPath(options::SDK);
Invocation.setTargetTriple(options::Target);
for (auto &Arg : options::Xcc) {
Invocation.getClangImporterOptions().ExtraArgs.push_back(Arg);
}
std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;
for (const auto &Path : options::FrameworkSearchPaths) {
FrameworkSearchPaths.push_back({ Path, /*isSystem*/ false});
}
for (const auto &Path : options::SystemFrameworkSearchPaths) {
FrameworkSearchPaths.push_back({ Path, /*isSystem*/ true });
}
Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);
Invocation.getSearchPathOptions().LibrarySearchPaths = options::LibrarySearchPaths;
Invocation.setImportSearchPaths(options::ImportSearchPaths);
Invocation.getLangOptions().EnableObjCInterop = llvm::Triple(options::Target).isOSDarwin();
Invocation.getLangOptions().DebuggerSupport = true;
Invocation.getFrontendOptions().EnableLibraryEvolution = true;
Invocation.setClangModuleCachePath(options::ModuleCachePath);
Invocation.getClangImporterOptions().ModuleCachePath = options::ModuleCachePath;
Invocation.setDefaultPrebuiltCacheIfNecessary();
if (!options::SwiftVersion.empty()) {
using version::Version;
bool isValid = false;
if (auto Version = Version::parseVersionString(options::SwiftVersion,
SourceLoc(), nullptr)) {
if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {
Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;
isValid = true;
}
}
if (!isValid) {
llvm::errs() << "Unsupported Swift Version.\n";
return EXIT_FAILURE;
}
}
symbolgraphgen::SymbolGraphOptions Options {
options::OutputDir,
llvm::Triple(options::Target),
options::PrettyPrint,
AccessLevel::Public,
!options::SkipSynthesizedMembers,
};
if (!options::MinimumAccessLevel.empty()) {
Options.MinimumAccessLevel =
llvm::StringSwitch<AccessLevel>(options::MinimumAccessLevel)
.Case("open", AccessLevel::Open)
.Case("public", AccessLevel::Public)
.Case("internal", AccessLevel::Internal)
.Case("fileprivate", AccessLevel::FilePrivate)
.Case("private", AccessLevel::Private)
.Default(AccessLevel::Public);
}
PrintingDiagnosticConsumer DiagPrinter;
CompilerInstance CI;
CI.getDiags().addConsumer(DiagPrinter);
if (CI.setup(Invocation)) {
llvm::outs() << "Failed to setup compiler instance\n";
return EXIT_FAILURE;
}
auto M = CI.getASTContext().getModuleByName(options::ModuleName);
SmallVector<Identifier, 32> VisibleModuleNames;
CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);
if (!M) {
llvm::errs()
<< "Couldn't load module '" << options::ModuleName << '\''
<< " in the current SDK and search paths.\n";
if (VisibleModuleNames.empty()) {
llvm::errs() << "Could not find any modules.\n";
} else {
std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),
[](const Identifier &A, const Identifier &B) -> bool {
return A.str() < B.str();
});
llvm::errs() << "Current visible modules:\n";
for (const auto &ModuleName : VisibleModuleNames) {
llvm::errs() << ModuleName.str() << "\n";
}
}
return EXIT_FAILURE;
}
const auto &MainFile = M->getMainFile(FileUnitKind::SerializedAST);
llvm::errs() << "Emitting symbol graph for module file: " << MainFile.getModuleDefiningPath() << '\n';
int Success = symbolgraphgen::emitSymbolGraphForModule(M, Options);
// Look for cross-import overlays that the given module imports.
// Clear out the diagnostic printer before looking for cross-import overlay modules,
// since some SDK modules can cause errors in the getModuleByName() call. The call
// itself will properly return nullptr after this failure, so for our purposes we
// don't need to print these errors.
CI.getDiags().removeConsumer(DiagPrinter);
for (const auto &ModuleName : VisibleModuleNames) {
if (ModuleName.str().startswith("_")) {
auto CIM = CI.getASTContext().getModuleByName(ModuleName.str());
if (CIM && CIM->isCrossImportOverlayOf(M)) {
const auto &CIMainFile = CIM->getMainFile(FileUnitKind::SerializedAST);
llvm::errs() << "Emitting symbol graph for cross-import overlay module file: "
<< CIMainFile.getModuleDefiningPath() << '\n';
Success |= symbolgraphgen::emitSymbolGraphForModule(CIM, Options);
}
}
}
return Success;
}
|
//===--- swift_indent_main.cpp - Swift code formatting tool ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// Extracts a Symbol Graph from a .swiftmodule file.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/Version.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/SymbolGraphGen/SymbolGraphGen.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using namespace llvm::opt;
namespace options {
static llvm::cl::OptionCategory Category("swift-symbolgraph-extract Options");
static llvm::cl::opt<std::string>
ModuleName("module-name", llvm::cl::desc("Name of the module to extract (Required)"), llvm::cl::cat(Category));
static llvm::cl::list<std::string>
FrameworkSearchPaths("F", llvm::cl::desc("Add a directory to the framework search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
SystemFrameworkSearchPaths("Fsystem", llvm::cl::desc("Add directory to system framework search path"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
LibrarySearchPaths("L", llvm::cl::desc("Add a directory to the library search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::list<std::string>
ImportSearchPaths("I", llvm::cl::desc("Add directory to the import search paths"), llvm::cl::ZeroOrMore,
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
ModuleCachePath("module-cache-path", llvm::cl::desc("Specifies a path to cache modules"), llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
SDK("sdk", llvm::cl::desc("Path to the SDK"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
Target("target", llvm::cl::desc("Target triple (Required)"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
SwiftVersion("swift-version", llvm::cl::desc("Interpret input according to a specific Swift language version number"), llvm::cl::cat(Category));
static llvm::cl::opt<bool>
PrettyPrint("pretty-print", llvm::cl::desc("Pretty-print the resulting Symbol Graph JSON"), llvm::cl::cat(Category));
static llvm::cl::opt<bool>
SkipSynthesizedMembers("skip-synthesized-members",
llvm::cl::desc("Skip members inherited through classes or default implementations"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
MinimumAccessLevel("minimum-access-level", llvm::cl::desc("Include symbols with this access level or more"), llvm::cl::cat(Category));
static llvm::cl::list<std::string>
Xcc("Xcc", llvm::cl::desc("Pass the following command-line flag to Clang"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
ResourceDir("resource-dir",
llvm::cl::desc("Override the directory that holds the compiler resource files"),
llvm::cl::cat(Category));
static llvm::cl::opt<std::string>
OutputDir("output-dir", llvm::cl::desc("Symbol Graph JSON Output Directory (Required)"), llvm::cl::cat(Category));
} // end namespace options
static bool argumentsAreValid() {
bool Valid = true;
if (options::Target.empty()) {
llvm::errs() << "Required -target option is missing\n";
Valid = false;
}
if (options::ModuleName.empty()) {
llvm::errs() << "Required -module-name argument is missing\n";
Valid = false;
}
if (options::OutputDir.empty()) {
llvm::errs() << "Required -output-dir argument is missing\n";
Valid = false;
}
return Valid;
}
int swift_symbolgraph_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr) {
INITIALIZE_LLVM();
llvm::cl::HideUnrelatedOptions(options::Category);
// LLVM Command Line expects to trim off argv[0].
SmallVector<const char *, 8> ArgsWithArgv0 { Argv0 };
ArgsWithArgv0.append(Args.begin(), Args.end());
if (Args.empty()) {
ArgsWithArgv0.push_back("-help");
}
llvm::cl::ParseCommandLineOptions(ArgsWithArgv0.size(),
llvm::makeArrayRef(ArgsWithArgv0).data(),
"Swift Symbol Graph Extractor\n");
if (!argumentsAreValid()) {
llvm::cl::PrintHelpMessage();
return EXIT_FAILURE;
}
if (!llvm::sys::fs::is_directory(options::OutputDir)) {
llvm::errs() << "-output-dir argument '" << options::OutputDir
<< " does not exist or is not a directory\n";
return EXIT_FAILURE;
}
CompilerInvocation Invocation;
Invocation.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
Invocation.setModuleName("swift_symbolgraph_extract");
if (!options::ResourceDir.empty()) {
Invocation.setRuntimeResourcePath(options::ResourceDir);
}
Invocation.setSDKPath(options::SDK);
Invocation.setTargetTriple(options::Target);
for (auto &Arg : options::Xcc) {
Invocation.getClangImporterOptions().ExtraArgs.push_back(Arg);
}
std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;
for (const auto &Path : options::FrameworkSearchPaths) {
FrameworkSearchPaths.push_back({ Path, /*isSystem*/ false});
}
for (const auto &Path : options::SystemFrameworkSearchPaths) {
FrameworkSearchPaths.push_back({ Path, /*isSystem*/ true });
}
Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);
Invocation.getSearchPathOptions().LibrarySearchPaths = options::LibrarySearchPaths;
Invocation.setImportSearchPaths(options::ImportSearchPaths);
Invocation.getLangOptions().EnableObjCInterop = llvm::Triple(options::Target).isOSDarwin();
Invocation.getLangOptions().DebuggerSupport = true;
Invocation.getFrontendOptions().EnableLibraryEvolution = true;
Invocation.setClangModuleCachePath(options::ModuleCachePath);
Invocation.getClangImporterOptions().ModuleCachePath = options::ModuleCachePath;
Invocation.setDefaultPrebuiltCacheIfNecessary();
if (!options::SwiftVersion.empty()) {
using version::Version;
bool isValid = false;
if (auto Version = Version::parseVersionString(options::SwiftVersion,
SourceLoc(), nullptr)) {
if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {
Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;
isValid = true;
}
}
if (!isValid) {
llvm::errs() << "Unsupported Swift Version.\n";
return EXIT_FAILURE;
}
}
symbolgraphgen::SymbolGraphOptions Options {
options::OutputDir,
llvm::Triple(options::Target),
options::PrettyPrint,
AccessLevel::Public,
!options::SkipSynthesizedMembers,
};
if (!options::MinimumAccessLevel.empty()) {
Options.MinimumAccessLevel =
llvm::StringSwitch<AccessLevel>(options::MinimumAccessLevel)
.Case("open", AccessLevel::Open)
.Case("public", AccessLevel::Public)
.Case("internal", AccessLevel::Internal)
.Case("fileprivate", AccessLevel::FilePrivate)
.Case("private", AccessLevel::Private)
.Default(AccessLevel::Public);
}
PrintingDiagnosticConsumer DiagPrinter;
CompilerInstance CI;
CI.getDiags().addConsumer(DiagPrinter);
if (CI.setup(Invocation)) {
llvm::outs() << "Failed to setup compiler instance\n";
return EXIT_FAILURE;
}
auto M = CI.getASTContext().getModuleByName(options::ModuleName);
SmallVector<Identifier, 32> VisibleModuleNames;
CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);
if (!M) {
llvm::errs()
<< "Couldn't load module '" << options::ModuleName << '\''
<< " in the current SDK and search paths.\n";
if (VisibleModuleNames.empty()) {
llvm::errs() << "Could not find any modules.\n";
} else {
std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),
[](const Identifier &A, const Identifier &B) -> bool {
return A.str() < B.str();
});
llvm::errs() << "Current visible modules:\n";
for (const auto &ModuleName : VisibleModuleNames) {
llvm::errs() << ModuleName.str() << "\n";
}
}
return EXIT_FAILURE;
}
const auto &MainFile = M->getMainFile(FileUnitKind::SerializedAST);
llvm::errs() << "Emitting symbol graph for module file: " << MainFile.getModuleDefiningPath() << '\n';
int Success = symbolgraphgen::emitSymbolGraphForModule(M, Options);
// Look for cross-import overlays that the given module imports.
// Clear out the diagnostic printer before looking for cross-import overlay modules,
// since some SDK modules can cause errors in the getModuleByName() call. The call
// itself will properly return nullptr after this failure, so for our purposes we
// don't need to print these errors.
CI.removeDiagnosticConsumer(&DiagPrinter);
for (const auto &ModuleName : VisibleModuleNames) {
if (ModuleName.str().startswith("_")) {
auto CIM = CI.getASTContext().getModuleByName(ModuleName.str());
if (CIM && CIM->isCrossImportOverlayOf(M)) {
const auto &CIMainFile = CIM->getMainFile(FileUnitKind::SerializedAST);
llvm::errs() << "Emitting symbol graph for cross-import overlay module file: "
<< CIMainFile.getModuleDefiningPath() << '\n';
Success |= symbolgraphgen::emitSymbolGraphForModule(CIM, Options);
}
}
}
return Success;
}
|
remove DiagPrinter directly from the CompilerInvocation
|
remove DiagPrinter directly from the CompilerInvocation
|
C++
|
apache-2.0
|
jmgc/swift,glessard/swift,roambotics/swift,tkremenek/swift,gregomni/swift,tkremenek/swift,ahoppen/swift,parkera/swift,roambotics/swift,apple/swift,rudkx/swift,glessard/swift,atrick/swift,ahoppen/swift,hooman/swift,apple/swift,ahoppen/swift,gregomni/swift,jmgc/swift,ahoppen/swift,JGiola/swift,apple/swift,parkera/swift,xwu/swift,parkera/swift,benlangmuir/swift,roambotics/swift,roambotics/swift,tkremenek/swift,xwu/swift,xwu/swift,JGiola/swift,rudkx/swift,hooman/swift,JGiola/swift,xwu/swift,tkremenek/swift,glessard/swift,JGiola/swift,hooman/swift,gregomni/swift,tkremenek/swift,rudkx/swift,parkera/swift,roambotics/swift,atrick/swift,benlangmuir/swift,jmgc/swift,atrick/swift,parkera/swift,jmgc/swift,parkera/swift,xwu/swift,xwu/swift,tkremenek/swift,apple/swift,hooman/swift,hooman/swift,gregomni/swift,parkera/swift,apple/swift,benlangmuir/swift,apple/swift,rudkx/swift,jmgc/swift,jmgc/swift,ahoppen/swift,glessard/swift,glessard/swift,rudkx/swift,parkera/swift,atrick/swift,JGiola/swift,benlangmuir/swift,hooman/swift,hooman/swift,jmgc/swift,tkremenek/swift,gregomni/swift,atrick/swift,benlangmuir/swift,gregomni/swift,roambotics/swift,glessard/swift,rudkx/swift,atrick/swift,JGiola/swift,benlangmuir/swift,xwu/swift,ahoppen/swift
|
3b305aed3e4925ba83bf56fb46ba0b1271529a2b
|
chrome/test/ui/ppapi_uitest.cc
|
chrome/test/ui/ppapi_uitest.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, FAILS_Buffer) {
RunTest("Buffer");
}
// http://bugs.chromium.org/51345
TEST_F(PPAPITest, DISABLED_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
TEST_F(PPAPITest, FileRef) {
RunTestViaHTTP("FileRef");
}
TEST_F(PPAPITest, FileIO) {
RunTestViaHTTP("FileIO");
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("third_party"));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// http://bugs.chromium.org/51345
TEST_F(PPAPITest, DISABLED_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
|
Revert 63271 - Add the FileRef and FileIO tests to ppapi_uitest.cc
|
Revert 63271 - Add the FileRef and FileIO tests to ppapi_uitest.cc
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/3883003
[email protected]
Review URL: http://codereview.chromium.org/4019001
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@63282 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium
|
f5bb899e48b28f9d0ab842c0659ea99e34c95909
|
chrome/test/ui/ppapi_uitest.cc
|
chrome/test/ui/ppapi_uitest.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
// In-process plugin test runner. See OutOfProcessPPAPITest below for the
// out-of-process version.
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Smooth scrolling confuses the scrollbar test.
launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
std::string query("testcase=");
query += test_case;
replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(
test_server.GetURL("files/test_case.html?testcase=" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
// See comment above TestingInstance in ppapi/test/testing_instance.h.
// Basically it sets a series of numbered cookies. The value of "..." means
// it's still working and we should continue to wait, any other value
// indicates completion (in this case it will start with "PASS" or "FAIL").
// This keeps us from timing out on cookie waits for long tests.
int progress_number = 0;
std::string progress;
while (true) {
std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d",
progress_number);
progress = WaitUntilCookieNonEmpty(tab.get(), test_url,
cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());
if (progress != "...")
break;
progress_number++;
}
if (progress_number == 0) {
// Failing the first time probably means the plugin wasn't loaded.
ASSERT_FALSE(progress.empty())
<< "Plugin couldn't be loaded. Make sure the PPAPI test plugin is "
<< "built, in the right place, and doesn't have any missing symbols.";
} else {
ASSERT_FALSE(progress.empty()) << "Test timed out.";
}
EXPECT_STREQ("PASS", progress.c_str());
}
};
// Variant of PPAPITest that runs plugins out-of-process to test proxy
// codepaths.
class OutOfProcessPPAPITest : public PPAPITest {
public:
OutOfProcessPPAPITest() {
// Run PPAPI out-of-process to exercise proxy implementations.
launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);
}
};
// Use these macros to run the tests for a specific interface.
// Most interfaces should be tested with both macros.
#define TEST_PPAPI_IN_PROCESS(test_name) \
TEST_F(PPAPITest, test_name) { \
RunTest(#test_name); \
}
#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \
TEST_F(OutOfProcessPPAPITest, test_name) { \
RunTest(#test_name); \
}
// Similar macros that test over HTTP.
#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \
TEST_F(PPAPITest, test_name) { \
RunTestViaHTTP(#test_name); \
}
#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \
TEST_F(OutOfProcessPPAPITest, test_name) { \
RunTestViaHTTP(#test_name); \
}
//
// Interface tests.
//
TEST_PPAPI_IN_PROCESS(Broker)
TEST_PPAPI_OUT_OF_PROCESS(Broker)
TEST_PPAPI_IN_PROCESS(Core)
TEST_PPAPI_OUT_OF_PROCESS(Core)
TEST_PPAPI_IN_PROCESS(CursorControl)
TEST_PPAPI_OUT_OF_PROCESS(CursorControl)
TEST_PPAPI_IN_PROCESS(Instance)
// http://crbug.com/91729
TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)
TEST_PPAPI_IN_PROCESS(Graphics2D)
TEST_PPAPI_OUT_OF_PROCESS(Graphics2D)
TEST_PPAPI_IN_PROCESS(ImageData)
TEST_PPAPI_OUT_OF_PROCESS(ImageData)
TEST_PPAPI_IN_PROCESS(Buffer)
TEST_PPAPI_OUT_OF_PROCESS(Buffer)
TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)
// http://crbug.com/89961
#if defined(OS_WIN)
// It often takes too long time (and fails otherwise) on Windows.
#define MAYBE_URLLoader DISABLED_URLLoader
#else
#define MAYBE_URLLoader FAILS_URLLoader
#endif
TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {
RunTestViaHTTP("URLLoader");
}
TEST_PPAPI_IN_PROCESS(PaintAggregator)
TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)
TEST_PPAPI_IN_PROCESS(Scrollbar)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {
RunTest("Scrollbar");
}
TEST_PPAPI_IN_PROCESS(URLUtil)
TEST_PPAPI_OUT_OF_PROCESS(URLUtil)
TEST_PPAPI_IN_PROCESS(CharSet)
TEST_PPAPI_OUT_OF_PROCESS(CharSet)
TEST_PPAPI_IN_PROCESS(Crypto)
TEST_PPAPI_OUT_OF_PROCESS(Crypto)
TEST_PPAPI_IN_PROCESS(Var)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Var) {
RunTest("Var");
}
TEST_PPAPI_IN_PROCESS(VarDeprecated)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)
// Windows defines 'PostMessage', so we have to undef it.
#ifdef PostMessage
#undef PostMessage
#endif
TEST_PPAPI_IN_PROCESS(PostMessage)
#if !defined(OS_WIN)
// Times out on Windows XP: http://crbug.com/95557
TEST_PPAPI_OUT_OF_PROCESS(PostMessage)
#endif
TEST_PPAPI_IN_PROCESS(Memory)
TEST_PPAPI_OUT_OF_PROCESS(Memory)
TEST_PPAPI_IN_PROCESS(VideoDecoder)
TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)
// http://crbug.com/90039 and http://crbug.com/83443 (Mac)
TEST_F(PPAPITest, FAILS_FileIO) {
RunTestViaHTTP("FileIO");
}
TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) {
RunTestViaHTTP("FileIO");
}
TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)
TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)
TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)
// http://crbug.com/96767
#if !defined(OS_MACOSX)
TEST_F(PPAPITest, FLAKY_FlashFullscreen) {
RunTestViaHTTP("FlashFullscreen");
}
TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {
RunTestViaHTTP("FlashFullscreen");
}
// New implementation only honors fullscreen requests within a context of
// a user gesture. Since we do not yet have an infrastructure for testing
// those under ppapi_tests, the tests below time out when run automtically.
// To test the code, run them manually following the directions here:
// www.chromium.org/developers/design-documents/pepper-plugin-implementation
// and click on the plugin area (gray square) to force fullscreen mode and
// get the test unstuck.
TEST_F(PPAPITest, DISABLED_Fullscreen) {
RunTestViaHTTP("Fullscreen");
}
TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {
RunTestViaHTTP("Fullscreen");
}
#endif
#if defined(OS_POSIX)
#define MAYBE_DirectoryReader FLAKY_DirectoryReader
#else
#define MAYBE_DirectoryReader DirectoryReader
#endif
// Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008
TEST_F(PPAPITest, MAYBE_DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
#if defined(ENABLE_P2P_APIS)
// Flaky. http://crbug.com/84294
TEST_F(PPAPITest, FLAKY_Transport) {
RunTest("Transport");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Transport) {
RunTestViaHTTP("Transport");
}
#endif // ENABLE_P2P_APIS
TEST_PPAPI_IN_PROCESS(UMA)
// There is no proxy.
TEST_F(OutOfProcessPPAPITest, FAILS_UMA) {
RunTest("UMA");
}
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
// In-process plugin test runner. See OutOfProcessPPAPITest below for the
// out-of-process version.
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Smooth scrolling confuses the scrollbar test.
launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
std::string query("testcase=");
query += test_case;
replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(
test_server.GetURL("files/test_case.html?testcase=" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
// See comment above TestingInstance in ppapi/test/testing_instance.h.
// Basically it sets a series of numbered cookies. The value of "..." means
// it's still working and we should continue to wait, any other value
// indicates completion (in this case it will start with "PASS" or "FAIL").
// This keeps us from timing out on cookie waits for long tests.
int progress_number = 0;
std::string progress;
while (true) {
std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d",
progress_number);
progress = WaitUntilCookieNonEmpty(tab.get(), test_url,
cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());
if (progress != "...")
break;
progress_number++;
}
if (progress_number == 0) {
// Failing the first time probably means the plugin wasn't loaded.
ASSERT_FALSE(progress.empty())
<< "Plugin couldn't be loaded. Make sure the PPAPI test plugin is "
<< "built, in the right place, and doesn't have any missing symbols.";
} else {
ASSERT_FALSE(progress.empty()) << "Test timed out.";
}
EXPECT_STREQ("PASS", progress.c_str());
}
};
// Variant of PPAPITest that runs plugins out-of-process to test proxy
// codepaths.
class OutOfProcessPPAPITest : public PPAPITest {
public:
OutOfProcessPPAPITest() {
// Run PPAPI out-of-process to exercise proxy implementations.
launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);
}
};
// Use these macros to run the tests for a specific interface.
// Most interfaces should be tested with both macros.
#define TEST_PPAPI_IN_PROCESS(test_name) \
TEST_F(PPAPITest, test_name) { \
RunTest(#test_name); \
}
#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \
TEST_F(OutOfProcessPPAPITest, test_name) { \
RunTest(#test_name); \
}
// Similar macros that test over HTTP.
#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \
TEST_F(PPAPITest, test_name) { \
RunTestViaHTTP(#test_name); \
}
#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \
TEST_F(OutOfProcessPPAPITest, test_name) { \
RunTestViaHTTP(#test_name); \
}
//
// Interface tests.
//
TEST_PPAPI_IN_PROCESS(Broker)
TEST_PPAPI_OUT_OF_PROCESS(Broker)
TEST_PPAPI_IN_PROCESS(Core)
TEST_PPAPI_OUT_OF_PROCESS(Core)
TEST_PPAPI_IN_PROCESS(CursorControl)
TEST_PPAPI_OUT_OF_PROCESS(CursorControl)
TEST_PPAPI_IN_PROCESS(Instance)
// http://crbug.com/91729
TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)
TEST_PPAPI_IN_PROCESS(Graphics2D)
TEST_PPAPI_OUT_OF_PROCESS(Graphics2D)
TEST_PPAPI_IN_PROCESS(ImageData)
TEST_PPAPI_OUT_OF_PROCESS(ImageData)
TEST_PPAPI_IN_PROCESS(Buffer)
TEST_PPAPI_OUT_OF_PROCESS(Buffer)
TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)
// http://crbug.com/89961
#if defined(OS_WIN)
// It often takes too long time (and fails otherwise) on Windows.
#define MAYBE_URLLoader DISABLED_URLLoader
#else
#define MAYBE_URLLoader FAILS_URLLoader
#endif
TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {
RunTestViaHTTP("URLLoader");
}
TEST_PPAPI_IN_PROCESS(PaintAggregator)
TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)
TEST_PPAPI_IN_PROCESS(Scrollbar)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {
RunTest("Scrollbar");
}
TEST_PPAPI_IN_PROCESS(URLUtil)
TEST_PPAPI_OUT_OF_PROCESS(URLUtil)
TEST_PPAPI_IN_PROCESS(CharSet)
TEST_PPAPI_OUT_OF_PROCESS(CharSet)
TEST_PPAPI_IN_PROCESS(Crypto)
TEST_PPAPI_OUT_OF_PROCESS(Crypto)
TEST_PPAPI_IN_PROCESS(Var)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Var) {
RunTest("Var");
}
TEST_PPAPI_IN_PROCESS(VarDeprecated)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)
// Windows defines 'PostMessage', so we have to undef it.
#ifdef PostMessage
#undef PostMessage
#endif
TEST_PPAPI_IN_PROCESS(PostMessage)
#if !defined(OS_WIN)
// Times out on Windows XP: http://crbug.com/95557
TEST_PPAPI_OUT_OF_PROCESS(PostMessage)
#endif
TEST_PPAPI_IN_PROCESS(Memory)
TEST_PPAPI_OUT_OF_PROCESS(Memory)
TEST_PPAPI_IN_PROCESS(VideoDecoder)
TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)
// http://crbug.com/90039 and http://crbug.com/83443 (Mac)
TEST_F(PPAPITest, FAILS_FileIO) {
RunTestViaHTTP("FileIO");
}
#ifdef ADDRESS_SANITIZER
#define MAYBE_FileIO DISABLED_FileIO
#else
#define MAYBE_FileIO FAILS_FileIO
#endif
TEST_F(OutOfProcessPPAPITest, MAYBE_FileIO) {
RunTestViaHTTP("FileIO");
}
TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)
TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)
TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)
// http://crbug.com/96767
#if !defined(OS_MACOSX)
TEST_F(PPAPITest, FLAKY_FlashFullscreen) {
RunTestViaHTTP("FlashFullscreen");
}
TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {
RunTestViaHTTP("FlashFullscreen");
}
// New implementation only honors fullscreen requests within a context of
// a user gesture. Since we do not yet have an infrastructure for testing
// those under ppapi_tests, the tests below time out when run automtically.
// To test the code, run them manually following the directions here:
// www.chromium.org/developers/design-documents/pepper-plugin-implementation
// and click on the plugin area (gray square) to force fullscreen mode and
// get the test unstuck.
TEST_F(PPAPITest, DISABLED_Fullscreen) {
RunTestViaHTTP("Fullscreen");
}
TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {
RunTestViaHTTP("Fullscreen");
}
#endif
#if defined(OS_POSIX)
#define MAYBE_DirectoryReader FLAKY_DirectoryReader
#else
#define MAYBE_DirectoryReader DirectoryReader
#endif
// Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008
TEST_F(PPAPITest, MAYBE_DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
#if defined(ENABLE_P2P_APIS)
// Flaky. http://crbug.com/84294
TEST_F(PPAPITest, FLAKY_Transport) {
RunTest("Transport");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Transport) {
RunTestViaHTTP("Transport");
}
#endif // ENABLE_P2P_APIS
TEST_PPAPI_IN_PROCESS(UMA)
// There is no proxy.
TEST_F(OutOfProcessPPAPITest, FAILS_UMA) {
RunTest("UMA");
}
|
Disable OutOfProcessPPAPITest.FAILS_FileIO under AddressSanitizer
|
Disable OutOfProcessPPAPITest.FAILS_FileIO under AddressSanitizer
BUG=83443
TBR=sanga
Review URL: http://codereview.chromium.org/8359028
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@106712 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium
|
089001bd9276f634a2455e7734a213a5d01c8a23
|
atom/browser/node_debugger.cc
|
atom/browser/node_debugger.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/node_debugger.h"
#include <memory>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "libplatform/libplatform.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {}
NodeDebugger::~NodeDebugger() {}
void NodeDebugger::Start() {
auto* inspector = env_->inspector_agent();
if (inspector == nullptr)
return;
std::vector<std::string> args;
for (auto& arg : base::CommandLine::ForCurrentProcess()->argv()) {
#if defined(OS_WIN)
args.push_back(base::UTF16ToUTF8(arg));
#else
args.push_back(arg);
#endif
}
auto options = std::make_shared<node::DebugOptions>();
std::vector<std::string> exec_args;
std::vector<std::string> v8_args;
std::string error;
node::options_parser::DebugOptionsParser::instance.Parse(
&args, &exec_args, &v8_args, options.get(),
node::options_parser::kDisallowedInEnvironment, &error);
if (!error.empty()) {
// TODO(jeremy): what's the appropriate behaviour here?
LOG(ERROR) << "Error parsing node options: " << error;
}
// Set process._debugWaitConnect if --inspect-brk was specified to stop
// the debugger on the first line
if (options->wait_for_connect()) {
mate::Dictionary process(env_->isolate(), env_->process_object());
process.Set("_breakFirstLine", true);
}
const char* path = "";
if (inspector->Start(path, options))
DCHECK(env_->inspector_agent()->IsListening());
}
} // namespace atom
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/node_debugger.h"
#include <memory>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "libplatform/libplatform.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {}
NodeDebugger::~NodeDebugger() {}
void NodeDebugger::Start() {
auto* inspector = env_->inspector_agent();
if (inspector == nullptr)
return;
std::vector<std::string> args;
for (auto& arg : base::CommandLine::ForCurrentProcess()->argv()) {
#if defined(OS_WIN)
args.push_back(base::UTF16ToUTF8(arg));
#else
args.push_back(arg);
#endif
}
auto options = std::make_shared<node::DebugOptions>();
std::vector<std::string> exec_args;
std::vector<std::string> v8_args;
std::vector<std::string> errors;
node::options_parser::DebugOptionsParser::instance.Parse(
&args, &exec_args, &v8_args, options.get(),
node::options_parser::kDisallowedInEnvironment, &errors);
if (!errors.empty()) {
std::string error_str;
for (const auto& error : errors)
error_str += error;
// TODO(jeremy): what's the appropriate behaviour here?
LOG(ERROR) << "Error parsing node options: " << error_str;
}
// Set process._debugWaitConnect if --inspect-brk was specified to stop
// the debugger on the first line
if (options->wait_for_connect()) {
mate::Dictionary process(env_->isolate(), env_->process_object());
process.Set("_breakFirstLine", true);
}
const char* path = "";
if (inspector->Start(path, options, true /* is_main */))
DCHECK(env_->inspector_agent()->IsListening());
}
} // namespace atom
|
update node inspector api usage
|
fix: update node inspector api usage
|
C++
|
mit
|
seanchas116/electron,bpasero/electron,seanchas116/electron,electron/electron,gerhardberger/electron,seanchas116/electron,gerhardberger/electron,bpasero/electron,electron/electron,bpasero/electron,electron/electron,electron/electron,gerhardberger/electron,seanchas116/electron,gerhardberger/electron,gerhardberger/electron,gerhardberger/electron,the-ress/electron,bpasero/electron,the-ress/electron,electron/electron,bpasero/electron,the-ress/electron,the-ress/electron,seanchas116/electron,the-ress/electron,the-ress/electron,seanchas116/electron,electron/electron,the-ress/electron,electron/electron,gerhardberger/electron,bpasero/electron,bpasero/electron
|
536e89b0c80c6121c9e875ed320f8637019a82b0
|
json/testparsestring.cpp
|
json/testparsestring.cpp
|
#include <iostream>
#include <iomanip> // for std::setw
#include <nlohmann/json.hpp>
using json = nlohmann::json;
bool parse_and_dump(const char* text, json& result)
{
// parse and serialize JSON
result = json::parse(text);
//std::cout << std::setw(4) << j_complete << "\n\n";
return true;
}
int test_parse_string()
{
// a JSON text
auto text = R"(
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
)";
json myobj;
if ( parse_and_dump(text, myobj) ) {
std::cout << std::setw(4) << myobj << "\n\n";
return true;
}
return false;
}
|
#include <iostream>
#include <iomanip> // for std::setw
#include <nlohmann/json.hpp>
bool parse_and_dump(const char* text, nlohmann::json& result)
{
using json = nlohmann::json;
// parse and serialize JSON
result = json::parse(text);
//std::cout << std::setw(4) << j_complete << "\n\n";
return true;
}
int test_parse_string()
{
using namespace std;
using json = nlohmann::json;
cout << __func__ << " uses a RAW string to initialize a json object\n";
// a JSON text
auto text = R"(
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
)";
json myobj;
auto query = myobj.meta();
cout << "json.hpp version: " << query["version"]["string"] << endl;
if ( parse_and_dump(text, myobj) ) {
cout << std::setw(4) << myobj << "\n\n";
return true;
}
return false;
}
|
UPDATE json, add some message for details
|
UPDATE json, add some message for details
|
C++
|
mit
|
ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt
|
84f31cef60ccddab38589b5ac90678fbd9208785
|
interpreter/cling/lib/Interpreter/ValuePrinter.cpp
|
interpreter/cling/lib/Interpreter/ValuePrinter.cpp
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/Value.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValuePublic(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, const char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v,
const cling::ValuePrinterInfo& VPI) {
const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr();
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl())
if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
cling::Value* V = (cling::Value*)v;
if (V->isValid()) {
o << "boxes [";
const clang::ASTContext& C = *VPI.getASTContext();
o <<
"(" <<
V->type.getAsString(C.getPrintingPolicy()) <<
") ";
clang::QualType valType = V->type.getDesugaredType(C);
if (valType->isPointerType())
o << V->value.PointerVal;
else if (valType->isFloatingType())
o << V->value.DoubleVal;
else if (valType->isIntegerType())
o << V->value.IntVal.getSExtValue();
else if (valType->isBooleanType())
o << V->value.IntVal.getBoolValue();
o << "]\n";
return;
} else
o << "<<<invalid>>> ";
}
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p,
const cling::ValuePrinterInfo& VPI) {
clang::QualType Ty = VPI.getExpr()->getType();
const clang::ASTContext& C = *VPI.getASTContext();
Ty = Ty.getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Char_U:
case clang::BuiltinType::UChar:
case clang::BuiltinType::Char_S:
case clang::BuiltinType::SChar: StreamChar(o, *(char*)p); break;
case clang::BuiltinType::Short: o << *(short*)p << "\n"; break;
case clang::BuiltinType::UShort: o << *(unsigned short*)p << "\n"; break;
case clang::BuiltinType::Int: o << *(int*)p << "\n"; break;
case clang::BuiltinType::UInt: o << *(unsigned int*)p << "\n"; break;
case clang::BuiltinType::Long: o << *(long*)p << "\n"; break;
case clang::BuiltinType::ULong: o << *(unsigned long*)p << "\n"; break;
case clang::BuiltinType::LongLong: o << *(long long*)p << "\n"; break;
case clang::BuiltinType::ULongLong: o << *(unsigned long long*)p << "\n";
break;
case clang::BuiltinType::Float: o << *(float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(double*)p << "\n"; break;
default:
StreamObj(o, p, VPI);
}
}
else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
StreamObj(o, p, VPI);
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()));
}
else if (Ty->isEnumeralType()) {
StreamObj(o, p, VPI);
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(uint64_t*)p;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << "\n";
}
else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p, VPI);
}
namespace cling {
void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, VPI);
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/Interpreter/Value.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
// Implements the CValuePrinter interface.
extern "C" void cling_PrintValue(void* /*clang::Expr**/ E,
void* /*clang::ASTContext**/ C,
const void* value) {
clang::Expr* Exp = (clang::Expr*)E;
clang::ASTContext* Context = (clang::ASTContext*)C;
cling::ValuePrinterInfo VPI(Exp, Context);
cling::printValuePublic(llvm::outs(), value, value, VPI);
cling::flushOStream(llvm::outs());
}
static void StreamChar(llvm::raw_ostream& o, const char v) {
o << '"' << v << "\"\n";
}
static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) {
o << '"';
const char* p = v;
for (;*p && p - v < 128; ++p) {
o << *p;
}
if (*p) o << "\"...\n";
else o << "\"\n";
}
static void StreamRef(llvm::raw_ostream& o, const void* v) {
o <<"&" << v << "\n";
}
static void StreamPtr(llvm::raw_ostream& o, const void* v) {
o << v << "\n";
}
static void StreamObj(llvm::raw_ostream& o, const void* v,
const cling::ValuePrinterInfo& VPI) {
const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr();
if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl())
if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) {
cling::Value* V = (cling::Value*)v;
if (V->isValid()) {
o << "boxes [";
const clang::ASTContext& C = *VPI.getASTContext();
o <<
"(" <<
V->type.getAsString(C.getPrintingPolicy()) <<
") ";
clang::QualType valType = V->type.getDesugaredType(C);
if (valType->isPointerType())
o << V->value.PointerVal;
else if (valType->isFloatingType())
o << V->value.DoubleVal;
else if (valType->isIntegerType())
o << V->value.IntVal.getSExtValue();
else if (valType->isBooleanType())
o << V->value.IntVal.getBoolValue();
o << "]\n";
return;
} else
o << "<<<invalid>>> ";
}
// TODO: Print the object members.
o << "@" << v << "\n";
}
static void StreamValue(llvm::raw_ostream& o, const void* const p,
const cling::ValuePrinterInfo& VPI) {
clang::QualType Ty = VPI.getExpr()->getType();
const clang::ASTContext& C = *VPI.getASTContext();
Ty = Ty.getDesugaredType(C);
if (const clang::BuiltinType *BT
= llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) {
switch (BT->getKind()) {
case clang::BuiltinType::Bool:
if (*(const bool*)p) o << "true\n";
else o << "false\n"; break;
case clang::BuiltinType::Char_U:
case clang::BuiltinType::UChar:
case clang::BuiltinType::Char_S:
case clang::BuiltinType::SChar: StreamChar(o, *(const char*)p); break;
case clang::BuiltinType::Short: o << *(const short*)p << "\n"; break;
case clang::BuiltinType::UShort:
o << *(const unsigned short*)p << "\n";
break;
case clang::BuiltinType::Int: o << *(const int*)p << "\n"; break;
case clang::BuiltinType::UInt:
o << *(const unsigned int*)p << "\n";
break;
case clang::BuiltinType::Long: o << *(const long*)p << "\n"; break;
case clang::BuiltinType::ULong:
o << *(const unsigned long*)p << "\n";
break;
case clang::BuiltinType::LongLong:
o << *(const long long*)p << "\n";
break;
case clang::BuiltinType::ULongLong:
o << *(const unsigned long long*)p << "\n";
break;
case clang::BuiltinType::Float: o << *(const float*)p << "\n"; break;
case clang::BuiltinType::Double: o << *(const double*)p << "\n"; break;
default:
StreamObj(o, p, VPI);
}
}
else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) {
StreamObj(o, p, VPI);
o <<"c_str: ";
StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str()));
}
else if (Ty->isEnumeralType()) {
StreamObj(o, p, VPI);
clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl();
uint64_t value = *(const uint64_t*)p;
bool IsFirst = true;
llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, Ty);
for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
E = ED->enumerator_end(); I != E; ++I) {
if (I->getInitVal() == ValAsAPSInt) {
if (!IsFirst) {
o << " ? ";
}
o << "(" << I->getQualifiedNameAsString() << ")";
IsFirst = false;
}
}
o << " : (int) " << ValAsAPSInt.toString(/*Radix = */10) << "\n";
}
else if (Ty->isReferenceType())
StreamRef(o, p);
else if (Ty->isPointerType()) {
clang::QualType PointeeTy = Ty->getPointeeType();
if (PointeeTy->isCharType())
StreamCharPtr(o, (const char*)p);
else
StreamPtr(o, p);
}
else
StreamObj(o, p, VPI);
}
namespace cling {
void printValuePublicDefault(llvm::raw_ostream& o, const void* const p,
const ValuePrinterInfo& VPI) {
const clang::Expr* E = VPI.getExpr();
o << "(";
o << E->getType().getAsString();
if (E->isRValue()) // show the user that the var cannot be changed
o << " const";
o << ") ";
StreamValue(o, p, VPI);
}
void flushOStream(llvm::raw_ostream& o) {
o.flush();
}
} // end namespace cling
|
Improve const-correctness in casts.
|
Improve const-correctness in casts.
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@46294 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
|
5ebbc8e697643bad1869a1dee105b182d26e1f36
|
Infovis/Testing/Cxx/TestOrderStatistics.cxx
|
Infovis/Testing/Cxx/TestOrderStatistics.cxx
|
/*
* Copyright 2007 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkTable.h"
#include "vtkOrderStatistics.h"
//=============================================================================
int TestOrderStatistics( int, char *[] )
{
int testIntValue = 0;
double mingledData[] =
{
46,
45,
47,
49,
46,
47,
46,
46,
47,
46,
47,
49,
49,
49,
47,
45,
50,
50,
46,
46,
51,
50,
48,
48,
52,
54,
48,
47,
52,
52,
49,
49,
53,
54,
50,
50,
53,
54,
50,
52,
53,
53,
50,
51,
54,
54,
49,
49,
52,
52,
50,
51,
52,
52,
49,
47,
48,
48,
48,
50,
46,
48,
47,
47,
};
int nVals = 32;
vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Metric 0" );
vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Metric 1" );
vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Metric 2" );
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 1;
dataset1Arr->InsertNextValue( mingledData[ti] );
dataset2Arr->InsertNextValue( mingledData[ti + 1] );
dataset3Arr->InsertNextValue( -1. );
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
vtkTable* paramsTable = vtkTable::New();
int nMetrics = 3;
vtkIdType columns[] = { 1, 2, 0 };
double centers[] = { 49.5, -1., 49.2188 };
double radii[] = { 1.5 * sqrt( 7.54839 ), 0., 1.5 * sqrt( 5.98286 ) };
vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
idTypeCol->SetName( "Column" );
for ( int i = 0; i < nMetrics; ++ i )
{
idTypeCol->InsertNextValue( columns[i] );
}
paramsTable->AddColumn( idTypeCol );
idTypeCol->Delete();
vtkDoubleArray* doubleCol = vtkDoubleArray::New();
doubleCol->SetName( "Nominal" );
for ( int i = 0; i < nMetrics; ++ i )
{
doubleCol->InsertNextValue( centers[i] );
}
paramsTable->AddColumn( doubleCol );
doubleCol->Delete();
doubleCol = vtkDoubleArray::New();
doubleCol->SetName( "Deviation" );
for ( int i = 0; i < nMetrics; ++ i )
{
doubleCol->InsertNextValue( radii[i] );
}
paramsTable->AddColumn( doubleCol );
doubleCol->Delete();
vtkOrderStatistics* haruspex = vtkOrderStatistics::New();
haruspex->SetInput( 0, datasetTable );
haruspex->SetInput( 1, paramsTable );
vtkTable* outputTable = haruspex->GetOutput();
datasetTable->Delete();
paramsTable->Delete();
// -- Select Columns of Interest --
haruspex->AddColumnRange( 0, 5 ); // Include invalid indices 3 and 4
for ( int i = 0; i< nMetrics; ++ i )
{ // Try to add all valid indices once more
haruspex->AddColumn( columns[i] );
}
haruspex->RemoveColumn( 3 ); // Remove invalid index 3 (but keep 4)
// -- Test Learn Mode --
haruspex->SetExecutionMode( vtkStatisticsAlgorithm::LearnMode );
haruspex->Update();
vtkIdType n = haruspex->GetSampleSize();
cout << "## Calculated the following statistics ( "
<< n
<< " entries per column ):\n";
for ( vtkIdType r = 0; r < outputTable->GetNumberOfRows(); ++ r )
{
cout << " "
<< datasetTable->GetColumnName( outputTable->GetValue( r, 0 ).ToInt() );
for ( int i = 1; i < 14; ++ i )
{
cout << ", "
<< outputTable->GetColumnName( i )
<< "="
<< outputTable->GetValue( r, i ).ToDouble();
}
cout << "\n";
}
haruspex->Delete();
return 0;
}
|
/*
* Copyright 2007 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkTable.h"
#include "vtkOrderStatistics.h"
//=============================================================================
int TestOrderStatistics( int, char *[] )
{
int testIntValue = 0;
double mingledData[] =
{
46,
45,
47,
49,
46,
47,
46,
46,
47,
46,
47,
49,
49,
49,
47,
45,
50,
50,
46,
46,
51,
50,
48,
48,
52,
54,
48,
47,
52,
52,
49,
49,
53,
54,
50,
50,
53,
54,
50,
52,
53,
53,
50,
51,
54,
54,
49,
49,
52,
52,
50,
51,
52,
52,
49,
47,
48,
48,
48,
50,
46,
48,
47,
47,
};
int nVals = 32;
vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
dataset1Arr->SetNumberOfComponents( 1 );
dataset1Arr->SetName( "Metric 0" );
vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
dataset2Arr->SetNumberOfComponents( 1 );
dataset2Arr->SetName( "Metric 1" );
vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
dataset3Arr->SetNumberOfComponents( 1 );
dataset3Arr->SetName( "Metric 2" );
for ( int i = 0; i < nVals; ++ i )
{
int ti = i << 1;
dataset1Arr->InsertNextValue( mingledData[ti] );
dataset2Arr->InsertNextValue( mingledData[ti + 1] );
dataset3Arr->InsertNextValue( -1. );
}
vtkTable* datasetTable = vtkTable::New();
datasetTable->AddColumn( dataset1Arr );
dataset1Arr->Delete();
datasetTable->AddColumn( dataset2Arr );
dataset2Arr->Delete();
datasetTable->AddColumn( dataset3Arr );
dataset3Arr->Delete();
vtkTable* paramsTable = vtkTable::New();
int nMetrics = 3;
vtkIdType columns[] = { 1, 2, 0 };
double centers[] = { 49.5, -1., 49.2188 };
double radii[] = { 1.5 * sqrt( 7.54839 ), 0., 1.5 * sqrt( 5.98286 ) };
vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
idTypeCol->SetName( "Column" );
for ( int i = 0; i < nMetrics; ++ i )
{
idTypeCol->InsertNextValue( columns[i] );
}
paramsTable->AddColumn( idTypeCol );
idTypeCol->Delete();
vtkDoubleArray* doubleCol = vtkDoubleArray::New();
doubleCol->SetName( "Nominal" );
for ( int i = 0; i < nMetrics; ++ i )
{
doubleCol->InsertNextValue( centers[i] );
}
paramsTable->AddColumn( doubleCol );
doubleCol->Delete();
doubleCol = vtkDoubleArray::New();
doubleCol->SetName( "Deviation" );
for ( int i = 0; i < nMetrics; ++ i )
{
doubleCol->InsertNextValue( radii[i] );
}
paramsTable->AddColumn( doubleCol );
doubleCol->Delete();
vtkOrderStatistics* haruspex = vtkOrderStatistics::New();
haruspex->SetInput( 0, datasetTable );
haruspex->SetInput( 1, paramsTable );
vtkTable* outputTable = haruspex->GetOutput();
datasetTable->Delete();
paramsTable->Delete();
// -- Select Columns of Interest --
haruspex->AddColumnRange( 0, 5 ); // Include invalid indices 3 and 4
for ( int i = 0; i< nMetrics; ++ i )
{ // Try to add all valid indices once more
haruspex->AddColumn( columns[i] );
}
haruspex->RemoveColumn( 3 ); // Remove invalid index 3 (but keep 4)
// -- Test Learn Mode --
haruspex->SetExecutionMode( vtkStatisticsAlgorithm::LearnMode );
haruspex->Update();
vtkIdType n = haruspex->GetSampleSize();
cout << "## Calculated the following statistics ( "
<< n
<< " entries per column ):\n";
for ( vtkIdType r = 0; r < outputTable->GetNumberOfRows(); ++ r )
{
cout << " "
<< datasetTable->GetColumnName( outputTable->GetValue( r, 0 ).ToInt() );
for ( int i = 1; i < 14; ++ i )
{
cout << ", "
<< outputTable->GetColumnName( i )
<< "="
<< outputTable->GetValue( r, i ).ToDouble();
}
cout << "\n";
}
haruspex->Delete();
testIntValue = 0;
return 0;
}
|
use an unused variable
|
COMP: use an unused variable
|
C++
|
bsd-3-clause
|
msmolens/VTK,johnkit/vtk-dev,mspark93/VTK,jmerkow/VTK,sumedhasingla/VTK,mspark93/VTK,biddisco/VTK,msmolens/VTK,arnaudgelas/VTK,johnkit/vtk-dev,daviddoria/PointGraphsPhase1,sankhesh/VTK,cjh1/VTK,SimVascular/VTK,aashish24/VTK-old,aashish24/VTK-old,msmolens/VTK,SimVascular/VTK,jmerkow/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,collects/VTK,jmerkow/VTK,biddisco/VTK,demarle/VTK,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,spthaolt/VTK,arnaudgelas/VTK,sumedhasingla/VTK,ashray/VTK-EVM,collects/VTK,msmolens/VTK,cjh1/VTK,demarle/VTK,demarle/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,hendradarwin/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,johnkit/vtk-dev,biddisco/VTK,Wuteyan/VTK,hendradarwin/VTK,sumedhasingla/VTK,sankhesh/VTK,gram526/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,collects/VTK,jeffbaumes/jeffbaumes-vtk,aashish24/VTK-old,mspark93/VTK,arnaudgelas/VTK,SimVascular/VTK,candy7393/VTK,spthaolt/VTK,daviddoria/PointGraphsPhase1,arnaudgelas/VTK,candy7393/VTK,aashish24/VTK-old,gram526/VTK,mspark93/VTK,spthaolt/VTK,sankhesh/VTK,candy7393/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,johnkit/vtk-dev,cjh1/VTK,SimVascular/VTK,candy7393/VTK,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,cjh1/VTK,sankhesh/VTK,mspark93/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,spthaolt/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,sankhesh/VTK,arnaudgelas/VTK,gram526/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,gram526/VTK,gram526/VTK,biddisco/VTK,demarle/VTK,keithroe/vtkoptix,cjh1/VTK,Wuteyan/VTK,msmolens/VTK,berendkleinhaneveld/VTK,biddisco/VTK,sankhesh/VTK,ashray/VTK-EVM,cjh1/VTK,arnaudgelas/VTK,sumedhasingla/VTK,candy7393/VTK,mspark93/VTK,jmerkow/VTK,candy7393/VTK,spthaolt/VTK,sumedhasingla/VTK,hendradarwin/VTK,gram526/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,msmolens/VTK,collects/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,jmerkow/VTK,sankhesh/VTK,demarle/VTK,sumedhasingla/VTK,hendradarwin/VTK,demarle/VTK,gram526/VTK,sumedhasingla/VTK,jeffbaumes/jeffbaumes-vtk,keithroe/vtkoptix,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,biddisco/VTK,keithroe/vtkoptix,keithroe/vtkoptix,mspark93/VTK,ashray/VTK-EVM,ashray/VTK-EVM,demarle/VTK,collects/VTK,biddisco/VTK,Wuteyan/VTK,Wuteyan/VTK,candy7393/VTK,daviddoria/PointGraphsPhase1,keithroe/vtkoptix,gram526/VTK,ashray/VTK-EVM,ashray/VTK-EVM,hendradarwin/VTK,mspark93/VTK,SimVascular/VTK,Wuteyan/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,hendradarwin/VTK,naucoin/VTKSlicerWidgets,demarle/VTK,jmerkow/VTK,msmolens/VTK,aashish24/VTK-old,collects/VTK,spthaolt/VTK,ashray/VTK-EVM,aashish24/VTK-old,spthaolt/VTK,keithroe/vtkoptix,SimVascular/VTK,keithroe/vtkoptix
|
a683be2e678f8ea769cae564c6f8d1d09220e63f
|
kernel/kernel/perf.cpp
|
kernel/kernel/perf.cpp
|
/*
* Copyright (c) 2022 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*
* SPDX-License-Identifier: MIT
*/
#include <onyx/cpu.h>
#include <onyx/dev.h>
#include <onyx/init.h>
#include <onyx/percpu.h>
#include <onyx/perf_probe.h>
#include <onyx/timer.h>
#ifdef __x86_64__
#include <onyx/x86/apic.h>
#endif
#include <onyx/atomic.hpp>
#define PERF_LOCK_EXCLUSIVE UINT_MAX
/**
* @brief Protects the data structures below (particularly, fg).
* It counts the number of cpus that have it grabbed, or PERF_LOCK_EXCLUSIVE.
* EXCLUSIVE is held when setting up or disabling perf probing.
*/
cul::atomic_uint perf_lock;
/**
* @brief Lock the perf lock in shared mode
*
*/
static void perf_lock_shared()
{
while (true)
{
auto old = perf_lock.load(mem_order::relaxed);
if (old == PERF_LOCK_EXCLUSIVE)
{
do
{
cpu_relax();
old = perf_lock.load(mem_order::relaxed);
} while (old == PERF_LOCK_EXCLUSIVE);
}
if (perf_lock.compare_exchange_strong(old, old + 1, mem_order::acquire, mem_order::relaxed))
[[likely]]
return;
}
}
/**
* @brief Unlock the shared perf lock
*
*/
static void perf_unlock_shared()
{
perf_lock.sub_fetch(1, mem_order::release);
}
/**
* @brief Lock the perf lock in exclusive mode
*
*/
static void perf_lock_exclusive()
{
irq_disable();
while (true)
{
auto old = perf_lock.load(mem_order::relaxed);
if (old != 0)
{
do
{
cpu_relax();
old = perf_lock.load(mem_order::relaxed);
} while (old != 0);
}
if (perf_lock.compare_exchange_strong(old, PERF_LOCK_EXCLUSIVE, mem_order::acquire,
mem_order::relaxed)) [[likely]]
return;
}
}
/**
* @brief Unlock the perf unlock in exclusive mode
*
*/
static void perf_unlock_exclusive()
{
perf_lock.store(0, mem_order::release);
irq_enable();
}
bool perf_probe_enabled = false;
bool perf_probe_wait_enabled = false;
struct flame_graph_pcpu *fg;
clockevent *ce;
/**
* @brief Enable wait perf probing
*
* @return 0 on success, negative error codes
*/
static int perf_probe_enable_wait()
{
perf_lock_exclusive();
if (perf_probe_enabled)
return perf_unlock_exclusive(), -EINVAL;
if (!fg)
{
fg = (flame_graph_pcpu *) calloc(sizeof(flame_graph_pcpu), get_nr_cpus());
assert(fg != nullptr);
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
fg[i].windex = 0;
fg[i].nentries = FLAME_GRAPH_NENTRIES;
fg[i].fge =
(flame_graph_entry *) calloc(sizeof(flame_graph_entry), FLAME_GRAPH_NENTRIES);
assert(fg[i].fge != nullptr);
}
}
perf_probe_wait_enabled = true;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Check is wait perf probing is enabled
*
* @return True if enabled, else false
*/
bool perf_probe_is_enabled_wait()
{
return perf_probe_wait_enabled;
}
extern cul::atomic_size_t used_pages;
/**
* @brief Enable CPU perf probing
*
* @return 0 on success, negative error codes
*/
static int perf_probe_enable()
{
perf_lock_exclusive();
if (perf_probe_wait_enabled)
return perf_unlock_exclusive(), -EINVAL;
if (!fg)
{
fg = (flame_graph_pcpu *) calloc(sizeof(flame_graph_pcpu), get_nr_cpus());
assert(fg != nullptr);
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
fg[i].windex = 0;
fg[i].nentries = FLAME_GRAPH_NENTRIES;
fg[i].fge = (flame_graph_entry *) vmalloc(
vm_size_to_pages(sizeof(flame_graph_entry) * FLAME_GRAPH_NENTRIES), VM_TYPE_REGULAR,
VM_READ | VM_WRITE);
assert(fg[i].fge != nullptr);
}
}
if (!ce)
{
ce = (clockevent *) new clockevent;
assert(ce != nullptr);
}
auto ev = ce;
ev->callback = [](clockevent *ev_) {
#ifdef __x86_64__
apic_send_ipi_all(0, X86_PERFPROBE);
#endif
ev_->deadline = clocksource_get_time() + NS_PER_MS;
};
ev->deadline = clocksource_get_time() + 1 * NS_PER_MS;
ev->flags = CLOCKEVENT_FLAG_ATOMIC | CLOCKEVENT_FLAG_PULSE;
timer_queue_clockevent(ev);
perf_probe_enabled = true;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Copy the probe buffers to userspace, and free them
*
* @param ubuf User buffer
* @return 0 on success, negative error codes
*/
static int perf_probe_ucopy(void *ubuf)
{
perf_lock_exclusive();
if (!fg)
{
perf_unlock_exclusive();
return -EINVAL;
}
unsigned char *ubuf2 = (unsigned char *) ubuf;
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
for (size_t j = 0; j < fg[i].nentries; j++)
{
auto fge = &fg[i].fge[j];
if (copy_to_user(ubuf2, fge, sizeof(*fge)) < 0)
return perf_unlock_exclusive(), -EFAULT;
ubuf2 += sizeof(flame_graph_entry);
}
}
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
vfree(fg[i].fge, vm_size_to_pages(sizeof(flame_graph_entry) * FLAME_GRAPH_NENTRIES));
}
free(fg);
fg = nullptr;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Disable CPU perf probing
*
*/
static void perf_disable_probing()
{
perf_lock_exclusive();
if (!perf_probe_enabled && !perf_probe_wait_enabled)
{
perf_unlock_exclusive();
return;
}
if (ce)
{
timer_cancel_event(ce);
delete ce;
ce = nullptr;
}
perf_probe_enabled = false;
perf_unlock_exclusive();
}
static int perf_probe_ioctl_enable_disable_cpu(void *argp)
{
int is;
if (copy_from_user(&is, argp, sizeof(is)) < 0)
return -EFAULT;
int st = 0;
if ((bool) is)
st = perf_probe_enable();
else
{
perf_disable_probing();
}
return st;
}
static unsigned int perf_probe_ioctl_get_buflen()
{
perf_lock_shared();
if (!fg)
return perf_unlock_shared(), -EINVAL;
size_t len = 0;
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
len += fg[i].nentries * sizeof(flame_graph_entry);
}
perf_unlock_shared();
return len;
}
static unsigned int perf_probe_ioctl_enable_disable_wait(void *argp)
{
int is;
if (copy_from_user(&is, argp, sizeof(is)) < 0)
return -EFAULT;
int st = 0;
if ((bool) is)
st = perf_probe_enable_wait();
else
{
perf_lock_exclusive();
perf_probe_wait_enabled = false;
perf_unlock_exclusive();
}
return st;
}
unsigned int perf_probe_ioctl(int request, void *argp, struct file *file)
{
switch (request)
{
case PERF_PROBE_ENABLE_DISABLE_CPU:
return perf_probe_ioctl_enable_disable_cpu(argp);
case PERF_PROBE_GET_BUFFER_LENGTH:
return perf_probe_ioctl_get_buflen();
case PERF_PROBE_READ_DATA:
return perf_probe_ucopy(argp);
case PERF_PROBE_ENABLE_DISABLE_WAIT:
return perf_probe_ioctl_enable_disable_wait(argp);
}
return -ENOTTY;
}
PER_CPU_VAR(flame_graph_entry *curwait_fge) = nullptr;
/**
* @brief Set up a wait probe. Called right before platform_yield()
*
* @param fge flame_graph_entry, stack allocated
*/
void perf_probe_setup_wait(struct flame_graph_entry *fge)
{
const auto t0 = clocksource_get_time();
fge->rips[31] = t0;
write_per_cpu(curwait_fge, fge);
}
/**
* @brief Commit the wait probe
*
* @param fge flame_graph_entry, stack allocated
*/
void perf_probe_commit_wait(const struct flame_graph_entry *fge)
{
perf_lock_shared();
if (!perf_probe_wait_enabled)
{
perf_unlock_shared();
return;
}
auto _ = irq_save_and_disable();
struct flame_graph_pcpu *pcpu = &fg[get_cpu_nr()];
struct flame_graph_entry *e = &pcpu->fge[pcpu->windex % FLAME_GRAPH_NENTRIES];
pcpu->windex++;
memcpy(e, fge, sizeof(*fge));
const auto t1 = clocksource_get_time();
e->rips[31] = t1 - e->rips[31];
irq_restore(_);
perf_unlock_shared();
}
/**
* @brief Try to take a trace for the wait probe
*
* @param regs Registers
*/
void perf_probe_try_wait_trace(struct registers *regs)
{
auto curfge = get_per_cpu(curwait_fge);
// It's possible curfge may no longer exist
if (!curfge)
return;
#ifdef __x86_64__
curfge->rips[0] = regs->rip;
curfge->rips[1] = 0;
stack_trace_get((unsigned long *) regs->rbp, curfge->rips + 1, 30);
#endif
write_per_cpu(curwait_fge, nullptr);
}
/**
* @brief Check if CPU perf probing is enabled
*
* @return True if enabled, else false
*/
bool perf_probe_is_enabled()
{
return perf_probe_enabled;
}
/**
* @brief Do a CPU perf probe
*
* @param regs Registers
*/
void perf_probe_do(struct registers *regs)
{
perf_lock_shared();
if (!perf_probe_enabled)
{
perf_unlock_shared();
return;
}
auto _ = irq_save_and_disable();
struct flame_graph_pcpu *pcpu = &fg[get_cpu_nr()];
struct flame_graph_entry *e = &pcpu->fge[pcpu->windex % FLAME_GRAPH_NENTRIES];
(void) e;
pcpu->windex++;
#ifdef __x86_64__
e->rips[0] = regs->rip;
e->rips[1] = 0;
stack_trace_get((unsigned long *) regs->rbp, e->rips + 1, 31);
#endif
irq_restore(_);
perf_unlock_shared();
}
const file_ops perf_probe_fops = {.read = nullptr, // TODO
.ioctl = perf_probe_ioctl};
/**
* @brief Initialize perf-probe
*
*/
void perf_init()
{
auto ex = dev_register_chardevs(0, 1, 0, &perf_probe_fops, "perf-probe");
ex.unwrap()->show(0644);
}
INIT_LEVEL_CORE_KERNEL_ENTRY(perf_init);
|
/*
* Copyright (c) 2022 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*
* SPDX-License-Identifier: MIT
*/
#include <onyx/cpu.h>
#include <onyx/dev.h>
#include <onyx/init.h>
#include <onyx/percpu.h>
#include <onyx/perf_probe.h>
#include <onyx/timer.h>
#ifdef __x86_64__
#include <onyx/x86/apic.h>
#endif
#include <onyx/atomic.hpp>
#define PERF_LOCK_EXCLUSIVE UINT_MAX
/**
* @brief Protects the data structures below (particularly, fg).
* It counts the number of cpus that have it grabbed, or PERF_LOCK_EXCLUSIVE.
* EXCLUSIVE is held when setting up or disabling perf probing.
*/
cul::atomic_uint perf_lock;
/**
* @brief Lock the perf lock in shared mode
*
*/
static void perf_lock_shared()
{
while (true)
{
auto old = perf_lock.load(mem_order::relaxed);
if (old == PERF_LOCK_EXCLUSIVE)
{
do
{
cpu_relax();
old = perf_lock.load(mem_order::relaxed);
} while (old == PERF_LOCK_EXCLUSIVE);
}
if (perf_lock.compare_exchange_strong(old, old + 1, mem_order::acquire, mem_order::relaxed))
[[likely]]
return;
}
}
/**
* @brief Unlock the shared perf lock
*
*/
static void perf_unlock_shared()
{
perf_lock.sub_fetch(1, mem_order::release);
}
/**
* @brief Lock the perf lock in exclusive mode
*
*/
static void perf_lock_exclusive()
{
irq_disable();
while (true)
{
auto old = perf_lock.load(mem_order::relaxed);
if (old != 0)
{
do
{
cpu_relax();
old = perf_lock.load(mem_order::relaxed);
} while (old != 0);
}
if (perf_lock.compare_exchange_strong(old, PERF_LOCK_EXCLUSIVE, mem_order::acquire,
mem_order::relaxed)) [[likely]]
return;
}
}
/**
* @brief Unlock the perf unlock in exclusive mode
*
*/
static void perf_unlock_exclusive()
{
perf_lock.store(0, mem_order::release);
irq_enable();
}
bool perf_probe_enabled = false;
bool perf_probe_wait_enabled = false;
struct flame_graph_pcpu *fg;
clockevent *ce;
/**
* @brief Enable wait perf probing
*
* @return 0 on success, negative error codes
*/
static int perf_probe_enable_wait()
{
perf_lock_exclusive();
if (perf_probe_enabled)
return perf_unlock_exclusive(), -EINVAL;
if (!fg)
{
fg = (flame_graph_pcpu *) calloc(sizeof(flame_graph_pcpu), get_nr_cpus());
assert(fg != nullptr);
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
fg[i].windex = 0;
fg[i].nentries = FLAME_GRAPH_NENTRIES;
fg[i].fge = (flame_graph_entry *) vmalloc(
vm_size_to_pages(sizeof(flame_graph_entry) * FLAME_GRAPH_NENTRIES), VM_TYPE_REGULAR,
VM_READ | VM_WRITE);
assert(fg[i].fge != nullptr);
}
}
perf_probe_wait_enabled = true;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Check is wait perf probing is enabled
*
* @return True if enabled, else false
*/
bool perf_probe_is_enabled_wait()
{
return perf_probe_wait_enabled;
}
extern cul::atomic_size_t used_pages;
/**
* @brief Enable CPU perf probing
*
* @return 0 on success, negative error codes
*/
static int perf_probe_enable()
{
perf_lock_exclusive();
if (perf_probe_wait_enabled)
return perf_unlock_exclusive(), -EINVAL;
if (!fg)
{
fg = (flame_graph_pcpu *) calloc(sizeof(flame_graph_pcpu), get_nr_cpus());
assert(fg != nullptr);
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
fg[i].windex = 0;
fg[i].nentries = FLAME_GRAPH_NENTRIES;
fg[i].fge = (flame_graph_entry *) vmalloc(
vm_size_to_pages(sizeof(flame_graph_entry) * FLAME_GRAPH_NENTRIES), VM_TYPE_REGULAR,
VM_READ | VM_WRITE);
assert(fg[i].fge != nullptr);
}
}
if (!ce)
{
ce = (clockevent *) new clockevent;
assert(ce != nullptr);
}
auto ev = ce;
ev->callback = [](clockevent *ev_) {
#ifdef __x86_64__
apic_send_ipi_all(0, X86_PERFPROBE);
#endif
ev_->deadline = clocksource_get_time() + NS_PER_MS;
};
ev->deadline = clocksource_get_time() + 1 * NS_PER_MS;
ev->flags = CLOCKEVENT_FLAG_ATOMIC | CLOCKEVENT_FLAG_PULSE;
timer_queue_clockevent(ev);
perf_probe_enabled = true;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Copy the probe buffers to userspace, and free them
*
* @param ubuf User buffer
* @return 0 on success, negative error codes
*/
static int perf_probe_ucopy(void *ubuf)
{
perf_lock_exclusive();
if (!fg)
{
perf_unlock_exclusive();
return -EINVAL;
}
unsigned char *ubuf2 = (unsigned char *) ubuf;
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
for (size_t j = 0; j < fg[i].nentries; j++)
{
auto fge = &fg[i].fge[j];
if (copy_to_user(ubuf2, fge, sizeof(*fge)) < 0)
return perf_unlock_exclusive(), -EFAULT;
ubuf2 += sizeof(flame_graph_entry);
}
}
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
vfree(fg[i].fge, vm_size_to_pages(sizeof(flame_graph_entry) * FLAME_GRAPH_NENTRIES));
}
free(fg);
fg = nullptr;
perf_unlock_exclusive();
return 0;
}
/**
* @brief Disable CPU perf probing
*
*/
static void perf_disable_probing()
{
perf_lock_exclusive();
if (!perf_probe_enabled && !perf_probe_wait_enabled)
{
perf_unlock_exclusive();
return;
}
if (ce)
{
timer_cancel_event(ce);
delete ce;
ce = nullptr;
}
perf_probe_enabled = false;
perf_unlock_exclusive();
}
static int perf_probe_ioctl_enable_disable_cpu(void *argp)
{
int is;
if (copy_from_user(&is, argp, sizeof(is)) < 0)
return -EFAULT;
int st = 0;
if ((bool) is)
st = perf_probe_enable();
else
{
perf_disable_probing();
}
return st;
}
static unsigned int perf_probe_ioctl_get_buflen()
{
perf_lock_shared();
if (!fg)
return perf_unlock_shared(), -EINVAL;
size_t len = 0;
for (unsigned int i = 0; i < get_nr_cpus(); i++)
{
len += fg[i].nentries * sizeof(flame_graph_entry);
}
perf_unlock_shared();
return len;
}
static unsigned int perf_probe_ioctl_enable_disable_wait(void *argp)
{
int is;
if (copy_from_user(&is, argp, sizeof(is)) < 0)
return -EFAULT;
int st = 0;
if ((bool) is)
st = perf_probe_enable_wait();
else
{
perf_lock_exclusive();
perf_probe_wait_enabled = false;
perf_unlock_exclusive();
}
return st;
}
unsigned int perf_probe_ioctl(int request, void *argp, struct file *file)
{
switch (request)
{
case PERF_PROBE_ENABLE_DISABLE_CPU:
return perf_probe_ioctl_enable_disable_cpu(argp);
case PERF_PROBE_GET_BUFFER_LENGTH:
return perf_probe_ioctl_get_buflen();
case PERF_PROBE_READ_DATA:
return perf_probe_ucopy(argp);
case PERF_PROBE_ENABLE_DISABLE_WAIT:
return perf_probe_ioctl_enable_disable_wait(argp);
}
return -ENOTTY;
}
PER_CPU_VAR(flame_graph_entry *curwait_fge) = nullptr;
/**
* @brief Set up a wait probe. Called right before platform_yield()
*
* @param fge flame_graph_entry, stack allocated
*/
void perf_probe_setup_wait(struct flame_graph_entry *fge)
{
const auto t0 = clocksource_get_time();
fge->rips[31] = t0;
write_per_cpu(curwait_fge, fge);
}
/**
* @brief Commit the wait probe
*
* @param fge flame_graph_entry, stack allocated
*/
void perf_probe_commit_wait(const struct flame_graph_entry *fge)
{
perf_lock_shared();
if (!perf_probe_wait_enabled)
{
perf_unlock_shared();
return;
}
auto _ = irq_save_and_disable();
struct flame_graph_pcpu *pcpu = &fg[get_cpu_nr()];
struct flame_graph_entry *e = &pcpu->fge[pcpu->windex % FLAME_GRAPH_NENTRIES];
pcpu->windex++;
memcpy(e, fge, sizeof(*fge));
const auto t1 = clocksource_get_time();
e->rips[31] = t1 - e->rips[31];
irq_restore(_);
perf_unlock_shared();
}
/**
* @brief Try to take a trace for the wait probe
*
* @param regs Registers
*/
void perf_probe_try_wait_trace(struct registers *regs)
{
auto curfge = get_per_cpu(curwait_fge);
// It's possible curfge may no longer exist
if (!curfge)
return;
#ifdef __x86_64__
curfge->rips[0] = regs->rip;
curfge->rips[1] = 0;
stack_trace_get((unsigned long *) regs->rbp, curfge->rips + 1, 30);
#endif
write_per_cpu(curwait_fge, nullptr);
}
/**
* @brief Check if CPU perf probing is enabled
*
* @return True if enabled, else false
*/
bool perf_probe_is_enabled()
{
return perf_probe_enabled;
}
/**
* @brief Do a CPU perf probe
*
* @param regs Registers
*/
void perf_probe_do(struct registers *regs)
{
perf_lock_shared();
if (!perf_probe_enabled)
{
perf_unlock_shared();
return;
}
auto _ = irq_save_and_disable();
struct flame_graph_pcpu *pcpu = &fg[get_cpu_nr()];
struct flame_graph_entry *e = &pcpu->fge[pcpu->windex % FLAME_GRAPH_NENTRIES];
(void) e;
pcpu->windex++;
#ifdef __x86_64__
e->rips[0] = regs->rip;
e->rips[1] = 0;
stack_trace_get((unsigned long *) regs->rbp, e->rips + 1, 31);
#endif
irq_restore(_);
perf_unlock_shared();
}
const file_ops perf_probe_fops = {.read = nullptr, // TODO
.ioctl = perf_probe_ioctl};
/**
* @brief Initialize perf-probe
*
*/
void perf_init()
{
auto ex = dev_register_chardevs(0, 1, 0, &perf_probe_fops, "perf-probe");
ex.unwrap()->show(0644);
}
INIT_LEVEL_CORE_KERNEL_ENTRY(perf_init);
|
Fix large calloc on wait time sampling
|
perf: Fix large calloc on wait time sampling
Signed-off-by: Pedro Falcato <[email protected]>
|
C++
|
mit
|
heatd/Onyx,heatd/Onyx,heatd/Onyx,heatd/Onyx
|
15df0a27bbf1409f974edbc1f5ffbdf2715ec4f9
|
src/cpu/o3/bpred_unit_impl.hh
|
src/cpu/o3/bpred_unit_impl.hh
|
/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
*/
#include "arch/types.hh"
#include "arch/isa_traits.hh"
#include "base/trace.hh"
#include "base/traceflags.hh"
#include "cpu/o3/bpred_unit.hh"
template<class Impl>
BPredUnit<Impl>::BPredUnit(Params *params)
: BTB(params->BTBEntries,
params->BTBTagSize,
params->instShiftAmt)
{
// Setup the selected predictor.
if (params->predType == "local") {
localBP = new LocalBP(params->localPredictorSize,
params->localCtrBits,
params->instShiftAmt);
predictor = Local;
} else if (params->predType == "tournament") {
tournamentBP = new TournamentBP(params->localPredictorSize,
params->localCtrBits,
params->localHistoryTableSize,
params->localHistoryBits,
params->globalPredictorSize,
params->globalHistoryBits,
params->globalCtrBits,
params->choicePredictorSize,
params->choiceCtrBits,
params->instShiftAmt);
predictor = Tournament;
} else {
fatal("Invalid BP selected!");
}
for (int i=0; i < Impl::MaxThreads; i++)
RAS[i].init(params->RASSize);
}
template <class Impl>
void
BPredUnit<Impl>::regStats()
{
lookups
.name(name() + ".BPredUnit.lookups")
.desc("Number of BP lookups")
;
condPredicted
.name(name() + ".BPredUnit.condPredicted")
.desc("Number of conditional branches predicted")
;
condIncorrect
.name(name() + ".BPredUnit.condIncorrect")
.desc("Number of conditional branches incorrect")
;
BTBLookups
.name(name() + ".BPredUnit.BTBLookups")
.desc("Number of BTB lookups")
;
BTBHits
.name(name() + ".BPredUnit.BTBHits")
.desc("Number of BTB hits")
;
BTBCorrect
.name(name() + ".BPredUnit.BTBCorrect")
.desc("Number of correct BTB predictions (this stat may not "
"work properly.")
;
usedRAS
.name(name() + ".BPredUnit.usedRAS")
.desc("Number of times the RAS was used to get a target.")
;
RASIncorrect
.name(name() + ".BPredUnit.RASInCorrect")
.desc("Number of incorrect RAS predictions.")
;
}
template <class Impl>
void
BPredUnit<Impl>::switchOut()
{
// Clear any state upon switch out.
for (int i = 0; i < Impl::MaxThreads; ++i) {
squash(0, i);
}
}
template <class Impl>
void
BPredUnit<Impl>::takeOverFrom()
{
// Can reset all predictor state, but it's not necessarily better
// than leaving it be.
/*
for (int i = 0; i < Impl::MaxThreads; ++i)
RAS[i].reset();
BP.reset();
BTB.reset();
*/
}
template <class Impl>
bool
BPredUnit<Impl>::predict(DynInstPtr &inst, Addr &PC, unsigned tid)
{
// See if branch predictor predicts taken.
// If so, get its target addr either from the BTB or the RAS.
// Save off record of branch stuff so the RAS can be fixed
// up once it's done.
using TheISA::MachInst;
bool pred_taken = false;
Addr target;
++lookups;
void *bp_history = NULL;
if (inst->isUncondCtrl()) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Unconditional control.\n", tid);
pred_taken = true;
// Tell the BP there was an unconditional branch.
BPUncond(bp_history);
} else {
++condPredicted;
pred_taken = BPLookup(PC, bp_history);
DPRINTF(Fetch, "BranchPred: [tid:%i]: Branch predictor predicted %i "
"for PC %#x\n",
tid, pred_taken, inst->readPC());
}
PredictorHistory predict_record(inst->seqNum, PC, pred_taken,
bp_history, tid);
// Now lookup in the BTB or RAS.
if (pred_taken) {
if (inst->isReturn()) {
++usedRAS;
// If it's a function return call, then look up the address
// in the RAS.
target = RAS[tid].top();
// Record the top entry of the RAS, and its index.
predict_record.usedRAS = true;
predict_record.RASIndex = RAS[tid].topIdx();
predict_record.RASTarget = target;
assert(predict_record.RASIndex < 16);
RAS[tid].pop();
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x is a return, "
"RAS predicted target: %#x, RAS index: %i.\n",
tid, inst->readPC(), target, predict_record.RASIndex);
} else {
++BTBLookups;
if (inst->isCall()) {
#if ISA_HAS_DELAY_SLOT
Addr ras_pc = PC + (2 * sizeof(MachInst)); // Next Next PC
#else
Addr ras_pc = PC + sizeof(MachInst); // Next PC
#endif
RAS[tid].push(ras_pc);
// Record that it was a call so that the top RAS entry can
// be popped off if the speculation is incorrect.
predict_record.wasCall = true;
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x was a call"
", adding %#x to the RAS index: %i.\n",
tid, inst->readPC(), ras_pc, RAS[tid].topIdx());
}
if (BTB.valid(PC, tid)) {
++BTBHits;
// If it's not a return, use the BTB to get the target addr.
target = BTB.lookup(PC, tid);
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x predicted"
" target is %#x.\n",
tid, inst->readPC(), target);
} else {
DPRINTF(Fetch, "BranchPred: [tid:%i]: BTB doesn't have a "
"valid entry.\n",tid);
pred_taken = false;
}
}
}
predHist[tid].push_front(predict_record);
DPRINTF(Fetch, "[tid:%i]: predHist.size(): %i\n", tid, predHist[tid].size());
return pred_taken;
}
template <class Impl>
void
BPredUnit<Impl>::update(const InstSeqNum &done_sn, unsigned tid)
{
DPRINTF(Fetch, "BranchPred: [tid:%i]: Commiting branches until "
"[sn:%lli].\n", tid, done_sn);
while (!predHist[tid].empty() &&
predHist[tid].back().seqNum <= done_sn) {
// Update the branch predictor with the correct results.
BPUpdate(predHist[tid].back().PC,
predHist[tid].back().predTaken,
predHist[tid].back().bpHistory);
predHist[tid].pop_back();
}
}
template <class Impl>
void
BPredUnit<Impl>::squash(const InstSeqNum &squashed_sn, unsigned tid)
{
History &pred_hist = predHist[tid];
while (!pred_hist.empty() &&
pred_hist.front().seqNum > squashed_sn) {
if (pred_hist.front().usedRAS) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Restoring top of RAS to: %i,"
" target: %#x.\n",
tid,
pred_hist.front().RASIndex,
pred_hist.front().RASTarget);
RAS[tid].restore(pred_hist.front().RASIndex,
pred_hist.front().RASTarget);
} else if (pred_hist.front().wasCall) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Removing speculative entry "
"added to the RAS.\n",tid);
RAS[tid].pop();
}
// This call should delete the bpHistory.
BPSquash(pred_hist.front().bpHistory);
pred_hist.pop_front();
}
}
template <class Impl>
void
BPredUnit<Impl>::squash(const InstSeqNum &squashed_sn,
const Addr &corr_target,
const bool actually_taken,
unsigned tid)
{
// Now that we know that a branch was mispredicted, we need to undo
// all the branches that have been seen up until this branch and
// fix up everything.
History &pred_hist = predHist[tid];
++condIncorrect;
DPRINTF(Fetch, "BranchPred: [tid:%i]: Squashing from sequence number %i, "
"setting target to %#x.\n",
tid, squashed_sn, corr_target);
squash(squashed_sn, tid);
// If there's a squash due to a syscall, there may not be an entry
// corresponding to the squash. In that case, don't bother trying to
// fix up the entry.
if (!pred_hist.empty()) {
assert(pred_hist.front().seqNum == squashed_sn);
if (pred_hist.front().usedRAS) {
++RASIncorrect;
}
BPUpdate(pred_hist.front().PC, actually_taken,
pred_hist.front().bpHistory);
BTB.update(pred_hist.front().PC, corr_target, tid);
pred_hist.pop_front();
}
}
template <class Impl>
void
BPredUnit<Impl>::BPUncond(void * &bp_history)
{
// Only the tournament predictor cares about unconditional branches.
if (predictor == Tournament) {
tournamentBP->uncondBr(bp_history);
}
}
template <class Impl>
void
BPredUnit<Impl>::BPSquash(void *bp_history)
{
if (predictor == Local) {
localBP->squash(bp_history);
} else if (predictor == Tournament) {
tournamentBP->squash(bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
bool
BPredUnit<Impl>::BPLookup(Addr &inst_PC, void * &bp_history)
{
if (predictor == Local) {
return localBP->lookup(inst_PC, bp_history);
} else if (predictor == Tournament) {
return tournamentBP->lookup(inst_PC, bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
void
BPredUnit<Impl>::BPUpdate(Addr &inst_PC, bool taken, void *bp_history)
{
if (predictor == Local) {
localBP->update(inst_PC, taken, bp_history);
} else if (predictor == Tournament) {
tournamentBP->update(inst_PC, taken, bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
void
BPredUnit<Impl>::dump()
{
typename History::iterator pred_hist_it;
for (int i = 0; i < Impl::MaxThreads; ++i) {
if (!predHist[i].empty()) {
pred_hist_it = predHist[i].begin();
cprintf("predHist[%i].size(): %i\n", i, predHist[i].size());
while (pred_hist_it != predHist[i].end()) {
cprintf("[sn:%lli], PC:%#x, tid:%i, predTaken:%i, "
"bpHistory:%#x\n",
(*pred_hist_it).seqNum, (*pred_hist_it).PC,
(*pred_hist_it).tid, (*pred_hist_it).predTaken,
(*pred_hist_it).bpHistory);
pred_hist_it++;
}
cprintf("\n");
}
}
}
|
/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
*/
#include "arch/types.hh"
#include "arch/isa_traits.hh"
#include "base/trace.hh"
#include "base/traceflags.hh"
#include "cpu/o3/bpred_unit.hh"
template<class Impl>
BPredUnit<Impl>::BPredUnit(Params *params)
: BTB(params->BTBEntries,
params->BTBTagSize,
params->instShiftAmt)
{
// Setup the selected predictor.
if (params->predType == "local") {
localBP = new LocalBP(params->localPredictorSize,
params->localCtrBits,
params->instShiftAmt);
predictor = Local;
} else if (params->predType == "tournament") {
tournamentBP = new TournamentBP(params->localPredictorSize,
params->localCtrBits,
params->localHistoryTableSize,
params->localHistoryBits,
params->globalPredictorSize,
params->globalHistoryBits,
params->globalCtrBits,
params->choicePredictorSize,
params->choiceCtrBits,
params->instShiftAmt);
predictor = Tournament;
} else {
fatal("Invalid BP selected!");
}
for (int i=0; i < Impl::MaxThreads; i++)
RAS[i].init(params->RASSize);
}
template <class Impl>
void
BPredUnit<Impl>::regStats()
{
lookups
.name(name() + ".BPredUnit.lookups")
.desc("Number of BP lookups")
;
condPredicted
.name(name() + ".BPredUnit.condPredicted")
.desc("Number of conditional branches predicted")
;
condIncorrect
.name(name() + ".BPredUnit.condIncorrect")
.desc("Number of conditional branches incorrect")
;
BTBLookups
.name(name() + ".BPredUnit.BTBLookups")
.desc("Number of BTB lookups")
;
BTBHits
.name(name() + ".BPredUnit.BTBHits")
.desc("Number of BTB hits")
;
BTBCorrect
.name(name() + ".BPredUnit.BTBCorrect")
.desc("Number of correct BTB predictions (this stat may not "
"work properly.")
;
usedRAS
.name(name() + ".BPredUnit.usedRAS")
.desc("Number of times the RAS was used to get a target.")
;
RASIncorrect
.name(name() + ".BPredUnit.RASInCorrect")
.desc("Number of incorrect RAS predictions.")
;
}
template <class Impl>
void
BPredUnit<Impl>::switchOut()
{
// Clear any state upon switch out.
for (int i = 0; i < Impl::MaxThreads; ++i) {
squash(0, i);
}
}
template <class Impl>
void
BPredUnit<Impl>::takeOverFrom()
{
// Can reset all predictor state, but it's not necessarily better
// than leaving it be.
/*
for (int i = 0; i < Impl::MaxThreads; ++i)
RAS[i].reset();
BP.reset();
BTB.reset();
*/
}
template <class Impl>
bool
BPredUnit<Impl>::predict(DynInstPtr &inst, Addr &PC, unsigned tid)
{
// See if branch predictor predicts taken.
// If so, get its target addr either from the BTB or the RAS.
// Save off record of branch stuff so the RAS can be fixed
// up once it's done.
using TheISA::MachInst;
bool pred_taken = false;
Addr target = PC;
++lookups;
void *bp_history = NULL;
if (inst->isUncondCtrl()) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Unconditional control.\n", tid);
pred_taken = true;
// Tell the BP there was an unconditional branch.
BPUncond(bp_history);
} else {
++condPredicted;
pred_taken = BPLookup(PC, bp_history);
DPRINTF(Fetch, "BranchPred: [tid:%i]: Branch predictor predicted %i "
"for PC %#x\n",
tid, pred_taken, inst->readPC());
}
PredictorHistory predict_record(inst->seqNum, PC, pred_taken,
bp_history, tid);
// Now lookup in the BTB or RAS.
if (pred_taken) {
if (inst->isReturn()) {
++usedRAS;
// If it's a function return call, then look up the address
// in the RAS.
target = RAS[tid].top();
// Record the top entry of the RAS, and its index.
predict_record.usedRAS = true;
predict_record.RASIndex = RAS[tid].topIdx();
predict_record.RASTarget = target;
assert(predict_record.RASIndex < 16);
RAS[tid].pop();
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x is a return, "
"RAS predicted target: %#x, RAS index: %i.\n",
tid, inst->readPC(), target, predict_record.RASIndex);
} else {
++BTBLookups;
if (inst->isCall()) {
#if ISA_HAS_DELAY_SLOT
Addr ras_pc = PC + (2 * sizeof(MachInst)); // Next Next PC
#else
Addr ras_pc = PC + sizeof(MachInst); // Next PC
#endif
RAS[tid].push(ras_pc);
// Record that it was a call so that the top RAS entry can
// be popped off if the speculation is incorrect.
predict_record.wasCall = true;
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x was a call"
", adding %#x to the RAS index: %i.\n",
tid, inst->readPC(), ras_pc, RAS[tid].topIdx());
}
if (BTB.valid(PC, tid)) {
++BTBHits;
// If it's not a return, use the BTB to get the target addr.
target = BTB.lookup(PC, tid);
DPRINTF(Fetch, "BranchPred: [tid:%i]: Instruction %#x predicted"
" target is %#x.\n",
tid, inst->readPC(), target);
} else {
DPRINTF(Fetch, "BranchPred: [tid:%i]: BTB doesn't have a "
"valid entry.\n",tid);
pred_taken = false;
}
}
}
PC = target;
predHist[tid].push_front(predict_record);
DPRINTF(Fetch, "[tid:%i]: predHist.size(): %i\n", tid, predHist[tid].size());
return pred_taken;
}
template <class Impl>
void
BPredUnit<Impl>::update(const InstSeqNum &done_sn, unsigned tid)
{
DPRINTF(Fetch, "BranchPred: [tid:%i]: Commiting branches until "
"[sn:%lli].\n", tid, done_sn);
while (!predHist[tid].empty() &&
predHist[tid].back().seqNum <= done_sn) {
// Update the branch predictor with the correct results.
BPUpdate(predHist[tid].back().PC,
predHist[tid].back().predTaken,
predHist[tid].back().bpHistory);
predHist[tid].pop_back();
}
}
template <class Impl>
void
BPredUnit<Impl>::squash(const InstSeqNum &squashed_sn, unsigned tid)
{
History &pred_hist = predHist[tid];
while (!pred_hist.empty() &&
pred_hist.front().seqNum > squashed_sn) {
if (pred_hist.front().usedRAS) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Restoring top of RAS to: %i,"
" target: %#x.\n",
tid,
pred_hist.front().RASIndex,
pred_hist.front().RASTarget);
RAS[tid].restore(pred_hist.front().RASIndex,
pred_hist.front().RASTarget);
} else if (pred_hist.front().wasCall) {
DPRINTF(Fetch, "BranchPred: [tid:%i]: Removing speculative entry "
"added to the RAS.\n",tid);
RAS[tid].pop();
}
// This call should delete the bpHistory.
BPSquash(pred_hist.front().bpHistory);
pred_hist.pop_front();
}
}
template <class Impl>
void
BPredUnit<Impl>::squash(const InstSeqNum &squashed_sn,
const Addr &corr_target,
const bool actually_taken,
unsigned tid)
{
// Now that we know that a branch was mispredicted, we need to undo
// all the branches that have been seen up until this branch and
// fix up everything.
History &pred_hist = predHist[tid];
++condIncorrect;
DPRINTF(Fetch, "BranchPred: [tid:%i]: Squashing from sequence number %i, "
"setting target to %#x.\n",
tid, squashed_sn, corr_target);
squash(squashed_sn, tid);
// If there's a squash due to a syscall, there may not be an entry
// corresponding to the squash. In that case, don't bother trying to
// fix up the entry.
if (!pred_hist.empty()) {
assert(pred_hist.front().seqNum == squashed_sn);
if (pred_hist.front().usedRAS) {
++RASIncorrect;
}
BPUpdate(pred_hist.front().PC, actually_taken,
pred_hist.front().bpHistory);
BTB.update(pred_hist.front().PC, corr_target, tid);
pred_hist.pop_front();
}
}
template <class Impl>
void
BPredUnit<Impl>::BPUncond(void * &bp_history)
{
// Only the tournament predictor cares about unconditional branches.
if (predictor == Tournament) {
tournamentBP->uncondBr(bp_history);
}
}
template <class Impl>
void
BPredUnit<Impl>::BPSquash(void *bp_history)
{
if (predictor == Local) {
localBP->squash(bp_history);
} else if (predictor == Tournament) {
tournamentBP->squash(bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
bool
BPredUnit<Impl>::BPLookup(Addr &inst_PC, void * &bp_history)
{
if (predictor == Local) {
return localBP->lookup(inst_PC, bp_history);
} else if (predictor == Tournament) {
return tournamentBP->lookup(inst_PC, bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
void
BPredUnit<Impl>::BPUpdate(Addr &inst_PC, bool taken, void *bp_history)
{
if (predictor == Local) {
localBP->update(inst_PC, taken, bp_history);
} else if (predictor == Tournament) {
tournamentBP->update(inst_PC, taken, bp_history);
} else {
panic("Predictor type is unexpected value!");
}
}
template <class Impl>
void
BPredUnit<Impl>::dump()
{
typename History::iterator pred_hist_it;
for (int i = 0; i < Impl::MaxThreads; ++i) {
if (!predHist[i].empty()) {
pred_hist_it = predHist[i].begin();
cprintf("predHist[%i].size(): %i\n", i, predHist[i].size());
while (pred_hist_it != predHist[i].end()) {
cprintf("[sn:%lli], PC:%#x, tid:%i, predTaken:%i, "
"bpHistory:%#x\n",
(*pred_hist_it).seqNum, (*pred_hist_it).PC,
(*pred_hist_it).tid, (*pred_hist_it).predTaken,
(*pred_hist_it).bpHistory);
pred_hist_it++;
}
cprintf("\n");
}
}
}
|
Make sure the value of PC is actually updated now that the instruction target isn't set explicitly.
|
Make sure the value of PC is actually updated now that the instruction target isn't set explicitly.
--HG--
extra : convert_revision : 4c00a219ac1d82abea78e4e8d70f529a435fdfe2
|
C++
|
bsd-3-clause
|
TUD-OS/gem5-dtu,KuroeKurose/gem5,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,rallylee/gem5,Weil0ng/gem5,TUD-OS/gem5-dtu,markoshorro/gem5,samueldotj/TeeRISC-Simulator,gem5/gem5,KuroeKurose/gem5,rallylee/gem5,zlfben/gem5,aclifton/cpeg853-gem5,HwisooSo/gemV-update,zlfben/gem5,austinharris/gem5-riscv,HwisooSo/gemV-update,rjschof/gem5,qizenguf/MLC-STT,samueldotj/TeeRISC-Simulator,samueldotj/TeeRISC-Simulator,rallylee/gem5,austinharris/gem5-riscv,gem5/gem5,TUD-OS/gem5-dtu,Weil0ng/gem5,yb-kim/gemV,briancoutinho0905/2dsampling,markoshorro/gem5,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,sobercoder/gem5,joerocklin/gem5,TUD-OS/gem5-dtu,yb-kim/gemV,Weil0ng/gem5,cancro7/gem5,joerocklin/gem5,TUD-OS/gem5-dtu,samueldotj/TeeRISC-Simulator,yb-kim/gemV,kaiyuanl/gem5,HwisooSo/gemV-update,gem5/gem5,cancro7/gem5,samueldotj/TeeRISC-Simulator,rallylee/gem5,gedare/gem5,yb-kim/gemV,aclifton/cpeg853-gem5,SanchayanMaity/gem5,gem5/gem5,sobercoder/gem5,sobercoder/gem5,qizenguf/MLC-STT,sobercoder/gem5,markoshorro/gem5,yb-kim/gemV,HwisooSo/gemV-update,gedare/gem5,powerjg/gem5-ci-test,TUD-OS/gem5-dtu,zlfben/gem5,austinharris/gem5-riscv,markoshorro/gem5,aclifton/cpeg853-gem5,HwisooSo/gemV-update,SanchayanMaity/gem5,KuroeKurose/gem5,powerjg/gem5-ci-test,aclifton/cpeg853-gem5,Weil0ng/gem5,Weil0ng/gem5,qizenguf/MLC-STT,cancro7/gem5,joerocklin/gem5,joerocklin/gem5,KuroeKurose/gem5,gem5/gem5,Weil0ng/gem5,briancoutinho0905/2dsampling,markoshorro/gem5,kaiyuanl/gem5,cancro7/gem5,qizenguf/MLC-STT,SanchayanMaity/gem5,SanchayanMaity/gem5,austinharris/gem5-riscv,sobercoder/gem5,rjschof/gem5,SanchayanMaity/gem5,austinharris/gem5-riscv,zlfben/gem5,gedare/gem5,Weil0ng/gem5,aclifton/cpeg853-gem5,aclifton/cpeg853-gem5,austinharris/gem5-riscv,sobercoder/gem5,rjschof/gem5,samueldotj/TeeRISC-Simulator,rallylee/gem5,joerocklin/gem5,joerocklin/gem5,qizenguf/MLC-STT,KuroeKurose/gem5,gedare/gem5,KuroeKurose/gem5,powerjg/gem5-ci-test,sobercoder/gem5,yb-kim/gemV,SanchayanMaity/gem5,joerocklin/gem5,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,qizenguf/MLC-STT,TUD-OS/gem5-dtu,rjschof/gem5,HwisooSo/gemV-update,SanchayanMaity/gem5,rjschof/gem5,cancro7/gem5,rallylee/gem5,yb-kim/gemV,briancoutinho0905/2dsampling,markoshorro/gem5,yb-kim/gemV,kaiyuanl/gem5,rjschof/gem5,kaiyuanl/gem5,qizenguf/MLC-STT,rallylee/gem5,gedare/gem5,powerjg/gem5-ci-test,gem5/gem5,kaiyuanl/gem5,aclifton/cpeg853-gem5,gedare/gem5,kaiyuanl/gem5,zlfben/gem5,joerocklin/gem5,kaiyuanl/gem5,gedare/gem5,samueldotj/TeeRISC-Simulator,zlfben/gem5,austinharris/gem5-riscv,KuroeKurose/gem5,gem5/gem5,cancro7/gem5,briancoutinho0905/2dsampling,markoshorro/gem5,HwisooSo/gemV-update,cancro7/gem5,zlfben/gem5,rjschof/gem5
|
8f6f3d8d34c925199b1c7230f33f93a6d3a901df
|
gameserver/world/test/tile_test.cc
|
gameserver/world/test/tile_test.cc
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Simon Sandström
*
* 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 "tile.h"
#include "item.h"
#include "gtest/gtest.h"
class TileTest : public ::testing::Test
{
public:
TileTest()
{
ItemData itemDataA;
itemDataA.valid = true;
itemDataA.name = "Item A";
Item::setItemData(itemIdA, itemDataA);
ItemData itemDataB;
itemDataB.valid = true;
itemDataB.name = "Item B";
Item::setItemData(itemIdB, itemDataB);
ItemData itemDataC;
itemDataC.valid = true;
itemDataC.name = "Item C";
Item::setItemData(itemIdC, itemDataC);
ItemData itemDataD;
itemDataD.valid = true;
itemDataD.name = "Item D";
Item::setItemData(itemIdD, itemDataD);
}
protected:
static constexpr ItemId itemIdA = 1;
static constexpr ItemId itemIdB = 2;
static constexpr ItemId itemIdC = 3;
static constexpr ItemId itemIdD = 4;
};
TEST_F(TileTest, Constructor)
{
Item groundItem(itemIdA);
Tile tileA(groundItem);
ASSERT_EQ(tileA.getItem(0).getItemId(), groundItem.getItemId());
ASSERT_EQ(tileA.getNumberOfThings(), 1u); // Only ground item
}
TEST_F(TileTest, AddRemoveCreatures)
{
Item groundItem(itemIdA);
Tile tile(groundItem);
CreatureId creatureA(1);
CreatureId creatureB(2);
CreatureId creatureC(3);
// Add a creature and remove it
tile.addCreature(creatureA);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u); // Ground item + creature
auto result = tile.removeCreature(creatureA);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
// Add all three creatures
tile.addCreature(creatureA);
tile.addCreature(creatureB);
tile.addCreature(creatureC);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 3u);
// Remove creatureA and creatureC
result = tile.removeCreature(creatureA);
ASSERT_TRUE(result);
result = tile.removeCreature(creatureC);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u);
// Try to remove creatureA again
result = tile.removeCreature(creatureA);
ASSERT_FALSE(result);
// Remove last creature
result = tile.removeCreature(creatureB);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
}
TEST_F(TileTest, AddRemoveItems)
{
Item groundItem(itemIdD);
Tile tile(groundItem);
Item itemA(itemIdA);
Item itemB(itemIdB);
Item itemC(itemIdC);
// Add an item and remove it
tile.addItem(itemA);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u); // Ground item + item
auto result = tile.removeItem(itemA.getItemId(), 1); // Only item => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
// Add all three items
tile.addItem(itemA);
tile.addItem(itemB);
tile.addItem(itemC);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 3u);
// Remove itemA and itemC
result = tile.removeItem(itemA.getItemId(), 3); // Two items were added after itemA => stackpos = 3
ASSERT_TRUE(result);
result = tile.removeItem(itemC.getItemId(), 1); // itemC was added last => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u);
// Try to remove itemA again
result = tile.removeItem(itemA.getItemId(), 1);
ASSERT_FALSE(result);
// Remove last item
result = tile.removeItem(itemB.getItemId(), 1); // Only item => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Simon Sandström
*
* 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 "tile.h"
#include "item.h"
#include "gtest/gtest.h"
class TileTest : public ::testing::Test
{
public:
TileTest()
{
ItemData itemDataA;
itemDataA.valid = true;
itemDataA.name = "Item A";
Item::setItemData(itemIdA, itemDataA);
ItemData itemDataB;
itemDataB.valid = true;
itemDataB.name = "Item B";
Item::setItemData(itemIdB, itemDataB);
ItemData itemDataC;
itemDataC.valid = true;
itemDataC.name = "Item C";
Item::setItemData(itemIdC, itemDataC);
ItemData itemDataD;
itemDataD.valid = true;
itemDataD.name = "Item D";
Item::setItemData(itemIdD, itemDataD);
}
protected:
static constexpr ItemId itemIdA = 1;
static constexpr ItemId itemIdB = 2;
static constexpr ItemId itemIdC = 3;
static constexpr ItemId itemIdD = 4;
};
TEST_F(TileTest, Constructor)
{
Item groundItem(itemIdA);
Tile tileA(groundItem);
ASSERT_EQ(tileA.getItem(0)->getItemId(), groundItem.getItemId());
ASSERT_EQ(tileA.getNumberOfThings(), 1u); // Only ground item
}
TEST_F(TileTest, AddRemoveCreatures)
{
Item groundItem(itemIdA);
Tile tile(groundItem);
CreatureId creatureA(1);
CreatureId creatureB(2);
CreatureId creatureC(3);
// Add a creature and remove it
tile.addCreature(creatureA);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u); // Ground item + creature
auto result = tile.removeCreature(creatureA);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
// Add all three creatures
tile.addCreature(creatureA);
tile.addCreature(creatureB);
tile.addCreature(creatureC);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 3u);
// Remove creatureA and creatureC
result = tile.removeCreature(creatureA);
ASSERT_TRUE(result);
result = tile.removeCreature(creatureC);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u);
// Try to remove creatureA again
result = tile.removeCreature(creatureA);
ASSERT_FALSE(result);
// Remove last creature
result = tile.removeCreature(creatureB);
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
}
TEST_F(TileTest, AddRemoveItems)
{
Item groundItem(itemIdD);
Tile tile(groundItem);
Item itemA(itemIdA);
Item itemB(itemIdB);
Item itemC(itemIdC);
// Add an item and remove it
tile.addItem(itemA);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u); // Ground item + item
auto result = tile.removeItem(itemA.getItemId(), 1); // Only item => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
// Add all three items
tile.addItem(itemA);
tile.addItem(itemB);
tile.addItem(itemC);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 3u);
// Remove itemA and itemC
result = tile.removeItem(itemA.getItemId(), 3); // Two items were added after itemA => stackpos = 3
ASSERT_TRUE(result);
result = tile.removeItem(itemC.getItemId(), 1); // itemC was added last => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 1u);
// Try to remove itemA again
result = tile.removeItem(itemA.getItemId(), 1);
ASSERT_FALSE(result);
// Remove last item
result = tile.removeItem(itemB.getItemId(), 1); // Only item => stackpos = 1
ASSERT_TRUE(result);
ASSERT_EQ(tile.getNumberOfThings(), 1u + 0u);
}
|
Fix world/test build issue
|
Fix world/test build issue
|
C++
|
mit
|
gurka/gameserver,gurka/gameserver,gurka/gameserver
|
6e34790ff83ddd54e1eb13b2d08e60ab36ba0e91
|
gameserver/wsclient/src/network.cc
|
gameserver/wsclient/src/network.cc
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Simon Sandström
*
* 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 "network.h"
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <cstdint>
#include <string>
#include <vector>
#include "logger.h"
#include "outgoing_packet.h"
#include "incoming_packet.h"
namespace
{
emscripten::val ws = emscripten::val::null();
std::function<void(network::IncomingPacket*)> handle_packet;
void connect()
{
ws = emscripten::val::global("WebSocket").new_(emscripten::val("ws://192.168.1.4:8172"));
ws.set("onopen", emscripten::val::module_property("onopen"));
ws.set("onmessage", emscripten::val::module_property("onmessage"));
}
void send_packet(const network::OutgoingPacket& packet)
{
static std::uint8_t header[2];
header[0] = packet.getLength();
header[1] = packet.getLength() >> 8;
ws.call<void>("send", std::string(reinterpret_cast<const char*>(header), 2));
ws.call<void>("send", std::string(reinterpret_cast<const char*>(packet.getBuffer()), packet.getLength()));
}
void onopen(emscripten::val event)
{
(void)event;
// Send login packet
network::OutgoingPacket packet;
packet.addU8(0x0A);
packet.skipBytes(5);
packet.addString("Alice");
packet.addString("1");
send_packet(packet);
}
void onmessage(emscripten::val event)
{
// Convert to Uint8Array
auto reader = emscripten::val::global("FileReader").new_();
reader.call<void>("readAsArrayBuffer", event["data"]);
reader.call<void>("addEventListener", std::string("loadend"), emscripten::val::module_property("onmessage_buffer"));
}
void onmessage_buffer(emscripten::val event)
{
static std::vector<std::uint8_t> buffer;
const auto str = event["target"]["result"].as<std::string>();
buffer.insert(buffer.end(),
reinterpret_cast<const std::uint8_t*>(str.data()),
reinterpret_cast<const std::uint8_t*>(str.data() + str.length()));
//LOG_INFO("%s: BEFORE: %d AFTER: %d ADDED: %d", __func__, buffer.size() - str.length(), buffer.size(), str.length());
// Check if we have enough for next packet
while (buffer.size() >= 2u)
{
const auto next_packet_length = buffer[0] | (buffer[1] << 8);
//LOG_INFO("%s: next_packet_length: %d", __func__, next_packet_length);
if (buffer.size() >= 2u + next_packet_length)
{
network::IncomingPacket packet(buffer.data() + 2, next_packet_length);
handle_packet(&packet);
buffer.erase(buffer.begin(), buffer.begin() + 2u + next_packet_length);
}
else
{
break;
}
}
//LOG_INFO("%s: AFTER HANDLE: %d", __func__, buffer.size());
}
EMSCRIPTEN_BINDINGS(websocket_callbacks)
{
emscripten::function("onopen", &onopen);
emscripten::function("onmessage", &onmessage);
emscripten::function("onmessage_buffer", &onmessage_buffer);
}
}
namespace wsclient::network
{
void start(const std::function<void(IncomingPacket*)> callback)
{
handle_packet = callback;
connect();
}
} // namespace wsclient::network
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Simon Sandström
*
* 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 "network.h"
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <cstdint>
#include <string>
#include <vector>
#include "logger.h"
#include "outgoing_packet.h"
#include "incoming_packet.h"
namespace
{
emscripten::val ws = emscripten::val::null();
std::function<void(network::IncomingPacket*)> handle_packet;
void connect()
{
const auto url = emscripten::val::global("URLSearchParams").new_(emscripten::val::global("location")["search"]);
const auto address = url.call<std::string>("get", emscripten::val("address"));
LOG_INFO("%s: found address: '%s'", __func__, address.c_str());
ws = emscripten::val::global("WebSocket").new_(emscripten::val(address));
ws.set("onopen", emscripten::val::module_property("onopen"));
ws.set("onmessage", emscripten::val::module_property("onmessage"));
}
void send_packet(const network::OutgoingPacket& packet)
{
static std::uint8_t header[2];
header[0] = packet.getLength();
header[1] = packet.getLength() >> 8;
ws.call<void>("send", std::string(reinterpret_cast<const char*>(header), 2));
ws.call<void>("send", std::string(reinterpret_cast<const char*>(packet.getBuffer()), packet.getLength()));
}
void onopen(emscripten::val event)
{
(void)event;
// Send login packet
network::OutgoingPacket packet;
packet.addU8(0x0A);
packet.skipBytes(5);
packet.addString("Alice");
packet.addString("1");
send_packet(packet);
}
void onmessage(emscripten::val event)
{
// Convert to Uint8Array
auto reader = emscripten::val::global("FileReader").new_();
reader.call<void>("readAsArrayBuffer", event["data"]);
reader.call<void>("addEventListener", std::string("loadend"), emscripten::val::module_property("onmessage_buffer"));
}
void onmessage_buffer(emscripten::val event)
{
static std::vector<std::uint8_t> buffer;
const auto str = event["target"]["result"].as<std::string>();
buffer.insert(buffer.end(),
reinterpret_cast<const std::uint8_t*>(str.data()),
reinterpret_cast<const std::uint8_t*>(str.data() + str.length()));
//LOG_INFO("%s: BEFORE: %d AFTER: %d ADDED: %d", __func__, buffer.size() - str.length(), buffer.size(), str.length());
// Check if we have enough for next packet
while (buffer.size() >= 2u)
{
const auto next_packet_length = buffer[0] | (buffer[1] << 8);
//LOG_INFO("%s: next_packet_length: %d", __func__, next_packet_length);
if (buffer.size() >= 2u + next_packet_length)
{
network::IncomingPacket packet(buffer.data() + 2, next_packet_length);
handle_packet(&packet);
buffer.erase(buffer.begin(), buffer.begin() + 2u + next_packet_length);
}
else
{
break;
}
}
//LOG_INFO("%s: AFTER HANDLE: %d", __func__, buffer.size());
}
EMSCRIPTEN_BINDINGS(websocket_callbacks)
{
emscripten::function("onopen", &onopen);
emscripten::function("onmessage", &onmessage);
emscripten::function("onmessage_buffer", &onmessage_buffer);
}
}
namespace wsclient::network
{
void start(const std::function<void(IncomingPacket*)> callback)
{
handle_packet = callback;
connect();
}
} // namespace wsclient::network
|
use address from query parameter
|
wsclient: use address from query parameter
|
C++
|
mit
|
gurka/gameserver,gurka/gameserver,gurka/gameserver
|
f5804cddbc2d103cabf7054905dc1bd59512b9b6
|
vcl/inc/unx/gtk/gtksalmenu.hxx
|
vcl/inc/unx/gtk/gtksalmenu.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Copyright © 2011 Canonical Ltd.
*
* 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
* licence, 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.
*
* Author: Antonio Fernández <[email protected]>
*/
#ifndef GTKSALMENU_HXX
#define GTKSALMENU_HXX
#include <vector>
#include <gio/gio.h>
#include <unx/salmenu.h>
#include <unx/gtk/gtkframe.hxx>
#include <unx/gtk/glomenu.h>
#include <unx/gtk/gloactiongroup.h>
class MenuItemList;
class GtkSalMenuItem;
// Generate the complete structure of a menu.
//static void GenerateFullMenu( GtkSalMenu* pSalMenu );
class GtkSalMenu : public SalMenu
{
private:
std::vector< GtkSalMenuItem* > maItems;
sal_Bool mbMenuBar;
Menu* mpVCLMenu;
GtkSalMenu* mpOldSalMenu;
GtkSalMenu* mpParentSalMenu;
const GtkSalFrame* mpFrame;
// GMenuModel and GActionGroup attributes
GMenuModel* mpMenuModel;
GActionGroup* mpActionGroup;
GtkSalMenu* GetMenuForItemCommand( gchar* aCommand, gboolean bGetSubmenu );
void ImplUpdate( gboolean bRecurse );
public:
GtkSalMenu( sal_Bool bMenuBar );
virtual ~GtkSalMenu();
virtual sal_Bool VisibleMenuBar(); // must return TRUE to actually DISPLAY native menu bars
// otherwise only menu messages are processed (eg, OLE on Windows)
virtual void InsertItem( SalMenuItem* pSalMenuItem, unsigned nPos );
virtual void RemoveItem( unsigned nPos );
virtual void SetSubMenu( SalMenuItem* pSalMenuItem, SalMenu* pSubMenu, unsigned nPos );
virtual void SetFrame( const SalFrame* pFrame );
virtual const GtkSalFrame* GetFrame() const;
virtual void CheckItem( unsigned nPos, sal_Bool bCheck );
virtual void EnableItem( unsigned nPos, sal_Bool bEnable );
virtual void ShowItem( unsigned nPos, sal_Bool bShow );
virtual void SetItemText( unsigned nPos, SalMenuItem* pSalMenuItem, const rtl::OUString& rText );
virtual void SetItemImage( unsigned nPos, SalMenuItem* pSalMenuItem, const Image& rImage);
virtual void SetAccelerator( unsigned nPos, SalMenuItem* pSalMenuItem, const KeyCode& rKeyCode, const rtl::OUString& rKeyName );
virtual void GetSystemMenuData( SystemMenuData* pData );
virtual void SetMenu( Menu* pMenu ) { mpVCLMenu = pMenu; }
virtual Menu* GetMenu() { return mpVCLMenu; }
virtual GtkSalMenu* GetParentSalMenu() { return mpParentSalMenu; }
virtual void SetMenuModel( GMenuModel* pMenuModel ) { mpMenuModel = pMenuModel; }
virtual GMenuModel* GetMenuModel() { return mpMenuModel; }
virtual unsigned GetItemCount() { return maItems.size(); }
virtual GtkSalMenuItem* GetItemAtPos( unsigned nPos ) { return maItems[ nPos ]; }
virtual void SetActionGroup( GActionGroup* pActionGroup ) { mpActionGroup = pActionGroup; }
virtual GActionGroup* GetActionGroup() { return mpActionGroup; }
virtual sal_Bool IsItemVisible( unsigned nPos );
void NativeSetItemText( unsigned nSection, unsigned nItemPos, const rtl::OUString& rText );
void NativeSetItemCommand( unsigned nSection,
unsigned nItemPos,
sal_uInt16 nId,
const gchar* aCommand,
MenuItemBits nBits,
gboolean bChecked,
gboolean bIsSubmenu );
void NativeSetEnableItem( gchar* aCommand, gboolean bEnable );
void NativeCheckItem( unsigned nSection, unsigned nItemPos, MenuItemBits bits, gboolean bCheck );
void NativeSetAccelerator( unsigned nSection, unsigned nItemPos, const KeyCode& rKeyCode, const rtl::OUString& rKeyName );
void DispatchCommand( gint itemId, const gchar* aCommand );
void Activate( const gchar* aMenuCommand );
void Deactivate( const gchar* aMenuCommand );
void Display( sal_Bool bVisible );
bool PrepUpdate();
void Update(); // Update this menu only.
void UpdateFull(); // Update full menu hierarchy from this menu.
};
class GtkSalMenuItem : public SalMenuItem
{
public:
GtkSalMenuItem( const SalItemParams* );
virtual ~GtkSalMenuItem();
sal_uInt16 mnId; // Item ID
MenuItemType mnType; // Item type
sal_Bool mbVisible; // Item visibility.
Menu* mpVCLMenu; // VCL Menu into which this menu item is inserted
GtkSalMenu* mpParentMenu; // The menu into which this menu item is inserted
GtkSalMenu* mpSubMenu; // Submenu of this item (if defined)
};
#endif // GTKSALMENU_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Copyright © 2011 Canonical Ltd.
*
* 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
* licence, 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.
*
* Author: Antonio Fernández <[email protected]>
*/
#ifndef GTKSALMENU_HXX
#define GTKSALMENU_HXX
#include <vector>
#include <gio/gio.h>
#include <unx/salmenu.h>
#include <unx/gtk/gtkframe.hxx>
#include <unx/gtk/glomenu.h>
#include <unx/gtk/gloactiongroup.h>
class MenuItemList;
class GtkSalMenuItem;
class GtkSalMenu : public SalMenu
{
private:
std::vector< GtkSalMenuItem* > maItems;
sal_Bool mbMenuBar;
Menu* mpVCLMenu;
GtkSalMenu* mpOldSalMenu;
GtkSalMenu* mpParentSalMenu;
const GtkSalFrame* mpFrame;
// GMenuModel and GActionGroup attributes
GMenuModel* mpMenuModel;
GActionGroup* mpActionGroup;
GtkSalMenu* GetMenuForItemCommand( gchar* aCommand, gboolean bGetSubmenu );
void ImplUpdate( gboolean bRecurse );
public:
GtkSalMenu( sal_Bool bMenuBar );
virtual ~GtkSalMenu();
virtual sal_Bool VisibleMenuBar(); // must return TRUE to actually DISPLAY native menu bars
// otherwise only menu messages are processed (eg, OLE on Windows)
virtual void InsertItem( SalMenuItem* pSalMenuItem, unsigned nPos );
virtual void RemoveItem( unsigned nPos );
virtual void SetSubMenu( SalMenuItem* pSalMenuItem, SalMenu* pSubMenu, unsigned nPos );
virtual void SetFrame( const SalFrame* pFrame );
virtual const GtkSalFrame* GetFrame() const;
virtual void CheckItem( unsigned nPos, sal_Bool bCheck );
virtual void EnableItem( unsigned nPos, sal_Bool bEnable );
virtual void ShowItem( unsigned nPos, sal_Bool bShow );
virtual void SetItemText( unsigned nPos, SalMenuItem* pSalMenuItem, const rtl::OUString& rText );
virtual void SetItemImage( unsigned nPos, SalMenuItem* pSalMenuItem, const Image& rImage);
virtual void SetAccelerator( unsigned nPos, SalMenuItem* pSalMenuItem, const KeyCode& rKeyCode, const rtl::OUString& rKeyName );
virtual void GetSystemMenuData( SystemMenuData* pData );
virtual void SetMenu( Menu* pMenu ) { mpVCLMenu = pMenu; }
virtual Menu* GetMenu() { return mpVCLMenu; }
virtual GtkSalMenu* GetParentSalMenu() { return mpParentSalMenu; }
virtual void SetMenuModel( GMenuModel* pMenuModel ) { mpMenuModel = pMenuModel; }
virtual GMenuModel* GetMenuModel() { return mpMenuModel; }
virtual unsigned GetItemCount() { return maItems.size(); }
virtual GtkSalMenuItem* GetItemAtPos( unsigned nPos ) { return maItems[ nPos ]; }
virtual void SetActionGroup( GActionGroup* pActionGroup ) { mpActionGroup = pActionGroup; }
virtual GActionGroup* GetActionGroup() { return mpActionGroup; }
virtual sal_Bool IsItemVisible( unsigned nPos );
void NativeSetItemText( unsigned nSection, unsigned nItemPos, const rtl::OUString& rText );
void NativeSetItemCommand( unsigned nSection,
unsigned nItemPos,
sal_uInt16 nId,
const gchar* aCommand,
MenuItemBits nBits,
gboolean bChecked,
gboolean bIsSubmenu );
void NativeSetEnableItem( gchar* aCommand, gboolean bEnable );
void NativeCheckItem( unsigned nSection, unsigned nItemPos, MenuItemBits bits, gboolean bCheck );
void NativeSetAccelerator( unsigned nSection, unsigned nItemPos, const KeyCode& rKeyCode, const rtl::OUString& rKeyName );
void DispatchCommand( gint itemId, const gchar* aCommand );
void Activate( const gchar* aMenuCommand );
void Deactivate( const gchar* aMenuCommand );
void Display( sal_Bool bVisible );
bool PrepUpdate();
void Update(); // Update this menu only.
void UpdateFull(); // Update full menu hierarchy from this menu.
};
class GtkSalMenuItem : public SalMenuItem
{
public:
GtkSalMenuItem( const SalItemParams* );
virtual ~GtkSalMenuItem();
sal_uInt16 mnId; // Item ID
MenuItemType mnType; // Item type
sal_Bool mbVisible; // Item visibility.
Menu* mpVCLMenu; // VCL Menu into which this menu item is inserted
GtkSalMenu* mpParentMenu; // The menu into which this menu item is inserted
GtkSalMenu* mpSubMenu; // Submenu of this item (if defined)
};
#endif // GTKSALMENU_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
remove unused prototype
|
remove unused prototype
Change-Id: If3deb18695d0bef3545d6aef5e598435996a7207
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
0024d7283a47a1b362953cbe77f30ae7177a2781
|
src/dev/arm/timer_cpulocal.hh
|
src/dev/arm/timer_cpulocal.hh
|
/*
* Copyright (c) 2010-2011 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Geoffrey Blake
*/
#ifndef __DEV_ARM_LOCALTIMER_HH__
#define __DEV_ARM_LOCALTIMER_HH__
#include "base/range.hh"
#include "dev/io_device.hh"
#include "params/CpuLocalTimer.hh"
/** @file
* This implements the cpu local timer from the Cortex-A9 MPCore
* Technical Reference Manual rev r2p2 (ARM DDI 0407F)
*/
class Gic;
class CpuLocalTimer : public BasicPioDevice
{
protected:
class Timer
{
public:
enum {
TimerLoadReg = 0x00,
TimerCounterReg = 0x04,
TimerControlReg = 0x08,
TimerIntStatusReg = 0x0C,
WatchdogLoadReg = 0x20,
WatchdogCounterReg = 0x24,
WatchdogControlReg = 0x28,
WatchdogIntStatusReg = 0x2C,
WatchdogResetStatusReg = 0x30,
WatchdogDisableReg = 0x34,
Size = 0x38
};
BitUnion32(TimerCtrl)
Bitfield<0> enable;
Bitfield<1> autoReload;
Bitfield<2> intEnable;
Bitfield<3,7> reserved;
Bitfield<8,15> prescalar;
EndBitUnion(TimerCtrl)
BitUnion32(WatchdogCtrl)
Bitfield<0> enable;
Bitfield<1> autoReload;
Bitfield<2> intEnable;
Bitfield<3> watchdogMode;
Bitfield<4,7> reserved;
Bitfield<8,15> prescalar;
EndBitUnion(WatchdogCtrl)
protected:
std::string _name;
/** Pointer to parent class */
CpuLocalTimer *parent;
/** Number of interrupt to cause/clear */
uint32_t intNumTimer;
uint32_t intNumWatchdog;
/** Cpu this timer is attached to */
uint32_t cpuNum;
/** Number of ticks in a clock input */
Tick clock;
/** Control register as specified above */
TimerCtrl timerControl;
WatchdogCtrl watchdogControl;
/** If timer has caused an interrupt. This is irrespective of
* interrupt enable */
bool rawIntTimer;
bool rawIntWatchdog;
bool rawResetWatchdog;
uint32_t watchdogDisableReg;
/** If an interrupt is currently pending. Logical and of Timer or
* Watchdog Ctrl.enable and rawIntTimer or rawIntWatchdog */
bool pendingIntTimer;
bool pendingIntWatchdog;
/** Value to load into counters when periodic mode reaches 0 */
uint32_t timerLoadValue;
uint32_t watchdogLoadValue;
/** Called when the counter reaches 0 */
void timerAtZero();
EventWrapper<Timer, &Timer::timerAtZero> timerZeroEvent;
void watchdogAtZero();
EventWrapper<Timer, &Timer::watchdogAtZero> watchdogZeroEvent;
public:
/** Restart the counter ticking at val
* @param val the value to start at */
void restartTimerCounter(uint32_t val);
void restartWatchdogCounter(uint32_t val);
Timer();
std::string name() const { return _name; }
/** Handle read for a single timer */
void read(PacketPtr pkt, Addr daddr);
/** Handle write for a single timer */
void write(PacketPtr pkt, Addr daddr);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
friend class CpuLocalTimer;
};
static const int CPU_MAX = 8;
/** Pointer to the GIC for causing an interrupt */
Gic *gic;
/** Timers that do the actual work */
Timer localTimer[CPU_MAX];
public:
typedef CpuLocalTimerParams Params;
const Params *
params() const
{
return dynamic_cast<const Params *>(_params);
}
/**
* The constructor for RealView just registers itself with the MMU.
* @param p params structure
*/
CpuLocalTimer(Params *p);
/**
* Handle a read to the device
* @param pkt The memory request.
* @return Returns latency of device read
*/
virtual Tick read(PacketPtr pkt);
/**
* Handle a write to the device.
* @param pkt The memory request.
* @return Returns latency of device write
*/
virtual Tick write(PacketPtr pkt);
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
#endif // __DEV_ARM_SP804_HH__
|
/*
* Copyright (c) 2010-2011 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Geoffrey Blake
*/
#ifndef __DEV_ARM_LOCALTIMER_HH__
#define __DEV_ARM_LOCALTIMER_HH__
#include "base/range.hh"
#include "dev/io_device.hh"
#include "params/CpuLocalTimer.hh"
/** @file
* This implements the cpu local timer from the Cortex-A9 MPCore
* Technical Reference Manual rev r2p2 (ARM DDI 0407F)
*/
class Gic;
class CpuLocalTimer : public BasicPioDevice
{
protected:
class Timer
{
public:
enum {
TimerLoadReg = 0x00,
TimerCounterReg = 0x04,
TimerControlReg = 0x08,
TimerIntStatusReg = 0x0C,
WatchdogLoadReg = 0x20,
WatchdogCounterReg = 0x24,
WatchdogControlReg = 0x28,
WatchdogIntStatusReg = 0x2C,
WatchdogResetStatusReg = 0x30,
WatchdogDisableReg = 0x34,
Size = 0x38
};
BitUnion32(TimerCtrl)
Bitfield<0> enable;
Bitfield<1> autoReload;
Bitfield<2> intEnable;
Bitfield<7,3> reserved;
Bitfield<15,8> prescalar;
EndBitUnion(TimerCtrl)
BitUnion32(WatchdogCtrl)
Bitfield<0> enable;
Bitfield<1> autoReload;
Bitfield<2> intEnable;
Bitfield<3> watchdogMode;
Bitfield<7,4> reserved;
Bitfield<15,8> prescalar;
EndBitUnion(WatchdogCtrl)
protected:
std::string _name;
/** Pointer to parent class */
CpuLocalTimer *parent;
/** Number of interrupt to cause/clear */
uint32_t intNumTimer;
uint32_t intNumWatchdog;
/** Cpu this timer is attached to */
uint32_t cpuNum;
/** Number of ticks in a clock input */
Tick clock;
/** Control register as specified above */
TimerCtrl timerControl;
WatchdogCtrl watchdogControl;
/** If timer has caused an interrupt. This is irrespective of
* interrupt enable */
bool rawIntTimer;
bool rawIntWatchdog;
bool rawResetWatchdog;
uint32_t watchdogDisableReg;
/** If an interrupt is currently pending. Logical and of Timer or
* Watchdog Ctrl.enable and rawIntTimer or rawIntWatchdog */
bool pendingIntTimer;
bool pendingIntWatchdog;
/** Value to load into counters when periodic mode reaches 0 */
uint32_t timerLoadValue;
uint32_t watchdogLoadValue;
/** Called when the counter reaches 0 */
void timerAtZero();
EventWrapper<Timer, &Timer::timerAtZero> timerZeroEvent;
void watchdogAtZero();
EventWrapper<Timer, &Timer::watchdogAtZero> watchdogZeroEvent;
public:
/** Restart the counter ticking at val
* @param val the value to start at */
void restartTimerCounter(uint32_t val);
void restartWatchdogCounter(uint32_t val);
Timer();
std::string name() const { return _name; }
/** Handle read for a single timer */
void read(PacketPtr pkt, Addr daddr);
/** Handle write for a single timer */
void write(PacketPtr pkt, Addr daddr);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
friend class CpuLocalTimer;
};
static const int CPU_MAX = 8;
/** Pointer to the GIC for causing an interrupt */
Gic *gic;
/** Timers that do the actual work */
Timer localTimer[CPU_MAX];
public:
typedef CpuLocalTimerParams Params;
const Params *
params() const
{
return dynamic_cast<const Params *>(_params);
}
/**
* The constructor for RealView just registers itself with the MMU.
* @param p params structure
*/
CpuLocalTimer(Params *p);
/**
* Handle a read to the device
* @param pkt The memory request.
* @return Returns latency of device read
*/
virtual Tick read(PacketPtr pkt);
/**
* Handle a write to the device.
* @param pkt The memory request.
* @return Returns latency of device write
*/
virtual Tick write(PacketPtr pkt);
virtual void serialize(std::ostream &os);
virtual void unserialize(Checkpoint *cp, const std::string §ion);
};
#endif // __DEV_ARM_SP804_HH__
|
Fix bifield definition in timer_cpulocal.hh
|
dev: Fix bifield definition in timer_cpulocal.hh
Bitfield definition in the local timer model for ARM had the bitfield
range numbers reversed which could lead to buggy behavior.
|
C++
|
bsd-3-clause
|
vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,vovojh/gem5,hoangt/tpzsimul.gem5,vovojh/gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,vovojh/gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-
|
1250a24335f4671a5046bc13a62b5210c5ecd2c9
|
backends/bmv2/JsonObjects.cpp
|
backends/bmv2/JsonObjects.cpp
|
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lib/json.h"
#include "JsonObjects.h"
#include "helpers.h"
namespace BMV2 {
const int JSON_MAJOR_VERSION = 2;
const int JSON_MINOR_VERSION = 7;
JsonObjects::JsonObjects() {
toplevel = new Util::JsonObject();
header_types = insert_array_field(toplevel, "header_types");
headers = insert_array_field(toplevel, "headers");
header_stacks = insert_array_field(toplevel, "header_stacks");
field_lists = insert_array_field(toplevel, "field_lists");
errors = insert_array_field(toplevel, "errors");
enums = insert_array_field(toplevel, "enums");
parsers = insert_array_field(toplevel, "parsers");
deparsers = insert_array_field(toplevel, "deparsers");
meter_arrays = insert_array_field(toplevel, "meter_arrays");
counters = insert_array_field(toplevel, "counter_arrays");
register_arrays = insert_array_field(toplevel, "register_arrays");
calculations = insert_array_field(toplevel, "calculations");
learn_lists = insert_array_field(toplevel, "learn_lists");
actions = insert_array_field(toplevel, "actions");
pipelines = insert_array_field(toplevel, "pipelines");
checksums = insert_array_field(toplevel, "checksums");
force_arith = insert_array_field(toplevel, "force_arith");
externs = insert_array_field(toplevel, "extern_instances");
field_aliases = insert_array_field(toplevel, "field_aliases");
}
Util::JsonObject*
JsonObjects::find_object_by_name(Util::JsonArray* array, const cstring& name) {
for (auto e : *array) {
auto obj = e->to<Util::JsonObject>();
auto val = obj->get("name")->to<Util::JsonValue>();
if (val != nullptr && val->isString() && val->getString() == name) {
return obj;
}
}
return nullptr;
}
/// Insert a json array to a parent object under key 'name'.
Util::JsonArray*
JsonObjects::insert_array_field(Util::JsonObject* parent, cstring name) {
auto result = new Util::JsonArray();
parent->emplace(name, result);
return result;
}
/// Append a json array to a parent json array.
Util::JsonArray*
JsonObjects::append_array(Util::JsonArray* parent) {
auto result = new Util::JsonArray();
parent->append(result);
return result;
}
/// Insert a json array named 'parameters' in a parent json object.
Util::JsonArray*
JsonObjects::create_parameters(Util::JsonObject* object) {
return insert_array_field(object, "parameters");
}
/// Append a json object r to a parent json array,
/// insert a field 'op' with 'name' to parent.
Util::JsonObject*
JsonObjects::create_primitive(Util::JsonArray* parent, cstring name) {
auto result = new Util::JsonObject();
result->emplace("op", name);
parent->append(result);
return result;
}
void
JsonObjects::add_program_info(const cstring& name) {
toplevel->emplace("program", name);
}
void
JsonObjects::add_meta_info() {
auto info = new Util::JsonObject();
static constexpr int version_major = JSON_MAJOR_VERSION;
static constexpr int version_minor = JSON_MINOR_VERSION;
auto version = insert_array_field(info, "version");
version->append(version_major);
version->append(version_minor);
info->emplace("compiler", "https://github.com/p4lang/p4c");
toplevel->emplace("__meta__", info);
meta = info; // TODO(hanw): remove
}
/**
* Create a header type in json.
* @param name header name
* @param type header type
* @param max_length maximum length for a header with varbit fields;
* if 0 header does not contain varbit fields
* @param fields a JsonArray for the fields in the header
*/
unsigned
JsonObjects::add_header_type(const cstring& name, Util::JsonArray*& fields, unsigned max_length) {
std::string sname(name, name.size());
auto header_type_id_it = header_type_id.find(sname);
if (header_type_id_it != header_type_id.end()) {
return header_type_id_it->second;
}
auto header_type = new Util::JsonObject();
unsigned id = BMV2::nextId("header_types");
header_type_id[sname] = id;
header_type->emplace("name", name);
header_type->emplace("id", id);
if (fields != nullptr) {
header_type->emplace("fields", fields);
} else {
auto temp = new Util::JsonArray();
header_type->emplace("fields", temp);
}
if (max_length > 0)
header_type->emplace("max_length", max_length);
header_types->append(header_type);
return id;
}
/// Create a header type with empty field list.
unsigned
JsonObjects::add_header_type(const cstring& name) {
std::string sname(name, name.size());
auto header_type_id_it = header_type_id.find(sname);
if (header_type_id_it != header_type_id.end()) {
return header_type_id_it->second;
}
auto header_type = new Util::JsonObject();
unsigned id = BMV2::nextId("header_types");
header_type_id[sname] = id;
header_type->emplace("name", name);
header_type->emplace("id", id);
auto temp = new Util::JsonArray();
header_type->emplace("fields", temp);
header_types->append(header_type);
return id;
}
/// Create a set of fields to an existing header type.
/// The header type is decribed by the name.
void
JsonObjects::add_header_field(const cstring& name, Util::JsonArray*& field) {
CHECK_NULL(field);
Util::JsonObject* headerType = find_object_by_name(header_types, name);
Util::JsonArray* fields = headerType->get("fields")->to<Util::JsonArray>();
BUG_CHECK(fields != nullptr, "header '%1%' not found", name);
fields->append(field);
}
/// Create a header instance in json.
unsigned
JsonObjects::add_header(const cstring& type, const cstring& name) {
auto header = new Util::JsonObject();
unsigned id = BMV2::nextId("headers");
LOG1("add header id " << id);
header->emplace("name", name);
header->emplace("id", id);
header->emplace("header_type", type);
header->emplace("metadata", false);
header->emplace("pi_omit", true);
headers->append(header);
return id;
}
unsigned
JsonObjects::add_metadata(const cstring& type, const cstring& name) {
auto header = new Util::JsonObject();
unsigned id = BMV2::nextId("headers");
LOG1("add metadata header id " << id);
header->emplace("name", name);
header->emplace("id", id);
header->emplace("header_type", type);
header->emplace("metadata", true);
header->emplace("pi_omit", true); // Don't expose in PI.
headers->append(header);
return id;
}
void
JsonObjects::add_header_stack(const cstring& type, const cstring& name,
const unsigned size, std::vector<unsigned>& ids) {
auto stack = new Util::JsonObject();
unsigned id = BMV2::nextId("stack");
stack->emplace("name", name);
stack->emplace("id", id);
stack->emplace("header_type", type);
stack->emplace("size", size);
auto members = new Util::JsonArray();
stack->emplace("header_ids", members);
for (auto id : ids) {
members->append(id);
}
header_stacks->append(stack);
}
/// Add an error to json.
void
JsonObjects::add_error(const cstring& name, const unsigned type) {
auto arr = append_array(errors);
arr->append(name);
arr->append(type);
}
/// Add a single enum entry to json.
/// A enum entry is identified with { enum_name, entry_name, entry_value }
void
JsonObjects::add_enum(const cstring& enum_name, const cstring& entry_name,
const unsigned entry_value) {
// look up enum in json by name
Util::JsonObject* enum_json = find_object_by_name(enums, enum_name);
if (enum_json == nullptr) { // first entry in a new enum
enum_json = new Util::JsonObject();
enum_json->emplace("name", enum_name);
auto entries = insert_array_field(enum_json, "entries");
auto entry = new Util::JsonArray();
entry->append(entry_name);
entry->append(entry_value);
entries->append(entry);
enums->append(enum_json);
LOG3("new enum object: " << enum_name << " " << entry_name << " " << entry_value);
} else { // add entry to existing enum
auto entries = enum_json->get("entries")->to<Util::JsonArray>();
auto entry = new Util::JsonArray();
entry->append(entry_name);
entry->append(entry_value);
entries->append(entry);
LOG3("new enum entry: " << enum_name << " " << entry_name << " " << entry_value);
}
}
unsigned
JsonObjects::add_parser(const cstring& name) {
auto parser = new Util::JsonObject();
unsigned id = BMV2::nextId("parser");
parser->emplace("name", name);
parser->emplace("id", id);
parser->emplace("init_state", IR::ParserState::start);
auto parse_states = new Util::JsonArray();
parser->emplace("parse_states", parse_states);
parsers->append(parser);
map_parser.emplace(id, parser);
return id;
}
/// insert parser state into a parser identified by parser_id
/// return the id of the parser state
unsigned
JsonObjects::add_parser_state(const unsigned parser_id, const cstring& state_name) {
if (map_parser.find(parser_id) == map_parser.end())
BUG("parser %1% not found.", parser_id);
auto parser = map_parser[parser_id];
auto states = parser->get("parse_states")->to<Util::JsonArray>();
auto state = new Util::JsonObject();
unsigned state_id = BMV2::nextId("parse_states");
state->emplace("name", state_name);
state->emplace("id", state_id);
auto operations = new Util::JsonArray();
state->emplace("parser_ops", operations);
auto transitions = new Util::JsonArray();
state->emplace("transitions", transitions);
states->append(state);
auto key = new Util::JsonArray();
state->emplace("transition_key", key);
map_parser_state.emplace(state_id, state);
return state_id;
}
void
JsonObjects::add_parser_transition(const unsigned state_id, Util::IJson* transition) {
if (map_parser_state.find(state_id) == map_parser_state.end())
BUG("parser state %1% not found.", state_id);
auto state = map_parser_state[state_id];
auto transitions = state->get("transitions")->to<Util::JsonArray>();
CHECK_NULL(transitions);
auto trans = transition->to<Util::JsonObject>();
CHECK_NULL(trans);
transitions->append(trans);
}
void
JsonObjects::add_parser_op(const unsigned state_id, Util::IJson* op) {
if (map_parser_state.find(state_id) == map_parser_state.end())
BUG("parser state %1% not found.", state_id);
auto state = map_parser_state[state_id];
auto statements = state->get("parser_ops")->to<Util::JsonArray>();
CHECK_NULL(statements);
statements->append(op);
}
void
JsonObjects::add_parser_transition_key(const unsigned state_id, Util::IJson* newKey) {
if (map_parser_state.find(state_id) != map_parser_state.end()) {
auto state = map_parser_state[state_id];
auto keys = state->get("transition_key")->to<Util::JsonArray>();
CHECK_NULL(keys);
auto new_keys = newKey->to<Util::JsonArray>();
for (auto k : *new_keys) {
keys->append(k);
}
}
}
unsigned
JsonObjects::add_action(const cstring& name, Util::JsonArray*& params, Util::JsonArray*& body) {
CHECK_NULL(params);
CHECK_NULL(body);
auto action = new Util::JsonObject();
action->emplace("name", name);
unsigned id = BMV2::nextId("actions");
action->emplace("id", id);
action->emplace("runtime_data", params);
action->emplace("primitives", body);
actions->append(action);
return id;
}
void
JsonObjects::add_extern_attribute(const cstring& name, const cstring& type,
const cstring& value, Util::JsonArray* attributes) {
auto attr = new Util::JsonObject();
attr->emplace("name", name);
attr->emplace("type", type);
attr->emplace("value", value);
attributes->append(attr);
}
void
JsonObjects::add_extern(const cstring& name, const cstring& type,
Util::JsonArray*& attributes) {
auto extn = new Util::JsonObject();
unsigned id = BMV2::nextId("extern_instances");
extn->emplace("name", name);
extn->emplace("id", id);
extn->emplace("type", type);
extn->emplace("attribute_values", attributes);
externs->append(extn);
}
} // namespace BMV2
|
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lib/json.h"
#include "JsonObjects.h"
#include "helpers.h"
namespace BMV2 {
const int JSON_MAJOR_VERSION = 2;
const int JSON_MINOR_VERSION = 7;
JsonObjects::JsonObjects() {
toplevel = new Util::JsonObject();
meta = new Util::JsonObject();
header_types = insert_array_field(toplevel, "header_types");
headers = insert_array_field(toplevel, "headers");
header_stacks = insert_array_field(toplevel, "header_stacks");
field_lists = insert_array_field(toplevel, "field_lists");
errors = insert_array_field(toplevel, "errors");
enums = insert_array_field(toplevel, "enums");
parsers = insert_array_field(toplevel, "parsers");
deparsers = insert_array_field(toplevel, "deparsers");
meter_arrays = insert_array_field(toplevel, "meter_arrays");
counters = insert_array_field(toplevel, "counter_arrays");
register_arrays = insert_array_field(toplevel, "register_arrays");
calculations = insert_array_field(toplevel, "calculations");
learn_lists = insert_array_field(toplevel, "learn_lists");
actions = insert_array_field(toplevel, "actions");
pipelines = insert_array_field(toplevel, "pipelines");
checksums = insert_array_field(toplevel, "checksums");
force_arith = insert_array_field(toplevel, "force_arith");
externs = insert_array_field(toplevel, "extern_instances");
field_aliases = insert_array_field(toplevel, "field_aliases");
}
Util::JsonObject*
JsonObjects::find_object_by_name(Util::JsonArray* array, const cstring& name) {
for (auto e : *array) {
auto obj = e->to<Util::JsonObject>();
auto val = obj->get("name")->to<Util::JsonValue>();
if (val != nullptr && val->isString() && val->getString() == name) {
return obj;
}
}
return nullptr;
}
/// Insert a json array to a parent object under key 'name'.
Util::JsonArray*
JsonObjects::insert_array_field(Util::JsonObject* parent, cstring name) {
auto result = new Util::JsonArray();
parent->emplace(name, result);
return result;
}
/// Append a json array to a parent json array.
Util::JsonArray*
JsonObjects::append_array(Util::JsonArray* parent) {
auto result = new Util::JsonArray();
parent->append(result);
return result;
}
/// Insert a json array named 'parameters' in a parent json object.
Util::JsonArray*
JsonObjects::create_parameters(Util::JsonObject* object) {
return insert_array_field(object, "parameters");
}
/// Append a json object r to a parent json array,
/// insert a field 'op' with 'name' to parent.
Util::JsonObject*
JsonObjects::create_primitive(Util::JsonArray* parent, cstring name) {
auto result = new Util::JsonObject();
result->emplace("op", name);
parent->append(result);
return result;
}
void
JsonObjects::add_program_info(const cstring& name) {
toplevel->emplace("program", name);
}
void
JsonObjects::add_meta_info() {
static constexpr int version_major = JSON_MAJOR_VERSION;
static constexpr int version_minor = JSON_MINOR_VERSION;
auto version = insert_array_field(meta, "version");
version->append(version_major);
version->append(version_minor);
meta->emplace("compiler", "https://github.com/p4lang/p4c");
toplevel->emplace("__meta__", meta);
}
/**
* Create a header type in json.
* @param name header name
* @param type header type
* @param max_length maximum length for a header with varbit fields;
* if 0 header does not contain varbit fields
* @param fields a JsonArray for the fields in the header
*/
unsigned
JsonObjects::add_header_type(const cstring& name, Util::JsonArray*& fields, unsigned max_length) {
std::string sname(name, name.size());
auto header_type_id_it = header_type_id.find(sname);
if (header_type_id_it != header_type_id.end()) {
return header_type_id_it->second;
}
auto header_type = new Util::JsonObject();
unsigned id = BMV2::nextId("header_types");
header_type_id[sname] = id;
header_type->emplace("name", name);
header_type->emplace("id", id);
if (fields != nullptr) {
header_type->emplace("fields", fields);
} else {
auto temp = new Util::JsonArray();
header_type->emplace("fields", temp);
}
if (max_length > 0)
header_type->emplace("max_length", max_length);
header_types->append(header_type);
return id;
}
/// Create a header type with empty field list.
unsigned
JsonObjects::add_header_type(const cstring& name) {
std::string sname(name, name.size());
auto header_type_id_it = header_type_id.find(sname);
if (header_type_id_it != header_type_id.end()) {
return header_type_id_it->second;
}
auto header_type = new Util::JsonObject();
unsigned id = BMV2::nextId("header_types");
header_type_id[sname] = id;
header_type->emplace("name", name);
header_type->emplace("id", id);
auto temp = new Util::JsonArray();
header_type->emplace("fields", temp);
header_types->append(header_type);
return id;
}
/// Create a set of fields to an existing header type.
/// The header type is decribed by the name.
void
JsonObjects::add_header_field(const cstring& name, Util::JsonArray*& field) {
CHECK_NULL(field);
Util::JsonObject* headerType = find_object_by_name(header_types, name);
Util::JsonArray* fields = headerType->get("fields")->to<Util::JsonArray>();
BUG_CHECK(fields != nullptr, "header '%1%' not found", name);
fields->append(field);
}
/// Create a header instance in json.
unsigned
JsonObjects::add_header(const cstring& type, const cstring& name) {
auto header = new Util::JsonObject();
unsigned id = BMV2::nextId("headers");
LOG1("add header id " << id);
header->emplace("name", name);
header->emplace("id", id);
header->emplace("header_type", type);
header->emplace("metadata", false);
header->emplace("pi_omit", true);
headers->append(header);
return id;
}
unsigned
JsonObjects::add_metadata(const cstring& type, const cstring& name) {
auto header = new Util::JsonObject();
unsigned id = BMV2::nextId("headers");
LOG1("add metadata header id " << id);
header->emplace("name", name);
header->emplace("id", id);
header->emplace("header_type", type);
header->emplace("metadata", true);
header->emplace("pi_omit", true); // Don't expose in PI.
headers->append(header);
return id;
}
void
JsonObjects::add_header_stack(const cstring& type, const cstring& name,
const unsigned size, std::vector<unsigned>& ids) {
auto stack = new Util::JsonObject();
unsigned id = BMV2::nextId("stack");
stack->emplace("name", name);
stack->emplace("id", id);
stack->emplace("header_type", type);
stack->emplace("size", size);
auto members = new Util::JsonArray();
stack->emplace("header_ids", members);
for (auto id : ids) {
members->append(id);
}
header_stacks->append(stack);
}
/// Add an error to json.
void
JsonObjects::add_error(const cstring& name, const unsigned type) {
auto arr = append_array(errors);
arr->append(name);
arr->append(type);
}
/// Add a single enum entry to json.
/// A enum entry is identified with { enum_name, entry_name, entry_value }
void
JsonObjects::add_enum(const cstring& enum_name, const cstring& entry_name,
const unsigned entry_value) {
// look up enum in json by name
Util::JsonObject* enum_json = find_object_by_name(enums, enum_name);
if (enum_json == nullptr) { // first entry in a new enum
enum_json = new Util::JsonObject();
enum_json->emplace("name", enum_name);
auto entries = insert_array_field(enum_json, "entries");
auto entry = new Util::JsonArray();
entry->append(entry_name);
entry->append(entry_value);
entries->append(entry);
enums->append(enum_json);
LOG3("new enum object: " << enum_name << " " << entry_name << " " << entry_value);
} else { // add entry to existing enum
auto entries = enum_json->get("entries")->to<Util::JsonArray>();
auto entry = new Util::JsonArray();
entry->append(entry_name);
entry->append(entry_value);
entries->append(entry);
LOG3("new enum entry: " << enum_name << " " << entry_name << " " << entry_value);
}
}
unsigned
JsonObjects::add_parser(const cstring& name) {
auto parser = new Util::JsonObject();
unsigned id = BMV2::nextId("parser");
parser->emplace("name", name);
parser->emplace("id", id);
parser->emplace("init_state", IR::ParserState::start);
auto parse_states = new Util::JsonArray();
parser->emplace("parse_states", parse_states);
parsers->append(parser);
map_parser.emplace(id, parser);
return id;
}
/// insert parser state into a parser identified by parser_id
/// return the id of the parser state
unsigned
JsonObjects::add_parser_state(const unsigned parser_id, const cstring& state_name) {
if (map_parser.find(parser_id) == map_parser.end())
BUG("parser %1% not found.", parser_id);
auto parser = map_parser[parser_id];
auto states = parser->get("parse_states")->to<Util::JsonArray>();
auto state = new Util::JsonObject();
unsigned state_id = BMV2::nextId("parse_states");
state->emplace("name", state_name);
state->emplace("id", state_id);
auto operations = new Util::JsonArray();
state->emplace("parser_ops", operations);
auto transitions = new Util::JsonArray();
state->emplace("transitions", transitions);
states->append(state);
auto key = new Util::JsonArray();
state->emplace("transition_key", key);
map_parser_state.emplace(state_id, state);
return state_id;
}
void
JsonObjects::add_parser_transition(const unsigned state_id, Util::IJson* transition) {
if (map_parser_state.find(state_id) == map_parser_state.end())
BUG("parser state %1% not found.", state_id);
auto state = map_parser_state[state_id];
auto transitions = state->get("transitions")->to<Util::JsonArray>();
CHECK_NULL(transitions);
auto trans = transition->to<Util::JsonObject>();
CHECK_NULL(trans);
transitions->append(trans);
}
void
JsonObjects::add_parser_op(const unsigned state_id, Util::IJson* op) {
if (map_parser_state.find(state_id) == map_parser_state.end())
BUG("parser state %1% not found.", state_id);
auto state = map_parser_state[state_id];
auto statements = state->get("parser_ops")->to<Util::JsonArray>();
CHECK_NULL(statements);
statements->append(op);
}
void
JsonObjects::add_parser_transition_key(const unsigned state_id, Util::IJson* newKey) {
if (map_parser_state.find(state_id) != map_parser_state.end()) {
auto state = map_parser_state[state_id];
auto keys = state->get("transition_key")->to<Util::JsonArray>();
CHECK_NULL(keys);
auto new_keys = newKey->to<Util::JsonArray>();
for (auto k : *new_keys) {
keys->append(k);
}
}
}
unsigned
JsonObjects::add_action(const cstring& name, Util::JsonArray*& params, Util::JsonArray*& body) {
CHECK_NULL(params);
CHECK_NULL(body);
auto action = new Util::JsonObject();
action->emplace("name", name);
unsigned id = BMV2::nextId("actions");
action->emplace("id", id);
action->emplace("runtime_data", params);
action->emplace("primitives", body);
actions->append(action);
return id;
}
void
JsonObjects::add_extern_attribute(const cstring& name, const cstring& type,
const cstring& value, Util::JsonArray* attributes) {
auto attr = new Util::JsonObject();
attr->emplace("name", name);
attr->emplace("type", type);
attr->emplace("value", value);
attributes->append(attr);
}
void
JsonObjects::add_extern(const cstring& name, const cstring& type,
Util::JsonArray*& attributes) {
auto extn = new Util::JsonObject();
unsigned id = BMV2::nextId("extern_instances");
extn->emplace("name", name);
extn->emplace("id", id);
extn->emplace("type", type);
extn->emplace("attribute_values", attributes);
externs->append(extn);
}
} // namespace BMV2
|
Fix memory error when building bmv2 JSON
|
Fix memory error when building bmv2 JSON
Backend::convert was inserting json->meta into jsonTop, but that pointer
would later get overwritten in add_meta_info.
|
C++
|
apache-2.0
|
hanw/p4c,p4lang/p4c,p4lang/p4c,mbudiu-vmw/p4c-clone,mbudiu-vmw/p4c-clone,p4lang/p4c,mbudiu-vmw/p4c-clone,hanw/p4c,hanw/p4c,mbudiu-vmw/p4c-clone,p4lang/p4c,p4lang/p4c,hanw/p4c
|
d7c200a6101a0a9e0481a6c2d530ff0d9d7859b0
|
cintex/src/CINTEnumBuilder.cxx
|
cintex/src/CINTEnumBuilder.cxx
|
// @(#)root/cintex:$Name: v5-13-04b $:$Id: CINTEnumBuilder.cxx,v 1.10 2006/07/03 10:22:13 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTEnumBuilder.h"
#include "Api.h"
#include <sstream>
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
void CINTEnumBuilder::Setup(const Type& e) {
// Setup enum info.
if ( e.IsEnum() ) {
string name = CintName(e.Name(SCOPED));
int tagnum = ::G__defined_tagname(name.c_str(), 2);
if( -1 != tagnum ) return;
if ( Cintex::Debug() ) {
cout << "Cintex: Building enum " << name << endl;
}
Scope scope = e.DeclaringScope();
CINTScopeBuilder::Setup( scope );
bool isCPPMacroEnum = name == "$CPP_MACROS";
if (!isCPPMacroEnum) {
G__linked_taginfo taginfo;
taginfo.tagnum = -1;
taginfo.tagtype = 'e';
taginfo.tagname = name.c_str();
G__get_linked_tagnum(&taginfo);
tagnum = taginfo.tagnum;
::G__tagtable_setup( tagnum, sizeof(int), -1, 0,(char*)NULL, NULL, NULL);
}
//--- setup enum values -------
int isstatic;
if ( scope.IsTopScope() ) {
isstatic = -1;
/* Setting up global variables */
::G__resetplocal();
}
else {
string sname = CintName(scope.Name(SCOPED));
int stagnum = ::G__defined_tagname(sname.c_str(), 2);
isstatic = -2;
if( -1 == stagnum ) return;
::G__tag_memvar_setup(stagnum);
}
for ( size_t i = 0; i < e.DataMemberSize(); i++ ) {
stringstream s;
s << e.DataMemberAt(i).Name() << "=";
if ( isCPPMacroEnum ) s << (const char*)e.DataMemberAt(i).Offset();
else s << (int)e.DataMemberAt(i).Offset();
string item = s.str();
if ( Cintex::Debug() ) cout << "Cintex: item " << i << " " << item <<endl;
if ( isCPPMacroEnum )
::G__memvar_setup((void*)G__PVOID, 'p', 0, 0, -1, -1, -1, 1, item.c_str(), 1, (char*)NULL);
else
::G__memvar_setup((void*)G__PVOID, 'i', 0, 1, tagnum, -1, isstatic, 1, item.c_str(), 0, (char*)NULL);
}
if ( scope.IsTopScope() ) {
::G__resetglobalenv();
}
else {
::G__tag_memvar_reset();
}
}
}
}}
|
// @(#)root/cintex:$Name: $:$Id: CINTEnumBuilder.cxx,v 1.11 2006/12/08 09:36:06 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTEnumBuilder.h"
#include "Api.h"
#include <sstream>
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
void CINTEnumBuilder::Setup(const Type& e) {
// Setup enum info.
if ( e.IsEnum() ) {
string name = CintName(e.Name(SCOPED));
int tagnum = ::G__defined_tagname(name.c_str(), 2);
if( -1 != tagnum ) {
// This enum is already known to CINT.
// But did we just declare it via an EnumTypeBuilder?
// If so it won't have any members yet, so only return if
// the e's first member is already known to CINT:
if (e.DataMemberSize()) {
std::string strVarname(e.DataMemberAt(0).Name(SCOPED));
char* varname = new char[strVarname.length()];
strcpy(varname, strVarname.c_str());
int i = 0;
int varhash = 0;
long dummy_struct_offset = 0;
long dummy_store_struct_offset = 0;
G__hash(varname, varhash, i);
i = 0;
bool known = ((G__searchvariable(varname, varhash, 0, 0, &dummy_struct_offset,
&dummy_store_struct_offset, &i, 0)));
delete []varname;
if (known)
return;
} else
return;
}
if ( Cintex::Debug() ) {
cout << "Cintex: Building enum " << name << endl;
}
Scope scope = e.DeclaringScope();
CINTScopeBuilder::Setup( scope );
bool isCPPMacroEnum = name == "$CPP_MACROS";
if (!isCPPMacroEnum) {
G__linked_taginfo taginfo;
taginfo.tagnum = -1;
taginfo.tagtype = 'e';
taginfo.tagname = name.c_str();
G__get_linked_tagnum(&taginfo);
tagnum = taginfo.tagnum;
::G__tagtable_setup( tagnum, sizeof(int), -1, 0,(char*)NULL, NULL, NULL);
}
//--- setup enum values -------
int isstatic;
if ( scope.IsTopScope() ) {
isstatic = -1;
/* Setting up global variables */
::G__resetplocal();
}
else {
string sname = CintName(scope.Name(SCOPED));
int stagnum = ::G__defined_tagname(sname.c_str(), 2);
isstatic = -2;
if( -1 == stagnum ) return;
::G__tag_memvar_setup(stagnum);
}
for ( size_t i = 0; i < e.DataMemberSize(); i++ ) {
stringstream s;
s << e.DataMemberAt(i).Name() << "=";
if ( isCPPMacroEnum ) s << (const char*)e.DataMemberAt(i).Offset();
else s << (int)e.DataMemberAt(i).Offset();
string item = s.str();
if ( Cintex::Debug() ) cout << "Cintex: item " << i << " " << item <<endl;
if ( isCPPMacroEnum )
::G__memvar_setup((void*)G__PVOID, 'p', 0, 0, -1, -1, -1, 1, item.c_str(), 1, (char*)NULL);
else
::G__memvar_setup((void*)G__PVOID, 'i', 0, 1, tagnum, -1, isstatic, 1, item.c_str(), 0, (char*)NULL);
}
if ( scope.IsTopScope() ) {
::G__resetglobalenv();
}
else {
::G__tag_memvar_reset();
}
}
}
}}
|
Fix problem where an enum "forward" declared by EnumTypeBuilder wasn't updated by the EnumBuilder later, so its "members" were never set up.
|
Fix problem where an enum "forward" declared by EnumTypeBuilder wasn't updated by the EnumBuilder later, so its "members" were never set up.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@19473 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
satyarth934/root,mhuwiler/rootauto,satyarth934/root,zzxuanyuan/root,BerserkerTroll/root,vukasinmilosevic/root,gbitzes/root,sbinet/cxx-root,vukasinmilosevic/root,thomaskeck/root,mkret2/root,omazapa/root-old,olifre/root,georgtroska/root,0x0all/ROOT,evgeny-boger/root,omazapa/root,krafczyk/root,jrtomps/root,kirbyherm/root-r-tools,dfunke/root,mkret2/root,BerserkerTroll/root,arch1tect0r/root,mkret2/root,Duraznos/root,sawenzel/root,CristinaCristescu/root,root-mirror/root,simonpf/root,sirinath/root,nilqed/root,karies/root,ffurano/root5,0x0all/ROOT,gganis/root,dfunke/root,sbinet/cxx-root,lgiommi/root,Duraznos/root,georgtroska/root,abhinavmoudgil95/root,jrtomps/root,tc3t/qoot,tc3t/qoot,davidlt/root,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,esakellari/root,satyarth934/root,buuck/root,BerserkerTroll/root,buuck/root,georgtroska/root,esakellari/root,0x0all/ROOT,thomaskeck/root,bbockelm/root,evgeny-boger/root,Duraznos/root,beniz/root,karies/root,omazapa/root-old,mkret2/root,esakellari/root,smarinac/root,lgiommi/root,simonpf/root,mhuwiler/rootauto,vukasinmilosevic/root,perovic/root,abhinavmoudgil95/root,root-mirror/root,davidlt/root,mattkretz/root,davidlt/root,Y--/root,krafczyk/root,kirbyherm/root-r-tools,dfunke/root,sirinath/root,omazapa/root-old,sirinath/root,Dr15Jones/root,thomaskeck/root,gganis/root,CristinaCristescu/root,lgiommi/root,agarciamontoro/root,omazapa/root,perovic/root,jrtomps/root,gbitzes/root,kirbyherm/root-r-tools,georgtroska/root,veprbl/root,ffurano/root5,satyarth934/root,arch1tect0r/root,olifre/root,esakellari/root,satyarth934/root,tc3t/qoot,gbitzes/root,Duraznos/root,root-mirror/root,agarciamontoro/root,ffurano/root5,root-mirror/root,buuck/root,BerserkerTroll/root,agarciamontoro/root,evgeny-boger/root,abhinavmoudgil95/root,sbinet/cxx-root,georgtroska/root,0x0all/ROOT,gganis/root,gganis/root,ffurano/root5,abhinavmoudgil95/root,lgiommi/root,agarciamontoro/root,smarinac/root,satyarth934/root,Duraznos/root,strykejern/TTreeReader,cxx-hep/root-cern,tc3t/qoot,thomaskeck/root,sbinet/cxx-root,omazapa/root-old,omazapa/root,sirinath/root,olifre/root,abhinavmoudgil95/root,alexschlueter/cern-root,esakellari/my_root_for_test,dfunke/root,sirinath/root,root-mirror/root,mkret2/root,evgeny-boger/root,gbitzes/root,sirinath/root,Y--/root,CristinaCristescu/root,sbinet/cxx-root,nilqed/root,agarciamontoro/root,pspe/root,evgeny-boger/root,gganis/root,abhinavmoudgil95/root,agarciamontoro/root,thomaskeck/root,olifre/root,agarciamontoro/root,cxx-hep/root-cern,karies/root,omazapa/root-old,mhuwiler/rootauto,bbockelm/root,sawenzel/root,evgeny-boger/root,bbockelm/root,0x0all/ROOT,arch1tect0r/root,mhuwiler/rootauto,mattkretz/root,buuck/root,sbinet/cxx-root,0x0all/ROOT,davidlt/root,BerserkerTroll/root,jrtomps/root,smarinac/root,evgeny-boger/root,esakellari/root,tc3t/qoot,sirinath/root,georgtroska/root,beniz/root,mkret2/root,sawenzel/root,abhinavmoudgil95/root,CristinaCristescu/root,veprbl/root,mhuwiler/rootauto,0x0all/ROOT,smarinac/root,pspe/root,pspe/root,abhinavmoudgil95/root,esakellari/my_root_for_test,satyarth934/root,simonpf/root,nilqed/root,veprbl/root,ffurano/root5,mhuwiler/rootauto,davidlt/root,esakellari/my_root_for_test,root-mirror/root,esakellari/my_root_for_test,sbinet/cxx-root,cxx-hep/root-cern,lgiommi/root,Y--/root,perovic/root,gganis/root,Dr15Jones/root,mattkretz/root,strykejern/TTreeReader,veprbl/root,zzxuanyuan/root,Duraznos/root,karies/root,bbockelm/root,omazapa/root,georgtroska/root,krafczyk/root,thomaskeck/root,lgiommi/root,jrtomps/root,omazapa/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,mhuwiler/rootauto,mattkretz/root,gbitzes/root,zzxuanyuan/root,buuck/root,ffurano/root5,zzxuanyuan/root,evgeny-boger/root,gganis/root,krafczyk/root,zzxuanyuan/root,sirinath/root,buuck/root,karies/root,karies/root,davidlt/root,nilqed/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,gganis/root,mkret2/root,sawenzel/root,Duraznos/root,cxx-hep/root-cern,perovic/root,karies/root,arch1tect0r/root,veprbl/root,agarciamontoro/root,vukasinmilosevic/root,lgiommi/root,satyarth934/root,gbitzes/root,esakellari/my_root_for_test,alexschlueter/cern-root,omazapa/root,nilqed/root,veprbl/root,beniz/root,pspe/root,Duraznos/root,mkret2/root,bbockelm/root,esakellari/my_root_for_test,dfunke/root,mattkretz/root,agarciamontoro/root,Dr15Jones/root,krafczyk/root,dfunke/root,arch1tect0r/root,davidlt/root,krafczyk/root,jrtomps/root,root-mirror/root,gbitzes/root,kirbyherm/root-r-tools,pspe/root,buuck/root,esakellari/root,olifre/root,dfunke/root,dfunke/root,Dr15Jones/root,davidlt/root,vukasinmilosevic/root,alexschlueter/cern-root,simonpf/root,arch1tect0r/root,Y--/root,krafczyk/root,olifre/root,olifre/root,CristinaCristescu/root,beniz/root,bbockelm/root,kirbyherm/root-r-tools,vukasinmilosevic/root,vukasinmilosevic/root,zzxuanyuan/root,Duraznos/root,mkret2/root,karies/root,BerserkerTroll/root,beniz/root,perovic/root,BerserkerTroll/root,zzxuanyuan/root-compressor-dummy,karies/root,karies/root,Duraznos/root,abhinavmoudgil95/root,0x0all/ROOT,0x0all/ROOT,cxx-hep/root-cern,sbinet/cxx-root,gganis/root,smarinac/root,veprbl/root,agarciamontoro/root,beniz/root,sawenzel/root,sirinath/root,simonpf/root,sawenzel/root,mattkretz/root,omazapa/root-old,omazapa/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,esakellari/root,satyarth934/root,lgiommi/root,gganis/root,evgeny-boger/root,nilqed/root,esakellari/my_root_for_test,Y--/root,simonpf/root,abhinavmoudgil95/root,thomaskeck/root,alexschlueter/cern-root,vukasinmilosevic/root,satyarth934/root,bbockelm/root,krafczyk/root,krafczyk/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,vukasinmilosevic/root,cxx-hep/root-cern,zzxuanyuan/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,esakellari/my_root_for_test,kirbyherm/root-r-tools,omazapa/root-old,dfunke/root,olifre/root,Y--/root,bbockelm/root,nilqed/root,cxx-hep/root-cern,root-mirror/root,sawenzel/root,perovic/root,vukasinmilosevic/root,jrtomps/root,thomaskeck/root,omazapa/root-old,zzxuanyuan/root,tc3t/qoot,alexschlueter/cern-root,cxx-hep/root-cern,smarinac/root,tc3t/qoot,mhuwiler/rootauto,sawenzel/root,pspe/root,evgeny-boger/root,arch1tect0r/root,veprbl/root,dfunke/root,karies/root,georgtroska/root,esakellari/root,lgiommi/root,ffurano/root5,mhuwiler/rootauto,CristinaCristescu/root,nilqed/root,simonpf/root,bbockelm/root,gbitzes/root,mkret2/root,sirinath/root,nilqed/root,mkret2/root,zzxuanyuan/root-compressor-dummy,pspe/root,strykejern/TTreeReader,arch1tect0r/root,pspe/root,simonpf/root,olifre/root,Y--/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,nilqed/root,abhinavmoudgil95/root,gganis/root,strykejern/TTreeReader,perovic/root,omazapa/root,Dr15Jones/root,nilqed/root,zzxuanyuan/root,smarinac/root,beniz/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,lgiommi/root,arch1tect0r/root,tc3t/qoot,gbitzes/root,root-mirror/root,zzxuanyuan/root,root-mirror/root,alexschlueter/cern-root,kirbyherm/root-r-tools,arch1tect0r/root,omazapa/root-old,Dr15Jones/root,Y--/root,mattkretz/root,agarciamontoro/root,smarinac/root,beniz/root,sawenzel/root,smarinac/root,perovic/root,buuck/root,pspe/root,perovic/root,omazapa/root,sirinath/root,arch1tect0r/root,mattkretz/root,simonpf/root,mhuwiler/rootauto,pspe/root,veprbl/root,CristinaCristescu/root,simonpf/root,CristinaCristescu/root,omazapa/root,tc3t/qoot,mattkretz/root,strykejern/TTreeReader,mattkretz/root,omazapa/root,BerserkerTroll/root,thomaskeck/root,Y--/root,davidlt/root,olifre/root,Y--/root,tc3t/qoot,strykejern/TTreeReader,dfunke/root,beniz/root,veprbl/root,davidlt/root,veprbl/root,sbinet/cxx-root,perovic/root,pspe/root,perovic/root,zzxuanyuan/root,jrtomps/root,esakellari/root,beniz/root,zzxuanyuan/root-compressor-dummy,beniz/root,esakellari/root,BerserkerTroll/root,alexschlueter/cern-root,sawenzel/root,buuck/root,BerserkerTroll/root,sbinet/cxx-root,buuck/root,satyarth934/root,strykejern/TTreeReader,CristinaCristescu/root,krafczyk/root,simonpf/root,thomaskeck/root,BerserkerTroll/root,jrtomps/root,gbitzes/root,mattkretz/root,jrtomps/root,zzxuanyuan/root,root-mirror/root,smarinac/root,esakellari/root,CristinaCristescu/root,sawenzel/root,omazapa/root-old,esakellari/my_root_for_test,esakellari/my_root_for_test,georgtroska/root,Y--/root,bbockelm/root,lgiommi/root,CristinaCristescu/root,omazapa/root-old,krafczyk/root,buuck/root,mhuwiler/rootauto,davidlt/root,olifre/root
|
2d733a47cec00f38acc69d26476fe6f6a9929811
|
SofaKernel/framework/framework_test/helper/system/PluginManager_test.cpp
|
SofaKernel/framework/framework_test/helper/system/PluginManager_test.cpp
|
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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 2.1 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, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>
#include <gtest/gtest.h>
#include <SofaTest/TestMessageHandler.h>
#include <fstream>
using sofa::helper::system::PluginManager;
using sofa::helper::system::FileSystem;
static std::string pluginName = "TestPlugin" ;
#ifdef NDEBUG
static std::string pluginFileName = "TestPlugin" ;
#else
static std::string pluginFileName = "TestPlugin_d" ;
#endif //N_DEBUG
static std::string nonpluginName = "RandomNameForAPluginButHopeItDoesNotExist";
const std::string dotExt = "." + sofa::helper::system::DynamicLibrary::extension;
#ifdef WIN32
const std::string separator = "\\";
const std::string prefix = "";
#else
const std::string separator = "/";
const std::string prefix = "lib";
#endif // WIN32
struct PluginManager_test: public ::testing::Test
{
std::string pluginDir;
void SetUp()
{
// Add the plugin directory to PluginRepository
#ifdef WIN32
pluginDir = sofa::helper::Utils::getExecutableDirectory();
#else
pluginDir = sofa::helper::Utils::getSofaPathPrefix() + "/lib";
#endif
sofa::helper::system::PluginRepository.addFirstPath(pluginDir);
}
void TearDown()
{
PluginManager&pm = PluginManager::getInstance();
//empty loaded plugin(s)
for (PluginManager::PluginMap::iterator it = pm.getPluginMap().begin(); it != pm.getPluginMap().end(); it++)
ASSERT_TRUE(pm.unloadPlugin((*it).first));
ASSERT_EQ(pm.getPluginMap().size(), 0u);
}
};
TEST_F(PluginManager_test, loadTestPluginByPath)
{
PluginManager&pm = PluginManager::getInstance();
std::string pluginPath = pluginDir + separator + prefix + pluginFileName + dotExt;
std::string nonpluginPath = pluginDir + separator + prefix + nonpluginName + dotExt;
ASSERT_TRUE(pm.loadPluginByPath(pluginPath));
ASSERT_FALSE(pm.loadPluginByPath(nonpluginPath));
ASSERT_GT(pm.findPlugin(pluginName).size(), 0u);
ASSERT_EQ(pm.findPlugin(nonpluginName).size(), 0u);
}
TEST_F(PluginManager_test, loadTestPluginByName )
{
PluginManager&pm = PluginManager::getInstance();
ASSERT_TRUE(pm.loadPluginByName(pluginName) );
ASSERT_FALSE(pm.loadPluginByName(nonpluginName));
std::string pluginPath = pm.findPlugin(pluginName);
ASSERT_GT(pluginPath.size(), 0u);
ASSERT_EQ(pm.findPlugin(nonpluginName).size(), 0u);
}
TEST_F(PluginManager_test, pluginEntries)
{
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
sofa::helper::system::Plugin& p = pm.getPluginMap()[pluginPath];
EXPECT_TRUE(p.initExternalModule.func != NULL);
EXPECT_TRUE(p.getModuleName.func != NULL);
EXPECT_TRUE(p.getModuleVersion.func != NULL);
EXPECT_TRUE(p.getModuleLicense.func != NULL);
EXPECT_TRUE(p.getModuleDescription.func != NULL);
EXPECT_TRUE(p.getModuleComponentList.func != NULL);
}
TEST_F(PluginManager_test, pluginEntriesValues)
{
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
sofa::helper::system::Plugin& p = pm.getPluginMap()[pluginPath];
std::string testModuleName = "TestPlugin";
std::string testModuleVersion = "0.7";
std::string testModuleLicence = "LicenceTest";
std::string testModuleDescription = "Description of the Test Plugin";
std::string testModuleComponentList = "ComponentA, ComponentB";
ASSERT_EQ(0, std::string(p.getModuleName()).compare(testModuleName));
ASSERT_NE(0, std::string(p.getModuleName()).compare(testModuleName + "azerty"));
ASSERT_EQ(0, std::string(p.getModuleVersion()).compare(testModuleVersion));
ASSERT_NE(0, std::string(p.getModuleVersion()).compare(testModuleVersion + "77777"));
ASSERT_EQ(0, std::string(p.getModuleLicense()).compare(testModuleLicence));
ASSERT_NE(0, std::string(p.getModuleLicense()).compare(testModuleLicence + "GPLBSDProprio"));
ASSERT_EQ(0, std::string(p.getModuleDescription()).compare(testModuleDescription));
ASSERT_NE(0, std::string(p.getModuleDescription()).compare(testModuleDescription + "blablablabalbal"));
ASSERT_EQ(0, std::string(p.getModuleComponentList()).compare(testModuleComponentList));
ASSERT_NE(0, std::string(p.getModuleComponentList()).compare(testModuleComponentList + "ComponentZ"));
}
TEST_F(PluginManager_test, testIniFile)
{
EXPECT_MSG_NOEMIT(Deprecated);
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
const std::string pathIniFile = "PluginManager_test.ini";
pm.writeToIniFile(pathIniFile);
//writeToIniFile does not return anything to say if the file was created without error...
ASSERT_TRUE(FileSystem::exists(pathIniFile));
ASSERT_TRUE(pm.unloadPlugin(pluginPath));
ASSERT_EQ(pm.getPluginMap().size(), 0u);
ASSERT_TRUE(FileSystem::exists(pathIniFile));
pm.readFromIniFile(pathIniFile);
ASSERT_EQ(pm.findPlugin(pluginName).compare(pluginPath), 0);
}
TEST_F(PluginManager_test, testDeprecatedIniFileWoVersion)
{
EXPECT_MSG_EMIT(Deprecated);
PluginManager&pm = PluginManager::getInstance();
ASSERT_EQ(pm.getPluginMap().size(), 0u);
const std::string pathIniFile = "PluginManager_test_deprecated_wo_version.ini";
std::ofstream outstream(pathIniFile.c_str());
outstream << pluginName << std::endl;
outstream.close();
ASSERT_TRUE(FileSystem::exists(pathIniFile));
pm.readFromIniFile(pathIniFile);
}
|
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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 2.1 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, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>
#include <gtest/gtest.h>
#include <SofaTest/TestMessageHandler.h>
#include <fstream>
using sofa::helper::system::PluginManager;
using sofa::helper::system::FileSystem;
static std::string pluginName = "TestPlugin" ;
#ifdef NDEBUG
static std::string pluginFileName = "TestPlugin" ;
#else
static std::string pluginFileName = "TestPlugin_d" ;
#endif //N_DEBUG
static std::string nonpluginName = "RandomNameForAPluginButHopeItDoesNotExist";
const std::string dotExt = "." + sofa::helper::system::DynamicLibrary::extension;
#ifdef WIN32
const std::string separator = "\\";
const std::string prefix = "";
#else
const std::string separator = "/";
const std::string prefix = "lib";
#endif // WIN32
struct PluginManager_test: public ::testing::Test
{
std::string pluginDir;
void SetUp()
{
// Add the plugin directory to PluginRepository
#ifdef WIN32
pluginDir = sofa::helper::Utils::getExecutableDirectory();
#else
pluginDir = sofa::helper::Utils::getSofaPathPrefix() + "/lib";
#endif
sofa::helper::system::PluginRepository.addFirstPath(pluginDir);
}
void TearDown()
{
PluginManager&pm = PluginManager::getInstance();
//empty loaded plugin(s)
std::vector<std::string> toDelete;
for (PluginManager::PluginMap::const_iterator it = pm.getPluginMap().begin(); it != pm.getPluginMap().end(); it++)
{
toDelete.push_back((*it).first);
//std::cout << pm.getPluginMap().size() << std::endl;
//std::cout << "Try to unload Plugin :" << (*it).first << std::endl;
//ASSERT_TRUE(pm.unloadPlugin((*it).first));
}
for(std::string p : toDelete)
ASSERT_TRUE(pm.unloadPlugin(p));
ASSERT_EQ(pm.getPluginMap().size(), 0u);
}
};
TEST_F(PluginManager_test, loadTestPluginByPath)
{
PluginManager&pm = PluginManager::getInstance();
std::string pluginPath = pluginDir + separator + prefix + pluginFileName + dotExt;
std::string nonpluginPath = pluginDir + separator + prefix + nonpluginName + dotExt;
std::cout << pm.getPluginMap().size() << std::endl;
ASSERT_TRUE(pm.loadPluginByPath(pluginPath));
std::cout << pm.getPluginMap().size() << std::endl;
ASSERT_FALSE(pm.loadPluginByPath(nonpluginPath));
std::cout << pm.getPluginMap().size() << std::endl;
ASSERT_GT(pm.findPlugin(pluginName).size(), 0u);
ASSERT_EQ(pm.findPlugin(nonpluginName).size(), 0u);
}
TEST_F(PluginManager_test, loadTestPluginByName )
{
PluginManager&pm = PluginManager::getInstance();
ASSERT_TRUE(pm.loadPluginByName(pluginName) );
ASSERT_FALSE(pm.loadPluginByName(nonpluginName));
std::string pluginPath = pm.findPlugin(pluginName);
ASSERT_GT(pluginPath.size(), 0u);
ASSERT_EQ(pm.findPlugin(nonpluginName).size(), 0u);
}
TEST_F(PluginManager_test, pluginEntries)
{
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
sofa::helper::system::Plugin& p = pm.getPluginMap()[pluginPath];
EXPECT_TRUE(p.initExternalModule.func != NULL);
EXPECT_TRUE(p.getModuleName.func != NULL);
EXPECT_TRUE(p.getModuleVersion.func != NULL);
EXPECT_TRUE(p.getModuleLicense.func != NULL);
EXPECT_TRUE(p.getModuleDescription.func != NULL);
EXPECT_TRUE(p.getModuleComponentList.func != NULL);
}
TEST_F(PluginManager_test, pluginEntriesValues)
{
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
sofa::helper::system::Plugin& p = pm.getPluginMap()[pluginPath];
std::string testModuleName = "TestPlugin";
std::string testModuleVersion = "0.7";
std::string testModuleLicence = "LicenceTest";
std::string testModuleDescription = "Description of the Test Plugin";
std::string testModuleComponentList = "ComponentA, ComponentB";
ASSERT_EQ(0, std::string(p.getModuleName()).compare(testModuleName));
ASSERT_NE(0, std::string(p.getModuleName()).compare(testModuleName + "azerty"));
ASSERT_EQ(0, std::string(p.getModuleVersion()).compare(testModuleVersion));
ASSERT_NE(0, std::string(p.getModuleVersion()).compare(testModuleVersion + "77777"));
ASSERT_EQ(0, std::string(p.getModuleLicense()).compare(testModuleLicence));
ASSERT_NE(0, std::string(p.getModuleLicense()).compare(testModuleLicence + "GPLBSDProprio"));
ASSERT_EQ(0, std::string(p.getModuleDescription()).compare(testModuleDescription));
ASSERT_NE(0, std::string(p.getModuleDescription()).compare(testModuleDescription + "blablablabalbal"));
ASSERT_EQ(0, std::string(p.getModuleComponentList()).compare(testModuleComponentList));
ASSERT_NE(0, std::string(p.getModuleComponentList()).compare(testModuleComponentList + "ComponentZ"));
}
TEST_F(PluginManager_test, testIniFile)
{
EXPECT_MSG_NOEMIT(Deprecated);
PluginManager&pm = PluginManager::getInstance();
pm.loadPluginByName(pluginName);
const std::string pluginPath = pm.findPlugin(pluginName);
const std::string pathIniFile = "PluginManager_test.ini";
pm.writeToIniFile(pathIniFile);
//writeToIniFile does not return anything to say if the file was created without error...
ASSERT_TRUE(FileSystem::exists(pathIniFile));
ASSERT_TRUE(pm.unloadPlugin(pluginPath));
ASSERT_EQ(pm.getPluginMap().size(), 0u);
ASSERT_TRUE(FileSystem::exists(pathIniFile));
pm.readFromIniFile(pathIniFile);
ASSERT_EQ(pm.findPlugin(pluginName).compare(pluginPath), 0);
}
TEST_F(PluginManager_test, testDeprecatedIniFileWoVersion)
{
EXPECT_MSG_EMIT(Deprecated);
PluginManager&pm = PluginManager::getInstance();
ASSERT_EQ(pm.getPluginMap().size(), 0u);
const std::string pathIniFile = "PluginManager_test_deprecated_wo_version.ini";
std::ofstream outstream(pathIniFile.c_str());
outstream << pluginName << std::endl;
outstream.close();
ASSERT_TRUE(FileSystem::exists(pathIniFile));
pm.readFromIniFile(pathIniFile);
}
|
fix test
|
[SofaFramework_test] fix test
|
C++
|
lgpl-2.1
|
FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa
|
2d2138cae09a040e086380bee41542f6b1da3c73
|
qterm/qterm.cpp
|
qterm/qterm.cpp
|
#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#define WIDTH 80
#define HEIGHT 17
#define BLINK_SPEED 1000
QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
term_create( &terminal );
term_begin( terminal, WIDTH, HEIGHT, 0 );
init();
}
QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
this->terminal = terminal;
init();
}
void QTerm::init()
{
char_width = 0;
char_height = 0;
cursor_x = -1;
cursor_y = -1;
cursor_on = 1;
term_set_user_data( terminal, this );
term_register_update( terminal, term_update );
term_register_cursor( terminal, term_update_cursor );
term_register_bell( terminal, term_bell );
notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
cursor_timer = new QTimer( this );
QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));
#ifdef __QNX__
BlackBerry::Keyboard::instance().show();
#endif
cursor_timer->start(BLINK_SPEED);
}
QTerm::~QTerm()
{
delete notifier;
delete exit_notifier;
term_free( terminal );
}
void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
int f = open("/pps/services/multimedia/sound/control", O_RDWR);
write(f, command, sizeof(command));
::close(f);
#else
QApplication::beep();
#endif
}
void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
term->update( x * term->char_width, y * term->char_height,
width * term->char_width, height * term->char_height + term->char_descent );
}
void QTerm::term_update_cursor(term_t handle, int x, int y)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
// Update old cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
term->cursor_x = x;
term->cursor_y = y;
// Update new cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
}
void QTerm::terminal_data()
{
if( !term_process_child( terminal ) ) {
exit(0);
}
}
void QTerm::terminate()
{
exit(0);
}
void QTerm::blink_cursor()
{
cursor_on ^= 1;
update( cursor_x * char_width,
cursor_y * char_height,
char_width, char_height );
}
void QTerm::paintEvent(QPaintEvent *event)
{
int i, j, color;
int new_width;
int new_height;
const uint32_t **grid;
const uint32_t **attribs;
const uint32_t **colors;
QPainter painter(this);
QFont font;
font.setStyleHint(QFont::TypeWriter);
font.setFamily("Monospace");
font.setFixedPitch(true);
font.setKerning(false);
painter.setBackgroundMode(Qt::TransparentMode);
painter.setBrush(QColor(8, 0, 0));
painter.setFont(font);
// First erase the grid with its current dimensions
painter.drawRect(event->rect());
new_width = painter.fontMetrics().maxWidth();
// Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
// when width of different characters returns the correct value
if( new_width == 0 ) {
new_width = painter.fontMetrics().width(QChar('X'));
}
new_height = painter.fontMetrics().lineSpacing();
if( char_width != new_width
|| char_height != new_height ) {
char_width = new_width;
char_height = new_height;
char_descent = painter.fontMetrics().descent();
term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 );
update( contentsRect() );
return;
}
painter.setPen(QColor(255, 255, 255));
painter.setBrush(QColor(255, 255, 255));
grid = term_get_grid( terminal );
attribs = term_get_attribs( terminal );
colors = term_get_colours( terminal );
for( i = 0; i < term_get_height( terminal ); i ++ ) {
for( j = 0; j < term_get_width( terminal ); j ++ ) {
if( cursor_on && j == cursor_x && i == cursor_y ) {
painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
painter.setPen(QColor(0, 0, 0));
painter.drawText(j * char_width, (i + 1) * char_height, QString( QChar( grid[ i ][ j ] ) ) );
painter.setPen(QColor(255, 255, 255));
} else {
color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
painter.drawText(j * char_width, (i + 1) * char_height, QString( QChar( grid[ i ][ j ] ) ) );
}
}
}
}
void QTerm::keyPressEvent(QKeyEvent *event)
{
switch(event->key()) {
case Qt::Key_Return:
term_send_data( terminal, "\n", 1 );
break;
case Qt::Key_Backspace:
term_send_data( terminal, "\b", 1 );
break;
case Qt::Key_CapsLock:
case Qt::Key_Shift:
break;
default:
term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
break;
}
}
void QTerm::resizeEvent(QResizeEvent *event)
{
if( char_width != 0 && char_height != 0 ) {
term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
}
}
int main(int argc, char *argv[])
{
term_t terminal;
if( !term_create( &terminal ) ) {
fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
exit(1);
}
if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
exit(1);
}
{
QCoreApplication::addLibraryPath("app/native/lib");
QApplication app(argc, argv);
QTerm term(NULL, terminal);
term.show();
return app.exec();
}
}
|
#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#define WIDTH 80
#define HEIGHT 17
#define BLINK_SPEED 1000
QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
term_create( &terminal );
term_begin( terminal, WIDTH, HEIGHT, 0 );
init();
}
QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
this->terminal = terminal;
init();
}
void QTerm::init()
{
char_width = 0;
char_height = 0;
cursor_x = -1;
cursor_y = -1;
cursor_on = 1;
term_set_user_data( terminal, this );
term_register_update( terminal, term_update );
term_register_cursor( terminal, term_update_cursor );
term_register_bell( terminal, term_bell );
notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
cursor_timer = new QTimer( this );
QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));
#ifdef __QNX__
BlackBerry::Keyboard::instance().show();
#endif
cursor_timer->start(BLINK_SPEED);
}
QTerm::~QTerm()
{
delete notifier;
delete exit_notifier;
term_free( terminal );
}
void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
int f = open("/pps/services/multimedia/sound/control", O_RDWR);
write(f, command, sizeof(command));
::close(f);
#else
QApplication::beep();
#endif
}
void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
term->update( x * term->char_width, y * term->char_height,
width * term->char_width, height * term->char_height + term->char_descent );
}
void QTerm::term_update_cursor(term_t handle, int x, int y)
{
QTerm *term = (QTerm *)term_get_user_data( handle );
// Update old cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
term->cursor_x = x;
term->cursor_y = y;
// Update new cursor location
term->update( term->cursor_x * term->char_width,
term->cursor_y * term->char_height,
term->char_width, term->char_height );
}
void QTerm::terminal_data()
{
if( !term_process_child( terminal ) ) {
exit(0);
}
}
void QTerm::terminate()
{
exit(0);
}
void QTerm::blink_cursor()
{
cursor_on ^= 1;
update( cursor_x * char_width,
cursor_y * char_height,
char_width, char_height );
}
void QTerm::paintEvent(QPaintEvent *event)
{
int i, j, color;
int new_width;
int new_height;
const uint32_t **grid;
const uint32_t **attribs;
const uint32_t **colors;
QPainter painter(this);
QFont font;
font.setStyleHint(QFont::TypeWriter);
font.setFamily("Monospace");
font.setFixedPitch(true);
font.setKerning(false);
painter.setBackgroundMode(Qt::TransparentMode);
painter.setBrush(QColor(8, 0, 0));
painter.setFont(font);
// First erase the grid with its current dimensions
painter.drawRect(event->rect());
new_width = painter.fontMetrics().maxWidth();
// Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
// when width of different characters returns the correct value
if( new_width == 0 ) {
new_width = painter.fontMetrics().width(QChar('X'));
}
new_height = painter.fontMetrics().lineSpacing();
if( char_width != new_width
|| char_height != new_height ) {
char_width = new_width;
char_height = new_height;
char_descent = painter.fontMetrics().descent();
term_resize( terminal, contentsRect().width() / char_width, contentsRect().height() / char_height, 0 );
update( contentsRect() );
return;
}
painter.setPen(QColor(255, 255, 255));
painter.setBrush(QColor(255, 255, 255));
grid = term_get_grid( terminal );
attribs = term_get_attribs( terminal );
colors = term_get_colours( terminal );
for( i = 0; i < term_get_height( terminal ); i ++ ) {
for( j = 0; j < term_get_width( terminal ); j ++ ) {
if( cursor_on && j == cursor_x && i == cursor_y ) {
painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
painter.setPen(QColor(0, 0, 0));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
painter.setPen(QColor(255, 255, 255));
} else {
color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
}
}
}
}
void QTerm::keyPressEvent(QKeyEvent *event)
{
switch(event->key()) {
case Qt::Key_Return:
term_send_data( terminal, "\n", 1 );
break;
case Qt::Key_Backspace:
term_send_data( terminal, "\b", 1 );
break;
case Qt::Key_CapsLock:
case Qt::Key_Shift:
break;
default:
term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
break;
}
}
void QTerm::resizeEvent(QResizeEvent *event)
{
if( char_width != 0 && char_height != 0 ) {
term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
}
}
int main(int argc, char *argv[])
{
term_t terminal;
if( !term_create( &terminal ) ) {
fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
exit(1);
}
if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
exit(1);
}
{
QCoreApplication::addLibraryPath("app/native/lib");
QApplication app(argc, argv);
QTerm term(NULL, terminal);
term.show();
return app.exec();
}
}
|
Fix characters in the bottom row getting cut off
|
Fix characters in the bottom row getting cut off
|
C++
|
apache-2.0
|
absmall/libterm,absmall/libterm
|
a50ebfcc2788a5a3e5fa0e1859777b2f727f37c7
|
android/jni/BvsA.cpp
|
android/jni/BvsA.cpp
|
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <bvs/bvs.h>
#include "BvsA.h"
#include <opencv2/core/core.hpp>
static JavaVM *gJavaVM;
static jobject gInterfaceObject;
BVS::BVS* bvs;
jobject javaObj;
void shutdownFunction()
{
LOG(1,"daemon exit caused by bvs shutdown request!");
//bvs->quit();
alarm(1); // SIGALRM after 1 second so all framework/module threads have a chance to quit
}
cv::Mat* getNativeAddress()
{
return javaMat;
}
void drawToAndroid()
{
/*
if(!javaMat)
{
LOG(0,"ExampleCV no javaMat ADDR");
javaMat=getNativeAddress();
}
*javaMat=img;
*/
// LOG(0,"JNI drawToAndroid");
int status;
JNIEnv *env;
bool isAttached =false;
status = gJavaVM->GetEnv((void **) &env, JNI_VERSION_1_6);
// LOG(0,"STATUS: " << status);
if(status < 0)
{
// LOG(1, "callback_handler: failed to get JNI environment, assuming native thread");
status = gJavaVM->AttachCurrentThread(&env, NULL);
if(status <0)
{
// LOG(1, "callback_handler: failed to attach current thread");
return;
}
}
jclass javaClass = env-> GetObjectClass(javaObj);
if (javaClass == 0)
{
LOG(0,"FindClass error");
return;
}
//LOG(0,"Setting methodID");
//Method takes a cv::Mat and returns nothing, void
//jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "(Lorg/opencv/core/Mat;)V");
//jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "([Ljava/lang/Integer;)V");
jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "()V");
if (javaMethodID == 0)
{
LOG(0,"GetMethodID error");
return;
}
// LOG(0,"methodID set");
isAttached=true;
env->CallVoidMethod(javaObj, javaMethodID);
if(isAttached)
{
gJavaVM->DetachCurrentThread();
}
}
extern "C"
{
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
gJavaVM=vm;
JNIEnv *env;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK)
return -1;
LOG(0,"JNI INIT");
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL Java_com_cvhci_bvsa_MainActivity_bvsAndroid(JNIEnv *env, jobject obj, jstring configFilePath, jlong addrMat)
{
LOGD("Java_com_cvhci_bvsa_MainActivity_bvsAndroid enter");
javaMat = (cv::Mat*)addrMat;
LOG(1,"JNI bvsAndroid Mat Adress " << javaMat);
javaObj = env->NewGlobalRef(obj);
const char* configStrChars = env->GetStringUTFChars(configFilePath, (jboolean *)0);
LOGD(configStrChars);
// char* bvsconfig[] ={"v",const_cast<char*>(configStrChars)};
const char* bvsconfig[] ={"v",configStrChars};
bvs = new BVS::BVS(2,bvsconfig);
bvs->loadModules();
LOGD("connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
bvs->run();
}
}
|
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <bvs/bvs.h>
#include "BvsA.h"
#include <opencv2/core/core.hpp>
static JavaVM *gJavaVM;
BVS::BVS* bvs;
jobject javaObj;
void shutdownFunction()
{
LOG(1,"daemon exit caused by bvs shutdown request!");
//bvs->quit();
alarm(1); // SIGALRM after 1 second so all framework/module threads have a chance to quit
}
cv::Mat* getNativeAddress()
{
return javaMat;
}
void drawToAndroid()
{
/*
if(!javaMat)
{
LOG(0,"ExampleCV no javaMat ADDR");
javaMat=getNativeAddress();
}
*javaMat=img;
*/
// LOG(0,"JNI drawToAndroid");
int status;
JNIEnv *env;
bool isAttached =false;
status = gJavaVM->GetEnv((void **) &env, JNI_VERSION_1_6);
// LOG(0,"STATUS: " << status);
if(status < 0)
{
// LOG(1, "callback_handler: failed to get JNI environment, assuming native thread");
status = gJavaVM->AttachCurrentThread(&env, NULL);
if(status <0)
{
// LOG(1, "callback_handler: failed to attach current thread");
return;
}
}
jclass javaClass = env-> GetObjectClass(javaObj);
if (javaClass == 0)
{
LOG(0,"FindClass error");
return;
}
//LOG(0,"Setting methodID");
//Method takes a cv::Mat and returns nothing, void
//jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "(Lorg/opencv/core/Mat;)V");
//jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "([Ljava/lang/Integer;)V");
jmethodID javaMethodID= env->GetMethodID(javaClass, "drawToDisplay", "()V");
if (javaMethodID == 0)
{
LOG(0,"GetMethodID error");
return;
}
// LOG(0,"methodID set");
isAttached=true;
env->CallVoidMethod(javaObj, javaMethodID);
if(isAttached)
{
gJavaVM->DetachCurrentThread();
}
}
extern "C"
{
jint JNI_OnLoad(JavaVM* vm, void*)
{
gJavaVM=vm;
JNIEnv *env;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK)
return -1;
LOG(0,"JNI INIT");
return JNI_VERSION_1_6;
}
JNIEXPORT void JNICALL Java_com_cvhci_bvsa_MainActivity_bvsAndroid(JNIEnv *env, jobject obj, jstring configFilePath, jlong addrMat)
{
LOGD("Java_com_cvhci_bvsa_MainActivity_bvsAndroid enter");
javaMat = (cv::Mat*)addrMat;
LOG(1,"JNI bvsAndroid Mat Adress " << javaMat);
javaObj = env->NewGlobalRef(obj);
const char* configStrChars = env->GetStringUTFChars(configFilePath, (jboolean *)0);
LOGD(configStrChars);
// char* bvsconfig[] ={"v",const_cast<char*>(configStrChars)};
const char* bvsconfig[] ={"v",configStrChars};
bvs = new BVS::BVS(2,bvsconfig);
bvs->loadModules();
LOGD("connecting modules!");
bvs->connectAllModules();
LOG(2, "starting!");
bvs->start();
bvs->run();
}
}
|
fix compiler warnings
|
BvsA: fix compiler warnings
|
C++
|
mit
|
nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs
|
7814846d2dbc9bdc87155c9376b5f7c3d1baa90d
|
lib/Support/BinaryStreamReader.cpp
|
lib/Support/BinaryStreamReader.cpp
|
//===- BinaryStreamReader.cpp - Reads objects from a binary stream --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/BinaryStreamError.h"
#include "llvm/Support/BinaryStreamRef.h"
using namespace llvm;
using endianness = llvm::support::endianness;
BinaryStreamReader::BinaryStreamReader(BinaryStreamRef Ref) : Stream(Ref) {}
BinaryStreamReader::BinaryStreamReader(BinaryStream &Stream) : Stream(Stream) {}
BinaryStreamReader::BinaryStreamReader(ArrayRef<uint8_t> Data,
endianness Endian)
: Stream(Data, Endian) {}
BinaryStreamReader::BinaryStreamReader(StringRef Data, endianness Endian)
: Stream(Data, Endian) {}
Error BinaryStreamReader::readLongestContiguousChunk(
ArrayRef<uint8_t> &Buffer) {
if (auto EC = Stream.readLongestContiguousChunk(Offset, Buffer))
return EC;
Offset += Buffer.size();
return Error::success();
}
Error BinaryStreamReader::readBytes(ArrayRef<uint8_t> &Buffer, uint32_t Size) {
if (auto EC = Stream.readBytes(Offset, Size, Buffer))
return EC;
Offset += Size;
return Error::success();
}
Error BinaryStreamReader::readCString(StringRef &Dest) {
// TODO: This could be made more efficient by using readLongestContiguousChunk
// and searching for null terminators in the resulting buffer.
uint32_t Length = 0;
// First compute the length of the string by reading 1 byte at a time.
uint32_t OriginalOffset = getOffset();
const char *C;
while (true) {
if (auto EC = readObject(C))
return EC;
if (*C == '\0')
break;
++Length;
}
// Now go back and request a reference for that many bytes.
uint32_t NewOffset = getOffset();
setOffset(OriginalOffset);
if (auto EC = readFixedString(Dest, Length))
return EC;
// Now set the offset back to where it was after we calculated the length.
setOffset(NewOffset);
return Error::success();
}
Error BinaryStreamReader::readFixedString(StringRef &Dest, uint32_t Length) {
ArrayRef<uint8_t> Bytes;
if (auto EC = readBytes(Bytes, Length))
return EC;
Dest = StringRef(reinterpret_cast<const char *>(Bytes.begin()), Bytes.size());
return Error::success();
}
Error BinaryStreamReader::readStreamRef(BinaryStreamRef &Ref) {
return readStreamRef(Ref, bytesRemaining());
}
Error BinaryStreamReader::readStreamRef(BinaryStreamRef &Ref, uint32_t Length) {
if (bytesRemaining() < Length)
return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
Ref = Stream.slice(Offset, Length);
Offset += Length;
return Error::success();
}
Error BinaryStreamReader::skip(uint32_t Amount) {
if (Amount > bytesRemaining())
return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
Offset += Amount;
return Error::success();
}
Error BinaryStreamReader::padToAlignment(uint32_t Align) {
uint32_t NewOffset = alignTo(Offset, Align);
return skip(NewOffset - Offset);
}
uint8_t BinaryStreamReader::peek() const {
ArrayRef<uint8_t> Buffer;
auto EC = Stream.readBytes(Offset, 1, Buffer);
assert(!EC && "Cannot peek an empty buffer!");
llvm::consumeError(std::move(EC));
return Buffer[0];
}
std::pair<BinaryStreamReader, BinaryStreamReader>
BinaryStreamReader::split(uint32_t Off) const {
assert(getLength() >= Off);
BinaryStreamRef First = Stream.drop_front(Offset);
BinaryStreamRef Second = First.drop_front(Off);
First = First.keep_front(Off);
BinaryStreamReader W1{First};
BinaryStreamReader W2{Second};
return std::make_pair(W1, W2);
}
|
//===- BinaryStreamReader.cpp - Reads objects from a binary stream --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/BinaryStreamError.h"
#include "llvm/Support/BinaryStreamRef.h"
using namespace llvm;
using endianness = llvm::support::endianness;
BinaryStreamReader::BinaryStreamReader(BinaryStreamRef Ref) : Stream(Ref) {}
BinaryStreamReader::BinaryStreamReader(BinaryStream &Stream) : Stream(Stream) {}
BinaryStreamReader::BinaryStreamReader(ArrayRef<uint8_t> Data,
endianness Endian)
: Stream(Data, Endian) {}
BinaryStreamReader::BinaryStreamReader(StringRef Data, endianness Endian)
: Stream(Data, Endian) {}
Error BinaryStreamReader::readLongestContiguousChunk(
ArrayRef<uint8_t> &Buffer) {
if (auto EC = Stream.readLongestContiguousChunk(Offset, Buffer))
return EC;
Offset += Buffer.size();
return Error::success();
}
Error BinaryStreamReader::readBytes(ArrayRef<uint8_t> &Buffer, uint32_t Size) {
if (auto EC = Stream.readBytes(Offset, Size, Buffer))
return EC;
Offset += Size;
return Error::success();
}
Error BinaryStreamReader::readCString(StringRef &Dest) {
uint32_t OriginalOffset = getOffset();
uint32_t FoundOffset = 0;
while (true) {
uint32_t ThisOffset = getOffset();
ArrayRef<uint8_t> Buffer;
if (auto EC = readLongestContiguousChunk(Buffer))
return EC;
StringRef S(reinterpret_cast<const char *>(Buffer.begin()), Buffer.size());
size_t Pos = S.find_first_of('\0');
if (LLVM_LIKELY(Pos != StringRef::npos)) {
FoundOffset = Pos + ThisOffset;
break;
}
}
assert(FoundOffset >= OriginalOffset);
setOffset(OriginalOffset);
size_t Length = FoundOffset - OriginalOffset;
if (auto EC = readFixedString(Dest, Length))
return EC;
// Now set the offset back to after the null terminator.
setOffset(FoundOffset + 1);
return Error::success();
}
Error BinaryStreamReader::readFixedString(StringRef &Dest, uint32_t Length) {
ArrayRef<uint8_t> Bytes;
if (auto EC = readBytes(Bytes, Length))
return EC;
Dest = StringRef(reinterpret_cast<const char *>(Bytes.begin()), Bytes.size());
return Error::success();
}
Error BinaryStreamReader::readStreamRef(BinaryStreamRef &Ref) {
return readStreamRef(Ref, bytesRemaining());
}
Error BinaryStreamReader::readStreamRef(BinaryStreamRef &Ref, uint32_t Length) {
if (bytesRemaining() < Length)
return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
Ref = Stream.slice(Offset, Length);
Offset += Length;
return Error::success();
}
Error BinaryStreamReader::skip(uint32_t Amount) {
if (Amount > bytesRemaining())
return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
Offset += Amount;
return Error::success();
}
Error BinaryStreamReader::padToAlignment(uint32_t Align) {
uint32_t NewOffset = alignTo(Offset, Align);
return skip(NewOffset - Offset);
}
uint8_t BinaryStreamReader::peek() const {
ArrayRef<uint8_t> Buffer;
auto EC = Stream.readBytes(Offset, 1, Buffer);
assert(!EC && "Cannot peek an empty buffer!");
llvm::consumeError(std::move(EC));
return Buffer[0];
}
std::pair<BinaryStreamReader, BinaryStreamReader>
BinaryStreamReader::split(uint32_t Off) const {
assert(getLength() >= Off);
BinaryStreamRef First = Stream.drop_front(Offset);
BinaryStreamRef Second = First.drop_front(Off);
First = First.keep_front(Off);
BinaryStreamReader W1{First};
BinaryStreamReader W2{Second};
return std::make_pair(W1, W2);
}
|
Make BinaryStreamReader::readCString a bit faster.
|
Make BinaryStreamReader::readCString a bit faster.
Previously it would do a character by character search for a null
terminator, to account for the fact that an arbitrary stream need not
store its data contiguously so you couldn't just do a memchr. However, the
stream API has a function which will return the longest contiguous chunk
without doing a copy, and by using this function we can do a memchr on the
individual chunks. For certain types of streams like data from object
files etc, this is guaranteed to find the null terminator with only a
single memchr, but even with discontiguous streams such as
MappedBlockStream, it's rare that any given string will cross a block
boundary, so even those will almost always be satisfied with a single
memchr.
This optimization is worth a 10-12% reduction in link time (4.2 seconds ->
3.75 seconds)
Differential Revision: https://reviews.llvm.org/D33503
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@303918 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
|
da86792963005c0bdbc0293e9b53efa09dc15116
|
TetrisGame/core/Game.cpp
|
TetrisGame/core/Game.cpp
|
#pragma once
#include "Game.h"
namespace REKTetrisGame
{
Game::Game()
{
//The window we'll be rendering to
_window = nullptr;
// Engine renderer
_renderer = nullptr;
// The class who manage all input
_inputManager = nullptr;
// Handle the game behavior according to the context (In-game, Pause, Menu etc...)
_gameContextManager = nullptr;
// Manage all sounds
_soundManager = nullptr;
_gameMenu = nullptr;
_boardGame = nullptr;
_gameOverScreen = nullptr;
_gameConfiguration = nullptr;
}
Game::~Game()
{
}
void Game::Loop(SDL_Event& e)
{
bool quitGame = false;
while (!quitGame)
{
SDL_RenderClear(_renderer.get());
if (_inputManager != nullptr)
_inputManager->CheckInput(e, quitGame);
if (_boardGame != nullptr)
{
if (!_boardGame->IsGameOver())
{
_boardGame->Update();
}
_boardGame->Draw();
}
HandleGameMenu();
// Handle Game Over
if (_boardGame != nullptr)
{
if (_boardGame->IsGameOver() && GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
{
GameContextManager::CurrentGameContext = GameContextEnum::GAMEOVER;
}
}
if (GameContextManager::CurrentGameContext == GameContextEnum::GAMEOVER)
{
if (_gameOverScreen == nullptr)
{
auto gamepadConfig = _inputManager->GetGamepadConfiguration();
_gameOverScreen = std::make_unique<GameOverScreen>(gamepadConfig);
}
_gameOverScreen->Draw();
}
//Update the surface
//SDL_UpdateWindowSurface(_window); // software rendering : Not good
SDL_RenderPresent(_renderer.get()); // GPU rendering : Good !
}
}
// Return true if no error
bool Game::Init()
{
bool isInitOk = true;
if (!AreAllAssetsExists())
{
ErrorMessageManager::WriteErrorMessageToMessageBox("All assets are not present in resources folder, you need to redownload the game. Application will be closed. END END END");
isInitOk = false;
}
else
{
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("SDL could not be initialized. Application will be closed.");
isInitOk = false;
}
else
{
_gameConfiguration = std::make_shared<GameConfiguration>();
if (_gameConfiguration->IsConfigFileFound())
{
_window = std::shared_ptr<SDL_Window>(
SDL_CreateWindow("Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, _gameConfiguration->GetFullscreenConfig())
, SdlDeleter()
);
if (_window == nullptr)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Window could not be created. Application will be closed.");
isInitOk = false;
}
else
{
_renderer = std::shared_ptr<SDL_Renderer>(
SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)
, SdlDeleter()
);
if (_renderer == nullptr)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Renderer could not be created. Application will be closed.");
isInitOk = false;
}
else
{
// Init screen with light grey all over the surface
SDL_SetRenderDrawColor(_renderer.get(), 0x44, 0x87, 0xC5, SDL_ALPHA_OPAQUE);
SDL_RenderSetLogicalSize(_renderer.get(), SCREEN_WIDTH, SCREEN_HEIGHT);
// About mouse cursor
if (SDL_ShowCursor(SDL_DISABLE) < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Cannot hide mouse cursor. Application will be closed.");
isInitOk = false;
}
else
{
_gameContextManager = std::make_shared<GameContextManager>();
_inputManager = std::make_unique<InputManager>(_gameContextManager);
// SDL_ttf
if (TTF_Init() != 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Could not load SDL2_ttf. Application will be closed.");
isInitOk = false;
}
else
{
_soundManager = std::make_shared<SoundManager>();
if (_soundManager->Init() < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Could not Init SDL2_Mixer with OGG format. Application will be closed.");
isInitOk = false;
}
else
{
_soundManager->PlayMusic(AssetsFilePathConsts::Music, 4000);
SetSDLMainObjectsToProvider();
}
}
}
}
}
}
}
}
return isInitOk;
}
bool Game::AreAllAssetsExists()
{
std::vector<std::string> fileNames;
fileNames.push_back(AssetsFilePathConsts::ConfigFile);
fileNames.push_back(AssetsFilePathConsts::Font);
fileNames.push_back(AssetsFilePathConsts::Music);
fileNames.push_back(AssetsFilePathConsts::SoundMenuClick);
fileNames.push_back(AssetsFilePathConsts::SoundMenuOver);
fileNames.push_back(AssetsFilePathConsts::TetrominoBlue);
fileNames.push_back(AssetsFilePathConsts::TetrominoBrown);
fileNames.push_back(AssetsFilePathConsts::TetrominoGreen);
fileNames.push_back(AssetsFilePathConsts::TetrominoOrange);
fileNames.push_back(AssetsFilePathConsts::TetrominoPurple);
fileNames.push_back(AssetsFilePathConsts::TetrominoRed);
fileNames.push_back(AssetsFilePathConsts::TetrominoYellow);
fileNames.push_back(KeyboardKeysFilePathConsts::EnterKey);
fileNames.push_back(KeyboardKeysFilePathConsts::BackspaceKey);
fileNames.push_back(GamepadButtonsFilePathConsts::AButton);
fileNames.push_back(GamepadButtonsFilePathConsts::BButton);
bool allAssetsExists = true;
for (auto filename : fileNames)
{
if (!FileManager::IsFileExists(filename))
{
allAssetsExists = false;
break;
}
}
return allAssetsExists;
}
void Game::Run()
{
if (Init())
{
SDL_Event e;
Loop(e);
}
}
void Game::SetSDLMainObjectsToProvider() const
{
SDLMainObjectsProvider::_renderer = _renderer;
SDLMainObjectsProvider::_window = _window;
}
void Game::HandleGameMenu()
{
if (_gameContextManager != nullptr
&& (
GameContextManager::CurrentGameContext == GameContextEnum::MENU
|| GameContextManager::CurrentGameContext == GameContextEnum::STARTED
))
{
if (_gameMenu == nullptr)
{
auto gamepadConfig = _inputManager->GetGamepadConfiguration();
_gameMenu = std::make_shared<GameMenu>(_soundManager, _gameConfiguration, gamepadConfig);
_gameContextManager->SetGameMenu(_gameMenu);
_soundManager->PlaySound(AssetsFilePathConsts::SoundMenuClick, 1);
}
_gameMenu->Draw(_boardGame);
}
if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME && _gameMenu != nullptr)
{
_gameMenu.reset();
_soundManager->PlaySound(AssetsFilePathConsts::SoundMenuOver, 1);
if (_boardGame != nullptr && _boardGame->IsGameOver())
{
// We leave menu after game over and restart a new game
if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
{
_boardGame.reset();
_boardGame = nullptr;
_boardGame = std::make_shared<Board>();
_gameContextManager->SetBoardGame(_boardGame);
}
}
else if (_boardGame == nullptr)
{
_boardGame = std::make_shared<Board>();
_gameContextManager->SetBoardGame(_boardGame);
}
}
}
}
|
#pragma once
#include "Game.h"
namespace REKTetrisGame
{
Game::Game()
{
//The window we'll be rendering to
_window = nullptr;
// Engine renderer
_renderer = nullptr;
// The class who manage all input
_inputManager = nullptr;
// Handle the game behavior according to the context (In-game, Pause, Menu etc...)
_gameContextManager = nullptr;
// Manage all sounds
_soundManager = nullptr;
_gameMenu = nullptr;
_boardGame = nullptr;
_gameOverScreen = nullptr;
_gameConfiguration = nullptr;
}
Game::~Game()
{
}
void Game::Loop(SDL_Event& e)
{
bool quitGame = false;
while (!quitGame)
{
SDL_RenderClear(_renderer.get());
if (_inputManager != nullptr)
_inputManager->CheckInput(e, quitGame);
if (_boardGame != nullptr)
{
if (!_boardGame->IsGameOver())
{
_boardGame->Update();
}
_boardGame->Draw();
}
HandleGameMenu();
// Handle Game Over
if (_boardGame != nullptr)
{
if (_boardGame->IsGameOver() && GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
{
GameContextManager::CurrentGameContext = GameContextEnum::GAMEOVER;
}
}
if (GameContextManager::CurrentGameContext == GameContextEnum::GAMEOVER)
{
if (_gameOverScreen == nullptr)
{
auto gamepadConfig = _inputManager->GetGamepadConfiguration();
_gameOverScreen = std::make_unique<GameOverScreen>(gamepadConfig);
}
_gameOverScreen->Draw();
}
//Update the surface
//SDL_UpdateWindowSurface(_window); // software rendering : Not good
SDL_RenderPresent(_renderer.get()); // GPU rendering : Good !
}
}
// Return true if no error
bool Game::Init()
{
bool isInitOk = true;
if (!AreAllAssetsExists())
{
ErrorMessageManager::WriteErrorMessageToMessageBox("All assets are not present in resources folder, you need to redownload the game.\nApplication will be closed.");
isInitOk = false;
}
else
{
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("SDL could not be initialized.\nApplication will be closed.");
isInitOk = false;
}
else
{
_gameConfiguration = std::make_shared<GameConfiguration>();
if (_gameConfiguration->IsConfigFileFound())
{
_window = std::shared_ptr<SDL_Window>(
SDL_CreateWindow("Tetris", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, _gameConfiguration->GetFullscreenConfig())
, SdlDeleter()
);
if (_window == nullptr)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Window could not be created.\nApplication will be closed.");
isInitOk = false;
}
else
{
_renderer = std::shared_ptr<SDL_Renderer>(
SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)
, SdlDeleter()
);
if (_renderer == nullptr)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Renderer could not be created.\nApplication will be closed.");
isInitOk = false;
}
else
{
// Init screen with light grey all over the surface
SDL_SetRenderDrawColor(_renderer.get(), 0x44, 0x87, 0xC5, SDL_ALPHA_OPAQUE);
SDL_RenderSetLogicalSize(_renderer.get(), SCREEN_WIDTH, SCREEN_HEIGHT);
// About mouse cursor
if (SDL_ShowCursor(SDL_DISABLE) < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Cannot hide mouse cursor.\nApplication will be closed.");
isInitOk = false;
}
else
{
_gameContextManager = std::make_shared<GameContextManager>();
_inputManager = std::make_unique<InputManager>(_gameContextManager);
// SDL_ttf
if (TTF_Init() != 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Could not load SDL2_ttf.\nApplication will be closed.");
isInitOk = false;
}
else
{
_soundManager = std::make_shared<SoundManager>();
if (_soundManager->Init() < 0)
{
ErrorMessageManager::WriteErrorMessageToMessageBox("Could not Init SDL2_Mixer with OGG format.\nApplication will be closed.");
isInitOk = false;
}
else
{
_soundManager->PlayMusic(AssetsFilePathConsts::Music, 4000);
SetSDLMainObjectsToProvider();
}
}
}
}
}
}
}
}
return isInitOk;
}
bool Game::AreAllAssetsExists()
{
std::vector<std::string> fileNames;
fileNames.push_back(AssetsFilePathConsts::ConfigFile);
fileNames.push_back(AssetsFilePathConsts::Font);
fileNames.push_back(AssetsFilePathConsts::Music);
fileNames.push_back(AssetsFilePathConsts::SoundMenuClick);
fileNames.push_back(AssetsFilePathConsts::SoundMenuOver);
fileNames.push_back(AssetsFilePathConsts::TetrominoBlue);
fileNames.push_back(AssetsFilePathConsts::TetrominoBrown);
fileNames.push_back(AssetsFilePathConsts::TetrominoGreen);
fileNames.push_back(AssetsFilePathConsts::TetrominoOrange);
fileNames.push_back(AssetsFilePathConsts::TetrominoPurple);
fileNames.push_back(AssetsFilePathConsts::TetrominoRed);
fileNames.push_back(AssetsFilePathConsts::TetrominoYellow);
fileNames.push_back(KeyboardKeysFilePathConsts::EnterKey);
fileNames.push_back(KeyboardKeysFilePathConsts::BackspaceKey);
fileNames.push_back(GamepadButtonsFilePathConsts::AButton);
fileNames.push_back(GamepadButtonsFilePathConsts::BButton);
bool allAssetsExists = true;
for (auto filename : fileNames)
{
if (!FileManager::IsFileExists(filename))
{
allAssetsExists = false;
break;
}
}
return allAssetsExists;
}
void Game::Run()
{
if (Init())
{
SDL_Event e;
Loop(e);
}
}
void Game::SetSDLMainObjectsToProvider() const
{
SDLMainObjectsProvider::_renderer = _renderer;
SDLMainObjectsProvider::_window = _window;
}
void Game::HandleGameMenu()
{
if (_gameContextManager != nullptr
&& (
GameContextManager::CurrentGameContext == GameContextEnum::MENU
|| GameContextManager::CurrentGameContext == GameContextEnum::STARTED
))
{
if (_gameMenu == nullptr)
{
auto gamepadConfig = _inputManager->GetGamepadConfiguration();
_gameMenu = std::make_shared<GameMenu>(_soundManager, _gameConfiguration, gamepadConfig);
_gameContextManager->SetGameMenu(_gameMenu);
_soundManager->PlaySound(AssetsFilePathConsts::SoundMenuClick, 1);
}
_gameMenu->Draw(_boardGame);
}
if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME && _gameMenu != nullptr)
{
_gameMenu.reset();
_soundManager->PlaySound(AssetsFilePathConsts::SoundMenuOver, 1);
if (_boardGame != nullptr && _boardGame->IsGameOver())
{
// We leave menu after game over and restart a new game
if (GameContextManager::CurrentGameContext == GameContextEnum::INGAME)
{
_boardGame.reset();
_boardGame = nullptr;
_boardGame = std::make_shared<Board>();
_gameContextManager->SetBoardGame(_boardGame);
}
}
else if (_boardGame == nullptr)
{
_boardGame = std::make_shared<Board>();
_gameContextManager->SetBoardGame(_boardGame);
}
}
}
}
|
Fix error messages
|
Fix error messages
|
C++
|
mit
|
R-E-K/8bits-Tetris
|
710b9a683c84461d430bb2df20073b1e10a13fc3
|
src/index/ranker/ranker.cpp
|
src/index/ranker/ranker.cpp
|
/**
* @file ranker.cpp
* @author Sean Massung
*/
#include "corpus/document.h"
#include "index/inverted_index.h"
#include "index/postings_data.h"
#include "index/ranker/ranker.h"
#include "index/score_data.h"
namespace meta
{
namespace index
{
std::vector<std::pair<doc_id, double>> ranker::score(inverted_index& idx,
corpus::document& query,
uint64_t num_results)
{
if (query.counts().empty())
idx.tokenize(query);
score_data sd{idx, idx.avg_doc_length(),
idx.num_docs(), idx.total_corpus_terms(),
query};
// zeros out elements and (if necessary) resizes the vector; this eliminates
// constructing a new vector each query for the same index
_results.assign(sd.num_docs, 0.0);
for (auto& tpair : query.counts())
{
term_id t_id{idx.get_term_id(tpair.first)};
auto pdata = idx.search_primary(t_id);
sd.doc_count = pdata->counts().size();
sd.t_id = t_id;
sd.query_term_count = tpair.second;
sd.corpus_term_count = idx.total_num_occurences(sd.t_id);
for (auto& dpair : pdata->counts())
{
sd.d_id = dpair.first;
sd.doc_term_count = dpair.second;
sd.doc_size = idx.doc_size(dpair.first);
sd.doc_unique_terms = idx.unique_terms(dpair.first);
_results[dpair.first] += score_one(sd);
}
}
using doc_pair = std::pair<doc_id, double>;
auto doc_pair_comp = [](const doc_pair& a, const doc_pair& b) {
return a.second < b.second;
};
std::priority_queue<doc_pair,
std::vector<doc_pair>,
decltype(doc_pair_comp)
> pq{doc_pair_comp};
for (uint64_t id = 0; id < _results.size(); ++id)
{
// if lower score than lowest score, don't add
if(!pq.empty() && _results[id] < pq.top().second)
continue;
pq.emplace(doc_id{id}, _results[id]);
if (pq.size() > num_results)
pq.pop();
}
std::vector<doc_pair> sorted;
while (!pq.empty())
{
sorted.emplace_back(pq.top());
pq.pop();
}
//std::reverse(sorted.begin(), sorted.end());
return sorted;
}
}
}
|
/**
* @file ranker.cpp
* @author Sean Massung
*/
#include "corpus/document.h"
#include "index/inverted_index.h"
#include "index/postings_data.h"
#include "index/ranker/ranker.h"
#include "index/score_data.h"
namespace meta
{
namespace index
{
std::vector<std::pair<doc_id, double>> ranker::score(inverted_index& idx,
corpus::document& query,
uint64_t num_results)
{
if (query.counts().empty())
idx.tokenize(query);
score_data sd{idx, idx.avg_doc_length(),
idx.num_docs(), idx.total_corpus_terms(),
query};
// zeros out elements and (if necessary) resizes the vector; this eliminates
// constructing a new vector each query for the same index
_results.assign(sd.num_docs, 0.0);
for (auto& tpair : query.counts())
{
term_id t_id{idx.get_term_id(tpair.first)};
auto pdata = idx.search_primary(t_id);
sd.doc_count = pdata->counts().size();
sd.t_id = t_id;
sd.query_term_count = tpair.second;
sd.corpus_term_count = idx.total_num_occurences(sd.t_id);
for (auto& dpair : pdata->counts())
{
sd.d_id = dpair.first;
sd.doc_term_count = dpair.second;
sd.doc_size = idx.doc_size(dpair.first);
sd.doc_unique_terms = idx.unique_terms(dpair.first);
_results[dpair.first] += score_one(sd);
}
}
using doc_pair = std::pair<doc_id, double>;
auto doc_pair_comp = [](const doc_pair& a, const doc_pair& b) {
return a.second < b.second;
};
std::priority_queue<doc_pair,
std::vector<doc_pair>,
decltype(doc_pair_comp)
> pq{doc_pair_comp};
for (uint64_t id = 0; id < _results.size(); ++id)
{
// if lower score than lowest score, don't add
if(!pq.empty() && _results[id] < pq.top().second)
continue;
pq.emplace(doc_id{id}, _results[id]);
if (pq.size() > num_results)
pq.pop();
}
std::vector<doc_pair> sorted;
while (!pq.empty())
{
sorted.emplace_back(pq.top());
pq.pop();
}
return sorted;
}
}
}
|
remove debugging comment...
|
remove debugging comment...
|
C++
|
mit
|
gef756/meta,husseinhazimeh/meta,esparza83/meta,husseinhazimeh/meta,esparza83/meta,esparza83/meta,esparza83/meta,husseinhazimeh/meta,saq7/MeTA,saq7/MeTA,esparza83/meta,gef756/meta,husseinhazimeh/meta,gef756/meta,saq7/MeTA,gef756/meta,husseinhazimeh/meta,gef756/meta
|
1f7a528b3e0e6a8010a32017f5bae77f43155715
|
upnp.cpp
|
upnp.cpp
|
/*
* Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QString>
#include <QTcpSocket>
#include <QTimer>
#include <QFile>
#include <QUdpSocket>
#include <QVariantMap>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
/*! Inits the UPnP discorvery. */
void DeRestPluginPrivate::initUpnpDiscovery()
{
DBG_Assert(udpSock == 0);
QHostAddress groupAddress("239.255.255.250");
udpSock = new QUdpSocket(this);
udpSockOut = new QUdpSocket(this);
if (!udpSock->bind(1900, QUdpSocket::ShareAddress)) // SSDP
{
DBG_Printf(DBG_ERROR, "UPNP error %s\n", qPrintable(udpSock->errorString()));
}
if (!udpSock->joinMulticastGroup(groupAddress))
{
DBG_Printf(DBG_ERROR, "UPNP error %s\n", qPrintable(udpSock->errorString()));
}
connect(udpSock, SIGNAL(readyRead()),
this, SLOT(upnpReadyRead()));
QTimer *timer = new QTimer(this);
timer->setSingleShot(false);
connect(timer, SIGNAL(timeout()),
this, SLOT(announceUpnp()));
timer->start(20 * 1000);
// replace description_in.xml template with dynamic content
QString serverRoot = deCONZ::appArgumentString("--http-root", "");
if (serverRoot != "")
{
descriptionXml.clear();
QFile f(serverRoot + "/description_in.xml");
if (f.open(QFile::ReadOnly))
{
QByteArray line;
do {
line = f.readLine(320);
if (!line.isEmpty())
{
line.replace(QString("{{PORT}}"), qPrintable(QString::number(gwPort)));
line.replace(QString("{{IPADDRESS}}"), qPrintable(gwIpAddress));
line.replace(QString("{{UUID}}"), qPrintable(gwUuid));
descriptionXml.append(line);
DBG_Printf(DBG_INFO_L2, "%s", line.constData());
}
} while (!line.isEmpty());
}
}
}
/*! Sends SSDP broadcast for announcement. */
void DeRestPluginPrivate::announceUpnp()
{
quint16 port = 1900;
QHostAddress host;
QByteArray datagram = QString(
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"CACHE-CONTROL: max-age=100\r\n"
"LOCATION: http://%1:%2/description.xml\r\n"
"SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1\r\n"
"NTS: ssdp:alive\r\n"
"NT: upnp:rootdevice\r\n"
"USN: uuid:%3::upnp:rootdevice\r\n"
"\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble())
.arg(gwConfig["uuid"].toString()).toLocal8Bit();
host.setAddress("239.255.255.250");
if (udpSockOut->writeDatagram(datagram, host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
}
/*! Handles SSDP packets. */
void DeRestPluginPrivate::upnpReadyRead()
{
while (udpSock->hasPendingDatagrams())
{
quint16 port;
QHostAddress host;
QByteArray datagram;
datagram.resize(udpSock->pendingDatagramSize());
udpSock->readDatagram(datagram.data(), datagram.size(), &host, &port);
if (datagram.startsWith("M-SEARCH *"))
{
DBG_Printf(DBG_HTTP, "UPNP %s:%u\n%s\n", qPrintable(host.toString()), port, datagram.data());
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: upnp:rootdevice\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: uuid:rootdevice\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: urn:schemas-upnp-org:device:basic:1\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
}
}
}
|
/*
* Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QString>
#include <QTcpSocket>
#include <QTimer>
#include <QFile>
#include <QUdpSocket>
#include <QVariantMap>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
/*! Inits the UPnP discorvery. */
void DeRestPluginPrivate::initUpnpDiscovery()
{
DBG_Assert(udpSock == 0);
QHostAddress groupAddress("239.255.255.250");
udpSock = new QUdpSocket(this);
udpSockOut = new QUdpSocket(this);
if (!udpSock->bind(QHostAddress::AnyIPv4, 1900, QUdpSocket::ShareAddress)) // SSDP
{
DBG_Printf(DBG_ERROR, "UPNP error %s\n", qPrintable(udpSock->errorString()));
}
if (!udpSock->joinMulticastGroup(groupAddress))
{
DBG_Printf(DBG_ERROR, "UPNP error %s\n", qPrintable(udpSock->errorString()));
}
connect(udpSock, SIGNAL(readyRead()),
this, SLOT(upnpReadyRead()));
QTimer *timer = new QTimer(this);
timer->setSingleShot(false);
connect(timer, SIGNAL(timeout()),
this, SLOT(announceUpnp()));
timer->start(20 * 1000);
// replace description_in.xml template with dynamic content
QString serverRoot = deCONZ::appArgumentString("--http-root", "");
if (serverRoot != "")
{
descriptionXml.clear();
QFile f(serverRoot + "/description_in.xml");
if (f.open(QFile::ReadOnly))
{
QByteArray line;
do {
line = f.readLine(320);
if (!line.isEmpty())
{
line.replace(QString("{{PORT}}"), qPrintable(QString::number(gwPort)));
line.replace(QString("{{IPADDRESS}}"), qPrintable(gwIpAddress));
line.replace(QString("{{UUID}}"), qPrintable(gwUuid));
descriptionXml.append(line);
DBG_Printf(DBG_INFO_L2, "%s", line.constData());
}
} while (!line.isEmpty());
}
}
}
/*! Sends SSDP broadcast for announcement. */
void DeRestPluginPrivate::announceUpnp()
{
quint16 port = 1900;
QHostAddress host;
QByteArray datagram = QString(
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"CACHE-CONTROL: max-age=100\r\n"
"LOCATION: http://%1:%2/description.xml\r\n"
"SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1\r\n"
"NTS: ssdp:alive\r\n"
"NT: upnp:rootdevice\r\n"
"USN: uuid:%3::upnp:rootdevice\r\n"
"\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble())
.arg(gwConfig["uuid"].toString()).toLocal8Bit();
host.setAddress("239.255.255.250");
if (udpSockOut->writeDatagram(datagram, host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
}
/*! Handles SSDP packets. */
void DeRestPluginPrivate::upnpReadyRead()
{
while (udpSock->hasPendingDatagrams())
{
quint16 port;
QHostAddress host;
QByteArray datagram;
datagram.resize(udpSock->pendingDatagramSize());
udpSock->readDatagram(datagram.data(), datagram.size(), &host, &port);
if (datagram.startsWith("M-SEARCH *"))
{
DBG_Printf(DBG_HTTP, "UPNP %s:%u\n%s\n", qPrintable(host.toString()), port, datagram.data());
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: upnp:rootdevice\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: uuid:rootdevice\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
datagram.clear();
datagram.append("HTTP/1.1 200 OK\r\n");
datagram.append("CACHE-CONTROL: max-age=100\r\n");
datagram.append("EXT:\r\n");
datagram.append(QString("LOCATION: http://%1:%2/description.xml\r\n")
.arg(gwConfig["ipaddress"].toString())
.arg(gwConfig["port"].toDouble()).toLocal8Bit());
datagram.append("SERVER: FreeRTOS/7.4.2, UPnP/1.0, IpBridge/1.8.0\r\n");
datagram.append("ST: urn:schemas-upnp-org:device:basic:1\r\n");
datagram.append(QString("USN: uuid:%1::upnp:rootdevice\r\n").arg(gwUuid));
datagram.append("\r\n");
if (udpSockOut->writeDatagram(datagram.data(), datagram.size(), host, port) == -1)
{
DBG_Printf(DBG_ERROR, "UDP send error %s\n", qPrintable(udpSockOut->errorString()));
}
}
}
}
|
Fix binding UDP port in mixed IPv4/6 networks
|
Fix binding UDP port in mixed IPv4/6 networks
|
C++
|
bsd-3-clause
|
dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin
|
8bd418e9c4584d77ba02e07ba3f20aa8544fb5f2
|
syzygy/pe/export_dll.cc
|
syzygy/pe/export_dll.cc
|
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string.h>
#include <time.h>
#include <cstdlib>
// A simple piece of data to be exported.
extern int kExportedData[1024] = { 0 };
int function1() {
return rand();
}
int function2() {
return strlen("hello");
}
int function3() {
return static_cast<int>(clock()) + function1();
}
|
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string.h>
#include <time.h>
#include <cstdlib>
// A simple piece of data to be exported.
extern int kExportedData[1024] = { 0 };
int function1() {
return rand();
}
int function2() {
return static_cast<int>(strlen("hello"));
}
int function3() {
return static_cast<int>(clock()) + function1();
}
|
Make the implicit cast of size_t to int explicit
|
Make the implicit cast of size_t to int explicit
BUG=
Review-Url: https://codereview.chromium.org/2107263002
|
C++
|
apache-2.0
|
google/syzygy,google/syzygy,google/syzygy,Eloston/syzygy,google/syzygy,Eloston/syzygy
|
ab9f18d6148d158397e62f9faf70ea447d37813c
|
open_spiel/algorithms/tabular_best_response_mdp.cc
|
open_spiel/algorithms/tabular_best_response_mdp.cc
|
// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/tabular_best_response_mdp.h"
#include <cmath>
#include <limits>
#include <numeric>
#include <string>
#include <utility>
#include "open_spiel/abseil-cpp/absl/algorithm/container.h"
#include "open_spiel/abseil-cpp/absl/memory/memory.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/algorithms/expected_returns.h"
#include "open_spiel/policy.h"
#include "open_spiel/simultaneous_move_game.h"
#include "open_spiel/spiel_globals.h"
namespace open_spiel {
namespace algorithms {
namespace {
constexpr double kSolveTolerance = 1e-12;
} // namespace
MDPNode::MDPNode(const std::string& node_key)
: terminal_(false), total_weight_(0), children_(), value_(0),
node_key_(node_key) {}
void MDPNode::IncTransitionWeight(Action a, MDPNode *child, double weight) {
SPIEL_CHECK_NE(child, nullptr);
children_[a][child] += weight;
}
MDP::MDP() : terminal_node_uid_(0), num_nonterminal_nodes_(0) {
node_map_[kRootKey] = absl::make_unique<MDPNode>(std::string(kRootKey));
node_map_[kRootKey]->add_weight(1.0);
}
MDPNode *MDP::CreateTerminalNode(const std::string &node_key) {
++terminal_node_uid_;
MDPNode *terminal_node = LookupOrCreateNode(node_key, true);
terminal_node->set_terminal(true);
return terminal_node;
}
MDPNode *MDP::LookupOrCreateNode(const std::string &node_key, bool terminal) {
const auto &iter = node_map_.find(node_key);
if (iter != node_map_.end()) {
return iter->second.get();
} else {
MDPNode *new_node = new MDPNode(node_key);
node_map_[node_key].reset(new_node);
if (!terminal) {
num_nonterminal_nodes_++;
}
return new_node;
}
}
double MDP::Solve(double tolerance, TabularPolicy *br_policy) {
double delta = 0;
do {
delta = 0.0;
for (auto &key_and_node : node_map_) {
MDPNode *node = key_and_node.second.get();
if (node->terminal()) {
continue;
}
double max_value = -std::numeric_limits<double>::infinity();
Action max_action = kInvalidAction;
double node_weight = node->total_weight();
SPIEL_CHECK_GE(node_weight, 0.0);
// Compute Bellman value from children.
for (const auto &action_and_child : node->children()) {
double action_value = 0.0;
Action action = action_and_child.first;
for (auto &child_value : node->children()[action]) {
MDPNode *child = child_value.first;
double transition_weight = child_value.second;
SPIEL_CHECK_NE(child, nullptr);
double prob = transition_weight / node_weight;
if (std::isnan(prob)) {
// When transition_weight = node_weight = 0, set to 0
prob = 0.0;
}
SPIEL_CHECK_PROB(prob);
action_value += prob * child->value();
}
if (action_value > max_value) {
max_value = action_value;
max_action = action;
}
}
SPIEL_CHECK_NE(max_action, kInvalidAction);
delta += std::abs(node->value() - max_value);
node->set_value(max_value);
// Set the best response to the maximum-value action, if it's non-null.
if (node->node_key() != kRootKey) {
ActionsAndProbs br_state_policy;
for (const auto &[action, child] : node->children()) {
SetProb(&br_state_policy, action, action == max_action ? 1.0 : 0.0);
}
br_policy->SetStatePolicy(node->node_key(), br_state_policy);
}
}
} while (delta > tolerance);
return RootNode()->value();
}
double
TabularBestResponseMDP::OpponentReach(const std::vector<double>& reach_probs,
Player p) const {
double product = 1.0;
for (int i = 0; i < reach_probs.size(); i++) {
if (p != i) {
product *= reach_probs[i];
}
}
return product;
}
void TabularBestResponseMDP::BuildMDPs(
const State &state, const std::vector<double>& reach_probs,
const std::vector<MDPNode*>& parent_nodes,
const std::vector<Action>& parent_actions, Player only_for_player) {
if (state.IsTerminal()) {
std::vector<double> terminal_values = state.Returns();
for (Player p = 0; p < game_.NumPlayers(); ++p) {
std::string node_key = state.ToString();
MDPNode *node = mdps_.at(p)->CreateTerminalNode(node_key);
node->set_value(terminal_values[p]);
double opponent_reach = OpponentReach(reach_probs, p);
SPIEL_CHECK_GE(opponent_reach, 0.0);
SPIEL_CHECK_LE(opponent_reach, 1.0);
// Following line is not actually necessary because the weight of a leaf
// is never in a denominator for a transition probability, btu we include
// it to keep the semantics of the values consistent across the ISMDP.
node->add_weight(opponent_reach);
MDPNode *parent_node = parent_nodes[p];
SPIEL_CHECK_NE(parent_node, nullptr);
parent_node->IncTransitionWeight(parent_actions[p], node, opponent_reach);
}
} else if (state.IsChanceNode()) {
ActionsAndProbs outcomes_and_probs = state.ChanceOutcomes();
for (const auto &[outcome, prob] : outcomes_and_probs) {
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(outcome);
std::vector<double> new_reach_probs = reach_probs;
// Chance prob is at the end of the vector.
new_reach_probs[game_.NumPlayers()] *= prob;
BuildMDPs(*state_copy, new_reach_probs, parent_nodes, parent_actions,
only_for_player);
}
} else if (state.IsSimultaneousNode()) {
// Several nodes are created: one for each player as the maximizer.
std::vector<std::string> node_keys;
std::vector<MDPNode*> nodes;
std::vector<double> opponent_reaches;
std::vector<ActionsAndProbs> fixed_state_policies;
node_keys.reserve(num_players_);
nodes.reserve(num_players_);
opponent_reaches.reserve(num_players_);
fixed_state_policies.reserve(num_players_);
for (Player player = 0; player < num_players_; ++player) {
node_keys.push_back(GetNodeKey(state, player));
nodes.push_back(mdps_.at(player)->LookupOrCreateNode(node_keys[player]));
opponent_reaches.push_back(OpponentReach(reach_probs, player));
fixed_state_policies.push_back(
fixed_policy_.GetStatePolicy(state, player));
SPIEL_CHECK_GE(opponent_reaches[player], 0.0);
SPIEL_CHECK_LE(opponent_reaches[player], 1.0);
nodes[player]->add_weight(opponent_reaches[player]);
MDPNode* parent_node = parent_nodes[player];
SPIEL_CHECK_NE(parent_node, nullptr);
parent_node->IncTransitionWeight(parent_actions[player], nodes[player],
opponent_reaches[player]);
}
// Traverse over the list of joint actions. For each one, first deconstruct
// the actions, and then recurse once for each player as the maximizer with
// the others as the fixed policies.
const auto& sim_move_state = down_cast<const SimMoveState&>(state);
for (Action joint_action : state.LegalActions()) {
std::vector<Action> actions =
sim_move_state.FlatJointActionToActions(joint_action);
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(joint_action);
std::vector<double> new_reach_probs = reach_probs;
std::vector<MDPNode*> new_parent_nodes = parent_nodes;
std::vector<Action> new_parent_actions = parent_actions;
for (Player player = 0; player < num_players_; ++player) {
double action_prob = GetProb(fixed_state_policies[player],
actions[player]);
SPIEL_CHECK_PROB(action_prob);
new_reach_probs[player] *= action_prob;
new_parent_nodes[player] = nodes[player];
new_parent_actions[player] = actions[player];
}
BuildMDPs(*state_copy, new_reach_probs, new_parent_nodes,
new_parent_actions, only_for_player);
}
} else {
// Normal decisions node.
std::vector<Action> legal_actions = state.LegalActions();
Player player = state.CurrentPlayer();
std::string node_key = GetNodeKey(state, player);
MDPNode *node = mdps_.at(player)->LookupOrCreateNode(node_key);
double opponent_reach = OpponentReach(reach_probs, player);
SPIEL_CHECK_GE(opponent_reach, 0.0);
SPIEL_CHECK_LE(opponent_reach, 1.0);
node->add_weight(opponent_reach);
MDPNode *parent_node = parent_nodes[player];
SPIEL_CHECK_NE(parent_node, nullptr);
parent_node->IncTransitionWeight(parent_actions[player], node,
opponent_reach);
ActionsAndProbs state_policy = fixed_policy_.GetStatePolicy(state);
for (Action action : legal_actions) {
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(action);
std::vector<double> new_reach_probs = reach_probs;
double action_prob = GetProb(state_policy, action);
SPIEL_CHECK_PROB(action_prob);
new_reach_probs[player] *= action_prob;
std::vector<MDPNode *> new_parent_nodes = parent_nodes;
new_parent_nodes[player] = node;
std::vector<Action> new_parent_actions = parent_actions;
new_parent_actions[player] = action;
BuildMDPs(*state_copy, new_reach_probs, new_parent_nodes,
new_parent_actions, only_for_player);
}
}
}
std::string TabularBestResponseMDP::GetNodeKey(const State &state,
Player player) const {
switch (game_.GetType().information) {
case GameType::Information::kImperfectInformation:
case GameType::Information::kOneShot:
return state.InformationStateString(player);
case GameType::Information::kPerfectInformation:
return state.ObservationString(player);
default:
SpielFatalError("Information type not supported.");
}
}
TabularBestResponseMDP::TabularBestResponseMDP(const Game &game,
const Policy &fixed_policy)
: game_(game), fixed_policy_(fixed_policy),
num_players_(game.NumPlayers()) {}
int TabularBestResponseMDP::TotalNumNonterminals() const {
int total_num_nonterminals = 0;
for (Player p = 0; p < num_players_; ++p) {
total_num_nonterminals += mdps_[p]->NumNonTerminalNodes();
}
return total_num_nonterminals;
}
int TabularBestResponseMDP::TotalSize() const {
int total_size = 0;
for (Player p = 0; p < num_players_; ++p) {
total_size += mdps_[p]->TotalSize();
}
return total_size;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::ComputeBestResponses() {
TabularBestResponseMDPInfo br_info(num_players_);
// Initialize IS-MDPs for each player, if necessary.
if (mdps_.empty()) {
for (Player p = 0; p < num_players_; p++) {
mdps_.push_back(absl::make_unique<MDP>());
}
}
std::vector<MDPNode *> parent_nodes;
parent_nodes.reserve(num_players_);
for (Player p = 0; p < num_players_; p++) {
parent_nodes.push_back(mdps_[p]->RootNode());
}
std::vector<double> reach_probs(num_players_ + 1, 1.0); // include chance.
std::vector<Action> parent_actions(num_players_, 0);
std::unique_ptr<State> initial_state = game_.NewInitialState();
BuildMDPs(*initial_state, reach_probs, parent_nodes, parent_actions);
for (Player p = 0; p < num_players_; p++) {
br_info.br_values[p] =
mdps_[p]->Solve(kSolveTolerance, &br_info.br_policies[p]);
}
return br_info;
}
TabularBestResponseMDPInfo
TabularBestResponseMDP::ComputeBestResponse(Player max_player) {
TabularBestResponseMDPInfo br_info(num_players_);
// TODO(author5): implement this.
SpielFatalError("Unimplemented.");
return br_info;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::NashConv() {
TabularBestResponseMDPInfo br_info = ComputeBestResponses();
std::unique_ptr<State> state = game_.NewInitialState();
br_info.on_policy_values =
ExpectedReturns(*state, fixed_policy_,
/*depth_limit*/ -1, /*use_infostate_get_policy*/ false);
for (Player p = 0; p < num_players_; ++p) {
br_info.deviation_incentives[p] =
br_info.br_values[p] - br_info.on_policy_values[p];
br_info.nash_conv += br_info.deviation_incentives[p];
}
return br_info;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::Exploitability() {
SPIEL_CHECK_TRUE(game_.GetType().utility == GameType::Utility::kZeroSum ||
game_.GetType().utility == GameType::Utility::kConstantSum);
TabularBestResponseMDPInfo br_info = ComputeBestResponses();
br_info.nash_conv = absl::c_accumulate(br_info.br_values, 0.0);
br_info.exploitability =
(br_info.nash_conv - game_.UtilitySum()) / num_players_;
return br_info;
}
} // namespace algorithms
} // namespace open_spiel
|
// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/algorithms/tabular_best_response_mdp.h"
#include <cmath>
#include <limits>
#include <numeric>
#include <string>
#include <utility>
#include "open_spiel/abseil-cpp/absl/algorithm/container.h"
#include "open_spiel/abseil-cpp/absl/memory/memory.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/algorithms/expected_returns.h"
#include "open_spiel/policy.h"
#include "open_spiel/simultaneous_move_game.h"
#include "open_spiel/spiel_globals.h"
namespace open_spiel {
namespace algorithms {
namespace {
constexpr double kSolveTolerance = 1e-12;
} // namespace
MDPNode::MDPNode(const std::string& node_key)
: terminal_(false), total_weight_(0), children_(), value_(0),
node_key_(node_key) {}
void MDPNode::IncTransitionWeight(Action a, MDPNode *child, double weight) {
SPIEL_CHECK_TRUE(child != nullptr);
children_[a][child] += weight;
}
MDP::MDP() : terminal_node_uid_(0), num_nonterminal_nodes_(0) {
node_map_[kRootKey] = absl::make_unique<MDPNode>(std::string(kRootKey));
node_map_[kRootKey]->add_weight(1.0);
}
MDPNode *MDP::CreateTerminalNode(const std::string &node_key) {
++terminal_node_uid_;
MDPNode *terminal_node = LookupOrCreateNode(node_key, true);
terminal_node->set_terminal(true);
return terminal_node;
}
MDPNode *MDP::LookupOrCreateNode(const std::string &node_key, bool terminal) {
const auto &iter = node_map_.find(node_key);
if (iter != node_map_.end()) {
return iter->second.get();
} else {
MDPNode *new_node = new MDPNode(node_key);
node_map_[node_key].reset(new_node);
if (!terminal) {
num_nonterminal_nodes_++;
}
return new_node;
}
}
double MDP::Solve(double tolerance, TabularPolicy *br_policy) {
double delta = 0;
do {
delta = 0.0;
for (auto &key_and_node : node_map_) {
MDPNode *node = key_and_node.second.get();
if (node->terminal()) {
continue;
}
double max_value = -std::numeric_limits<double>::infinity();
Action max_action = kInvalidAction;
double node_weight = node->total_weight();
SPIEL_CHECK_GE(node_weight, 0.0);
// Compute Bellman value from children.
for (const auto &action_and_child : node->children()) {
double action_value = 0.0;
Action action = action_and_child.first;
for (auto &child_value : node->children()[action]) {
MDPNode *child = child_value.first;
double transition_weight = child_value.second;
SPIEL_CHECK_TRUE(child != nullptr);
double prob = transition_weight / node_weight;
if (std::isnan(prob)) {
// When transition_weight = node_weight = 0, set to 0
prob = 0.0;
}
SPIEL_CHECK_PROB(prob);
action_value += prob * child->value();
}
if (action_value > max_value) {
max_value = action_value;
max_action = action;
}
}
SPIEL_CHECK_NE(max_action, kInvalidAction);
delta += std::abs(node->value() - max_value);
node->set_value(max_value);
// Set the best response to the maximum-value action, if it's non-null.
if (node->node_key() != kRootKey) {
ActionsAndProbs br_state_policy;
for (const auto &[action, child] : node->children()) {
SetProb(&br_state_policy, action, action == max_action ? 1.0 : 0.0);
}
br_policy->SetStatePolicy(node->node_key(), br_state_policy);
}
}
} while (delta > tolerance);
return RootNode()->value();
}
double
TabularBestResponseMDP::OpponentReach(const std::vector<double>& reach_probs,
Player p) const {
double product = 1.0;
for (int i = 0; i < reach_probs.size(); i++) {
if (p != i) {
product *= reach_probs[i];
}
}
return product;
}
void TabularBestResponseMDP::BuildMDPs(
const State &state, const std::vector<double>& reach_probs,
const std::vector<MDPNode*>& parent_nodes,
const std::vector<Action>& parent_actions, Player only_for_player) {
if (state.IsTerminal()) {
std::vector<double> terminal_values = state.Returns();
for (Player p = 0; p < game_.NumPlayers(); ++p) {
std::string node_key = state.ToString();
MDPNode *node = mdps_.at(p)->CreateTerminalNode(node_key);
node->set_value(terminal_values[p]);
double opponent_reach = OpponentReach(reach_probs, p);
SPIEL_CHECK_GE(opponent_reach, 0.0);
SPIEL_CHECK_LE(opponent_reach, 1.0);
// Following line is not actually necessary because the weight of a leaf
// is never in a denominator for a transition probability, btu we include
// it to keep the semantics of the values consistent across the ISMDP.
node->add_weight(opponent_reach);
MDPNode *parent_node = parent_nodes[p];
SPIEL_CHECK_TRUE(parent_node != nullptr);
parent_node->IncTransitionWeight(parent_actions[p], node, opponent_reach);
}
} else if (state.IsChanceNode()) {
ActionsAndProbs outcomes_and_probs = state.ChanceOutcomes();
for (const auto &[outcome, prob] : outcomes_and_probs) {
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(outcome);
std::vector<double> new_reach_probs = reach_probs;
// Chance prob is at the end of the vector.
new_reach_probs[game_.NumPlayers()] *= prob;
BuildMDPs(*state_copy, new_reach_probs, parent_nodes, parent_actions,
only_for_player);
}
} else if (state.IsSimultaneousNode()) {
// Several nodes are created: one for each player as the maximizer.
std::vector<std::string> node_keys;
std::vector<MDPNode*> nodes;
std::vector<double> opponent_reaches;
std::vector<ActionsAndProbs> fixed_state_policies;
node_keys.reserve(num_players_);
nodes.reserve(num_players_);
opponent_reaches.reserve(num_players_);
fixed_state_policies.reserve(num_players_);
for (Player player = 0; player < num_players_; ++player) {
node_keys.push_back(GetNodeKey(state, player));
nodes.push_back(mdps_.at(player)->LookupOrCreateNode(node_keys[player]));
opponent_reaches.push_back(OpponentReach(reach_probs, player));
fixed_state_policies.push_back(
fixed_policy_.GetStatePolicy(state, player));
SPIEL_CHECK_GE(opponent_reaches[player], 0.0);
SPIEL_CHECK_LE(opponent_reaches[player], 1.0);
nodes[player]->add_weight(opponent_reaches[player]);
MDPNode* parent_node = parent_nodes[player];
SPIEL_CHECK_TRUE(parent_node != nullptr);
parent_node->IncTransitionWeight(parent_actions[player], nodes[player],
opponent_reaches[player]);
}
// Traverse over the list of joint actions. For each one, first deconstruct
// the actions, and then recurse once for each player as the maximizer with
// the others as the fixed policies.
const auto& sim_move_state = down_cast<const SimMoveState&>(state);
for (Action joint_action : state.LegalActions()) {
std::vector<Action> actions =
sim_move_state.FlatJointActionToActions(joint_action);
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(joint_action);
std::vector<double> new_reach_probs = reach_probs;
std::vector<MDPNode*> new_parent_nodes = parent_nodes;
std::vector<Action> new_parent_actions = parent_actions;
for (Player player = 0; player < num_players_; ++player) {
double action_prob = GetProb(fixed_state_policies[player],
actions[player]);
SPIEL_CHECK_PROB(action_prob);
new_reach_probs[player] *= action_prob;
new_parent_nodes[player] = nodes[player];
new_parent_actions[player] = actions[player];
}
BuildMDPs(*state_copy, new_reach_probs, new_parent_nodes,
new_parent_actions, only_for_player);
}
} else {
// Normal decisions node.
std::vector<Action> legal_actions = state.LegalActions();
Player player = state.CurrentPlayer();
std::string node_key = GetNodeKey(state, player);
MDPNode *node = mdps_.at(player)->LookupOrCreateNode(node_key);
double opponent_reach = OpponentReach(reach_probs, player);
SPIEL_CHECK_GE(opponent_reach, 0.0);
SPIEL_CHECK_LE(opponent_reach, 1.0);
node->add_weight(opponent_reach);
MDPNode *parent_node = parent_nodes[player];
SPIEL_CHECK_TRUE(parent_node != nullptr);
parent_node->IncTransitionWeight(parent_actions[player], node,
opponent_reach);
ActionsAndProbs state_policy = fixed_policy_.GetStatePolicy(state);
for (Action action : legal_actions) {
std::unique_ptr<State> state_copy = state.Clone();
state_copy->ApplyAction(action);
std::vector<double> new_reach_probs = reach_probs;
double action_prob = GetProb(state_policy, action);
SPIEL_CHECK_PROB(action_prob);
new_reach_probs[player] *= action_prob;
std::vector<MDPNode *> new_parent_nodes = parent_nodes;
new_parent_nodes[player] = node;
std::vector<Action> new_parent_actions = parent_actions;
new_parent_actions[player] = action;
BuildMDPs(*state_copy, new_reach_probs, new_parent_nodes,
new_parent_actions, only_for_player);
}
}
}
std::string TabularBestResponseMDP::GetNodeKey(const State &state,
Player player) const {
switch (game_.GetType().information) {
case GameType::Information::kImperfectInformation:
case GameType::Information::kOneShot:
return state.InformationStateString(player);
case GameType::Information::kPerfectInformation:
return state.ObservationString(player);
default:
SpielFatalError("Information type not supported.");
}
}
TabularBestResponseMDP::TabularBestResponseMDP(const Game &game,
const Policy &fixed_policy)
: game_(game), fixed_policy_(fixed_policy),
num_players_(game.NumPlayers()) {}
int TabularBestResponseMDP::TotalNumNonterminals() const {
int total_num_nonterminals = 0;
for (Player p = 0; p < num_players_; ++p) {
total_num_nonterminals += mdps_[p]->NumNonTerminalNodes();
}
return total_num_nonterminals;
}
int TabularBestResponseMDP::TotalSize() const {
int total_size = 0;
for (Player p = 0; p < num_players_; ++p) {
total_size += mdps_[p]->TotalSize();
}
return total_size;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::ComputeBestResponses() {
TabularBestResponseMDPInfo br_info(num_players_);
// Initialize IS-MDPs for each player, if necessary.
if (mdps_.empty()) {
for (Player p = 0; p < num_players_; p++) {
mdps_.push_back(absl::make_unique<MDP>());
}
}
std::vector<MDPNode *> parent_nodes;
parent_nodes.reserve(num_players_);
for (Player p = 0; p < num_players_; p++) {
parent_nodes.push_back(mdps_[p]->RootNode());
}
std::vector<double> reach_probs(num_players_ + 1, 1.0); // include chance.
std::vector<Action> parent_actions(num_players_, 0);
std::unique_ptr<State> initial_state = game_.NewInitialState();
BuildMDPs(*initial_state, reach_probs, parent_nodes, parent_actions);
for (Player p = 0; p < num_players_; p++) {
br_info.br_values[p] =
mdps_[p]->Solve(kSolveTolerance, &br_info.br_policies[p]);
}
return br_info;
}
TabularBestResponseMDPInfo
TabularBestResponseMDP::ComputeBestResponse(Player max_player) {
TabularBestResponseMDPInfo br_info(num_players_);
// TODO(author5): implement this.
SpielFatalError("Unimplemented.");
return br_info;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::NashConv() {
TabularBestResponseMDPInfo br_info = ComputeBestResponses();
std::unique_ptr<State> state = game_.NewInitialState();
br_info.on_policy_values =
ExpectedReturns(*state, fixed_policy_,
/*depth_limit*/ -1, /*use_infostate_get_policy*/ false);
for (Player p = 0; p < num_players_; ++p) {
br_info.deviation_incentives[p] =
br_info.br_values[p] - br_info.on_policy_values[p];
br_info.nash_conv += br_info.deviation_incentives[p];
}
return br_info;
}
TabularBestResponseMDPInfo TabularBestResponseMDP::Exploitability() {
SPIEL_CHECK_TRUE(game_.GetType().utility == GameType::Utility::kZeroSum ||
game_.GetType().utility == GameType::Utility::kConstantSum);
TabularBestResponseMDPInfo br_info = ComputeBestResponses();
br_info.nash_conv = absl::c_accumulate(br_info.br_values, 0.0);
br_info.exploitability =
(br_info.nash_conv - game_.UtilitySum()) / num_players_;
return br_info;
}
} // namespace algorithms
} // namespace open_spiel
|
Fix https://github.com/deepmind/open_spiel/issues/577
|
Fix https://github.com/deepmind/open_spiel/issues/577
|
C++
|
apache-2.0
|
deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel,deepmind/open_spiel
|
cd66a11a30b81747f7aea053b55df279b3b31809
|
engine/renderers/RenderWorld.cpp
|
engine/renderers/RenderWorld.cpp
|
/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "RenderWorld.h"
#include "Device.h"
#include "Renderer.h"
#include "Allocator.h"
#include "Camera.h"
#include "Resource.h"
#include "Log.h"
#include "SpriteResource.h"
#include "Mesh.h"
#include "Sprite.h"
#include "Material.h"
#include "Config.h"
#include "Gui.h"
#include "GuiResource.h"
namespace crown
{
static const char* default_vertex =
"precision mediump float;"
"uniform mat4 u_model;"
"uniform mat4 u_model_view_projection;"
"attribute vec4 a_position;"
"attribute vec2 a_tex_coord0;"
"attribute vec4 a_color;"
"varying vec2 tex_coord0;"
"varying vec4 color;"
"void main(void)"
"{"
" tex_coord0 = a_tex_coord0;"
" color = a_color;"
" gl_Position = u_model_view_projection * a_position;"
"}";
static const char* default_fragment =
"precision mediump float;"
"void main(void)"
"{"
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);"
"}";
static const char* texture_fragment =
"precision mediump float;"
"varying vec2 tex_coord0;"
"varying vec4 color;"
"uniform sampler2D u_albedo_0;"
"void main(void)"
"{"
" gl_FragColor = texture2D(u_albedo_0, tex_coord0);"
"}";
//-----------------------------------------------------------------------------
RenderWorld::RenderWorld()
: m_mesh_pool(default_allocator(), MAX_MESHES, sizeof(Mesh), CE_ALIGNOF(Mesh))
, m_sprite_pool(default_allocator(), MAX_SPRITES, sizeof(Sprite), CE_ALIGNOF(Sprite))
, m_material_pool(default_allocator(), MAX_MATERIALS, sizeof(Material), CE_ALIGNOF(Material))
, m_gui_pool(default_allocator(), MAX_GUIS, sizeof(Gui), CE_ALIGNOF(Gui))
{
Renderer* r = device()->renderer();
m_default_vs = r->create_shader(ShaderType::VERTEX, default_vertex);
m_default_fs = r->create_shader(ShaderType::FRAGMENT, default_fragment);
m_texture_fs = r->create_shader(ShaderType::FRAGMENT, texture_fragment);
m_u_albedo_0 = r->create_uniform("u_albedo_0", UniformType::INTEGER_1, 1);
m_default_program = r->create_gpu_program(m_default_vs, m_default_fs);
m_texture_program = r->create_gpu_program(m_default_vs, m_texture_fs);
}
//-----------------------------------------------------------------------------
RenderWorld::~RenderWorld()
{
Renderer* r = device()->renderer();
r->destroy_gpu_program(m_texture_program);
r->destroy_gpu_program(m_default_program);
r->destroy_uniform(m_u_albedo_0);
r->destroy_shader(m_default_vs);
r->destroy_shader(m_default_fs);
r->destroy_shader(m_texture_fs);
}
//-----------------------------------------------------------------------------
MeshId RenderWorld::create_mesh(MeshResource* mr, SceneGraph& sg, int32_t node)
{
Mesh* mesh = CE_NEW(m_mesh_pool, Mesh)(sg, node, mr);
return m_mesh.create(mesh);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_mesh(MeshId id)
{
CE_ASSERT(m_mesh.has(id), "Mesh does not exist");
Mesh* mesh = m_mesh.lookup(id);
CE_DELETE(m_mesh_pool, mesh);
m_mesh.destroy(id);
}
//-----------------------------------------------------------------------------
Mesh* RenderWorld::lookup_mesh(MeshId mesh)
{
CE_ASSERT(m_mesh.has(mesh), "Mesh does not exits");
return m_mesh.lookup(mesh);
}
//-----------------------------------------------------------------------------
SpriteId RenderWorld::create_sprite(SpriteResource* sr, SceneGraph& sg, int32_t node)
{
Sprite* sprite = CE_NEW(m_sprite_pool, Sprite)(*this, sg, node, sr);
return m_sprite.create(sprite);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_sprite(SpriteId id)
{
CE_ASSERT(m_sprite.has(id), "Sprite does not exist");
Sprite* sprite = m_sprite.lookup(id);
CE_DELETE(m_sprite_pool, sprite);
m_sprite.destroy(id);
}
//-----------------------------------------------------------------------------
Sprite* RenderWorld::lookup_sprite(SpriteId id)
{
CE_ASSERT(m_sprite.has(id), "Sprite does not exist");
return m_sprite.lookup(id);
}
//-----------------------------------------------------------------------------
MaterialId RenderWorld::create_material(MaterialResource* mr)
{
Material* mat = CE_NEW(m_material_pool, Material)(mr);
return m_materials.create(mat);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_material(MaterialId id)
{
CE_DELETE(m_material_pool, m_materials.lookup(id));
m_materials.destroy(id);
}
//-----------------------------------------------------------------------------
Material* RenderWorld::lookup_material(MaterialId id)
{
return m_materials.lookup(id);
}
//-----------------------------------------------------------------------------
GuiId RenderWorld::create_gui(GuiResource* gr)
{
Renderer* r = device()->renderer();
Gui* gui = CE_NEW(m_gui_pool, Gui)(*this, gr, *r);
GuiId id = m_guis.create(gui);
gui->set_id(id);
return id;
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_gui(GuiId id)
{
CE_ASSERT(m_guis.has(id), "Gui does not exist");
CE_DELETE(m_gui_pool, m_guis.lookup(id));
m_guis.destroy(id);
}
//-----------------------------------------------------------------------------
Gui* RenderWorld::lookup_gui(GuiId id)
{
CE_ASSERT(m_guis.has(id), "Gui does not exist");
return m_guis.lookup(id);
}
//-----------------------------------------------------------------------------
void RenderWorld::update(const Matrix4x4& view, const Matrix4x4& projection, uint16_t x, uint16_t y, uint16_t width, uint16_t height, float dt)
{
Renderer* r = device()->renderer();
Matrix4x4 inv_view = view;
inv_view.invert();
r->set_layer_view(0, inv_view);
r->set_layer_projection(0, projection);
r->set_layer_viewport(0, x, y, width, height);
r->set_layer_clear(0, CLEAR_COLOR | CLEAR_DEPTH, Color4::LIGHTBLUE, 1.0f);
r->set_state(STATE_DEPTH_WRITE | STATE_COLOR_WRITE | STATE_CULL_CCW);
r->commit(0);
// Draw all meshes
for (uint32_t m = 0; m < m_mesh.size(); m++)
{
const Mesh* mesh = m_mesh.m_objects[m];
r->set_state(STATE_DEPTH_WRITE | STATE_COLOR_WRITE | STATE_ALPHA_WRITE | STATE_CULL_CW);
r->set_vertex_buffer(mesh->m_vbuffer);
r->set_index_buffer(mesh->m_ibuffer);
r->set_program(m_default_program);
// r->set_texture(0, m_u_albedo_0, grass_texture, TEXTURE_FILTER_LINEAR | TEXTURE_WRAP_CLAMP_EDGE);
// r->set_uniform(u_brightness, UNIFORM_FLOAT_1, &brightness, 1);
r->set_pose(mesh->world_pose());
r->commit(0);
}
// Draw all sprites
for (uint32_t s = 0; s < m_sprite.size(); s++)
{
r->set_program(m_texture_program);
m_sprite[s]->render(*r, m_u_albedo_0, dt);
}
// // Draw all guis
// for (uint32_t g = 0; g < m_guis.size(); g++)
// {
// m_guis[g]->render();
// }
}
} // namespace crown
|
/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "RenderWorld.h"
#include "Device.h"
#include "Renderer.h"
#include "Allocator.h"
#include "Camera.h"
#include "Resource.h"
#include "Log.h"
#include "SpriteResource.h"
#include "Mesh.h"
#include "Sprite.h"
#include "Material.h"
#include "Config.h"
#include "Gui.h"
#include "GuiResource.h"
namespace crown
{
static const char* default_vertex =
"precision mediump float;"
"uniform mat4 u_model;"
"uniform mat4 u_model_view_projection;"
"attribute vec4 a_position;"
"attribute vec2 a_tex_coord0;"
"attribute vec4 a_color;"
"varying vec2 tex_coord0;"
"varying vec4 color;"
"void main(void)"
"{"
" tex_coord0 = a_tex_coord0;"
" color = a_color;"
" gl_Position = u_model_view_projection * a_position;"
"}";
static const char* default_fragment =
"precision mediump float;"
"void main(void)"
"{"
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);"
"}";
static const char* texture_fragment =
"precision mediump float;"
"varying vec2 tex_coord0;"
"varying vec4 color;"
"uniform sampler2D u_albedo_0;"
"void main(void)"
"{"
" gl_FragColor = texture2D(u_albedo_0, tex_coord0);"
"}";
//-----------------------------------------------------------------------------
RenderWorld::RenderWorld()
: m_mesh_pool(default_allocator(), MAX_MESHES, sizeof(Mesh), CE_ALIGNOF(Mesh))
, m_sprite_pool(default_allocator(), MAX_SPRITES, sizeof(Sprite), CE_ALIGNOF(Sprite))
, m_material_pool(default_allocator(), MAX_MATERIALS, sizeof(Material), CE_ALIGNOF(Material))
, m_gui_pool(default_allocator(), MAX_GUIS, sizeof(Gui), CE_ALIGNOF(Gui))
{
Renderer* r = device()->renderer();
m_default_vs = r->create_shader(ShaderType::VERTEX, default_vertex);
m_default_fs = r->create_shader(ShaderType::FRAGMENT, default_fragment);
m_texture_fs = r->create_shader(ShaderType::FRAGMENT, texture_fragment);
m_u_albedo_0 = r->create_uniform("u_albedo_0", UniformType::INTEGER_1, 1);
m_default_program = r->create_gpu_program(m_default_vs, m_default_fs);
m_texture_program = r->create_gpu_program(m_default_vs, m_texture_fs);
}
//-----------------------------------------------------------------------------
RenderWorld::~RenderWorld()
{
Renderer* r = device()->renderer();
r->destroy_gpu_program(m_texture_program);
r->destroy_gpu_program(m_default_program);
r->destroy_uniform(m_u_albedo_0);
r->destroy_shader(m_default_vs);
r->destroy_shader(m_default_fs);
r->destroy_shader(m_texture_fs);
}
//-----------------------------------------------------------------------------
MeshId RenderWorld::create_mesh(MeshResource* mr, SceneGraph& sg, int32_t node)
{
Mesh* mesh = CE_NEW(m_mesh_pool, Mesh)(sg, node, mr);
return m_mesh.create(mesh);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_mesh(MeshId id)
{
CE_ASSERT(m_mesh.has(id), "Mesh does not exist");
Mesh* mesh = m_mesh.lookup(id);
CE_DELETE(m_mesh_pool, mesh);
m_mesh.destroy(id);
}
//-----------------------------------------------------------------------------
Mesh* RenderWorld::lookup_mesh(MeshId mesh)
{
CE_ASSERT(m_mesh.has(mesh), "Mesh does not exits");
return m_mesh.lookup(mesh);
}
//-----------------------------------------------------------------------------
SpriteId RenderWorld::create_sprite(SpriteResource* sr, SceneGraph& sg, int32_t node)
{
Sprite* sprite = CE_NEW(m_sprite_pool, Sprite)(*this, sg, node, sr);
return m_sprite.create(sprite);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_sprite(SpriteId id)
{
CE_ASSERT(m_sprite.has(id), "Sprite does not exist");
Sprite* sprite = m_sprite.lookup(id);
CE_DELETE(m_sprite_pool, sprite);
m_sprite.destroy(id);
}
//-----------------------------------------------------------------------------
Sprite* RenderWorld::lookup_sprite(SpriteId id)
{
CE_ASSERT(m_sprite.has(id), "Sprite does not exist");
return m_sprite.lookup(id);
}
//-----------------------------------------------------------------------------
MaterialId RenderWorld::create_material(MaterialResource* mr)
{
Material* mat = CE_NEW(m_material_pool, Material)(mr);
return m_materials.create(mat);
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_material(MaterialId id)
{
CE_DELETE(m_material_pool, m_materials.lookup(id));
m_materials.destroy(id);
}
//-----------------------------------------------------------------------------
Material* RenderWorld::lookup_material(MaterialId id)
{
return m_materials.lookup(id);
}
//-----------------------------------------------------------------------------
GuiId RenderWorld::create_gui(GuiResource* gr)
{
Renderer* r = device()->renderer();
Gui* gui = CE_NEW(m_gui_pool, Gui)(*this, gr, *r);
GuiId id = m_guis.create(gui);
gui->set_id(id);
return id;
}
//-----------------------------------------------------------------------------
void RenderWorld::destroy_gui(GuiId id)
{
CE_ASSERT(m_guis.has(id), "Gui does not exist");
CE_DELETE(m_gui_pool, m_guis.lookup(id));
m_guis.destroy(id);
}
//-----------------------------------------------------------------------------
Gui* RenderWorld::lookup_gui(GuiId id)
{
CE_ASSERT(m_guis.has(id), "Gui does not exist");
return m_guis.lookup(id);
}
//-----------------------------------------------------------------------------
void RenderWorld::update(const Matrix4x4& view, const Matrix4x4& projection, uint16_t x, uint16_t y, uint16_t width, uint16_t height, float dt)
{
Renderer* r = device()->renderer();
Matrix4x4 inv_view = view;
inv_view.invert();
r->set_layer_view(0, inv_view);
r->set_layer_projection(0, projection);
r->set_layer_viewport(0, x, y, width, height);
r->set_layer_clear(0, CLEAR_COLOR | CLEAR_DEPTH, Color4::LIGHTBLUE, 1.0f);
r->set_state(STATE_DEPTH_WRITE | STATE_COLOR_WRITE | STATE_CULL_CCW);
r->commit(0);
// Draw all meshes
for (uint32_t m = 0; m < m_mesh.size(); m++)
{
const Mesh* mesh = m_mesh.m_objects[m];
r->set_state(STATE_DEPTH_WRITE | STATE_COLOR_WRITE | STATE_ALPHA_WRITE | STATE_CULL_CW);
r->set_vertex_buffer(mesh->m_vbuffer);
r->set_index_buffer(mesh->m_ibuffer);
r->set_program(m_default_program);
// r->set_texture(0, m_u_albedo_0, grass_texture, TEXTURE_FILTER_LINEAR | TEXTURE_WRAP_CLAMP_EDGE);
// r->set_uniform(u_brightness, UNIFORM_FLOAT_1, &brightness, 1);
r->set_pose(mesh->world_pose());
r->commit(0);
}
// Draw all sprites
for (uint32_t s = 0; s < m_sprite.size(); s++)
{
r->set_program(m_texture_program);
m_sprite[s]->render(*r, m_u_albedo_0, dt);
}
// Draw all guis
for (uint32_t g = 0; g < m_guis.size(); g++)
{
m_guis[g]->render();
}
}
} // namespace crown
|
Enable rendering of GUI
|
Enable rendering of GUI
|
C++
|
mit
|
mikymod/crown,mikymod/crown,mikymod/crown,dbartolini/crown,galek/crown,mikymod/crown,dbartolini/crown,dbartolini/crown,taylor001/crown,taylor001/crown,galek/crown,dbartolini/crown,galek/crown,taylor001/crown,galek/crown,taylor001/crown
|
5e31ec604588b52db7439b76215b2c6d75f72031
|
gm/p3.cpp
|
gm/p3.cpp
|
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorSpace.h"
#include "SkColorSpaceXformSteps.h"
#include "SkString.h"
static void mark_good(SkCanvas* canvas, SkScalar x = 300, SkScalar y = 40) {
canvas->saveLayer(nullptr, nullptr);
SkPaint paint;
// A green circle.
paint.setColor(SkColorSetRGB(27, 158, 119));
canvas->drawCircle(x,y, 12, paint);
// Cut out a check mark.
paint.setBlendMode(SkBlendMode::kSrc);
paint.setColor(0x00000000);
paint.setStrokeWidth(2);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(x-6, y,
x-1, y+5, paint);
canvas->drawLine(x-1, y+5,
x+7, y-5, paint);
canvas->restore();
}
static void mark_bad(SkCanvas* canvas, SkScalar x = 300, SkScalar y = 40) {
canvas->saveLayer(nullptr, nullptr);
SkPaint paint;
// A red circle.
paint.setColor(SkColorSetRGB(231, 41, 138));
canvas->drawCircle(x,y, 12, paint);
// Cut out an 'X'.
paint.setBlendMode(SkBlendMode::kSrc);
paint.setColor(0x00000000);
paint.setStrokeWidth(2);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(x-5,y-5,
x+5,y+5, paint);
canvas->drawLine(x+5,y-5,
x-5,y+5, paint);
canvas->restore();
}
static bool nearly_equal(SkColor4f x, SkColor4f y) {
const float K = 0.01f;
return fabsf(x.fR - y.fR) < K
&& fabsf(x.fG - y.fG) < K
&& fabsf(x.fB - y.fB) < K
&& fabsf(x.fA - y.fA) < K;
}
static SkString fmt(SkColor4f c) {
return SkStringPrintf("%.2g %.2g %.2g %.2g", c.fR, c.fG, c.fB, c.fA);
}
static SkColor4f transform(SkColor4f c, SkColorSpace* src, SkColorSpace* dst) {
SkColorSpaceXformSteps(src, kUnpremul_SkAlphaType,
dst, kUnpremul_SkAlphaType).apply(c.vec());
return c;
}
DEF_SIMPLE_GM(p3, canvas, 320, 240) {
auto p3 = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
SkColorSpace::kDCIP3_D65_Gamut);
auto native = canvas->imageInfo().refColorSpace();
SkPaint text;
text.setAntiAlias(true);
// Draw a P3 red rectangle.
SkPaint paint;
paint.setColor4f({1,0,0,1}, p3.get());
canvas->drawRect({10,10,70,70}, SkPaint{});
canvas->drawRect({10,10,70,70}, paint);
// Read it back as floats in the color space of the canvas.
SkBitmap bm;
bm.allocPixels(SkImageInfo::Make(60,60, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType, native));
if (!canvas->readPixels(bm, 10,10)) {
canvas->drawString("can't readPixels() on this canvas :(", 100,20, text);
mark_good(canvas);
return;
}
// Let's look at one pixel and see if it matches the paint color.
SkColor4f pixel;
memcpy(&pixel, bm.getAddr(10,10), sizeof(pixel));
// We should see pixel represent the paint color faithfully in the canvas' native colorspace.
SkColor4f expected = transform(paint.getColor4f(), nullptr, native.get());
if (canvas->imageInfo().colorType() < kRGBA_F16_SkColorType) {
// We can't expect normalized formats to hold values outside [0,1].
expected = expected.pin();
}
if (canvas->imageInfo().colorType() == kGray_8_SkColorType) {
// Drawing into Gray8 is known to be maybe-totally broken.
// TODO: update expectation here to be {lum,lum,lum,1} if we fix Gray8.
expected = SkColor4f{NAN, NAN, NAN, 1};
}
if (nearly_equal(pixel, expected)) {
mark_good(canvas);
} else {
mark_bad(canvas);
}
struct {
const char* label;
SkColor4f color;
} lines[] = {
{"Native:" , pixel },
{"Expected:", expected },
{"P3:" , transform(pixel, native.get(), p3.get())},
};
SkAutoCanvasRestore saveRestore(canvas, true);
for (auto l : lines) {
canvas->drawString(l.label, 80,20, text);
canvas->drawString(fmt(l.color).c_str(), 140,20, text);
canvas->translate(0,20);
}
// TODO: draw P3 colors more ways
}
|
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkColorSpace.h"
#include "SkColorSpaceXformSteps.h"
#include "SkGradientShader.h"
#include "SkString.h"
template <typename Fn>
static void mark(SkCanvas* canvas, Fn&& fn) {
SkPaint alpha;
alpha.setAlpha(0x50);
canvas->saveLayer(nullptr, &alpha);
canvas->translate(140,40);
canvas->scale(2,2);
fn();
canvas->restore();
}
static void mark_good(SkCanvas* canvas) {
mark(canvas, [&]{
SkPaint paint;
// A green circle.
paint.setColor(SkColorSetRGB(27, 158, 119));
canvas->drawCircle(0,0, 12, paint);
// Cut out a check mark.
paint.setBlendMode(SkBlendMode::kSrc);
paint.setColor(0x00000000);
paint.setStrokeWidth(2);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(-6, 0,
-1, 5, paint);
canvas->drawLine(-1, +5,
+7, -5, paint);
});
}
static void mark_bad(SkCanvas* canvas) {
mark(canvas, [&] {
SkPaint paint;
// A red circle.
paint.setColor(SkColorSetRGB(231, 41, 138));
canvas->drawCircle(0,0, 12, paint);
// Cut out an 'X'.
paint.setBlendMode(SkBlendMode::kSrc);
paint.setColor(0x00000000);
paint.setStrokeWidth(2);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawLine(-5,-5,
+5,+5, paint);
canvas->drawLine(+5,-5,
-5,+5, paint);
});
}
static bool nearly_equal(SkColor4f x, SkColor4f y) {
const float K = 0.01f;
return fabsf(x.fR - y.fR) < K
&& fabsf(x.fG - y.fG) < K
&& fabsf(x.fB - y.fB) < K
&& fabsf(x.fA - y.fA) < K;
}
static SkString fmt(SkColor4f c) {
return SkStringPrintf("%.2g %.2g %.2g %.2g", c.fR, c.fG, c.fB, c.fA);
}
static SkColor4f transform(SkColor4f c, SkColorSpace* src, SkColorSpace* dst) {
SkColorSpaceXformSteps(src, kUnpremul_SkAlphaType,
dst, kUnpremul_SkAlphaType).apply(c.vec());
return c;
}
static void compare_pixel(const char* label,
SkCanvas* canvas, int x, int y,
SkColor4f color, SkColorSpace* cs) {
SkPaint text;
text.setAntiAlias(true);
auto canvas_cs = canvas->imageInfo().refColorSpace();
// I'm not really sure if this makes things easier or harder to follow,
// but we sniff the canvas to grab its current y-translate, so that (x,y)
// can be written in sort of chunk-relative terms.
const SkMatrix& m = canvas->getTotalMatrix();
SkASSERT(m.isTranslate());
SkScalar dy = m.getTranslateY();
SkASSERT(dy == (int)dy);
y += (int)dy;
SkBitmap bm;
bm.allocPixels(SkImageInfo::Make(1,1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType, canvas_cs));
if (!canvas->readPixels(bm, x,y)) {
mark_good(canvas);
canvas->drawString("can't readPixels() on this canvas :(", 100,20, text);
return;
}
SkColor4f pixel;
memcpy(&pixel, bm.getAddr(0,0), sizeof(pixel));
SkColor4f expected = transform(color,cs, canvas_cs.get());
if (canvas->imageInfo().colorType() < kRGBA_F16_SkColorType) {
// We can't expect normalized formats to hold values outside [0,1].
expected = expected.pin();
}
if (canvas->imageInfo().colorType() == kGray_8_SkColorType) {
// Drawing into Gray8 is known to be maybe-totally broken.
// TODO: update expectation here to be {lum,lum,lum,1} if we fix Gray8.
expected = SkColor4f{NAN, NAN, NAN, 1};
}
if (nearly_equal(pixel, expected)) {
mark_good(canvas);
} else {
mark_bad(canvas);
}
struct {
const char* label;
SkColor4f color;
} lines[] = {
{"Pixel:" , pixel },
{"Expected:", expected},
};
SkAutoCanvasRestore saveRestore(canvas, true);
canvas->drawString(label, 80,20, text);
for (auto l : lines) {
canvas->translate(0,20);
canvas->drawString(l.label, 80,20, text);
canvas->drawString(fmt(l.color).c_str(), 140,20, text);
}
}
DEF_SIMPLE_GM(p3, canvas, 450, 200) {
auto p3 = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
SkColorSpace::kDCIP3_D65_Gamut);
// Draw a P3 red rectangle and check the corner.
{
SkPaint paint;
paint.setColor4f({1,0,0,1}, p3.get());
canvas->drawRect({10,10,70,70}, SkPaint{});
canvas->drawRect({10,10,70,70}, paint);
compare_pixel("drawRect P3 red ",
canvas, 10,10,
{1,0,0,1}, p3.get());
}
canvas->translate(0,80);
// Draw a gradient from P3 red to P3 green, and check the corners.
{
SkPoint points[] = {{10.5,10.5}, {69.5,69.5}};
SkColor4f colors[] = {{1,0,0,1}, {0,1,0,1}};
SkPaint paint;
paint.setShader(SkGradientShader::MakeLinear(points, colors, p3,
nullptr, SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode));
canvas->drawRect({10,10,70,70}, SkPaint{});
canvas->drawRect({10,10,70,70}, paint);
canvas->save();
compare_pixel("gradient P3 red",
canvas, 10,10,
{1,0,0,1}, p3.get());
canvas->translate(180, 0);
compare_pixel("gradient P3 green",
canvas, 69,69,
{0,1,0,1}, p3.get());
canvas->restore();
}
// TODO: draw P3 colors more ways
}
|
add a linear gradient to P3 gm
|
add a linear gradient to P3 gm
I've tweaked the indicators into overlays so there can be one for each
pixel sampled. This lets me test both gradient corners.
I've dropped displaying the P3 value... not sure if it's as useful as
the other two, and I'm worried about information overload. There's
already a lot to look at.
Change-Id: I57a41c3af0162e8132e50c47a0b967714a57e9e5
Reviewed-on: https://skia-review.googlesource.com/154220
Commit-Queue: Brian Osman <[email protected]>
Reviewed-by: Brian Osman <[email protected]>
Auto-Submit: Mike Klein <[email protected]>
|
C++
|
bsd-3-clause
|
HalCanary/skia-hc,rubenvb/skia,google/skia,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,HalCanary/skia-hc,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,rubenvb/skia,HalCanary/skia-hc,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia
|
b9aaf5ef17154174ae0c8b0616c9821609f9856f
|
searchlib/src/vespa/searchlib/attribute/enumstore.cpp
|
searchlib/src/vespa/searchlib/attribute/enumstore.cpp
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "enumstore.hpp"
#include <vespa/vespalib/datastore/sharded_hash_map.h>
#include <vespa/vespalib/util/rcuvector.hpp>
#include <iomanip>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.enum_store");
namespace search {
template <>
void
EnumStoreT<const char*>::write_value(BufferWriter& writer, Index idx) const
{
const char* src = _store.get(idx);
size_t sz = strlen(src) + 1;
writer.write(src, sz);
}
template <>
ssize_t
EnumStoreT<const char*>::load_unique_value(const void* src, size_t available, Index& idx)
{
const char* value = static_cast<const char*>(src);
size_t slen = strlen(value);
size_t sz = slen + 1;
if (available < sz) {
return -1;
}
Index prev_idx = idx;
idx = _store.get_allocator().allocate(value);
if (prev_idx.valid()) {
auto cmp = make_comparator(value);
assert(cmp.less(prev_idx, Index()));
}
return sz;
}
std::unique_ptr<vespalib::datastore::IUniqueStoreDictionary>
make_enum_store_dictionary(IEnumStore &store, bool has_postings, const DictionaryConfig & dict_cfg,
std::unique_ptr<EntryComparator> compare,
std::unique_ptr<EntryComparator> folded_compare)
{
using NoBTreeDictionary = vespalib::datastore::NoBTreeDictionary;
using ShardedHashMap = vespalib::datastore::ShardedHashMap;
if (has_postings) {
if (folded_compare) {
return std::make_unique<EnumStoreFoldedDictionary>(store, std::move(compare), std::move(folded_compare));
} else {
switch (dict_cfg.getType()) {
case DictionaryConfig::Type::HASH:
return std::make_unique<EnumStoreDictionary<NoBTreeDictionary, ShardedHashMap>>(store, std::move(compare));
case DictionaryConfig::Type::BTREE_AND_HASH:
return std::make_unique<EnumStoreDictionary<EnumPostingTree, ShardedHashMap>>(store, std::move(compare));
default:
return std::make_unique<EnumStoreDictionary<EnumPostingTree>>(store, std::move(compare));
}
}
} else {
return std::make_unique<EnumStoreDictionary<EnumTree>>(store, std::move(compare));
}
}
}
namespace vespalib::datastore {
template class DataStoreT<search::IEnumStore::InternalIndex>;
}
namespace vespalib::btree {
template
class BTreeBuilder<search::IEnumStore::Index, BTreeNoLeafData, NoAggregated,
search::EnumTreeTraits::INTERNAL_SLOTS, search::EnumTreeTraits::LEAF_SLOTS>;
template
class BTreeBuilder<search::IEnumStore::Index, vespalib::datastore::EntryRef, NoAggregated,
search::EnumTreeTraits::INTERNAL_SLOTS, search::EnumTreeTraits::LEAF_SLOTS>;
}
namespace search {
template class EnumStoreT<const char*>;
template class EnumStoreT<int8_t>;
template class EnumStoreT<int16_t>;
template class EnumStoreT<int32_t>;
template class EnumStoreT<int64_t>;
template class EnumStoreT<float>;
template class EnumStoreT<double>;
} // namespace search
namespace vespalib {
template class RcuVectorBase<search::IEnumStore::Index>;
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "enumstore.hpp"
#include <vespa/vespalib/datastore/sharded_hash_map.h>
#include <vespa/vespalib/util/rcuvector.hpp>
#include <iomanip>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.enum_store");
namespace search {
template <>
void
EnumStoreT<const char*>::write_value(BufferWriter& writer, Index idx) const
{
const char* src = _store.get(idx);
size_t sz = strlen(src) + 1;
writer.write(src, sz);
}
template <>
ssize_t
EnumStoreT<const char*>::load_unique_value(const void* src, size_t available, Index& idx)
{
const char* value = static_cast<const char*>(src);
size_t slen = strlen(value);
size_t sz = slen + 1;
if (available < sz) {
return -1;
}
idx = _store.get_allocator().allocate(value);
return sz;
}
std::unique_ptr<vespalib::datastore::IUniqueStoreDictionary>
make_enum_store_dictionary(IEnumStore &store, bool has_postings, const DictionaryConfig & dict_cfg,
std::unique_ptr<EntryComparator> compare,
std::unique_ptr<EntryComparator> folded_compare)
{
using NoBTreeDictionary = vespalib::datastore::NoBTreeDictionary;
using ShardedHashMap = vespalib::datastore::ShardedHashMap;
if (has_postings) {
if (folded_compare) {
return std::make_unique<EnumStoreFoldedDictionary>(store, std::move(compare), std::move(folded_compare));
} else {
switch (dict_cfg.getType()) {
case DictionaryConfig::Type::HASH:
return std::make_unique<EnumStoreDictionary<NoBTreeDictionary, ShardedHashMap>>(store, std::move(compare));
case DictionaryConfig::Type::BTREE_AND_HASH:
return std::make_unique<EnumStoreDictionary<EnumPostingTree, ShardedHashMap>>(store, std::move(compare));
default:
return std::make_unique<EnumStoreDictionary<EnumPostingTree>>(store, std::move(compare));
}
}
} else {
return std::make_unique<EnumStoreDictionary<EnumTree>>(store, std::move(compare));
}
}
}
namespace vespalib::datastore {
template class DataStoreT<search::IEnumStore::InternalIndex>;
}
namespace vespalib::btree {
template
class BTreeBuilder<search::IEnumStore::Index, BTreeNoLeafData, NoAggregated,
search::EnumTreeTraits::INTERNAL_SLOTS, search::EnumTreeTraits::LEAF_SLOTS>;
template
class BTreeBuilder<search::IEnumStore::Index, vespalib::datastore::EntryRef, NoAggregated,
search::EnumTreeTraits::INTERNAL_SLOTS, search::EnumTreeTraits::LEAF_SLOTS>;
}
namespace search {
template class EnumStoreT<const char*>;
template class EnumStoreT<int8_t>;
template class EnumStoreT<int16_t>;
template class EnumStoreT<int32_t>;
template class EnumStoreT<int64_t>;
template class EnumStoreT<float>;
template class EnumStoreT<double>;
} // namespace search
namespace vespalib {
template class RcuVectorBase<search::IEnumStore::Index>;
}
|
Remove assert that no longer is valid.
|
Remove assert that no longer is valid.
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
aa4c6cb347153f9e878ac4f5299b72da0e63ee67
|
tutorials/dataframe/tdf009_FromScratchVSTTree.C
|
tutorials/dataframe/tdf009_FromScratchVSTTree.C
|
/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -nodraw
/// This tutorial illustrates how simpler it can be to use a
/// TDataFrame to create a dataset with respect to the usage
/// of the TTree interfaces.
///
/// \macro_code
///
/// \date August 2017
/// \author Danilo Piparo
// ## Preparation
void tdf009_FromScratchVSTTree() {
// ## Preparation
auto treeName = "myTree";
// ##This is the classic way
TFile f("tdf009_FromScratchVSTTree_classic.root", "RECREATE");
TTree t(treeName, treeName);
double b1;
int b2;
t.Branch("b1", &b1);
t.Branch("b2", &b2);
for (int i = 0; i < 10; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
// ## This is the TDataFrame way
// Few lines are needed to achieve the same result.
// Parallel creation of the TTree is not supported in the
// classic method.
ROOT::Experimental::TDataFrame tdf(10);
auto b = 0.;
tdf.Define("b1",[&b](){return b++;})
.Define("b2","(int) b1 * b1") // This can even be a string
.Snapshot(treeName, "tdf009_FromScratchVSTTree_tdf.root");
}
|
/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -nodraw
/// This tutorial illustrates how simpler it can be to use a
/// TDataFrame to create a dataset with respect to the usage
/// of the TTree interfaces.
///
/// \macro_code
///
/// \date August 2017
/// \author Danilo Piparo
// ##This is the classic way of creating a ROOT dataset
// The steps are:
// - Create a file
// - Create a tree associated to the file
// - Define the variables to write in the entries
// - Define the branches associated to those variables
// - Write the event loop to set the right value to the variables
// - Call TTree::Fill to save the value of the variables
// - Write the TTree
// - Close the file
void classicWay()
{
TFile f("tdf009_FromScratchVSTTree_classic.root", "RECREATE");
TTree t("treeName", "treeName");
double b1;
int b2;
t.Branch("b1", &b1);
t.Branch("b2", &b2);
for (int i = 0; i < 10; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
}
// ##This is the TDF way of creating a ROOT dataset
// Few lines are needed to achieve the same result.
// Parallel creation of the TTree is not supported in the
// classic method.
// In this case the steps are:
// - Create an empty TDataFrame
// - If needed, define variables for the functions used to fill the branches
// - Create new columns expressing their content with lambdas, functors, functions or strings
// - Invoke the Snapshot action
//
// Parallelism is not the only advantage. Starting from an existing dataset and
// filter it, enrich it with new columns, leave aside some other columns and
// write a new dataset becomes very easy to do.
void TDFWay()
{
ROOT::Experimental::TDataFrame tdf(10);
auto b = 0.;
tdf.Define("b1",[&b](){return b++;})
.Define("b2","(int) b1 * b1") // This can even be a string
.Snapshot("treeName", "tdf009_FromScratchVSTTree_tdf.root");
}
void tdf009_FromScratchVSTTree() {
classicWay();
TDFWay();
}
|
Add to the TDF vs TTree tutorial more explainations
|
[TDF] Add to the TDF vs TTree tutorial more explainations
and more context and a clearer structure (thanks Axel for the feedback!)
|
C++
|
lgpl-2.1
|
karies/root,karies/root,karies/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,root-mirror/root,karies/root,karies/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,root-mirror/root,olifre/root,olifre/root,karies/root,zzxuanyuan/root,karies/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,karies/root,zzxuanyuan/root,karies/root,olifre/root,zzxuanyuan/root,olifre/root,olifre/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,zzxuanyuan/root,karies/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root
|
cbe4cb648cd71ac0dab89050f75eff44530d1894
|
views/examples/example_base.cc
|
views/examples/example_base.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/examples/example_base.h"
#include <stdarg.h>
#include <string>
#include "base/string_util.h"
#include "views/controls/button/text_button.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/examples/examples_main.h"
namespace {
using views::View;
// Some of GTK based view classes require WidgetGTK in the view
// parent chain. This class is used to defer the creation of such
// views until a WidgetGTK is added to the view hierarchy.
class ContainerView : public View {
public:
explicit ContainerView(examples::ExampleBase* base)
: example_view_created_(false),
example_base_(base) {
}
protected:
// views::View overrides:
virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
View::ViewHierarchyChanged(is_add, parent, child);
// We're not using child == this because a Widget may not be
// availalbe when this is added to the hierarchy.
if (is_add && GetWidget() && !example_view_created_) {
example_view_created_ = true;
example_base_->CreateExampleView(this);
}
}
private:
// true if the example view has already been created, or false otherwise.
bool example_view_created_;
examples::ExampleBase* example_base_;
DISALLOW_COPY_AND_ASSIGN(ContainerView);
};
} // namespace
namespace examples {
ExampleBase::ExampleBase(ExamplesMain* main)
: main_(main) {
container_ = new ContainerView(this);
}
// Prints a message in the status area, at the bottom of the window.
void ExampleBase::PrintStatus(const wchar_t* format, ...) {
va_list ap;
va_start(ap, format);
std::wstring msg;
StringAppendV(&msg, format, ap);
main_->SetStatus(msg);
}
} // namespace examples
|
// 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 "views/examples/example_base.h"
#include <stdarg.h>
#include <string>
#include "base/string_util.h"
#include "views/controls/button/text_button.h"
#include "views/controls/tabbed_pane/tabbed_pane.h"
#include "views/examples/examples_main.h"
#if defined(OS_CHROMEOS)
#include "views/controls/menu/native_menu_gtk.h"
#endif
namespace {
using views::View;
// Some of GTK based view classes require WidgetGTK in the view
// parent chain. This class is used to defer the creation of such
// views until a WidgetGTK is added to the view hierarchy.
class ContainerView : public View {
public:
explicit ContainerView(examples::ExampleBase* base)
: example_view_created_(false),
example_base_(base) {
}
protected:
// views::View overrides:
virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
View::ViewHierarchyChanged(is_add, parent, child);
// We're not using child == this because a Widget may not be
// availalbe when this is added to the hierarchy.
if (is_add && GetWidget() && !example_view_created_) {
example_view_created_ = true;
example_base_->CreateExampleView(this);
}
}
private:
// true if the example view has already been created, or false otherwise.
bool example_view_created_;
examples::ExampleBase* example_base_;
DISALLOW_COPY_AND_ASSIGN(ContainerView);
};
} // namespace
namespace views {
// OS_CHROMEOS requires a MenuWrapper::CreateWrapper implementation.
// TODO(oshima): Fix chromium-os:7409 so that this isn't required.
#if defined(OS_CHROMEOS)
// static
MenuWrapper* MenuWrapper::CreateWrapper(Menu2* menu) {
return new NativeMenuGtk(menu);
}
#endif // OS_CHROMEOS
} // namespace views
namespace examples {
ExampleBase::ExampleBase(ExamplesMain* main)
: main_(main) {
container_ = new ContainerView(this);
}
// Prints a message in the status area, at the bottom of the window.
void ExampleBase::PrintStatus(const wchar_t* format, ...) {
va_list ap;
va_start(ap, format);
std::wstring msg;
StringAppendV(&msg, format, ap);
main_->SetStatus(msg);
}
} // namespace examples
|
Add CreateWrapper to views/examples/examples_base.cc
|
Add CreateWrapper to views/examples/examples_base.cc
Necessary for view_examples to compile with GYP_DEFINES="chromeos=1".
BUG=http://code.google.com/p/chromium-os/issues/detail?id=7409 (temporary fix)
TEST=build all in chrome repo with chromeos=1
Review URL: http://codereview.chromium.org/3614008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@61691 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,Chilledheart/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,rogerwang/chromium,chuan9/chromium-crosswalk,robclark/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,dushu1203/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,rogerwang/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,dednal/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,M4sse/chromium.src,robclark/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,robclark/chromium,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,jaruba/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,keishi/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,rogerwang/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ltilve/chromium,markYoungH/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,keishi/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,markYoungH/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Chilledheart/chromium,dednal/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,robclark/chromium,fujunwei/chromium-crosswalk,keishi/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,keishi/chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,patrickm/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,robclark/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,M4sse/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,Chilledheart/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,keishi/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,robclark/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,rogerwang/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,keishi/chromium,jaruba/chromium.src,Jonekee/chromium.src,robclark/chromium,nacl-webkit/chrome_deps,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,Chilledheart/chromium,robclark/chromium,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,patrickm/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,Chilledheart/chromium,anirudhSK/chromium,keishi/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,ltilve/chromium,markYoungH/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk
|
45c33e9dcfb215493e31dc53a068b5dd1860a367
|
machxo2/bitstream.cc
|
machxo2/bitstream.cc
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 gatecat <[email protected]>
* Copyright (C) 2021 William D. Jones <[email protected]>
*
* Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 <fstream>
#include "bitstream.h"
#include "config.h"
#include "nextpnr.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
// These seem simple enough to do inline for now.
namespace BaseConfigs {
void config_empty_lcmxo2_1200hc(ChipConfig &cc)
{
cc.chip_name = "LCMXO2-1200HC";
cc.tiles["EBR_R6C11:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C15:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C18:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C21:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C2:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C5:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C8:EBR1"].add_unknown(0, 12);
cc.tiles["PT4:CFG0"].add_unknown(5, 30);
cc.tiles["PT4:CFG0"].add_unknown(5, 32);
cc.tiles["PT4:CFG0"].add_unknown(5, 36);
cc.tiles["PT7:CFG3"].add_unknown(5, 18);
}
} // namespace BaseConfigs
// Convert an absolute wire name to a relative Trellis one
static std::string get_trellis_wirename(Context *ctx, Location loc, WireId wire)
{
std::string basename = ctx->tile_info(wire)->wire_data[wire.index].name.get();
std::string prefix2 = basename.substr(0, 2);
std::string prefix7 = basename.substr(0, 7);
int max_col = ctx->chip_info->width - 1;
// Handle MachXO2's wonderful naming quirks for wires in left/right tiles, whose
// relative coords push them outside the bounds of the chip.
auto is_pio_wire = [](std::string name) {
return (name.find("DI") != std::string::npos || name.find("JDI") != std::string::npos ||
name.find("PADD") != std::string::npos || name.find("INDD") != std::string::npos ||
name.find("IOLDO") != std::string::npos || name.find("IOLTO") != std::string::npos ||
name.find("JCE") != std::string::npos || name.find("JCLK") != std::string::npos ||
name.find("JLSR") != std::string::npos || name.find("JONEG") != std::string::npos ||
name.find("JOPOS") != std::string::npos || name.find("JTS") != std::string::npos ||
name.find("JIN") != std::string::npos || name.find("JIP") != std::string::npos ||
// Connections to global mux
name.find("JINCK") != std::string::npos);
};
if (prefix2 == "G_" || prefix2 == "L_" || prefix2 == "R_" || prefix7 == "BRANCH_")
return basename;
if (prefix2 == "U_" || prefix2 == "D_") {
// We needded to keep U_ and D_ prefixes to generate the routing
// graph connections properly, but in truth they are not relevant
// outside of the center row of tiles as far as the database is
// concerned. So convert U_/D_ prefixes back to G_ if not in the
// center row.
// FIXME: This is hardcoded to 1200HC coordinates for now. Perhaps
// add a center row/col field to chipdb?
if (loc.y == 6)
return basename;
else
return "G_" + basename.substr(2);
}
if (loc == wire.location) {
// TODO: JINCK is not currently handled by this.
if (is_pio_wire(basename)) {
if (wire.location.x == 0)
return "W1_" + basename;
else if (wire.location.x == max_col)
return "E1_" + basename;
}
return basename;
}
std::string rel_prefix;
if (wire.location.y < loc.y)
rel_prefix += "N" + std::to_string(loc.y - wire.location.y);
if (wire.location.y > loc.y)
rel_prefix += "S" + std::to_string(wire.location.y - loc.y);
if (wire.location.x > loc.x)
rel_prefix += "E" + std::to_string(wire.location.x - loc.x);
if (wire.location.x < loc.x)
rel_prefix += "W" + std::to_string(loc.x - wire.location.x);
return rel_prefix + "_" + basename;
}
static void set_pip(Context *ctx, ChipConfig &cc, PipId pip)
{
std::string tile = ctx->get_pip_tilename(pip);
std::string source = get_trellis_wirename(ctx, pip.location, ctx->getPipSrcWire(pip));
std::string sink = get_trellis_wirename(ctx, pip.location, ctx->getPipDstWire(pip));
cc.tiles[tile].add_arc(sink, source);
}
static std::vector<bool> int_to_bitvector(int val, int size)
{
std::vector<bool> bv;
for (int i = 0; i < size; i++) {
bv.push_back((val & (1 << i)) != 0);
}
return bv;
}
std::string intstr_or_default(const dict<IdString, Property> &ct, const IdString &key, std::string def = "0")
{
auto found = ct.find(key);
if (found == ct.end())
return def;
else {
if (found->second.is_string)
return found->second.as_string();
else
return std::to_string(found->second.as_int64());
}
};
// Get the PIC tile corresponding to a PIO bel
static std::string get_pic_tile(Context *ctx, BelId bel)
{
static const std::set<std::string> pio_l = {"PIC_L0", "PIC_LS0", "PIC_L0_VREF3"};
static const std::set<std::string> pio_r = {"PIC_R0", "PIC_RS0"};
std::string pio_name = ctx->tile_info(bel)->bel_data[bel.index].name.get();
if (bel.location.y == 0) {
return ctx->get_tile_by_type_and_loc(0, bel.location.x, "PIC_T0");
} else if (bel.location.y == ctx->chip_info->height - 1) {
return ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, "PIC_B0");
} else if (bel.location.x == 0) {
return ctx->get_tile_by_type_and_loc(bel.location.y, 0, pio_l);
} else if (bel.location.x == ctx->chip_info->width - 1) {
return ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, pio_r);
} else {
NPNR_ASSERT_FALSE("bad PIO location");
}
}
void write_bitstream(Context *ctx, std::string text_config_file)
{
ChipConfig cc;
switch (ctx->args.type) {
case ArchArgs::LCMXO2_1200HC:
BaseConfigs::config_empty_lcmxo2_1200hc(cc);
break;
default:
NPNR_ASSERT_FALSE("Unsupported device type");
}
cc.metadata.push_back("Part: " + ctx->get_full_chip_name());
// Add all set, configurable pips to the config
for (auto pip : ctx->getPips()) {
if (ctx->getBoundPipNet(pip) != nullptr) {
if (ctx->get_pip_class(pip) == 0) { // ignore fixed pips
set_pip(ctx, cc, pip);
}
}
}
// TODO: Bank Voltages
// Configure slices
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (ci->bel == BelId()) {
log_warning("found unplaced cell '%s' during bitstream gen. Not writing to bitstream.\n",
ci->name.c_str(ctx));
continue;
}
BelId bel = ci->bel;
if (ci->type == id_FACADE_SLICE) {
std::string tname = ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, "PLC");
std::string slice = ctx->tile_info(bel)->bel_data[bel.index].name.get();
NPNR_ASSERT(slice.substr(0, 5) == "SLICE");
int int_index = slice[5] - 'A';
NPNR_ASSERT(int_index >= 0 && int_index < 4);
int lut0_init = int_or_default(ci->params, ctx->id("LUT0_INITVAL"));
int lut1_init = int_or_default(ci->params, ctx->id("LUT1_INITVAL"));
cc.tiles[tname].add_word(slice + ".K0.INIT", int_to_bitvector(lut0_init, 16));
cc.tiles[tname].add_word(slice + ".K1.INIT", int_to_bitvector(lut1_init, 16));
cc.tiles[tname].add_enum(slice + ".MODE", str_or_default(ci->params, ctx->id("MODE"), "LOGIC"));
cc.tiles[tname].add_enum(slice + ".GSR", str_or_default(ci->params, ctx->id("GSR"), "ENABLED"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".SRMODE",
str_or_default(ci->params, ctx->id("SRMODE"), "LSR_OVER_CE"));
cc.tiles[tname].add_enum(slice + ".CEMUX", intstr_or_default(ci->params, ctx->id("CEMUX"), "1"));
cc.tiles[tname].add_enum("CLK" + std::to_string(int_index) + ".CLKMUX",
intstr_or_default(ci->params, ctx->id("CLKMUX"), "0"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".LSRMUX",
str_or_default(ci->params, ctx->id("LSRMUX"), "LSR"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".LSRONMUX",
intstr_or_default(ci->params, ctx->id("LSRONMUX"), "LSRMUX"));
cc.tiles[tname].add_enum(slice + ".REGMODE", str_or_default(ci->params, ctx->id("REGMODE"), "FF"));
cc.tiles[tname].add_enum(slice + ".REG0.SD", intstr_or_default(ci->params, ctx->id("REG0_SD"), "0"));
cc.tiles[tname].add_enum(slice + ".REG1.SD", intstr_or_default(ci->params, ctx->id("REG1_SD"), "0"));
cc.tiles[tname].add_enum(slice + ".REG0.REGSET",
str_or_default(ci->params, ctx->id("REG0_REGSET"), "RESET"));
cc.tiles[tname].add_enum(slice + ".REG1.REGSET",
str_or_default(ci->params, ctx->id("REG1_REGSET"), "RESET"));
} else if (ci->type == ctx->id("FACADE_IO")) {
std::string pio = ctx->tile_info(bel)->bel_data[bel.index].name.get();
std::string iotype = str_or_default(ci->attrs, ctx->id("IO_TYPE"), "LVCMOS33");
std::string dir = str_or_default(ci->params, ctx->id("DIR"), "INPUT");
std::string pic_tile = get_pic_tile(ctx, bel);
cc.tiles[pic_tile].add_enum(pio + ".BASE_TYPE", dir + "_" + iotype);
} else if (ci->type == ctx->id("OSCH")) {
std::string freq = str_or_default(ci->params, ctx->id("NOM_FREQ"), "2.08");
cc.tiles[ctx->get_tile_by_type("CFG1")].add_enum("OSCH.MODE", "OSCH");
cc.tiles[ctx->get_tile_by_type("CFG1")].add_enum("OSCH.NOM_FREQ", freq);
}
}
// Configure chip
if (!text_config_file.empty()) {
std::ofstream out_config(text_config_file);
out_config << cc;
}
}
NEXTPNR_NAMESPACE_END
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 gatecat <[email protected]>
* Copyright (C) 2021 William D. Jones <[email protected]>
*
* Permission to use, copy, modify, and/or 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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 <fstream>
#include "bitstream.h"
#include "config.h"
#include "nextpnr.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
// These seem simple enough to do inline for now.
namespace BaseConfigs {
void config_empty_lcmxo2_1200hc(ChipConfig &cc)
{
cc.chip_name = "LCMXO2-1200HC";
cc.tiles["EBR_R6C11:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C15:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C18:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C21:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C2:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C5:EBR1"].add_unknown(0, 12);
cc.tiles["EBR_R6C8:EBR1"].add_unknown(0, 12);
cc.tiles["PT4:CFG0"].add_unknown(5, 30);
cc.tiles["PT4:CFG0"].add_unknown(5, 32);
cc.tiles["PT4:CFG0"].add_unknown(5, 36);
cc.tiles["PT7:CFG3"].add_unknown(5, 18);
}
} // namespace BaseConfigs
// Convert an absolute wire name to a relative Trellis one
static std::string get_trellis_wirename(Context *ctx, Location loc, WireId wire)
{
std::string basename = ctx->tile_info(wire)->wire_data[wire.index].name.get();
std::string prefix2 = basename.substr(0, 2);
std::string prefix7 = basename.substr(0, 7);
int max_col = ctx->chip_info->width - 1;
// Handle MachXO2's wonderful naming quirks for wires in left/right tiles, whose
// relative coords push them outside the bounds of the chip.
auto is_pio_wire = [](std::string name) {
return (name.find("DI") != std::string::npos || name.find("JDI") != std::string::npos ||
name.find("PADD") != std::string::npos || name.find("INDD") != std::string::npos ||
name.find("IOLDO") != std::string::npos || name.find("IOLTO") != std::string::npos ||
name.find("JCE") != std::string::npos || name.find("JCLK") != std::string::npos ||
name.find("JLSR") != std::string::npos || name.find("JONEG") != std::string::npos ||
name.find("JOPOS") != std::string::npos || name.find("JTS") != std::string::npos ||
name.find("JIN") != std::string::npos || name.find("JIP") != std::string::npos ||
// Connections to global mux
name.find("JINCK") != std::string::npos);
};
if (prefix2 == "G_" || prefix2 == "L_" || prefix2 == "R_" || prefix7 == "BRANCH_")
return basename;
if (prefix2 == "U_" || prefix2 == "D_") {
// We needded to keep U_ and D_ prefixes to generate the routing
// graph connections properly, but in truth they are not relevant
// outside of the center row of tiles as far as the database is
// concerned. So convert U_/D_ prefixes back to G_ if not in the
// center row.
// FIXME: This is hardcoded to 1200HC coordinates for now. Perhaps
// add a center row/col field to chipdb?
if (loc.y == 6)
return basename;
else
return "G_" + basename.substr(2);
}
if (loc == wire.location) {
// TODO: JINCK is not currently handled by this.
if (is_pio_wire(basename)) {
if (wire.location.x == 0)
return "W1_" + basename;
else if (wire.location.x == max_col)
return "E1_" + basename;
}
return basename;
}
std::string rel_prefix;
if (wire.location.y < loc.y)
rel_prefix += "N" + std::to_string(loc.y - wire.location.y);
if (wire.location.y > loc.y)
rel_prefix += "S" + std::to_string(wire.location.y - loc.y);
if (wire.location.x > loc.x)
rel_prefix += "E" + std::to_string(wire.location.x - loc.x);
if (wire.location.x < loc.x)
rel_prefix += "W" + std::to_string(loc.x - wire.location.x);
return rel_prefix + "_" + basename;
}
static void set_pip(Context *ctx, ChipConfig &cc, PipId pip)
{
std::string tile = ctx->get_pip_tilename(pip);
std::string tile_type = ctx->chip_info->tiletype_names[ctx->tile_info(pip)->pips_data[pip.index].tile_type].get();
std::string source = get_trellis_wirename(ctx, pip.location, ctx->getPipSrcWire(pip));
std::string sink = get_trellis_wirename(ctx, pip.location, ctx->getPipDstWire(pip));
cc.tiles[tile].add_arc(sink, source);
// Special case pips whose config bits are spread across tiles.
if (source == "G_PCLKCIBVIQT0" && sink == "G_VPRXCLKI0") {
if (tile_type == "CENTER7") {
cc.tiles[ctx->get_tile_by_type("CENTER8")].add_arc(sink, source);
} else if (tile_type == "CENTER8") {
cc.tiles[ctx->get_tile_by_type("CENTER7")].add_arc(sink, source);
} else {
NPNR_ASSERT_FALSE("Tile does not contain special-cased pip");
}
}
}
static std::vector<bool> int_to_bitvector(int val, int size)
{
std::vector<bool> bv;
for (int i = 0; i < size; i++) {
bv.push_back((val & (1 << i)) != 0);
}
return bv;
}
std::string intstr_or_default(const dict<IdString, Property> &ct, const IdString &key, std::string def = "0")
{
auto found = ct.find(key);
if (found == ct.end())
return def;
else {
if (found->second.is_string)
return found->second.as_string();
else
return std::to_string(found->second.as_int64());
}
};
// Get the PIC tile corresponding to a PIO bel
static std::string get_pic_tile(Context *ctx, BelId bel)
{
static const std::set<std::string> pio_l = {"PIC_L0", "PIC_LS0", "PIC_L0_VREF3"};
static const std::set<std::string> pio_r = {"PIC_R0", "PIC_RS0"};
std::string pio_name = ctx->tile_info(bel)->bel_data[bel.index].name.get();
if (bel.location.y == 0) {
return ctx->get_tile_by_type_and_loc(0, bel.location.x, "PIC_T0");
} else if (bel.location.y == ctx->chip_info->height - 1) {
return ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, "PIC_B0");
} else if (bel.location.x == 0) {
return ctx->get_tile_by_type_and_loc(bel.location.y, 0, pio_l);
} else if (bel.location.x == ctx->chip_info->width - 1) {
return ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, pio_r);
} else {
NPNR_ASSERT_FALSE("bad PIO location");
}
}
void write_bitstream(Context *ctx, std::string text_config_file)
{
ChipConfig cc;
switch (ctx->args.type) {
case ArchArgs::LCMXO2_1200HC:
BaseConfigs::config_empty_lcmxo2_1200hc(cc);
break;
default:
NPNR_ASSERT_FALSE("Unsupported device type");
}
cc.metadata.push_back("Part: " + ctx->get_full_chip_name());
// Add all set, configurable pips to the config
for (auto pip : ctx->getPips()) {
if (ctx->getBoundPipNet(pip) != nullptr) {
if (ctx->get_pip_class(pip) == 0) { // ignore fixed pips
set_pip(ctx, cc, pip);
}
}
}
// TODO: Bank Voltages
// Configure slices
for (auto &cell : ctx->cells) {
CellInfo *ci = cell.second.get();
if (ci->bel == BelId()) {
log_warning("found unplaced cell '%s' during bitstream gen. Not writing to bitstream.\n",
ci->name.c_str(ctx));
continue;
}
BelId bel = ci->bel;
if (ci->type == id_FACADE_SLICE) {
std::string tname = ctx->get_tile_by_type_and_loc(bel.location.y, bel.location.x, "PLC");
std::string slice = ctx->tile_info(bel)->bel_data[bel.index].name.get();
NPNR_ASSERT(slice.substr(0, 5) == "SLICE");
int int_index = slice[5] - 'A';
NPNR_ASSERT(int_index >= 0 && int_index < 4);
int lut0_init = int_or_default(ci->params, ctx->id("LUT0_INITVAL"));
int lut1_init = int_or_default(ci->params, ctx->id("LUT1_INITVAL"));
cc.tiles[tname].add_word(slice + ".K0.INIT", int_to_bitvector(lut0_init, 16));
cc.tiles[tname].add_word(slice + ".K1.INIT", int_to_bitvector(lut1_init, 16));
cc.tiles[tname].add_enum(slice + ".MODE", str_or_default(ci->params, ctx->id("MODE"), "LOGIC"));
cc.tiles[tname].add_enum(slice + ".GSR", str_or_default(ci->params, ctx->id("GSR"), "ENABLED"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".SRMODE",
str_or_default(ci->params, ctx->id("SRMODE"), "LSR_OVER_CE"));
cc.tiles[tname].add_enum(slice + ".CEMUX", intstr_or_default(ci->params, ctx->id("CEMUX"), "1"));
cc.tiles[tname].add_enum("CLK" + std::to_string(int_index) + ".CLKMUX",
intstr_or_default(ci->params, ctx->id("CLKMUX"), "0"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".LSRMUX",
str_or_default(ci->params, ctx->id("LSRMUX"), "LSR"));
cc.tiles[tname].add_enum("LSR" + std::to_string(int_index) + ".LSRONMUX",
intstr_or_default(ci->params, ctx->id("LSRONMUX"), "LSRMUX"));
cc.tiles[tname].add_enum(slice + ".REGMODE", str_or_default(ci->params, ctx->id("REGMODE"), "FF"));
cc.tiles[tname].add_enum(slice + ".REG0.SD", intstr_or_default(ci->params, ctx->id("REG0_SD"), "0"));
cc.tiles[tname].add_enum(slice + ".REG1.SD", intstr_or_default(ci->params, ctx->id("REG1_SD"), "0"));
cc.tiles[tname].add_enum(slice + ".REG0.REGSET",
str_or_default(ci->params, ctx->id("REG0_REGSET"), "RESET"));
cc.tiles[tname].add_enum(slice + ".REG1.REGSET",
str_or_default(ci->params, ctx->id("REG1_REGSET"), "RESET"));
} else if (ci->type == ctx->id("FACADE_IO")) {
std::string pio = ctx->tile_info(bel)->bel_data[bel.index].name.get();
std::string iotype = str_or_default(ci->attrs, ctx->id("IO_TYPE"), "LVCMOS33");
std::string dir = str_or_default(ci->params, ctx->id("DIR"), "INPUT");
std::string pic_tile = get_pic_tile(ctx, bel);
cc.tiles[pic_tile].add_enum(pio + ".BASE_TYPE", dir + "_" + iotype);
} else if (ci->type == ctx->id("OSCH")) {
std::string freq = str_or_default(ci->params, ctx->id("NOM_FREQ"), "2.08");
cc.tiles[ctx->get_tile_by_type("CFG1")].add_enum("OSCH.MODE", "OSCH");
cc.tiles[ctx->get_tile_by_type("CFG1")].add_enum("OSCH.NOM_FREQ", freq);
}
}
// Configure chip
if (!text_config_file.empty()) {
std::ofstream out_config(text_config_file);
out_config << cc;
}
}
NEXTPNR_NAMESPACE_END
|
Add a special case for pips whose config bits are in multiple tiles.
|
machxo2: Add a special case for pips whose config bits are in multiple
tiles.
|
C++
|
isc
|
YosysHQ/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr,SymbiFlow/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr
|
46e591adf6f38dbc7e5ea4f3758758ed8098f44a
|
src/libshogun/base/init.cpp
|
src/libshogun/base/init.cpp
|
/*
* 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.
*
* Written (W) 2009 Soeren Sonnenburg
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "base/init.h"
#include "lib/Mathematics.h"
#include "lib/memory.h"
#include "lib/Set.h"
#include "base/Parallel.h"
#include "base/Version.h"
namespace shogun
{
CParallel* sg_parallel=NULL;
CIO* sg_io=NULL;
CVersion* sg_version=NULL;
CMath* sg_math=NULL;
#ifdef TRACE_MEMORY_ALLOCS
CSet<CMemoryBlock>* sg_mallocs=NULL;
#endif
/// function called to print normal messages
void (*sg_print_message)(FILE* target, const char* str) = NULL;
/// function called to print warning messages
void (*sg_print_warning)(FILE* target, const char* str) = NULL;
/// function called to print error messages
void (*sg_print_error)(FILE* target, const char* str) = NULL;
/// function called to cancel things
void (*sg_cancel_computations)(bool &delayed, bool &immediately)=NULL;
void init_shogun(void (*print_message)(FILE* target, const char* str),
void (*print_warning)(FILE* target, const char* str),
void (*print_error)(FILE* target, const char* str),
void (*cancel_computations)(bool &delayed, bool &immediately))
{
if (!sg_io)
sg_io = new shogun::CIO();
if (!sg_parallel)
sg_parallel=new shogun::CParallel();
if (!sg_version)
sg_version = new shogun::CVersion();
if (!sg_math)
sg_math = new shogun::CMath();
#ifdef TRACE_MEMORY_ALLOCS
if (!sg_mallocs)
sg_mallocs = new shogun::CSet<CMemoryBlock>();
SG_REF(sg_mallocs);
#endif
SG_REF(sg_io);
SG_REF(sg_parallel);
SG_REF(sg_version);
SG_REF(sg_math);
sg_print_message=print_message;
sg_print_warning=print_warning;
sg_print_error=print_error;
sg_cancel_computations=cancel_computations;
}
void exit_shogun()
{
sg_print_message=NULL;
sg_print_warning=NULL;
sg_print_error=NULL;
sg_cancel_computations=NULL;
SG_UNREF(sg_math);
SG_UNREF(sg_version);
SG_UNREF(sg_parallel);
SG_UNREF(sg_io);
// will leak memory alloc statistics on exit
}
void set_global_io(CIO* io)
{
SG_UNREF(sg_io);
sg_io=io;
SG_REF(sg_io);
}
CIO* get_global_io()
{
SG_REF(sg_io);
return sg_io;
}
void set_global_parallel(CParallel* parallel)
{
SG_UNREF(sg_parallel);
sg_parallel=parallel;
SG_REF(sg_parallel);
}
CParallel* get_global_parallel()
{
SG_REF(sg_parallel);
return sg_parallel;
}
void set_global_version(CVersion* version)
{
SG_UNREF(sg_version);
sg_version=version;
SG_REF(sg_version);
}
CVersion* get_global_version()
{
SG_REF(sg_version);
return sg_version;
}
void set_global_math(CMath* math)
{
SG_UNREF(sg_math);
sg_math=math;
SG_REF(sg_math);
}
CMath* get_global_math()
{
SG_REF(sg_math);
return sg_math;
}
}
|
/*
* 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.
*
* Written (W) 2009 Soeren Sonnenburg
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "base/init.h"
#include "lib/Mathematics.h"
#include "lib/memory.h"
#include "lib/Set.h"
#include "base/Parallel.h"
#include "base/Version.h"
#include <locale.h>
namespace shogun
{
CParallel* sg_parallel=NULL;
CIO* sg_io=NULL;
CVersion* sg_version=NULL;
CMath* sg_math=NULL;
#ifdef TRACE_MEMORY_ALLOCS
CSet<CMemoryBlock>* sg_mallocs=NULL;
#endif
/// function called to print normal messages
void (*sg_print_message)(FILE* target, const char* str) = NULL;
/// function called to print warning messages
void (*sg_print_warning)(FILE* target, const char* str) = NULL;
/// function called to print error messages
void (*sg_print_error)(FILE* target, const char* str) = NULL;
/// function called to cancel things
void (*sg_cancel_computations)(bool &delayed, bool &immediately)=NULL;
void init_shogun(void (*print_message)(FILE* target, const char* str),
void (*print_warning)(FILE* target, const char* str),
void (*print_error)(FILE* target, const char* str),
void (*cancel_computations)(bool &delayed, bool &immediately))
{
setlocale(LC_ALL, "");
if (!sg_io)
sg_io = new shogun::CIO();
if (!sg_parallel)
sg_parallel=new shogun::CParallel();
if (!sg_version)
sg_version = new shogun::CVersion();
if (!sg_math)
sg_math = new shogun::CMath();
#ifdef TRACE_MEMORY_ALLOCS
if (!sg_mallocs)
sg_mallocs = new shogun::CSet<CMemoryBlock>();
SG_REF(sg_mallocs);
#endif
SG_REF(sg_io);
SG_REF(sg_parallel);
SG_REF(sg_version);
SG_REF(sg_math);
sg_print_message=print_message;
sg_print_warning=print_warning;
sg_print_error=print_error;
sg_cancel_computations=cancel_computations;
}
void exit_shogun()
{
sg_print_message=NULL;
sg_print_warning=NULL;
sg_print_error=NULL;
sg_cancel_computations=NULL;
SG_UNREF(sg_math);
SG_UNREF(sg_version);
SG_UNREF(sg_parallel);
SG_UNREF(sg_io);
// will leak memory alloc statistics on exit
}
void set_global_io(CIO* io)
{
SG_UNREF(sg_io);
sg_io=io;
SG_REF(sg_io);
}
CIO* get_global_io()
{
SG_REF(sg_io);
return sg_io;
}
void set_global_parallel(CParallel* parallel)
{
SG_UNREF(sg_parallel);
sg_parallel=parallel;
SG_REF(sg_parallel);
}
CParallel* get_global_parallel()
{
SG_REF(sg_parallel);
return sg_parallel;
}
void set_global_version(CVersion* version)
{
SG_UNREF(sg_version);
sg_version=version;
SG_REF(sg_version);
}
CVersion* get_global_version()
{
SG_REF(sg_version);
return sg_version;
}
void set_global_math(CMath* math)
{
SG_UNREF(sg_math);
sg_math=math;
SG_REF(sg_math);
}
CMath* get_global_math()
{
SG_REF(sg_math);
return sg_math;
}
}
|
set C locale on startup in init_shogun to prevent incompatiblies with fprintf and floating point separators
|
set C locale on startup in init_shogun to prevent incompatiblies with fprintf and floating point separators
|
C++
|
bsd-3-clause
|
besser82/shogun,Saurabh7/shogun,sorig/shogun,Saurabh7/shogun,Saurabh7/shogun,geektoni/shogun,lambday/shogun,sorig/shogun,karlnapf/shogun,geektoni/shogun,geektoni/shogun,lisitsyn/shogun,geektoni/shogun,Saurabh7/shogun,Saurabh7/shogun,shogun-toolbox/shogun,lambday/shogun,shogun-toolbox/shogun,lambday/shogun,Saurabh7/shogun,geektoni/shogun,karlnapf/shogun,shogun-toolbox/shogun,lisitsyn/shogun,lisitsyn/shogun,besser82/shogun,karlnapf/shogun,shogun-toolbox/shogun,Saurabh7/shogun,lisitsyn/shogun,lambday/shogun,geektoni/shogun,besser82/shogun,Saurabh7/shogun,besser82/shogun,lisitsyn/shogun,karlnapf/shogun,sorig/shogun,sorig/shogun,karlnapf/shogun,sorig/shogun,karlnapf/shogun,sorig/shogun,shogun-toolbox/shogun,Saurabh7/shogun,besser82/shogun,besser82/shogun,lambday/shogun,lambday/shogun,shogun-toolbox/shogun,lisitsyn/shogun
|
8a94f0f8acf0537b8b49613fbba73ad1ee75facf
|
matrix/AxisAngle.hpp
|
matrix/AxisAngle.hpp
|
/**
* @file AxisAngle.hpp
*
* @author James Goppert <[email protected]>
*/
#pragma once
#include "math.hpp"
#include "helper_functions.hpp"
namespace matrix
{
template <typename Type>
class Dcm;
template <typename Type>
class Euler;
template <typename Type>
class AxisAngle;
/**
* AxisAngle class
*
* The rotation between two coordinate frames is
* described by this class.
*/
template<typename Type>
class AxisAngle : public Vector<Type, 3>
{
public:
virtual ~AxisAngle() {};
typedef Matrix<Type, 3, 1> Matrix31;
/**
* Constructor from array
*
* @param data_ array
*/
AxisAngle(const Type *data_) :
Vector<Type, 3>(data_)
{
}
/**
* Standard constructor
*/
AxisAngle() :
Vector<Type, 3>()
{
}
/**
* Constructor from Matrix31
*
* @param other Matrix31 to copy
*/
AxisAngle(const Matrix31 &other) :
Vector<Type, 3>(other)
{
}
/**
* Constructor from quaternion
*
* This sets the instance from a quaternion representing coordinate transformation from
* frame 2 to frame 1 where the rotation from frame 1 to frame 2 is described
* by a 3-2-1 intrinsic Tait-Bryan rotation sequence.
*
* @param q quaternion
*/
AxisAngle(const Quaternion<Type> &q) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
Type ang = (Type)2.0f*acosf(q(0));
Type mag = sinf(ang/2.0f);
if (fabs(ang) < 1e-10f) {
v(0) = 0;
v(1) = 0;
v(2) = 0;
} else {
v(0) = ang*q(1)/mag;
v(1) = ang*q(2)/mag;
v(2) = ang*q(3)/mag;
}
}
/**
* Constructor from dcm
*
* Instance is initialized from a dcm representing coordinate transformation
* from frame 2 to frame 1.
*
* @param dcm dcm to set quaternion to
*/
AxisAngle(const Dcm<Type> &dcm) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v = Quaternion<Type>(dcm);
}
/**
* Constructor from euler angles
*
* This sets the instance to a quaternion representing coordinate transformation from
* frame 2 to frame 1 where the rotation from frame 1 to frame 2 is described
* by a 3-2-1 intrinsic Tait-Bryan rotation sequence.
*
* @param euler euler angle instance
*/
AxisAngle(const Euler<Type> &euler) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v = Quaternion<Type>(euler);
}
/**
* Constructor from 3 axis angle values (unit vector * angle)
*
* @param x r_x*angle
* @param y r_y*angle
* @param z r_z*angle
*/
AxisAngle(Type x, Type y, Type z) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v(0) = x;
v(1) = y;
v(2) = z;
}
/**
* Constructor from axis and angle
*
* @param axis An axis of rotation, normalized if not unit length
* @param angle The amount to rotate
*/
AxisAngle(const Matrix31 & axis_, Type angle_) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
// make sure axis is a unit vector
Vector<Type, 3> a = axis_;
a = a.unit();
v(0) = a(0)*angle_;
v(1) = a(1)*angle_;
v(2) = a(2)*angle_;
}
Vector<Type, 3> axis() {
return Vector<Type, 3>::unit();
}
Type angle() {
return Vector<Type, 3>::norm();
}
};
typedef AxisAngle<float> AxisAnglef;
} // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
|
/**
* @file AxisAngle.hpp
*
* @author James Goppert <[email protected]>
*/
#pragma once
#include "math.hpp"
#include "helper_functions.hpp"
namespace matrix
{
template <typename Type>
class Dcm;
template <typename Type>
class Euler;
template <typename Type>
class AxisAngle;
/**
* AxisAngle class
*
* The rotation between two coordinate frames is
* described by this class.
*/
template<typename Type>
class AxisAngle : public Vector<Type, 3>
{
public:
virtual ~AxisAngle() {};
typedef Matrix<Type, 3, 1> Matrix31;
/**
* Constructor from array
*
* @param data_ array
*/
AxisAngle(const Type *data_) :
Vector<Type, 3>(data_)
{
}
/**
* Standard constructor
*/
AxisAngle() :
Vector<Type, 3>()
{
}
/**
* Constructor from Matrix31
*
* @param other Matrix31 to copy
*/
AxisAngle(const Matrix31 &other) :
Vector<Type, 3>(other)
{
}
/**
* Constructor from quaternion
*
* This sets the instance from a quaternion representing coordinate transformation from
* frame 2 to frame 1 where the rotation from frame 1 to frame 2 is described
* by a 3-2-1 intrinsic Tait-Bryan rotation sequence.
*
* @param q quaternion
*/
AxisAngle(const Quaternion<Type> &q) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
Type ang = (Type)2.0f*acosf(q(0));
Type mag = sinf(ang/2.0f);
if (fabsf(ang) < 1e-10f) {
v(0) = 0;
v(1) = 0;
v(2) = 0;
} else {
v(0) = ang*q(1)/mag;
v(1) = ang*q(2)/mag;
v(2) = ang*q(3)/mag;
}
}
/**
* Constructor from dcm
*
* Instance is initialized from a dcm representing coordinate transformation
* from frame 2 to frame 1.
*
* @param dcm dcm to set quaternion to
*/
AxisAngle(const Dcm<Type> &dcm) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v = Quaternion<Type>(dcm);
}
/**
* Constructor from euler angles
*
* This sets the instance to a quaternion representing coordinate transformation from
* frame 2 to frame 1 where the rotation from frame 1 to frame 2 is described
* by a 3-2-1 intrinsic Tait-Bryan rotation sequence.
*
* @param euler euler angle instance
*/
AxisAngle(const Euler<Type> &euler) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v = Quaternion<Type>(euler);
}
/**
* Constructor from 3 axis angle values (unit vector * angle)
*
* @param x r_x*angle
* @param y r_y*angle
* @param z r_z*angle
*/
AxisAngle(Type x, Type y, Type z) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
v(0) = x;
v(1) = y;
v(2) = z;
}
/**
* Constructor from axis and angle
*
* @param axis An axis of rotation, normalized if not unit length
* @param angle The amount to rotate
*/
AxisAngle(const Matrix31 & axis_, Type angle_) :
Vector<Type, 3>()
{
AxisAngle &v = *this;
// make sure axis is a unit vector
Vector<Type, 3> a = axis_;
a = a.unit();
v(0) = a(0)*angle_;
v(1) = a(1)*angle_;
v(2) = a(2)*angle_;
}
Vector<Type, 3> axis() {
return Vector<Type, 3>::unit();
}
Type angle() {
return Vector<Type, 3>::norm();
}
};
typedef AxisAngle<float> AxisAnglef;
} // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
|
Fix axis angle fabsf usage.
|
Fix axis angle fabsf usage.
|
C++
|
bsd-3-clause
|
PX4/Matrix,PX4/Matrix,PX4/Matrix
|
e01fb92aa9a950dd875e65620f53ce3b15e2d23b
|
snapshot/win/exception_snapshot_win_test.cc
|
snapshot/win/exception_snapshot_win_test.cc
|
// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/win/exception_snapshot_win.h"
#include <string>
#include "base/files/file_path.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "client/crashpad_client.h"
#include "gtest/gtest.h"
#include "snapshot/win/process_snapshot_win.h"
#include "test/errors.h"
#include "test/test_paths.h"
#include "test/win/child_launcher.h"
#include "util/file/file_io.h"
#include "util/thread/thread.h"
#include "util/win/exception_handler_server.h"
#include "util/win/registration_protocol_win.h"
#include "util/win/scoped_handle.h"
#include "util/win/scoped_process_suspend.h"
namespace crashpad {
namespace test {
namespace {
// Runs the ExceptionHandlerServer on a background thread.
class RunServerThread : public Thread {
public:
// Instantiates a thread which will invoke server->Run(delegate);
RunServerThread(ExceptionHandlerServer* server,
ExceptionHandlerServer::Delegate* delegate)
: server_(server), delegate_(delegate) {}
~RunServerThread() override {}
private:
// Thread:
void ThreadMain() override { server_->Run(delegate_); }
ExceptionHandlerServer* server_;
ExceptionHandlerServer::Delegate* delegate_;
DISALLOW_COPY_AND_ASSIGN(RunServerThread);
};
// During destruction, ensures that the server is stopped and the background
// thread joined.
class ScopedStopServerAndJoinThread {
public:
ScopedStopServerAndJoinThread(ExceptionHandlerServer* server, Thread* thread)
: server_(server), thread_(thread) {}
~ScopedStopServerAndJoinThread() {
server_->Stop();
thread_->Join();
}
private:
ExceptionHandlerServer* server_;
Thread* thread_;
DISALLOW_COPY_AND_ASSIGN(ScopedStopServerAndJoinThread);
};
class CrashingDelegate : public ExceptionHandlerServer::Delegate {
public:
CrashingDelegate(HANDLE server_ready, HANDLE completed_test_event)
: server_ready_(server_ready),
completed_test_event_(completed_test_event),
break_near_(0) {}
~CrashingDelegate() {}
void set_break_near(WinVMAddress break_near) { break_near_ = break_near; }
void ExceptionHandlerServerStarted() override { SetEvent(server_ready_); }
unsigned int ExceptionHandlerServerException(
HANDLE process,
WinVMAddress exception_information_address,
WinVMAddress debug_critical_section_address) override {
ScopedProcessSuspend suspend(process);
ProcessSnapshotWin snapshot;
snapshot.Initialize(process,
ProcessSuspensionState::kSuspended,
exception_information_address,
debug_critical_section_address);
// Confirm the exception record was read correctly.
EXPECT_NE(snapshot.Exception()->ThreadID(), 0u);
EXPECT_EQ(EXCEPTION_BREAKPOINT, snapshot.Exception()->Exception());
// Verify the exception happened at the expected location with a bit of
// slop space to allow for reading the current PC before the exception
// happens. See TestCrashingChild().
constexpr uint64_t kAllowedOffset = 100;
EXPECT_GT(snapshot.Exception()->ExceptionAddress(), break_near_);
EXPECT_LT(snapshot.Exception()->ExceptionAddress(),
break_near_ + kAllowedOffset);
SetEvent(completed_test_event_);
return snapshot.Exception()->Exception();
}
private:
HANDLE server_ready_; // weak
HANDLE completed_test_event_; // weak
WinVMAddress break_near_;
DISALLOW_COPY_AND_ASSIGN(CrashingDelegate);
};
void TestCrashingChild(TestPaths::Architecture architecture) {
// Set up the registration server on a background thread.
ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent");
ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent");
CrashingDelegate delegate(server_ready.get(), completed.get());
ExceptionHandlerServer exception_handler_server(true);
std::wstring pipe_name(L"\\\\.\\pipe\\test_name");
exception_handler_server.SetPipeName(pipe_name);
RunServerThread server_thread(&exception_handler_server, &delegate);
server_thread.Start();
ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
&exception_handler_server, &server_thread);
EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
// Spawn a child process, passing it the pipe name to connect to.
base::FilePath child_test_executable =
TestPaths::BuildArtifact(L"snapshot",
L"crashing_child",
TestPaths::FileType::kExecutable,
architecture);
ChildLauncher child(child_test_executable, pipe_name);
ASSERT_NO_FATAL_FAILURE(child.Start());
// The child tells us (approximately) where it will crash.
WinVMAddress break_near_address;
LoggingReadFileExactly(child.stdout_read_handle(),
&break_near_address,
sizeof(break_near_address));
delegate.set_break_near(break_near_address);
// Wait for the child to crash and the exception information to be validated.
EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
EXPECT_EQ(child.WaitForExit(), EXCEPTION_BREAKPOINT);
}
#if defined(ADDRESS_SANITIZER)
// https://crbug.com/845011
#define MAYBE_ChildCrash DISABLED_ChildCrash
#else
#define MAYBE_ChildCrash ChildCrash
#endif
TEST(ExceptionSnapshotWinTest, MAYBE_ChildCrash) {
TestCrashingChild(TestPaths::Architecture::kDefault);
}
#if defined(ARCH_CPU_64_BITS)
TEST(ExceptionSnapshotWinTest, ChildCrashWOW64) {
if (!TestPaths::Has32BitBuildArtifacts()) {
GTEST_SKIP();
}
TestCrashingChild(TestPaths::Architecture::k32Bit);
}
#endif // ARCH_CPU_64_BITS
class SimulateDelegate : public ExceptionHandlerServer::Delegate {
public:
SimulateDelegate(HANDLE server_ready, HANDLE completed_test_event)
: server_ready_(server_ready),
completed_test_event_(completed_test_event),
dump_near_(0) {}
~SimulateDelegate() {}
void set_dump_near(WinVMAddress dump_near) { dump_near_ = dump_near; }
void ExceptionHandlerServerStarted() override { SetEvent(server_ready_); }
unsigned int ExceptionHandlerServerException(
HANDLE process,
WinVMAddress exception_information_address,
WinVMAddress debug_critical_section_address) override {
ScopedProcessSuspend suspend(process);
ProcessSnapshotWin snapshot;
snapshot.Initialize(process,
ProcessSuspensionState::kSuspended,
exception_information_address,
debug_critical_section_address);
EXPECT_TRUE(snapshot.Exception());
EXPECT_EQ(snapshot.Exception()->Exception(), 0x517a7edu);
// Verify the dump was captured at the expected location with some slop
// space.
#if defined(ADDRESS_SANITIZER)
// ASan instrumentation inserts more instructions between the expected
// location and what's reported. https://crbug.com/845011.
constexpr uint64_t kAllowedOffset = 500;
#elif !NDEBUG
// Debug build is likely not optimized and contains more instructions.
constexpr uint64_t kAllowedOffset = 150;
#else
constexpr uint64_t kAllowedOffset = 100;
#endif
EXPECT_GT(snapshot.Exception()->Context()->InstructionPointer(),
dump_near_);
EXPECT_LT(snapshot.Exception()->Context()->InstructionPointer(),
dump_near_ + kAllowedOffset);
EXPECT_EQ(snapshot.Exception()->ExceptionAddress(),
snapshot.Exception()->Context()->InstructionPointer());
SetEvent(completed_test_event_);
return 0;
}
private:
HANDLE server_ready_; // weak
HANDLE completed_test_event_; // weak
WinVMAddress dump_near_;
DISALLOW_COPY_AND_ASSIGN(SimulateDelegate);
};
void TestDumpWithoutCrashingChild(TestPaths::Architecture architecture) {
// Set up the registration server on a background thread.
ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent");
ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent");
SimulateDelegate delegate(server_ready.get(), completed.get());
ExceptionHandlerServer exception_handler_server(true);
std::wstring pipe_name(L"\\\\.\\pipe\\test_name");
exception_handler_server.SetPipeName(pipe_name);
RunServerThread server_thread(&exception_handler_server, &delegate);
server_thread.Start();
ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
&exception_handler_server, &server_thread);
EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
// Spawn a child process, passing it the pipe name to connect to.
base::FilePath child_test_executable =
TestPaths::BuildArtifact(L"snapshot",
L"dump_without_crashing",
TestPaths::FileType::kExecutable,
architecture);
ChildLauncher child(child_test_executable, pipe_name);
ASSERT_NO_FATAL_FAILURE(child.Start());
// The child tells us (approximately) where it will capture a dump.
WinVMAddress dump_near_address;
LoggingReadFileExactly(child.stdout_read_handle(),
&dump_near_address,
sizeof(dump_near_address));
delegate.set_dump_near(dump_near_address);
// Wait for the child to crash and the exception information to be validated.
EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
EXPECT_EQ(child.WaitForExit(), 0u);
}
#if defined(ADDRESS_SANITIZER)
// https://crbug.com/845011
#define MAYBE_ChildDumpWithoutCrashing DISABLED_ChildDumpWithoutCrashing
#else
#define MAYBE_ChildDumpWithoutCrashing ChildDumpWithoutCrashing
#endif
TEST(SimulateCrash, MAYBE_ChildDumpWithoutCrashing) {
TestDumpWithoutCrashingChild(TestPaths::Architecture::kDefault);
}
#if defined(ARCH_CPU_64_BITS)
TEST(SimulateCrash, ChildDumpWithoutCrashingWOW64) {
if (!TestPaths::Has32BitBuildArtifacts()) {
GTEST_SKIP();
}
TestDumpWithoutCrashingChild(TestPaths::Architecture::k32Bit);
}
#endif // ARCH_CPU_64_BITS
} // namespace
} // namespace test
} // namespace crashpad
|
// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/win/exception_snapshot_win.h"
#include <string>
#include "base/files/file_path.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "client/crashpad_client.h"
#include "gtest/gtest.h"
#include "snapshot/win/process_snapshot_win.h"
#include "test/errors.h"
#include "test/test_paths.h"
#include "test/win/child_launcher.h"
#include "util/file/file_io.h"
#include "util/thread/thread.h"
#include "util/win/exception_handler_server.h"
#include "util/win/registration_protocol_win.h"
#include "util/win/scoped_handle.h"
#include "util/win/scoped_process_suspend.h"
namespace crashpad {
namespace test {
namespace {
// Runs the ExceptionHandlerServer on a background thread.
class RunServerThread : public Thread {
public:
// Instantiates a thread which will invoke server->Run(delegate);
RunServerThread(ExceptionHandlerServer* server,
ExceptionHandlerServer::Delegate* delegate)
: server_(server), delegate_(delegate) {}
~RunServerThread() override {}
private:
// Thread:
void ThreadMain() override { server_->Run(delegate_); }
ExceptionHandlerServer* server_;
ExceptionHandlerServer::Delegate* delegate_;
DISALLOW_COPY_AND_ASSIGN(RunServerThread);
};
// During destruction, ensures that the server is stopped and the background
// thread joined.
class ScopedStopServerAndJoinThread {
public:
ScopedStopServerAndJoinThread(ExceptionHandlerServer* server, Thread* thread)
: server_(server), thread_(thread) {}
~ScopedStopServerAndJoinThread() {
server_->Stop();
thread_->Join();
}
private:
ExceptionHandlerServer* server_;
Thread* thread_;
DISALLOW_COPY_AND_ASSIGN(ScopedStopServerAndJoinThread);
};
class CrashingDelegate : public ExceptionHandlerServer::Delegate {
public:
CrashingDelegate(HANDLE server_ready, HANDLE completed_test_event)
: server_ready_(server_ready),
completed_test_event_(completed_test_event),
break_near_(0) {}
~CrashingDelegate() {}
void set_break_near(WinVMAddress break_near) { break_near_ = break_near; }
void ExceptionHandlerServerStarted() override { SetEvent(server_ready_); }
unsigned int ExceptionHandlerServerException(
HANDLE process,
WinVMAddress exception_information_address,
WinVMAddress debug_critical_section_address) override {
ScopedProcessSuspend suspend(process);
ProcessSnapshotWin snapshot;
snapshot.Initialize(process,
ProcessSuspensionState::kSuspended,
exception_information_address,
debug_critical_section_address);
// Confirm the exception record was read correctly.
EXPECT_NE(snapshot.Exception()->ThreadID(), 0u);
EXPECT_EQ(EXCEPTION_BREAKPOINT, snapshot.Exception()->Exception());
// Verify the exception happened at the expected location with a bit of
// slop space to allow for reading the current PC before the exception
// happens. See TestCrashingChild().
constexpr uint64_t kAllowedOffset = 100;
EXPECT_GT(snapshot.Exception()->ExceptionAddress(), break_near_);
EXPECT_LT(snapshot.Exception()->ExceptionAddress(),
break_near_ + kAllowedOffset);
SetEvent(completed_test_event_);
return snapshot.Exception()->Exception();
}
private:
HANDLE server_ready_; // weak
HANDLE completed_test_event_; // weak
WinVMAddress break_near_;
DISALLOW_COPY_AND_ASSIGN(CrashingDelegate);
};
void TestCrashingChild(TestPaths::Architecture architecture) {
// Set up the registration server on a background thread.
ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent");
ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent");
CrashingDelegate delegate(server_ready.get(), completed.get());
ExceptionHandlerServer exception_handler_server(true);
std::wstring pipe_name(L"\\\\.\\pipe\\test_name");
exception_handler_server.SetPipeName(pipe_name);
RunServerThread server_thread(&exception_handler_server, &delegate);
server_thread.Start();
ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
&exception_handler_server, &server_thread);
EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
// Spawn a child process, passing it the pipe name to connect to.
base::FilePath child_test_executable =
TestPaths::BuildArtifact(L"snapshot",
L"crashing_child",
TestPaths::FileType::kExecutable,
architecture);
ChildLauncher child(child_test_executable, pipe_name);
ASSERT_NO_FATAL_FAILURE(child.Start());
// The child tells us (approximately) where it will crash.
WinVMAddress break_near_address;
LoggingReadFileExactly(child.stdout_read_handle(),
&break_near_address,
sizeof(break_near_address));
delegate.set_break_near(break_near_address);
// Wait for the child to crash and the exception information to be validated.
EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
EXPECT_EQ(child.WaitForExit(), EXCEPTION_BREAKPOINT);
}
#if defined(ADDRESS_SANITIZER)
// https://crbug.com/845011
#define MAYBE_ChildCrash DISABLED_ChildCrash
#else
#define MAYBE_ChildCrash ChildCrash
#endif
TEST(ExceptionSnapshotWinTest, MAYBE_ChildCrash) {
TestCrashingChild(TestPaths::Architecture::kDefault);
}
#if defined(ARCH_CPU_64_BITS)
TEST(ExceptionSnapshotWinTest, ChildCrashWOW64) {
if (!TestPaths::Has32BitBuildArtifacts()) {
GTEST_SKIP();
}
TestCrashingChild(TestPaths::Architecture::k32Bit);
}
#endif // ARCH_CPU_64_BITS
class SimulateDelegate : public ExceptionHandlerServer::Delegate {
public:
SimulateDelegate(HANDLE server_ready, HANDLE completed_test_event)
: server_ready_(server_ready),
completed_test_event_(completed_test_event),
dump_near_(0) {}
~SimulateDelegate() {}
void set_dump_near(WinVMAddress dump_near) { dump_near_ = dump_near; }
void ExceptionHandlerServerStarted() override { SetEvent(server_ready_); }
unsigned int ExceptionHandlerServerException(
HANDLE process,
WinVMAddress exception_information_address,
WinVMAddress debug_critical_section_address) override {
ScopedProcessSuspend suspend(process);
ProcessSnapshotWin snapshot;
snapshot.Initialize(process,
ProcessSuspensionState::kSuspended,
exception_information_address,
debug_critical_section_address);
EXPECT_TRUE(snapshot.Exception());
EXPECT_EQ(snapshot.Exception()->Exception(), 0x517a7edu);
// Verify the dump was captured at the expected location with some slop
// space.
#if defined(ADDRESS_SANITIZER)
// ASan instrumentation inserts more instructions between the expected
// location and what's reported. https://crbug.com/845011.
constexpr uint64_t kAllowedOffset = 500;
#elif !defined(NDEBUG)
// Debug build is likely not optimized and contains more instructions.
constexpr uint64_t kAllowedOffset = 150;
#else
constexpr uint64_t kAllowedOffset = 100;
#endif
EXPECT_GT(snapshot.Exception()->Context()->InstructionPointer(),
dump_near_);
EXPECT_LT(snapshot.Exception()->Context()->InstructionPointer(),
dump_near_ + kAllowedOffset);
EXPECT_EQ(snapshot.Exception()->ExceptionAddress(),
snapshot.Exception()->Context()->InstructionPointer());
SetEvent(completed_test_event_);
return 0;
}
private:
HANDLE server_ready_; // weak
HANDLE completed_test_event_; // weak
WinVMAddress dump_near_;
DISALLOW_COPY_AND_ASSIGN(SimulateDelegate);
};
void TestDumpWithoutCrashingChild(TestPaths::Architecture architecture) {
// Set up the registration server on a background thread.
ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent");
ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr));
ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent");
SimulateDelegate delegate(server_ready.get(), completed.get());
ExceptionHandlerServer exception_handler_server(true);
std::wstring pipe_name(L"\\\\.\\pipe\\test_name");
exception_handler_server.SetPipeName(pipe_name);
RunServerThread server_thread(&exception_handler_server, &delegate);
server_thread.Start();
ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
&exception_handler_server, &server_thread);
EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
// Spawn a child process, passing it the pipe name to connect to.
base::FilePath child_test_executable =
TestPaths::BuildArtifact(L"snapshot",
L"dump_without_crashing",
TestPaths::FileType::kExecutable,
architecture);
ChildLauncher child(child_test_executable, pipe_name);
ASSERT_NO_FATAL_FAILURE(child.Start());
// The child tells us (approximately) where it will capture a dump.
WinVMAddress dump_near_address;
LoggingReadFileExactly(child.stdout_read_handle(),
&dump_near_address,
sizeof(dump_near_address));
delegate.set_dump_near(dump_near_address);
// Wait for the child to crash and the exception information to be validated.
EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0)
<< ErrorMessage("WaitForSingleObject");
EXPECT_EQ(child.WaitForExit(), 0u);
}
#if defined(ADDRESS_SANITIZER)
// https://crbug.com/845011
#define MAYBE_ChildDumpWithoutCrashing DISABLED_ChildDumpWithoutCrashing
#else
#define MAYBE_ChildDumpWithoutCrashing ChildDumpWithoutCrashing
#endif
TEST(SimulateCrash, MAYBE_ChildDumpWithoutCrashing) {
TestDumpWithoutCrashingChild(TestPaths::Architecture::kDefault);
}
#if defined(ARCH_CPU_64_BITS)
TEST(SimulateCrash, ChildDumpWithoutCrashingWOW64) {
if (!TestPaths::Has32BitBuildArtifacts()) {
GTEST_SKIP();
}
TestDumpWithoutCrashingChild(TestPaths::Architecture::k32Bit);
}
#endif // ARCH_CPU_64_BITS
} // namespace
} // namespace test
} // namespace crashpad
|
Fix #elif in crrev.com/c/1949846
|
Fix #elif in crrev.com/c/1949846
I was editing the patch in gerrit and looks like it undone !defined
change and I landed wrong version.
Bug: chromium:1030261
Change-Id: Ib645839bac5450fe55ecd9f3a38155022b7f6c13
Reviewed-on: https://chromium-review.googlesource.com/c/crashpad/crashpad/+/1951624
Reviewed-by: Mark Mentovai <[email protected]>
Commit-Queue: Vitaly Buka <[email protected]>
|
C++
|
apache-2.0
|
chromium/crashpad,chromium/crashpad,chromium/crashpad
|
985d9637d8332388bd4b586b88abdaad405efd78
|
common/system/magic_server.cc
|
common/system/magic_server.cc
|
#include "magic_server.h"
#include "sim_api.h"
#include "simulator.h"
#include "thread_manager.h"
#include "logmem.h"
#include "performance_model.h"
#include "fastforward_performance_model.h"
#include "core_manager.h"
#include "dvfs_manager.h"
#include "hooks_manager.h"
#include "stats.h"
#include "timer.h"
#include "thread.h"
MagicServer::MagicServer()
: m_performance_enabled(false)
{
}
MagicServer::~MagicServer()
{ }
UInt64 MagicServer::Magic(thread_id_t thread_id, core_id_t core_id, UInt64 cmd, UInt64 arg0, UInt64 arg1)
{
ScopedLock sl(Sim()->getThreadManager()->getLock());
return Magic_unlocked(thread_id, core_id, cmd, arg0, arg1);
}
UInt64 MagicServer::Magic_unlocked(thread_id_t thread_id, core_id_t core_id, UInt64 cmd, UInt64 arg0, UInt64 arg1)
{
switch(cmd)
{
case SIM_CMD_ROI_TOGGLE:
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(! m_performance_enabled);
}
else
{
return 0;
}
case SIM_CMD_ROI_START:
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_ROI_BEGIN, 0);
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(true);
}
else
{
return 0;
}
case SIM_CMD_ROI_END:
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_ROI_END, 0);
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(false);
}
else
{
return 0;
}
case SIM_CMD_MHZ_SET:
return setFrequency(arg0, arg1);
case SIM_CMD_NAMED_MARKER:
{
char str[256];
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
core->accessMemory(Core::NONE, Core::READ, arg1, str, 256, Core::MEM_MODELED_NONE);
str[255] = '\0';
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: 0, str: str };
Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_MARKER, (UInt64)&args);
return 0;
}
case SIM_CMD_SET_THREAD_NAME:
{
char str[256];
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
core->accessMemory(Core::NONE, Core::READ, arg0, str, 256, Core::MEM_MODELED_NONE);
str[255] = '\0';
Sim()->getStatsManager()->logMarker(Sim()->getClockSkewMinimizationServer()->getGlobalTime(), core_id, thread_id, 0xff00ff00000001, 0, str);
Sim()->getThreadManager()->getThreadFromID(thread_id)->setName(str);
return 0;
}
case SIM_CMD_MARKER:
{
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: arg1, str: NULL };
Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_MARKER, (UInt64)&args);
return 0;
}
case SIM_CMD_USER:
{
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: arg1, str: NULL };
return Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_USER, (UInt64)&args, true /* expect return value */);
}
case SIM_CMD_INSTRUMENT_MODE:
return setInstrumentationMode(arg0);
case SIM_CMD_MHZ_GET:
return getFrequency(arg0);
default:
LOG_ASSERT_ERROR(false, "Got invalid Magic %lu, arg0(%lu) arg1(%lu)", cmd, arg0, arg1);
}
return 0;
}
UInt64 MagicServer::getGlobalInstructionCount(void)
{
UInt64 ninstrs = 0;
for (UInt32 i = 0; i < Sim()->getConfig()->getApplicationCores(); i++)
ninstrs += Sim()->getCoreManager()->getCoreFromID(i)->getInstructionCount();
return ninstrs;
}
static Timer t_start;
UInt64 ninstrs_start;
__attribute__((weak)) void PinDetach(void) {}
void MagicServer::enablePerformance()
{
Sim()->getStatsManager()->recordStats("roi-begin");
ninstrs_start = getGlobalInstructionCount();
t_start.start();
Simulator::enablePerformanceModels();
Sim()->setInstrumentationMode(InstMode::inst_mode_roi, true /* update_barrier */);
}
void MagicServer::disablePerformance()
{
Simulator::disablePerformanceModels();
Sim()->getStatsManager()->recordStats("roi-end");
float seconds = t_start.getTime() / 1e9;
UInt64 ninstrs = getGlobalInstructionCount() - ninstrs_start;
printf("[SNIPER] Simulated %.1fM instructions @ %.1f KIPS (%.1f KIPS / target core - %.1fns/instr)\n",
ninstrs / 1e6, ninstrs / seconds / 1e3,
ninstrs / seconds / 1e3 / Sim()->getConfig()->getApplicationCores(),
seconds * 1e9 / (float(ninstrs ? ninstrs : 1.) / Sim()->getConfig()->getApplicationCores()));
PerformanceModel *perf = Sim()->getCoreManager()->getCoreFromID(0)->getPerformanceModel();
if (perf->getFastforwardPerformanceModel()->getFastforwardedTime() > SubsecondTime::Zero())
{
// NOTE: Prints out the non-idle ratio for core 0 only, but it's just indicative anyway
double ff_ratio = double(perf->getFastforwardPerformanceModel()->getFastforwardedTime().getNS())
/ double(perf->getNonIdleElapsedTime().getNS());
double percent_detailed = 100. * (1. - ff_ratio);
printf("[SNIPER] Sampling: executed %.2f%% of simulated time in detailed mode\n", percent_detailed);
}
fflush(NULL);
Sim()->setInstrumentationMode(InstMode::inst_mode_end, true /* update_barrier */);
PinDetach();
}
void print_allocations();
UInt64 MagicServer::setPerformance(bool enabled)
{
if (m_performance_enabled == enabled)
return 1;
m_performance_enabled = enabled;
//static bool enabled = false;
static Timer t_start;
//ScopedLock sl(l_alloc);
if (m_performance_enabled)
{
printf("[SNIPER] Enabling performance models\n");
fflush(NULL);
t_start.start();
logmem_enable(true);
Sim()->getHooksManager()->callHooks(HookType::HOOK_ROI_BEGIN, 0);
}
else
{
Sim()->getHooksManager()->callHooks(HookType::HOOK_ROI_END, 0);
printf("[SNIPER] Disabling performance models\n");
float seconds = t_start.getTime() / 1e9;
printf("[SNIPER] Leaving ROI after %.2f seconds\n", seconds);
fflush(NULL);
logmem_enable(false);
logmem_write_allocations();
}
if (enabled)
enablePerformance();
else
disablePerformance();
return 0;
}
UInt64 MagicServer::setFrequency(UInt64 core_number, UInt64 freq_in_mhz)
{
UInt32 num_cores = Sim()->getConfig()->getApplicationCores();
UInt64 freq_in_hz;
if (core_number >= num_cores)
return 1;
freq_in_hz = 1000000 * freq_in_mhz;
printf("[SNIPER] Setting frequency for core %" PRId64 " in DVFS domain %d to %" PRId64 " MHz\n", core_number, Sim()->getDvfsManager()->getCoreDomainId(core_number), freq_in_mhz);
if (freq_in_hz > 0)
Sim()->getDvfsManager()->setCoreDomain(core_number, ComponentPeriod::fromFreqHz(freq_in_hz));
else {
Sim()->getThreadManager()->stallThread_async(core_number, ThreadManager::STALL_BROKEN, SubsecondTime::MaxTime());
Sim()->getCoreManager()->getCoreFromID(core_number)->setState(Core::BROKEN);
}
// First set frequency, then call hooks so hook script can find the new frequency by querying the DVFS manager
Sim()->getHooksManager()->callHooks(HookType::HOOK_CPUFREQ_CHANGE, core_number);
return 0;
}
UInt64 MagicServer::getFrequency(UInt64 core_number)
{
UInt32 num_cores = Sim()->getConfig()->getApplicationCores();
if (core_number >= num_cores)
return UINT64_MAX;
const ComponentPeriod *per = Sim()->getDvfsManager()->getCoreDomain(core_number);
return per->getPeriodInFreqMHz();
}
UInt64 MagicServer::setInstrumentationMode(UInt64 sim_api_opt)
{
InstMode::inst_mode_t inst_mode;
switch (sim_api_opt)
{
case SIM_OPT_INSTRUMENT_DETAILED:
inst_mode = InstMode::DETAILED;
break;
case SIM_OPT_INSTRUMENT_WARMUP:
inst_mode = InstMode::CACHE_ONLY;
break;
case SIM_OPT_INSTRUMENT_FASTFORWARD:
inst_mode = InstMode::FAST_FORWARD;
break;
default:
LOG_PRINT_ERROR("Unexpected magic instrument opt type: %lx.", sim_api_opt);
}
Sim()->setInstrumentationMode(inst_mode, true /* update_barrier */);
return 0;
}
|
#include "magic_server.h"
#include "sim_api.h"
#include "simulator.h"
#include "thread_manager.h"
#include "logmem.h"
#include "performance_model.h"
#include "fastforward_performance_model.h"
#include "core_manager.h"
#include "dvfs_manager.h"
#include "hooks_manager.h"
#include "stats.h"
#include "timer.h"
#include "thread.h"
MagicServer::MagicServer()
: m_performance_enabled(false)
{
}
MagicServer::~MagicServer()
{ }
UInt64 MagicServer::Magic(thread_id_t thread_id, core_id_t core_id, UInt64 cmd, UInt64 arg0, UInt64 arg1)
{
ScopedLock sl(Sim()->getThreadManager()->getLock());
return Magic_unlocked(thread_id, core_id, cmd, arg0, arg1);
}
UInt64 MagicServer::Magic_unlocked(thread_id_t thread_id, core_id_t core_id, UInt64 cmd, UInt64 arg0, UInt64 arg1)
{
switch(cmd)
{
case SIM_CMD_ROI_TOGGLE:
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(! m_performance_enabled);
}
else
{
return 0;
}
case SIM_CMD_ROI_START:
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_ROI_BEGIN, 0);
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(true);
}
else
{
return 0;
}
case SIM_CMD_ROI_END:
Sim()->getHooksManager()->callHooks(HookType::HOOK_APPLICATION_ROI_END, 0);
if (Sim()->getConfig()->getSimulationROI() == Config::ROI_MAGIC)
{
return setPerformance(false);
}
else
{
return 0;
}
case SIM_CMD_MHZ_SET:
return setFrequency(arg0, arg1);
case SIM_CMD_NAMED_MARKER:
{
char str[256];
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
core->accessMemory(Core::NONE, Core::READ, arg1, str, 256, Core::MEM_MODELED_NONE);
str[255] = '\0';
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: 0, str: str };
Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_MARKER, (UInt64)&args);
return 0;
}
case SIM_CMD_SET_THREAD_NAME:
{
char str[256];
Core *core = Sim()->getCoreManager()->getCoreFromID(core_id);
core->accessMemory(Core::NONE, Core::READ, arg0, str, 256, Core::MEM_MODELED_NONE);
str[255] = '\0';
Sim()->getStatsManager()->logMarker(Sim()->getClockSkewMinimizationServer()->getGlobalTime(), core_id, thread_id, 0xff00ff00000001, 0, str);
Sim()->getThreadManager()->getThreadFromID(thread_id)->setName(str);
return 0;
}
case SIM_CMD_MARKER:
{
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: arg1, str: NULL };
Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_MARKER, (UInt64)&args);
return 0;
}
case SIM_CMD_USER:
{
MagicMarkerType args = { thread_id: thread_id, core_id: core_id, arg0: arg0, arg1: arg1, str: NULL };
return Sim()->getHooksManager()->callHooks(HookType::HOOK_MAGIC_USER, (UInt64)&args, true /* expect return value */);
}
case SIM_CMD_INSTRUMENT_MODE:
return setInstrumentationMode(arg0);
case SIM_CMD_MHZ_GET:
return getFrequency(arg0);
default:
LOG_ASSERT_ERROR(false, "Got invalid Magic %lu, arg0(%lu) arg1(%lu)", cmd, arg0, arg1);
}
return 0;
}
UInt64 MagicServer::getGlobalInstructionCount(void)
{
UInt64 ninstrs = 0;
for (UInt32 i = 0; i < Sim()->getConfig()->getApplicationCores(); i++)
ninstrs += Sim()->getCoreManager()->getCoreFromID(i)->getInstructionCount();
return ninstrs;
}
static Timer t_start;
UInt64 ninstrs_start;
__attribute__((weak)) void PinDetach(void) {}
void MagicServer::enablePerformance()
{
Sim()->getStatsManager()->recordStats("roi-begin");
ninstrs_start = getGlobalInstructionCount();
t_start.start();
Simulator::enablePerformanceModels();
Sim()->setInstrumentationMode(InstMode::inst_mode_roi, true /* update_barrier */);
}
void MagicServer::disablePerformance()
{
Simulator::disablePerformanceModels();
Sim()->getStatsManager()->recordStats("roi-end");
float seconds = t_start.getTime() / 1e9;
UInt64 ninstrs = getGlobalInstructionCount() - ninstrs_start;
UInt64 cycles = SubsecondTime::divideRounded(Sim()->getClockSkewMinimizationServer()->getGlobalTime(),
Sim()->getCoreManager()->getCoreFromID(0)->getDvfsDomain()->getPeriod());
printf("[SNIPER] Simulated %.1fM instructions, %.1fM cycles, %.2f IPC\n",
ninstrs / 1e6,
cycles / 1e6,
float(ninstrs) / (cycles ? cycles : 1));
printf("[SNIPER] Simulation speed %.1f KIPS (%.1f KIPS / target core - %.1fns/instr)\n",
ninstrs / seconds / 1e3,
ninstrs / seconds / 1e3 / Sim()->getConfig()->getApplicationCores(),
seconds * 1e9 / (float(ninstrs ? ninstrs : 1.) / Sim()->getConfig()->getApplicationCores()));
PerformanceModel *perf = Sim()->getCoreManager()->getCoreFromID(0)->getPerformanceModel();
if (perf->getFastforwardPerformanceModel()->getFastforwardedTime() > SubsecondTime::Zero())
{
// NOTE: Prints out the non-idle ratio for core 0 only, but it's just indicative anyway
double ff_ratio = double(perf->getFastforwardPerformanceModel()->getFastforwardedTime().getNS())
/ double(perf->getNonIdleElapsedTime().getNS());
double percent_detailed = 100. * (1. - ff_ratio);
printf("[SNIPER] Sampling: executed %.2f%% of simulated time in detailed mode\n", percent_detailed);
}
fflush(NULL);
Sim()->setInstrumentationMode(InstMode::inst_mode_end, true /* update_barrier */);
PinDetach();
}
void print_allocations();
UInt64 MagicServer::setPerformance(bool enabled)
{
if (m_performance_enabled == enabled)
return 1;
m_performance_enabled = enabled;
//static bool enabled = false;
static Timer t_start;
//ScopedLock sl(l_alloc);
if (m_performance_enabled)
{
printf("[SNIPER] Enabling performance models\n");
fflush(NULL);
t_start.start();
logmem_enable(true);
Sim()->getHooksManager()->callHooks(HookType::HOOK_ROI_BEGIN, 0);
}
else
{
Sim()->getHooksManager()->callHooks(HookType::HOOK_ROI_END, 0);
printf("[SNIPER] Disabling performance models\n");
float seconds = t_start.getTime() / 1e9;
printf("[SNIPER] Leaving ROI after %.2f seconds\n", seconds);
fflush(NULL);
logmem_enable(false);
logmem_write_allocations();
}
if (enabled)
enablePerformance();
else
disablePerformance();
return 0;
}
UInt64 MagicServer::setFrequency(UInt64 core_number, UInt64 freq_in_mhz)
{
UInt32 num_cores = Sim()->getConfig()->getApplicationCores();
UInt64 freq_in_hz;
if (core_number >= num_cores)
return 1;
freq_in_hz = 1000000 * freq_in_mhz;
printf("[SNIPER] Setting frequency for core %" PRId64 " in DVFS domain %d to %" PRId64 " MHz\n", core_number, Sim()->getDvfsManager()->getCoreDomainId(core_number), freq_in_mhz);
if (freq_in_hz > 0)
Sim()->getDvfsManager()->setCoreDomain(core_number, ComponentPeriod::fromFreqHz(freq_in_hz));
else {
Sim()->getThreadManager()->stallThread_async(core_number, ThreadManager::STALL_BROKEN, SubsecondTime::MaxTime());
Sim()->getCoreManager()->getCoreFromID(core_number)->setState(Core::BROKEN);
}
// First set frequency, then call hooks so hook script can find the new frequency by querying the DVFS manager
Sim()->getHooksManager()->callHooks(HookType::HOOK_CPUFREQ_CHANGE, core_number);
return 0;
}
UInt64 MagicServer::getFrequency(UInt64 core_number)
{
UInt32 num_cores = Sim()->getConfig()->getApplicationCores();
if (core_number >= num_cores)
return UINT64_MAX;
const ComponentPeriod *per = Sim()->getDvfsManager()->getCoreDomain(core_number);
return per->getPeriodInFreqMHz();
}
UInt64 MagicServer::setInstrumentationMode(UInt64 sim_api_opt)
{
InstMode::inst_mode_t inst_mode;
switch (sim_api_opt)
{
case SIM_OPT_INSTRUMENT_DETAILED:
inst_mode = InstMode::DETAILED;
break;
case SIM_OPT_INSTRUMENT_WARMUP:
inst_mode = InstMode::CACHE_ONLY;
break;
case SIM_OPT_INSTRUMENT_FASTFORWARD:
inst_mode = InstMode::FAST_FORWARD;
break;
default:
LOG_PRINT_ERROR("Unexpected magic instrument opt type: %lx.", sim_api_opt);
}
Sim()->setInstrumentationMode(inst_mode, true /* update_barrier */);
return 0;
}
|
Print out simulated runtime and IPC in post-ROI summary
|
[magic] Print out simulated runtime and IPC in post-ROI summary
|
C++
|
mit
|
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
|
9e1e586d289a76f34b01f150a2f4a42dfcc6e1d1
|
viewer/primitives/simple_geometry_primitives.hh
|
viewer/primitives/simple_geometry_primitives.hh
|
#pragma once
#include "sophus.hh"
#include "viewer/primitives/primitive.hh"
#include "geometry/shapes/halfspace.hh"
#include <vector>
namespace viewer {
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
struct Axes {
SE3 axes_from_world;
double scale = 1.0;
};
struct Line {
Vec3 start;
Vec3 end;
Vec4 color = Vec4::Ones();
double width = 2.6;
};
struct Ray {
Vec3 origin;
Vec3 direction;
double length = 1.0;
Vec4 color = Vec4::Ones();
double width = 1.0;
};
struct Points {
std::vector<Vec3> points;
Vec4 color = Vec4::Ones();
double size = 1.0;
};
struct Point {
Vec3 point;
Vec4 color = Vec4(1.0, 1.0, 0.0, 1.0);
double size = 1.0;
};
struct ColoredPoints {
std::vector<Vec3> points;
std::vector<Vec4> colors;
double size = 1.0;
};
struct Points2d {
using Vec2 = Eigen::Vector2d;
std::vector<Vec2> points;
Vec4 color = Vec4::Ones();
double size = 1.0;
double z_offset = 0.0;
};
struct Sphere {
Vec3 center;
double radius;
Vec4 color = Vec4(0.0, 1.0, 0.0, 1.0);
};
struct Plane {
geometry::shapes::Plane plane;
double line_spacing = 1.0;
Vec4 color = Vec4(0.8, 0.8, 0.8, 0.8);
};
struct AxisAlignedBox {
Vec3 lower;
Vec3 upper;
Vec4 color = Vec4(1.0, 0.0, 1.0, 0.6);
};
struct Polygon {
std::vector<Vec3, Eigen::aligned_allocator<Vec3>> points;
double width = 3.0;
double height = 0.01;
Vec4 color = Vec4(1.0, 0.0, 1.0, 0.6);
bool outline = false;
};
void draw_axes(const Axes &axes);
void draw_lines(const std::vector<Line> &lines);
void draw_plane_grid(const Plane &plane);
void draw_points(const Points &points);
void draw_colored_points(const ColoredPoints &points);
void draw_points2d(const Points2d &points);
void draw_sphere(const Sphere &sphere);
void draw_point(const Point &point);
void draw_polygon(const Polygon &polygon);
} // namespace viewer
|
#pragma once
#include "sophus.hh"
#include "viewer/primitives/primitive.hh"
#include "geometry/shapes/halfspace.hh"
#include <vector>
namespace viewer {
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
struct Axes {
SE3 axes_from_world;
double scale = 1.0;
};
struct Line {
Vec3 start;
Vec3 end;
Vec4 color = Vec4::Ones();
double width = 2.6;
};
struct Ray {
Vec3 origin;
Vec3 direction;
double length = 1.0;
Vec4 color = Vec4::Ones();
double width = 1.0;
};
struct Points {
std::vector<Vec3> points;
Vec4 color = Vec4::Ones();
double size = 1.0;
};
struct Point {
Vec3 point;
Vec4 color = Vec4(1.0, 1.0, 0.0, 1.0);
double size = 1.0;
};
struct ColoredPoints {
std::vector<Vec3> points;
std::vector<Vec4> colors;
double size = 1.0;
};
struct Points2d {
using Vec2 = Eigen::Vector2d;
std::vector<Vec2> points;
Vec4 color = Vec4::Ones();
double size = 1.0;
double z_offset = 0.0;
};
struct Sphere {
Vec3 center;
double radius;
Vec4 color = Vec4(0.0, 1.0, 0.0, 1.0);
};
struct Plane {
geometry::shapes::Plane plane;
Vec4 color = Vec4(0.8, 0.8, 0.8, 0.8);
double line_spacing = 1.0;
};
struct AxisAlignedBox {
Vec3 lower;
Vec3 upper;
Vec4 color = Vec4(1.0, 0.0, 1.0, 0.6);
};
struct Polygon {
std::vector<Vec3, Eigen::aligned_allocator<Vec3>> points;
double width = 3.0;
double height = 0.01;
Vec4 color = Vec4(1.0, 0.0, 1.0, 0.6);
bool outline = false;
};
void draw_axes(const Axes &axes);
void draw_lines(const std::vector<Line> &lines);
void draw_plane_grid(const Plane &plane);
void draw_points(const Points &points);
void draw_colored_points(const ColoredPoints &points);
void draw_points2d(const Points2d &points);
void draw_sphere(const Sphere &sphere);
void draw_point(const Point &point);
void draw_polygon(const Polygon &polygon);
} // namespace viewer
|
Make plane color selection easier
|
Make plane color selection easier
|
C++
|
mit
|
jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments
|
19fa1c3013ccae96ce4bf3388645bf459e70978f
|
ouzel/graphics/direct3d11/TextureResourceD3D11.cpp
|
ouzel/graphics/direct3d11/TextureResourceD3D11.cpp
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
default: return DXGI_FORMAT_UNKNOWN;
}
}
TextureResourceD3D11::TextureResourceD3D11()
{
}
TextureResourceD3D11::~TextureResourceD3D11()
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
}
if (renderTargetView)
{
renderTargetView->Release();
}
if (resourceView)
{
resourceView->Release();
}
if (texture)
{
texture->Release();
}
if (samplerState)
{
samplerState->Release();
}
width = 0;
height = 0;
}
bool TextureResourceD3D11::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());
if (dirty & DIRTY_DATA)
{
if (size.v[0] > 0 &&
size.v[1] > 0)
{
if (!texture ||
static_cast<UINT>(size.v[0]) != width ||
static_cast<UINT>(size.v[1]) != height)
{
if (texture)
{
texture->Release();
}
if (resourceView)
{
resourceView->Release();
resourceView = nullptr;
}
width = static_cast<UINT>(size.v[0]);
height = static_cast<UINT>(size.v[1]);
DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);
if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
{
Log(Log::Level::ERR) << "Invalid pixel format";
return false;
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
textureDesc.ArraySize = 1;
textureDesc.Format = d3d11PixelFormat;
textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
textureDesc.SampleDesc.Count = sampleCount;
textureDesc.SampleDesc.Quality = 0;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
textureDesc.MiscFlags = 0;
HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
resourceViewDesc.Format = d3d11PixelFormat;
resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
resourceViewDesc.Texture2D.MostDetailedMip = 0;
resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
}
hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
return false;
}
if (renderTarget)
{
if (renderTargetView)
{
renderTargetView->Release();
}
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
renderTargetViewDesc.Format = d3d11PixelFormat;
renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
renderTargetViewDesc.Texture2D.MipSlice = 0;
}
HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
return false;
}
}
if (depth)
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
D3D11_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.SampleDesc.Count = sampleCount;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
return false;
}
hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
return false;
}
}
}
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
nullptr, levels[level].data.data(),
static_cast<UINT>(levels[level].pitch), 0);
}
}
}
}
if (dirty & DIRTY_DATA)
{
clearFrameBufferView = clearColorBuffer;
clearDepthBufferView = clearDepthBuffer;
frameBufferClearColor[0] = clearColor.normR();
frameBufferClearColor[1] = clearColor.normG();
frameBufferClearColor[2] = clearColor.normB();
frameBufferClearColor[3] = clearColor.normA();
if (samplerState) samplerState->Release();
RendererD3D11::SamplerStateDesc samplerDesc;
samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
samplerDesc.addressX = addressX;
samplerDesc.addressY = addressY;
samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;
samplerState = rendererD3D11->getSamplerState(samplerDesc);
if (!samplerState)
{
Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
return false;
}
samplerState->AddRef();
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "TextureResourceD3D11.h"
#include "RendererD3D11.h"
#include "core/Engine.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT getD3D11PixelFormat(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return DXGI_FORMAT_A8_UNORM;
case PixelFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
case PixelFormat::R8_SNORM: return DXGI_FORMAT_R8_SNORM;
case PixelFormat::R8_UINT: return DXGI_FORMAT_R8_UINT;
case PixelFormat::R8_SINT: return DXGI_FORMAT_R8_SINT;
case PixelFormat::R16_UNORM: return DXGI_FORMAT_R16_UNORM;
case PixelFormat::R16_SNORM: return DXGI_FORMAT_R16_SNORM;
case PixelFormat::R16_UINT: return DXGI_FORMAT_R16_UINT;
case PixelFormat::R16_SINT: return DXGI_FORMAT_R16_SINT;
case PixelFormat::R16_FLOAT: return DXGI_FORMAT_R16_FLOAT;
case PixelFormat::R32_UINT: return DXGI_FORMAT_R32_UINT;
case PixelFormat::R32_SINT: return DXGI_FORMAT_R32_SINT;
case PixelFormat::R32_FLOAT: return DXGI_FORMAT_R32_FLOAT;
case PixelFormat::RG8_UNORM: return DXGI_FORMAT_R8G8_UNORM;
case PixelFormat::RG8_SNORM: return DXGI_FORMAT_R8G8_SNORM;
case PixelFormat::RG8_UINT: return DXGI_FORMAT_R8G8_UINT;
case PixelFormat::RG8_SINT: return DXGI_FORMAT_R8G8_SINT;
case PixelFormat::RGBA8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case PixelFormat::RGBA8_SNORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case PixelFormat::RGBA8_UINT: return DXGI_FORMAT_R8G8B8A8_UINT;
case PixelFormat::RGBA8_SINT: return DXGI_FORMAT_R8G8B8A8_SINT;
case PixelFormat::RGBA16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case PixelFormat::RGBA16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case PixelFormat::RGBA16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT;
case PixelFormat::RGBA16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT;
case PixelFormat::RGBA16_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case PixelFormat::RGBA32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT;
case PixelFormat::RGBA32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT;
case PixelFormat::RGBA32_FLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT;
default: return DXGI_FORMAT_UNKNOWN;
}
}
TextureResourceD3D11::TextureResourceD3D11()
{
}
TextureResourceD3D11::~TextureResourceD3D11()
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
}
if (renderTargetView)
{
renderTargetView->Release();
}
if (resourceView)
{
resourceView->Release();
}
if (texture)
{
texture->Release();
}
if (samplerState)
{
samplerState->Release();
}
width = 0;
height = 0;
}
bool TextureResourceD3D11::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
RendererD3D11* rendererD3D11 = static_cast<RendererD3D11*>(sharedEngine->getRenderer());
if (dirty & DIRTY_DATA)
{
if (size.v[0] > 0 &&
size.v[1] > 0)
{
if (!texture ||
static_cast<UINT>(size.v[0]) != width ||
static_cast<UINT>(size.v[1]) != height)
{
if (texture)
{
texture->Release();
}
if (resourceView)
{
resourceView->Release();
resourceView = nullptr;
}
width = static_cast<UINT>(size.v[0]);
height = static_cast<UINT>(size.v[1]);
DXGI_FORMAT d3d11PixelFormat = getD3D11PixelFormat(pixelFormat);
if (d3d11PixelFormat == DXGI_FORMAT_UNKNOWN)
{
Log(Log::Level::ERR) << "Invalid pixel format";
return false;
}
D3D11_TEXTURE2D_DESC textureDesc;
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = (levels.size() > 1) ? 0 : 1;
textureDesc.ArraySize = 1;
textureDesc.Format = d3d11PixelFormat;
textureDesc.Usage = (dynamic && !renderTarget) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
textureDesc.CPUAccessFlags = (dynamic && !renderTarget) ? D3D11_CPU_ACCESS_WRITE : 0;
textureDesc.SampleDesc.Count = sampleCount;
textureDesc.SampleDesc.Quality = 0;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (renderTarget ? D3D11_BIND_RENDER_TARGET : 0);
textureDesc.MiscFlags = 0;
HRESULT hr = rendererD3D11->getDevice()->CreateTexture2D(&textureDesc, nullptr, &texture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 texture";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
resourceViewDesc.Format = d3d11PixelFormat;
resourceViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
resourceViewDesc.Texture2D.MostDetailedMip = 0;
resourceViewDesc.Texture2D.MipLevels = static_cast<UINT>(levels.size());
}
hr = rendererD3D11->getDevice()->CreateShaderResourceView(texture, &resourceViewDesc, &resourceView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 shader resource view";
return false;
}
if (renderTarget)
{
if (renderTargetView)
{
renderTargetView->Release();
}
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
renderTargetViewDesc.Format = d3d11PixelFormat;
renderTargetViewDesc.ViewDimension = (sampleCount > 1) ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
if (sampleCount == 1)
{
renderTargetViewDesc.Texture2D.MipSlice = 0;
}
HRESULT hr = rendererD3D11->getDevice()->CreateRenderTargetView(texture, &renderTargetViewDesc, &renderTargetView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 render target view";
return false;
}
}
if (depth)
{
if (depthStencilTexture)
{
depthStencilTexture->Release();
}
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = nullptr;
}
D3D11_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = width;
depthStencilDesc.Height = height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilDesc.SampleDesc.Count = sampleCount;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
hr = rendererD3D11->getDevice()->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencilTexture);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil texture";
return false;
}
hr = rendererD3D11->getDevice()->CreateDepthStencilView(depthStencilTexture, nullptr, &depthStencilView);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 depth stencil view";
return false;
}
}
}
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
rendererD3D11->getContext()->UpdateSubresource(texture, static_cast<UINT>(level),
nullptr, levels[level].data.data(),
static_cast<UINT>(levels[level].pitch), 0);
}
}
}
}
if (dirty & DIRTY_PARAMETERS)
{
clearFrameBufferView = clearColorBuffer;
clearDepthBufferView = clearDepthBuffer;
frameBufferClearColor[0] = clearColor.normR();
frameBufferClearColor[1] = clearColor.normG();
frameBufferClearColor[2] = clearColor.normB();
frameBufferClearColor[3] = clearColor.normA();
if (samplerState) samplerState->Release();
RendererD3D11::SamplerStateDesc samplerDesc;
samplerDesc.filter = (filter == Texture::Filter::DEFAULT) ? rendererD3D11->getTextureFilter() : filter;
samplerDesc.addressX = addressX;
samplerDesc.addressY = addressY;
samplerDesc.maxAnisotropy = (maxAnisotropy == 0) ? rendererD3D11->getMaxAnisotropy() : maxAnisotropy;
samplerState = rendererD3D11->getSamplerState(samplerDesc);
if (!samplerState)
{
Log(Log::Level::ERR) << "Failed to get D3D11 sampler state";
return false;
}
samplerState->AddRef();
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
|
Check if parameters are dirty instead of data
|
Check if parameters are dirty instead of data
|
C++
|
unlicense
|
elvman/ouzel,Hotspotmar/ouzel,Hotspotmar/ouzel,elnormous/ouzel,Hotspotmar/ouzel,elnormous/ouzel,elnormous/ouzel,elvman/ouzel
|
f642ab9c6f7585e47a11afa6e51e8cb4924bc929
|
eventrpc/eventrpc/thread.cpp
|
eventrpc/eventrpc/thread.cpp
|
#include "thread.h"
#include "log.h"
namespace eventrpc {
static const int MB = 1024 * 1024;
Thread::Thread(const std::string &name, shared_ptr<Runnable> runnable)
: name_(name),
runnable_(runnable),
cpu_affinity_(0),
detach_(true),
stack_size_(1),
policy_(SCHED_RR) {
}
Thread::Thread(shared_ptr<Runnable> runnable)
: name_("Anonymous Thread"),
runnable_(runnable),
cpu_affinity_(0),
detach_(true),
stack_size_(1),
policy_(SCHED_RR) {
}
Thread::~Thread() {
}
bool Thread::Init() {
pthread_attr_t thread_attr;
if (pthread_attr_init(&thread_attr) != 0) {
LOG_ERROR() << "pthread_attr_init error";
return false;
}
if(pthread_attr_setdetachstate(
&thread_attr,
detach_ ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE) != 0) {
LOG_ERROR() << "pthread_attr_setdetachstate error";
return false;
}
if (pthread_attr_setstacksize(&thread_attr,
MB * stack_size_) != 0) {
LOG_ERROR() << "pthread_attr_setstacksize error";
return false;
}
if (pthread_attr_setschedpolicy(&thread_attr, policy_) != 0) {
LOG_ERROR() << "pthread_attr_setschedpolicy error";
return false;
}
/*
struct sched_param sched_param;
sched_param.sched_priority = priority_;
if (pthread_attr_setschedparam(&thread_attr, &sched_param) != 0) {
LOG_ERROR() << "pthread_attr_setschedparam error";
return false;
}
*/
if (pthread_create(&thread_id_, &thread_attr,
&Thread::threadMain, (void*)this) != 0) {
LOG_ERROR() << "pthread_create error";
return false;
}
return true;
}
void * Thread::threadMain(void *arg) {
Thread *self = static_cast<Thread*>(arg);
int cpu_affinity = self->cpu_affinity_;
if (cpu_affinity >= 0) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu_affinity, &mask);
int ret = sched_setaffinity(0, sizeof(mask), &mask);
LOG_INFO() << "SetAffinity to: " << cpu_affinity
<< " ret: " << ret;
}
self->runnable_->Run();
return NULL;
}
void Thread::Start() {
if (!Init()) {
return;
}
}
void Thread::Join() {
if (!detach_) {
detach_ = pthread_join(thread_id_, NULL) == 0;
}
}
};
|
#include "thread.h"
#include "log.h"
namespace eventrpc {
static const int MB = 1024 * 1024;
Thread::Thread(const std::string &name, shared_ptr<Runnable> runnable)
: name_(name),
runnable_(runnable),
cpu_affinity_(0),
detach_(true),
stack_size_(1),
policy_(SCHED_RR) {
}
Thread::Thread(shared_ptr<Runnable> runnable)
: name_("Anonymous Thread"),
runnable_(runnable),
cpu_affinity_(0),
detach_(true),
stack_size_(1),
policy_(SCHED_RR) {
}
Thread::~Thread() {
}
bool Thread::Init() {
pthread_attr_t thread_attr;
if (pthread_attr_init(&thread_attr) != 0) {
LOG_ERROR() << "pthread_attr_init error";
return false;
}
if(pthread_attr_setdetachstate(
&thread_attr,
detach_ ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE) != 0) {
LOG_ERROR() << "pthread_attr_setdetachstate error";
return false;
}
if (pthread_attr_setstacksize(&thread_attr,
MB * stack_size_) != 0) {
LOG_ERROR() << "pthread_attr_setstacksize error";
return false;
}
if (pthread_attr_setschedpolicy(&thread_attr, policy_) != 0) {
LOG_ERROR() << "pthread_attr_setschedpolicy error";
return false;
}
if (pthread_create(&thread_id_, &thread_attr,
&Thread::threadMain, (void*)this) != 0) {
LOG_ERROR() << "pthread_create error";
return false;
}
return true;
}
void * Thread::threadMain(void *arg) {
Thread *self = static_cast<Thread*>(arg);
int cpu_affinity = self->cpu_affinity_;
if (cpu_affinity >= 0) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu_affinity, &mask);
int ret = sched_setaffinity(0, sizeof(mask), &mask);
LOG_INFO() << "SetAffinity to: " << cpu_affinity
<< " ret: " << ret;
}
self->runnable_->Run();
return NULL;
}
void Thread::Start() {
ASSERT_EQ(true, Init());
}
void Thread::Join() {
if (!detach_) {
detach_ = pthread_join(thread_id_, NULL) == 0;
}
}
};
|
refactor thread cpp
|
refactor thread cpp
|
C++
|
bsd-3-clause
|
iCoolcoder/avidya,wenyongking/avidya,wanggchongg/avidya,TheFool0415/avidya,songyundi2014/avidya,fujianbo/avidya,yangaofeng/avidya,iCoolcoder/avidya,wanyisunflower/avidya,zackxue/avidya,crisish/avidya,wenyongking/avidya,TheFool0415/avidya,JackSon3756/avidya,CuriousBoy0822/avidya,songyundi2014/avidya,weimaolong/avidya,yangaofeng/avidya,hnzhangshilong/avidya,sandynie/avidya,baiduGo/avidya,baiduGo/avidya,wanyisunflower/avidya,CuriousBoy0822/avidya,fujianbo/avidya,xmandy/avidya,CoderJie/avidya,crisish/avidya,hnzhangshilong/avidya,wanggchongg/avidya,sandynie/avidya,zackxue/avidya,JackSon3756/avidya,CoderJie/avidya,weimaolong/avidya,xmandy/avidya
|
35d494ffc0cf0186cfe62cd9f7cd30b55dfe54c7
|
akonadi/akonadiconsole/searchwidget.cpp
|
akonadi/akonadiconsole/searchwidget.cpp
|
/*
This file is part of Akonadi.
Copyright (c) 2009 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "searchwidget.h"
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/itemsearchjob.h>
#include <kmessagebox.h>
#include <QtGui/QComboBox>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QListView>
#include <QtGui/QPushButton>
#include <QtGui/QStringListModel>
#include <QtGui/QTextBrowser>
#include <QtGui/QTextEdit>
#include <QtCore/QDebug>
SearchWidget::SearchWidget( QWidget *parent )
: QWidget( parent )
{
QGridLayout *layout = new QGridLayout( this );
mQueryCombo = new QComboBox;
mQueryWidget = new QTextEdit;
mResultView = new QListView;
mItemView = new QTextBrowser;
QPushButton *button = new QPushButton( "Search" );
layout->addWidget( new QLabel( "SPARQL Query:" ), 0, 0 );
layout->addWidget( mQueryCombo, 0, 1, Qt::AlignRight );
layout->addWidget( mQueryWidget, 1, 0, 1, 2 );
layout->addWidget( new QLabel( "Matching Item UIDs:" ), 2, 0 );
layout->addWidget( new QLabel( "View:" ), 2, 1 );
layout->addWidget( mResultView, 3, 0, 1, 1 );
layout->addWidget( mItemView, 3, 1, 1, 1 );
layout->addWidget( button, 4, 1, Qt::AlignRight );
mQueryCombo->addItem( "Empty" );
mQueryCombo->addItem( "Contacts by email address" );
mQueryCombo->addItem( "Contacts by name" );
connect( button, SIGNAL( clicked() ), this, SLOT( search() ) );
connect( mQueryCombo, SIGNAL( activated( int ) ), this, SLOT( querySelected( int ) ) );
connect( mResultView, SIGNAL( activated( const QModelIndex& ) ), this, SLOT( fetchItem( const QModelIndex& ) ) );
mResultModel = new QStringListModel( this );
mResultView->setModel( mResultModel );
}
SearchWidget::~SearchWidget()
{
}
void SearchWidget::search()
{
Akonadi::ItemSearchJob *job = new Akonadi::ItemSearchJob( mQueryWidget->toPlainText() );
connect( job, SIGNAL( result( KJob* ) ), this, SLOT( searchFinished( KJob* ) ) );
}
void SearchWidget::searchFinished( KJob *job )
{
mResultModel->setStringList( QStringList() );
mItemView->clear();
if ( job->error() ) {
KMessageBox::error( this, job->errorString() );
return;
}
QStringList uidList;
Akonadi::ItemSearchJob *searchJob = qobject_cast<Akonadi::ItemSearchJob*>( job );
const Akonadi::Item::List items = searchJob->items();
foreach ( const Akonadi::Item &item, items ) {
uidList << QString::number( item.id() );
}
mResultModel->setStringList( uidList );
}
void SearchWidget::querySelected( int index )
{
if ( index == 0 ) {
mQueryWidget->clear();
} else if ( index == 1 ) {
mQueryWidget->setPlainText( ""
"SELECT ?person WHERE {\n"
" ?person <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#hasEmailAddress> ?email .\n"
" ?email <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#emailAddress> \"[email protected]\"^^<http://www.w3.org/2001/XMLSchema#string> .\n"
" }\n"
);
} else if ( index == 2 ) {
mQueryWidget->setPlainText( ""
"prefix nco:<http://www.semanticdesktop.org/ontologies/2007/03/22/nco#>\n"
"SELECT ?r WHERE {\n"
" ?r nco:fullname \"Tobias Koenig\"^^<http://www.w3.org/2001/XMLSchema#string>.\n"
"}\n"
);
}
}
void SearchWidget::fetchItem( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const QString uid = index.data( Qt::DisplayRole ).toString();
Akonadi::ItemFetchJob *fetchJob = new Akonadi::ItemFetchJob( Akonadi::Item( uid.toLongLong() ) );
fetchJob->fetchScope().fetchFullPayload();
connect( fetchJob, SIGNAL( result( KJob* ) ), this, SLOT( itemFetched( KJob* ) ) );
}
void SearchWidget::itemFetched( KJob *job )
{
mItemView->clear();
if ( job->error() ) {
KMessageBox::error( this, "Error on fetching item" );
return;
}
Akonadi::ItemFetchJob *fetchJob = qobject_cast<Akonadi::ItemFetchJob*>( job );
if ( !fetchJob->items().isEmpty() ) {
const Akonadi::Item item = fetchJob->items().first();
mItemView->setPlainText( QString::fromUtf8( item.payloadData() ) );
}
}
#include "searchwidget.moc"
|
/*
This file is part of Akonadi.
Copyright (c) 2009 Tobias Koenig <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "searchwidget.h"
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
#include <akonadi/itemsearchjob.h>
#include <kmessagebox.h>
#include <QtGui/QComboBox>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QListView>
#include <QtGui/QPushButton>
#include <QtGui/QStringListModel>
#include <QtGui/QTextBrowser>
#include <QtGui/QTextEdit>
#include <QtCore/QDebug>
SearchWidget::SearchWidget( QWidget *parent )
: QWidget( parent )
{
QGridLayout *layout = new QGridLayout( this );
mQueryCombo = new QComboBox;
mQueryWidget = new QTextEdit;
mResultView = new QListView;
mItemView = new QTextBrowser;
QPushButton *button = new QPushButton( "Search" );
layout->addWidget( new QLabel( "SPARQL Query:" ), 0, 0 );
layout->addWidget( mQueryCombo, 0, 1, Qt::AlignRight );
layout->addWidget( mQueryWidget, 1, 0, 1, 2 );
layout->addWidget( new QLabel( "Matching Item UIDs:" ), 2, 0 );
layout->addWidget( new QLabel( "View:" ), 2, 1 );
layout->addWidget( mResultView, 3, 0, 1, 1 );
layout->addWidget( mItemView, 3, 1, 1, 1 );
layout->addWidget( button, 4, 1, Qt::AlignRight );
mQueryCombo->addItem( "Empty" );
mQueryCombo->addItem( "Contacts by email address" );
mQueryCombo->addItem( "Contacts by name" );
mQueryCombo->addItem( "Email by From/Full Name" );
connect( button, SIGNAL( clicked() ), this, SLOT( search() ) );
connect( mQueryCombo, SIGNAL( activated( int ) ), this, SLOT( querySelected( int ) ) );
connect( mResultView, SIGNAL( activated( const QModelIndex& ) ), this, SLOT( fetchItem( const QModelIndex& ) ) );
mResultModel = new QStringListModel( this );
mResultView->setModel( mResultModel );
}
SearchWidget::~SearchWidget()
{
}
void SearchWidget::search()
{
Akonadi::ItemSearchJob *job = new Akonadi::ItemSearchJob( mQueryWidget->toPlainText() );
connect( job, SIGNAL( result( KJob* ) ), this, SLOT( searchFinished( KJob* ) ) );
}
void SearchWidget::searchFinished( KJob *job )
{
mResultModel->setStringList( QStringList() );
mItemView->clear();
if ( job->error() ) {
KMessageBox::error( this, job->errorString() );
return;
}
QStringList uidList;
Akonadi::ItemSearchJob *searchJob = qobject_cast<Akonadi::ItemSearchJob*>( job );
const Akonadi::Item::List items = searchJob->items();
foreach ( const Akonadi::Item &item, items ) {
uidList << QString::number( item.id() );
}
mResultModel->setStringList( uidList );
}
void SearchWidget::querySelected( int index )
{
if ( index == 0 ) {
mQueryWidget->clear();
} else if ( index == 1 ) {
mQueryWidget->setPlainText( ""
"SELECT ?person WHERE {\n"
" ?person <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#hasEmailAddress> ?email .\n"
" ?email <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#emailAddress> \"[email protected]\"^^<http://www.w3.org/2001/XMLSchema#string> .\n"
" }\n"
);
} else if ( index == 2 ) {
mQueryWidget->setPlainText( ""
"prefix nco:<http://www.semanticdesktop.org/ontologies/2007/03/22/nco#>\n"
"SELECT ?r WHERE {\n"
" ?r nco:fullname \"Tobias Koenig\"^^<http://www.w3.org/2001/XMLSchema#string>.\n"
"}\n"
);
} else if ( index == 3 ) {
mQueryWidget->setPlainText( "SELECT ?mail WHERE {\n"
" ?mail <http://www.semanticdesktop.org/ontologies/2007/03/22/nmo#from> ?person .\n"
" ?person <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#fullname> "
"'Martin Koller'^^<http://www.w3.org/2001/XMLSchema#string> .\n"
"}\n"
);
}
}
void SearchWidget::fetchItem( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const QString uid = index.data( Qt::DisplayRole ).toString();
Akonadi::ItemFetchJob *fetchJob = new Akonadi::ItemFetchJob( Akonadi::Item( uid.toLongLong() ) );
fetchJob->fetchScope().fetchFullPayload();
connect( fetchJob, SIGNAL( result( KJob* ) ), this, SLOT( itemFetched( KJob* ) ) );
}
void SearchWidget::itemFetched( KJob *job )
{
mItemView->clear();
if ( job->error() ) {
KMessageBox::error( this, "Error on fetching item" );
return;
}
Akonadi::ItemFetchJob *fetchJob = qobject_cast<Akonadi::ItemFetchJob*>( job );
if ( !fetchJob->items().isEmpty() ) {
const Akonadi::Item item = fetchJob->items().first();
mItemView->setPlainText( QString::fromUtf8( item.payloadData() ) );
}
}
#include "searchwidget.moc"
|
add "Email by From/Full Name" search query example
|
add "Email by From/Full Name" search query example
svn path=/branches/work/akonadi-ports/kdepim/; revision=1036825
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
7e5e68aa23ebac22842938060ba4f308251f48f8
|
lib/asan/asan_globals.cc
|
lib/asan/asan_globals.cc
|
//===-- asan_globals.cc ---------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Handle globals.
//===----------------------------------------------------------------------===//
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_mapping.h"
#include "asan_poisoning.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "asan_stats.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
namespace __asan {
typedef __asan_global Global;
struct ListOfGlobals {
const Global *g;
ListOfGlobals *next;
};
static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
static LowLevelAllocator allocator_for_globals;
static ListOfGlobals *list_of_all_globals;
static const int kDynamicInitGlobalsInitialCapacity = 512;
struct DynInitGlobal {
Global g;
bool initialized;
};
typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
// Lazy-initialized and never deleted.
static VectorOfGlobals *dynamic_init_globals;
// We want to remember where a certain range of globals was registered.
struct GlobalRegistrationSite {
u32 stack_id;
Global *g_first, *g_last;
};
typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
static GlobalRegistrationSiteVector *global_registration_site_vector;
ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
FastPoisonShadow(g->beg, g->size_with_redzone, value);
}
ALWAYS_INLINE void PoisonRedZones(const Global &g) {
uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
kAsanGlobalRedzoneMagic);
if (g.size != aligned_size) {
FastPoisonShadowPartialRightRedzone(
g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
g.size % SHADOW_GRANULARITY,
SHADOW_GRANULARITY,
kAsanGlobalRedzoneMagic);
}
}
static void ReportGlobal(const Global &g, const char *prefix) {
Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
prefix, &g, (void*)g.beg, g.size, g.size_with_redzone, g.name,
g.module_name, g.has_dynamic_init);
}
bool DescribeAddressIfGlobal(uptr addr, uptr size) {
if (!flags()->report_globals) return false;
BlockingMutexLock lock(&mu_for_globals);
bool res = false;
for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
const Global &g = *l->g;
if (flags()->report_globals >= 2)
ReportGlobal(g, "Search");
res |= DescribeAddressRelativeToGlobal(addr, size, g);
}
return res;
}
u32 FindRegistrationSite(const Global *g) {
CHECK(global_registration_site_vector);
for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
if (g >= grs.g_first && g <= grs.g_last)
return grs.stack_id;
}
return 0;
}
// Register a global variable.
// This function may be called more than once for every global
// so we store the globals in a map.
static void RegisterGlobal(const Global *g) {
CHECK(asan_inited);
if (flags()->report_globals >= 2)
ReportGlobal(*g, "Added");
CHECK(flags()->report_globals);
CHECK(AddrIsInMem(g->beg));
CHECK(AddrIsAlignedByGranularity(g->beg));
CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
if (flags()->detect_odr_violation) {
// Try detecting ODR (One Definition Rule) violation, i.e. the situation
// where two globals with the same name are defined in different modules.
if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
// This check may not be enough: if the first global is much larger
// the entire redzone of the second global may be within the first global.
for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
if (g->beg == l->g->beg &&
(flags()->detect_odr_violation >= 2 || g->size != l->g->size))
ReportODRViolation(g, FindRegistrationSite(g),
l->g, FindRegistrationSite(l->g));
}
}
}
if (flags()->poison_heap)
PoisonRedZones(*g);
ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
l->g = g;
l->next = list_of_all_globals;
list_of_all_globals = l;
if (g->has_dynamic_init) {
if (dynamic_init_globals == 0) {
dynamic_init_globals = new(allocator_for_globals)
VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
}
DynInitGlobal dyn_global = { *g, false };
dynamic_init_globals->push_back(dyn_global);
}
}
static void UnregisterGlobal(const Global *g) {
CHECK(asan_inited);
CHECK(flags()->report_globals);
CHECK(AddrIsInMem(g->beg));
CHECK(AddrIsAlignedByGranularity(g->beg));
CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
if (flags()->poison_heap)
PoisonShadowForGlobal(g, 0);
// We unpoison the shadow memory for the global but we do not remove it from
// the list because that would require O(n^2) time with the current list
// implementation. It might not be worth doing anyway.
}
void StopInitOrderChecking() {
BlockingMutexLock lock(&mu_for_globals);
if (!flags()->check_initialization_order || !dynamic_init_globals)
return;
flags()->check_initialization_order = false;
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
// Unpoison the whole global.
PoisonShadowForGlobal(g, 0);
// Poison redzones back.
PoisonRedZones(*g);
}
}
} // namespace __asan
// ---------------------- Interface ---------------- {{{1
using namespace __asan; // NOLINT
// Register an array of globals.
void __asan_register_globals(__asan_global *globals, uptr n) {
if (!flags()->report_globals) return;
GET_STACK_TRACE_FATAL_HERE;
u32 stack_id = StackDepotPut(stack.trace, stack.size);
BlockingMutexLock lock(&mu_for_globals);
if (!global_registration_site_vector)
global_registration_site_vector =
new(allocator_for_globals) GlobalRegistrationSiteVector(128);
GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
global_registration_site_vector->push_back(site);
if (flags()->report_globals >= 2) {
PRINT_CURRENT_STACK();
Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
}
for (uptr i = 0; i < n; i++) {
RegisterGlobal(&globals[i]);
}
}
// Unregister an array of globals.
// We must do this when a shared objects gets dlclosed.
void __asan_unregister_globals(__asan_global *globals, uptr n) {
if (!flags()->report_globals) return;
BlockingMutexLock lock(&mu_for_globals);
for (uptr i = 0; i < n; i++) {
UnregisterGlobal(&globals[i]);
}
}
// This method runs immediately prior to dynamic initialization in each TU,
// when all dynamically initialized globals are unpoisoned. This method
// poisons all global variables not defined in this TU, so that a dynamic
// initializer can only touch global variables in the same TU.
void __asan_before_dynamic_init(const char *module_name) {
if (!flags()->check_initialization_order ||
!flags()->poison_heap)
return;
bool strict_init_order = flags()->strict_init_order;
CHECK(dynamic_init_globals);
CHECK(module_name);
CHECK(asan_inited);
BlockingMutexLock lock(&mu_for_globals);
if (flags()->report_globals >= 3)
Printf("DynInitPoison module: %s\n", module_name);
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
if (dyn_g.initialized)
continue;
if (g->module_name != module_name)
PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
else if (!strict_init_order)
dyn_g.initialized = true;
}
}
// This method runs immediately after dynamic initialization in each TU, when
// all dynamically initialized globals except for those defined in the current
// TU are poisoned. It simply unpoisons all dynamically initialized globals.
void __asan_after_dynamic_init() {
if (!flags()->check_initialization_order ||
!flags()->poison_heap)
return;
CHECK(asan_inited);
BlockingMutexLock lock(&mu_for_globals);
// FIXME: Optionally report that we're unpoisoning globals from a module.
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
if (!dyn_g.initialized) {
// Unpoison the whole global.
PoisonShadowForGlobal(g, 0);
// Poison redzones back.
PoisonRedZones(*g);
}
}
}
|
//===-- asan_globals.cc ---------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Handle globals.
//===----------------------------------------------------------------------===//
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_mapping.h"
#include "asan_poisoning.h"
#include "asan_report.h"
#include "asan_stack.h"
#include "asan_stats.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_mutex.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
namespace __asan {
typedef __asan_global Global;
struct ListOfGlobals {
const Global *g;
ListOfGlobals *next;
};
static BlockingMutex mu_for_globals(LINKER_INITIALIZED);
static LowLevelAllocator allocator_for_globals;
static ListOfGlobals *list_of_all_globals;
static const int kDynamicInitGlobalsInitialCapacity = 512;
struct DynInitGlobal {
Global g;
bool initialized;
};
typedef InternalMmapVector<DynInitGlobal> VectorOfGlobals;
// Lazy-initialized and never deleted.
static VectorOfGlobals *dynamic_init_globals;
// We want to remember where a certain range of globals was registered.
struct GlobalRegistrationSite {
u32 stack_id;
Global *g_first, *g_last;
};
typedef InternalMmapVector<GlobalRegistrationSite> GlobalRegistrationSiteVector;
static GlobalRegistrationSiteVector *global_registration_site_vector;
ALWAYS_INLINE void PoisonShadowForGlobal(const Global *g, u8 value) {
FastPoisonShadow(g->beg, g->size_with_redzone, value);
}
ALWAYS_INLINE void PoisonRedZones(const Global &g) {
uptr aligned_size = RoundUpTo(g.size, SHADOW_GRANULARITY);
FastPoisonShadow(g.beg + aligned_size, g.size_with_redzone - aligned_size,
kAsanGlobalRedzoneMagic);
if (g.size != aligned_size) {
FastPoisonShadowPartialRightRedzone(
g.beg + RoundDownTo(g.size, SHADOW_GRANULARITY),
g.size % SHADOW_GRANULARITY,
SHADOW_GRANULARITY,
kAsanGlobalRedzoneMagic);
}
}
static void ReportGlobal(const Global &g, const char *prefix) {
Report("%s Global[%p]: beg=%p size=%zu/%zu name=%s module=%s dyn_init=%zu\n",
prefix, &g, (void *)g.beg, g.size, g.size_with_redzone, g.name,
g.module_name, g.has_dynamic_init);
if (g.location) {
Report(" location (%p): name=%s[%p], %d %d\n", g.location,
g.location->filename, g.location->filename, g.location->line_no,
g.location->column_no);
}
}
bool DescribeAddressIfGlobal(uptr addr, uptr size) {
if (!flags()->report_globals) return false;
BlockingMutexLock lock(&mu_for_globals);
bool res = false;
for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
const Global &g = *l->g;
if (flags()->report_globals >= 2)
ReportGlobal(g, "Search");
res |= DescribeAddressRelativeToGlobal(addr, size, g);
}
return res;
}
u32 FindRegistrationSite(const Global *g) {
CHECK(global_registration_site_vector);
for (uptr i = 0, n = global_registration_site_vector->size(); i < n; i++) {
GlobalRegistrationSite &grs = (*global_registration_site_vector)[i];
if (g >= grs.g_first && g <= grs.g_last)
return grs.stack_id;
}
return 0;
}
// Register a global variable.
// This function may be called more than once for every global
// so we store the globals in a map.
static void RegisterGlobal(const Global *g) {
CHECK(asan_inited);
if (flags()->report_globals >= 2)
ReportGlobal(*g, "Added");
CHECK(flags()->report_globals);
CHECK(AddrIsInMem(g->beg));
CHECK(AddrIsAlignedByGranularity(g->beg));
CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
if (flags()->detect_odr_violation) {
// Try detecting ODR (One Definition Rule) violation, i.e. the situation
// where two globals with the same name are defined in different modules.
if (__asan_region_is_poisoned(g->beg, g->size_with_redzone)) {
// This check may not be enough: if the first global is much larger
// the entire redzone of the second global may be within the first global.
for (ListOfGlobals *l = list_of_all_globals; l; l = l->next) {
if (g->beg == l->g->beg &&
(flags()->detect_odr_violation >= 2 || g->size != l->g->size))
ReportODRViolation(g, FindRegistrationSite(g),
l->g, FindRegistrationSite(l->g));
}
}
}
if (flags()->poison_heap)
PoisonRedZones(*g);
ListOfGlobals *l = new(allocator_for_globals) ListOfGlobals;
l->g = g;
l->next = list_of_all_globals;
list_of_all_globals = l;
if (g->has_dynamic_init) {
if (dynamic_init_globals == 0) {
dynamic_init_globals = new(allocator_for_globals)
VectorOfGlobals(kDynamicInitGlobalsInitialCapacity);
}
DynInitGlobal dyn_global = { *g, false };
dynamic_init_globals->push_back(dyn_global);
}
}
static void UnregisterGlobal(const Global *g) {
CHECK(asan_inited);
CHECK(flags()->report_globals);
CHECK(AddrIsInMem(g->beg));
CHECK(AddrIsAlignedByGranularity(g->beg));
CHECK(AddrIsAlignedByGranularity(g->size_with_redzone));
if (flags()->poison_heap)
PoisonShadowForGlobal(g, 0);
// We unpoison the shadow memory for the global but we do not remove it from
// the list because that would require O(n^2) time with the current list
// implementation. It might not be worth doing anyway.
}
void StopInitOrderChecking() {
BlockingMutexLock lock(&mu_for_globals);
if (!flags()->check_initialization_order || !dynamic_init_globals)
return;
flags()->check_initialization_order = false;
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
// Unpoison the whole global.
PoisonShadowForGlobal(g, 0);
// Poison redzones back.
PoisonRedZones(*g);
}
}
} // namespace __asan
// ---------------------- Interface ---------------- {{{1
using namespace __asan; // NOLINT
// Register an array of globals.
void __asan_register_globals(__asan_global *globals, uptr n) {
if (!flags()->report_globals) return;
GET_STACK_TRACE_FATAL_HERE;
u32 stack_id = StackDepotPut(stack.trace, stack.size);
BlockingMutexLock lock(&mu_for_globals);
if (!global_registration_site_vector)
global_registration_site_vector =
new(allocator_for_globals) GlobalRegistrationSiteVector(128);
GlobalRegistrationSite site = {stack_id, &globals[0], &globals[n - 1]};
global_registration_site_vector->push_back(site);
if (flags()->report_globals >= 2) {
PRINT_CURRENT_STACK();
Printf("=== ID %d; %p %p\n", stack_id, &globals[0], &globals[n - 1]);
}
for (uptr i = 0; i < n; i++) {
RegisterGlobal(&globals[i]);
}
}
// Unregister an array of globals.
// We must do this when a shared objects gets dlclosed.
void __asan_unregister_globals(__asan_global *globals, uptr n) {
if (!flags()->report_globals) return;
BlockingMutexLock lock(&mu_for_globals);
for (uptr i = 0; i < n; i++) {
UnregisterGlobal(&globals[i]);
}
}
// This method runs immediately prior to dynamic initialization in each TU,
// when all dynamically initialized globals are unpoisoned. This method
// poisons all global variables not defined in this TU, so that a dynamic
// initializer can only touch global variables in the same TU.
void __asan_before_dynamic_init(const char *module_name) {
if (!flags()->check_initialization_order ||
!flags()->poison_heap)
return;
bool strict_init_order = flags()->strict_init_order;
CHECK(dynamic_init_globals);
CHECK(module_name);
CHECK(asan_inited);
BlockingMutexLock lock(&mu_for_globals);
if (flags()->report_globals >= 3)
Printf("DynInitPoison module: %s\n", module_name);
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
if (dyn_g.initialized)
continue;
if (g->module_name != module_name)
PoisonShadowForGlobal(g, kAsanInitializationOrderMagic);
else if (!strict_init_order)
dyn_g.initialized = true;
}
}
// This method runs immediately after dynamic initialization in each TU, when
// all dynamically initialized globals except for those defined in the current
// TU are poisoned. It simply unpoisons all dynamically initialized globals.
void __asan_after_dynamic_init() {
if (!flags()->check_initialization_order ||
!flags()->poison_heap)
return;
CHECK(asan_inited);
BlockingMutexLock lock(&mu_for_globals);
// FIXME: Optionally report that we're unpoisoning globals from a module.
for (uptr i = 0, n = dynamic_init_globals->size(); i < n; ++i) {
DynInitGlobal &dyn_g = (*dynamic_init_globals)[i];
const Global *g = &dyn_g.g;
if (!dyn_g.initialized) {
// Unpoison the whole global.
PoisonShadowForGlobal(g, 0);
// Poison redzones back.
PoisonRedZones(*g);
}
}
}
|
Use metadata to pass source-level information from Clang to ASan.
|
[ASan] Use metadata to pass source-level information from Clang to ASan.
Instead of creating global variables for source locations and global names,
just create metadata nodes and strings. They will be transformed into actual
globals in the instrumentation pass (if necessary). This approach is more
flexible:
1) we don't have to ensure that our custom globals survive all the optimizations
2) if globals are discarded for some reason, we will simply ignore metadata for them
and won't have to erase corresponding globals
3) metadata for source locations can be reused for other purposes: e.g. we may
attach source location metadata to alloca instructions and provide better descriptions
for stack variables in ASan error reports.
No functionality change.
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@214604 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
a28e769d1f53329b52bdcdefec0078630a633ef0
|
test/src/misc/cifar.cpp
|
test/src/misc/cifar.cpp
|
//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/neural/activation_layer.hpp"
#include "dll/dbn.hpp"
#include "cifar/cifar10_reader.hpp"
// Fully-Connected Network on CIFAR-10
TEST_CASE("cifar/dense/sgd/1", "[dense][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::dense_desc<3 * 32 * 32, 1000>::layer_t,
dll::dense_desc<1000, 500>::layer_t,
dll::dense_desc<500, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = cifar::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 3 * 32 * 32>>(2000);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.01;
dbn->momentum = 0.9;
auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
std::cout << "ft_error:" << ft_error << std::endl;
CHECK(ft_error < 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("cifar/conv/sgd/1", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<3, 32, 32, 6, 5, 5>::layer_t,
dll::conv_desc<6, 28, 28, 6, 5, 5>::layer_t,
dll::dense_desc<6 * 24 * 24, 500>::layer_t,
dll::dense_desc<500, 10, dll::activation<dll::function::SOFTMAX>>::layer_t
>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = cifar::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 3, 32, 32>>(1000);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.01;
dbn->momentum = 0.9;
FT_CHECK(50, 6e-2);
TEST_CHECK(0.2);
}
TEST_CASE("cifar/conv/sgd/2", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<3, 32, 32, 12, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::mp_layer_3d_desc<12, 28, 28, 1, 2, 2>::layer_t,
dll::conv_desc<12, 14, 14, 24, 3, 3, dll::activation<dll::function::RELU>>::layer_t,
dll::mp_layer_3d_desc<24, 12, 12, 1, 2, 2>::layer_t,
dll::dense_desc<24 * 6 * 6, 64, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<64, 10, dll::activation<dll::function::SOFTMAX>>::layer_t
>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = cifar::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 3, 32, 32>>(5000);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.001;
dbn->momentum = 0.9;
FT_CHECK(50, 6e-2);
TEST_CHECK(0.2);
}
|
//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/neural/activation_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/datasets.hpp"
// Fully-Connected Network on CIFAR-10
TEST_CASE("cifar/dense/sgd/1", "[dense][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::dense_desc<3 * 32 * 32, 1000>::layer_t,
dll::dense_desc<1000, 500>::layer_t,
dll::dense_desc<500, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = dll::make_cifar10_dataset_sub(2000, 0, dll::batch_size<20>{});
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.01;
dbn->momentum = 0.9;
FT_CHECK_DATASET(50, 5e-2);
TEST_CHECK_DATASET(0.2);
}
TEST_CASE("cifar/conv/sgd/1", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<3, 32, 32, 6, 5, 5>::layer_t,
dll::conv_desc<6, 28, 28, 6, 5, 5>::layer_t,
dll::dense_desc<6 * 24 * 24, 500>::layer_t,
dll::dense_desc<500, 10, dll::activation<dll::function::SOFTMAX>>::layer_t
>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<20>>::dbn_t dbn_t;
auto dataset = cifar::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 3, 32, 32>>(1000);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.01;
dbn->momentum = 0.9;
FT_CHECK(50, 6e-2);
TEST_CHECK(0.2);
}
TEST_CASE("cifar/conv/sgd/2", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<3, 32, 32, 12, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::mp_layer_3d_desc<12, 28, 28, 1, 2, 2>::layer_t,
dll::conv_desc<12, 14, 14, 24, 3, 3, dll::activation<dll::function::RELU>>::layer_t,
dll::mp_layer_3d_desc<24, 12, 12, 1, 2, 2>::layer_t,
dll::dense_desc<24 * 6 * 6, 64, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<64, 10, dll::activation<dll::function::SOFTMAX>>::layer_t
>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = cifar::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 3, 32, 32>>(5000);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->display();
dbn->learning_rate = 0.001;
dbn->momentum = 0.9;
FT_CHECK(50, 6e-2);
TEST_CHECK(0.2);
}
|
Use the CIFAR-10 dataset reader in a test
|
Use the CIFAR-10 dataset reader in a test
|
C++
|
mit
|
wichtounet/dll,wichtounet/dll,wichtounet/dll
|
2bbada0fc4e89a4b96b93b06c8fa11083100d362
|
test/stressSpectrum.cxx
|
test/stressSpectrum.cxx
|
// @(#)root/test:$name: $:$id: stressSpectrum.cxx,v 1.15 2002/10/25 10:47:51 rdm exp $
// Author: Rene Brun 17/01/2006
/////////////////////////////////////////////////////////////////
//
// TSPectrum test suite
// ====================
//
// This stress program tests many elements of the TSpectrum, TSpectrum2 classes.
//
// To run in batch, do
// stressSpectrum : run 100 experiments with graphics (default)
// stressSpectrum 1000 : run 1000 experiments with graphics
// stressSpectrum -b 200 : run 200 experiments in batch mode
// stressSpectrum -b : run 100 experiments in batch mode
//
// To run interactively, do
// root -b
// Root > .x stressSpectrum.cxx : run 100 experiments with graphics (default)
// Root > .x stressSpectrum.cxx(20) : run 20 experiments
// Root > .x stressSpectrum.cxx+(30) : run 30 experiments via ACLIC
//
// Several tests are run sequentially. Each test will produce one line (Test OK or Test FAILED) .
// At the end of the test a table is printed showing the global results
// Real Time and Cpu Time.
// One single number (ROOTMARKS) is also calculated showing the relative
// performance of your machine compared to a reference machine
// a Pentium IV 3.0 Ghz) with 512 MBytes of memory
// and 120 GBytes IDE disk.
//
// An example of output when all the tests run OK is shown below:
//
//////////////////////////////////////////////////////////////////////////
// //
//****************************************************************************
//* Starting stress S P E C T R U M *
//****************************************************************************
//Peak1 : found = 62.52/ 68.94, good = 66.64/ 67.11, ghost = 6.52/ 8.56,--- OK
//Peak2 : found =173/300, good =173, ghost =7,----------------------------- OK
//****************************************************************************
//stressSpectrum: Real Time = 19.86 seconds Cpu Time = 19.04 seconds
//****************************************************************************
//* ROOTMARKS = 810.9 * Root5.09/01 20051216/1229
//****************************************************************************
#include "TApplication.h"
#include "TBenchmark.h"
#include "TCanvas.h"
#include "TH2.h"
#include "TF2.h"
#include "TRandom.h"
#include "TSpectrum.h"
#include "TSpectrum2.h"
#include "TStyle.h"
#include "Riostream.h"
#include "TROOT.h"
Int_t npeaks;
Double_t fpeaks(Double_t *x, Double_t *par) {
Double_t result = par[0] + par[1]*x[0];
for (Int_t p=0;p<npeaks;p++) {
Double_t norm = par[3*p+2];
Double_t mean = par[3*p+3];
Double_t sigma = par[3*p+4];
result += norm*TMath::Gaus(x[0],mean,sigma);
}
return result;
}
Double_t fpeaks2(Double_t *x, Double_t *par) {
Double_t result = 0.1;
for (Int_t p=0;p<npeaks;p++) {
Double_t norm = par[5*p+0];
Double_t mean1 = par[5*p+1];
Double_t sigma1 = par[5*p+2];
Double_t mean2 = par[5*p+3];
Double_t sigma2 = par[5*p+4];
result += norm*TMath::Gaus(x[0],mean1,sigma1)*TMath::Gaus(x[1],mean2,sigma2);
}
return result;
}
void findPeaks(Int_t pmin, Int_t pmax, Int_t &nfound, Int_t &ngood, Int_t &nghost) {
npeaks = (Int_t)gRandom->Uniform(pmin,pmax);
Int_t nbins = 500;
Double_t dxbins = 2;
TH1F *h = new TH1F("h","test",nbins,0,nbins*dxbins);
//generate n peaks at random
Double_t par[3000];
par[0] = 0.8;
par[1] = -0.6/1000;
Int_t p,pf;
for (p=0;p<npeaks;p++) {
par[3*p+2] = 1;
par[3*p+3] = 10+gRandom->Rndm()*(nbins-20)*dxbins;
par[3*p+4] = 3+2*gRandom->Rndm();
}
TF1 *f = new TF1("f",fpeaks,0,nbins*dxbins,2+3*npeaks);
f->SetNpx(1000);
f->SetParameters(par);
h->FillRandom("f",200000);
TSpectrum *s = new TSpectrum(4*npeaks);
nfound = s->Search(h,2,"goff");
//Search found peaks
ngood = 0;
Float_t *xpeaks = s->GetPositionX();
for (p=0;p<npeaks;p++) {
for (Int_t pf=0;pf<nfound;pf++) {
Double_t dx = TMath::Abs(xpeaks[pf] - par[3*p+3]);
if (dx <dxbins) ngood++;
}
}
//Search ghost peaks
nghost = 0;
for (pf=0;pf<nfound;pf++) {
Int_t nf=0;
for (Int_t p=0;p<npeaks;p++) {
Double_t dx = TMath::Abs(xpeaks[pf] - par[3*p+3]);
if (dx <dxbins) nf++;
}
if (nf == 0) nghost++;
}
delete f;
delete h;
delete s;
}
void stress1(Int_t ntimes) {
Int_t pmin = 5;
Int_t pmax = 55;
TCanvas *c1 = new TCanvas("c1","Spectrum results",10,10,800,800);
c1->Divide(2,2);
gStyle->SetOptFit();
TH1F *hpeaks = new TH1F("hpeaks","Number of peaks",pmax-pmin,pmin,pmax);
TH1F *hfound = new TH1F("hfound","% peak founds",100,0,100);
TH1F *hgood = new TH1F("hgood", "% good peaks",100,0,100);
TH1F *hghost = new TH1F("hghost","% ghost peaks",100,0,100);
Int_t nfound,ngood,nghost;
for (Int_t i=0;i<ntimes;i++) {
findPeaks(pmin,pmax,nfound,ngood,nghost);
hpeaks->Fill(npeaks);
hfound->Fill(100*Double_t(nfound)/Double_t(npeaks));
hgood->Fill(100*Double_t(ngood)/Double_t(npeaks));
hghost->Fill(100*Double_t(nghost)/Double_t(npeaks));
//printf("npeaks = %d, nfound = %d, ngood = %d, nghost = %d\n",npeaks,nfound,ngood,nghost);
}
c1->cd(1);
hpeaks->Fit("pol1","lq");
c1->cd(2);
hfound->Fit("gaus","lq");
c1->cd(3);
hgood->Fit("gaus","lq");
c1->cd(4);
hghost->Fit("gaus","lq","",0,30);
c1->cd();
Double_t p1 = hfound->GetFunction("gaus")->GetParameter(1);
Double_t ep1 = hfound->GetFunction("gaus")->GetParError(1);
Double_t p2 = hgood->GetFunction("gaus")->GetParameter(1);
Double_t ep2 = hgood->GetFunction("gaus")->GetParError(1);
Double_t p3 = hghost->GetFunction("gaus")->GetParameter(1);
Double_t ep3 = hghost->GetFunction("gaus")->GetParError(1);
Double_t p1ref = 68.94; //ref numbers obtained with ntimes=1000
Double_t p2ref = 67.11;
Double_t p3ref = 8.56;
//printf("p1=%g+-%g, p2=%g+-%g, p3=%g+-%g\n",p1,ep1,p2,ep2,p3,ep3);
char sok[20];
if (TMath::Abs(p1ref-p1) < 2*ep1 && TMath::Abs(p2ref-p2) < 2*ep2 && TMath::Abs(p3ref-p3) < 2*ep3 ) {
sprintf(sok,"OK");
} else {
sprintf(sok,"failed");
}
printf("Peak1 : found =%6.2f/%6.2f, good =%6.2f/%6.2f, ghost =%5.2f/%5.2f,--- %s\n",
p1,p1ref,p2,p2ref,p3,p3ref,sok);
}
void stress2(Int_t np2) {
npeaks = np2;
TRandom r;
Int_t nbinsx = 200;
Int_t nbinsy = 200;
Double_t xmin = 0;
Double_t xmax = (Double_t)nbinsx;
Double_t ymin = 0;
Double_t ymax = (Double_t)nbinsy;
Double_t dx = (xmax-xmin)/nbinsx;
Double_t dy = (ymax-ymin)/nbinsy;
TH2F *h2 = new TH2F("h2","test",nbinsx,xmin,xmax,nbinsy,ymin,ymax);
h2->SetStats(0);
//generate n peaks at random
Double_t par[3000];
Int_t p;
for (p=0;p<npeaks;p++) {
par[5*p+0] = r.Uniform(0.2,1);
par[5*p+1] = r.Uniform(xmin,xmax);
par[5*p+2] = r.Uniform(dx,5*dx);
par[5*p+3] = r.Uniform(ymin,ymax);
par[5*p+4] = r.Uniform(dy,5*dy);
}
TF2 *f2 = new TF2("f2",fpeaks2,xmin,xmax,ymin,ymax,5*npeaks);
f2->SetNpx(100);
f2->SetNpy(100);
f2->SetParameters(par);
h2->FillRandom("f2",500000);
//now the real stuff
TSpectrum2 *s = new TSpectrum2(2*npeaks);
Int_t nfound = s->Search(h2,2,"goff");
//searching good and ghost peaks (approximation)
Int_t pf,ngood = 0;
Float_t *xpeaks = s->GetPositionX();
Float_t *ypeaks = s->GetPositionY();
for (p=0;p<npeaks;p++) {
for (Int_t pf=0;pf<nfound;pf++) {
Double_t diffx = TMath::Abs(xpeaks[pf] - par[5*p+1]);
Double_t diffy = TMath::Abs(ypeaks[pf] - par[5*p+3]);
if (diffx < 2*dx && diffy < 2*dy) ngood++;
}
}
if (ngood > nfound) ngood = nfound;
//Search ghost peaks (approximation)
Int_t nghost = 0;
for (pf=0;pf<nfound;pf++) {
Int_t nf=0;
for (Int_t p=0;p<npeaks;p++) {
Double_t diffx = TMath::Abs(xpeaks[pf] - par[5*p+1]);
Double_t diffy = TMath::Abs(ypeaks[pf] - par[5*p+3]);
if (diffx < 2*dx && diffy < 2*dy) nf++;
}
if (nf == 0) nghost++;
}
delete s;
delete f2;
delete h2;
Int_t nfoundRef = 174;
Int_t ngoodRef = 174;
Int_t nghostRef = 7;
char sok[20];
if (nfound == nfoundRef && ngood == ngoodRef && nghost == nghostRef) {
sprintf(sok,"OK");
} else {
sprintf(sok,"failed");
}
printf("Peak2 : found =%d/%d, good =%d, ghost =%d,----------------------------- %s\n",
nfound,npeaks,ngood,nghost,sok);
}
#ifndef __CINT__
void stressSpectrum(Int_t ntimes) {
#else
void stressSpectrum(Int_t ntimes=100) {
#endif
cout << "****************************************************************************" <<endl;
cout << "* Starting stress S P E C T R U M *" <<endl;
cout << "****************************************************************************" <<endl;
gBenchmark->Start("stressSpectrum");
stress1(ntimes);
stress2(300);
gBenchmark->Stop ("stressSpectrum");
Double_t reftime100 = 19.04; //pcbrun compiled
Double_t ct = gBenchmark->GetCpuTime("stressSpectrum");
const Double_t rootmarks = 800*reftime100*ntimes/(100*ct);
printf("****************************************************************************\n");
gBenchmark->Print("stressSpectrum");
printf("****************************************************************************\n");
printf("* ROOTMARKS =%6.1f * Root%-8s %d/%d\n",rootmarks,gROOT->GetVersion(),
gROOT->GetVersionDate(),gROOT->GetVersionTime());
printf("****************************************************************************\n");
}
#ifndef __CINT__
int main(int argc, char **argv)
{
TApplication theApp("App", &argc, argv);
gROOT->SetBatch();
gBenchmark = new TBenchmark();
Int_t ntimes = 100;
if (argc > 1) ntimes = atoi(argv[1]);
stressSpectrum(ntimes);
return 0;
}
#endif
|
// @(#)root/test:$name: $:$id: stressSpectrum.cxx,v 1.15 2002/10/25 10:47:51 rdm exp $
// Author: Rene Brun 17/01/2006
/////////////////////////////////////////////////////////////////
//
// TSPectrum test suite
// ====================
//
// This stress program tests many elements of the TSpectrum, TSpectrum2 classes.
//
// To run in batch, do
// stressSpectrum : run 100 experiments with graphics (default)
// stressSpectrum 1000 : run 1000 experiments with graphics
// stressSpectrum -b 200 : run 200 experiments in batch mode
// stressSpectrum -b : run 100 experiments in batch mode
//
// To run interactively, do
// root -b
// Root > .x stressSpectrum.cxx : run 100 experiments with graphics (default)
// Root > .x stressSpectrum.cxx(20) : run 20 experiments
// Root > .x stressSpectrum.cxx+(30) : run 30 experiments via ACLIC
//
// Several tests are run sequentially. Each test will produce one line (Test OK or Test FAILED) .
// At the end of the test a table is printed showing the global results
// Real Time and Cpu Time.
// One single number (ROOTMARKS) is also calculated showing the relative
// performance of your machine compared to a reference machine
// a Pentium IV 3.0 Ghz) with 512 MBytes of memory
// and 120 GBytes IDE disk.
//
// An example of output when all the tests run OK is shown below:
//
//////////////////////////////////////////////////////////////////////////
// //
//****************************************************************************
//* Starting stress S P E C T R U M *
//****************************************************************************
//Peak1 : found = 62.52/ 68.94, good = 66.64/ 67.11, ghost = 6.52/ 8.56,--- OK
//Peak2 : found =173/300, good =173, ghost =7,----------------------------- OK
//****************************************************************************
//stressSpectrum: Real Time = 19.86 seconds Cpu Time = 19.04 seconds
//****************************************************************************
//* ROOTMARKS = 810.9 * Root5.09/01 20051216/1229
//****************************************************************************
#include "TApplication.h"
#include "TBenchmark.h"
#include "TCanvas.h"
#include "TH2.h"
#include "TF2.h"
#include "TRandom.h"
#include "TSpectrum.h"
#include "TSpectrum2.h"
#include "TStyle.h"
#include "Riostream.h"
#include "TROOT.h"
Int_t npeaks;
Double_t fpeaks(Double_t *x, Double_t *par) {
Double_t result = par[0] + par[1]*x[0];
for (Int_t p=0;p<npeaks;p++) {
Double_t norm = par[3*p+2];
Double_t mean = par[3*p+3];
Double_t sigma = par[3*p+4];
result += norm*TMath::Gaus(x[0],mean,sigma);
}
return result;
}
Double_t fpeaks2(Double_t *x, Double_t *par) {
Double_t result = 0.1;
for (Int_t p=0;p<npeaks;p++) {
Double_t norm = par[5*p+0];
Double_t mean1 = par[5*p+1];
Double_t sigma1 = par[5*p+2];
Double_t mean2 = par[5*p+3];
Double_t sigma2 = par[5*p+4];
result += norm*TMath::Gaus(x[0],mean1,sigma1)*TMath::Gaus(x[1],mean2,sigma2);
}
return result;
}
void findPeaks(Int_t pmin, Int_t pmax, Int_t &nfound, Int_t &ngood, Int_t &nghost) {
npeaks = (Int_t)gRandom->Uniform(pmin,pmax);
Int_t nbins = 500;
Double_t dxbins = 2;
TH1F *h = new TH1F("h","test",nbins,0,nbins*dxbins);
//generate n peaks at random
Double_t par[3000];
par[0] = 0.8;
par[1] = -0.6/1000;
Int_t p,pf;
for (p=0;p<npeaks;p++) {
par[3*p+2] = 1;
par[3*p+3] = 10+gRandom->Rndm()*(nbins-20)*dxbins;
par[3*p+4] = 3+2*gRandom->Rndm();
}
TF1 *f = new TF1("f",fpeaks,0,nbins*dxbins,2+3*npeaks);
f->SetNpx(1000);
f->SetParameters(par);
h->FillRandom("f",200000);
TSpectrum *s = new TSpectrum(4*npeaks);
nfound = s->Search(h,2,"goff");
//Search found peaks
ngood = 0;
Float_t *xpeaks = s->GetPositionX();
for (p=0;p<npeaks;p++) {
for (Int_t pf=0;pf<nfound;pf++) {
Double_t dx = TMath::Abs(xpeaks[pf] - par[3*p+3]);
if (dx <dxbins) ngood++;
}
}
//Search ghost peaks
nghost = 0;
for (pf=0;pf<nfound;pf++) {
Int_t nf=0;
for (Int_t p=0;p<npeaks;p++) {
Double_t dx = TMath::Abs(xpeaks[pf] - par[3*p+3]);
if (dx <dxbins) nf++;
}
if (nf == 0) nghost++;
}
delete f;
delete h;
delete s;
}
void stress1(Int_t ntimes) {
Int_t pmin = 5;
Int_t pmax = 55;
TCanvas *c1 = new TCanvas("c1","Spectrum results",10,10,800,800);
c1->Divide(2,2);
gStyle->SetOptFit();
TH1F *hpeaks = new TH1F("hpeaks","Number of peaks",pmax-pmin,pmin,pmax);
TH1F *hfound = new TH1F("hfound","% peak founds",100,0,100);
TH1F *hgood = new TH1F("hgood", "% good peaks",100,0,100);
TH1F *hghost = new TH1F("hghost","% ghost peaks",100,0,100);
Int_t nfound,ngood,nghost;
for (Int_t i=0;i<ntimes;i++) {
findPeaks(pmin,pmax,nfound,ngood,nghost);
hpeaks->Fill(npeaks);
hfound->Fill(100*Double_t(nfound)/Double_t(npeaks));
hgood->Fill(100*Double_t(ngood)/Double_t(npeaks));
hghost->Fill(100*Double_t(nghost)/Double_t(npeaks));
//printf("npeaks = %d, nfound = %d, ngood = %d, nghost = %d\n",npeaks,nfound,ngood,nghost);
}
c1->cd(1);
hpeaks->Fit("pol1","lq");
c1->cd(2);
hfound->Fit("gaus","lq");
c1->cd(3);
hgood->Fit("gaus","lq");
c1->cd(4);
hghost->Fit("gaus","lq","",0,30);
c1->cd();
Double_t p1 = hfound->GetFunction("gaus")->GetParameter(1);
Double_t ep1 = hfound->GetFunction("gaus")->GetParError(1);
Double_t p2 = hgood->GetFunction("gaus")->GetParameter(1);
Double_t ep2 = hgood->GetFunction("gaus")->GetParError(1);
Double_t p3 = hghost->GetFunction("gaus")->GetParameter(1);
Double_t ep3 = hghost->GetFunction("gaus")->GetParError(1);
Double_t p1ref = 73.75; //ref numbers obtained with ntimes=1000
Double_t p2ref = 68.60;
Double_t p3ref = 8.39;
//printf("p1=%g+-%g, p2=%g+-%g, p3=%g+-%g\n",p1,ep1,p2,ep2,p3,ep3);
char sok[20];
if (TMath::Abs(p1ref-p1) < 2*ep1 && TMath::Abs(p2ref-p2) < 2*ep2 && TMath::Abs(p3ref-p3) < 2*ep3 ) {
sprintf(sok,"OK");
} else {
sprintf(sok,"failed");
}
printf("Peak1 : found =%6.2f/%6.2f, good =%6.2f/%6.2f, ghost =%5.2f/%5.2f,--- %s\n",
p1,p1ref,p2,p2ref,p3,p3ref,sok);
}
void stress2(Int_t np2) {
npeaks = np2;
TRandom r;
Int_t nbinsx = 200;
Int_t nbinsy = 200;
Double_t xmin = 0;
Double_t xmax = (Double_t)nbinsx;
Double_t ymin = 0;
Double_t ymax = (Double_t)nbinsy;
Double_t dx = (xmax-xmin)/nbinsx;
Double_t dy = (ymax-ymin)/nbinsy;
TH2F *h2 = new TH2F("h2","test",nbinsx,xmin,xmax,nbinsy,ymin,ymax);
h2->SetStats(0);
//generate n peaks at random
Double_t par[3000];
Int_t p;
for (p=0;p<npeaks;p++) {
par[5*p+0] = r.Uniform(0.2,1);
par[5*p+1] = r.Uniform(xmin,xmax);
par[5*p+2] = r.Uniform(dx,5*dx);
par[5*p+3] = r.Uniform(ymin,ymax);
par[5*p+4] = r.Uniform(dy,5*dy);
}
TF2 *f2 = new TF2("f2",fpeaks2,xmin,xmax,ymin,ymax,5*npeaks);
f2->SetNpx(100);
f2->SetNpy(100);
f2->SetParameters(par);
h2->FillRandom("f2",500000);
//now the real stuff
TSpectrum2 *s = new TSpectrum2(2*npeaks);
Int_t nfound = s->Search(h2,2,"goff");
//searching good and ghost peaks (approximation)
Int_t pf,ngood = 0;
Float_t *xpeaks = s->GetPositionX();
Float_t *ypeaks = s->GetPositionY();
for (p=0;p<npeaks;p++) {
for (Int_t pf=0;pf<nfound;pf++) {
Double_t diffx = TMath::Abs(xpeaks[pf] - par[5*p+1]);
Double_t diffy = TMath::Abs(ypeaks[pf] - par[5*p+3]);
if (diffx < 2*dx && diffy < 2*dy) ngood++;
}
}
if (ngood > nfound) ngood = nfound;
//Search ghost peaks (approximation)
Int_t nghost = 0;
for (pf=0;pf<nfound;pf++) {
Int_t nf=0;
for (Int_t p=0;p<npeaks;p++) {
Double_t diffx = TMath::Abs(xpeaks[pf] - par[5*p+1]);
Double_t diffy = TMath::Abs(ypeaks[pf] - par[5*p+3]);
if (diffx < 2*dx && diffy < 2*dy) nf++;
}
if (nf == 0) nghost++;
}
delete s;
delete f2;
delete h2;
Int_t nfoundRef = 165;
Int_t ngoodRef = 165;
Int_t nghostRef = 12;
char sok[20];
if (nfound == nfoundRef && ngood == ngoodRef && nghost == nghostRef) {
sprintf(sok,"OK");
} else {
sprintf(sok,"failed");
}
printf("Peak2 : found =%d/%d, good =%d, ghost =%d,---------------------------- %s\n",
nfound,npeaks,ngood,nghost,sok);
}
#ifndef __CINT__
void stressSpectrum(Int_t ntimes) {
#else
void stressSpectrum(Int_t ntimes=100) {
#endif
cout << "****************************************************************************" <<endl;
cout << "* Starting stress S P E C T R U M *" <<endl;
cout << "****************************************************************************" <<endl;
gBenchmark->Start("stressSpectrum");
stress1(ntimes);
stress2(300);
gBenchmark->Stop ("stressSpectrum");
Double_t reftime100 = 19.04; //pcbrun compiled
Double_t ct = gBenchmark->GetCpuTime("stressSpectrum");
const Double_t rootmarks = 800*reftime100*ntimes/(100*ct);
printf("****************************************************************************\n");
gBenchmark->Print("stressSpectrum");
printf("****************************************************************************\n");
printf("* ROOTMARKS =%6.1f * Root%-8s %d/%d\n",rootmarks,gROOT->GetVersion(),
gROOT->GetVersionDate(),gROOT->GetVersionTime());
printf("****************************************************************************\n");
}
#ifndef __CINT__
int main(int argc, char **argv)
{
TApplication theApp("App", &argc, argv);
gROOT->SetBatch();
gBenchmark = new TBenchmark();
Int_t ntimes = 100;
if (argc > 1) ntimes = atoi(argv[1]);
stressSpectrum(ntimes);
return 0;
}
#endif
|
Change the reference values following the move from TRandom to TRandom3
|
Change the reference values following the move from TRandom to TRandom3
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@15115 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
cxx-hep/root-cern,beniz/root,CristinaCristescu/root,Y--/root,sawenzel/root,sbinet/cxx-root,root-mirror/root,mhuwiler/rootauto,ffurano/root5,veprbl/root,0x0all/ROOT,Duraznos/root,bbockelm/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,karies/root,Duraznos/root,vukasinmilosevic/root,sbinet/cxx-root,mhuwiler/rootauto,esakellari/my_root_for_test,alexschlueter/cern-root,sirinath/root,dfunke/root,arch1tect0r/root,tc3t/qoot,pspe/root,kirbyherm/root-r-tools,gbitzes/root,thomaskeck/root,abhinavmoudgil95/root,beniz/root,evgeny-boger/root,Duraznos/root,mattkretz/root,perovic/root,cxx-hep/root-cern,jrtomps/root,zzxuanyuan/root,sirinath/root,evgeny-boger/root,pspe/root,davidlt/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,bbockelm/root,georgtroska/root,sbinet/cxx-root,bbockelm/root,beniz/root,sirinath/root,pspe/root,karies/root,Duraznos/root,Y--/root,mhuwiler/rootauto,gganis/root,satyarth934/root,ffurano/root5,davidlt/root,root-mirror/root,omazapa/root-old,simonpf/root,perovic/root,mattkretz/root,veprbl/root,esakellari/root,esakellari/root,veprbl/root,buuck/root,abhinavmoudgil95/root,smarinac/root,dfunke/root,Dr15Jones/root,0x0all/ROOT,esakellari/root,simonpf/root,simonpf/root,nilqed/root,beniz/root,gganis/root,arch1tect0r/root,nilqed/root,ffurano/root5,sbinet/cxx-root,bbockelm/root,gganis/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,agarciamontoro/root,alexschlueter/cern-root,sbinet/cxx-root,simonpf/root,abhinavmoudgil95/root,cxx-hep/root-cern,BerserkerTroll/root,zzxuanyuan/root,jrtomps/root,dfunke/root,tc3t/qoot,arch1tect0r/root,omazapa/root-old,omazapa/root-old,lgiommi/root,omazapa/root,buuck/root,veprbl/root,cxx-hep/root-cern,olifre/root,BerserkerTroll/root,sawenzel/root,krafczyk/root,davidlt/root,Dr15Jones/root,simonpf/root,sbinet/cxx-root,pspe/root,evgeny-boger/root,thomaskeck/root,mattkretz/root,abhinavmoudgil95/root,buuck/root,esakellari/root,sirinath/root,gganis/root,mkret2/root,zzxuanyuan/root,Y--/root,sirinath/root,smarinac/root,satyarth934/root,beniz/root,krafczyk/root,mkret2/root,arch1tect0r/root,mkret2/root,olifre/root,CristinaCristescu/root,agarciamontoro/root,dfunke/root,evgeny-boger/root,root-mirror/root,lgiommi/root,lgiommi/root,veprbl/root,zzxuanyuan/root,vukasinmilosevic/root,thomaskeck/root,omazapa/root-old,bbockelm/root,mattkretz/root,krafczyk/root,sawenzel/root,evgeny-boger/root,mkret2/root,davidlt/root,strykejern/TTreeReader,strykejern/TTreeReader,esakellari/root,perovic/root,evgeny-boger/root,abhinavmoudgil95/root,root-mirror/root,omazapa/root-old,ffurano/root5,thomaskeck/root,karies/root,omazapa/root-old,mattkretz/root,omazapa/root,karies/root,Dr15Jones/root,jrtomps/root,esakellari/root,jrtomps/root,nilqed/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,beniz/root,omazapa/root-old,beniz/root,buuck/root,zzxuanyuan/root,kirbyherm/root-r-tools,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,omazapa/root-old,cxx-hep/root-cern,thomaskeck/root,BerserkerTroll/root,omazapa/root,satyarth934/root,tc3t/qoot,strykejern/TTreeReader,sbinet/cxx-root,dfunke/root,root-mirror/root,sirinath/root,simonpf/root,simonpf/root,mattkretz/root,mhuwiler/rootauto,mhuwiler/rootauto,buuck/root,mkret2/root,georgtroska/root,olifre/root,CristinaCristescu/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,smarinac/root,arch1tect0r/root,zzxuanyuan/root,sirinath/root,omazapa/root-old,mhuwiler/rootauto,smarinac/root,strykejern/TTreeReader,lgiommi/root,esakellari/my_root_for_test,gbitzes/root,buuck/root,simonpf/root,satyarth934/root,dfunke/root,zzxuanyuan/root,arch1tect0r/root,davidlt/root,tc3t/qoot,zzxuanyuan/root-compressor-dummy,Y--/root,nilqed/root,tc3t/qoot,beniz/root,karies/root,satyarth934/root,0x0all/ROOT,satyarth934/root,thomaskeck/root,alexschlueter/cern-root,arch1tect0r/root,perovic/root,satyarth934/root,agarciamontoro/root,evgeny-boger/root,sirinath/root,smarinac/root,tc3t/qoot,kirbyherm/root-r-tools,davidlt/root,BerserkerTroll/root,mhuwiler/rootauto,pspe/root,gganis/root,mhuwiler/rootauto,mattkretz/root,evgeny-boger/root,satyarth934/root,mhuwiler/rootauto,buuck/root,dfunke/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,georgtroska/root,thomaskeck/root,mkret2/root,vukasinmilosevic/root,Duraznos/root,olifre/root,omazapa/root,smarinac/root,sawenzel/root,Y--/root,veprbl/root,zzxuanyuan/root,beniz/root,gbitzes/root,simonpf/root,esakellari/my_root_for_test,root-mirror/root,krafczyk/root,georgtroska/root,cxx-hep/root-cern,BerserkerTroll/root,tc3t/qoot,buuck/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,perovic/root,Y--/root,karies/root,root-mirror/root,veprbl/root,root-mirror/root,sbinet/cxx-root,Duraznos/root,bbockelm/root,arch1tect0r/root,olifre/root,lgiommi/root,esakellari/root,BerserkerTroll/root,satyarth934/root,nilqed/root,bbockelm/root,lgiommi/root,root-mirror/root,esakellari/my_root_for_test,gbitzes/root,perovic/root,karies/root,BerserkerTroll/root,esakellari/root,georgtroska/root,veprbl/root,strykejern/TTreeReader,lgiommi/root,tc3t/qoot,agarciamontoro/root,arch1tect0r/root,davidlt/root,lgiommi/root,davidlt/root,CristinaCristescu/root,olifre/root,zzxuanyuan/root,evgeny-boger/root,beniz/root,bbockelm/root,gbitzes/root,omazapa/root-old,Dr15Jones/root,olifre/root,gbitzes/root,gbitzes/root,Duraznos/root,smarinac/root,alexschlueter/cern-root,Duraznos/root,gganis/root,nilqed/root,esakellari/root,olifre/root,nilqed/root,karies/root,omazapa/root,agarciamontoro/root,sirinath/root,esakellari/my_root_for_test,agarciamontoro/root,agarciamontoro/root,nilqed/root,sbinet/cxx-root,satyarth934/root,veprbl/root,jrtomps/root,agarciamontoro/root,krafczyk/root,nilqed/root,sawenzel/root,georgtroska/root,dfunke/root,omazapa/root,bbockelm/root,vukasinmilosevic/root,esakellari/my_root_for_test,olifre/root,veprbl/root,omazapa/root,Y--/root,karies/root,Duraznos/root,CristinaCristescu/root,thomaskeck/root,0x0all/ROOT,gganis/root,omazapa/root-old,perovic/root,buuck/root,dfunke/root,cxx-hep/root-cern,omazapa/root,Duraznos/root,abhinavmoudgil95/root,lgiommi/root,sawenzel/root,alexschlueter/cern-root,omazapa/root,CristinaCristescu/root,zzxuanyuan/root,Y--/root,jrtomps/root,georgtroska/root,Y--/root,buuck/root,mkret2/root,karies/root,gbitzes/root,sirinath/root,ffurano/root5,thomaskeck/root,evgeny-boger/root,sawenzel/root,esakellari/my_root_for_test,simonpf/root,root-mirror/root,vukasinmilosevic/root,zzxuanyuan/root,pspe/root,vukasinmilosevic/root,mkret2/root,buuck/root,nilqed/root,alexschlueter/cern-root,beniz/root,olifre/root,kirbyherm/root-r-tools,sawenzel/root,CristinaCristescu/root,jrtomps/root,kirbyherm/root-r-tools,pspe/root,smarinac/root,gbitzes/root,esakellari/my_root_for_test,mkret2/root,zzxuanyuan/root-compressor-dummy,sawenzel/root,perovic/root,abhinavmoudgil95/root,krafczyk/root,cxx-hep/root-cern,simonpf/root,Dr15Jones/root,abhinavmoudgil95/root,mhuwiler/rootauto,CristinaCristescu/root,veprbl/root,0x0all/ROOT,krafczyk/root,tc3t/qoot,ffurano/root5,georgtroska/root,mkret2/root,agarciamontoro/root,karies/root,vukasinmilosevic/root,vukasinmilosevic/root,olifre/root,CristinaCristescu/root,perovic/root,davidlt/root,omazapa/root,esakellari/my_root_for_test,BerserkerTroll/root,Duraznos/root,davidlt/root,esakellari/root,gganis/root,gganis/root,evgeny-boger/root,strykejern/TTreeReader,BerserkerTroll/root,mattkretz/root,agarciamontoro/root,zzxuanyuan/root,bbockelm/root,sawenzel/root,bbockelm/root,krafczyk/root,pspe/root,sbinet/cxx-root,mattkretz/root,gbitzes/root,smarinac/root,CristinaCristescu/root,pspe/root,0x0all/ROOT,georgtroska/root,mattkretz/root,lgiommi/root,jrtomps/root,dfunke/root,nilqed/root,perovic/root,jrtomps/root,agarciamontoro/root,vukasinmilosevic/root,gganis/root,mhuwiler/rootauto,root-mirror/root,pspe/root,Dr15Jones/root,dfunke/root,0x0all/ROOT,vukasinmilosevic/root,jrtomps/root,mkret2/root,gganis/root,strykejern/TTreeReader,georgtroska/root,omazapa/root,vukasinmilosevic/root,lgiommi/root,alexschlueter/cern-root,kirbyherm/root-r-tools,sbinet/cxx-root,BerserkerTroll/root,sirinath/root,ffurano/root5,0x0all/ROOT,perovic/root,CristinaCristescu/root,satyarth934/root,Y--/root,abhinavmoudgil95/root,georgtroska/root,sawenzel/root,davidlt/root,gbitzes/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,smarinac/root,tc3t/qoot,kirbyherm/root-r-tools,pspe/root,esakellari/root,thomaskeck/root,Y--/root,abhinavmoudgil95/root,jrtomps/root,Dr15Jones/root,BerserkerTroll/root
|
a734936d106f7001326870ee8e304ca9baf1a463
|
ouzel/utils/Utils.hpp
|
ouzel/utils/Utils.hpp
|
// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_UTILS_UTILS_HPP
#define OUZEL_UTILS_UTILS_HPP
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <limits>
#include <random>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
namespace ouzel
{
extern std::mt19937 randomEngine;
template <typename T>
inline size_t getVectorSize(const typename std::vector<T>& vec)
{
return sizeof(T) * vec.size();
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T decodeBigEndian(const void* buffer)
{
const uint8_t* bytes = static_cast<const uint8_t*>(buffer);
T result = 0;
for (uintptr_t i = 0; i < sizeof(T); ++i)
result |= static_cast<T>(bytes[sizeof(buffer) - i - 1] << (i * 8));
return result;
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T decodeLittleEndian(const void* buffer)
{
const uint8_t* bytes = static_cast<const uint8_t*>(buffer);
T result = 0;
for (uintptr_t i = 0; i < sizeof(T); ++i)
result |= static_cast<T>(bytes[i] << (i * 8));
return result;
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline void encodeBigEndian(void* buffer, T value)
{
uint8_t* bytes = static_cast<uint8_t*>(buffer);
for (uintptr_t i = 0; i < sizeof(T); ++i)
bytes[i] = static_cast<uint8_t>(value >> ((sizeof(T) - i - 1) * 8));
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T encodeLittleEndian(void* buffer, T value)
{
uint8_t* bytes = static_cast<uint8_t*>(buffer);
for (uintptr_t i = 0; i < sizeof(T); ++i)
bytes[i] = static_cast<uint8_t>(value >> (i * 8));
}
template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
std::string hexToString(T n, size_t len = 0)
{
static constexpr const char* digits = "0123456789ABCDEF";
if (len == 0)
{
uint64_t t = static_cast<uint64_t>(n);
do
{
t >>= 4;
++len;
}
while (t);
}
std::string result(len, '0');
for (size_t i = 0, j = (len - 1) * 4; i < len; ++i, j -= 4)
result[i] = digits[(n >> j) & 0x0F];
return result;
}
inline std::vector<std::string> explodeString(const std::string& str, char delimiter = ' ')
{
std::string buffer;
std::vector<std::string> result;
for(char c : str)
if (c != delimiter) buffer.push_back(c);
else if (c == delimiter && !buffer.empty())
{
result.push_back(buffer);
buffer.clear();
}
if (!buffer.empty()) result.push_back(buffer);
return result;
}
void setCurrentThreadName(const std::string& name);
void setThreadPriority(std::thread& t, float priority, bool realtime);
}
#endif // OUZEL_UTILS_UTILS_HPP
|
// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_UTILS_UTILS_HPP
#define OUZEL_UTILS_UTILS_HPP
#include <cstdint>
#include <cstdlib>
#include <random>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
namespace ouzel
{
extern std::mt19937 randomEngine;
template <typename T>
inline size_t getVectorSize(const typename std::vector<T>& vec)
{
return sizeof(T) * vec.size();
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T decodeBigEndian(const void* buffer)
{
const uint8_t* bytes = static_cast<const uint8_t*>(buffer);
T result = 0;
for (uintptr_t i = 0; i < sizeof(T); ++i)
result |= static_cast<T>(bytes[sizeof(buffer) - i - 1] << (i * 8));
return result;
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T decodeLittleEndian(const void* buffer)
{
const uint8_t* bytes = static_cast<const uint8_t*>(buffer);
T result = 0;
for (uintptr_t i = 0; i < sizeof(T); ++i)
result |= static_cast<T>(bytes[i] << (i * 8));
return result;
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline void encodeBigEndian(void* buffer, T value)
{
uint8_t* bytes = static_cast<uint8_t*>(buffer);
for (uintptr_t i = 0; i < sizeof(T); ++i)
bytes[i] = static_cast<uint8_t>(value >> ((sizeof(T) - i - 1) * 8));
}
template <class T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
inline T encodeLittleEndian(void* buffer, T value)
{
uint8_t* bytes = static_cast<uint8_t*>(buffer);
for (uintptr_t i = 0; i < sizeof(T); ++i)
bytes[i] = static_cast<uint8_t>(value >> (i * 8));
}
template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
std::string hexToString(T n, size_t len = 0)
{
static constexpr const char* digits = "0123456789ABCDEF";
if (len == 0)
{
uint64_t t = static_cast<uint64_t>(n);
do
{
t >>= 4;
++len;
}
while (t);
}
std::string result(len, '0');
for (size_t i = 0, j = (len - 1) * 4; i < len; ++i, j -= 4)
result[i] = digits[(n >> j) & 0x0F];
return result;
}
inline std::vector<std::string> explodeString(const std::string& str, char delimiter = ' ')
{
std::string buffer;
std::vector<std::string> result;
for(char c : str)
if (c != delimiter) buffer.push_back(c);
else if (c == delimiter && !buffer.empty())
{
result.push_back(buffer);
buffer.clear();
}
if (!buffer.empty()) result.push_back(buffer);
return result;
}
void setCurrentThreadName(const std::string& name);
void setThreadPriority(std::thread& t, float priority, bool realtime);
}
#endif // OUZEL_UTILS_UTILS_HPP
|
Remove unneeded includes from the Utils.hpp
|
Remove unneeded includes from the Utils.hpp
|
C++
|
unlicense
|
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
|
98bc61493ff4d7c4c51a09aba4e33ba69d7b387d
|
Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx
|
Modules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkDisplacementFieldJacobianDeterminantFilter.h"
#include "itkNullImageToImageFilterDriver.hxx"
#include "itkStdStreamStateSave.h"
#include "itkTestingMacros.h"
static bool
TestDisplacementJacobianDeterminantValue()
{
bool testPassed = true;
constexpr unsigned int ImageDimension = 2;
using VectorType = itk::Vector<float, ImageDimension>;
using FieldType = itk::Image<VectorType, ImageDimension>;
// In this case, the image to be warped is also a vector field.
using VectorImageType = FieldType;
std::cout << "Create the dispacementfield image pattern." << std::endl;
VectorImageType::RegionType region;
// NOTE: Making the image size much larger than necessary in order to get
// some meaningful time measurements. Simulate a 256x256x256 image.
VectorImageType::SizeType size = { { 4096, 4096 } };
region.SetSize(size);
auto dispacementfield = VectorImageType::New();
dispacementfield->SetLargestPossibleRegion(region);
dispacementfield->SetBufferedRegion(region);
dispacementfield->Allocate();
VectorType values;
values[0] = 0;
values[1] = 0;
using Iterator = itk::ImageRegionIteratorWithIndex<VectorImageType>;
for (Iterator inIter(dispacementfield, region); !inIter.IsAtEnd(); ++inIter)
{
const unsigned int i = inIter.GetIndex()[0];
const unsigned int j = inIter.GetIndex()[1];
values[0] = 0.125 * i * i + 0.125 * j;
values[1] = 0.125 * i * j + 0.25 * j;
inIter.Set(values);
// std::cout << "Setting: " << values << " at " << inIter.GetIndex() << std::endl;
}
// Displacement field:
//|-------------------------------------------|
//| [0.25;0.5] | [0.375;0.75] | [0.75;1] |
//|-------------------------------------------|
//| [0.125;0.25] | [0.25;0.375] | [0.625;0.5] |
//|-------------------------------------------|
//| [0.0;0.0] | [0.125;0.0] | [0.5;0] |
//|-------------------------------------------|
//
// J(1,1) = [ (.625-.125)/2 (.5-.25)/2; (.375-.125)/2 (.75-0.0)/2] =[ .25 .125; .125 .375]
// det((J+I)(1,1))=((.25+1.0)*(.375+1.0))-(.125*.125) = 1.703125;
const float expectedJacobianDeterminant = (((.25 + 1.0) * (.375 + 1.0)) - (.125 * .125));
using FilterType = itk::DisplacementFieldJacobianDeterminantFilter<VectorImageType, float>;
auto filter = FilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter);
bool useImageSpacing = true;
#if !defined(ITK_FUTURE_LEGACY_REMOVE)
if (useImageSpacing)
{
filter->SetUseImageSpacingOn();
}
else
{
filter->SetUseImageSpacingOff();
}
#endif
ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing);
filter->SetInput(dispacementfield);
filter->Update();
itk::Image<float, 2>::Pointer output = filter->GetOutput();
VectorImageType::IndexType index;
index[0] = 1;
index[1] = 1;
float jacobianDeterminant = output->GetPixel(index);
// std::cout << "Output " << output->GetPixel(index) << std::endl;
double epsilon = 1e-13;
if (itk::Math::abs(jacobianDeterminant - expectedJacobianDeterminant) > epsilon)
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Error in pixel value at index [" << index << "]" << std::endl;
std::cerr << "Expected value " << jacobianDeterminant << std::endl;
std::cerr << " differs from " << expectedJacobianDeterminant;
std::cerr << " by more than " << epsilon << std::endl;
testPassed = false;
}
else
{
std::cout << "Test passed." << std::endl;
}
return testPassed;
}
int
itkDisplacementFieldJacobianDeterminantFilterTest(int, char *[])
{
// Save the format stream variables for std::cout
// They will be restored when coutState goes out of scope
// scope.
itk::StdStreamStateSave coutState(std::cout);
bool ValueTestPassed = TestDisplacementJacobianDeterminantValue();
try
{
using VectorType = itk::Vector<float, 3>;
using VectorImageType = itk::Image<VectorType, 3>;
using ScalarVectorImageType = itk::Image<float, 3>;
// Set up filter
using FilterType = itk::DisplacementFieldJacobianDeterminantFilter<VectorImageType, float>;
auto filter = FilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter);
// Run the test
itk::Size<3> sz;
sz[0] = 100;
sz[1] = 100;
sz[2] = 100;
itk::NullImageToImageFilterDriver<VectorImageType, ScalarVectorImageType> test1;
test1.SetImageSize(sz);
test1.SetFilter(filter);
test1.Execute();
filter->Print(std::cout);
// Run the test again with ImageSpacingOn
bool useImageSpacing = true;
ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing);
test1.Execute();
filter->Print(std::cout);
// Run the test again with specified weights
typename FilterType::WeightsType weights{ { 1.0, 2.0, 3.0 } };
filter->SetDerivativeWeights(weights);
ITK_TEST_SET_GET_VALUE(weights, filter->GetDerivativeWeights());
test1.Execute();
filter->Print(std::cout);
}
catch (const itk::ExceptionObject & err)
{
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if (ValueTestPassed == false)
{
return EXIT_FAILURE;
}
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkDisplacementFieldJacobianDeterminantFilter.h"
#include "itkNullImageToImageFilterDriver.hxx"
#include "itkStdStreamStateSave.h"
#include "itkTestingMacros.h"
static bool
TestDisplacementJacobianDeterminantValue()
{
bool testPassed = true;
constexpr unsigned int ImageDimension = 2;
using VectorType = itk::Vector<float, ImageDimension>;
using FieldType = itk::Image<VectorType, ImageDimension>;
// In this case, the image to be warped is also a vector field.
using VectorImageType = FieldType;
std::cout << "Create the dispacementfield image pattern." << std::endl;
VectorImageType::RegionType region;
// NOTE: Making the image size much larger than necessary in order to get
// some meaningful time measurements. Simulate a 256x256x256 image.
VectorImageType::SizeType size = { { 4096, 4096 } };
region.SetSize(size);
auto dispacementfield = VectorImageType::New();
dispacementfield->SetLargestPossibleRegion(region);
dispacementfield->SetBufferedRegion(region);
dispacementfield->Allocate();
VectorType values;
values[0] = 0;
values[1] = 0;
using Iterator = itk::ImageRegionIteratorWithIndex<VectorImageType>;
for (Iterator inIter(dispacementfield, region); !inIter.IsAtEnd(); ++inIter)
{
const unsigned int i = inIter.GetIndex()[0];
const unsigned int j = inIter.GetIndex()[1];
values[0] = 0.125 * i * i + 0.125 * j;
values[1] = 0.125 * i * j + 0.25 * j;
inIter.Set(values);
// std::cout << "Setting: " << values << " at " << inIter.GetIndex() << std::endl;
}
// Displacement field:
//|-------------------------------------------|
//| [0.25;0.5] | [0.375;0.75] | [0.75;1] |
//|-------------------------------------------|
//| [0.125;0.25] | [0.25;0.375] | [0.625;0.5] |
//|-------------------------------------------|
//| [0.0;0.0] | [0.125;0.0] | [0.5;0] |
//|-------------------------------------------|
//
// J(1,1) = [ (.625-.125)/2 (.5-.25)/2; (.375-.125)/2 (.75-0.0)/2] =[ .25 .125; .125 .375]
// det((J+I)(1,1))=((.25+1.0)*(.375+1.0))-(.125*.125) = 1.703125;
const float expectedJacobianDeterminant = (((.25 + 1.0) * (.375 + 1.0)) - (.125 * .125));
using FilterType = itk::DisplacementFieldJacobianDeterminantFilter<VectorImageType, float>;
auto filter = FilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter);
bool useImageSpacing = true;
#if !defined(ITK_FUTURE_LEGACY_REMOVE)
if (useImageSpacing)
{
filter->SetUseImageSpacingOn();
}
else
{
filter->SetUseImageSpacingOff();
}
#endif
ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing);
filter->SetInput(dispacementfield);
filter->Update();
itk::Image<float, 2>::Pointer output = filter->GetOutput();
VectorImageType::IndexType index;
index[0] = 1;
index[1] = 1;
float jacobianDeterminant = output->GetPixel(index);
// std::cout << "Output " << output->GetPixel(index) << std::endl;
double epsilon = 1e-13;
if (itk::Math::abs(jacobianDeterminant - expectedJacobianDeterminant) > epsilon)
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Error in pixel value at index [" << index << "]" << std::endl;
std::cerr << "Expected value " << jacobianDeterminant << std::endl;
std::cerr << " differs from " << expectedJacobianDeterminant;
std::cerr << " by more than " << epsilon << std::endl;
testPassed = false;
}
else
{
std::cout << "Test passed." << std::endl;
}
return testPassed;
}
int
itkDisplacementFieldJacobianDeterminantFilterTest(int, char *[])
{
// Save the format stream variables for std::cout
// They will be restored when coutState goes out of scope
// scope.
itk::StdStreamStateSave coutState(std::cout);
bool ValueTestPassed = TestDisplacementJacobianDeterminantValue();
try
{
using VectorType = itk::Vector<float, 3>;
using VectorImageType = itk::Image<VectorType, 3>;
using ScalarVectorImageType = itk::Image<float, 3>;
// Set up filter
using FilterType = itk::DisplacementFieldJacobianDeterminantFilter<VectorImageType, float>;
auto filter = FilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, DisplacementFieldJacobianDeterminantFilter, ImageToImageFilter);
// Run the test
itk::Size<3> sz;
sz[0] = 100;
sz[1] = 100;
sz[2] = 100;
itk::NullImageToImageFilterDriver<VectorImageType, ScalarVectorImageType> test1;
test1.SetImageSize(sz);
test1.SetFilter(filter);
test1.Execute();
filter->Print(std::cout);
// Run the test again with ImageSpacingOn
bool useImageSpacing = true;
ITK_TEST_SET_GET_BOOLEAN(filter, UseImageSpacing, useImageSpacing);
test1.Execute();
filter->Print(std::cout);
// Run the test again with specified weights
typename FilterType::WeightsType weights{ { { 1.0, 2.0, 3.0 } } };
filter->SetDerivativeWeights(weights);
ITK_TEST_SET_GET_VALUE(weights, filter->GetDerivativeWeights());
test1.Execute();
filter->Print(std::cout);
}
catch (const itk::ExceptionObject & err)
{
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if (ValueTestPassed == false)
{
return EXIT_FAILURE;
}
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
|
Fix missing initialization braces warning
|
COMP: Fix missing initialization braces warning
Fix missing initialization braces warning.
Fixes:
```
[CTest: warning matched]
/Users/builder/externalModules/Filtering/DisplacementField/test/itkDisplacementFieldJacobianDeterminantFilterTest.cxx:169:49:
warning: suggest braces around initialization of subobject [-Wmissing-braces]
typename FilterType::WeightsType weights{ { 1.0, 2.0, 3.0 } };
^~~~~~~~~~~~~
{ }
```
Raised for example in:
https://open.cdash.org/viewBuildError.php?type=1&buildid=7679172
|
C++
|
apache-2.0
|
Kitware/ITK,Kitware/ITK,thewtex/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,richardbeare/ITK,BRAINSia/ITK,richardbeare/ITK,thewtex/ITK,richardbeare/ITK,BRAINSia/ITK,hjmjohnson/ITK,Kitware/ITK,richardbeare/ITK,BRAINSia/ITK,hjmjohnson/ITK,hjmjohnson/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,BRAINSia/ITK,Kitware/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,richardbeare/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,hjmjohnson/ITK,thewtex/ITK,thewtex/ITK,BRAINSia/ITK,hjmjohnson/ITK,thewtex/ITK
|
04e8d4e369ab881f952cc7eb7c9830f5b8d500ee
|
ash/system/ime/tray_ime.cc
|
ash/system/ime/tray_ime.cc
|
// 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 "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_notification_view.h"
#include "ash/system/tray/tray_views.h"
#include "ash/wm/shelf_layout_manager.h"
#include "base/logging.h"
#include "base/timer.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToImageSkia());
IMEInfo info;
Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public TrayDetailsView,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: login_(login) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
Reset();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
AppendHeaderEntry();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
CreateScrollableList();
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
scroll_content()->AddChildView(container);
ime_map_[container] = list[i].id;
}
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
if (i == 0)
container->set_border(views::Border::CreateSolidSidedBorder(1, 0, 0, 0,
kBorderLightColor));
scroll_content()->AddChildView(container);
property_map_[container] = property_list[i].key;
}
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void ClickedOn(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
if (sender == footer()->content()) {
Shell::GetInstance()->system_tray()->ShowDefaultView(BUBBLE_USE_EXISTING);
} else if (sender == settings_) {
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
class IMENotificationView : public TrayNotificationView {
public:
explicit IMENotificationView(TrayIME* tray)
: TrayNotificationView(tray, IDR_AURA_UBER_TRAY_IME) {
InitView(GetLabel());
}
void UpdateLabel() {
RestartAutoCloseTimer();
UpdateView(GetLabel());
}
void StartAutoCloseTimer(int seconds) {
autoclose_.Stop();
autoclose_delay_ = seconds;
if (autoclose_delay_) {
autoclose_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(autoclose_delay_),
this, &IMENotificationView::Close);
}
}
void StopAutoCloseTimer() {
autoclose_.Stop();
}
void RestartAutoCloseTimer() {
if (autoclose_delay_)
StartAutoCloseTimer(autoclose_delay_);
}
// Overridden from TrayNotificationView.
virtual void OnClickAction() OVERRIDE {
tray()->PopupDetailedView(0, true);
}
private:
void Close() {
tray()->HideNotificationView();
}
views::Label* GetLabel() {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfo current;
delegate->GetCurrentIME(¤t);
// TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE for
// third party IMEs
return new views::Label(
l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
current.medium_name));
}
int autoclose_delay_;
base::OneShotTimer<IMENotificationView> autoclose_;
DISALLOW_COPY_AND_ASSIGN(IMENotificationView);
};
} // namespace tray
TrayIME::TrayIME()
: tray_label_(NULL),
default_(NULL),
detailed_(NULL),
notification_(NULL),
message_shown_(false) {
}
TrayIME::~TrayIME() {
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
if (current.third_party) {
tray_label_->label()->SetText(current.short_name + UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
tray_label_->SetVisible(count > 1);
SetTrayLabelItemBorder(tray_label_,
ash::Shell::GetInstance()->system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView;
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEPropertyInfoList property_list;
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
if (list.size() <= 1 && property_list.size() <= 1)
return NULL;
CHECK(default_ == NULL);
default_ = new tray::IMEDefaultView(this);
return default_;
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ = new tray::IMEDetailedView(this, status);
return detailed_;
}
views::View* TrayIME::CreateNotificationView(user::LoginStatus status) {
DCHECK(notification_ == NULL);
notification_ = new tray::IMENotificationView(this);
notification_->StartAutoCloseTimer(kTrayPopupAutoCloseDelayForTextInSeconds);
return notification_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::DestroyNotificationView() {
notification_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
}
void TrayIME::OnIMERefresh(bool show_message) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_)
default_->UpdateLabel(current);
if (detailed_)
detailed_->Update(list, property_list);
if (list.size() > 1 && show_message) {
// If the notification is still visible, hide it and clear the flag so it is
// refreshed.
if (notification_) {
notification_->UpdateLabel();
} else if (!Shell::GetPrimaryRootWindowController()->shelf()->IsVisible() ||
!message_shown_) {
ShowNotificationView();
message_shown_ = true;
}
}
}
} // namespace internal
} // namespace ash
|
// 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 "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_details_view.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_item_view.h"
#include "ash/system/tray/tray_notification_view.h"
#include "ash/system/tray/tray_views.h"
#include "ash/wm/shelf_layout_manager.h"
#include "base/logging.h"
#include "base/timer.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToImageSkia());
IMEInfo info;
Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public TrayDetailsView,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: login_(login) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
Reset();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
AppendHeaderEntry();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
CreateScrollableList();
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
scroll_content()->AddChildView(container);
ime_map_[container] = list[i].id;
}
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
if (i == 0)
container->set_border(views::Border::CreateSolidSidedBorder(1, 0, 0, 0,
kBorderLightColor));
scroll_content()->AddChildView(container);
property_map_[container] = property_list[i].key;
}
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void ClickedOn(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
if (sender == footer()->content()) {
Shell::GetInstance()->system_tray()->ShowDefaultView(BUBBLE_USE_EXISTING);
} else if (sender == settings_) {
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
class IMENotificationView : public TrayNotificationView {
public:
explicit IMENotificationView(TrayIME* tray)
: TrayNotificationView(tray, IDR_AURA_UBER_TRAY_IME) {
InitView(GetLabel());
}
void UpdateLabel() {
RestartAutoCloseTimer();
UpdateView(GetLabel());
}
void StartAutoCloseTimer(int seconds) {
autoclose_.Stop();
autoclose_delay_ = seconds;
if (autoclose_delay_) {
autoclose_.Start(FROM_HERE,
base::TimeDelta::FromSeconds(autoclose_delay_),
this, &IMENotificationView::Close);
}
}
void StopAutoCloseTimer() {
autoclose_.Stop();
}
void RestartAutoCloseTimer() {
if (autoclose_delay_)
StartAutoCloseTimer(autoclose_delay_);
}
// Overridden from TrayNotificationView.
virtual void OnClickAction() OVERRIDE {
tray()->PopupDetailedView(0, true);
}
private:
void Close() {
tray()->HideNotificationView();
}
views::Label* GetLabel() {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfo current;
delegate->GetCurrentIME(¤t);
// TODO(zork): Use IDS_ASH_STATUS_TRAY_THIRD_PARTY_IME_TURNED_ON_BUBBLE for
// third party IMEs
views::Label* label = new views::Label(
l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_IME_TURNED_ON_BUBBLE,
current.medium_name));
label->SetMultiLine(true);
label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
return label;
}
int autoclose_delay_;
base::OneShotTimer<IMENotificationView> autoclose_;
DISALLOW_COPY_AND_ASSIGN(IMENotificationView);
};
} // namespace tray
TrayIME::TrayIME()
: tray_label_(NULL),
default_(NULL),
detailed_(NULL),
notification_(NULL),
message_shown_(false) {
}
TrayIME::~TrayIME() {
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
if (current.third_party) {
tray_label_->label()->SetText(current.short_name + UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
tray_label_->SetVisible(count > 1);
SetTrayLabelItemBorder(tray_label_,
ash::Shell::GetInstance()->system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView;
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEPropertyInfoList property_list;
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
if (list.size() <= 1 && property_list.size() <= 1)
return NULL;
CHECK(default_ == NULL);
default_ = new tray::IMEDefaultView(this);
return default_;
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ = new tray::IMEDetailedView(this, status);
return detailed_;
}
views::View* TrayIME::CreateNotificationView(user::LoginStatus status) {
DCHECK(notification_ == NULL);
notification_ = new tray::IMENotificationView(this);
notification_->StartAutoCloseTimer(kTrayPopupAutoCloseDelayForTextInSeconds);
return notification_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::DestroyNotificationView() {
notification_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(user::LoginStatus status) {
}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
}
void TrayIME::OnIMERefresh(bool show_message) {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_)
default_->UpdateLabel(current);
if (detailed_)
detailed_->Update(list, property_list);
if (list.size() > 1 && show_message) {
// If the notification is still visible, hide it and clear the flag so it is
// refreshed.
if (notification_) {
notification_->UpdateLabel();
} else if (!Shell::GetPrimaryRootWindowController()->shelf()->IsVisible() ||
!message_shown_) {
ShowNotificationView();
message_shown_ = true;
}
}
}
} // namespace internal
} // namespace ash
|
Fix input method changed notification window looking.
|
Fix input method changed notification window looking.
Set multi-line explicitly and left align flag into ime tray, otherwise not all text is displayed.
BUG=157535
TEST=Manually done on lumpy
Review URL: https://chromiumcodereview.appspot.com/11266034
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@164434 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
littlstar/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,timopulkkinen/BubbleFish,ondra-novak/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,ltilve/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,zcbenz/cefode-chromium,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,dednal/chromium.src,dednal/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,anirudhSK/chromium,littlstar/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,jaruba/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,Chilledheart/chromium,markYoungH/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Just-D/chromium-1,Just-D/chromium-1,jaruba/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,anirudhSK/chromium,littlstar/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,Chilledheart/chromium,jaruba/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,M4sse/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,dednal/chromium.src,M4sse/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src
|
4c8edb308feb04fc3d51eebcd8bc1da09ad6c2c1
|
modules/io/synth.cpp
|
modules/io/synth.cpp
|
#include "io/synth.h"
#include <opencv2/imgproc.hpp>
#include "core/exception.h"
using namespace cv;
base_Synth::base_Synth()
{
}
base_Synth::~base_Synth()
{
}
SynthBars::SynthBars()
: base_Synth()
{
Reset(28, 28, 6);
}
void SynthBars::Reset(int rows, int cols, int nb_variations)
{
if(nb_variations <= 0) { SEM_THROW_VALUE_ERROR("No. of variation must be > 0."); }
rows_ = rows;
cols_ = cols;
nb_variations_ = nb_variations;
delta_ = 180.f/static_cast<float>(nb_variations_);
}
void SynthBars::Next(Mat &feature, Mat &label)
{
unsigned int index = randu<unsigned int>()%nb_variations_;
float angle = IndexToDeg(index);
Draw(angle, feature);
label = Mat1f(1, 1, angle);
}
void SynthBars::Draw(float angle_deg, Mat &img) const
{
Mat1f label = Mat1f(1, 1, -angle_deg);
Mat1f mag(1, 1, rows_+cols_), x, y;
polarToCart(mag, label, x, y, true);
Point2i centre(cols_/2, rows_/2);
Point2i a(x(0), y(0));
a += centre;
polarToCart(-mag, label, x, y, true);
Point2i b(x(0), y(0));
b += centre;
img = Mat1b::zeros(rows_, cols_);
line(img, a, b, Scalar_<uchar>(255), 3, LINE_8);
}
float SynthBars::IndexToDeg(unsigned int index) const
{
return (index % nb_variations_) * delta_;
}
|
#include "io/synth.h"
#include <opencv2/imgproc.hpp>
#include "core/exception.h"
using namespace cv;
base_Synth::base_Synth()
{
}
base_Synth::~base_Synth()
{
}
SynthBars::SynthBars()
: base_Synth()
{
Reset(28, 28, 6);
}
void SynthBars::Reset(int rows, int cols, int nb_variations)
{
if(nb_variations <= 0) { SEM_THROW_VALUE_ERROR("No. of variation must be > 0."); }
rows_ = rows;
cols_ = cols;
nb_variations_ = nb_variations;
delta_ = 180.f/static_cast<float>(nb_variations_);
}
void SynthBars::Next(Mat &feature, Mat &label)
{
unsigned int index = randu<unsigned int>()%nb_variations_;
float angle = IndexToDeg(index);
Draw(angle, feature);
label = Mat1f(1, 1, angle);
}
void SynthBars::Draw(float angle_deg, Mat &img) const
{
Mat1f label = Mat1f(2, 1, -angle_deg);
Mat1f mag(2, 1, rows_+cols_), x, y;
polarToCart(mag, label, x, y, true);
Point2i centre(cols_/2, rows_/2),
a(x(0), y(0)), b(x(1), y(1));
a += centre;
img = Mat1b::zeros(rows_, cols_);
line(img, a, centre-b, Scalar_<uchar>(255), 3, LINE_8);
}
float SynthBars::IndexToDeg(unsigned int index) const
{
return (index % nb_variations_) * delta_;
}
|
reduce steps in drawing oriented bars
|
reduce steps in drawing oriented bars
|
C++
|
bsd-3-clause
|
kashefy/elm,kashefy/elm,kashefy/elm,kashefy/elm
|
5fc904227c8f2b6e713de6abb610d6fbd96dd705
|
webkit/api/src/WebBindings.cpp
|
webkit/api/src/WebBindings.cpp
|
/*
* Copyright (C) 2009 Google 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebBindings.h"
#include "npruntime_priv.h"
#include "webkit/api/public/WebDragData.h"
#if USE(V8_BINDING)
#include "ChromiumDataObject.h"
#include "ClipboardChromium.h"
#include "EventNames.h"
#include "MouseEvent.h"
#include "NPV8Object.h" // for PrivateIdentifier
#include "V8Helpers.h"
#include "V8Proxy.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "bridge/c/c_utility.h"
#endif
#if USE(JAVASCRIPTCORE_BINDINGS)
using JSC::Bindings::PrivateIdentifier;
#endif
using namespace WebCore;
namespace WebKit {
bool WebBindings::construct(NPP npp, NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant* result)
{
return NPN_Construct(npp, npobj, args, argCount, result);
}
NPObject* WebBindings::createObject(NPP npp, NPClass* npClass)
{
return NPN_CreateObject(npp, npClass);
}
bool WebBindings::enumerate(NPP id, NPObject* obj, NPIdentifier** identifier, uint32_t* val)
{
return NPN_Enumerate(id, obj, identifier, val);
}
bool WebBindings::evaluateHelper(NPP npp, bool popups_allowed, NPObject* npobj, NPString* npscript, NPVariant* result)
{
return NPN_EvaluateHelper(npp, popups_allowed, npobj, npscript, result);
}
NPIdentifier WebBindings::getIntIdentifier(int32_t number)
{
return NPN_GetIntIdentifier(number);
}
bool WebBindings::getProperty(NPP npp, NPObject* obj, NPIdentifier propertyName, NPVariant *result)
{
return NPN_GetProperty(npp, obj, propertyName, result);
}
NPIdentifier WebBindings::getStringIdentifier(const NPUTF8* string)
{
return NPN_GetStringIdentifier(string);
}
void WebBindings::getStringIdentifiers(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers)
{
NPN_GetStringIdentifiers(names, nameCount, identifiers);
}
bool WebBindings::hasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
{
return NPN_HasMethod(npp, npObject, methodName);
}
bool WebBindings::hasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
{
return NPN_HasProperty(npp, npObject, propertyName);
}
bool WebBindings::identifierIsString(NPIdentifier identifier)
{
return NPN_IdentifierIsString(identifier);
}
int32_t WebBindings::intFromIdentifier(NPIdentifier identifier)
{
return NPN_IntFromIdentifier(identifier);
}
void WebBindings::initializeVariantWithStringCopy(NPVariant* variant, const NPString* value)
{
#if USE(V8)
_NPN_InitializeVariantWithStringCopy(variant, value);
#else
NPN_InitializeVariantWithStringCopy(variant, value);
#endif
}
bool WebBindings::invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
{
return NPN_Invoke(npp, npObject, methodName, arguments, argumentCount, result);
}
bool WebBindings::invokeDefault(NPP id, NPObject* obj, const NPVariant* args, uint32_t count, NPVariant* result)
{
return NPN_InvokeDefault(id, obj, args, count, result);
}
void WebBindings::releaseObject(NPObject* npObject)
{
return NPN_ReleaseObject(npObject);
}
void WebBindings::releaseVariantValue(NPVariant* variant)
{
NPN_ReleaseVariantValue(variant);
}
bool WebBindings::removeProperty(NPP id, NPObject* object, NPIdentifier identifier)
{
return NPN_RemoveProperty(id, object, identifier);
}
NPObject* WebBindings::retainObject(NPObject* npObject)
{
return NPN_RetainObject(npObject);
}
void WebBindings::setException(NPObject* obj, const NPUTF8* message)
{
NPN_SetException(obj, message);
}
bool WebBindings::setProperty(NPP id, NPObject* obj, NPIdentifier identifier, const NPVariant* variant)
{
return NPN_SetProperty(id, obj, identifier, variant);
}
void WebBindings::unregisterObject(NPObject* npObject)
{
#if USE(V8)
_NPN_UnregisterObject(npObject);
#endif
}
NPUTF8* WebBindings::utf8FromIdentifier(NPIdentifier identifier)
{
return NPN_UTF8FromIdentifier(identifier);
}
void WebBindings::extractIdentifierData(const NPIdentifier& identifier, const NPUTF8*& string, int32_t& number, bool& isString)
{
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
if (!priv) {
isString = false;
number = 0;
return;
}
isString = priv->isString;
if (isString)
string = priv->value.string;
else
number = priv->value.number;
}
#if USE(V8)
static v8::Local<v8::Value> getEvent(const v8::Handle<v8::Context>& context)
{
static v8::Persistent<v8::String> eventSymbol(v8::Persistent<v8::String>::New(v8::String::NewSymbol("event")));
return context->Global()->Get(eventSymbol);
}
static bool getDragDataImpl(NPObject* npobj, int* eventId, WebDragData* data)
{
if (npobj == NULL)
return false;
if (npobj->_class != npScriptObjectClass)
return false;
v8::HandleScope handleScope;
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return false;
// Get the current WebCore event.
v8::Handle<v8::Value> currentEvent(getEvent(context));
Event* event = V8DOMWrapper::convertToNativeEvent(currentEvent);
if (event == NULL)
return false;
// Check that the given npobj is that event.
V8NPObject* object = reinterpret_cast<V8NPObject*>(npobj);
Event* given = V8DOMWrapper::convertToNativeEvent(object->v8Object);
if (given != event)
return false;
// Check the execution frames are same origin.
V8Proxy* current = V8Proxy::retrieve(V8Proxy::retrieveFrameForCurrentContext());
Frame* frame = V8Proxy::retrieveFrame(context);
if (!current || !current->canAccessFrame(frame, false))
return false;
const EventNames& names(eventNames());
const AtomicString& eventType(event->type());
enum DragTargetMouseEventId {
DragEnterId = 1, DragOverId = 2, DragLeaveId = 3, DropId = 4
};
// The event type should be a drag event.
if (eventType == names.dragenterEvent)
*eventId = DragEnterId;
else if (eventType == names.dragoverEvent)
*eventId = DragOverId;
else if (eventType == names.dragleaveEvent)
*eventId = DragLeaveId;
else if (eventType == names.dropEvent)
*eventId = DropId;
else
return false;
// Drag events are mouse events and should have a clipboard.
MouseEvent* me = reinterpret_cast<MouseEvent*>(event);
Clipboard* clipboard = me->clipboard();
if (!clipboard)
return false;
// And that clipboard should be accessible by WebKit policy.
ClipboardChromium* chrome = reinterpret_cast<ClipboardChromium*>(clipboard);
HashSet<String> accessible(chrome->types());
if (accessible.isEmpty())
return false;
RefPtr<ChromiumDataObject> dataObject(chrome->dataObject());
if (dataObject && data)
*data = WebDragData(dataObject);
return dataObject != NULL;
}
#endif
bool WebBindings::getDragData(NPObject* event, int* eventId, WebDragData* data)
{
#if USE(V8)
return getDragDataImpl(event, eventId, data);
#else
// Not supported on other ports (JSC, etc).
return false;
#endif
}
bool WebBindings::isDragEvent(NPObject* event)
{
int eventId;
return getDragData(event, &eventId, NULL);
}
} // namespace WebKit
|
/*
* Copyright (C) 2009 Google 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebBindings.h"
#include "npruntime_priv.h"
#include "webkit/api/public/WebDragData.h"
#if USE(V8_BINDING)
#include "ChromiumDataObject.h"
#include "ClipboardChromium.h"
#include "EventNames.h"
#include "MouseEvent.h"
#include "NPV8Object.h" // for PrivateIdentifier
#include "V8Helpers.h"
#include "V8Proxy.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "bridge/c/c_utility.h"
#endif
#if USE(JAVASCRIPTCORE_BINDINGS)
using JSC::Bindings::PrivateIdentifier;
#endif
using namespace WebCore;
namespace WebKit {
bool WebBindings::construct(NPP npp, NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant* result)
{
return NPN_Construct(npp, npobj, args, argCount, result);
}
NPObject* WebBindings::createObject(NPP npp, NPClass* npClass)
{
return NPN_CreateObject(npp, npClass);
}
bool WebBindings::enumerate(NPP id, NPObject* obj, NPIdentifier** identifier, uint32_t* val)
{
return NPN_Enumerate(id, obj, identifier, val);
}
bool WebBindings::evaluateHelper(NPP npp, bool popups_allowed, NPObject* npobj, NPString* npscript, NPVariant* result)
{
return NPN_EvaluateHelper(npp, popups_allowed, npobj, npscript, result);
}
NPIdentifier WebBindings::getIntIdentifier(int32_t number)
{
return NPN_GetIntIdentifier(number);
}
bool WebBindings::getProperty(NPP npp, NPObject* obj, NPIdentifier propertyName, NPVariant *result)
{
return NPN_GetProperty(npp, obj, propertyName, result);
}
NPIdentifier WebBindings::getStringIdentifier(const NPUTF8* string)
{
return NPN_GetStringIdentifier(string);
}
void WebBindings::getStringIdentifiers(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers)
{
NPN_GetStringIdentifiers(names, nameCount, identifiers);
}
bool WebBindings::hasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
{
return NPN_HasMethod(npp, npObject, methodName);
}
bool WebBindings::hasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
{
return NPN_HasProperty(npp, npObject, propertyName);
}
bool WebBindings::identifierIsString(NPIdentifier identifier)
{
return NPN_IdentifierIsString(identifier);
}
int32_t WebBindings::intFromIdentifier(NPIdentifier identifier)
{
return NPN_IntFromIdentifier(identifier);
}
void WebBindings::initializeVariantWithStringCopy(NPVariant* variant, const NPString* value)
{
#if USE(V8)
_NPN_InitializeVariantWithStringCopy(variant, value);
#else
NPN_InitializeVariantWithStringCopy(variant, value);
#endif
}
bool WebBindings::invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
{
return NPN_Invoke(npp, npObject, methodName, arguments, argumentCount, result);
}
bool WebBindings::invokeDefault(NPP id, NPObject* obj, const NPVariant* args, uint32_t count, NPVariant* result)
{
return NPN_InvokeDefault(id, obj, args, count, result);
}
void WebBindings::releaseObject(NPObject* npObject)
{
return NPN_ReleaseObject(npObject);
}
void WebBindings::releaseVariantValue(NPVariant* variant)
{
NPN_ReleaseVariantValue(variant);
}
bool WebBindings::removeProperty(NPP id, NPObject* object, NPIdentifier identifier)
{
return NPN_RemoveProperty(id, object, identifier);
}
NPObject* WebBindings::retainObject(NPObject* npObject)
{
return NPN_RetainObject(npObject);
}
void WebBindings::setException(NPObject* obj, const NPUTF8* message)
{
NPN_SetException(obj, message);
}
bool WebBindings::setProperty(NPP id, NPObject* obj, NPIdentifier identifier, const NPVariant* variant)
{
return NPN_SetProperty(id, obj, identifier, variant);
}
void WebBindings::unregisterObject(NPObject* npObject)
{
#if USE(V8)
_NPN_UnregisterObject(npObject);
#endif
}
NPUTF8* WebBindings::utf8FromIdentifier(NPIdentifier identifier)
{
return NPN_UTF8FromIdentifier(identifier);
}
void WebBindings::extractIdentifierData(const NPIdentifier& identifier, const NPUTF8*& string, int32_t& number, bool& isString)
{
PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);
if (!priv) {
isString = false;
number = 0;
return;
}
isString = priv->isString;
if (isString)
string = priv->value.string;
else
number = priv->value.number;
}
#if USE(V8)
static v8::Local<v8::Value> getEvent(const v8::Handle<v8::Context>& context)
{
static v8::Persistent<v8::String> eventSymbol(v8::Persistent<v8::String>::New(v8::String::NewSymbol("event")));
return context->Global()->GetHiddenValue(eventSymbol);
}
static bool getDragDataImpl(NPObject* npobj, int* eventId, WebDragData* data)
{
if (npobj == NULL)
return false;
if (npobj->_class != npScriptObjectClass)
return false;
v8::HandleScope handleScope;
v8::Handle<v8::Context> context = v8::Context::GetEntered();
if (context.IsEmpty())
return false;
// Get the current WebCore event.
v8::Handle<v8::Value> currentEvent(getEvent(context));
Event* event = V8DOMWrapper::convertToNativeEvent(currentEvent);
if (event == NULL)
return false;
// Check that the given npobj is that event.
V8NPObject* object = reinterpret_cast<V8NPObject*>(npobj);
Event* given = V8DOMWrapper::convertToNativeEvent(object->v8Object);
if (given != event)
return false;
// Check the execution frames are same origin.
V8Proxy* current = V8Proxy::retrieve(V8Proxy::retrieveFrameForCurrentContext());
Frame* frame = V8Proxy::retrieveFrame(context);
if (!current || !current->canAccessFrame(frame, false))
return false;
const EventNames& names(eventNames());
const AtomicString& eventType(event->type());
enum DragTargetMouseEventId {
DragEnterId = 1, DragOverId = 2, DragLeaveId = 3, DropId = 4
};
// The event type should be a drag event.
if (eventType == names.dragenterEvent)
*eventId = DragEnterId;
else if (eventType == names.dragoverEvent)
*eventId = DragOverId;
else if (eventType == names.dragleaveEvent)
*eventId = DragLeaveId;
else if (eventType == names.dropEvent)
*eventId = DropId;
else
return false;
// Drag events are mouse events and should have a clipboard.
MouseEvent* me = reinterpret_cast<MouseEvent*>(event);
Clipboard* clipboard = me->clipboard();
if (!clipboard)
return false;
// And that clipboard should be accessible by WebKit policy.
ClipboardChromium* chrome = reinterpret_cast<ClipboardChromium*>(clipboard);
HashSet<String> accessible(chrome->types());
if (accessible.isEmpty())
return false;
RefPtr<ChromiumDataObject> dataObject(chrome->dataObject());
if (dataObject && data)
*data = WebDragData(dataObject);
return dataObject != NULL;
}
#endif
bool WebBindings::getDragData(NPObject* event, int* eventId, WebDragData* data)
{
#if USE(V8)
return getDragDataImpl(event, eventId, data);
#else
// Not supported on other ports (JSC, etc).
return false;
#endif
}
bool WebBindings::isDragEvent(NPObject* event)
{
int eventId;
return getDragData(event, &eventId, NULL);
}
} // namespace WebKit
|
Revert r22390.
|
Revert r22390.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/159884
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@22443 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium
|
73a3d249f6e7ae99c6eade652b4c788fe3a6b793
|
tests/core/property.c++
|
tests/core/property.c++
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* 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 "test.h++"
#include "core/property.h++"
namespace
{
using skui::test::assert;
void test_value_changed_signal()
{
int changed_value = 0;
auto slot = [&changed_value](int i) { changed_value = i; };
skui::core::property<int> property;
property.value_changed.connect(slot);
property = 1;
assert(changed_value == 1, "changed slot called on assignment");
property = std::move(2);
assert(changed_value == 2, "moving value into property emits signal");
}
void test_basic_operations()
{
bool slot_called = false;
auto slot = [&slot_called](int) { slot_called = true; };
skui::core::property<int> property{0};
property.value_changed.connect(slot);
assert(property == 0, "==");
assert(0 == property, "== (reversed)");
assert(property < 1, "<" );
assert(property <= 0, "<=");
assert(property > -1, ">" );
assert(property >= 0, ">=");
assert(property != 1, "!=");
assert(!slot_called, "operators don't emit value_changed");
slot_called = false;
property = 1;
assert(property == 1, "assignment");
assert(slot_called, "assignment emits value_changed");
slot_called = false;
skui::core::property<int> other_property{property};
assert(property == other_property && other_property == 1, "copy construction");
assert(!slot_called, "copy construction does not emit value_changed");
slot_called = false;
other_property = 0;
assert(slot_called, "connection copied");
slot_called = false;
other_property = std::move(property);
assert(other_property == 1, "move assignment moves value");
assert(!slot_called, "move constructor does not emit value_changed");
slot_called = false;
property = 0;
assert(!slot_called, "moved-from property is disconnected");
slot_called = false;
other_property = 0;
assert(slot_called, "moved-to property is connected");
}
}
int main()
{
test_value_changed_signal();
test_basic_operations();
return skui::test::exit_code;
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* 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 "test.h++"
#include "core/property.h++"
namespace
{
using skui::test::assert;
void test_value_changed_signal()
{
int changed_value = 0;
auto slot = [&changed_value](int i) { changed_value = i; };
skui::core::property<int> property{};
property.value_changed.connect(slot);
property = 1;
assert(changed_value == 1, "changed slot called on assignment");
property = std::move(2);
assert(changed_value == 2, "moving value into property emits signal");
}
void test_basic_operations()
{
bool slot_called = false;
auto slot = [&slot_called](int) { slot_called = true; };
skui::core::property<int> property{0};
property.value_changed.connect(slot);
assert(property == 0, "==");
assert(0 == property, "== (reversed)");
assert(property < 1, "<" );
assert(property <= 0, "<=");
assert(property > -1, ">" );
assert(property >= 0, ">=");
assert(property != 1, "!=");
assert(!slot_called, "operators don't emit value_changed");
slot_called = false;
property = 1;
assert(property == 1, "assignment");
assert(slot_called, "assignment emits value_changed");
slot_called = false;
skui::core::property<int> other_property{property};
assert(property == other_property && other_property == 1, "copy construction");
assert(!slot_called, "copy construction does not emit value_changed");
slot_called = false;
other_property = 0;
assert(slot_called, "connection copied");
slot_called = false;
other_property = std::move(property);
assert(other_property == 1, "move assignment moves value");
assert(!slot_called, "move constructor does not emit value_changed");
slot_called = false;
property = 0;
assert(!slot_called, "moved-from property is disconnected");
slot_called = false;
other_property = 0;
assert(slot_called, "moved-to property is connected");
}
}
int main()
{
test_value_changed_signal();
test_basic_operations();
return skui::test::exit_code;
}
|
Initialize uninitialized property in tests.
|
Initialize uninitialized property in tests.
|
C++
|
mit
|
skui-org/skui,rubenvb/skui,skui-org/skui,rubenvb/skui
|
275234763b50c059dbf173e00294d0ea7f452d92
|
webrtc/base/platform_thread.cc
|
webrtc/base/platform_thread.cc
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the below.
do {
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
sched_yield();
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the below.
#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
const struct timespec ts_null = {0};
#endif
do {
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
#if defined(WEBRTC_MAC)
sched_yield();
#else
nanosleep(&ts_null, nullptr);
#endif
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
|
Revert of Use sched_yield on all POSIX platforms in PlatformThread. (patchset #1 id:1 of https://codereview.webrtc.org/2725573002/ )
|
Revert of Use sched_yield on all POSIX platforms in PlatformThread. (patchset #1 id:1 of https://codereview.webrtc.org/2725573002/ )
Reason for revert:
breaks linux_ubsan bots.
Original issue's description:
> Reland of Use sched_yield on all POSIX platforms in PlatformThread. (patchset #1 id:1 of https://codereview.webrtc.org/2712133003/ )
>
> Reason for revert:
> Relanding - using sched_yield() in PlatformThread on all posix platforms.
>
> Original issue's description:
> > Revert of Use sched_yield on all POSIX platforms in PlatformThread. (patchset #1 id:1 of https://codereview.webrtc.org/2716683002/ )
> >
> > Reason for revert:
> > Reverting this change since it didn't affect the perf regressions we were seeing and actually seems to have caused more regressions as per comment in the bug.
> >
> > Original issue's description:
> > > Use sched_yield on all POSIX platforms in PlatformThread.
> > > (not only MacOS)
> > >
> > > This is a test to see if perf regressions we're seeing may be related to the use of nanosleep().
> > >
> > > BUG=695438
> > > [email protected]
> > >
> > > Review-Url: https://codereview.webrtc.org/2716683002 .
> > > Cr-Commit-Position: refs/heads/master@{#16807}
> > > Committed: https://chromium.googlesource.com/external/webrtc/+/384498abb5a0dc3e871e437e56b4a556c3ec1023
> >
> > [email protected]
> > # Skipping CQ checks because original CL landed less than 1 days ago.
> > NOPRESUBMIT=true
> > NOTREECHECKS=true
> > NOTRY=true
> > BUG=695438
> >
> > Review-Url: https://codereview.webrtc.org/2712133003
> > Cr-Commit-Position: refs/heads/master@{#16833}
> > Committed: https://chromium.googlesource.com/external/webrtc/+/3ba1a8cd1b875dc7bfcb7075fe4f78d0dfe0ff98
>
> [email protected]
> # Not skipping CQ checks because original CL landed more than 1 days ago.
> BUG=695438
>
> Review-Url: https://codereview.webrtc.org/2725573002
> Cr-Commit-Position: refs/heads/master@{#16899}
> Committed: https://chromium.googlesource.com/external/webrtc/+/4974df41838367e4d50c42bef3be121c7ac6e331
[email protected],[email protected]
# Skipping CQ checks because original CL landed less than 1 days ago.
NOPRESUBMIT=true
NOTREECHECKS=true
NOTRY=true
BUG=695438
Review-Url: https://codereview.webrtc.org/2721893002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#16903}
|
C++
|
bsd-3-clause
|
ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
|
60919257651b951423706a23dbcb203d0d6d476c
|
src/Tools/Arguments/Types/File_system/File_system.cpp
|
src/Tools/Arguments/Types/File_system/File_system.cpp
|
#include <fstream>
#include <dirent.h>
#include "File_system.hpp"
std::string aff3ct::tools::openmode_to_string(const openmode& mode)
{
std::string str;
switch(mode)
{
case openmode::read :
str += "read only";
break;
case openmode::write :
str += "write only";
break;
case openmode::read_write : // nothing to check
str += "read/write";
break;
}
return str;
}
bool aff3ct::tools::isFile::check(const std::string& filename)
{
std::ifstream f(filename);
auto is_good = f.good();
std::cout << "# (DBG) filename = '" << filename << "', exist = " << is_good << std::endl;
return f.good();
}
bool aff3ct::tools::isFolder::check(const std::string& foldername)
{
DIR *dp = opendir(foldername.c_str());
std::cout << "# (DBG) foldername = '" << foldername << "', exist = " << (dp != nullptr) << std::endl;
if (dp != nullptr)
{
closedir(dp);
return true;
}
return false;
}
bool aff3ct::tools::isPath::check(const std::string& path)
{
return isFile::check(path) || isFolder::check(path);
}
bool aff3ct::tools::noCheck::check(const std::string&)
{
return true;
}
|
#include <fstream>
#include <dirent.h>
#include "File_system.hpp"
std::string aff3ct::tools::openmode_to_string(const openmode& mode)
{
std::string str;
switch(mode)
{
case openmode::read :
str += "read only";
break;
case openmode::write :
str += "write only";
break;
case openmode::read_write : // nothing to check
str += "read/write";
break;
}
return str;
}
bool aff3ct::tools::isFile::check(const std::string& filename)
{
std::ifstream f(filename);
DIR *dp = opendir(filename.c_str());
std::cout << "# (DBG) filename = '" << filename << "', exist = " << (f.good() && !dp) << std::endl;
// if filename is a directory return false
if (dp != nullptr)
{
closedir(dp);
return false;
}
return f.good();
}
bool aff3ct::tools::isFolder::check(const std::string& foldername)
{
DIR *dp = opendir(foldername.c_str());
std::cout << "# (DBG) foldername = '" << foldername << "', exist = " << (dp != nullptr) << std::endl;
if (dp != nullptr)
{
closedir(dp);
return true;
}
return false;
}
bool aff3ct::tools::isPath::check(const std::string& path)
{
return isFile::check(path) || isFolder::check(path);
}
bool aff3ct::tools::noCheck::check(const std::string&)
{
return true;
}
|
Fix the 'isFile::check' function to detect only files instead of files and directories.
|
Fix the 'isFile::check' function to detect only files instead of files and directories.
|
C++
|
mit
|
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
|
7be15981c04e9a9b39969c936e86346efe3de7c2
|
tests/mesh/mesh_input.C
|
tests/mesh/mesh_input.C
|
#include <libmesh/equation_systems.h>
#include <libmesh/implicit_system.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_communication.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/dyna_io.h>
#include <libmesh/exodusII_io.h>
#include <libmesh/dof_map.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
Number x_plus_y (const Point& p,
const Parameters&,
const std::string&,
const std::string&)
{
const Real & x = p(0);
const Real & y = p(1);
return x + y;
}
class MeshInputTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( MeshInputTest );
#if LIBMESH_DIM > 1
#ifdef LIBMESH_HAVE_EXODUS_API
CPPUNIT_TEST( testExodusCopyElementSolution );
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
// Eventually this will support complex numbers.
CPPUNIT_TEST( testExodusWriteElementDataFromDiscontinuousNodalData );
#endif
#endif
CPPUNIT_TEST( testDynaReadElem );
CPPUNIT_TEST( testDynaReadPatch );
CPPUNIT_TEST( testMeshMoveConstructor );
#endif // LIBMESH_DIM > 1
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
#ifdef LIBMESH_HAVE_EXODUS_API
void testExodusCopyElementSolution ()
{
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("e", CONSTANT, MONOMIAL);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(x_plus_y, nullptr, es.parameters);
ExodusII_IO exii(mesh);
// Don't try to write element data as nodal data
std::set<std::string> sys_list;
exii.write_equation_systems("mesh_with_soln.e", es, &sys_list);
// Just write it as element data
exii.write_element_data(es);
}
// copy_elemental_solution currently requires ReplicatedMesh
{
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("teste", CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("mesh_with_soln.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
exii.copy_elemental_solution(sys, "teste", "r_e");
#else
exii.copy_elemental_solution(sys, "teste", "e");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = Real(1.L/6.L); x < 1; x += Real(1.L/3.L))
for (Real y = Real(1.L/6.L); y < 1; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(x+y),
exotol);
}
}
}
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
void testExodusWriteElementDataFromDiscontinuousNodalData()
{
// first scope: write file
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST, L2_LAGRANGE);
MeshTools::Generation::build_cube
(mesh, 2, 2, 2, 0., 1., 0., 1., 0., 1., HEX8);
es.init();
// Set solution u^e_i = i, for the ith vertex of a given element e.
const DofMap & dof_map = sys.get_dof_map();
std::vector<dof_id_type> dof_indices;
for (const auto & elem : mesh.element_ptr_range())
{
dof_map.dof_indices(elem, dof_indices, /*var_id=*/0);
for (unsigned int i=0; i<dof_indices.size(); ++i)
sys.solution->set(dof_indices[i], i);
}
sys.solution->close();
// Now write to file.
ExodusII_IO exii(mesh);
// Don't try to write element data as averaged nodal data.
std::set<std::string> sys_list;
exii.write_equation_systems("elemental_from_nodal.e", es, &sys_list);
// Write one elemental data field per vertex value.
sys_list = {"SimpleSystem"};
exii.write_element_data_from_discontinuous_nodal_data
(es, &sys_list, /*var_suffix=*/"_elem_corner_");
} // end first scope
// second scope: read values back in, verify they are correct.
{
std::vector<std::string> file_var_names =
{"u_elem_corner_0",
"u_elem_corner_1",
"u_elem_corner_2",
"u_elem_corner_3"};
std::vector<Real> expected_values = {0., 1., 2., 3.};
// copy_elemental_solution currently requires ReplicatedMesh
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
for (auto i : index_range(file_var_names))
sys.add_variable(file_var_names[i], CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("elemental_from_nodal.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
for (auto i : index_range(file_var_names))
exii.copy_elemental_solution
(sys, sys.variable_name(i), file_var_names[i]);
// Check that the values we read back in are as expected.
for (const auto & elem : mesh.active_element_ptr_range())
for (auto i : index_range(file_var_names))
{
Real read_val = sys.point_value(i, elem->centroid());
LIBMESH_ASSERT_FP_EQUAL
(read_val, expected_values[i], TOLERANCE*TOLERANCE);
}
} // end second scope
} // end testExodusWriteElementDataFromDiscontinuousNodalData
#endif // !LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
void testDynaReadElem ()
{
Mesh mesh(*TestCommWorld);
DynaIO dyna(mesh);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
if (mesh.processor_id() == 0)
dyna.read("1_quad.dyn");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 1 QUAD9 finite element, attached via a trivial map to 9
// spline Node+NodeElem objects
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(10));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(18));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
if (mesh.query_elem_ptr(9))
{
const Elem & elem = mesh.elem_ref(9);
CPPUNIT_ASSERT_EQUAL(elem.type(), QUAD9);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem.node_ref(n).get_extra_datum<Real>(weight_index),
Real(0.75));
CPPUNIT_ASSERT_EQUAL(elem.point(0)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(0)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(1)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(1)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(2)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(2)(1), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(3)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(3)(1), Real(1.5));
CPPUNIT_ASSERT(elem.has_affine_map());
#if LIBMESH_DIM > 2
for (unsigned int v=0; v != 4; ++v)
CPPUNIT_ASSERT_EQUAL(elem.point(v)(2), Real(0));
#endif
}
}
void testDynaReadPatch ()
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read("25_quad.bxt");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 5^2 QUAD9 elements, with 11^2 nodes,
// tied to 49 Node/NodeElem spline nodes
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(25+49));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(121+49));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (const auto & elem : mesh.active_element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(0.04), elem->volume(), TOLERANCE);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(1.0));
unsigned int n_neighbors = 0, n_neighbors_expected = 2;
for (unsigned int side=0; side != 4; ++side)
if (elem->neighbor_ptr(side))
n_neighbors++;
Point c = elem->centroid();
if (c(0) > 0.2 && c(0) < 0.8)
n_neighbors_expected++;
if (c(1) > 0.2 && c(1) < 0.8)
n_neighbors_expected++;
CPPUNIT_ASSERT_EQUAL(n_neighbors, n_neighbors_expected);
}
// Now test whether we can assign the desired constraint equations
EquationSystems es(mesh);
ImplicitSystem & sys = es.add_system<ImplicitSystem>("test");
sys.add_variable("u", SECOND); // to match QUAD9
es.init();
dyna.add_spline_constraints(sys.get_dof_map(), 0, 0);
}
void testMeshMoveConstructor ()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
// Construct mesh2, stealing the resources of the original.
Mesh mesh2(std::move(mesh));
// Make sure mesh2 now has the 9 elements.
CPPUNIT_ASSERT_EQUAL(mesh2.n_elem(),
static_cast<dof_id_type>(9));
// Verify that the moved-from mesh's Partitioner and BoundaryInfo
// objects were successfully stolen. Note: moved-from unique_ptrs
// are guaranteed to compare equal to nullptr, see e.g. Section
// 20.8.1/4 of the standard.
// https://stackoverflow.com/questions/24061767/is-unique-ptr-guaranteed-to-store-nullptr-after-move
CPPUNIT_ASSERT(!mesh.partitioner());
CPPUNIT_ASSERT(!mesh.boundary_info);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshInputTest );
|
#include <libmesh/equation_systems.h>
#include <libmesh/implicit_system.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_communication.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/replicated_mesh.h>
#include <libmesh/dyna_io.h>
#include <libmesh/exodusII_io.h>
#include <libmesh/dof_map.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
Number x_plus_y (const Point& p,
const Parameters&,
const std::string&,
const std::string&)
{
const Real & x = p(0);
const Real & y = p(1);
return x + y;
}
class MeshInputTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( MeshInputTest );
#if LIBMESH_DIM > 1
#ifdef LIBMESH_HAVE_EXODUS_API
CPPUNIT_TEST( testExodusCopyElementSolution );
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
// Eventually this will support complex numbers.
CPPUNIT_TEST( testExodusWriteElementDataFromDiscontinuousNodalData );
#endif
#endif
CPPUNIT_TEST( testDynaReadElem );
CPPUNIT_TEST( testDynaReadPatch );
CPPUNIT_TEST( testMeshMoveConstructor );
#endif // LIBMESH_DIM > 1
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{}
void tearDown()
{}
#ifdef LIBMESH_HAVE_EXODUS_API
void testExodusCopyElementSolution ()
{
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("e", CONSTANT, MONOMIAL);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
es.init();
sys.project_solution(x_plus_y, nullptr, es.parameters);
ExodusII_IO exii(mesh);
// Don't try to write element data as nodal data
std::set<std::string> sys_list;
exii.write_equation_systems("mesh_with_soln.e", es, &sys_list);
// Just write it as element data
exii.write_element_data(es);
}
// copy_elemental_solution currently requires ReplicatedMesh
{
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System &sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("teste", CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("mesh_with_soln.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
// Read the solution e into variable teste.
//
// With complex numbers, we'll only bother reading the real
// part.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
exii.copy_elemental_solution(sys, "teste", "r_e");
#else
exii.copy_elemental_solution(sys, "teste", "e");
#endif
// Exodus only handles double precision
Real exotol = std::max(TOLERANCE*TOLERANCE, Real(1e-12));
for (Real x = Real(1.L/6.L); x < 1; x += Real(1.L/3.L))
for (Real y = Real(1.L/6.L); y < 1; y += Real(1.L/3.L))
{
Point p(x,y);
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(sys.point_value(0,p)),
libmesh_real(x+y),
exotol);
}
}
}
#ifndef LIBMESH_USE_COMPLEX_NUMBERS
void testExodusWriteElementDataFromDiscontinuousNodalData()
{
// first scope: write file
{
Mesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
sys.add_variable("u", FIRST, L2_LAGRANGE);
MeshTools::Generation::build_cube
(mesh, 2, 2, 2, 0., 1., 0., 1., 0., 1., HEX8);
es.init();
// Set solution u^e_i = i, for the ith vertex of a given element e.
const DofMap & dof_map = sys.get_dof_map();
std::vector<dof_id_type> dof_indices;
for (const auto & elem : mesh.element_ptr_range())
{
dof_map.dof_indices(elem, dof_indices, /*var_id=*/0);
for (unsigned int i=0; i<dof_indices.size(); ++i)
sys.solution->set(dof_indices[i], i);
}
sys.solution->close();
// Now write to file.
ExodusII_IO exii(mesh);
// Don't try to write element data as averaged nodal data.
std::set<std::string> sys_list;
exii.write_equation_systems("elemental_from_nodal.e", es, &sys_list);
// Write one elemental data field per vertex value.
sys_list = {"SimpleSystem"};
exii.write_element_data_from_discontinuous_nodal_data
(es, &sys_list, /*var_suffix=*/"_elem_corner_");
} // end first scope
// second scope: read values back in, verify they are correct.
{
std::vector<std::string> file_var_names =
{"u_elem_corner_0",
"u_elem_corner_1",
"u_elem_corner_2",
"u_elem_corner_3"};
std::vector<Real> expected_values = {0., 1., 2., 3.};
// copy_elemental_solution currently requires ReplicatedMesh
ReplicatedMesh mesh(*TestCommWorld);
EquationSystems es(mesh);
System & sys = es.add_system<System> ("SimpleSystem");
for (auto i : index_range(file_var_names))
sys.add_variable(file_var_names[i], CONSTANT, MONOMIAL);
ExodusII_IO exii(mesh);
if (mesh.processor_id() == 0)
exii.read("elemental_from_nodal.e");
MeshCommunication().broadcast(mesh);
mesh.prepare_for_use();
es.init();
for (auto i : index_range(file_var_names))
exii.copy_elemental_solution
(sys, sys.variable_name(i), file_var_names[i]);
// Check that the values we read back in are as expected.
for (const auto & elem : mesh.active_element_ptr_range())
for (auto i : index_range(file_var_names))
{
Real read_val = sys.point_value(i, elem->centroid());
LIBMESH_ASSERT_FP_EQUAL
(read_val, expected_values[i], TOLERANCE*TOLERANCE);
}
} // end second scope
} // end testExodusWriteElementDataFromDiscontinuousNodalData
#endif // !LIBMESH_USE_COMPLEX_NUMBERS
#endif // LIBMESH_HAVE_EXODUS_API
void testDynaReadElem ()
{
Mesh mesh(*TestCommWorld);
DynaIO dyna(mesh);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
if (mesh.processor_id() == 0)
dyna.read("1_quad.dyn");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 1 QUAD9 finite element, attached via a trivial map to 9
// spline Node+NodeElem objects
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(10));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(18));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
if (mesh.query_elem_ptr(9))
{
const Elem & elem = mesh.elem_ref(9);
CPPUNIT_ASSERT_EQUAL(elem.type(), QUAD9);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem.node_ref(n).get_extra_datum<Real>(weight_index),
Real(0.75));
CPPUNIT_ASSERT_EQUAL(elem.point(0)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(0)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(1)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(1)(1), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(2)(0), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(2)(1), Real(1.5));
CPPUNIT_ASSERT_EQUAL(elem.point(3)(0), Real(0.5));
CPPUNIT_ASSERT_EQUAL(elem.point(3)(1), Real(1.5));
CPPUNIT_ASSERT(elem.has_affine_map());
#if LIBMESH_DIM > 2
for (unsigned int v=0; v != 4; ++v)
CPPUNIT_ASSERT_EQUAL(elem.point(v)(2), Real(0));
#endif
}
}
void testDynaReadPatch ()
{
Mesh mesh(*TestCommWorld);
// Make DynaIO::add_spline_constraints work on DistributedMesh
mesh.allow_renumbering(false);
mesh.allow_remote_element_removal(false);
DynaIO dyna(mesh);
if (mesh.processor_id() == 0)
dyna.read("25_quad.bxt");
MeshCommunication().broadcast (mesh);
mesh.prepare_for_use();
// We have 5^2 QUAD9 elements, with 11^2 nodes,
// tied to 49 Node/NodeElem spline nodes
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(25+49));
CPPUNIT_ASSERT_EQUAL(mesh.n_nodes(), dof_id_type(121+49));
CPPUNIT_ASSERT_EQUAL(mesh.default_mapping_type(),
RATIONAL_BERNSTEIN_MAP);
unsigned char weight_index = mesh.default_mapping_data();
for (const auto & elem : mesh.active_element_ptr_range())
{
if (elem->type() == NODEELEM)
continue;
LIBMESH_ASSERT_FP_EQUAL(libmesh_real(0.04), elem->volume(), TOLERANCE);
for (unsigned int n=0; n != 9; ++n)
CPPUNIT_ASSERT_EQUAL
(elem->node_ref(n).get_extra_datum<Real>(weight_index),
Real(1.0));
unsigned int n_neighbors = 0, n_neighbors_expected = 2;
for (unsigned int side=0; side != 4; ++side)
if (elem->neighbor_ptr(side))
n_neighbors++;
Point c = elem->centroid();
if (c(0) > 0.2 && c(0) < 0.8)
n_neighbors_expected++;
if (c(1) > 0.2 && c(1) < 0.8)
n_neighbors_expected++;
CPPUNIT_ASSERT_EQUAL(n_neighbors, n_neighbors_expected);
}
#ifdef LIBMESH_ENABLE_CONSTRAINTS
// Now test whether we can assign the desired constraint equations
EquationSystems es(mesh);
ImplicitSystem & sys = es.add_system<ImplicitSystem>("test");
sys.add_variable("u", SECOND); // to match QUAD9
es.init();
dyna.add_spline_constraints(sys.get_dof_map(), 0, 0);
// We should have a constraint on every FE dof
CPPUNIT_ASSERT_EQUAL(sys.get_dof_map().n_constrained_dofs(), dof_id_type(121));
#endif // LIBMESH_ENABLE_CONSTRAINTS
}
void testMeshMoveConstructor ()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_square (mesh,
3, 3,
0., 1., 0., 1.);
// Construct mesh2, stealing the resources of the original.
Mesh mesh2(std::move(mesh));
// Make sure mesh2 now has the 9 elements.
CPPUNIT_ASSERT_EQUAL(mesh2.n_elem(),
static_cast<dof_id_type>(9));
// Verify that the moved-from mesh's Partitioner and BoundaryInfo
// objects were successfully stolen. Note: moved-from unique_ptrs
// are guaranteed to compare equal to nullptr, see e.g. Section
// 20.8.1/4 of the standard.
// https://stackoverflow.com/questions/24061767/is-unique-ptr-guaranteed-to-store-nullptr-after-move
CPPUNIT_ASSERT(!mesh.partitioner());
CPPUNIT_ASSERT(!mesh.boundary_info);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshInputTest );
|
Check constraint counts
|
Check constraint counts
|
C++
|
lgpl-2.1
|
libMesh/libmesh,roystgnr/libmesh,libMesh/libmesh,dschwen/libmesh,libMesh/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,roystgnr/libmesh,dschwen/libmesh,libMesh/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,capitalaslash/libmesh,libMesh/libmesh,jwpeterson/libmesh,roystgnr/libmesh,roystgnr/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,capitalaslash/libmesh,dschwen/libmesh,dschwen/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,capitalaslash/libmesh,jwpeterson/libmesh,dschwen/libmesh,capitalaslash/libmesh,libMesh/libmesh,dschwen/libmesh,libMesh/libmesh,capitalaslash/libmesh,libMesh/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,roystgnr/libmesh,capitalaslash/libmesh,dschwen/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,dschwen/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh
|
ad07e34190f6c41e0035ada25e39f5e4512f0967
|
parContextManager.cpp
|
parContextManager.cpp
|
//Implementation of the parallel statement execution manager
#include "parContextManager.h"
StatementContext::StatementContext() {
//Do nothing
}
/*=================================StatementContext=================================*/
void StatementContext::addIntFuture(std::future<int64_t>& f, const int64_t id) {
map_mutex.lock();
assert(int_future_id_map.count(id)==0 && "Statement id already exists");
int_future_id_map.insert(std::pair<int64_t,std::future<int64_t>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addFloatFuture(std::future<double>& f, const int64_t id) {
map_mutex.lock();
assert(float_future_id_map.count(id)==0 && "Statement id already exists");
float_future_id_map.insert(std::pair<int64_t,std::future<double>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addIntptrFuture(std::future<int64_t*>& f, const int64_t id) {
map_mutex.lock();
assert(intptr_future_id_map.count(id)==0 && "Statement id already exists");
intptr_future_id_map.insert(std::pair<int64_t,std::future<int64_t*>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addFloatptrFuture(std::future<double*>& f, const int64_t id) {
map_mutex.lock();
assert(floatptr_future_id_map.count(id)==0 && "Statement id already exists");
floatptr_future_id_map.insert(std::pair<int64_t,std::future<double*>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addVoidFuture(std::future<void>& f, const int64_t id) {
map_mutex.lock();
assert(void_future_id_map.count(id)==0 && "Statement id already exists");
void_future_id_map.insert(std::pair<int64_t,std::future<void>>(id,std::move(f)));
map_mutex.unlock();
}
std::future<int64_t> StatementContext::getIntFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(int_future_id_map.at(id));
int_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<double> StatementContext::getFloatFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(float_future_id_map.at(id));
float_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<int64_t*> StatementContext::getIntptrFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(intptr_future_id_map.at(id));
intptr_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<double*> StatementContext::getFloatptrFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(floatptr_future_id_map.at(id));
floatptr_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<void> StatementContext::getVoidFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(void_future_id_map.at(id));
void_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
/*=================================ParContextManager=================================*/
ParContextManager::ParContextManager() {
set_max_threads();
thread_count = 0;
next_cid = 0;
}
int64_t ParContextManager::make_context() {
mutex.lock();
int64_t cid = next_cid++;
mutex.unlock();
return cid;
}
void ParContextManager::destroy_context(const int64_t cid) {
mutex.lock();
assert(context_map.count(cid)==1);
context_map.erase(cid);
mutex.unlock();
}
void ParContextManager::sched_int(int64_t (*statement)(void),const int64_t id,const int64_t cid) {
mutex.lock();
std::future<int64_t> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addIntFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_float(double (*statement)(void),const int64_t id,const int64_t cid) {
mutex.lock();
std::future<double> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addFloatFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_intptr(int64_t* (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<int64_t*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addIntptrFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_floatptr(double* (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<double*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addFloatptrFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_void(void (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<void> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addVoidFuture(promise,id);
mutex.unlock();
}
int64_t ParContextManager::recon_int(const int64_t original,const int64_t known,const int64_t update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t> fv = context_map.at(cid).getIntFuture(id);
int64_t v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
double ParContextManager::recon_float(const double original,const int64_t known,const double update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double> fv = context_map.at(cid).getFloatFuture(id);
double v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
int64_t* ParContextManager::recon_intptr(const int64_t* original,const int64_t known,const int64_t* update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t*> fv = context_map.at(cid).getIntptrFuture(id);
int64_t* v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
double* ParContextManager::recon_floatptr(const double* original,const int64_t known,const double* update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double*> fv = context_map.at(cid).getFloatptrFuture(id);
double* v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
void ParContextManager::recon_void(const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<void> fv = context_map.at(cid).getVoidFuture(id);
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
fv.get();
} else {
fv.get();
thread_count--;
mutex.unlock();
}
}
void ParContextManager::set_max_threads() {
unsigned long dth = std::thread::hardware_concurrency()-1;
printf("Detected %d additional compute elements.\n",(int)dth);
if (dth < 0) max_threads = 0;
else if (dth > 3) max_threads = 3;
else max_threads = dth;
printf("Setting max execution threads to: %d\n",(int)max_threads+1);
}
|
//Implementation of the parallel statement execution manager
#include "parContextManager.h"
StatementContext::StatementContext() {
//Do nothing
}
/*=================================StatementContext=================================*/
void StatementContext::addIntFuture(std::future<int64_t>& f, const int64_t id) {
map_mutex.lock();
assert(int_future_id_map.count(id)==0 && "Statement id already exists");
int_future_id_map.insert(std::pair<int64_t,std::future<int64_t>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addFloatFuture(std::future<double>& f, const int64_t id) {
map_mutex.lock();
assert(float_future_id_map.count(id)==0 && "Statement id already exists");
float_future_id_map.insert(std::pair<int64_t,std::future<double>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addIntptrFuture(std::future<int64_t*>& f, const int64_t id) {
map_mutex.lock();
assert(intptr_future_id_map.count(id)==0 && "Statement id already exists");
intptr_future_id_map.insert(std::pair<int64_t,std::future<int64_t*>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addFloatptrFuture(std::future<double*>& f, const int64_t id) {
map_mutex.lock();
assert(floatptr_future_id_map.count(id)==0 && "Statement id already exists");
floatptr_future_id_map.insert(std::pair<int64_t,std::future<double*>>(id,std::move(f)));
map_mutex.unlock();
}
void StatementContext::addVoidFuture(std::future<void>& f, const int64_t id) {
map_mutex.lock();
assert(void_future_id_map.count(id)==0 && "Statement id already exists");
void_future_id_map.insert(std::pair<int64_t,std::future<void>>(id,std::move(f)));
map_mutex.unlock();
}
std::future<int64_t> StatementContext::getIntFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(int_future_id_map.at(id));
int_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<double> StatementContext::getFloatFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(float_future_id_map.at(id));
float_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<int64_t*> StatementContext::getIntptrFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(intptr_future_id_map.at(id));
intptr_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<double*> StatementContext::getFloatptrFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(floatptr_future_id_map.at(id));
floatptr_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
std::future<void> StatementContext::getVoidFuture(const int64_t id) {
map_mutex.lock();
auto f = std::move(void_future_id_map.at(id));
void_future_id_map.erase(id);
map_mutex.unlock();
return f;
}
/*=================================ParContextManager=================================*/
ParContextManager::ParContextManager() {
set_max_threads();
thread_count = 0;
next_cid = 0;
}
int64_t ParContextManager::make_context() {
mutex.lock();
int64_t cid = next_cid++;
mutex.unlock();
return cid;
}
void ParContextManager::destroy_context(const int64_t cid) {
mutex.lock();
assert(context_map.count(cid)==1);
context_map.erase(cid);
mutex.unlock();
}
void ParContextManager::sched_int(int64_t (*statement)(void),const int64_t id,const int64_t cid) {
mutex.lock();
std::future<int64_t> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addIntFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_float(double (*statement)(void),const int64_t id,const int64_t cid) {
mutex.lock();
std::future<double> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addFloatFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_intptr(int64_t* (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<int64_t*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addIntptrFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_floatptr(double* (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<double*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addFloatptrFuture(promise,id);
mutex.unlock();
}
void ParContextManager::sched_void(void (*statement)(void),int64_t id,const int64_t cid) {
mutex.lock();
std::future<void> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement);
} else {
promise = std::async(std::launch::async,statement);
thread_count++;
}
context_map.at(cid).addVoidFuture(promise,id);
mutex.unlock();
}
int64_t ParContextManager::recon_int(const int64_t original,const int64_t known,const int64_t update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t> fv = context_map.at(cid).getIntFuture(id);
int64_t v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
double ParContextManager::recon_float(const double original,const int64_t known,const double update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double> fv = context_map.at(cid).getFloatFuture(id);
double v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
int64_t* ParContextManager::recon_intptr(const int64_t* original,const int64_t known,const int64_t* update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t*> fv = context_map.at(cid).getIntptrFuture(id);
int64_t* v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
double* ParContextManager::recon_floatptr(const double* original,const int64_t known,const double* update,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double*> fv = context_map.at(cid).getFloatptrFuture(id);
double* v;
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
v = fv.get();
} else {
v = fv.get();
thread_count--;
mutex.unlock();
}
return v;
}
void ParContextManager::recon_void(const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<void> fv = context_map.at(cid).getVoidFuture(id);
if (fv.wait_for(span)==std::future_status::deferred) {
mutex.unlock();
fv.get();
} else {
fv.get();
thread_count--;
mutex.unlock();
}
}
void ParContextManager::set_max_threads() {
unsigned long dth = std::thread::hardware_concurrency();
printf("Detected %d compute elements.\n",(int)dth);
if (dth < 2) max_threads = 2;
else if (dth > 4) max_threads = 4;
else max_threads = dth;
printf("Setting max execution threads to: %d\n",(int)max_threads);
}
|
Improve parallism by not counting main as a worker
|
Improve parallism by not counting main as a worker
|
C++
|
apache-2.0
|
henfredemars/Fork-Lang,henfredemars/Fork-Lang,henfredemars/Fork-Lang,henfredemars/Fork-Lang,henfredemars/Fork-Lang,henfredemars/Fork-Lang,henfredemars/Fork-Lang
|
f980e88f33878a832d6f3cb6bffe24823486a6bd
|
gm/tilemodes.cpp
|
gm/tilemodes.cpp
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTypeface.h"
// effects
#include "SkGradientShader.h"
#include "SkUnitMappers.h"
#include "SkBlurDrawLooper.h"
static void makebm(SkBitmap* bm, SkBitmap::Config config, int w, int h) {
bm->setConfig(config, w, h);
bm->allocPixels();
bm->eraseColor(SK_ColorTRANSPARENT);
SkCanvas canvas(*bm);
SkPoint pts[] = { { 0, 0 }, { SkIntToScalar(w), SkIntToScalar(h)} };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE };
SkScalar pos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
SkPaint paint;
SkUnitMapper* um = NULL;
um = new SkCosineMapper;
// um = new SkDiscreteMapper(12);
SkAutoUnref au(um);
paint.setDither(true);
paint.setShader(SkGradientShader::CreateLinear(pts, colors, pos,
SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode, um))->unref();
canvas.drawPaint(paint);
}
static void setup(SkPaint* paint, const SkBitmap& bm, bool filter,
SkShader::TileMode tmx, SkShader::TileMode tmy) {
SkShader* shader = SkShader::CreateBitmapShader(bm, tmx, tmy);
paint->setShader(shader)->unref();
paint->setFilterBitmap(filter);
}
static const SkBitmap::Config gConfigs[] = {
SkBitmap::kARGB_8888_Config,
SkBitmap::kRGB_565_Config,
SkBitmap::kARGB_4444_Config
};
static const int gWidth = 32;
static const int gHeight = 32;
class TilingGM : public skiagm::GM {
SkBlurDrawLooper fLooper;
public:
TilingGM()
: fLooper(SkIntToScalar(1), SkIntToScalar(2), SkIntToScalar(2),
0x88000000) {
}
SkBitmap fTexture[SK_ARRAY_COUNT(gConfigs)];
protected:
SkString onShortName() {
return SkString("tilemodes");
}
SkISize onISize() { return SkISize::Make(880, 560); }
virtual void onOnceBeforeDraw() SK_OVERRIDE {
for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) {
makebm(&fTexture[i], gConfigs[i], gWidth, gHeight);
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkRect r = { 0, 0, SkIntToScalar(gWidth*2), SkIntToScalar(gHeight*2) };
static const char* gConfigNames[] = { "8888", "565", "4444" };
static const bool gFilters[] = { false, true };
static const char* gFilterNames[] = { "point", "bilinear" };
static const SkShader::TileMode gModes[] = { SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode };
static const char* gModeNames[] = { "C", "R", "M" };
SkScalar y = SkIntToScalar(24);
SkScalar x = SkIntToScalar(10);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
SkPaint p;
SkString str;
p.setAntiAlias(true);
p.setDither(true);
p.setLooper(&fLooper);
str.printf("[%s,%s]", gModeNames[kx], gModeNames[ky]);
p.setTextAlign(SkPaint::kCenter_Align);
canvas->drawText(str.c_str(), str.size(), x + r.width()/2, y, p);
x += r.width() * 4 / 3;
}
}
y += SkIntToScalar(16);
for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) {
for (size_t j = 0; j < SK_ARRAY_COUNT(gFilters); j++) {
x = SkIntToScalar(10);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
SkPaint paint;
setup(&paint, fTexture[i], gFilters[j], gModes[kx], gModes[ky]);
paint.setDither(true);
canvas->save();
canvas->translate(x, y);
canvas->drawRect(r, paint);
canvas->restore();
x += r.width() * 4 / 3;
}
}
{
SkPaint p;
SkString str;
p.setAntiAlias(true);
p.setLooper(&fLooper);
str.printf("%s, %s", gConfigNames[i], gFilterNames[j]);
canvas->drawText(str.c_str(), str.size(), x, y + r.height() * 2 / 3, p);
}
y += r.height() * 4 / 3;
}
}
}
private:
typedef skiagm::GM INHERITED;
};
static SkShader* make_bm(SkShader::TileMode tx, SkShader::TileMode ty) {
SkBitmap bm;
makebm(&bm, SkBitmap::kARGB_8888_Config, gWidth, gHeight);
return SkShader::CreateBitmapShader(bm, tx, ty);
}
static SkShader* make_grad(SkShader::TileMode tx, SkShader::TileMode ty) {
SkPoint pts[] = { { 0, 0 }, { SkIntToScalar(gWidth), SkIntToScalar(gHeight)} };
SkPoint center = { SkIntToScalar(gWidth)/2, SkIntToScalar(gHeight)/2 };
SkScalar rad = SkIntToScalar(gWidth)/2;
SkColor colors[] = { 0xFFFF0000, 0xFF0044FF };
int index = (int)ty;
switch (index % 3) {
case 0:
return SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), tx);
case 1:
return SkGradientShader::CreateRadial(center, rad, colors, NULL, SK_ARRAY_COUNT(colors), tx);
case 2:
return SkGradientShader::CreateSweep(center.fX, center.fY, colors, NULL, SK_ARRAY_COUNT(colors));
}
return NULL;
}
typedef SkShader* (*ShaderProc)(SkShader::TileMode, SkShader::TileMode);
class Tiling2GM : public skiagm::GM {
ShaderProc fProc;
SkString fName;
public:
Tiling2GM(ShaderProc proc, const char name[]) : fProc(proc) {
fName.printf("tilemode_%s", name);
}
protected:
SkString onShortName() {
return fName;
}
SkISize onISize() { return SkISize::Make(880, 560); }
virtual void onDraw(SkCanvas* canvas) {
canvas->scale(SkIntToScalar(3)/2, SkIntToScalar(3)/2);
const SkScalar w = SkIntToScalar(gWidth);
const SkScalar h = SkIntToScalar(gHeight);
SkRect r = { -w, -h, w*2, h*2 };
static const SkShader::TileMode gModes[] = {
SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode
};
static const char* gModeNames[] = {
"Clamp", "Repeat", "Mirror"
};
SkScalar y = SkIntToScalar(24);
SkScalar x = SkIntToScalar(66);
SkPaint p;
p.setAntiAlias(true);
p.setTextAlign(SkPaint::kCenter_Align);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
SkString str(gModeNames[kx]);
canvas->drawText(str.c_str(), str.size(), x + r.width()/2, y, p);
x += r.width() * 4 / 3;
}
y += SkIntToScalar(16) + h;
p.setTextAlign(SkPaint::kRight_Align);
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
x = SkIntToScalar(16) + w;
SkString str(gModeNames[ky]);
canvas->drawText(str.c_str(), str.size(), x, y + h/2, p);
x += SkIntToScalar(50);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
SkPaint paint;
paint.setShader(fProc(gModes[kx], gModes[ky]))->unref();
canvas->save();
canvas->translate(x, y);
canvas->drawRect(r, paint);
canvas->restore();
x += r.width() * 4 / 3;
}
y += r.height() * 4 / 3;
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory(void*) { return new TilingGM; }
static skiagm::GMRegistry reg(MyFactory);
static skiagm::GM* MyFactory2(void*) { return new Tiling2GM(make_bm, "bitmap"); }
static skiagm::GMRegistry reg2(MyFactory2);
static skiagm::GM* MyFactory3(void*) { return new Tiling2GM(make_grad, "gradient"); }
static skiagm::GMRegistry reg3(MyFactory3);
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTypeface.h"
// effects
#include "SkGradientShader.h"
#include "SkUnitMappers.h"
#include "SkBlurDrawLooper.h"
static void makebm(SkBitmap* bm, SkBitmap::Config config, int w, int h) {
bm->setConfig(config, w, h);
bm->allocPixels();
bm->eraseColor(SK_ColorTRANSPARENT);
SkCanvas canvas(*bm);
SkPoint pts[] = { { 0, 0 }, { SkIntToScalar(w), SkIntToScalar(h)} };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE };
SkScalar pos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
SkPaint paint;
SkUnitMapper* um = NULL;
um = new SkCosineMapper;
// um = new SkDiscreteMapper(12);
SkAutoUnref au(um);
paint.setDither(true);
paint.setShader(SkGradientShader::CreateLinear(pts, colors, pos,
SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode, um))->unref();
canvas.drawPaint(paint);
}
static void setup(SkPaint* paint, const SkBitmap& bm, bool filter,
SkShader::TileMode tmx, SkShader::TileMode tmy) {
SkShader* shader = SkShader::CreateBitmapShader(bm, tmx, tmy);
paint->setShader(shader)->unref();
paint->setFilterBitmap(filter);
}
static const SkBitmap::Config gConfigs[] = {
SkBitmap::kARGB_8888_Config,
SkBitmap::kRGB_565_Config,
SkBitmap::kARGB_4444_Config
};
static const int gWidth = 32;
static const int gHeight = 32;
class TilingGM : public skiagm::GM {
SkBlurDrawLooper fLooper;
public:
TilingGM()
: fLooper(SkIntToScalar(1), SkIntToScalar(2), SkIntToScalar(2),
0x88000000) {
}
SkBitmap fTexture[SK_ARRAY_COUNT(gConfigs)];
protected:
SkString onShortName() {
return SkString("tilemodes");
}
SkISize onISize() { return SkISize::Make(880, 560); }
virtual void onOnceBeforeDraw() SK_OVERRIDE {
for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) {
makebm(&fTexture[i], gConfigs[i], gWidth, gHeight);
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkRect r = { 0, 0, SkIntToScalar(gWidth*2), SkIntToScalar(gHeight*2) };
static const char* gConfigNames[] = { "8888", "565", "4444" };
static const bool gFilters[] = { false, true };
static const char* gFilterNames[] = { "point", "bilinear" };
static const SkShader::TileMode gModes[] = { SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode };
static const char* gModeNames[] = { "C", "R", "M" };
SkScalar y = SkIntToScalar(24);
SkScalar x = SkIntToScalar(10);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
SkPaint p;
SkString str;
p.setAntiAlias(true);
p.setDither(true);
p.setLooper(&fLooper);
str.printf("[%s,%s]", gModeNames[kx], gModeNames[ky]);
p.setTextAlign(SkPaint::kCenter_Align);
canvas->drawText(str.c_str(), str.size(), x + r.width()/2, y, p);
x += r.width() * 4 / 3;
}
}
y += SkIntToScalar(16);
for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) {
for (size_t j = 0; j < SK_ARRAY_COUNT(gFilters); j++) {
x = SkIntToScalar(10);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
SkPaint paint;
setup(&paint, fTexture[i], gFilters[j], gModes[kx], gModes[ky]);
paint.setDither(true);
canvas->save();
canvas->translate(x, y);
canvas->drawRect(r, paint);
canvas->restore();
x += r.width() * 4 / 3;
}
}
{
SkPaint p;
SkString str;
p.setAntiAlias(true);
p.setLooper(&fLooper);
str.printf("%s, %s", gConfigNames[i], gFilterNames[j]);
canvas->drawText(str.c_str(), str.size(), x, y + r.height() * 2 / 3, p);
}
y += r.height() * 4 / 3;
}
}
}
private:
typedef skiagm::GM INHERITED;
};
static SkShader* make_bm(SkShader::TileMode tx, SkShader::TileMode ty) {
SkBitmap bm;
makebm(&bm, SkBitmap::kARGB_8888_Config, gWidth, gHeight);
return SkShader::CreateBitmapShader(bm, tx, ty);
}
static SkShader* make_grad(SkShader::TileMode tx, SkShader::TileMode ty) {
SkPoint pts[] = { { 0, 0 }, { SkIntToScalar(gWidth), SkIntToScalar(gHeight)} };
SkPoint center = { SkIntToScalar(gWidth)/2, SkIntToScalar(gHeight)/2 };
SkScalar rad = SkIntToScalar(gWidth)/2;
SkColor colors[] = { 0xFFFF0000, 0xFF0044FF };
int index = (int)ty;
switch (index % 3) {
case 0:
return SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), tx);
case 1:
return SkGradientShader::CreateRadial(center, rad, colors, NULL, SK_ARRAY_COUNT(colors), tx);
case 2:
return SkGradientShader::CreateSweep(center.fX, center.fY, colors, NULL, SK_ARRAY_COUNT(colors));
}
return NULL;
}
typedef SkShader* (*ShaderProc)(SkShader::TileMode, SkShader::TileMode);
class Tiling2GM : public skiagm::GM {
ShaderProc fProc;
SkString fName;
public:
Tiling2GM(ShaderProc proc, const char name[]) : fProc(proc) {
fName.printf("tilemode_%s", name);
}
protected:
SkString onShortName() {
return fName;
}
SkISize onISize() { return SkISize::Make(880, 560); }
virtual void onDraw(SkCanvas* canvas) {
canvas->scale(SkIntToScalar(3)/2, SkIntToScalar(3)/2);
const SkScalar w = SkIntToScalar(gWidth);
const SkScalar h = SkIntToScalar(gHeight);
SkRect r = { -w, -h, w*2, h*2 };
static const SkShader::TileMode gModes[] = {
SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode
};
static const char* gModeNames[] = {
"Clamp", "Repeat", "Mirror"
};
SkScalar y = SkIntToScalar(24);
SkScalar x = SkIntToScalar(66);
SkPaint p;
p.setAntiAlias(true);
p.setTextAlign(SkPaint::kCenter_Align);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
SkString str(gModeNames[kx]);
canvas->drawText(str.c_str(), str.size(), x + r.width()/2, y, p);
x += r.width() * 4 / 3;
}
y += SkIntToScalar(16) + h;
p.setTextAlign(SkPaint::kRight_Align);
for (size_t ky = 0; ky < SK_ARRAY_COUNT(gModes); ky++) {
x = SkIntToScalar(16) + w;
SkString str(gModeNames[ky]);
canvas->drawText(str.c_str(), str.size(), x, y + h/2, p);
x += SkIntToScalar(50);
for (size_t kx = 0; kx < SK_ARRAY_COUNT(gModes); kx++) {
SkPaint paint;
paint.setShader(fProc(gModes[kx], gModes[ky]))->unref();
canvas->save();
canvas->translate(x, y);
canvas->drawRect(r, paint);
canvas->restore();
x += r.width() * 4 / 3;
}
y += r.height() * 4 / 3;
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM( return new TilingGM; )
DEF_GM( return new Tiling2GM(make_bm, "bitmap"); )
DEF_GM( return new Tiling2GM(make_grad, "gradient"); )
|
use DEF_GM
|
use DEF_GM
|
C++
|
bsd-3-clause
|
csulmone/skia,csulmone/skia,csulmone/skia,csulmone/skia
|
caaa893b893fc4b976ed7a967a114659ce356769
|
Code/Native/Source/LightSystem/ShadowManager.cpp
|
Code/Native/Source/LightSystem/ShadowManager.cpp
|
/**
*
* RenderPipeline
*
* Copyright (c) 2014-2015 tobspr <[email protected]>
*
* 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 "ShadowManager.h"
NotifyCategoryDef(shadowmanager, "");
/**
* @brief Constructs a new shadow atlas
* @details This constructs a new shadow atlas. There are a set of properties
* which should be set before calling ShadowManager::init, see the set-Methods.
* After all properties are set, ShadowManager::init should get called.
* ShadowManager::update should get called on a per frame basis.
*/
ShadowManager::ShadowManager() {
_max_updates = 10;
_atlas = NULL;
_atlas_size = 4096;
_tag_state_mgr = NULL;
_atlas_graphics_output = NULL;
}
/**
* @brief Destructs the ShadowManager
* @details This destructs the shadow manager, clearing all resources used
*/
ShadowManager::~ShadowManager() {
delete _atlas;
// Todo: Could eventually unregister all shadow cameras. Since the tag state
// manager does this on cleanup already, and we get destructed at the same
// time (if at all), this is not really necessary
}
/**
* @brief Initializes the ShadowManager.
* @details This initializes the ShadowManager. All properties should have
* been set before calling this, otherwise assertions will get triggered.
*
* This setups everything required for rendering shadows, including the
* shadow atlas and the various shadow cameras. After calling this method,
* no properties can be changed anymore.
*/
void ShadowManager::init() {
nassertv(!_scene_parent.is_empty()); // Scene parent not set, call set_scene_parent before init!
nassertv(_tag_state_mgr != NULL); // TagStateManager not set, call set_tag_state_mgr before init!
nassertv(_atlas_graphics_output != NULL); // AtlasGraphicsOutput not set, call set_atlas_graphics_output before init!
_cameras.resize(_max_updates);
_display_regions.resize(_max_updates);
_camera_nps.reserve(_max_updates);
// Create the cameras and regions
for(size_t i = 0; i < _max_updates; ++i) {
// Create the camera
PT(Camera) camera = new Camera("ShadowCam-" + to_string(i));
camera->set_lens(new MatrixLens());
camera->set_active(false);
camera->set_scene(_scene_parent);
_tag_state_mgr->register_shadow_camera(camera);
_camera_nps.push_back(_scene_parent.attach_new_node(camera));
_cameras[i] = camera;
// Create the display region
PT(DisplayRegion) region = _atlas_graphics_output->make_display_region();
region->set_sort(1000);
region->set_clear_depth_active(true);
region->set_clear_depth(1.0);
region->set_clear_color_active(false);
region->set_camera(_camera_nps[i]);
region->set_active(false);
_display_regions[i] = region;
}
// Create the atlas
_atlas = new ShadowAtlas(_atlas_size);
// Reserve enough space for the updates
_queued_updates.reserve(_max_updates);
}
/**
* @brief Updates the ShadowManager
* @details This updates the ShadowManager, processing all shadow sources which
* need to get updated.
*
* This first collects all sources which require an update, sorts them by priority,
* and then processes the first <max_updates> ShadowSources.
*
* This may not get called before ShadowManager::init, or an assertion will be
* thrown.
*/
void ShadowManager::update() {
nassertv(_atlas != NULL); // ShadowManager::init not called yet
nassertv(_queued_updates.size() <= _max_updates); // Internal error, should not happen
// Disable all cameras and regions which will not be used
for (size_t i = _queued_updates.size(); i < _max_updates; ++i) {
_cameras[i]->set_active(false);
_display_regions[i]->set_active(false);
}
// Iterate over all queued updates
for (size_t i = 0; i < _queued_updates.size(); ++i) {
const ShadowSource* source = _queued_updates[i];
// Enable the camera and display region, so they perform a render
_cameras[i]->set_active(true);
_display_regions[i]->set_active(true);
// Set the view projection matrix
DCAST(MatrixLens, _cameras[i]->get_lens())->set_user_mat(source->get_mvp());
// Optional: Show the camera frustum for debugging
// _cameras[i]->show_frustum();
// Set the correct dimensions on the display region
const LVecBase4f& uv = source->get_uv_region();
_display_regions[i]->set_dimensions(
uv.get_x(), // left
uv.get_x() + uv.get_z(), // right
uv.get_y(), // bottom
uv.get_y() + uv.get_w() // top
);
}
// Clear the update list
_queued_updates.clear();
_queued_updates.reserve(_max_updates);
}
|
/**
*
* RenderPipeline
*
* Copyright (c) 2014-2015 tobspr <[email protected]>
*
* 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 "ShadowManager.h"
NotifyCategoryDef(shadowmanager, "");
/**
* @brief Constructs a new shadow atlas
* @details This constructs a new shadow atlas. There are a set of properties
* which should be set before calling ShadowManager::init, see the set-Methods.
* After all properties are set, ShadowManager::init should get called.
* ShadowManager::update should get called on a per frame basis.
*/
ShadowManager::ShadowManager() {
_max_updates = 10;
_atlas = NULL;
_atlas_size = 4096;
_tag_state_mgr = NULL;
_atlas_graphics_output = NULL;
}
/**
* @brief Destructs the ShadowManager
* @details This destructs the shadow manager, clearing all resources used
*/
ShadowManager::~ShadowManager() {
delete _atlas;
// Todo: Could eventually unregister all shadow cameras. Since the tag state
// manager does this on cleanup already, and we get destructed at the same
// time (if at all), this is not really necessary
}
/**
* @brief Initializes the ShadowManager.
* @details This initializes the ShadowManager. All properties should have
* been set before calling this, otherwise assertions will get triggered.
*
* This setups everything required for rendering shadows, including the
* shadow atlas and the various shadow cameras. After calling this method,
* no properties can be changed anymore.
*/
void ShadowManager::init() {
nassertv(!_scene_parent.is_empty()); // Scene parent not set, call set_scene_parent before init!
nassertv(_tag_state_mgr != NULL); // TagStateManager not set, call set_tag_state_mgr before init!
nassertv(_atlas_graphics_output != NULL); // AtlasGraphicsOutput not set, call set_atlas_graphics_output before init!
_cameras.resize(_max_updates);
_display_regions.resize(_max_updates);
_camera_nps.reserve(_max_updates);
// Create the cameras and regions
for(size_t i = 0; i < _max_updates; ++i) {
// Create the camera
PT(Camera) camera = new Camera("ShadowCam-" + to_string((long long)i));
camera->set_lens(new MatrixLens());
camera->set_active(false);
camera->set_scene(_scene_parent);
_tag_state_mgr->register_shadow_camera(camera);
_camera_nps.push_back(_scene_parent.attach_new_node(camera));
_cameras[i] = camera;
// Create the display region
PT(DisplayRegion) region = _atlas_graphics_output->make_display_region();
region->set_sort(1000);
region->set_clear_depth_active(true);
region->set_clear_depth(1.0);
region->set_clear_color_active(false);
region->set_camera(_camera_nps[i]);
region->set_active(false);
_display_regions[i] = region;
}
// Create the atlas
_atlas = new ShadowAtlas(_atlas_size);
// Reserve enough space for the updates
_queued_updates.reserve(_max_updates);
}
/**
* @brief Updates the ShadowManager
* @details This updates the ShadowManager, processing all shadow sources which
* need to get updated.
*
* This first collects all sources which require an update, sorts them by priority,
* and then processes the first <max_updates> ShadowSources.
*
* This may not get called before ShadowManager::init, or an assertion will be
* thrown.
*/
void ShadowManager::update() {
nassertv(_atlas != NULL); // ShadowManager::init not called yet
nassertv(_queued_updates.size() <= _max_updates); // Internal error, should not happen
// Disable all cameras and regions which will not be used
for (size_t i = _queued_updates.size(); i < _max_updates; ++i) {
_cameras[i]->set_active(false);
_display_regions[i]->set_active(false);
}
// Iterate over all queued updates
for (size_t i = 0; i < _queued_updates.size(); ++i) {
const ShadowSource* source = _queued_updates[i];
// Enable the camera and display region, so they perform a render
_cameras[i]->set_active(true);
_display_regions[i]->set_active(true);
// Set the view projection matrix
DCAST(MatrixLens, _cameras[i]->get_lens())->set_user_mat(source->get_mvp());
// Optional: Show the camera frustum for debugging
// _cameras[i]->show_frustum();
// Set the correct dimensions on the display region
const LVecBase4f& uv = source->get_uv_region();
_display_regions[i]->set_dimensions(
uv.get_x(), // left
uv.get_x() + uv.get_z(), // right
uv.get_y(), // bottom
uv.get_y() + uv.get_w() // top
);
}
// Clear the update list
_queued_updates.clear();
_queued_updates.reserve(_max_updates);
}
|
Fix compilation error in VS2010
|
Fix compilation error in VS2010
|
C++
|
mit
|
croxis/SpaceDrive,croxis/SpaceDrive,croxis/SpaceDrive
|
6e281bc856a61d232cfc4727d8fe13703b0b4e42
|
examples/qt-widgets/main.cpp
|
examples/qt-widgets/main.cpp
|
#include "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
#include "MainWindow.h"
#include <QApplication>
#if defined(Q_OS_IOS)
extern "C" int qtmn(int argc, char** argv) {
#else
int main(int argc, char **argv) {
#endif
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
Fix iOS runtime error
|
Fix iOS runtime error
|
C++
|
bsd-2-clause
|
headupinclouds/hunter,lucmichalski/hunter,zhuhaow/hunter,fire-hunter/hunter,mchiasson/hunter,ulricheck/hunter,headupinclouds/hunter,madmongo1/hunter,madmongo1/hunter,ulricheck/hunter,dvirtz/hunter,NeroBurner/hunter,sumedhghaisas/hunter,ikliashchou/hunter,dvirtz/hunter,isaachier/hunter,ErniBrown/hunter,xsacha/hunter,headupinclouds/hunter,x10mind/hunter,vdsrd/hunter,stohrendorf/hunter,ErniBrown/hunter,ErniBrown/hunter,ikliashchou/hunter,NeroBurner/hunter,RomanYudintsev/hunter,ruslo/hunter,lucmichalski/hunter,stohrendorf/hunter,ingenue/hunter,ruslo/hunter,sumedhghaisas/hunter,ThomasFeher/hunter,ledocc/hunter,zhuhaow/hunter,ingenue/hunter,ErniBrown/hunter,pretyman/hunter,shekharhimanshu/hunter,fire-hunter/hunter,alamaison/hunter,jkhoogland/hunter,xsacha/hunter,madmongo1/hunter,stohrendorf/hunter,alamaison/hunter,tatraian/hunter,shekharhimanshu/hunter,dmpriso/hunter,designerror/hunter,ruslo/hunter,akalsi87/hunter,caseymcc/hunter,caseymcc/hunter,x10mind/hunter,zhuhaow/hunter,vdsrd/hunter,dan-42/hunter,tatraian/hunter,ledocc/hunter,jkhoogland/hunter,tatraian/hunter,isaachier/hunter,xsacha/hunter,designerror/hunter,dvirtz/hunter,pretyman/hunter,sumedhghaisas/hunter,ingenue/hunter,pretyman/hunter,ThomasFeher/hunter,vdsrd/hunter,Knitschi/hunter,ikliashchou/hunter,designerror/hunter,dan-42/hunter,ruslo/hunter,Knitschi/hunter,NeroBurner/hunter,xsacha/hunter,shekharhimanshu/hunter,ingenue/hunter,fwinnen/hunter,isaachier/hunter,akalsi87/hunter,daminetreg/hunter,dmpriso/hunter,jkhoogland/hunter,lucmichalski/hunter,ikliashchou/hunter,ulricheck/hunter,madmongo1/hunter,x10mind/hunter,RomanYudintsev/hunter,akalsi87/hunter,Knitschi/hunter,alamaison/hunter,fwinnen/hunter,NeroBurner/hunter,caseymcc/hunter,fwinnen/hunter,pretyman/hunter,mchiasson/hunter,fire-hunter/hunter,isaachier/hunter,dan-42/hunter,daminetreg/hunter,dmpriso/hunter,mchiasson/hunter,daminetreg/hunter,ThomasFeher/hunter,RomanYudintsev/hunter,ledocc/hunter,mchiasson/hunter,dan-42/hunter
|
23878d3945bcb8c3d78d65e1d1e393c3f975e657
|
base/process_util_linux.cc
|
base/process_util_linux.cc
|
// Copyright (c) 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 "base/process_util.h"
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/platform_thread.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "base/time.h"
namespace {
enum ParsingState {
KEY_NAME,
KEY_VALUE
};
} // namespace
namespace base {
bool LaunchApp(const std::vector<std::string>& argv,
const file_handle_mapping_vector& fds_to_remap,
bool wait, ProcessHandle* process_handle) {
bool retval = true;
char* argv_copy[argv.size() + 1];
for (size_t i = 0; i < argv.size(); i++) {
argv_copy[i] = new char[argv[i].size() + 1];
strcpy(argv_copy[i], argv[i].c_str());
}
argv_copy[argv.size()] = NULL;
// Make sure we don't leak any FDs to the child process by marking all FDs
// as close-on-exec.
int max_files = GetMaxFilesOpenInProcess();
for (int i = STDERR_FILENO + 1; i < max_files; i++) {
int flags = fcntl(i, F_GETFD);
if (flags != -1) {
fcntl(i, F_SETFD, flags | FD_CLOEXEC);
}
}
int pid = fork();
if (pid == 0) {
for (file_handle_mapping_vector::const_iterator it = fds_to_remap.begin();
it != fds_to_remap.end();
++it) {
int src_fd = it->first;
int dest_fd = it->second;
if (src_fd == dest_fd) {
int flags = fcntl(src_fd, F_GETFD);
if (flags != -1) {
fcntl(src_fd, F_SETFD, flags & ~FD_CLOEXEC);
}
} else {
dup2(src_fd, dest_fd);
}
}
execvp(argv_copy[0], argv_copy);
} else if (pid < 0) {
retval = false;
} else {
if (wait)
waitpid(pid, 0, 0);
if (process_handle)
*process_handle = pid;
}
for (size_t i = 0; i < argv.size(); i++)
delete[] argv_copy[i];
return retval;
}
bool LaunchApp(const CommandLine& cl,
bool wait, bool start_hidden,
ProcessHandle* process_handle) {
file_handle_mapping_vector no_files;
return LaunchApp(cl.argv(), no_files, wait, process_handle);
}
bool DidProcessCrash(ProcessHandle handle) {
int status;
if (waitpid(handle, &status, WNOHANG)) {
// I feel like dancing!
return false;
}
if (WIFSIGNALED(status)) {
int signum = WTERMSIG(status);
return (signum == SIGSEGV || signum == SIGILL || signum == SIGABRT ||
signum == SIGFPE);
}
if (WIFEXITED(status)) {
int exitcode = WEXITSTATUS(status);
return (exitcode != 0);
}
return false;
}
NamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,
const ProcessFilter* filter)
:
executable_name_(executable_name),
filter_(filter) {
procfs_dir_ = opendir("/proc");
}
NamedProcessIterator::~NamedProcessIterator() {
if (procfs_dir_) {
closedir(procfs_dir_);
procfs_dir_ = 0;
}
}
const ProcessEntry* NamedProcessIterator::NextProcessEntry() {
bool result = false;
do {
result = CheckForNextProcess();
} while (result && !IncludeEntry());
if (result)
return &entry_;
return NULL;
}
bool NamedProcessIterator::CheckForNextProcess() {
// TODO(port): skip processes owned by different UID
dirent* slot = 0;
const char* openparen;
const char* closeparen;
// Arbitrarily guess that there will never be more than 200 non-process files in /proc.
// (Hardy has 53.)
int skipped = 0;
const int kSkipLimit = 200;
while (skipped < kSkipLimit) {
slot = readdir(procfs_dir_);
// all done looking through /proc?
if (!slot)
return false;
// If not a process, keep looking for one.
bool notprocess = false;
int i;
for (i=0; i < NAME_MAX && slot->d_name[i]; ++i) {
if (!isdigit(slot->d_name[i])) {
notprocess = true;
break;
}
}
if (i == NAME_MAX || notprocess) {
skipped++;
continue;
}
// Read the process's status.
char buf[NAME_MAX + 12];
sprintf(buf, "/proc/%s/stat", slot->d_name);
FILE *fp = fopen(buf, "r");
if (!fp)
return false;
const char* result = fgets(buf, sizeof(buf), fp);
fclose(fp);
if (!result)
return false;
// Parse the status. It is formatted like this:
// %d (%s) %c %d ...
// pid (name) runstate ppid
// To avoid being fooled by names containing a closing paren, scan backwards.
openparen = strchr(buf, '(');
closeparen = strrchr(buf, ')');
if (!openparen || !closeparen)
return false;
char runstate = closeparen[2];
// Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?
// Allowed values: D R S T Z
if (runstate != 'Z')
break;
// Nope, it's a zombie; somebody isn't cleaning up after their children.
// (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)
// There could be a lot of zombies, can't really decrement i here.
}
if (skipped >= kSkipLimit) {
NOTREACHED();
return false;
}
entry_.pid = atoi(slot->d_name);
entry_.ppid = atoi(closeparen+3);
// TODO(port): read pid's commandline's $0, like killall does.
// Using the short name between openparen and closeparen won't work for long names!
int len = closeparen - openparen - 1;
if (len > NAME_MAX)
len = NAME_MAX;
memcpy(entry_.szExeFile, openparen + 1, len);
entry_.szExeFile[len] = 0;
return true;
}
bool NamedProcessIterator::IncludeEntry() {
// TODO(port): make this also work for non-ASCII filenames
bool result = strcmp(WideToASCII(executable_name_).c_str(), entry_.szExeFile) == 0 &&
(!filter_ || filter_->Includes(entry_.pid, entry_.ppid));
return result;
}
int GetProcessCount(const std::wstring& executable_name,
const ProcessFilter* filter) {
int count = 0;
NamedProcessIterator iter(executable_name, filter);
while (iter.NextProcessEntry())
++count;
return count;
}
bool KillProcesses(const std::wstring& executable_name, int exit_code,
const ProcessFilter* filter) {
bool result = true;
const ProcessEntry* entry;
NamedProcessIterator iter(executable_name, filter);
while ((entry = iter.NextProcessEntry()) != NULL)
result = KillProcess((*entry).pid, exit_code, true) && result;
return result;
}
bool WaitForProcessesToExit(const std::wstring& executable_name,
int wait_milliseconds,
const ProcessFilter* filter) {
bool result = false;
// TODO(port): This is inefficient, but works if there are multiple procs.
// TODO(port): use waitpid to avoid leaving zombies around
base::Time end_time = base::Time::Now() + base::TimeDelta::FromMilliseconds(wait_milliseconds);
do {
NamedProcessIterator iter(executable_name, filter);
if (!iter.NextProcessEntry()) {
result = true;
break;
}
PlatformThread::Sleep(100);
} while ((base::Time::Now() - end_time) > base::TimeDelta());
return result;
}
bool CleanupProcesses(const std::wstring& executable_name,
int wait_milliseconds,
int exit_code,
const ProcessFilter* filter) {
bool exited_cleanly =
WaitForProcessesToExit(executable_name, wait_milliseconds,
filter);
if (!exited_cleanly)
KillProcesses(executable_name, exit_code, filter);
return exited_cleanly;
}
///////////////////////////////////////////////////////////////////////////////
//// ProcessMetrics
// To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
// in your kernel configuration.
bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) {
std::string proc_io_contents;
if (!file_util::ReadFileToString(L"/proc/self/io", &proc_io_contents))
return false;
(*io_counters).OtherOperationCount = 0;
(*io_counters).OtherTransferCount = 0;
StringTokenizer tokenizer(proc_io_contents, ": \n");
ParsingState state = KEY_NAME;
std::string last_key_name;
while (tokenizer.GetNext()) {
switch (state) {
case KEY_NAME:
last_key_name = tokenizer.token();
state = KEY_VALUE;
break;
case KEY_VALUE:
DCHECK(!last_key_name.empty());
if (last_key_name == "syscr") {
(*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "syscw") {
(*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "rchar") {
(*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "wchar") {
(*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());
}
state = KEY_NAME;
break;
}
}
return true;
}
} // namespace base
|
// Copyright (c) 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 "base/process_util.h"
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/platform_thread.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "base/time.h"
namespace {
enum ParsingState {
KEY_NAME,
KEY_VALUE
};
} // namespace
namespace base {
bool LaunchApp(const std::vector<std::string>& argv,
const file_handle_mapping_vector& fds_to_remap,
bool wait, ProcessHandle* process_handle) {
bool retval = true;
char* argv_copy[argv.size() + 1];
for (size_t i = 0; i < argv.size(); i++) {
argv_copy[i] = new char[argv[i].size() + 1];
strcpy(argv_copy[i], argv[i].c_str());
}
argv_copy[argv.size()] = NULL;
// Make sure we don't leak any FDs to the child process by marking all FDs
// as close-on-exec.
int max_files = GetMaxFilesOpenInProcess();
for (int i = STDERR_FILENO + 1; i < max_files; i++) {
int flags = fcntl(i, F_GETFD);
if (flags != -1) {
fcntl(i, F_SETFD, flags | FD_CLOEXEC);
}
}
int pid = fork();
if (pid == 0) {
for (file_handle_mapping_vector::const_iterator it = fds_to_remap.begin();
it != fds_to_remap.end();
++it) {
int src_fd = it->first;
int dest_fd = it->second;
if (src_fd == dest_fd) {
int flags = fcntl(src_fd, F_GETFD);
if (flags != -1) {
fcntl(src_fd, F_SETFD, flags & ~FD_CLOEXEC);
}
} else {
dup2(src_fd, dest_fd);
}
}
execvp(argv_copy[0], argv_copy);
} else if (pid < 0) {
retval = false;
} else {
if (wait)
waitpid(pid, 0, 0);
if (process_handle)
*process_handle = pid;
}
for (size_t i = 0; i < argv.size(); i++)
delete[] argv_copy[i];
return retval;
}
bool LaunchApp(const CommandLine& cl,
bool wait, bool start_hidden,
ProcessHandle* process_handle) {
file_handle_mapping_vector no_files;
return LaunchApp(cl.argv(), no_files, wait, process_handle);
}
bool DidProcessCrash(ProcessHandle handle) {
int status;
if (waitpid(handle, &status, WNOHANG)) {
// I feel like dancing!
return false;
}
if (WIFSIGNALED(status)) {
switch(WTERMSIG(status)) {
case SIGSEGV:
case SIGILL:
case SIGABRT:
case SIGFPE:
return true;
default:
return false;
}
}
if (WIFEXITED(status))
return WEXITSTATUS(status) != 0;
return false;
}
NamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,
const ProcessFilter* filter)
: executable_name_(executable_name), filter_(filter) {
procfs_dir_ = opendir("/proc");
}
NamedProcessIterator::~NamedProcessIterator() {
if (procfs_dir_) {
closedir(procfs_dir_);
procfs_dir_ = NULL;
}
}
const ProcessEntry* NamedProcessIterator::NextProcessEntry() {
bool result = false;
do {
result = CheckForNextProcess();
} while (result && !IncludeEntry());
if (result)
return &entry_;
return NULL;
}
bool NamedProcessIterator::CheckForNextProcess() {
// TODO(port): skip processes owned by different UID
dirent* slot = 0;
const char* openparen;
const char* closeparen;
// Arbitrarily guess that there will never be more than 200 non-process
// files in /proc. Hardy has 53.
int skipped = 0;
const int kSkipLimit = 200;
while (skipped < kSkipLimit) {
slot = readdir(procfs_dir_);
// all done looking through /proc?
if (!slot)
return false;
// If not a process, keep looking for one.
bool notprocess = false;
int i;
for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) {
if (!isdigit(slot->d_name[i])) {
notprocess = true;
break;
}
}
if (i == NAME_MAX || notprocess) {
skipped++;
continue;
}
// Read the process's status.
char buf[NAME_MAX + 12];
sprintf(buf, "/proc/%s/stat", slot->d_name);
FILE *fp = fopen(buf, "r");
if (!fp)
return false;
const char* result = fgets(buf, sizeof(buf), fp);
fclose(fp);
if (!result)
return false;
// Parse the status. It is formatted like this:
// %d (%s) %c %d ...
// pid (name) runstate ppid
// To avoid being fooled by names containing a closing paren, scan
// backwards.
openparen = strchr(buf, '(');
closeparen = strrchr(buf, ')');
if (!openparen || !closeparen)
return false;
char runstate = closeparen[2];
// Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?
// Allowed values: D R S T Z
if (runstate != 'Z')
break;
// Nope, it's a zombie; somebody isn't cleaning up after their children.
// (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)
// There could be a lot of zombies, can't really decrement i here.
}
if (skipped >= kSkipLimit) {
NOTREACHED();
return false;
}
entry_.pid = atoi(slot->d_name);
entry_.ppid = atoi(closeparen + 3);
// TODO(port): read pid's commandline's $0, like killall does. Using the
// short name between openparen and closeparen won't work for long names!
int len = closeparen - openparen - 1;
if (len > NAME_MAX)
len = NAME_MAX;
memcpy(entry_.szExeFile, openparen + 1, len);
entry_.szExeFile[len] = 0;
return true;
}
bool NamedProcessIterator::IncludeEntry() {
// TODO(port): make this also work for non-ASCII filenames
if (WideToASCII(executable_name_) != entry_.szExeFile)
return false;
if (!filter_)
return true;
return filter_->Includes(entry_.pid, entry_.ppid);
}
int GetProcessCount(const std::wstring& executable_name,
const ProcessFilter* filter) {
int count = 0;
NamedProcessIterator iter(executable_name, filter);
while (iter.NextProcessEntry())
++count;
return count;
}
bool KillProcesses(const std::wstring& executable_name, int exit_code,
const ProcessFilter* filter) {
bool result = true;
const ProcessEntry* entry;
NamedProcessIterator iter(executable_name, filter);
while ((entry = iter.NextProcessEntry()) != NULL)
result = KillProcess((*entry).pid, exit_code, true) && result;
return result;
}
bool WaitForProcessesToExit(const std::wstring& executable_name,
int wait_milliseconds,
const ProcessFilter* filter) {
bool result = false;
// TODO(port): This is inefficient, but works if there are multiple procs.
// TODO(port): use waitpid to avoid leaving zombies around
base::Time end_time = base::Time::Now() +
base::TimeDelta::FromMilliseconds(wait_milliseconds);
do {
NamedProcessIterator iter(executable_name, filter);
if (!iter.NextProcessEntry()) {
result = true;
break;
}
PlatformThread::Sleep(100);
} while ((base::Time::Now() - end_time) > base::TimeDelta());
return result;
}
bool CleanupProcesses(const std::wstring& executable_name,
int wait_milliseconds,
int exit_code,
const ProcessFilter* filter) {
bool exited_cleanly =
WaitForProcessesToExit(executable_name, wait_milliseconds,
filter);
if (!exited_cleanly)
KillProcesses(executable_name, exit_code, filter);
return exited_cleanly;
}
// To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
// in your kernel configuration.
bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) {
std::string proc_io_contents;
if (!file_util::ReadFileToString(L"/proc/self/io", &proc_io_contents))
return false;
(*io_counters).OtherOperationCount = 0;
(*io_counters).OtherTransferCount = 0;
StringTokenizer tokenizer(proc_io_contents, ": \n");
ParsingState state = KEY_NAME;
std::string last_key_name;
while (tokenizer.GetNext()) {
switch (state) {
case KEY_NAME:
last_key_name = tokenizer.token();
state = KEY_VALUE;
break;
case KEY_VALUE:
DCHECK(!last_key_name.empty());
if (last_key_name == "syscr") {
(*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "syscw") {
(*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "rchar") {
(*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());
} else if (last_key_name == "wchar") {
(*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());
}
state = KEY_NAME;
break;
}
}
return true;
}
} // namespace base
|
Clean up a bunch of style errors in process_util_linux.cc.
|
Clean up a bunch of style errors in process_util_linux.cc.
Review URL: http://codereview.chromium.org/18615
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@8362 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
b8096e69fa183c6facc254b7c7b78cb5099dd770
|
base/test_file_util_mac.cc
|
base/test_file_util_mac.cc
|
// Copyright (c) 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 "base/test_file_util.h"
#include "base/logging.h"
namespace file_util {
bool EvictFileFromSystemCache(const FilePath& file) {
// TODO(port): Implement.
NOTIMPLEMENTED();
return false;
}
} // namespace file_util
|
// Copyright (c) 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 "base/test_file_util.h"
#include "base/logging.h"
namespace file_util {
bool EvictFileFromSystemCache(const FilePath& file) {
// There is no way that we can think of to dump something from the UBC. You
// can add something so when you open it, it doesn't go in, but that won't
// work here.
return true;
}
} // namespace file_util
|
Change the stub for file_util::EvictFileFromSystemCache
|
Change the stub for file_util::EvictFileFromSystemCache
I don't think there is a way to get something out of the UBC once it's in,
so for now I'm just making this api return true so it won't fail unittests.
I have email out to Amit incase he has any ideas.
Review URL: http://codereview.chromium.org/42333
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@11961 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Jonekee/chromium.src,ChromiumWebApps/chromium,keishi/chromium,ltilve/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,keishi/chromium,dushu1203/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,dednal/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,keishi/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,rogerwang/chromium,patrickm/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,robclark/chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,rogerwang/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,keishi/chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,ondra-novak/chromium.src,zcbenz/cefode-chromium,ondra-novak/chromium.src,M4sse/chromium.src,keishi/chromium,rogerwang/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,robclark/chromium,littlstar/chromium.src,jaruba/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,robclark/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,dednal/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,keishi/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,Just-D/chromium-1,ChromiumWebApps/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,keishi/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,mogoweb/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,ltilve/chromium,patrickm/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,ltilve/chromium,littlstar/chromium.src,keishi/chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,rogerwang/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,jaruba/chromium.src,keishi/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,zcbenz/cefode-chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,ltilve/chromium,markYoungH/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,M4sse/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,anirudhSK/chromium,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,M4sse/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Chilledheart/chromium,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,hujiajie/pa-chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,rogerwang/chromium,robclark/chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,rogerwang/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,rogerwang/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src
|
8ca9988afcff3c3490d12bbac50df67f2068854f
|
ChocolateyInstaller/WinMain.cpp
|
ChocolateyInstaller/WinMain.cpp
|
#pragma once
#pragma warning(push)
#pragma warning(disable: 4302 4838)
#include <atlbase.h>
#include <atlfile.h>
#include <atlcoll.h>
#include <atlstr.h>
#include <atlwin.h>
#include <atlapp.h>
#include <atlctrls.h>
#include <atldlgs.h>
#pragma warning(pop)
#include "unzip.h"
#include "resource.h"
#include <shellapi.h>
static HINSTANCE hInstance;
static void ShowFailureDialog(const CString& mainInstruction, const CString& content = _T("")) {
CTaskDialog td;
td.SetMainInstructionText(mainInstruction);
if (content.GetLength() != 0) td.SetContentText(content);
td.SetWindowTitle(_T("Chocolatey Installer"));
td.SetCommonButtons(TDCBF_CLOSE_BUTTON);
td.SetMainIcon(TD_ERROR_ICON);
td.ModifyFlags(0, TDF_ALLOW_DIALOG_CANCELLATION);
td.DoModal(HWND_DESKTOP);
}
static bool ExtractZip(WORD zipResourceId, const CString& directory) {
CResource zipResource;
if (!zipResource.Load(_T("ZIPFILE"), zipResourceId)) return false;
unsigned int dwSize = zipResource.GetSize();
if (dwSize < 0x100) return false;
HZIP zipFile = OpenZip(zipResource.Lock(), dwSize, NULL);
SetUnzipBaseDir(zipFile, directory.GetString());
ZRESULT zr; int index = 0; bool result = true;
do {
ZIPENTRY zipEntry;
zr = GetZipItem(zipFile, index, &zipEntry);
if (zr != ZR_MORE && zr != ZR_OK) {
result = false;
break;
}
CString targetFile = directory + "\\" + zipEntry.name;
DeleteFile(targetFile.GetString());
ZRESULT zr_inner = UnzipItem(zipFile, index, zipEntry.name);
if (zr_inner != ZR_OK) {
// Sometimes ZR_FLATE can be returned incorrectly if the file being
// decompressed is of zero length. (UnzipItem() cannot differentiate
// between a genuine zero-size read and an error condition.) Only fail
// if the size decompressed size is not actually zero.
if (zr_inner == ZR_FLATE && zipEntry.unc_size != 0) {
result = false;
break;
}
}
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
return result;
}
int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE /* hPrevInstance */, LPTSTR cmdLine, INT nCmdShow) {
hInstance = hInst;
TCHAR targetDir[MAX_PATH];
if (!::GetEnvironmentVariable(_T("TEMP"), targetDir, MAX_PATH)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_NOTEMPDIR);
CString content; content.LoadStringW(hInstance, IDS_NOTEMPDIR_DESC);
ShowFailureDialog(mainInstruction, content);
return 1;
}
_tcscat_s(targetDir, _T("\\ChocolateyInstaller"));
if (!::CreateDirectory(targetDir, nullptr) && ::GetLastError() != ERROR_ALREADY_EXISTS) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL);
CString content; content.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL_DESC);
ShowFailureDialog(mainInstruction, content);
return 1;
}
CString outputDir = targetDir;
const WORD IDR_CHOCOLATEY_NUPKG = 1, IDR_WIZARD_ZIP = 2;
if (!ExtractZip(IDR_CHOCOLATEY_NUPKG, outputDir + "\\choco_nupkg")) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return 1;
}
if (!ExtractZip(IDR_WIZARD_ZIP, outputDir)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return 1;
}
CString cmd = outputDir + "\\ChocolateyInstaller.Wizard.exe";
STARTUPINFO si; PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW;
if (!CreateProcess(cmd.GetString(), _T(""), nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXECFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return -1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
return 0;
}
|
#pragma once
#pragma warning(push)
#pragma warning(disable: 4302 4838)
#include <atlbase.h>
#include <atlfile.h>
#include <atlcoll.h>
#include <atlstr.h>
#include <atlwin.h>
#include <atlapp.h>
#include <atlctrls.h>
#include <atldlgs.h>
#pragma warning(pop)
#include "unzip.h"
#include "resource.h"
#include <shellapi.h>
static HINSTANCE hInstance;
static void ShowFailureDialog(const CString& mainInstruction, const CString& content = _T("")) {
CTaskDialog td;
td.SetMainInstructionText(mainInstruction);
if (content.GetLength() != 0) td.SetContentText(content);
td.SetWindowTitle(_T("Chocolatey Installer"));
td.SetCommonButtons(TDCBF_CLOSE_BUTTON);
td.SetMainIcon(TD_ERROR_ICON);
td.ModifyFlags(0, TDF_ALLOW_DIALOG_CANCELLATION);
td.DoModal(HWND_DESKTOP);
}
static bool ExtractZip(WORD zipResourceId, const CString& directory) {
CResource zipResource;
if (!zipResource.Load(_T("ZIPFILE"), zipResourceId)) return false;
unsigned int dwSize = zipResource.GetSize();
if (dwSize < 0x100) return false;
HZIP zipFile = OpenZip(zipResource.Lock(), dwSize, NULL);
SetUnzipBaseDir(zipFile, directory.GetString());
ZRESULT zr; int index = 0; bool result = true;
do {
ZIPENTRY zipEntry;
zr = GetZipItem(zipFile, index, &zipEntry);
if (zr != ZR_MORE && zr != ZR_OK) {
result = false;
break;
}
CString targetFile = directory + "\\" + zipEntry.name;
DeleteFile(targetFile.GetString());
ZRESULT zr_inner = UnzipItem(zipFile, index, zipEntry.name);
if (zr_inner != ZR_OK) {
// Sometimes ZR_FLATE can be returned incorrectly if the file being
// decompressed is of zero length. (UnzipItem() cannot differentiate
// between a genuine zero-size read and an error condition.) Only fail
// if the size decompressed size is not actually zero.
if (zr_inner == ZR_FLATE && zipEntry.unc_size != 0) {
result = false;
break;
}
}
index++;
} while (zr == ZR_MORE || zr == ZR_OK);
CloseZip(zipFile);
zipResource.Release();
return result;
}
int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE /* hPrevInstance */, LPTSTR cmdLine, INT nCmdShow) {
hInstance = hInst;
TCHAR targetDir[MAX_PATH];
if (!::GetEnvironmentVariable(_T("TEMP"), targetDir, MAX_PATH)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_NOTEMPDIR);
CString content; content.LoadStringW(hInstance, IDS_NOTEMPDIR_DESC);
ShowFailureDialog(mainInstruction, content);
return 1;
}
_tcscat_s(targetDir, _T("\\ChocolateyInstaller"));
if (!::CreateDirectory(targetDir, nullptr) && ::GetLastError() != ERROR_ALREADY_EXISTS) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL);
CString content; content.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL_DESC);
ShowFailureDialog(mainInstruction, content);
return 1;
}
CString outputDir = targetDir;
const WORD IDR_CHOCOLATEY_NUPKG = 1, IDR_WIZARD_ZIP = 2;
if (!ExtractZip(IDR_CHOCOLATEY_NUPKG, outputDir + "\\choco_nupkg")) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return 1;
}
if (!ExtractZip(IDR_WIZARD_ZIP, outputDir)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return 1;
}
CString cmd = outputDir + "\\ChocolateyInstaller.Wizard.exe";
STARTUPINFO si; PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(STARTUPINFO);
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW;
if (!CreateProcess(cmd.GetString(), _T(""), nullptr, nullptr, false, 0, nullptr, outputDir.GetString(), &si, &pi)) {
CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXECFAIL);
ShowFailureDialog(mainInstruction, _T(""));
return -1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
return 0;
}
|
Fix crash in CreateProcess()
|
Fix crash in CreateProcess()
|
C++
|
mit
|
wjk/ChocolateyInstaller,wjk/ChocolateyInstaller,wjk/ChocolateyInstaller
|
545f1ffdbedbb31613373f52d74231328308f23e
|
EMCAL/AliEMCALAfterBurnerUF.cxx
|
EMCAL/AliEMCALAfterBurnerUF.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
// After-burner for the EMCAL cluster unfolding algorithm
//
// Input: TObjArray *clusArray -- array of AliAODCaloClusters;
// AliAODCaloCells *cellsEMCAL -- EMCAL cells.
//
// Output is appended to clusArray, the original (unfolded or not) clusters
// are deleted or moved to another position in clusArray.
//
// If you want to use particular geometry, you must initialize it _before_
// creating AliEMCALAfterBurnerUF instance. Add this or similar line to the
// initialization section:
//
// AliEMCALGeometry::GetInstance("EMCAL_FIRSTYEARV1");
//
// gGeoManager must be initialized for this code to work! Do it yourself or
// provide geometry.root file in the current directory so that
// AliEMCALAfterBurnerUF will take it by itself.
// How to use:
//
// // add this lines to the initialization section of your analysis
// AliEMCALAfterBurnerUF *abuf = new AliEMCALAfterBurnerUF();
// TObjArray *clusArray = new TObjArray(100);
//
//
// AliAODEvent *event = (AliAODEvent*) InputEvent();
// AliAODCaloCells *cellsEMCAL = event->GetEMCALCells();
//
// for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++)
// {
// AliAODCaloCluster *clus = event->GetCaloCluster(i);
//
// clusArray->Add(clus->Clone()); // NOTE _CLONE_ in this line
// }
//
// abuf->UnfoldClusters(clusArray, cellsEMCAL);
//
// // do an analysis with clusArray
// // ....
//
// // prevent memory leak
// clusArray->Delete();
//
//----
// Author: Olga Driga (SUBATECH)
// --- ROOT system ---
#include <TObjArray.h>
#include <TClonesArray.h>
#include <TGeoManager.h>
// --- Standard library --
// --- AliRoot header files ---
#include <AliEMCALAfterBurnerUF.h>
#include <AliEMCALGeometry.h>
#include <AliEMCALUnfolding.h>
#include <AliAODCaloCluster.h>
#include <AliAODCaloCells.h>
#include <AliEMCALRecPoint.h>
#include <AliEMCALDigit.h>
ClassImp(AliEMCALAfterBurnerUF)
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF():
fGeom(NULL),
fLogWeight(4.5), // correct?
fECALocMaxCut(0.03), // value suggested by Adam
fRecPoints(NULL),
fDigitsArr(NULL),
fClusterUnfolding(NULL)
{
// Use this constructor, if unsure
Init();
}
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF(Float_t logWeight, Float_t ECALocMaxCut):
fGeom(NULL),
fLogWeight(logWeight),
fECALocMaxCut(ECALocMaxCut),
fRecPoints(NULL),
fDigitsArr(NULL),
fClusterUnfolding(NULL)
{
// This constructor allows to set parameters
// Recommended values:
// Float_t logWeight = 4.5, ECALocMaxCut = 0.03
Init();
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::Init()
{
// After-burner initialization
// Imports geometry.root (if required), creates unfolding class instance
//
// TODO: geometry.root does not allow to use the method AliEMCALRecPoint::EvalAll();
// for this to work, the OCDB geometry must be imported instead
if (!gGeoManager)
TGeoManager::Import("geometry.root");
// required for global cluster position recalculation
if (!gGeoManager)
Fatal("AliEMCALAfterBurnerUF::Init", "failed to import geometry.root");
// initialize geometry, if not yet initialized
if (!AliEMCALGeometry::GetInstance()) {
Warning("AliEMCALAfterBurnerUF::Init", "AliEMCALGeometry is not yet initialized. Initializing with EMCAL_COMPLETE");
AliEMCALGeometry::GetInstance("EMCAL_COMPLETE");
}
// AliEMCALRecPoint is using exactly this call
fGeom = AliEMCALGeometry::GetInstance();
if (!fGeom)
Fatal("AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF", "could not get EMCAL geometry");
fClusterUnfolding = new AliEMCALUnfolding(fGeom);
fClusterUnfolding->SetECALocalMaxCut(fECALocMaxCut);
// clusters --> recPoints, cells --> digits and back ;)
fRecPoints = new TObjArray(100);
fDigitsArr = new TClonesArray("AliEMCALDigit",1152);
}
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::~AliEMCALAfterBurnerUF()
{
if (fClusterUnfolding) delete fClusterUnfolding;
if (fRecPoints) delete fRecPoints;
if (fDigitsArr) delete fDigitsArr;
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::RecPoints2Clusters(TObjArray *clusArray)
{
// Restore clusters from recPoints
// Cluster energy, global position, cells and their amplitude fractions are restored
//
// TODO: restore time and other parameters
for(Int_t i = 0; i < fRecPoints->GetEntriesFast(); i++)
{
AliEMCALRecPoint *recPoint = (AliEMCALRecPoint*) fRecPoints->At(i);
Int_t ncells = recPoint->GetMultiplicity();
Int_t ncells_true = 0;
// cells and their amplitude fractions
UShort_t absIds[ncells]; // NOTE: unfolding must not give recPoints with no cells!
Double32_t ratios[ncells];
for (Int_t c = 0; c < ncells; c++) {
AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->At(recPoint->GetDigitsList()[c]);
absIds[ncells_true] = digit->GetId();
ratios[ncells_true] = recPoint->GetEnergiesList()[c]/digit->GetAmplitude();
if (ratios[ncells_true] > 0.001) ncells_true++;
}
if (ncells_true < 1) {
Warning("AliEMCALAfterBurnerUF::RecPoints2Clusters", "skipping cluster with no cells");
continue;
}
TVector3 gpos;
Float_t g[3];
// calculate new cluster position
recPoint->EvalGlobalPosition(fLogWeight, fDigitsArr);
recPoint->GetGlobalPosition(gpos);
gpos.GetXYZ(g);
// create a new cluster
AliAODCaloCluster *clus = new AliAODCaloCluster();
clus->SetType(AliAODCaloCluster::kEMCALClusterv1);
clus->SetE(recPoint->GetEnergy());
clus->SetPosition(g);
clus->SetNCells(ncells_true);
clus->SetCellsAbsId(absIds);
clus->SetCellsAmplitudeFraction(ratios);
// TODO: time not stored
// TODO: some other properties not stored
clusArray->Add(clus);
} // recPoints loop
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::UnfoldClusters(TObjArray *clusArray, AliAODCaloCells *cellsEMCAL)
{
// Unfolds clusters.
//
// Input: TObjArray of clusters, EMCAL cells.
// Output is added to the same array, original clusters are _deleted_ or moved to another position.
Int_t ndigits = 0;
Int_t nclus = clusArray->GetEntriesFast();
/* Fill recPoints with digits
*/
for (Int_t i = 0; i < nclus; i++)
{
AliAODCaloCluster *clus = (AliAODCaloCluster*) clusArray->At(i);
if (!clus->IsEMCAL()) continue;
// new recPoint
AliEMCALRecPoint *recPoint = new AliEMCALRecPoint("");
recPoint->SetClusterType(AliAODCaloCluster::kEMCALClusterv1);
fRecPoints->Add(recPoint);
// fill digits
for (Int_t c = 0; c < clus->GetNCells(); c++) {
Int_t absId = clus->GetCellAbsId(c);
Double_t amp = cellsEMCAL->GetCellAmplitude(absId);
Double_t time = cellsEMCAL->GetCellTime(absId);
// NOTE: it is easy to include cells recalibration here:
// amp *= factor;
AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(ndigits);
digit->SetId(absId);
digit->SetAmplitude(amp);
digit->SetTime(time);
digit->SetTimeR(time);
digit->SetIndexInList(ndigits);
recPoint->AddDigit(*digit, amp, kFALSE);
ndigits++;
}
// this cluster will be substituted with the result of unfolding
clusArray->RemoveAt(i);
delete clus;
} // cluster loop
/* Peform unfolding
*/
fClusterUnfolding->SetInput(fRecPoints->GetEntriesFast(), fRecPoints, fDigitsArr);
fClusterUnfolding->MakeUnfolding();
/* Restore clusters from recPoints.
*/
RecPoints2Clusters(clusArray);
// clean up
fRecPoints->Delete();
fDigitsArr->Delete();
clusArray->Compress();
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* 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. *
**************************************************************************/
// After-burner for the EMCAL cluster unfolding algorithm
//
// Input: TObjArray *clusArray -- array of AliAODCaloClusters;
// AliAODCaloCells *cellsEMCAL -- EMCAL cells.
//
// Output is appended to clusArray, the original (unfolded or not) clusters
// are deleted or moved to another position in clusArray.
//
// If you want to use particular geometry, you must initialize it _before_
// creating AliEMCALAfterBurnerUF instance. Add this or similar line to the
// initialization section:
//
// AliEMCALGeometry::GetInstance("EMCAL_FIRSTYEARV1");
//
// gGeoManager must be initialized for this code to work! Do it yourself or
// provide geometry.root file in the current directory so that
// AliEMCALAfterBurnerUF will take it by itself.
// How to use:
//
// // add this lines to the initialization section of your analysis
// AliEMCALAfterBurnerUF *abuf = new AliEMCALAfterBurnerUF();
// TObjArray *clusArray = new TObjArray(100);
//
//
// AliAODEvent *event = (AliAODEvent*) InputEvent();
// AliAODCaloCells *cellsEMCAL = event->GetEMCALCells();
//
// for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++)
// {
// AliAODCaloCluster *clus = event->GetCaloCluster(i);
//
// clusArray->Add(clus->Clone()); // NOTE _CLONE_ in this line
// }
//
// abuf->UnfoldClusters(clusArray, cellsEMCAL);
//
// // do an analysis with clusArray
// // ....
//
// // prevent memory leak
// clusArray->Delete();
//
//----
// Author: Olga Driga (SUBATECH)
// --- ROOT system ---
#include <TObjArray.h>
#include <TClonesArray.h>
#include <TGeoManager.h>
// --- Standard library --
// --- AliRoot header files ---
#include <AliEMCALAfterBurnerUF.h>
#include <AliEMCALGeometry.h>
#include <AliEMCALUnfolding.h>
#include <AliAODCaloCluster.h>
#include <AliAODCaloCells.h>
#include <AliEMCALRecPoint.h>
#include <AliEMCALDigit.h>
ClassImp(AliEMCALAfterBurnerUF)
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF():
fGeom(NULL),
fLogWeight(4.5), // correct?
fECALocMaxCut(0.03), // value suggested by Adam
fRecPoints(NULL),
fDigitsArr(NULL),
fClusterUnfolding(NULL)
{
// Use this constructor, if unsure
Init();
}
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF(Float_t logWeight, Float_t ECALocMaxCut):
fGeom(NULL),
fLogWeight(logWeight),
fECALocMaxCut(ECALocMaxCut),
fRecPoints(NULL),
fDigitsArr(NULL),
fClusterUnfolding(NULL)
{
// This constructor allows to set parameters
// Recommended values:
// Float_t logWeight = 4.5, ECALocMaxCut = 0.03
Init();
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::Init()
{
// After-burner initialization
// Imports geometry.root (if required), creates unfolding class instance
//
// TODO: geometry.root does not allow to use the method AliEMCALRecPoint::EvalAll();
// for this to work, the OCDB geometry must be imported instead
if (!gGeoManager)
Warning("AliEMCALAfterBurnerUF::Init","GeoManager not found, please import the geometry.root file or pass to the geometry the misalignment matrices");
// TGeoManager::Import("geometry.root");
// required for global cluster position recalculation
if (!gGeoManager)
Fatal("AliEMCALAfterBurnerUF::Init", "failed to import geometry.root");
// initialize geometry, if not yet initialized
if (!AliEMCALGeometry::GetInstance()) {
Warning("AliEMCALAfterBurnerUF::Init", "AliEMCALGeometry is not yet initialized. Initializing with EMCAL_FIRSTYEARV1");
AliEMCALGeometry::GetInstance("EMCAL_FIRSTYEARV1");
}
// AliEMCALRecPoint is using exactly this call
fGeom = AliEMCALGeometry::GetInstance();
if (!fGeom)
Fatal("AliEMCALAfterBurnerUF::AliEMCALAfterBurnerUF", "could not get EMCAL geometry");
fClusterUnfolding = new AliEMCALUnfolding(fGeom);
fClusterUnfolding->SetECALocalMaxCut(fECALocMaxCut);
// clusters --> recPoints, cells --> digits and back ;)
fRecPoints = new TObjArray(100);
fDigitsArr = new TClonesArray("AliEMCALDigit",1152);
}
//------------------------------------------------------------------------
AliEMCALAfterBurnerUF::~AliEMCALAfterBurnerUF()
{
if (fClusterUnfolding) delete fClusterUnfolding;
if (fRecPoints) delete fRecPoints;
if (fDigitsArr) {
fDigitsArr->Clear("C");
delete fDigitsArr;
}
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::RecPoints2Clusters(TObjArray *clusArray)
{
// Restore clusters from recPoints
// Cluster energy, global position, cells and their amplitude fractions are restored
//
// TODO: restore time and other parameters
for(Int_t i = 0; i < fRecPoints->GetEntriesFast(); i++)
{
AliEMCALRecPoint *recPoint = (AliEMCALRecPoint*) fRecPoints->At(i);
Int_t ncells = recPoint->GetMultiplicity();
Int_t ncells_true = 0;
// cells and their amplitude fractions
UShort_t absIds[ncells]; // NOTE: unfolding must not give recPoints with no cells!
Double32_t ratios[ncells];
for (Int_t c = 0; c < ncells; c++) {
AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->At(recPoint->GetDigitsList()[c]);
absIds[ncells_true] = digit->GetId();
ratios[ncells_true] = recPoint->GetEnergiesList()[c]/digit->GetAmplitude();
if (ratios[ncells_true] > 0.001) ncells_true++;
}
if (ncells_true < 1) {
Warning("AliEMCALAfterBurnerUF::RecPoints2Clusters", "skipping cluster with no cells");
continue;
}
TVector3 gpos;
Float_t g[3];
// calculate new cluster position
recPoint->EvalGlobalPosition(fLogWeight, fDigitsArr);
recPoint->GetGlobalPosition(gpos);
gpos.GetXYZ(g);
// create a new cluster
AliAODCaloCluster *clus = new AliAODCaloCluster();
clus->SetType(AliAODCaloCluster::kEMCALClusterv1);
clus->SetE(recPoint->GetEnergy());
clus->SetPosition(g);
clus->SetNCells(ncells_true);
clus->SetCellsAbsId(absIds);
clus->SetCellsAmplitudeFraction(ratios);
// TODO: time not stored
// TODO: some other properties not stored
clusArray->Add(clus);
} // recPoints loop
}
//------------------------------------------------------------------------
void AliEMCALAfterBurnerUF::UnfoldClusters(TObjArray *clusArray, AliAODCaloCells *cellsEMCAL)
{
// Unfolds clusters.
//
// Input: TObjArray of clusters, EMCAL cells.
// Output is added to the same array, original clusters are _deleted_ or moved to another position.
Int_t ndigits = 0;
Int_t nclus = clusArray->GetEntriesFast();
/* Fill recPoints with digits
*/
for (Int_t i = 0; i < nclus; i++)
{
AliAODCaloCluster *clus = (AliAODCaloCluster*) clusArray->At(i);
if (!clus->IsEMCAL()) continue;
// new recPoint
AliEMCALRecPoint *recPoint = new AliEMCALRecPoint("");
recPoint->SetClusterType(AliAODCaloCluster::kEMCALClusterv1);
fRecPoints->Add(recPoint);
// fill digits
for (Int_t c = 0; c < clus->GetNCells(); c++) {
Int_t absId = clus->GetCellAbsId(c);
Double_t amp = cellsEMCAL->GetCellAmplitude(absId);
Double_t time = cellsEMCAL->GetCellTime(absId);
// NOTE: it is easy to include cells recalibration here:
// amp *= factor;
AliEMCALDigit *digit = (AliEMCALDigit*) fDigitsArr->New(ndigits);
digit->SetId(absId);
digit->SetAmplitude(amp);
digit->SetTime(time);
digit->SetTimeR(time);
digit->SetIndexInList(ndigits);
recPoint->AddDigit(*digit, amp, kFALSE);
ndigits++;
}
// this cluster will be substituted with the result of unfolding
clusArray->RemoveAt(i);
delete clus;
} // cluster loop
/* Peform unfolding
*/
fClusterUnfolding->SetInput(fRecPoints->GetEntriesFast(), fRecPoints, fDigitsArr);
fClusterUnfolding->MakeUnfolding();
/* Restore clusters from recPoints.
*/
RecPoints2Clusters(clusArray);
// clean up
fRecPoints->Clear();
fDigitsArr->Clear("C");
clusArray->Compress();
}
|
change delete of arrays per event by clear, set default geometry to FIRSTYEARV1
|
change delete of arrays per event by clear, set default geometry to FIRSTYEARV1
|
C++
|
bsd-3-clause
|
jgrosseo/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,alisw/AliRoot,coppedis/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot
|
0bfab77f7627359def5f4c7982367fe8e119cd88
|
Graphics/vtkElevationFilter.cxx
|
Graphics/vtkElevationFilter.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkElevationFilter.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 "vtkElevationFilter.h"
#include "vtkCellData.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkElevationFilter, "1.57");
vtkStandardNewMacro(vtkElevationFilter);
// Construct object with LowPoint=(0,0,0) and HighPoint=(0,0,1). Scalar
// range is (0,1).
vtkElevationFilter::vtkElevationFilter()
{
this->LowPoint[0] = 0.0;
this->LowPoint[1] = 0.0;
this->LowPoint[2] = 0.0;
this->HighPoint[0] = 0.0;
this->HighPoint[1] = 0.0;
this->HighPoint[2] = 1.0;
this->ScalarRange[0] = 0.0;
this->ScalarRange[1] = 1.0;
}
//
// Convert position along ray into scalar value. Example use includes
// coloring terrain by elevation.
//
int vtkElevationFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType numPts, i;
int j;
vtkFloatArray *newScalars;
double l, x[3], s, v[3];
double diffVector[3], diffScalar;
int abort=0;
// Initialize
//
vtkDebugMacro(<<"Generating elevation scalars!");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
if ( ((numPts=input->GetNumberOfPoints()) < 1) )
{
vtkDebugMacro(<< "No input!");
return 1;
}
// Allocate
//
newScalars = vtkFloatArray::New();
newScalars->SetNumberOfTuples(numPts);
// Set up 1D parametric system
//
for (i=0; i<3; i++)
{
diffVector[i] = this->HighPoint[i] - this->LowPoint[i];
}
if ( (l = vtkMath::Dot(diffVector,diffVector)) == 0.0)
{
vtkErrorMacro(<< this << ": Bad vector, using (0,0,1)\n");
diffVector[0] = diffVector[1] = 0.0; diffVector[2] = 1.0;
l = 1.0;
}
// Compute parametric coordinate and map into scalar range
//
int tenth = numPts/10 + 1;
diffScalar = this->ScalarRange[1] - this->ScalarRange[0];
for (i=0; i<numPts && !abort; i++)
{
if ( ! (i % tenth) )
{
this->UpdateProgress ((double)i/numPts);
abort = this->GetAbortExecute();
}
input->GetPoint(i, x);
for (j=0; j<3; j++)
{
v[j] = x[j] - this->LowPoint[j];
}
s = vtkMath::Dot(v,diffVector) / l;
s = (s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s);
newScalars->SetValue(i,this->ScalarRange[0]+s*diffScalar);
}
// Update self
//
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
newScalars->SetName("Elevation");
output->GetPointData()->AddArray(newScalars);
output->GetPointData()->SetActiveScalars("Elevation");
newScalars->Delete();
return 1;
}
void vtkElevationFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Low Point: (" << this->LowPoint[0] << ", "
<< this->LowPoint[1] << ", "
<< this->LowPoint[2] << ")\n";
os << indent << "High Point: (" << this->HighPoint[0] << ", "
<< this->HighPoint[1] << ", "
<< this->HighPoint[2] << ")\n";
os << indent << "Scalar Range: (" << this->ScalarRange[0] << ", "
<< this->ScalarRange[1] << ")\n";
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkElevationFilter.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 "vtkElevationFilter.h"
#include "vtkCellData.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
vtkCxxRevisionMacro(vtkElevationFilter, "1.57.10.1");
vtkStandardNewMacro(vtkElevationFilter);
//----------------------------------------------------------------------------
vtkElevationFilter::vtkElevationFilter()
{
this->LowPoint[0] = 0.0;
this->LowPoint[1] = 0.0;
this->LowPoint[2] = 0.0;
this->HighPoint[0] = 0.0;
this->HighPoint[1] = 0.0;
this->HighPoint[2] = 1.0;
this->ScalarRange[0] = 0.0;
this->ScalarRange[1] = 1.0;
}
//----------------------------------------------------------------------------
vtkElevationFilter::~vtkElevationFilter()
{
}
//----------------------------------------------------------------------------
void vtkElevationFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Low Point: ("
<< this->LowPoint[0] << ", "
<< this->LowPoint[1] << ", "
<< this->LowPoint[2] << ")\n";
os << indent << "High Point: ("
<< this->HighPoint[0] << ", "
<< this->HighPoint[1] << ", "
<< this->HighPoint[2] << ")\n";
os << indent << "Scalar Range: ("
<< this->ScalarRange[0] << ", "
<< this->ScalarRange[1] << ")\n";
}
//----------------------------------------------------------------------------
int vtkElevationFilter::RequestData(vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// Get the input and output data objects.
vtkDataSet* input = vtkDataSet::GetData(inputVector[0]);
vtkDataSet* output = vtkDataSet::GetData(outputVector);
// Check the size of the input.
vtkIdType numPts = input->GetNumberOfPoints();
if(numPts < 1)
{
vtkDebugMacro("No input!");
return 1;
}
// Allocate space for the elevation scalar data.
vtkSmartPointer<vtkFloatArray> newScalars =
vtkSmartPointer<vtkFloatArray>::New();
newScalars->SetNumberOfTuples(numPts);
// Set up 1D parametric system and make sure it is valid.
double diffVector[3] =
{ this->HighPoint[0] - this->LowPoint[0],
this->HighPoint[1] - this->LowPoint[1],
this->HighPoint[2] - this->LowPoint[2] };
double length2 = vtkMath::Dot(diffVector, diffVector);
if(length2 <= 0)
{
vtkErrorMacro("Bad vector, using (0,0,1).");
diffVector[0] = 0;
diffVector[1] = 0;
diffVector[2] = 1;
length2 = 1.0;
}
// Support progress and abort.
vtkIdType tenth = (numPts >= 10? numPts/10 : 1);
double numPtsInv = 1.0/numPts;
int abort = 0;
// Compute parametric coordinate and map into scalar range.
double diffScalar = this->ScalarRange[1] - this->ScalarRange[0];
vtkDebugMacro("Generating elevation scalars!");
for(vtkIdType i=0; i < numPts && !abort; ++i)
{
// Periodically update progress and check for an abort request.
if(i % tenth == 0)
{
this->UpdateProgress((i+1)*numPtsInv);
abort = this->GetAbortExecute();
}
// Project this input point into the 1D system.
double x[3];
input->GetPoint(i, x);
double v[3] = { x[0] - this->LowPoint[0],
x[1] - this->LowPoint[1],
x[2] - this->LowPoint[2] };
double s = vtkMath::Dot(v, diffVector) / length2;
s = (s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s);
// Store the resulting scalar value.
newScalars->SetValue(i, this->ScalarRange[0] + s*diffScalar);
}
// Copy all the input geometry and data to the output.
output->CopyStructure(input);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
// Add the new scalars array to the output.
newScalars->SetName("Elevation");
output->GetPointData()->AddArray(newScalars);
output->GetPointData()->SetActiveScalars("Elevation");
return 1;
}
|
Merge changes from main tree into VTK-5-0 branch. (cvs -q up -j1.57 -j1.58 Graphics/vtkElevationFilter.cxx)
|
ENH: Merge changes from main tree into VTK-5-0 branch. (cvs -q up -j1.57 -j1.58 Graphics/vtkElevationFilter.cxx)
|
C++
|
bsd-3-clause
|
johnkit/vtk-dev,msmolens/VTK,demarle/VTK,biddisco/VTK,sumedhasingla/VTK,arnaudgelas/VTK,SimVascular/VTK,cjh1/VTK,mspark93/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,collects/VTK,candy7393/VTK,mspark93/VTK,daviddoria/PointGraphsPhase1,daviddoria/PointGraphsPhase1,Wuteyan/VTK,sankhesh/VTK,arnaudgelas/VTK,keithroe/vtkoptix,spthaolt/VTK,jmerkow/VTK,msmolens/VTK,aashish24/VTK-old,msmolens/VTK,ashray/VTK-EVM,mspark93/VTK,keithroe/vtkoptix,keithroe/vtkoptix,keithroe/vtkoptix,johnkit/vtk-dev,collects/VTK,hendradarwin/VTK,sgh/vtk,aashish24/VTK-old,naucoin/VTKSlicerWidgets,gram526/VTK,ashray/VTK-EVM,sankhesh/VTK,candy7393/VTK,biddisco/VTK,mspark93/VTK,sgh/vtk,ashray/VTK-EVM,biddisco/VTK,aashish24/VTK-old,jmerkow/VTK,Wuteyan/VTK,cjh1/VTK,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,candy7393/VTK,msmolens/VTK,sankhesh/VTK,naucoin/VTKSlicerWidgets,aashish24/VTK-old,SimVascular/VTK,gram526/VTK,sumedhasingla/VTK,johnkit/vtk-dev,jmerkow/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,mspark93/VTK,SimVascular/VTK,gram526/VTK,spthaolt/VTK,msmolens/VTK,demarle/VTK,collects/VTK,candy7393/VTK,candy7393/VTK,berendkleinhaneveld/VTK,arnaudgelas/VTK,Wuteyan/VTK,daviddoria/PointGraphsPhase1,demarle/VTK,spthaolt/VTK,jmerkow/VTK,keithroe/vtkoptix,gram526/VTK,collects/VTK,candy7393/VTK,sankhesh/VTK,demarle/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,naucoin/VTKSlicerWidgets,mspark93/VTK,gram526/VTK,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,cjh1/VTK,demarle/VTK,johnkit/vtk-dev,spthaolt/VTK,jmerkow/VTK,jmerkow/VTK,aashish24/VTK-old,daviddoria/PointGraphsPhase1,Wuteyan/VTK,gram526/VTK,sumedhasingla/VTK,gram526/VTK,demarle/VTK,jmerkow/VTK,hendradarwin/VTK,candy7393/VTK,cjh1/VTK,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,cjh1/VTK,hendradarwin/VTK,arnaudgelas/VTK,keithroe/vtkoptix,spthaolt/VTK,hendradarwin/VTK,biddisco/VTK,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,ashray/VTK-EVM,aashish24/VTK-old,collects/VTK,ashray/VTK-EVM,spthaolt/VTK,biddisco/VTK,Wuteyan/VTK,sumedhasingla/VTK,SimVascular/VTK,Wuteyan/VTK,jmerkow/VTK,ashray/VTK-EVM,sumedhasingla/VTK,hendradarwin/VTK,msmolens/VTK,gram526/VTK,johnkit/vtk-dev,berendkleinhaneveld/VTK,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,SimVascular/VTK,msmolens/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,sumedhasingla/VTK,sgh/vtk,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,candy7393/VTK,sgh/vtk,daviddoria/PointGraphsPhase1,collects/VTK,demarle/VTK,spthaolt/VTK,johnkit/vtk-dev,SimVascular/VTK,sgh/vtk,msmolens/VTK,biddisco/VTK,cjh1/VTK,naucoin/VTKSlicerWidgets,naucoin/VTKSlicerWidgets,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,sgh/vtk,biddisco/VTK,keithroe/vtkoptix,SimVascular/VTK,ashray/VTK-EVM,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,keithroe/vtkoptix
|
b5afc1a0d98837fceba336649c4ee7fd2707e6ed
|
Iceberg3D/source/IntroState.cpp
|
Iceberg3D/source/IntroState.cpp
|
#include "IntroState.h"
#include "GlobalIncludes.h"
using namespace std;
using namespace glm;
void IntroState::pause(){}
void IntroState::resume(){}
void IntroState::finalize(){}
void IntroState::handle_events(){}
void IntroState::initialize()
{
// Initialize resources
model = make_unique<Model>("assets/deadpool/dead 123456.obj");
modelProgram = make_shared<ShaderProgram>();
modelProgram->create_program();
modelProgram->add_shader_from_file("shaders/modelVert.glsl", GL_VERTEX_SHADER);
modelProgram->add_shader_from_file("shaders/modelFrag.glsl", GL_FRAGMENT_SHADER);
modelProgram->link_program();
camera = make_unique<Camera>(game_, vec3(0.0, 25.0, -70.0), glm::vec3(0), 100.0);
camera->enable_input();
SkyboxParameters snowySkybox;
snowySkybox.right = "Assets/ame_powder/powderpeak_rt.tga";
snowySkybox.left = "Assets/ame_powder/powderpeak_lf.tga";
snowySkybox.top = "Assets/ame_powder/powderpeak_up.tga";
snowySkybox.bottom = "Assets/ame_powder/powderpeak_dn.tga";
snowySkybox.front = "Assets/ame_powder/powderpeak_ft.tga";
snowySkybox.back = "Assets/ame_powder/powderpeak_bk.tga";
skybox = make_unique<Skybox>(snowySkybox);
angle = 0.0f;
}
void IntroState::update()
{
angle += game_->delta_time() * float(pi<float>());
camera->update(game_);
}
void IntroState::draw()
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
modelProgram->use();
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
// TODO: Instanced Rendering
model->transform_manager()->translate(glm::mat4(1.0f), vec3(2.0f * i, 2.0f * j, 0.0f));
model->transform_manager()->rotate(angle, vec3(0.0f, 1.0f, 0.0f));
model->transform_manager()->scale(vec3(0.02f, 0.02f, 0.02f));
mat4 mvp = camera->make_mvp(model->transform_manager()->model_matrix());
modelProgram->set_uniform("mvpMatrix", &mvp);
model->draw(modelProgram.get(), camera.get());
}
}
glDisable(GL_CULL_FACE);
skybox->draw(camera.get());
}
|
#include "IntroState.h"
#include "GlobalIncludes.h"
using namespace std;
using namespace glm;
void IntroState::pause(){}
void IntroState::resume(){}
void IntroState::finalize(){}
void IntroState::handle_events(){}
void IntroState::initialize()
{
// Initialize resources
model = make_unique<Model>("assets/deadpool/dead 123456.obj");
modelProgram = make_shared<ShaderProgram>();
modelProgram->create_program();
modelProgram->add_shader_from_file("shaders/modelVert.glsl", GL_VERTEX_SHADER);
modelProgram->add_shader_from_file("shaders/modelFrag.glsl", GL_FRAGMENT_SHADER);
modelProgram->link_program();
camera = make_unique<Camera>(game_, vec3(10.0, 12.0, 30.0), glm::vec3(0), 100.0);
camera->enable_input();
SkyboxParameters snowySkybox;
snowySkybox.right = "Assets/ame_powder/powderpeak_rt.tga";
snowySkybox.left = "Assets/ame_powder/powderpeak_lf.tga";
snowySkybox.top = "Assets/ame_powder/powderpeak_up.tga";
snowySkybox.bottom = "Assets/ame_powder/powderpeak_dn.tga";
snowySkybox.front = "Assets/ame_powder/powderpeak_ft.tga";
snowySkybox.back = "Assets/ame_powder/powderpeak_bk.tga";
skybox = make_unique<Skybox>(snowySkybox);
angle = 0.0f;
}
void IntroState::update()
{
angle += game_->delta_time() * float(pi<float>());
camera->update(game_);
}
void IntroState::draw()
{
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
modelProgram->use();
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
// TODO: Instanced Rendering
model->transform_manager()->translate(glm::mat4(1.0f), vec3(8.0f * i, 8.0f * j, 0.0f));
model->transform_manager()->rotate(angle, vec3(0.0f, 1.0f, 0.0f));
model->transform_manager()->scale(vec3(0.02f, 0.02f, 0.02f));
mat4 mvp = camera->make_mvp(model->transform_manager()->model_matrix());
modelProgram->set_uniform("mvpMatrix", &mvp);
model->draw(modelProgram.get(), camera.get());
}
}
glDisable(GL_CULL_FACE);
skybox->draw(camera.get());
}
|
Tweak demo.
|
Tweak demo.
|
C++
|
mit
|
matthewjberger/Iceberg3D,matthewjberger/Iceberg3D
|
b3d0e060f4af41efb5af4363e7ee60b0c4f215fa
|
mcrouter/tools/mcpiper/MessagePrinter.cpp
|
mcrouter/tools/mcpiper/MessagePrinter.cpp
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "MessagePrinter.h"
namespace facebook { namespace memcache {
namespace {
bool matchIPAddress(const folly::IPAddress& expectedIp,
const folly::SocketAddress& address) {
return !address.empty() && expectedIp == address.getIPAddress();
}
bool matchPort(uint16_t expectedPort, const folly::SocketAddress& address) {
return !address.empty() && expectedPort == address.getPort();
}
std::string describeAddress(const folly::SocketAddress& address) {
auto res = address.describe();
if (address.getFamily() == AF_UNIX) {
// Check if the path was truncated.
if (res.size() >=
MessageHeader::kAddressMaxSize - kUnixSocketPrefix.size() - 1) {
return res + "...";
}
}
return res;
}
} // anonymous namespace
MessagePrinter::MessagePrinter(Options options,
Filter filter,
std::unique_ptr<ValueFormatter> valueFormatter)
: options_(std::move(options)),
filter_(std::move(filter)),
valueFormatter_(std::move(valueFormatter)) {
if (options_.disableColor) {
targetOut_.setColorOutput(false);
}
}
bool MessagePrinter::matchAddress(const folly::SocketAddress& from,
const folly::SocketAddress& to) const {
// Initial filters
if (!filter_.host.empty() &&
!matchIPAddress(filter_.host, from) &&
!matchIPAddress(filter_.host, to)) {
return false;
}
if (filter_.port != 0 &&
!matchPort(filter_.port, from) &&
!matchPort(filter_.port, to)) {
return false;
}
return true;
}
void MessagePrinter::countStats() {
++printedMessages_;
if (options_.maxMessages > 0 && printedMessages_ >= options_.maxMessages) {
assert(options_.stopRunningFn);
options_.stopRunningFn(*this);
}
if (options_.numAfterMatch > 0) {
--afterMatchCount_;
}
}
void MessagePrinter::printRawMessage(const struct iovec* iovsBegin,
size_t iovsCount) {
if (iovsBegin == nullptr) {
return;
}
std::string rawMessage;
for (size_t i = 0; i < iovsCount; ++i) {
rawMessage.append(
static_cast<char*>(iovsBegin[i].iov_base), iovsBegin[i].iov_len);
}
targetOut_ << rawMessage;
targetOut_.flush();
countStats();
}
std::string MessagePrinter::serializeConnectionDetails(
const folly::SocketAddress& from,
const folly::SocketAddress& to,
mc_protocol_t protocol) {
std::string out;
if (!from.empty()) {
out.append(describeAddress(from));
}
if (!from.empty() || !to.empty()) {
out.append(" -> ");
}
if (!to.empty()) {
out.append(describeAddress(to));
}
if ((!from.empty() || !to.empty()) && protocol != mc_unknown_protocol) {
out.append(folly::sformat(" ({})", mc_protocol_to_string(protocol)));
}
return out;
}
std::string MessagePrinter::serializeMessageHeader(mc_op_t op,
mc_res_t result,
const std::string& key) {
std::string out;
if (op != mc_op_unknown) {
out.append(mc_op_to_string(op));
}
if (result != mc_res_unknown) {
if (out.size() > 0) {
out.push_back(' ');
}
out.append(mc_res_to_string(result));
}
if (key.size()) {
if (out.size() > 0) {
out.push_back(' ');
}
out.append(folly::backslashify(key));
}
return out;
}
/**
* Matches all the occurences of "pattern" in "text"
*
* @return A vector of pairs containing the index and size (respectively)
* of all ocurrences.
*/
std::vector<std::pair<size_t, size_t>> MessagePrinter::matchAll(
folly::StringPiece text, const boost::regex& pattern) const {
std::vector<std::pair<size_t, size_t>> result;
boost::cregex_token_iterator it(text.begin(), text.end(), pattern);
boost::cregex_token_iterator end;
while (it != end) {
result.emplace_back(it->first - text.begin(), it->length());
++it;
}
return result;
}
}} // facebook::memcache
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "MessagePrinter.h"
#include <folly/Bits.h>
namespace facebook { namespace memcache {
namespace {
bool matchIPAddress(const folly::IPAddress& expectedIp,
const folly::SocketAddress& address) {
return !address.empty() && expectedIp == address.getIPAddress();
}
bool matchPort(uint16_t expectedPort, const folly::SocketAddress& address) {
return !address.empty() && expectedPort == address.getPort();
}
std::string describeAddress(const folly::SocketAddress& address) {
auto res = address.describe();
if (address.getFamily() == AF_UNIX) {
// Check if the path was truncated.
if (res.size() >=
MessageHeader::kAddressMaxSize - kUnixSocketPrefix.size() - 1) {
return res + "...";
}
}
return res;
}
} // anonymous namespace
MessagePrinter::MessagePrinter(Options options,
Filter filter,
std::unique_ptr<ValueFormatter> valueFormatter)
: options_(std::move(options)),
filter_(std::move(filter)),
valueFormatter_(std::move(valueFormatter)) {
if (options_.disableColor) {
targetOut_.setColorOutput(false);
}
}
bool MessagePrinter::matchAddress(const folly::SocketAddress& from,
const folly::SocketAddress& to) const {
// Initial filters
if (!filter_.host.empty() &&
!matchIPAddress(filter_.host, from) &&
!matchIPAddress(filter_.host, to)) {
return false;
}
if (filter_.port != 0 &&
!matchPort(filter_.port, from) &&
!matchPort(filter_.port, to)) {
return false;
}
return true;
}
void MessagePrinter::countStats() {
++printedMessages_;
if (options_.maxMessages > 0 && printedMessages_ >= options_.maxMessages) {
assert(options_.stopRunningFn);
options_.stopRunningFn(*this);
}
if (options_.numAfterMatch > 0) {
--afterMatchCount_;
}
}
void MessagePrinter::printRawMessage(const struct iovec* iovsBegin,
size_t iovsCount) {
if (iovsBegin == nullptr) {
return;
}
std::string rawMessage;
for (size_t i = 0; i < iovsCount; ++i) {
rawMessage.append(
static_cast<char*>(iovsBegin[i].iov_base), iovsBegin[i].iov_len);
}
uint64_t rawMessageSize = folly::Endian::little(rawMessage.size());
targetOut_ << std::string(
reinterpret_cast<char*>(&rawMessageSize), sizeof(uint64_t))
<< rawMessage;
targetOut_.flush();
countStats();
}
std::string MessagePrinter::serializeConnectionDetails(
const folly::SocketAddress& from,
const folly::SocketAddress& to,
mc_protocol_t protocol) {
std::string out;
if (!from.empty()) {
out.append(describeAddress(from));
}
if (!from.empty() || !to.empty()) {
out.append(" -> ");
}
if (!to.empty()) {
out.append(describeAddress(to));
}
if ((!from.empty() || !to.empty()) && protocol != mc_unknown_protocol) {
out.append(folly::sformat(" ({})", mc_protocol_to_string(protocol)));
}
return out;
}
std::string MessagePrinter::serializeMessageHeader(mc_op_t op,
mc_res_t result,
const std::string& key) {
std::string out;
if (op != mc_op_unknown) {
out.append(mc_op_to_string(op));
}
if (result != mc_res_unknown) {
if (out.size() > 0) {
out.push_back(' ');
}
out.append(mc_res_to_string(result));
}
if (key.size()) {
if (out.size() > 0) {
out.push_back(' ');
}
out.append(folly::backslashify(key));
}
return out;
}
/**
* Matches all the occurences of "pattern" in "text"
*
* @return A vector of pairs containing the index and size (respectively)
* of all ocurrences.
*/
std::vector<std::pair<size_t, size_t>> MessagePrinter::matchAll(
folly::StringPiece text, const boost::regex& pattern) const {
std::vector<std::pair<size_t, size_t>> result;
boost::cregex_token_iterator it(text.begin(), text.end(), pattern);
boost::cregex_token_iterator end;
while (it != end) {
result.emplace_back(it->first - text.begin(), it->length());
++it;
}
return result;
}
}} // facebook::memcache
|
print message size in --raw option
|
print message size in --raw option
Summary: added print of message size
Reviewed By: andreazevedo
Differential Revision: D3616344
fbshipit-source-id: 640aee477e5b09ca8bd35275d29ee7a101f9237c
|
C++
|
mit
|
facebook/mcrouter,facebook/mcrouter,facebook/mcrouter,yqzhang/mcrouter,yqzhang/mcrouter,yqzhang/mcrouter,yqzhang/mcrouter,facebook/mcrouter
|
667f493a5b7c4a66dfe7254862c6146820bb5cd1
|
Testing/Code/IO/otbImageFileWriterWithExtendedOptionBox.cxx
|
Testing/Code/IO/otbImageFileWriterWithExtendedOptionBox.cxx
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "itkMacro.h"
#include <iostream>
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"
int otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])
{
// Verify the number of parameters in the command line
const std::string inputFilename = argv[1];
const std::string outputFilename = argv[2];
const unsigned int startx = atoi(argv[3]);
const unsigned int starty = atoi(argv[4]);
const unsigned int sizex = atoi(argv[5]);
const unsigned int sizey = atoi(argv[6]);
const std::string separator = ":";
typedef float InputPixelType;
typedef float OutputPixelType;
typedef otb::VectorImage<InputPixelType, 2> InputImageType;
typedef typename InputImageType::PixelType PixelType;
typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType,
InputImageType::InternalPixelType> ExtractROIFilterType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
typedef itk::ImageRegionIterator< InputImageType > IteratorType;
typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;
ReaderType::Pointer reader = ReaderType::New();
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(inputFilename);
//Build output filename with extended box
std::ostringstream outputFilenameExtended;
outputFilenameExtended
<< outputFilename
<< "?&box=" << startx << separator
<< starty << separator
<< sizex << separator
<< sizey
;
std::cout << "Output image with user defined path " << outputFilenameExtended.str() << std::endl;
writer->SetFileName(outputFilenameExtended.str());
writer->SetInput(reader->GetOutput());
extractROIFilter->SetStartX(startx);
extractROIFilter->SetStartY(starty);
extractROIFilter->SetSizeX(sizex);
extractROIFilter->SetSizeY(sizey);
extractROIFilter->SetInput(reader->GetOutput());
writer->Update();
extractROIFilter->Update();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(outputFilename);
reader2->Update();
InputImageType::ConstPointer readImage = reader2->GetOutput();
InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();
ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );
ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );
ritr.GoToBegin();
extractitr.GoToBegin();
std::cout << "Comparing the pixel values.. :" << std::endl;
while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )
{
if( ritr.Get() != extractitr.Get() )
{
std::cerr << "Pixel comparison failed at index = " << ritr.GetIndex() << std::endl;
std::cerr << "Expected pixel value " << extractitr.Get() << std::endl;
std::cerr << "Read Image pixel value " << ritr.Get() << std::endl;
return EXIT_FAILURE;
}
++extractitr;
++ritr;
}
std::cout << std::endl;
std::cout << "Test PASSED !" << std::endl;
return EXIT_SUCCESS;
}
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "itkMacro.h"
#include <iostream>
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiChannelExtractROI.h"
int otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])
{
// Verify the number of parameters in the command line
const std::string inputFilename = argv[1];
const std::string outputFilename = argv[2];
const unsigned int startx = atoi(argv[3]);
const unsigned int starty = atoi(argv[4]);
const unsigned int sizex = atoi(argv[5]);
const unsigned int sizey = atoi(argv[6]);
const std::string separator = ":";
typedef float InputPixelType;
typedef float OutputPixelType;
typedef otb::VectorImage<InputPixelType, 2> InputImageType;
typedef InputImageType::PixelType PixelType;
typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType,
InputImageType::InternalPixelType> ExtractROIFilterType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
typedef itk::ImageRegionIterator< InputImageType > IteratorType;
typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;
ReaderType::Pointer reader = ReaderType::New();
ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(inputFilename);
//Build output filename with extended box
std::ostringstream outputFilenameExtended;
outputFilenameExtended
<< outputFilename
<< "?&box=" << startx << separator
<< starty << separator
<< sizex << separator
<< sizey
;
std::cout << "Output image with user defined path " << outputFilenameExtended.str() << std::endl;
writer->SetFileName(outputFilenameExtended.str());
writer->SetInput(reader->GetOutput());
extractROIFilter->SetStartX(startx);
extractROIFilter->SetStartY(starty);
extractROIFilter->SetSizeX(sizex);
extractROIFilter->SetSizeY(sizey);
extractROIFilter->SetInput(reader->GetOutput());
writer->Update();
extractROIFilter->Update();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(outputFilename);
reader2->Update();
InputImageType::ConstPointer readImage = reader2->GetOutput();
InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();
ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );
ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );
ritr.GoToBegin();
extractitr.GoToBegin();
std::cout << "Comparing the pixel values.. :" << std::endl;
while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )
{
if( ritr.Get() != extractitr.Get() )
{
std::cerr << "Pixel comparison failed at index = " << ritr.GetIndex() << std::endl;
std::cerr << "Expected pixel value " << extractitr.Get() << std::endl;
std::cerr << "Read Image pixel value " << ritr.Get() << std::endl;
return EXIT_FAILURE;
}
++extractitr;
++ritr;
}
std::cout << std::endl;
std::cout << "Test PASSED !" << std::endl;
return EXIT_SUCCESS;
}
|
remove typename outside a template
|
WARN: remove typename outside a template
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
dfaca9f4255ab4c3641290b20f02bade0f79a743
|
b-ask/b-ask.cpp
|
b-ask/b-ask.cpp
|
#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <signal.h>
std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;
int32x4_t va;
std::int32_t a ;
std::int32_t * ptr;
std::int32_t n = 2500;
std::int64_t size = sizeof(a)*n;
std::int32_t limit = n-4;
std::int32_t data_bit[] = {1, 0, 0, 1};
void inline sig_handler(int sign) {
free(ptr);
std::cout << "\nReceived signal. aborting." << std::endl ;
exit(-1);
}
void inline boost_song() {
using namespace std::chrono ;
int i{0} ;
while( true ) {
std::unique_lock<std::mutex> lk{m} ;
cv.wait( lk ) ;
while( high_resolution_clock::now() < end ) {
int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) };
va = vld1q_s32(var);
i++;
if(i==limit) i=0;
}
std::this_thread::sleep_until( reset ) ;
}
}
int init_memory(void) {
ptr = (int32_t *)malloc(size);
if( ptr == NULL ){
std::cout << "Malloc Error" << std::endl;
return -1;
}
for(int i=0; i<=n; i++){
ptr[i] = i;
}
return 0;
}
void send_data(float time) {
using namespace std::chrono ;
seconds const sec{1} ;
nanoseconds const nsec{ sec } ;
using rep = nanoseconds::rep ;
auto nsec_per_sec = nsec.count() ;
for(int32_t d : data_bit){
auto start = high_resolution_clock::now() ;
auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;
if( d == 1 ){
std::cout << "Detected 1 bit" << std::endl;
while (high_resolution_clock::now() < end) {
cv.notify_all() ;
std::this_thread::sleep_until( end ) ;
start = reset;
}
}
else{
std::this_thread::sleep_until( end ) ;
}
}
}
int main(){
signal(SIGINT, sig_handler);
init_memory();
for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {
std::thread t( boost_song ) ;
t.detach() ;
}
send_data(0.05);
free(ptr);
return 0;
}
|
#include <iostream>
#include <iomanip>
#include <chrono>
#include <arm_neon.h>
#include <stdlib.h>
#include <inttypes.h>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <signal.h>
std::mutex m ;
std::condition_variable cv ;
std::chrono::high_resolution_clock::time_point mid ;
std::chrono::high_resolution_clock::time_point reset ;
int32x4_t va;
std::int32_t a ;
std::int32_t * ptr;
std::int32_t n = 2500;
std::int64_t size = sizeof(a)*n;
std::int32_t limit = n-4;
std::int32_t data_bit[] = {1, 0, 0, 1};
void inline sig_handler(int sign) {
free(ptr);
std::cout << "\nReceived signal. aborting." << std::endl ;
exit(-1);
}
void inline boost_song() {
using namespace std::chrono ;
int i{0} ;
while( true ) {
std::unique_lock<std::mutex> lk{m} ;
cv.wait( lk ) ;
while( high_resolution_clock::now() < end ) {
int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) };
va = vld1q_s32(var);
i++;
if(i==limit) i=0;
}
std::this_thread::sleep_until( reset ) ;
}
}
int init_memory(void) {
ptr = (int32_t *)malloc(size);
if( ptr == NULL ){
std::cout << "Malloc Error" << std::endl;
return -1;
}
for(int i=0; i<=n; i++){
ptr[i] = i;
}
return 0;
}
void send_data(float time) {
using namespace std::chrono ;
seconds const sec{1} ;
nanoseconds const nsec{ sec } ;
using rep = nanoseconds::rep ;
auto nsec_per_sec = nsec.count() ;
for(int32_t d : data_bit){
auto start = high_resolution_clock::now() ;
auto end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;
if( d == 1 ){
std::cout << "Detected 1 bit" << std::endl;
while (high_resolution_clock::now() < end) {
cv.notify_all() ;
std::this_thread::sleep_until( end ) ;
start = reset;
}
}
else{
std::this_thread::sleep_until( end ) ;
}
}
}
int main(){
signal(SIGINT, sig_handler);
init_memory();
for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {
std::thread t( boost_song ) ;
t.detach() ;
}
send_data(0.05);
free(ptr);
return 0;
}
|
fix var
|
fix var
|
C++
|
mit
|
gorillanet/system-bus-radio-neon
|
b82b03e6e60349814e367409e3ce116e0f845e88
|
src/infill/LightningLayer.cpp
|
src/infill/LightningLayer.cpp
|
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningLayer.h" //The class we're implementing.
#include <iterator> // advance
#include "LightningDistanceField.h"
#include "LightningTreeNode.h"
#include "../sliceDataStorage.h"
#include "../utils/linearAlg2D.h"
#include "../utils/SVG.h"
#include "../utils/SparsePointGridInclusive.h"
using namespace cura;
coord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location)
{
return vSize(boundary_loc - unsupported_location);
}
Point GroundingLocation::p() const
{
if (tree_node != nullptr)
{
return tree_node->getLocation();
}
else
{
assert(boundary_location);
return boundary_location->p();
}
}
void LightningLayer::fillLocator(SparseLightningTreeNodeGrid& tree_node_locator)
{
std::function<void(LightningTreeNodeSPtr)> add_node_to_locator_func =
[&tree_node_locator](LightningTreeNodeSPtr node)
{
tree_node_locator.insert(node->getLocation(), node);
};
for (auto& tree : tree_roots)
{
tree->visitNodes(add_node_to_locator_func);
}
}
void LightningLayer::generateNewTrees
(
const Polygons& current_overhang,
const Polygons& current_outlines,
const LocToLineGrid& outlines_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang);
SparseLightningTreeNodeGrid tree_node_locator(locator_cell_size);
fillLocator(tree_node_locator);
// Until no more points need to be added to support all:
// Determine next point from tree/outline areas via distance-field
Point unsupported_location;
while (distance_field.tryGetNextPoint(&unsupported_location))
{
GroundingLocation grounding_loc =
getBestGroundingLocation
(
unsupported_location,
current_outlines,
outlines_locator,
supporting_radius,
wall_supporting_radius,
tree_node_locator
);
LightningTreeNodeSPtr new_parent;
LightningTreeNodeSPtr new_child;
attach(unsupported_location, grounding_loc, new_child, new_parent);
tree_node_locator.insert(new_child->getLocation(), new_child);
if (new_parent)
{
tree_node_locator.insert(new_parent->getLocation(), new_parent);
}
// update distance field
distance_field.update(grounding_loc.p(), unsupported_location);
}
}
GroundingLocation LightningLayer::getBestGroundingLocation
(
const Point& unsupported_location,
const Polygons& current_outlines,
const LocToLineGrid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius,
const SparseLightningTreeNodeGrid& tree_node_locator,
const LightningTreeNodeSPtr& exclude_tree
)
{
ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines);
Point node_location = cpp.p();
const coord_t within_dist = vSize(node_location - unsupported_location);
PolygonsPointIndex dummy;
LightningTreeNodeSPtr sub_tree{ nullptr };
coord_t current_dist = getWeightedDistance(node_location, unsupported_location);
if (current_dist >= wall_supporting_radius) // Only reconnect tree roots to other trees if they are not already close to the outlines.
{
auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, within_dist));
for (auto& candidate_wptr : candidate_trees)
{
auto candidate_sub_tree = candidate_wptr.lock();
if
(
(candidate_sub_tree && candidate_sub_tree != exclude_tree) &&
! (exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)) &&
! PolygonUtils::polygonCollidesWithLineSegment(unsupported_location, candidate_sub_tree->getLocation(), outline_locator, &dummy)
)
{
const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius);
if (candidate_dist < current_dist)
{
current_dist = candidate_dist;
sub_tree = candidate_sub_tree;
}
}
}
}
if (! sub_tree)
{
return GroundingLocation{ nullptr, cpp };
}
else
{
return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() };
}
}
bool LightningLayer::attach
(
const Point& unsupported_location,
const GroundingLocation& grounding_loc,
LightningTreeNodeSPtr& new_child,
LightningTreeNodeSPtr& new_root
)
{
// Update trees & distance fields.
if (grounding_loc.boundary_location)
{
new_root = LightningTreeNode::create(grounding_loc.p(), std::make_optional(grounding_loc.p()));
new_child = new_root->addChild(unsupported_location);
tree_roots.push_back(new_root);
return true;
}
else
{
new_child = grounding_loc.tree_node->addChild(unsupported_location);
return false;
}
}
void LightningLayer::reconnectRoots
(
std::vector<LightningTreeNodeSPtr>& to_be_reconnected_tree_roots,
const Polygons& current_outlines,
const LocToLineGrid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
constexpr coord_t tree_connecting_ignore_offset = 100;
SparseLightningTreeNodeGrid tree_node_locator(locator_cell_size);
fillLocator(tree_node_locator);
const coord_t within_max_dist = outline_locator.getCellSize() * 2;
for (auto root_ptr : to_be_reconnected_tree_roots)
{
auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr);
if (root_ptr->getLastGroundingLocation())
{
const Point& ground_loc = root_ptr->getLastGroundingLocation().value();
if (ground_loc != root_ptr->getLocation())
{
Point new_root_pt;
if (PolygonUtils::lineSegmentPolygonsIntersection(root_ptr->getLocation(), ground_loc, current_outlines, outline_locator, new_root_pt, within_max_dist))
{
auto new_root = LightningTreeNode::create(new_root_pt, new_root_pt);
root_ptr->addChild(new_root);
new_root->reroot();
tree_node_locator.insert(new_root->getLocation(), new_root);
*old_root_it = std::move(new_root); // replace old root with new root
continue;
}
}
}
const coord_t tree_connecting_ignore_width = wall_supporting_radius - tree_connecting_ignore_offset; // Ideally, the boundary size in which the valence rule is ignored would be configurable.
GroundingLocation ground =
getBestGroundingLocation
(
root_ptr->getLocation(),
current_outlines,
outline_locator,
supporting_radius,
tree_connecting_ignore_width,
tree_node_locator,
root_ptr
);
if (ground.boundary_location)
{
if (ground.boundary_location.value().p() == root_ptr->getLocation())
{
continue; // Already on the boundary.
}
auto new_root = LightningTreeNode::create(ground.p(), ground.p());
auto attach_ptr = root_ptr->closestNode(new_root->getLocation());
attach_ptr->reroot();
new_root->addChild(attach_ptr);
tree_node_locator.insert(new_root->getLocation(), new_root);
*old_root_it = std::move(new_root); // replace old root with new root
}
else
{
assert(ground.tree_node);
assert(ground.tree_node != root_ptr);
assert(!root_ptr->hasOffspring(ground.tree_node));
assert(!ground.tree_node->hasOffspring(root_ptr));
auto attach_ptr = root_ptr->closestNode(ground.tree_node->getLocation());
attach_ptr->reroot();
ground.tree_node->addChild(attach_ptr);
// remove old root
*old_root_it = std::move(tree_roots.back());
tree_roots.pop_back();
}
}
}
// Returns 'added someting'.
Polygons LightningLayer::convertToLines(const Polygons& limit_to_outline, const coord_t line_width) const
{
Polygons result_lines;
if (tree_roots.empty())
{
return result_lines;
}
for (const auto& tree : tree_roots)
{
// If even the furthest location in the tree is inside the polygon, the entire tree must be inside of the polygon.
// (Don't take the root as that may be on the edge and cause rounding errors to register as 'outside'.)
constexpr coord_t epsilon = 5;
Point should_be_inside = tree->getLocation();
PolygonUtils::moveInside(limit_to_outline, should_be_inside, epsilon, epsilon * epsilon);
if (limit_to_outline.inside(should_be_inside))
{
tree->convertToPolylines(result_lines, line_width);
}
}
return result_lines;
}
|
//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "LightningLayer.h" //The class we're implementing.
#include <iterator> // advance
#include "LightningDistanceField.h"
#include "LightningTreeNode.h"
#include "../sliceDataStorage.h"
#include "../utils/linearAlg2D.h"
#include "../utils/SVG.h"
#include "../utils/SparsePointGridInclusive.h"
using namespace cura;
coord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location)
{
return vSize(boundary_loc - unsupported_location);
}
Point GroundingLocation::p() const
{
if (tree_node != nullptr)
{
return tree_node->getLocation();
}
else
{
assert(boundary_location);
return boundary_location->p();
}
}
void LightningLayer::fillLocator(SparseLightningTreeNodeGrid& tree_node_locator)
{
std::function<void(LightningTreeNodeSPtr)> add_node_to_locator_func =
[&tree_node_locator](LightningTreeNodeSPtr node)
{
tree_node_locator.insert(node->getLocation(), node);
};
for (auto& tree : tree_roots)
{
tree->visitNodes(add_node_to_locator_func);
}
}
void LightningLayer::generateNewTrees
(
const Polygons& current_overhang,
const Polygons& current_outlines,
const LocToLineGrid& outlines_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang);
SparseLightningTreeNodeGrid tree_node_locator(locator_cell_size);
fillLocator(tree_node_locator);
// Until no more points need to be added to support all:
// Determine next point from tree/outline areas via distance-field
Point unsupported_location;
while (distance_field.tryGetNextPoint(&unsupported_location))
{
GroundingLocation grounding_loc =
getBestGroundingLocation
(
unsupported_location,
current_outlines,
outlines_locator,
supporting_radius,
wall_supporting_radius,
tree_node_locator
);
LightningTreeNodeSPtr new_parent;
LightningTreeNodeSPtr new_child;
attach(unsupported_location, grounding_loc, new_child, new_parent);
tree_node_locator.insert(new_child->getLocation(), new_child);
if (new_parent)
{
tree_node_locator.insert(new_parent->getLocation(), new_parent);
}
// update distance field
distance_field.update(grounding_loc.p(), unsupported_location);
}
}
GroundingLocation LightningLayer::getBestGroundingLocation
(
const Point& unsupported_location,
const Polygons& current_outlines,
const LocToLineGrid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius,
const SparseLightningTreeNodeGrid& tree_node_locator,
const LightningTreeNodeSPtr& exclude_tree
)
{
ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines);
Point node_location = cpp.p();
const coord_t within_dist = vSize(node_location - unsupported_location);
PolygonsPointIndex dummy;
LightningTreeNodeSPtr sub_tree{ nullptr };
coord_t current_dist = getWeightedDistance(node_location, unsupported_location);
if (current_dist >= wall_supporting_radius) // Only reconnect tree roots to other trees if they are not already close to the outlines.
{
auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, within_dist));
for (auto& candidate_wptr : candidate_trees)
{
auto candidate_sub_tree = candidate_wptr.lock();
if
(
(candidate_sub_tree && candidate_sub_tree != exclude_tree) &&
! (exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)) &&
! PolygonUtils::polygonCollidesWithLineSegment(unsupported_location, candidate_sub_tree->getLocation(), outline_locator, &dummy)
)
{
const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius);
if (candidate_dist < current_dist)
{
current_dist = candidate_dist;
sub_tree = candidate_sub_tree;
}
}
}
}
if (! sub_tree)
{
return GroundingLocation{ nullptr, cpp };
}
else
{
return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() };
}
}
bool LightningLayer::attach
(
const Point& unsupported_location,
const GroundingLocation& grounding_loc,
LightningTreeNodeSPtr& new_child,
LightningTreeNodeSPtr& new_root
)
{
// Update trees & distance fields.
if (grounding_loc.boundary_location)
{
new_root = LightningTreeNode::create(grounding_loc.p(), std::make_optional(grounding_loc.p()));
new_child = new_root->addChild(unsupported_location);
tree_roots.push_back(new_root);
return true;
}
else
{
new_child = grounding_loc.tree_node->addChild(unsupported_location);
return false;
}
}
void LightningLayer::reconnectRoots
(
std::vector<LightningTreeNodeSPtr>& to_be_reconnected_tree_roots,
const Polygons& current_outlines,
const LocToLineGrid& outline_locator,
const coord_t supporting_radius,
const coord_t wall_supporting_radius
)
{
constexpr coord_t tree_connecting_ignore_offset = 100;
SparseLightningTreeNodeGrid tree_node_locator(locator_cell_size);
fillLocator(tree_node_locator);
const coord_t within_max_dist = outline_locator.getCellSize() * 2;
for (auto root_ptr : to_be_reconnected_tree_roots)
{
auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr);
if (root_ptr->getLastGroundingLocation())
{
const Point& ground_loc = root_ptr->getLastGroundingLocation().value();
if (ground_loc != root_ptr->getLocation())
{
Point new_root_pt;
if (PolygonUtils::lineSegmentPolygonsIntersection(root_ptr->getLocation(), ground_loc, current_outlines, outline_locator, new_root_pt, within_max_dist))
{
auto new_root = LightningTreeNode::create(new_root_pt, new_root_pt);
root_ptr->addChild(new_root);
new_root->reroot();
tree_node_locator.insert(new_root->getLocation(), new_root);
*old_root_it = std::move(new_root); // replace old root with new root
continue;
}
}
}
const coord_t tree_connecting_ignore_width = wall_supporting_radius - tree_connecting_ignore_offset; // Ideally, the boundary size in which the valence rule is ignored would be configurable.
GroundingLocation ground =
getBestGroundingLocation
(
root_ptr->getLocation(),
current_outlines,
outline_locator,
supporting_radius,
tree_connecting_ignore_width,
tree_node_locator,
root_ptr
);
if (ground.boundary_location)
{
if (ground.boundary_location.value().p() == root_ptr->getLocation())
{
continue; // Already on the boundary.
}
auto new_root = LightningTreeNode::create(ground.p(), ground.p());
auto attach_ptr = root_ptr->closestNode(new_root->getLocation());
attach_ptr->reroot();
new_root->addChild(attach_ptr);
tree_node_locator.insert(new_root->getLocation(), new_root);
*old_root_it = std::move(new_root); // replace old root with new root
}
else
{
assert(ground.tree_node);
assert(ground.tree_node != root_ptr);
assert(!root_ptr->hasOffspring(ground.tree_node));
assert(!ground.tree_node->hasOffspring(root_ptr));
auto attach_ptr = root_ptr->closestNode(ground.tree_node->getLocation());
attach_ptr->reroot();
ground.tree_node->addChild(attach_ptr);
// remove old root
*old_root_it = std::move(tree_roots.back());
tree_roots.pop_back();
}
}
}
// Returns 'added someting'.
Polygons LightningLayer::convertToLines(const Polygons& limit_to_outline, const coord_t line_width) const
{
Polygons result_lines;
if (tree_roots.empty())
{
return result_lines;
}
for (const auto& tree : tree_roots)
{
tree->convertToPolylines(result_lines, line_width);
}
result_lines = limit_to_outline.intersectionPolyLines(result_lines);
return result_lines;
}
|
Fix missing infill layers
|
Fix missing infill layers
CURA-9088
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
9b0b415137cddbd818ac3755868e0fc117014965
|
src/jnc_ct/jnc_ct_DoxyMgr.cpp
|
src/jnc_ct/jnc_ct_DoxyMgr.cpp
|
#include "pch.h"
#include "jnc_ct_DoxyMgr.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//.............................................................................
sl::String
DoxyBlock::createDoxyDescriptionString ()
{
sl::String string;
if (!m_briefDescription.isEmpty ())
{
string.append ("<briefdescription><para>\n");
string.append (m_briefDescription);
string.append ("</para></briefdescription>\n");
}
if (!m_detailedDescription.isEmpty ())
{
string.append ("<detaileddescription><para>\n");
string.append (m_detailedDescription);
string.append ("</para></detaileddescription>\n");
}
return string;
}
//.............................................................................
bool
DoxyGroup::generateDocumentation (
const char* outputDir,
sl::String* itemXml,
sl::String* indexXml
)
{
indexXml->appendFormat (
"<compound kind='group' refid='%s'><name>%s</name></compound>\n",
m_refId.cc (),
m_name.cc ()
);
itemXml->format (
"<compounddef kind='group' id='%s'>\n"
"<compoundname>%s</compoundname>\n"
"<title>%s</title>\n",
m_refId.cc (),
m_name.cc (),
m_title.cc ()
);
sl::String sectionDef;
size_t count = m_itemArray.getCount ();
for (size_t i = 0; i < count; i++)
{
ModuleItem* item = m_itemArray [i];
ModuleItemDecl* decl = item->getDecl ();
if (!decl)
continue;
ModuleItemKind itemKind = item->getItemKind ();
bool isCompoundFile =
itemKind == ModuleItemKind_Namespace ||
itemKind == ModuleItemKind_Type && ((Type*) item)->getTypeKind () != TypeKind_Enum;
sl::String refId = item->getDoxyBlock ()->getRefId ();
if (!isCompoundFile)
{
sectionDef.appendFormat ("<memberdef id='%s'/>", refId.cc ());
sectionDef.append ('\n');
}
else
{
const char* elemName = itemKind == ModuleItemKind_Namespace ? "innernamespace" : "innerclass";
sl::String refId = item->getDoxyBlock ()->getRefId ();
itemXml->appendFormat ("<%s refid='%s'/>", elemName, refId.cc ());
itemXml->append ('\n');
}
}
if (!sectionDef.isEmpty ())
{
itemXml->append ("<sectiondef>\n");
itemXml->append (sectionDef);
itemXml->append ("</sectiondef>\n");
}
sl::BoxIterator <DoxyGroup*> groupIt = m_groupList.getHead ();
for (; groupIt; groupIt++)
{
DoxyGroup* group = *groupIt;
itemXml->appendFormat ("<innergroup refid='%s'/>", group->m_refId.cc ());
itemXml->append ('\n');
}
itemXml->append (createDoxyDescriptionString ());
itemXml->append ("</compounddef>\n");
return true;
}
//.............................................................................
DoxyMgr::DoxyMgr ()
{
m_module = Module::getCurrentConstructedModule ();
ASSERT (m_module);
}
void
DoxyMgr::clear ()
{
m_blockList.clear ();
m_groupList.clear ();
m_refIdMap.clear ();
m_groupMap.clear ();
m_targetList.clear ();
}
DoxyGroup*
DoxyMgr::getGroup (const sl::StringRef& name)
{
sl::StringHashTableMapIterator <DoxyGroup*> it = m_groupMap.visit (name);
if (it->m_value)
return it->m_value;
sl::String refId;
refId.format ("group_%s", name.cc ());
refId.replace ('-', '_');
DoxyGroup* group = AXL_MEM_NEW (DoxyGroup);
group->m_name = name;
group->m_refId = adjustRefId (refId);
m_groupList.insertTail (group);
it->m_value = group;
return group;
}
DoxyBlock*
DoxyMgr::createBlock ()
{
DoxyBlock* block = AXL_MEM_NEW (DoxyBlock);
m_blockList.insertTail (block);
return block;
}
sl::String
DoxyMgr::adjustRefId (const sl::StringRef& refId)
{
sl::StringHashTableMapIterator <size_t> it = m_refIdMap.visit (refId);
if (!it->m_value) // no collisions
{
it->m_value = 2; // start with index 2
return refId;
}
sl::String adjustedRefId;
adjustedRefId.format ("%s_%d", refId.cc (), it->m_value);
it->m_value++;
return adjustedRefId;
}
void
DoxyMgr::setBlockTarget (
DoxyBlock* block,
const sl::StringRef& targetName
)
{
Target* retarget = AXL_MEM_NEW (Target);
retarget->m_block = block;
retarget->m_targetName = targetName;
m_targetList.insertTail (retarget);
}
bool
DoxyMgr::resolveBlockTargets ()
{
bool result = true;
GlobalNamespace* globalNspace = m_module->m_namespaceMgr.getGlobalNamespace ();
Namespace* prevNspace = NULL;
sl::Iterator <Target> it = m_targetList.getHead ();
for (; it; it++)
{
Target* target = *it;
ModuleItem* item = prevNspace && target->m_targetName.find ('.') == -1 ?
prevNspace->findItem (target->m_targetName) :
NULL;
if (!item)
{
item = globalNspace->findItemByName (target->m_targetName);
if (!item)
{
result = false;
continue;
}
}
if (item->m_doxyBlock && item->m_doxyBlock->m_group && !target->m_block->m_group)
target->m_block->m_group = item->m_doxyBlock->m_group;
item->m_doxyBlock = target->m_block;
if (item->getItemKind () != ModuleItemKind_Property)
{
Namespace* itemNspace = item->getNamespace ();
if (itemNspace)
prevNspace = itemNspace;
}
}
if (!result)
err::setStringError ("documentation target(s) not found");
return result;
}
void
DoxyMgr::deleteEmptyGroups ()
{
bool isGroupDeleted;
do
{
isGroupDeleted = false;
sl::Iterator <DoxyGroup> groupIt = m_groupList.getHead ();
while (groupIt)
{
sl::Iterator <DoxyGroup> nextIt = groupIt.getNext ();
if (groupIt->isEmpty ())
{
if (groupIt->m_group)
groupIt->m_group->m_groupList.remove (groupIt->m_parentGroupListIt);
m_groupMap.eraseByKey (groupIt->m_name);
m_groupList.erase (groupIt);
isGroupDeleted = true;
}
groupIt = nextIt;
}
} while (isGroupDeleted);
}
bool
DoxyMgr::generateGroupDocumentation (
const char* outputDir,
sl::String* indexXml
)
{
bool result;
static char compoundFileHdr [] =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<doxygen>\n";
static char compoundFileTerm [] = "</doxygen>\n";
sl::String itemXml;
sl::Iterator <DoxyGroup> groupIt = m_groupList.getHead ();
for (; groupIt; groupIt++)
{
result = groupIt->generateDocumentation (outputDir, &itemXml, indexXml);
if (!result)
return false;
sl::String refId = groupIt->getRefId ();
sl::String fileName = sl::String (outputDir) + "/" + refId + ".xml";
io::File compoundFile;
result =
compoundFile.open (fileName, io::FileFlag_Clear) &&
compoundFile.write (compoundFileHdr, lengthof (compoundFileHdr)) != -1 &&
compoundFile.write (itemXml, itemXml.getLength ()) != -1 &&
compoundFile.write (compoundFileTerm, lengthof (compoundFileTerm)) != -1;
if (!result)
return false;
}
return true;
}
//.............................................................................
} // namespace ct
} // namespace jnc
|
#include "pch.h"
#include "jnc_ct_DoxyMgr.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//.............................................................................
sl::String
DoxyBlock::createDoxyDescriptionString ()
{
sl::String string;
if (!m_briefDescription.isEmpty ())
{
string.append ("<briefdescription><para>");
string.append (m_briefDescription.getTrimmedString ());
string.append ("</para></briefdescription>\n");
}
if (!m_detailedDescription.isEmpty ())
{
string.append ("<detaileddescription><para>");
string.append (m_detailedDescription.getTrimmedString ());
string.append ("</para></detaileddescription>\n");
}
return string;
}
//.............................................................................
bool
DoxyGroup::generateDocumentation (
const char* outputDir,
sl::String* itemXml,
sl::String* indexXml
)
{
indexXml->appendFormat (
"<compound kind='group' refid='%s'><name>%s</name></compound>\n",
m_refId.cc (),
m_name.cc ()
);
itemXml->format (
"<compounddef kind='group' id='%s'>\n"
"<compoundname>%s</compoundname>\n"
"<title>%s</title>\n",
m_refId.cc (),
m_name.cc (),
m_title.cc ()
);
sl::String sectionDef;
size_t count = m_itemArray.getCount ();
for (size_t i = 0; i < count; i++)
{
ModuleItem* item = m_itemArray [i];
ModuleItemDecl* decl = item->getDecl ();
if (!decl)
continue;
ModuleItemKind itemKind = item->getItemKind ();
bool isCompoundFile =
itemKind == ModuleItemKind_Namespace ||
itemKind == ModuleItemKind_Type && ((Type*) item)->getTypeKind () != TypeKind_Enum;
sl::String refId = item->getDoxyBlock ()->getRefId ();
if (!isCompoundFile)
{
sectionDef.appendFormat ("<memberdef id='%s'/>", refId.cc ());
sectionDef.append ('\n');
}
else
{
const char* elemName = itemKind == ModuleItemKind_Namespace ? "innernamespace" : "innerclass";
sl::String refId = item->getDoxyBlock ()->getRefId ();
itemXml->appendFormat ("<%s refid='%s'/>", elemName, refId.cc ());
itemXml->append ('\n');
}
}
if (!sectionDef.isEmpty ())
{
itemXml->append ("<sectiondef>\n");
itemXml->append (sectionDef);
itemXml->append ("</sectiondef>\n");
}
sl::BoxIterator <DoxyGroup*> groupIt = m_groupList.getHead ();
for (; groupIt; groupIt++)
{
DoxyGroup* group = *groupIt;
itemXml->appendFormat ("<innergroup refid='%s'/>", group->m_refId.cc ());
itemXml->append ('\n');
}
itemXml->append (createDoxyDescriptionString ());
itemXml->append ("</compounddef>\n");
return true;
}
//.............................................................................
DoxyMgr::DoxyMgr ()
{
m_module = Module::getCurrentConstructedModule ();
ASSERT (m_module);
}
void
DoxyMgr::clear ()
{
m_blockList.clear ();
m_groupList.clear ();
m_refIdMap.clear ();
m_groupMap.clear ();
m_targetList.clear ();
}
DoxyGroup*
DoxyMgr::getGroup (const sl::StringRef& name)
{
sl::StringHashTableMapIterator <DoxyGroup*> it = m_groupMap.visit (name);
if (it->m_value)
return it->m_value;
sl::String refId;
refId.format ("group_%s", name.cc ());
refId.replace ('-', '_');
DoxyGroup* group = AXL_MEM_NEW (DoxyGroup);
group->m_name = name;
group->m_refId = adjustRefId (refId);
m_groupList.insertTail (group);
it->m_value = group;
return group;
}
DoxyBlock*
DoxyMgr::createBlock ()
{
DoxyBlock* block = AXL_MEM_NEW (DoxyBlock);
m_blockList.insertTail (block);
return block;
}
sl::String
DoxyMgr::adjustRefId (const sl::StringRef& refId)
{
sl::StringHashTableMapIterator <size_t> it = m_refIdMap.visit (refId);
if (!it->m_value) // no collisions
{
it->m_value = 2; // start with index 2
return refId;
}
sl::String adjustedRefId;
adjustedRefId.format ("%s_%d", refId.cc (), it->m_value);
it->m_value++;
return adjustedRefId;
}
void
DoxyMgr::setBlockTarget (
DoxyBlock* block,
const sl::StringRef& targetName
)
{
Target* retarget = AXL_MEM_NEW (Target);
retarget->m_block = block;
retarget->m_targetName = targetName;
m_targetList.insertTail (retarget);
}
bool
DoxyMgr::resolveBlockTargets ()
{
bool result = true;
GlobalNamespace* globalNspace = m_module->m_namespaceMgr.getGlobalNamespace ();
Namespace* prevNspace = NULL;
sl::Iterator <Target> it = m_targetList.getHead ();
for (; it; it++)
{
Target* target = *it;
ModuleItem* item = prevNspace && target->m_targetName.find ('.') == -1 ?
prevNspace->findItem (target->m_targetName) :
NULL;
if (!item)
{
item = globalNspace->findItemByName (target->m_targetName);
if (!item)
{
result = false;
continue;
}
}
if (item->m_doxyBlock && item->m_doxyBlock->m_group && !target->m_block->m_group)
target->m_block->m_group = item->m_doxyBlock->m_group;
item->m_doxyBlock = target->m_block;
if (item->getItemKind () != ModuleItemKind_Property)
{
Namespace* itemNspace = item->getNamespace ();
if (itemNspace)
prevNspace = itemNspace;
}
}
if (!result)
err::setStringError ("documentation target(s) not found");
return result;
}
void
DoxyMgr::deleteEmptyGroups ()
{
bool isGroupDeleted;
do
{
isGroupDeleted = false;
sl::Iterator <DoxyGroup> groupIt = m_groupList.getHead ();
while (groupIt)
{
sl::Iterator <DoxyGroup> nextIt = groupIt.getNext ();
if (groupIt->isEmpty ())
{
if (groupIt->m_group)
groupIt->m_group->m_groupList.remove (groupIt->m_parentGroupListIt);
m_groupMap.eraseByKey (groupIt->m_name);
m_groupList.erase (groupIt);
isGroupDeleted = true;
}
groupIt = nextIt;
}
} while (isGroupDeleted);
}
bool
DoxyMgr::generateGroupDocumentation (
const char* outputDir,
sl::String* indexXml
)
{
bool result;
static char compoundFileHdr [] =
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<doxygen>\n";
static char compoundFileTerm [] = "</doxygen>\n";
sl::String itemXml;
sl::Iterator <DoxyGroup> groupIt = m_groupList.getHead ();
for (; groupIt; groupIt++)
{
result = groupIt->generateDocumentation (outputDir, &itemXml, indexXml);
if (!result)
return false;
sl::String refId = groupIt->getRefId ();
sl::String fileName = sl::String (outputDir) + "/" + refId + ".xml";
io::File compoundFile;
result =
compoundFile.open (fileName, io::FileFlag_Clear) &&
compoundFile.write (compoundFileHdr, lengthof (compoundFileHdr)) != -1 &&
compoundFile.write (itemXml, itemXml.getLength ()) != -1 &&
compoundFile.write (compoundFileTerm, lengthof (compoundFileTerm)) != -1;
if (!result)
return false;
}
return true;
}
//.............................................................................
} // namespace ct
} // namespace jnc
|
trim description string before saving to xml
|
[jancy] trim description string before saving to xml
|
C++
|
mit
|
vovkos/jancy,vovkos/jancy,vovkos/jancy,vovkos/jancy,vovkos/jancy
|
20c3d33d3e1bd0eee30f0d5f1517865ebff3965b
|
FileCheck/FileCheck.cpp
|
FileCheck/FileCheck.cpp
|
//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Str - The string to match.
std::string Str;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
/// NotStrings - These are all of the strings that are disallowed from
/// occurring between this match string and the previous one (or start of
/// file).
std::vector<std::pair<SMLoc, std::string> > NotStrings;
CheckString(const std::string &S, SMLoc L, bool isCheckNext)
: Str(S), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, std::string> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
StringRef PatternStr = Buffer.substr(0, EOL);
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
PatternStr.str()));
Buffer = Buffer.substr(EOL);
continue;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(PatternStr.str(),
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
if (!NotMatches.empty()) {
errs() << "error: '" << CheckPrefix
<< "-NOT:' not supported after last check line.\n";
return true;
}
return false;
}
// CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
// the check strings with a single space.
static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
std::string &Str = CheckStrings[i].Str;
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
/// CountNumNewlinesBetween - Count the number of newlines in the specified
/// range.
static unsigned CountNumNewlinesBetween(StringRef Range) {
unsigned NumNewLines = 0;
while (1) {
// Scan for newline.
Range = Range.substr(Range.find_first_of("\n\r"));
if (Range.empty()) return NumNewLines;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Range.size() > 1 &&
(Range[1] == '\n' || Range[1] == '\r') &&
(Range[0] != Range[1]))
Range = Range.substr(1);
Range = Range.substr(1);
}
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckStrings(CheckStrings);
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = Buffer.data();
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch != F->getBufferStart() &&
"CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
if (Pos == StringRef::npos) continue;
SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
CheckPrefix+"-NOT: string occurred!", "error");
SM.PrintMessage(CheckStr.NotStrings[i].first,
CheckPrefix+"-NOT: pattern specified here", "note");
return 1;
}
// Otherwise, everything is good. Step over the matched text and remember
// the position after the match as the end of the last match.
Buffer = Buffer.substr(CheckStr.Str.size());
LastMatch = Buffer.data();
}
return 0;
}
|
//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
class Pattern {
/// Str - The string to match.
std::string Str;
public:
Pattern(StringRef S) : Str(S.str()) {
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckString();
}
/// Match - Match the pattern string against the input buffer Buffer. This
/// returns the position that is matched or npos if there is no match. If
/// there is a match, the size of the matched string is returned in MatchLen.
size_t Match(StringRef Buffer, size_t &MatchLen) const {
MatchLen = Str.size();
return Buffer.find(Str);
}
private:
/// CanonicalizeCheckString - Replace all sequences of horizontal whitespace
/// in the check strings with a single space.
void CanonicalizeCheckString() {
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
};
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Pat - The pattern to match.
Pattern Pat;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
/// NotStrings - These are all of the strings that are disallowed from
/// occurring between this match string and the previous one (or start of
/// file).
std::vector<std::pair<SMLoc, std::string> > NotStrings;
CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
: Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, std::string> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
StringRef PatternStr = Buffer.substr(0, EOL);
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
PatternStr.str()));
Buffer = Buffer.substr(EOL);
continue;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
Pattern P(PatternStr);
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(P,
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
if (!NotMatches.empty()) {
errs() << "error: '" << CheckPrefix
<< "-NOT:' not supported after last check line.\n";
return true;
}
return false;
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
/// CountNumNewlinesBetween - Count the number of newlines in the specified
/// range.
static unsigned CountNumNewlinesBetween(StringRef Range) {
unsigned NumNewLines = 0;
while (1) {
// Scan for newline.
Range = Range.substr(Range.find_first_of("\n\r"));
if (Range.empty()) return NumNewLines;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Range.size() > 1 &&
(Range[1] == '\n' || Range[1] == '\r') &&
(Range[0] != Range[1]))
Range = Range.substr(1);
Range = Range.substr(1);
}
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = Buffer.data();
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
size_t MatchLen = 0;
Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch != F->getBufferStart() &&
"CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
if (Pos == StringRef::npos) continue;
SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
CheckPrefix+"-NOT: string occurred!", "error");
SM.PrintMessage(CheckStr.NotStrings[i].first,
CheckPrefix+"-NOT: pattern specified here", "note");
return 1;
}
// Otherwise, everything is good. Step over the matched text and remember
// the position after the match as the end of the last match.
Buffer = Buffer.substr(MatchLen);
LastMatch = Buffer.data();
}
return 0;
}
|
refactor out the match string into its own Pattern class.
|
refactor out the match string into its own Pattern class.
git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@82711 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-3-clause
|
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
|
b1765749f5f1de3803b8710a2bad7c624b2fc357
|
libevmjit/BasicBlock.cpp
|
libevmjit/BasicBlock.cpp
|
#include "BasicBlock.h"
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <llvm/IR/CFG.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/raw_os_ostream.h>
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
const char* BasicBlock::NamePrefix = "Instr.";
BasicBlock::BasicBlock(ProgramCounter _beginInstIdx, ProgramCounter _endInstIdx, llvm::Function* _mainFunc, llvm::IRBuilder<>& _builder) :
m_beginInstIdx(_beginInstIdx),
m_endInstIdx(_endInstIdx),
m_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), {NamePrefix, std::to_string(_beginInstIdx)}, _mainFunc)),
m_stack(*this),
m_builder(_builder)
{}
BasicBlock::BasicBlock(std::string _name, llvm::Function* _mainFunc, llvm::IRBuilder<>& _builder) :
m_beginInstIdx(0),
m_endInstIdx(0),
m_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), _name, _mainFunc)),
m_stack(*this),
m_builder(_builder)
{}
BasicBlock::LocalStack::LocalStack(BasicBlock& _owner) :
m_bblock(_owner)
{}
void BasicBlock::LocalStack::push(llvm::Value* _value)
{
m_bblock.m_currentStack.push_back(_value);
m_bblock.m_tosOffset += 1;
}
llvm::Value* BasicBlock::LocalStack::pop()
{
auto result = get(0);
if (m_bblock.m_currentStack.size() > 0)
m_bblock.m_currentStack.pop_back();
m_bblock.m_tosOffset -= 1;
return result;
}
/**
* Pushes a copy of _index-th element (tos is 0-th elem).
*/
void BasicBlock::LocalStack::dup(size_t _index)
{
auto val = get(_index);
push(val);
}
/**
* Swaps tos with _index-th element (tos is 0-th elem).
* _index must be > 0.
*/
void BasicBlock::LocalStack::swap(size_t _index)
{
assert(_index > 0);
auto val = get(_index);
auto tos = get(0);
set(_index, tos);
set(0, val);
}
std::vector<llvm::Value*>::iterator BasicBlock::LocalStack::getItemIterator(size_t _index)
{
auto& currentStack = m_bblock.m_currentStack;
if (_index < currentStack.size())
return currentStack.end() - _index - 1;
// Need to map more elements from the EVM stack
auto nNewItems = 1 + _index - currentStack.size();
currentStack.insert(currentStack.begin(), nNewItems, nullptr);
return currentStack.end() - _index - 1;
}
llvm::Value* BasicBlock::LocalStack::get(size_t _index)
{
auto& initialStack = m_bblock.m_initialStack;
auto itemIter = getItemIterator(_index);
if (*itemIter == nullptr)
{
// Need to fetch a new item from the EVM stack
assert(static_cast<int>(_index) >= m_bblock.m_tosOffset);
size_t initialIdx = _index - m_bblock.m_tosOffset;
if (initialIdx >= initialStack.size())
{
auto nNewItems = 1 + initialIdx - initialStack.size();
initialStack.insert(initialStack.end(), nNewItems, nullptr);
}
assert(initialStack[initialIdx] == nullptr);
// Create a dummy value.
std::string name = "get_" + boost::lexical_cast<std::string>(_index);
initialStack[initialIdx] = m_bblock.m_builder.CreatePHI(Type::Word, 0, name);
*itemIter = initialStack[initialIdx];
}
return *itemIter;
}
void BasicBlock::LocalStack::set(size_t _index, llvm::Value* _word)
{
auto itemIter = getItemIterator(_index);
*itemIter = _word;
}
void BasicBlock::synchronizeLocalStack(Stack& _evmStack)
{
auto blockTerminator = m_llvmBB->getTerminator();
assert(blockTerminator != nullptr);
m_builder.SetInsertPoint(blockTerminator);
auto currIter = m_currentStack.begin();
auto endIter = m_currentStack.end();
// Update (emit set()) changed values
for (int idx = m_currentStack.size() - 1 - m_tosOffset;
currIter < endIter && idx >= 0;
++currIter, --idx)
{
assert(static_cast<size_t>(idx) < m_initialStack.size());
if (*currIter != m_initialStack[idx]) // value needs update
_evmStack.set(static_cast<size_t>(idx), *currIter);
}
if (m_tosOffset < 0)
{
// Pop values
_evmStack.pop(static_cast<size_t>(-m_tosOffset));
}
// Push new values
for (; currIter < endIter; ++currIter)
{
assert(*currIter != nullptr);
_evmStack.push(*currIter);
}
// Emit get() for all (used) values from the initial stack
for (size_t idx = 0; idx < m_initialStack.size(); ++idx)
{
auto val = m_initialStack[idx];
if (val == nullptr)
continue;
assert(llvm::isa<llvm::PHINode>(val));
llvm::PHINode* phi = llvm::cast<llvm::PHINode>(val);
if (! phi->use_empty())
{
// Insert call to get() just before the PHI node and replace
// the uses of PHI with the uses of this new instruction.
m_builder.SetInsertPoint(phi);
auto newVal = _evmStack.get(idx);
phi->replaceAllUsesWith(newVal);
}
phi->eraseFromParent();
}
// Reset the stack
m_initialStack.erase(m_initialStack.begin(), m_initialStack.end());
m_currentStack.erase(m_currentStack.begin(), m_currentStack.end());
m_tosOffset = 0;
}
void BasicBlock::linkLocalStacks(std::vector<BasicBlock*> basicBlocks, llvm::IRBuilder<>& _builder)
{
struct BBInfo
{
BasicBlock& bblock;
std::vector<BBInfo*> predecessors;
size_t inputItems;
size_t outputItems;
std::vector<llvm::PHINode*> phisToRewrite;
BBInfo(BasicBlock& _bblock) :
bblock(_bblock),
predecessors(),
inputItems(0),
outputItems(0)
{
auto& initialStack = bblock.m_initialStack;
for (auto it = initialStack.begin();
it != initialStack.end() && *it != nullptr;
++it, ++inputItems);
//if (bblock.localStack().m_tosOffset > 0)
// outputItems = bblock.localStack().m_tosOffset;
auto& exitStack = bblock.m_currentStack;
for (auto it = exitStack.rbegin();
it != exitStack.rend() && *it != nullptr;
++it, ++outputItems);
}
};
std::map<llvm::BasicBlock*, BBInfo> cfg;
// Create nodes in cfg
for (auto bb : basicBlocks)
cfg.emplace(bb->llvm(), *bb);
// Create edges in cfg: for each bb info fill the list
// of predecessor infos.
for (auto& pair : cfg)
{
auto bb = pair.first;
auto& info = pair.second;
for (auto predIt = llvm::pred_begin(bb); predIt != llvm::pred_end(bb); ++predIt)
{
auto predInfoEntry = cfg.find(*predIt);
if (predInfoEntry != cfg.end())
info.predecessors.push_back(&predInfoEntry->second);
}
}
// Iteratively compute inputs and outputs of each block, until reaching fixpoint.
bool valuesChanged = true;
while (valuesChanged)
{
if (getenv("EVMCC_DEBUG_BLOCKS"))
{
for (auto& pair : cfg)
std::cerr << pair.second.bblock.llvm()->getName().str()
<< ": in " << pair.second.inputItems
<< ", out " << pair.second.outputItems
<< "\n";
}
valuesChanged = false;
for (auto& pair : cfg)
{
auto& info = pair.second;
if (info.predecessors.empty())
info.inputItems = 0; // no consequences for other blocks, so leave valuesChanged false
for (auto predInfo : info.predecessors)
{
if (predInfo->outputItems < info.inputItems)
{
info.inputItems = predInfo->outputItems;
valuesChanged = true;
}
else if (predInfo->outputItems > info.inputItems)
{
predInfo->outputItems = info.inputItems;
valuesChanged = true;
}
}
}
}
// Propagate values between blocks.
for (auto& entry : cfg)
{
auto& info = entry.second;
auto& bblock = info.bblock;
llvm::BasicBlock::iterator fstNonPhi(bblock.llvm()->getFirstNonPHI());
auto phiIter = bblock.m_initialStack.begin();
for (size_t index = 0; index < info.inputItems; ++index, ++phiIter)
{
assert(llvm::isa<llvm::PHINode>(*phiIter));
auto phi = llvm::cast<llvm::PHINode>(*phiIter);
for (auto predIt : info.predecessors)
{
auto& predExitStack = predIt->bblock.m_currentStack;
auto value = *(predExitStack.end() - 1 - index);
phi->addIncoming(value, predIt->bblock.llvm());
}
// Move phi to the front
if (llvm::BasicBlock::iterator(phi) != bblock.llvm()->begin())
{
phi->removeFromParent();
_builder.SetInsertPoint(bblock.llvm(), bblock.llvm()->begin());
_builder.Insert(phi);
}
}
// The items pulled directly from predecessors block must be removed
// from the list of items that has to be popped from the initial stack.
auto& initialStack = bblock.m_initialStack;
initialStack.erase(initialStack.begin(), initialStack.begin() + info.inputItems);
// Initial stack shrinks, so the size difference grows:
bblock.m_tosOffset += info.inputItems;
}
// We must account for the items that were pushed directly to successor
// blocks and thus should not be on the list of items to be pushed onto
// to EVM stack
for (auto& entry : cfg)
{
auto& info = entry.second;
auto& bblock = info.bblock;
auto& exitStack = bblock.m_currentStack;
exitStack.erase(exitStack.end() - info.outputItems, exitStack.end());
bblock.m_tosOffset -= info.outputItems;
}
}
void BasicBlock::dump()
{
dump(std::cerr, false);
}
void BasicBlock::dump(std::ostream& _out, bool _dotOutput)
{
llvm::raw_os_ostream out(_out);
out << (_dotOutput ? "" : "Initial stack:\n");
for (auto val : m_initialStack)
{
if (val == nullptr)
out << " ?";
else if (llvm::isa<llvm::Instruction>(val))
out << *val;
else
out << " " << *val;
out << (_dotOutput ? "\\l" : "\n");
}
out << (_dotOutput ? "| " : "Instructions:\n");
for (auto ins = m_llvmBB->begin(); ins != m_llvmBB->end(); ++ins)
out << *ins << (_dotOutput ? "\\l" : "\n");
if (! _dotOutput)
out << "Current stack (offset = " << m_tosOffset << "):\n";
else
out << "|";
for (auto val = m_currentStack.rbegin(); val != m_currentStack.rend(); ++val)
{
if (*val == nullptr)
out << " ?";
else if (llvm::isa<llvm::Instruction>(*val))
out << **val;
else
out << " " << **val;
out << (_dotOutput ? "\\l" : "\n");
}
if (! _dotOutput)
out << " ...\n----------------------------------------\n";
}
}
}
}
|
#include "BasicBlock.h"
#include <iostream>
#include <llvm/IR/CFG.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/raw_os_ostream.h>
#include "Type.h"
namespace dev
{
namespace eth
{
namespace jit
{
const char* BasicBlock::NamePrefix = "Instr.";
BasicBlock::BasicBlock(ProgramCounter _beginInstIdx, ProgramCounter _endInstIdx, llvm::Function* _mainFunc, llvm::IRBuilder<>& _builder) :
m_beginInstIdx(_beginInstIdx),
m_endInstIdx(_endInstIdx),
m_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), {NamePrefix, std::to_string(_beginInstIdx)}, _mainFunc)),
m_stack(*this),
m_builder(_builder)
{}
BasicBlock::BasicBlock(std::string _name, llvm::Function* _mainFunc, llvm::IRBuilder<>& _builder) :
m_beginInstIdx(0),
m_endInstIdx(0),
m_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), _name, _mainFunc)),
m_stack(*this),
m_builder(_builder)
{}
BasicBlock::LocalStack::LocalStack(BasicBlock& _owner) :
m_bblock(_owner)
{}
void BasicBlock::LocalStack::push(llvm::Value* _value)
{
m_bblock.m_currentStack.push_back(_value);
m_bblock.m_tosOffset += 1;
}
llvm::Value* BasicBlock::LocalStack::pop()
{
auto result = get(0);
if (m_bblock.m_currentStack.size() > 0)
m_bblock.m_currentStack.pop_back();
m_bblock.m_tosOffset -= 1;
return result;
}
/**
* Pushes a copy of _index-th element (tos is 0-th elem).
*/
void BasicBlock::LocalStack::dup(size_t _index)
{
auto val = get(_index);
push(val);
}
/**
* Swaps tos with _index-th element (tos is 0-th elem).
* _index must be > 0.
*/
void BasicBlock::LocalStack::swap(size_t _index)
{
assert(_index > 0);
auto val = get(_index);
auto tos = get(0);
set(_index, tos);
set(0, val);
}
std::vector<llvm::Value*>::iterator BasicBlock::LocalStack::getItemIterator(size_t _index)
{
auto& currentStack = m_bblock.m_currentStack;
if (_index < currentStack.size())
return currentStack.end() - _index - 1;
// Need to map more elements from the EVM stack
auto nNewItems = 1 + _index - currentStack.size();
currentStack.insert(currentStack.begin(), nNewItems, nullptr);
return currentStack.end() - _index - 1;
}
llvm::Value* BasicBlock::LocalStack::get(size_t _index)
{
auto& initialStack = m_bblock.m_initialStack;
auto itemIter = getItemIterator(_index);
if (*itemIter == nullptr)
{
// Need to fetch a new item from the EVM stack
assert(static_cast<int>(_index) >= m_bblock.m_tosOffset);
size_t initialIdx = _index - m_bblock.m_tosOffset;
if (initialIdx >= initialStack.size())
{
auto nNewItems = 1 + initialIdx - initialStack.size();
initialStack.insert(initialStack.end(), nNewItems, nullptr);
}
assert(initialStack[initialIdx] == nullptr);
// Create a dummy value.
std::string name = "get_" + std::to_string(_index);
initialStack[initialIdx] = m_bblock.m_builder.CreatePHI(Type::Word, 0, std::move(name));
*itemIter = initialStack[initialIdx];
}
return *itemIter;
}
void BasicBlock::LocalStack::set(size_t _index, llvm::Value* _word)
{
auto itemIter = getItemIterator(_index);
*itemIter = _word;
}
void BasicBlock::synchronizeLocalStack(Stack& _evmStack)
{
auto blockTerminator = m_llvmBB->getTerminator();
assert(blockTerminator != nullptr);
m_builder.SetInsertPoint(blockTerminator);
auto currIter = m_currentStack.begin();
auto endIter = m_currentStack.end();
// Update (emit set()) changed values
for (int idx = m_currentStack.size() - 1 - m_tosOffset;
currIter < endIter && idx >= 0;
++currIter, --idx)
{
assert(static_cast<size_t>(idx) < m_initialStack.size());
if (*currIter != m_initialStack[idx]) // value needs update
_evmStack.set(static_cast<size_t>(idx), *currIter);
}
if (m_tosOffset < 0)
{
// Pop values
_evmStack.pop(static_cast<size_t>(-m_tosOffset));
}
// Push new values
for (; currIter < endIter; ++currIter)
{
assert(*currIter != nullptr);
_evmStack.push(*currIter);
}
// Emit get() for all (used) values from the initial stack
for (size_t idx = 0; idx < m_initialStack.size(); ++idx)
{
auto val = m_initialStack[idx];
if (val == nullptr)
continue;
assert(llvm::isa<llvm::PHINode>(val));
llvm::PHINode* phi = llvm::cast<llvm::PHINode>(val);
if (! phi->use_empty())
{
// Insert call to get() just before the PHI node and replace
// the uses of PHI with the uses of this new instruction.
m_builder.SetInsertPoint(phi);
auto newVal = _evmStack.get(idx);
phi->replaceAllUsesWith(newVal);
}
phi->eraseFromParent();
}
// Reset the stack
m_initialStack.erase(m_initialStack.begin(), m_initialStack.end());
m_currentStack.erase(m_currentStack.begin(), m_currentStack.end());
m_tosOffset = 0;
}
void BasicBlock::linkLocalStacks(std::vector<BasicBlock*> basicBlocks, llvm::IRBuilder<>& _builder)
{
struct BBInfo
{
BasicBlock& bblock;
std::vector<BBInfo*> predecessors;
size_t inputItems;
size_t outputItems;
std::vector<llvm::PHINode*> phisToRewrite;
BBInfo(BasicBlock& _bblock) :
bblock(_bblock),
predecessors(),
inputItems(0),
outputItems(0)
{
auto& initialStack = bblock.m_initialStack;
for (auto it = initialStack.begin();
it != initialStack.end() && *it != nullptr;
++it, ++inputItems);
//if (bblock.localStack().m_tosOffset > 0)
// outputItems = bblock.localStack().m_tosOffset;
auto& exitStack = bblock.m_currentStack;
for (auto it = exitStack.rbegin();
it != exitStack.rend() && *it != nullptr;
++it, ++outputItems);
}
};
std::map<llvm::BasicBlock*, BBInfo> cfg;
// Create nodes in cfg
for (auto bb : basicBlocks)
cfg.emplace(bb->llvm(), *bb);
// Create edges in cfg: for each bb info fill the list
// of predecessor infos.
for (auto& pair : cfg)
{
auto bb = pair.first;
auto& info = pair.second;
for (auto predIt = llvm::pred_begin(bb); predIt != llvm::pred_end(bb); ++predIt)
{
auto predInfoEntry = cfg.find(*predIt);
if (predInfoEntry != cfg.end())
info.predecessors.push_back(&predInfoEntry->second);
}
}
// Iteratively compute inputs and outputs of each block, until reaching fixpoint.
bool valuesChanged = true;
while (valuesChanged)
{
if (getenv("EVMCC_DEBUG_BLOCKS"))
{
for (auto& pair : cfg)
std::cerr << pair.second.bblock.llvm()->getName().str()
<< ": in " << pair.second.inputItems
<< ", out " << pair.second.outputItems
<< "\n";
}
valuesChanged = false;
for (auto& pair : cfg)
{
auto& info = pair.second;
if (info.predecessors.empty())
info.inputItems = 0; // no consequences for other blocks, so leave valuesChanged false
for (auto predInfo : info.predecessors)
{
if (predInfo->outputItems < info.inputItems)
{
info.inputItems = predInfo->outputItems;
valuesChanged = true;
}
else if (predInfo->outputItems > info.inputItems)
{
predInfo->outputItems = info.inputItems;
valuesChanged = true;
}
}
}
}
// Propagate values between blocks.
for (auto& entry : cfg)
{
auto& info = entry.second;
auto& bblock = info.bblock;
llvm::BasicBlock::iterator fstNonPhi(bblock.llvm()->getFirstNonPHI());
auto phiIter = bblock.m_initialStack.begin();
for (size_t index = 0; index < info.inputItems; ++index, ++phiIter)
{
assert(llvm::isa<llvm::PHINode>(*phiIter));
auto phi = llvm::cast<llvm::PHINode>(*phiIter);
for (auto predIt : info.predecessors)
{
auto& predExitStack = predIt->bblock.m_currentStack;
auto value = *(predExitStack.end() - 1 - index);
phi->addIncoming(value, predIt->bblock.llvm());
}
// Move phi to the front
if (llvm::BasicBlock::iterator(phi) != bblock.llvm()->begin())
{
phi->removeFromParent();
_builder.SetInsertPoint(bblock.llvm(), bblock.llvm()->begin());
_builder.Insert(phi);
}
}
// The items pulled directly from predecessors block must be removed
// from the list of items that has to be popped from the initial stack.
auto& initialStack = bblock.m_initialStack;
initialStack.erase(initialStack.begin(), initialStack.begin() + info.inputItems);
// Initial stack shrinks, so the size difference grows:
bblock.m_tosOffset += info.inputItems;
}
// We must account for the items that were pushed directly to successor
// blocks and thus should not be on the list of items to be pushed onto
// to EVM stack
for (auto& entry : cfg)
{
auto& info = entry.second;
auto& bblock = info.bblock;
auto& exitStack = bblock.m_currentStack;
exitStack.erase(exitStack.end() - info.outputItems, exitStack.end());
bblock.m_tosOffset -= info.outputItems;
}
}
void BasicBlock::dump()
{
dump(std::cerr, false);
}
void BasicBlock::dump(std::ostream& _out, bool _dotOutput)
{
llvm::raw_os_ostream out(_out);
out << (_dotOutput ? "" : "Initial stack:\n");
for (auto val : m_initialStack)
{
if (val == nullptr)
out << " ?";
else if (llvm::isa<llvm::Instruction>(val))
out << *val;
else
out << " " << *val;
out << (_dotOutput ? "\\l" : "\n");
}
out << (_dotOutput ? "| " : "Instructions:\n");
for (auto ins = m_llvmBB->begin(); ins != m_llvmBB->end(); ++ins)
out << *ins << (_dotOutput ? "\\l" : "\n");
if (! _dotOutput)
out << "Current stack (offset = " << m_tosOffset << "):\n";
else
out << "|";
for (auto val = m_currentStack.rbegin(); val != m_currentStack.rend(); ++val)
{
if (*val == nullptr)
out << " ?";
else if (llvm::isa<llvm::Instruction>(*val))
out << **val;
else
out << " " << **val;
out << (_dotOutput ? "\\l" : "\n");
}
if (! _dotOutput)
out << " ...\n----------------------------------------\n";
}
}
}
}
|
Remove usage of boost::lexical_cast
|
Remove usage of boost::lexical_cast
|
C++
|
mit
|
vaporry/cpp-ethereum,anthony-cros/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,smartbitcoin/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,joeldo/cpp-ethereum,smartbitcoin/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,yann300/cpp-ethereum,chfast/webthree-umbrella,programonauta/webthree-umbrella,ethers/cpp-ethereum,xeddmc/cpp-ethereum,programonauta/webthree-umbrella,LefterisJP/cpp-ethereum,smartbitcoin/cpp-ethereum,d-das/cpp-ethereum,johnpeter66/ethminer,vaporry/cpp-ethereum,eco/cpp-ethereum,karek314/cpp-ethereum,anthony-cros/cpp-ethereum,karek314/cpp-ethereum,expanse-project/cpp-expanse,Sorceror32/go-get--u-github.com-tools-godep,d-das/cpp-ethereum,expanse-org/cpp-expanse,gluk256/cpp-ethereum,anthony-cros/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,d-das/cpp-ethereum,gluk256/cpp-ethereum,ethers/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,LefterisJP/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,expanse-org/cpp-expanse,LefterisJP/webthree-umbrella,xeddmc/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,LefterisJP/cpp-ethereum,yann300/cpp-ethereum,joeldo/cpp-ethereum,LefterisJP/webthree-umbrella,eco/cpp-ethereum,LefterisJP/cpp-ethereum,expanse-project/cpp-expanse,subtly/cpp-ethereum-micro,expanse-project/cpp-expanse,karek314/cpp-ethereum,vaporry/webthree-umbrella,xeddmc/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,gluk256/cpp-ethereum,vaporry/evmjit,LefterisJP/cpp-ethereum,joeldo/cpp-ethereum,yann300/cpp-ethereum,subtly/cpp-ethereum-micro,karek314/cpp-ethereum,yann300/cpp-ethereum,d-das/cpp-ethereum,ethers/cpp-ethereum,LefterisJP/cpp-ethereum,joeldo/cpp-ethereum,vaporry/cpp-ethereum,gluk256/cpp-ethereum,expanse-org/cpp-expanse,xeddmc/cpp-ethereum,vaporry/cpp-ethereum,d-das/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,vaporry/cpp-ethereum,expanse-project/cpp-expanse,expanse-org/cpp-expanse,smartbitcoin/cpp-ethereum,joeldo/cpp-ethereum,expanse-org/cpp-expanse,eco/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,eco/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,joeldo/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,vaporry/evmjit,expanse-project/cpp-expanse,yann300/cpp-ethereum,anthony-cros/cpp-ethereum,ethers/cpp-ethereum,subtly/cpp-ethereum-micro,anthony-cros/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,karek314/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,eco/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,johnpeter66/ethminer,ethers/cpp-ethereum,gluk256/cpp-ethereum,subtly/cpp-ethereum-micro,johnpeter66/ethminer,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,d-das/cpp-ethereum,gluk256/cpp-ethereum,arkpar/webthree-umbrella,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,xeddmc/cpp-ethereum,subtly/cpp-ethereum-micro,expanse-project/cpp-expanse,smartbitcoin/cpp-ethereum,ethers/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,subtly/cpp-ethereum-micro,eco/cpp-ethereum,yann300/cpp-ethereum,smartbitcoin/cpp-ethereum,karek314/cpp-ethereum,expanse-org/cpp-expanse,xeddmc/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,anthony-cros/cpp-ethereum
|
f7a5a784f2b46d3d23e6bcf261891e8757f385fc
|
api/exportApi.cpp
|
api/exportApi.cpp
|
/*! \file exportApi.h
* \author Jared Hoberock
* \brief Implementation of exportApi function.
*/
#include "exportApi.h"
#include "Gotham.h"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;
// wrapper for Gotham::material()
void Gotham_material(Gotham &g, std::auto_ptr<Material> m)
{
g.material(m.get());
m.release();
} // end Gotham_material()
// tell boost which multMatrix we mean
typedef void (Gotham::*multMatrix_vector)(const std::vector<float>&);
// tell boost which loadMatrix we mean
typedef void (Gotham::*loadMatrix_vector)(const std::vector<float>&);
// tell boost which getMatrix we mean
typedef void (Gotham::*getMatrix_vector)(const std::vector<float>&);
// deal with overloaded Gotham::mesh
void (Gotham::*mesh2)(std::vector<float>&,
std::vector<unsigned int>&)
= &Gotham::mesh;
void (Gotham::*mesh3)(std::vector<float>&,
std::vector<float>&,
std::vector<unsigned int> &)
= &Gotham::mesh;
void exportGotham(void)
{
class_<Gotham>("Gotham")
.def("pushMatrix", &Gotham::pushMatrix)
.def("popMatrix", &Gotham::popMatrix)
.def("translate", &Gotham::translate)
.def("rotate", &Gotham::rotate)
.def("scale", &Gotham::scale)
.def("multMatrix", multMatrix_vector(&Gotham::multMatrix))
.def("loadMatrix", loadMatrix_vector(&Gotham::loadMatrix))
.def("getMatrix", getMatrix_vector(&Gotham::getMatrix))
.def("mesh", mesh2)
.def("mesh", mesh3)
.def("sphere", &Gotham::sphere)
.def("render", &Gotham::render)
.def("material", Gotham_material)
.def("attribute", &Gotham::attribute)
.def("pushAttributes", &Gotham::pushAttributes)
.def("popAttributes", &Gotham::popAttributes)
;
} // end exportGotham()
void exportMaterial(void)
{
class_<Material, std::auto_ptr<Material> >("Material")
;
} // end exportMaterial()
void exportVectorFloat(void)
{
class_<std::vector<float> >("vector_float")
.def(vector_indexing_suite<std::vector<float> >())
;
} // end exportVectorFloat()
void exportVectorUint(void)
{
class_<std::vector<unsigned int> >("vector_uint")
.def(vector_indexing_suite<std::vector<unsigned int> >())
;
} // end exportVectorUint()
void exportApi(void)
{
exportGotham();
exportMaterial();
exportVectorFloat();
exportVectorUint();
} // end exportApi()
BOOST_PYTHON_MODULE(gotham)
{
exportApi();
} // end BOOST_PYTHON_MODULE()
|
/*! \file exportApi.h
* \author Jared Hoberock
* \brief Implementation of exportApi function.
*/
#include "exportApi.h"
#include "Gotham.h"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;
// wrapper for Gotham::material()
// see http://www.boost.org/libs/python/doc/v2/faq.html#ownership
void Gotham_material(Gotham &g, std::auto_ptr<Material> m)
{
g.material(m.get());
m.release();
} // end Gotham_material()
// tell boost which multMatrix we mean
typedef void (Gotham::*multMatrix_vector)(const std::vector<float>&);
// tell boost which loadMatrix we mean
typedef void (Gotham::*loadMatrix_vector)(const std::vector<float>&);
// tell boost which getMatrix we mean
typedef void (Gotham::*getMatrix_vector)(const std::vector<float>&);
// deal with overloaded Gotham::mesh
void (Gotham::*mesh2)(std::vector<float>&,
std::vector<unsigned int>&)
= &Gotham::mesh;
void (Gotham::*mesh3)(std::vector<float>&,
std::vector<float>&,
std::vector<unsigned int> &)
= &Gotham::mesh;
void exportGotham(void)
{
class_<Gotham>("Gotham")
.def("pushMatrix", &Gotham::pushMatrix)
.def("popMatrix", &Gotham::popMatrix)
.def("translate", &Gotham::translate)
.def("rotate", &Gotham::rotate)
.def("scale", &Gotham::scale)
.def("multMatrix", multMatrix_vector(&Gotham::multMatrix))
.def("loadMatrix", loadMatrix_vector(&Gotham::loadMatrix))
.def("getMatrix", getMatrix_vector(&Gotham::getMatrix))
.def("mesh", mesh2)
.def("mesh", mesh3)
.def("sphere", &Gotham::sphere)
.def("render", &Gotham::render)
.def("material", Gotham_material)
.def("attribute", &Gotham::attribute)
.def("pushAttributes", &Gotham::pushAttributes)
.def("popAttributes", &Gotham::popAttributes)
;
} // end exportGotham()
void exportMaterial(void)
{
class_<Material, std::auto_ptr<Material> >("Material")
;
} // end exportMaterial()
void exportVectorFloat(void)
{
class_<std::vector<float> >("vector_float")
.def(vector_indexing_suite<std::vector<float> >())
;
} // end exportVectorFloat()
void exportVectorUint(void)
{
class_<std::vector<unsigned int> >("vector_uint")
.def(vector_indexing_suite<std::vector<unsigned int> >())
;
} // end exportVectorUint()
void exportApi(void)
{
exportGotham();
exportMaterial();
exportVectorFloat();
exportVectorUint();
} // end exportApi()
BOOST_PYTHON_MODULE(gotham)
{
exportApi();
} // end BOOST_PYTHON_MODULE()
|
Add reference to boost python FAQ.
|
Add reference to boost python FAQ.
git-svn-id: eeeef91d721e48f02083ec31b1220ddf564a51e4@1063 3bb10773-34f4-0310-b88c-ec9d511ba0d9
|
C++
|
apache-2.0
|
jaredhoberock/gotham,jaredhoberock/gotham,jaredhoberock/gotham,jaredhoberock/gotham,jaredhoberock/gotham
|
636fca3be1ad815858c9a6a9cf30495a16bad58b
|
DataSpec/DNAMP1/SCAN.hpp
|
DataSpec/DNAMP1/SCAN.hpp
|
#ifndef _DNAMP1_SCAN_HPP_
#define _DNAMP1_SCAN_HPP_
#include "../DNACommon/DNACommon.hpp"
#include "DNAMP1.hpp"
namespace Retro
{
namespace DNAMP1
{
struct SCAN : BigYAML
{
DECL_YAML
Value<atUint32> version;
Value<atUint32> magic;
UniqueID32 frame;
UniqueID32 string;
enum ScanSpeed
{ Normal, Slow };
Value<ScanSpeed> scanSpeed;
enum Category
{
None,
SpacePirateData,
ChozoLore,
Creatures,
Research
};
Value<Category> category;
Value<bool> isImportant;
struct Texture : BigYAML
{
DECL_YAML
UniqueID32 texture;
Value<float> appearanceRange;
enum Position
{
Pane0,
Pane1,
Pane2,
Pane3,
Pane01,
Pane12,
Pane23,
Pane012,
Pane123,
Pane0123,
Pane4,
Pane5,
Pane6,
Pane7,
Pane45,
Pane56,
Pane67,
Pane456,
Pane567,
Pane4567,
Invalid = -1
};
Value<Position> position;
Value<atUint32> width; // width of animation cell
Value<atUint32> height; // height of animation cell
Value<float> interval; // 0.0 - 1.0
Value<float> fadeDuration; // 0.0 - 1.0
};
Texture textures[4];
static bool Extract(PAKEntryReadStream& rs, const HECL::ProjectPath& outPath)
{
SCAN scan;
scan.read(rs);
FILE* fp = HECL::Fopen(outPath.getAbsolutePath().c_str(), _S("wb"));
scan.toYAMLFile(fp);
fclose(fp);
return true;
}
static void Name(const SpecBase& dataSpec,
PAKEntryReadStream& rs,
PAKRouter<PAKBridge>& pakRouter,
PAK::Entry& entry)
{
SCAN scan;
scan.read(rs);
if (scan.string)
{
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(scan.string);
ent->name = HECL::Format("SCAN_%s_strg", entry.id.toString().c_str());
}
for (int i=0 ; i<4 ; ++i)
{
const Texture& tex = scan.textures[i];
if (tex.texture)
{
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(tex.texture);
ent->name = HECL::Format("SCAN_%s_tex%d", entry.id.toString().c_str(), i+1);
}
}
}
};
}
}
#endif
|
#ifndef _DNAMP1_SCAN_HPP_
#define _DNAMP1_SCAN_HPP_
#include "../DNACommon/DNACommon.hpp"
#include "DNAMP1.hpp"
namespace Retro
{
namespace DNAMP1
{
static const std::vector<std::string> PaneNames =
{
"imagepane_pane0",
"imagepane_pane1",
"imagepane_pane2",
"imagepane_pane3",
"imagepane_pane01",
"imagepane_pane12",
"imagepane_pane23",
"imagepane_pane012",
"imagepane_pane123",
"imagepane_pane0123",
"imagepane_pane4",
"imagepane_pane5",
"imagepane_pane6",
"imagepane_pane7",
"imagepane_pane45",
"imagepane_pane56",
"imagepane_pane67",
"imagepane_pane456",
"imagepane_pane567",
"imagepane_pane4567"
};
struct SCAN : BigYAML
{
DECL_YAML
Value<atUint32> version;
Value<atUint32> magic;
UniqueID32 frame;
UniqueID32 string;
enum ScanSpeed
{ Normal, Slow };
Value<ScanSpeed> scanSpeed;
enum Category
{
None,
SpacePirateData,
ChozoLore,
Creatures,
Research
};
Value<Category> category;
Value<bool> isImportant;
struct Texture : BigYAML
{
Delete __delete;
UniqueID32 texture;
Value<float> appearanceRange;
Value<atUint32> position;
Value<atUint32> width; // width of animation cell
Value<atUint32> height; // height of animation cell
Value<float> interval; // 0.0 - 1.0
Value<float> fadeDuration; // 0.0 - 1.0
void read(Athena::io::IStreamReader& __dna_reader)
{
/* texture */
texture.read(__dna_reader);
/* appearanceRange */
appearanceRange = __dna_reader.readFloatBig();
/* position */
position = __dna_reader.readUint32Big();
/* width */
width = __dna_reader.readUint32Big();
/* height */
height = __dna_reader.readUint32Big();
/* interval */
interval = __dna_reader.readFloatBig();
/* fadeDuration */
fadeDuration = __dna_reader.readFloatBig();
}
void write(Athena::io::IStreamWriter& __dna_writer) const
{
/* texture */
texture.write(__dna_writer);
/* appearanceRange */
__dna_writer.writeFloatBig(appearanceRange);
/* position */
__dna_writer.writeUint32Big(position);
/* width */
__dna_writer.writeUint32Big(width);
/* height */
__dna_writer.writeUint32Big(height);
/* interval */
__dna_writer.writeFloatBig(interval);
/* fadeDuration */
__dna_writer.writeFloatBig(fadeDuration);
}
void fromYAML(Athena::io::YAMLDocReader& __dna_docin)
{
/* texture */
__dna_docin.enumerate("texture", texture);
/* appearanceRange */
appearanceRange = __dna_docin.readFloat("appearanceRange");
/* position */
std::string tmp = __dna_docin.readString("position");
auto idx = std::find(PaneNames.begin(), PaneNames.end(), tmp);
if (idx != PaneNames.end())
position = idx - PaneNames.begin();
else
position = -1;
/* width */
width = __dna_docin.readUint32("width");
/* height */
height = __dna_docin.readUint32("height");
/* interval */
interval = __dna_docin.readFloat("interval");
/* fadeDuration */
fadeDuration = __dna_docin.readFloat("fadeDuration");
}
void toYAML(Athena::io::YAMLDocWriter& __dna_docout) const
{
/* texture */
__dna_docout.enumerate("texture", texture);
/* appearanceRange */
__dna_docout.writeFloat("appearanceRange", appearanceRange);
/* position */
if (position != -1)
__dna_docout.writeString("position", PaneNames.at(position));
else
__dna_docout.writeString("position", "undefined");
/* width */
__dna_docout.writeUint32("width", width);
/* height */
__dna_docout.writeUint32("height", height);
/* interval */
__dna_docout.writeFloat("interval", interval);
/* fadeDuration */
__dna_docout.writeFloat("fadeDuration", fadeDuration);
}
const char* DNAType() { return "Retro::DNAMP1::SCAN::Texture"; }
size_t binarySize(size_t __isz) const
{
__isz = texture.binarySize(__isz);
return __isz + 24;
}
};
Texture textures[4];
static bool Extract(PAKEntryReadStream& rs, const HECL::ProjectPath& outPath)
{
SCAN scan;
scan.read(rs);
FILE* fp = HECL::Fopen(outPath.getAbsolutePath().c_str(), _S("wb"));
scan.toYAMLFile(fp);
fclose(fp);
return true;
}
static void Name(const SpecBase& dataSpec,
PAKEntryReadStream& rs,
PAKRouter<PAKBridge>& pakRouter,
PAK::Entry& entry)
{
SCAN scan;
scan.read(rs);
if (scan.string)
{
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(scan.string);
ent->name = HECL::Format("SCAN_%s_strg", entry.id.toString().c_str());
}
for (int i=0 ; i<4 ; ++i)
{
const Texture& tex = scan.textures[i];
if (tex.texture)
{
PAK::Entry* ent = (PAK::Entry*)pakRouter.lookupEntry(tex.texture);
ent->name = HECL::Format("SCAN_%s_tex%d", entry.id.toString().c_str(), i+1);
}
}
}
};
}
}
#endif
|
Store widget names rather than enumerator values
|
Store widget names rather than enumerator values
|
C++
|
mit
|
AxioDL/PathShagged,AxioDL/PathShagged,RetroView/PathShagged,RetroView/PathShagged,AxioDL/PathShagged,RetroView/PathShagged
|
d01585c07782394c2b58262f293188d375e2b89a
|
edante/motion_planning/src/await_transition.cpp
|
edante/motion_planning/src/await_transition.cpp
|
/**
* @file await_transition.cpp
* @brief AwaitTransition action server
* @author Alejandro Bordallo <[email protected]>
* @date 2015-06-08
* @copyright (MIT) 2015 Edinferno
*/
#include "motion_planning/await_transition.hpp"
AwaitTransitionAction::AwaitTransitionAction(ros::NodeHandle nh,
std::string name) :
nh_(nh),
as_(nh_, name, false),
action_name_(name) {
//register the goal and feeback callbacks
as_.registerGoalCallback(boost::bind(&AwaitTransitionAction::goalCB, this));
as_.registerPreemptCallback(boost::bind(&AwaitTransitionAction::preemptCB,
this));
chest_sub_ = nh_.subscribe("/sensing/chest", 1,
&AwaitTransitionAction::checkTransition,
this);
ROS_INFO("Starting AwaitTransition action server");
// this->init();
as_.start();
}
AwaitTransitionAction::~AwaitTransitionAction(void) {
}
void AwaitTransitionAction::init() {
chest_presses_ = 0;
}
void AwaitTransitionAction::goalCB() {
chest_presses_ = 0;
ROS_INFO("New Goal");
state_ = as_.acceptNewGoal()->state;
ROS_INFO("State: %i", state_);
}
void AwaitTransitionAction::preemptCB() {
ROS_INFO("Preempt");
}
void AwaitTransitionAction::checkTransition(const std_msgs::UInt8::ConstPtr&
msg) {
chest_presses_ = msg->data;
ROS_INFO("Executing goal for %s", action_name_.c_str());
bool going = true;
bool success = true;
if (as_.isPreemptRequested() || !ros::ok()) {
ROS_INFO("%s: Preempted", action_name_.c_str());
as_.setPreempted();
success = false;
going = false;
}
while (going) {
ROS_INFO("Checking");
if (chest_presses_ == 1) {
ROS_INFO("Chest Button once");
if (state_ == GameState::INITIAL ||
state_ == GameState::PENALIZED ||
state_ == GameState::PLAYING)
{going = false;}
} else if (chest_presses_ == 2) {
ROS_INFO("Chest Button twice");
going = false;
} else if (chest_presses_ == 3) {
ROS_INFO("Chest Button thrice");
going = false;
}
usleep(100000);
}
if (success) {
result_.success = true;
ROS_INFO("%s: Succeeded!", action_name_.c_str());
as_.setSucceeded(result_);
} else {
result_.success = false;
ROS_INFO("%s: Failed!", action_name_.c_str());
as_.setSucceeded(result_);
}
}
|
/**
* @file await_transition.cpp
* @brief AwaitTransition action server
* @author Alejandro Bordallo <[email protected]>
* @date 2015-06-08
* @copyright (MIT) 2015 Edinferno
*/
#include "motion_planning/await_transition.hpp"
AwaitTransitionAction::AwaitTransitionAction(ros::NodeHandle nh,
std::string name) :
nh_(nh),
as_(nh_, name, false),
action_name_(name) {
//register the goal and feeback callbacks
as_.registerGoalCallback(boost::bind(&AwaitTransitionAction::goalCB, this));
as_.registerPreemptCallback(boost::bind(&AwaitTransitionAction::preemptCB,
this));
chest_sub_ = nh_.subscribe("/sensing/chest", 1,
&AwaitTransitionAction::checkTransition,
this);
ROS_INFO("Starting AwaitTransition action server");
// this->init();
as_.start();
}
AwaitTransitionAction::~AwaitTransitionAction(void) {
}
void AwaitTransitionAction::init() {
chest_presses_ = 0;
}
void AwaitTransitionAction::goalCB() {
chest_presses_ = 0;
state_ = as_.acceptNewGoal()->state;
}
void AwaitTransitionAction::preemptCB() {
ROS_INFO("Preempt");
as_.setPreempted();
}
void AwaitTransitionAction::checkTransition(const std_msgs::UInt8::ConstPtr&
msg) {
chest_presses_ = msg->data;
ROS_INFO("Executing goal for %s", action_name_.c_str());
bool going = true;
bool success = true;
if (as_.isPreemptRequested() || !ros::ok()) {
ROS_INFO("%s: Preempted", action_name_.c_str());
as_.setPreempted();
success = false;
going = false;
}
if (chest_presses_ == 1) {
ROS_INFO("Chest Button once");
if (state_ == GameState::INITIAL ||
state_ == GameState::PENALIZED ||
state_ == GameState::PLAYING)
{going = false;}
} else if (chest_presses_ == 2) {
ROS_INFO("Chest Button twice");
going = false;
} else if (chest_presses_ == 3) {
ROS_INFO("Chest Button thrice");
going = false;
}
if (success) {
result_.success = true;
ROS_INFO("%s: Succeeded!", action_name_.c_str());
as_.setSucceeded(result_);
} else {
result_.success = false;
ROS_INFO("%s: Failed!", action_name_.c_str());
as_.setSucceeded(result_);
}
}
|
Remove unnecessary poll and wait for checking button press, now callback
|
Remove unnecessary poll and wait for checking button press, now callback
|
C++
|
mit
|
edinferno/edinferno,edinferno/edinferno,edinferno/edinferno,edinferno/edinferno
|
47f869b731d7821f02eb601e409bd3ce347ed30b
|
editor/plugins/baked_lightmap_editor_plugin.cpp
|
editor/plugins/baked_lightmap_editor_plugin.cpp
|
/*************************************************************************/
/* baked_lightmap_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "baked_lightmap_editor_plugin.h"
void BakedLightmapEditorPlugin::_bake_select_file(const String &p_file) {
if (lightmap) {
BakedLightmap::BakeError err;
if (get_tree()->get_edited_scene_root() && get_tree()->get_edited_scene_root() == lightmap) {
err = lightmap->bake(lightmap, p_file);
} else {
err = lightmap->bake(lightmap->get_parent(), p_file);
}
bake_func_end();
switch (err) {
case BakedLightmap::BAKE_ERROR_NO_SAVE_PATH: {
String scene_path = lightmap->get_filename();
if (scene_path == String()) {
scene_path = lightmap->get_owner()->get_filename();
}
if (scene_path == String()) {
EditorNode::get_singleton()->show_warning(TTR("Can't determine a save path for lightmap images.\nSave your scene and try again."));
break;
}
scene_path = scene_path.get_basename() + ".lmbake";
file_dialog->set_current_path(scene_path);
file_dialog->popup_centered_ratio();
} break;
case BakedLightmap::BAKE_ERROR_NO_MESHES:
EditorNode::get_singleton()->show_warning(TTR("No meshes to bake. Make sure they contain an UV2 channel and that the 'Bake Light' flag is on."));
break;
case BakedLightmap::BAKE_ERROR_CANT_CREATE_IMAGE:
EditorNode::get_singleton()->show_warning(TTR("Failed creating lightmap images, make sure path is writable."));
break;
case BakedLightmap::BAKE_ERROR_LIGHTMAP_SIZE:
EditorNode::get_singleton()->show_warning(TTR("Failed determining lightmap size. Maximum lightmap size too small?"));
break;
case BakedLightmap::BAKE_ERROR_INVALID_MESH:
EditorNode::get_singleton()->show_warning(TTR("Some mesh is invalid. Make sure the UV2 channel values are contained within the [0.0,1.0] square region."));
break;
case BakedLightmap::BAKE_ERROR_NO_LIGHTMAPPER:
EditorNode::get_singleton()->show_warning(TTR("Godot editor was built without ray tracing support, lightmaps can't be baked."));
break;
default: {
}
}
}
}
void BakedLightmapEditorPlugin::_bake() {
_bake_select_file("");
}
void BakedLightmapEditorPlugin::edit(Object *p_object) {
BakedLightmap *s = Object::cast_to<BakedLightmap>(p_object);
if (!s)
return;
lightmap = s;
}
bool BakedLightmapEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("BakedLightmap");
}
void BakedLightmapEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
bake->show();
} else {
bake->hide();
}
}
EditorProgress *BakedLightmapEditorPlugin::tmp_progress = NULL;
EditorProgress *BakedLightmapEditorPlugin::tmp_subprogress = NULL;
bool BakedLightmapEditorPlugin::bake_func_step(float p_progress, const String &p_description, void *, bool p_force_refresh) {
if (!tmp_progress) {
tmp_progress = memnew(EditorProgress("bake_lightmaps", TTR("Bake Lightmaps"), 1000, true));
ERR_FAIL_COND_V(tmp_progress == nullptr, false);
}
return tmp_progress->step(p_description, p_progress * 1000, p_force_refresh);
}
bool BakedLightmapEditorPlugin::bake_func_substep(float p_progress, const String &p_description, void *, bool p_force_refresh) {
if (!tmp_subprogress) {
tmp_subprogress = memnew(EditorProgress("bake_lightmaps_substep", "", 1000, true));
ERR_FAIL_COND_V(tmp_subprogress == nullptr, false);
}
return tmp_subprogress->step(p_description, p_progress * 1000, p_force_refresh);
}
void BakedLightmapEditorPlugin::bake_func_end() {
if (tmp_progress != nullptr) {
memdelete(tmp_progress);
tmp_progress = nullptr;
}
if (tmp_subprogress != nullptr) {
memdelete(tmp_subprogress);
tmp_subprogress = nullptr;
}
}
void BakedLightmapEditorPlugin::_bind_methods() {
ClassDB::bind_method("_bake", &BakedLightmapEditorPlugin::_bake);
ClassDB::bind_method("_bake_select_file", &BakedLightmapEditorPlugin::_bake_select_file);
}
BakedLightmapEditorPlugin::BakedLightmapEditorPlugin(EditorNode *p_node) {
editor = p_node;
bake = memnew(ToolButton);
bake->set_icon(editor->get_gui_base()->get_icon("Bake", "EditorIcons"));
bake->set_text(TTR("Bake Lightmaps"));
bake->hide();
bake->connect("pressed", this, "_bake");
file_dialog = memnew(EditorFileDialog);
file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
file_dialog->add_filter("*.lmbake ; LightMap Bake");
file_dialog->set_title(TTR("Select lightmap bake file:"));
file_dialog->connect("file_selected", this, "_bake_select_file");
bake->add_child(file_dialog);
add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, bake);
lightmap = NULL;
BakedLightmap::bake_step_function = bake_func_step;
BakedLightmap::bake_substep_function = bake_func_substep;
}
BakedLightmapEditorPlugin::~BakedLightmapEditorPlugin() {
}
|
/*************************************************************************/
/* baked_lightmap_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "baked_lightmap_editor_plugin.h"
void BakedLightmapEditorPlugin::_bake_select_file(const String &p_file) {
if (lightmap) {
BakedLightmap::BakeError err;
if (get_tree()->get_edited_scene_root() && get_tree()->get_edited_scene_root() == lightmap) {
err = lightmap->bake(lightmap, p_file);
} else {
err = lightmap->bake(lightmap->get_parent(), p_file);
}
bake_func_end();
switch (err) {
case BakedLightmap::BAKE_ERROR_NO_SAVE_PATH: {
String scene_path = lightmap->get_filename();
if (scene_path == String()) {
scene_path = lightmap->get_owner()->get_filename();
}
if (scene_path == String()) {
EditorNode::get_singleton()->show_warning(TTR("Can't determine a save path for lightmap images.\nSave your scene and try again."));
break;
}
scene_path = scene_path.get_basename() + ".lmbake";
file_dialog->set_current_path(scene_path);
file_dialog->popup_centered_ratio();
} break;
case BakedLightmap::BAKE_ERROR_NO_MESHES:
EditorNode::get_singleton()->show_warning(TTR("No meshes to bake. Make sure they contain an UV2 channel and that the 'Bake Light' flag is on."));
break;
case BakedLightmap::BAKE_ERROR_CANT_CREATE_IMAGE:
EditorNode::get_singleton()->show_warning(TTR("Failed creating lightmap images, make sure path is writable."));
break;
case BakedLightmap::BAKE_ERROR_LIGHTMAP_SIZE:
EditorNode::get_singleton()->show_warning(TTR("Failed determining lightmap size. Maximum lightmap size too small?"));
break;
case BakedLightmap::BAKE_ERROR_INVALID_MESH:
EditorNode::get_singleton()->show_warning(TTR("Some mesh is invalid. Make sure the UV2 channel values are contained within the [0.0,1.0] square region."));
break;
case BakedLightmap::BAKE_ERROR_NO_LIGHTMAPPER:
#ifdef OSX_ENABLED
EditorNode::get_singleton()->show_warning(TTR("Godot editor was built without ray tracing support; lightmaps can't be baked.\nIf you are using an Apple Silicon-based Mac, try forcing Rosetta emulation on Godot.app in the application settings\nthen restart the editor."));
#else
EditorNode::get_singleton()->show_warning(TTR("Godot editor was built without ray tracing support; lightmaps can't be baked."));
#endif
break;
default: {
}
}
}
}
void BakedLightmapEditorPlugin::_bake() {
_bake_select_file("");
}
void BakedLightmapEditorPlugin::edit(Object *p_object) {
BakedLightmap *s = Object::cast_to<BakedLightmap>(p_object);
if (!s)
return;
lightmap = s;
}
bool BakedLightmapEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("BakedLightmap");
}
void BakedLightmapEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
bake->show();
} else {
bake->hide();
}
}
EditorProgress *BakedLightmapEditorPlugin::tmp_progress = NULL;
EditorProgress *BakedLightmapEditorPlugin::tmp_subprogress = NULL;
bool BakedLightmapEditorPlugin::bake_func_step(float p_progress, const String &p_description, void *, bool p_force_refresh) {
if (!tmp_progress) {
tmp_progress = memnew(EditorProgress("bake_lightmaps", TTR("Bake Lightmaps"), 1000, true));
ERR_FAIL_COND_V(tmp_progress == nullptr, false);
}
return tmp_progress->step(p_description, p_progress * 1000, p_force_refresh);
}
bool BakedLightmapEditorPlugin::bake_func_substep(float p_progress, const String &p_description, void *, bool p_force_refresh) {
if (!tmp_subprogress) {
tmp_subprogress = memnew(EditorProgress("bake_lightmaps_substep", "", 1000, true));
ERR_FAIL_COND_V(tmp_subprogress == nullptr, false);
}
return tmp_subprogress->step(p_description, p_progress * 1000, p_force_refresh);
}
void BakedLightmapEditorPlugin::bake_func_end() {
if (tmp_progress != nullptr) {
memdelete(tmp_progress);
tmp_progress = nullptr;
}
if (tmp_subprogress != nullptr) {
memdelete(tmp_subprogress);
tmp_subprogress = nullptr;
}
}
void BakedLightmapEditorPlugin::_bind_methods() {
ClassDB::bind_method("_bake", &BakedLightmapEditorPlugin::_bake);
ClassDB::bind_method("_bake_select_file", &BakedLightmapEditorPlugin::_bake_select_file);
}
BakedLightmapEditorPlugin::BakedLightmapEditorPlugin(EditorNode *p_node) {
editor = p_node;
bake = memnew(ToolButton);
bake->set_icon(editor->get_gui_base()->get_icon("Bake", "EditorIcons"));
bake->set_text(TTR("Bake Lightmaps"));
bake->hide();
bake->connect("pressed", this, "_bake");
file_dialog = memnew(EditorFileDialog);
file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
file_dialog->add_filter("*.lmbake ; LightMap Bake");
file_dialog->set_title(TTR("Select lightmap bake file:"));
file_dialog->connect("file_selected", this, "_bake_select_file");
bake->add_child(file_dialog);
add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, bake);
lightmap = NULL;
BakedLightmap::bake_step_function = bake_func_step;
BakedLightmap::bake_substep_function = bake_func_substep;
}
BakedLightmapEditorPlugin::~BakedLightmapEditorPlugin() {
}
|
Tweak lightmapper warning message to mention Rosetta emulation on macOS
|
Tweak lightmapper warning message to mention Rosetta emulation on macOS
|
C++
|
mit
|
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
|
1f4137531f6a7d3a5ac3b50891ca4b911281ad81
|
src/test/netbase_tests.cpp
|
src/test/netbase_tests.cpp
|
#include <boost/test/unit_test.hpp>
#include <string>
#include <vector>
#include "netbase.h"
using namespace std;
BOOST_AUTO_TEST_SUITE(netbase_tests)
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4());
BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(CNetAddr("::1").IsIPv6());
BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918());
BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918());
BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918());
BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849());
BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927());
BOOST_CHECK(CNetAddr("2002::1").IsRFC3964());
BOOST_CHECK(CNetAddr("FC00::").IsRFC4193());
BOOST_CHECK(CNetAddr("2001::2").IsRFC4380());
BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843());
BOOST_CHECK(CNetAddr("FE80::").IsRFC4862());
BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052());
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal());
BOOST_CHECK(CNetAddr("::1").IsLocal());
BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable());
BOOST_CHECK(CNetAddr("2001::1").IsRoutable());
BOOST_CHECK(CNetAddr("127.0.0.1").IsValid());
}
bool static TestSplitHost(string test, string host, int port)
{
string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.coingen.io", "www.coingen.io", -1));
BOOST_CHECK(TestSplitHost("[www.coingen.io]", "www.coingen.io", -1));
BOOST_CHECK(TestSplitHost("www.coingen.io:80", "www.coingen.io", 80));
BOOST_CHECK(TestSplitHost("[www.coingen.io]:80", "www.coingen.io", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:19985", "127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:19985", "127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:19985", "::ffff:127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("[::]:19985", "::", 19985));
BOOST_CHECK(TestSplitHost("::19985", "::19985", -1));
BOOST_CHECK(TestSplitHost(":19985", "", 19985));
BOOST_CHECK(TestSplitHost("[]:19985", "", 19985));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(string src, string canon)
{
CService addr;
if (!LookupNumeric(src.c_str(), addr, 65535))
return canon == "";
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:19985", "127.0.0.1:19985"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:19985", "[::]:19985"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", ""));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1("5wyqrzbvrdsumnok.onion");
CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca");
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <boost/test/unit_test.hpp>
#include <string>
#include <vector>
#include "netbase.h"
using namespace std;
BOOST_AUTO_TEST_SUITE(netbase_tests)
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4());
BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(CNetAddr("::1").IsIPv6());
BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918());
BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918());
BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918());
BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849());
BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927());
BOOST_CHECK(CNetAddr("2002::1").IsRFC3964());
BOOST_CHECK(CNetAddr("FC00::").IsRFC4193());
BOOST_CHECK(CNetAddr("2001::2").IsRFC4380());
BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843());
BOOST_CHECK(CNetAddr("FE80::").IsRFC4862());
BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052());
BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal());
BOOST_CHECK(CNetAddr("::1").IsLocal());
BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable());
BOOST_CHECK(CNetAddr("2001::1").IsRoutable());
BOOST_CHECK(CNetAddr("127.0.0.1").IsValid());
}
bool static TestSplitHost(string test, string host, int port)
{
string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.dobbscoin.info", "dobbscoin.info", -1));
BOOST_CHECK(TestSplitHost("[www.dobbscoin.info]", "dobbscoin.info", -1));
BOOST_CHECK(TestSplitHost("www.dobbscoin.info:80", "dobbscoin.info", 80));
BOOST_CHECK(TestSplitHost("[www.dobbscoin.info]:80", "www.dobbscoin.info", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:19985", "127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:19985", "127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:19985", "::ffff:127.0.0.1", 19985));
BOOST_CHECK(TestSplitHost("[::]:19985", "::", 19985));
BOOST_CHECK(TestSplitHost("::19985", "::19985", -1));
BOOST_CHECK(TestSplitHost(":19985", "", 19985));
BOOST_CHECK(TestSplitHost("[]:19985", "", 19985));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(string src, string canon)
{
CService addr;
if (!LookupNumeric(src.c_str(), addr, 65535))
return canon == "";
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:19985", "127.0.0.1:19985"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:19985", "[::]:19985"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", ""));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1("5wyqrzbvrdsumnok.onion");
CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca");
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_SUITE_END()
|
Update netbase_tests.cpp
|
Update netbase_tests.cpp
URL branding
|
C++
|
mit
|
Earlz/dobbscoin-source,dobbscoin/dobbscoin-source,dobbscoin/dobbscoin-source,Earlz/dobbscoin-source,dobbscoin/dobbscoin-source,dobbscoin/dobbscoin-source,dobbscoin/dobbscoin-source,Earlz/dobbscoin-source,dobbscoin/dobbscoin-source,Earlz/dobbscoin-source,Earlz/dobbscoin-source,Earlz/dobbscoin-source
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.