text
stringlengths 54
60.6k
|
---|
<commit_before>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <sstream>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(std::string s, std::string delim, size_t count)
{
if(delim.empty())
{
s = remove_extra_whitespace(s);
delim = " ";
}
if(s.empty())
{
return {};
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index - start_index));
start_index = std::min(end_index, s.size()) + delim.size();
++split_count;
}
if(start_index <= s.size())
{
result.push_back(s.substr(start_index));
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::ends_with(const std::string& s, const std::string& ending)
{
return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
std::string s2 = trim_outer_whitespace(s);
std::replace_if(s2.begin(), s2.end(), [](auto c) { return String::contains(whitespace, c); }, ' ');
std::string result;
std::copy_if(s2.begin(), s2.end(), std::back_inserter(result),
[&result](auto c)
{
return c != ' ' || result.back() != ' ';
});
return result;
}
std::string String::strip_comments(const std::string& str, const std::string& comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + std::string{start} + std::string{end});
}
if(start_comment_index >= end_comment_index)
{
throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + std::string{start} + std::string{end});
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + end.size());
try
{
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
catch(const std::invalid_argument& e)
{
throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str);
}
}
std::string String::lowercase(std::string s)
{
for(auto& c : s){ c = std::tolower(c); }
return s;
}
std::string String::format_integer(int n, const std::string& separator)
{
if(n < 0)
{
return '-' + format_integer(-n, separator);
}
else
{
auto s = std::to_string(n);
auto group_size = 3;
auto index = s.size() % group_size;
index = (index == 0 ? group_size : index);
auto result = s.substr(0, index);
for( ; index < s.size(); index += group_size)
{
result += separator;
result += s.substr(index, group_size);
}
return result;
}
}
size_t String::string_to_size_t(const std::string& s)
{
size_t characters_used;
auto result =
#ifdef __linux__
std::stoul(s, &characters_used);
#elif defined(_WIN64)
std::stoull(s, &characters_used);
#else
std::stoi(s, &characters_used);
#endif
if( ! String::trim_outer_whitespace(s.substr(characters_used)).empty())
{
throw std::invalid_argument("Non-numeric characters in string: " + s);
}
return result;
}
std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time,
const std::string& format)
{
auto time_c = std::chrono::system_clock::to_time_t(point_in_time);
std::tm time_out;
#ifdef _WIN32
localtime_s(&time_out, &time_c);
#elif defined(__linux__)
localtime_r(&time_c, &time_out);
#endif
auto ss = std::ostringstream{};
ss << std::put_time(&time_out, format.c_str());
return ss.str();
}
<commit_msg>Delete unneeded type conversion<commit_after>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <sstream>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(std::string s, std::string delim, size_t count)
{
if(delim.empty())
{
s = remove_extra_whitespace(s);
delim = " ";
}
if(s.empty())
{
return {};
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index - start_index));
start_index = std::min(end_index, s.size()) + delim.size();
++split_count;
}
if(start_index <= s.size())
{
result.push_back(s.substr(start_index));
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::ends_with(const std::string& s, const std::string& ending)
{
return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
std::string s2 = trim_outer_whitespace(s);
std::replace_if(s2.begin(), s2.end(), [](auto c) { return String::contains(whitespace, c); }, ' ');
std::string result;
std::copy_if(s2.begin(), s2.end(), std::back_inserter(result),
[&result](auto c)
{
return c != ' ' || result.back() != ' ';
});
return result;
}
std::string String::strip_comments(const std::string& str, const std::string& comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + start + end);
}
if(start_comment_index >= end_comment_index)
{
throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + start + end);
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + end.size());
try
{
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
catch(const std::invalid_argument& e)
{
throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str);
}
}
std::string String::lowercase(std::string s)
{
for(auto& c : s){ c = std::tolower(c); }
return s;
}
std::string String::format_integer(int n, const std::string& separator)
{
if(n < 0)
{
return '-' + format_integer(-n, separator);
}
else
{
auto s = std::to_string(n);
auto group_size = 3;
auto index = s.size() % group_size;
index = (index == 0 ? group_size : index);
auto result = s.substr(0, index);
for( ; index < s.size(); index += group_size)
{
result += separator;
result += s.substr(index, group_size);
}
return result;
}
}
size_t String::string_to_size_t(const std::string& s)
{
size_t characters_used;
auto result =
#ifdef __linux__
std::stoul(s, &characters_used);
#elif defined(_WIN64)
std::stoull(s, &characters_used);
#else
std::stoi(s, &characters_used);
#endif
if( ! String::trim_outer_whitespace(s.substr(characters_used)).empty())
{
throw std::invalid_argument("Non-numeric characters in string: " + s);
}
return result;
}
std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time,
const std::string& format)
{
auto time_c = std::chrono::system_clock::to_time_t(point_in_time);
std::tm time_out;
#ifdef _WIN32
localtime_s(&time_out, &time_c);
#elif defined(__linux__)
localtime_r(&time_c, &time_out);
#endif
auto ss = std::ostringstream{};
ss << std::put_time(&time_out, format.c_str());
return ss.str();
}
<|endoftext|> |
<commit_before>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <cmath>
namespace
{
const auto whitespace = std::string{" \t\n\r"};
}
std::vector<std::string> String::split(const std::string& s, const std::string& delim, const size_t count) noexcept
{
if(delim.empty())
{
return split(remove_extra_whitespace(s), " ", count);
}
if(s.empty())
{
return {};
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index - start_index));
start_index = std::min(end_index, s.size()) + delim.size();
++split_count;
}
if(start_index <= s.size())
{
result.push_back(s.substr(start_index));
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning) noexcept
{
return std::mismatch(beginning.begin(), beginning.end(), s.begin(), s.end()).first == beginning.end();
}
std::string String::trim_outer_whitespace(const std::string& s) noexcept
{
const auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
const auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s) noexcept
{
std::string s2 = trim_outer_whitespace(s);
std::replace_if(s2.begin(), s2.end(), [](auto c) { return String::contains(whitespace, c); }, ' ');
std::string result;
std::copy_if(s2.begin(), s2.end(), std::back_inserter(result),
[&result](auto c)
{
return c != ' ' || result.back() != ' ';
});
return result;
}
std::string String::strip_comments(const std::string& str, const std::string& comment) noexcept
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
const auto start_comment_index = str.find(start);
const auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + start + end);
}
if(start_comment_index >= end_comment_index)
{
throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + start + end);
}
try
{
const auto first_part = str.substr(0, start_comment_index);
const auto last_part = str.substr(end_comment_index + end.size());
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
catch(const std::invalid_argument& e)
{
throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str);
}
}
std::string String::strip_nested_block_comments(const std::string& str, const std::string& start, const std::string& end)
{
if(contains(start, end) || contains(end, start))
{
throw std::invalid_argument("Delimiters cannot share substrings: " + start + "," + end + ".");
}
const auto error_message = "Invalid nesting of delimiters " + start + "," + end + ": " + str;
std::string result;
auto depth = 0;
size_t index = 0;
while(index < str.size())
{
auto start_index = str.find(start, index);
auto end_index = str.find(end, index);
if(start_index < end_index)
{
if(depth == 0)
{
result += str.substr(index, start_index - index);
}
++depth;
index = start_index + start.size();
}
else if(end_index < start_index)
{
if(depth == 0)
{
throw std::invalid_argument(error_message);
}
--depth;
index = end_index + end.size();
}
else // start_index == end_index == std::string::npos
{
result += str.substr(index);
break;
}
}
if(depth != 0)
{
throw std::invalid_argument(error_message);
}
return result;
}
std::string String::remove_pgn_comments(const std::string& line)
{
const auto index = line.find_first_of(";({");
const auto delimiter = index < std::string::npos ? line[index] : '\0';
switch(delimiter)
{
case ';' : return remove_pgn_comments(strip_comments(line, ";"));
case '(' : return remove_pgn_comments(strip_nested_block_comments(line, "(", ")"));
case '{' : return remove_pgn_comments(strip_block_comment(line, "{", "}"));
default : return remove_extra_whitespace(line);
}
}
std::string String::extract_delimited_text(const std::string& str, const std::string& start, const std::string& end)
{
const auto start_split = split(str, start, 1);
if(start_split.size() != 2)
{
throw std::invalid_argument("Starting delimiter not found in \"" + str + "\": " + start + " " + end);
}
const auto start_of_inside = start_split[1];
const auto inside_split = split(start_of_inside, end, 1);
if(inside_split.size() != 2)
{
throw std::invalid_argument("Ending delimiter not found in \"" + str + "\": " + start + " " + end);
}
return inside_split[0];
}
char String::tolower(const char letter) noexcept
{
return char(std::tolower(letter));
}
char String::toupper(const char letter) noexcept
{
return char(std::toupper(letter));
}
std::string String::lowercase(std::string s) noexcept
{
std::transform(s.begin(), s.end(), s.begin(), String::tolower);
return s;
}
std::string String::round_to_decimals(const double x, const size_t decimal_places) noexcept
{
auto result = std::ostringstream();
result << std::fixed << std::setprecision(int(decimal_places)) << x;
return result.str();
}
std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time,
const std::string& format) noexcept
{
const auto time_c = std::chrono::system_clock::to_time_t(point_in_time);
std::tm time_out;
#ifdef _WIN32
localtime_s(&time_out, &time_c);
#elif defined(__linux__)
localtime_r(&time_c, &time_out);
#endif
auto ss = std::ostringstream{};
ss << std::put_time(&time_out, format.c_str());
return ss.str();
}
std::string String::add_to_file_name(const std::string& original_file_name, const std::string& addition) noexcept
{
const auto dot_index = std::min(original_file_name.find_last_of('.'), original_file_name.size());
return original_file_name.substr(0, dot_index) + addition + original_file_name.substr(dot_index);
}
<commit_msg>Simplify String::remove_extra_whitespace()<commit_after>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <cmath>
namespace
{
const auto whitespace = std::string{" \t\n\r"};
}
std::vector<std::string> String::split(const std::string& s, const std::string& delim, const size_t count) noexcept
{
if(delim.empty())
{
return split(remove_extra_whitespace(s), " ", count);
}
if(s.empty())
{
return {};
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index - start_index));
start_index = std::min(end_index, s.size()) + delim.size();
++split_count;
}
if(start_index <= s.size())
{
result.push_back(s.substr(start_index));
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning) noexcept
{
return std::mismatch(beginning.begin(), beginning.end(), s.begin(), s.end()).first == beginning.end();
}
std::string String::trim_outer_whitespace(const std::string& s) noexcept
{
const auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
const auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s) noexcept
{
std::string result;
std::copy_if(s.begin(), s.end(), std::back_inserter(result),
[&result](auto c)
{
return ! isspace(c) || ( ! result.empty() && ! std::isspace(result.back()));
});
return trim_outer_whitespace(result);
}
std::string String::strip_comments(const std::string& str, const std::string& comment) noexcept
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
const auto start_comment_index = str.find(start);
const auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + start + end);
}
if(start_comment_index >= end_comment_index)
{
throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + start + end);
}
try
{
const auto first_part = str.substr(0, start_comment_index);
const auto last_part = str.substr(end_comment_index + end.size());
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
catch(const std::invalid_argument& e)
{
throw std::invalid_argument(e.what() + std::string("\nOriginal line: ") + str);
}
}
std::string String::strip_nested_block_comments(const std::string& str, const std::string& start, const std::string& end)
{
if(contains(start, end) || contains(end, start))
{
throw std::invalid_argument("Delimiters cannot share substrings: " + start + "," + end + ".");
}
const auto error_message = "Invalid nesting of delimiters " + start + "," + end + ": " + str;
std::string result;
auto depth = 0;
size_t index = 0;
while(index < str.size())
{
auto start_index = str.find(start, index);
auto end_index = str.find(end, index);
if(start_index < end_index)
{
if(depth == 0)
{
result += str.substr(index, start_index - index);
}
++depth;
index = start_index + start.size();
}
else if(end_index < start_index)
{
if(depth == 0)
{
throw std::invalid_argument(error_message);
}
--depth;
index = end_index + end.size();
}
else // start_index == end_index == std::string::npos
{
result += str.substr(index);
break;
}
}
if(depth != 0)
{
throw std::invalid_argument(error_message);
}
return result;
}
std::string String::remove_pgn_comments(const std::string& line)
{
const auto index = line.find_first_of(";({");
const auto delimiter = index < std::string::npos ? line[index] : '\0';
switch(delimiter)
{
case ';' : return remove_pgn_comments(strip_comments(line, ";"));
case '(' : return remove_pgn_comments(strip_nested_block_comments(line, "(", ")"));
case '{' : return remove_pgn_comments(strip_block_comment(line, "{", "}"));
default : return remove_extra_whitespace(line);
}
}
std::string String::extract_delimited_text(const std::string& str, const std::string& start, const std::string& end)
{
const auto start_split = split(str, start, 1);
if(start_split.size() != 2)
{
throw std::invalid_argument("Starting delimiter not found in \"" + str + "\": " + start + " " + end);
}
const auto start_of_inside = start_split[1];
const auto inside_split = split(start_of_inside, end, 1);
if(inside_split.size() != 2)
{
throw std::invalid_argument("Ending delimiter not found in \"" + str + "\": " + start + " " + end);
}
return inside_split[0];
}
char String::tolower(const char letter) noexcept
{
return char(std::tolower(letter));
}
char String::toupper(const char letter) noexcept
{
return char(std::toupper(letter));
}
std::string String::lowercase(std::string s) noexcept
{
std::transform(s.begin(), s.end(), s.begin(), String::tolower);
return s;
}
std::string String::round_to_decimals(const double x, const size_t decimal_places) noexcept
{
auto result = std::ostringstream();
result << std::fixed << std::setprecision(int(decimal_places)) << x;
return result.str();
}
std::string String::date_and_time_format(const std::chrono::system_clock::time_point& point_in_time,
const std::string& format) noexcept
{
const auto time_c = std::chrono::system_clock::to_time_t(point_in_time);
std::tm time_out;
#ifdef _WIN32
localtime_s(&time_out, &time_c);
#elif defined(__linux__)
localtime_r(&time_c, &time_out);
#endif
auto ss = std::ostringstream{};
ss << std::put_time(&time_out, format.c_str());
return ss.str();
}
std::string String::add_to_file_name(const std::string& original_file_name, const std::string& addition) noexcept
{
const auto dot_index = std::min(original_file_name.find_last_of('.'), original_file_name.size());
return original_file_name.substr(0, dot_index) + addition + original_file_name.substr(dot_index);
}
<|endoftext|> |
<commit_before><commit_msg>add NFCTaskModule.cpp<commit_after>#include "NFCTaskModule.h"
bool NFCTaskModule::Init()
{
return true;
}
bool NFCTaskModule::Shut()
{
return true;
}
bool NFCTaskModule::Execute( const float fLasFrametime, const float fStartedTime )
{
return true;
}
bool NFCTaskModule::AfterInit()
{
return true;
}
int NFCTaskModule::AddTask( const NFIDENTID& self, const std::string& strTask )
{
// ҪضʱֹͣϵͳĿ
return 0;
}
int NFCTaskModule::RemoveTask( const NFIDENTID& self, const std::string& strTask )
{
return 0;
}<|endoftext|> |
<commit_before>#include "accountmanager.hpp"
#include "common.hpp"
#include <pajlada/settings/setting.hpp>
namespace chatterino {
namespace {
inline QString getEnvString(const char *target)
{
char *val = std::getenv(target);
if (val == nullptr) {
return QString();
}
return QString(val);
}
} // namespace
AccountManager::AccountManager()
: twitchAnonymousUser("justinfan64537", "", "")
{
QString envUsername = getEnvString("CHATTERINO2_USERNAME");
QString envOauthToken = getEnvString("CHATTERINO2_OAUTH");
if (!envUsername.isEmpty() && !envOauthToken.isEmpty()) {
this->addTwitchUser(twitch::TwitchUser(envUsername, envOauthToken, ""));
}
pajlada::Settings::Setting<std::string>::set(
"/accounts/current/roomID", "11148817", pajlada::Settings::SettingOption::DoNotWriteToJSON);
}
void AccountManager::load()
{
auto keys = pajlada::Settings::SettingManager::getObjectKeys("/accounts");
for (const auto &uid : keys) {
if (uid == "current") {
continue;
}
std::string username =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/username");
std::string userID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/userID");
std::string clientID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/clientID");
std::string oauthToken =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/oauthToken");
if (username.empty() || userID.empty() || clientID.empty() || oauthToken.empty()) {
continue;
}
twitch::TwitchUser user(qS(username), qS(oauthToken), qS(clientID));
this->addTwitchUser(user);
}
}
twitch::TwitchUser &AccountManager::getTwitchAnon()
{
return this->twitchAnonymousUser;
}
twitch::TwitchUser &AccountManager::getTwitchUser()
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
if (this->twitchUsers.size() == 0) {
return this->getTwitchAnon();
}
return this->twitchUsers.front();
}
std::vector<twitch::TwitchUser> AccountManager::getTwitchUsers()
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
return std::vector<twitch::TwitchUser>(this->twitchUsers);
}
bool AccountManager::removeTwitchUser(const QString &userName)
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
for (auto it = this->twitchUsers.begin(); it != this->twitchUsers.end(); it++) {
if ((*it).getUserName() == userName) {
this->twitchUsers.erase(it);
return true;
}
}
return false;
}
void AccountManager::addTwitchUser(const twitch::TwitchUser &user)
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
this->twitchUsers.push_back(user);
}
} // namespace chatterino
<commit_msg>Remove ability to log in with env variables<commit_after>#include "accountmanager.hpp"
#include "common.hpp"
#include <pajlada/settings/setting.hpp>
namespace chatterino {
namespace {
inline QString getEnvString(const char *target)
{
char *val = std::getenv(target);
if (val == nullptr) {
return QString();
}
return QString(val);
}
} // namespace
AccountManager::AccountManager()
: twitchAnonymousUser("justinfan64537", "", "")
{
}
void AccountManager::load()
{
auto keys = pajlada::Settings::SettingManager::getObjectKeys("/accounts");
for (const auto &uid : keys) {
if (uid == "current") {
continue;
}
std::string username =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/username");
std::string userID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/userID");
std::string clientID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/clientID");
std::string oauthToken =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/oauthToken");
if (username.empty() || userID.empty() || clientID.empty() || oauthToken.empty()) {
continue;
}
twitch::TwitchUser user(qS(username), qS(oauthToken), qS(clientID));
this->addTwitchUser(user);
printf("Adding user %s(%s)\n", username.c_str(), userID.c_str());
}
}
twitch::TwitchUser &AccountManager::getTwitchAnon()
{
return this->twitchAnonymousUser;
}
twitch::TwitchUser &AccountManager::getTwitchUser()
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
if (this->twitchUsers.size() == 0) {
return this->getTwitchAnon();
}
return this->twitchUsers.front();
}
std::vector<twitch::TwitchUser> AccountManager::getTwitchUsers()
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
return std::vector<twitch::TwitchUser>(this->twitchUsers);
}
bool AccountManager::removeTwitchUser(const QString &userName)
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
for (auto it = this->twitchUsers.begin(); it != this->twitchUsers.end(); it++) {
if ((*it).getUserName() == userName) {
this->twitchUsers.erase(it);
return true;
}
}
return false;
}
void AccountManager::addTwitchUser(const twitch::TwitchUser &user)
{
std::lock_guard<std::mutex> lock(this->twitchUsersMutex);
this->twitchUsers.push_back(user);
}
} // namespace chatterino
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qhelpsearchquerywidget.h"
#include <QtCore/QDebug>
#include <QtCore/QObject>
#include <QtCore/QStringList>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QFocusEvent>
#include <QtGui/QPushButton>
#include <QtGui/QToolButton>
QT_BEGIN_NAMESPACE
class QHelpSearchQueryWidgetPrivate : public QObject
{
Q_OBJECT
private:
QHelpSearchQueryWidgetPrivate()
: QObject()
{
searchButton = 0;
advancedSearchWidget = 0;
showHideAdvancedSearchButton = 0;
defaultQuery = 0;
exactQuery = 0;
similarQuery = 0;
withoutQuery = 0;
allQuery = 0;
atLeastQuery = 0;
}
~QHelpSearchQueryWidgetPrivate()
{
// nothing todo
}
QString escapeString(const QString &text)
{
QString retValue = text;
const QString escape(QLatin1String("\\"));
QStringList escapableCharsList;
escapableCharsList << QLatin1String("\\") << QLatin1String("+")
<< QLatin1String("-") << QLatin1String("!") << QLatin1String("(")
<< QLatin1String(")") << QLatin1String(":") << QLatin1String("^")
<< QLatin1String("[") << QLatin1String("]") << QLatin1String("{")
<< QLatin1String("}") << QLatin1String("~");
// make sure we won't end up with an empty string
foreach (const QString escapeChar, escapableCharsList) {
if (retValue.contains(escapeChar))
retValue.replace(escapeChar, QLatin1String(""));
}
if (retValue.trimmed().isEmpty())
return retValue;
retValue = text; // now realy escape the string...
foreach (const QString escapeChar, escapableCharsList) {
if (retValue.contains(escapeChar))
retValue.replace(escapeChar, escape + escapeChar);
}
return retValue;
}
QStringList buildTermList(const QString query)
{
bool s = false;
QString phrase;
QStringList wordList;
QString searchTerm = query;
for (int i = 0; i < searchTerm.length(); ++i) {
if (searchTerm[i] == QLatin1Char('\"') && !s) {
s = true;
phrase = searchTerm[i];
continue;
}
if (searchTerm[i] != QLatin1Char('\"') && s)
phrase += searchTerm[i];
if (searchTerm[i] == QLatin1Char('\"') && s) {
s = false;
phrase += searchTerm[i];
wordList.append(phrase);
searchTerm.remove(phrase);
}
}
if (s)
searchTerm.replace(phrase, phrase.mid(1));
const QRegExp exp(QLatin1String("\\s+"));
wordList += searchTerm.split(exp, QString::SkipEmptyParts);
return wordList;
}
private slots:
void showHideAdvancedSearch()
{
bool hidden = advancedSearchWidget->isHidden();
if (hidden) {
advancedSearchWidget->show();
showHideAdvancedSearchButton->setText((QLatin1String("-")));
} else {
advancedSearchWidget->hide();
showHideAdvancedSearchButton->setText((QLatin1String("+")));
}
defaultQuery->setEnabled(!hidden);
}
private:
friend class QHelpSearchQueryWidget;
QPushButton *searchButton;
QWidget* advancedSearchWidget;
QToolButton *showHideAdvancedSearchButton;
QLineEdit *defaultQuery;
QLineEdit *exactQuery;
QLineEdit *similarQuery;
QLineEdit *withoutQuery;
QLineEdit *allQuery;
QLineEdit *atLeastQuery;
};
#include "qhelpsearchquerywidget.moc"
/*!
\class QHelpSearchQueryWidget
\since 4.4
\inmodule QtHelp
\brief The QHelpSearchQueryWidget class provides a simple line edit or
an advanced widget to enable the user to input a search term in a
standardized input mask.
*/
/*!
\fn void QHelpSearchQueryWidget::search()
This signal is emitted when a the user has the search button invoked.
After reciving the signal you can ask the QHelpSearchQueryWidget for the build list
of QHelpSearchQuery's that you may pass to the QHelpSearchEngine's search() function.
*/
/*!
Constructs a new search query widget with the given \a parent.
*/
QHelpSearchQueryWidget::QHelpSearchQueryWidget(QWidget *parent)
: QWidget(parent)
{
d = new QHelpSearchQueryWidgetPrivate();
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->setMargin(0);
QHBoxLayout* hBoxLayout = new QHBoxLayout();
QLabel *label = new QLabel(tr("Search for:"), this);
d->defaultQuery = new QLineEdit(this);
d->searchButton = new QPushButton(tr("Search"), this);
hBoxLayout->addWidget(label);
hBoxLayout->addWidget(d->defaultQuery);
hBoxLayout->addWidget(d->searchButton);
vLayout->addLayout(hBoxLayout);
connect(d->searchButton, SIGNAL(clicked()), this, SIGNAL(search()));
connect(d->defaultQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
#if defined(QT_CLUCENE_SUPPORT)
hBoxLayout = new QHBoxLayout();
d->showHideAdvancedSearchButton = new QToolButton(this);
d->showHideAdvancedSearchButton->setText(QLatin1String("+"));
d->showHideAdvancedSearchButton->setMinimumSize(25, 20);
label = new QLabel(tr("Advanced search"), this);
QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
sizePolicy.setHeightForWidth(label->sizePolicy().hasHeightForWidth());
label->setSizePolicy(sizePolicy);
QFrame* hLine = new QFrame(this);
hLine->setFrameStyle(QFrame::HLine);
hBoxLayout->addWidget(d->showHideAdvancedSearchButton);
hBoxLayout->addWidget(label);
hBoxLayout->addWidget(hLine);
vLayout->addLayout(hBoxLayout);
// setup advanced search layout
d->advancedSearchWidget = new QWidget(this);
QGridLayout *gLayout = new QGridLayout(d->advancedSearchWidget);
gLayout->setMargin(0);
label = new QLabel(tr("words <B>similar</B> to:"), this);
gLayout->addWidget(label, 0, 0);
d->similarQuery = new QLineEdit(this);
gLayout->addWidget(d->similarQuery, 0, 1);
label = new QLabel(tr("<B>without</B> the words:"), this);
gLayout->addWidget(label, 1, 0);
d->withoutQuery = new QLineEdit(this);
gLayout->addWidget(d->withoutQuery, 1, 1);
label = new QLabel(tr("with <B>exact phrase</B>:"), this);
gLayout->addWidget(label, 2, 0);
d->exactQuery = new QLineEdit(this);
gLayout->addWidget(d->exactQuery, 2, 1);
label = new QLabel(tr("with <B>all</B> of the words:"), this);
gLayout->addWidget(label, 3, 0);
d->allQuery = new QLineEdit(this);
gLayout->addWidget(d->allQuery, 3, 1);
label = new QLabel(tr("with <B>at least one</B> of the words:"), this);
gLayout->addWidget(label, 4, 0);
d->atLeastQuery = new QLineEdit(this);
gLayout->addWidget(d->atLeastQuery, 4, 1);
vLayout->addWidget(d->advancedSearchWidget);
d->advancedSearchWidget->hide();
connect(d->exactQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->similarQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->withoutQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->allQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->atLeastQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->showHideAdvancedSearchButton, SIGNAL(clicked()),
d, SLOT(showHideAdvancedSearch()));
#endif
}
/*!
Destroys the search query widget.
*/
QHelpSearchQueryWidget::~QHelpSearchQueryWidget()
{
delete d;
}
/*!
Returns a list of querys to use in combination with the search engines
search(QList<QHelpSearchQuery> &query) function.
*/
QList<QHelpSearchQuery> QHelpSearchQueryWidget::query() const
{
#if !defined(QT_CLUCENE_SUPPORT)
QList<QHelpSearchQuery> queryList;
queryList.append(QHelpSearchQuery(QHelpSearchQuery::DEFAULT,
QStringList(d->defaultQuery->text())));
return queryList;
#else
QList<QHelpSearchQuery> queryList;
if (d->defaultQuery->isEnabled()) {
queryList.append(QHelpSearchQuery(QHelpSearchQuery::DEFAULT,
d->buildTermList(d->escapeString(d->defaultQuery->text()))));
} else {
const QRegExp exp(QLatin1String("\\s+"));
QStringList lst = d->similarQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList fuzzy;
foreach (const QString term, lst)
fuzzy += d->buildTermList(d->escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::FUZZY, fuzzy));
}
lst = d->withoutQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList without;
foreach (const QString term, lst)
without.append(d->escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::WITHOUT, without));
}
if (!d->exactQuery->text().isEmpty()) {
QString phrase = d->exactQuery->text().remove(QLatin1Char('\"'));
phrase = d->escapeString(phrase.simplified());
queryList.append(QHelpSearchQuery(QHelpSearchQuery::PHRASE, QStringList(phrase)));
}
lst = d->allQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList all;
foreach (const QString term, lst)
all.append(d->escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::ALL, all));
}
lst = d->atLeastQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList atLeast;
foreach (const QString term, lst)
atLeast += d->buildTermList(d->escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::ATLEAST, atLeast));
}
}
return queryList;
#endif
}
/*! \reimp
*/
void QHelpSearchQueryWidget::focusInEvent(QFocusEvent *focusEvent)
{
if (focusEvent->reason() != Qt::MouseFocusReason) {
d->defaultQuery->selectAll();
d->defaultQuery->setFocus();
}
}
QT_END_NAMESPACE
<commit_msg>Assistant: Added search history.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qhelpsearchquerywidget.h"
#include <QtCore/QDebug>
#include <QtCore/QAbstractListModel>
#include <QtCore/QObject>
#include <QtCore/QStringList>
#include <QtCore/QtGlobal>
#include <QtGui/QCompleter>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QFocusEvent>
#include <QtGui/QPushButton>
#include <QtGui/QToolButton>
QT_BEGIN_NAMESPACE
class QHelpSearchQueryWidgetPrivate : public QObject
{
Q_OBJECT
private:
struct QueryHistory {
explicit QueryHistory() : curQuery(-1) {}
QList<QList<QHelpSearchQuery> > queries;
int curQuery;
};
class CompleterModel : public QAbstractListModel
{
public:
explicit CompleterModel(QObject *parent)
: QAbstractListModel(parent) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const
{
return parent.isValid() ? 0 : termList.size();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
{
if (!index.isValid() || index.row() >= termList.count()||
(role != Qt::EditRole && role != Qt::DisplayRole))
return QVariant();
return termList.at(index.row());
}
void addTerm(const QString &term)
{
if (!termList.contains(term)) {
termList.append(term);
reset();
}
}
private:
QStringList termList;
};
QHelpSearchQueryWidgetPrivate()
: QObject(), simpleSearch(true),
searchCompleter(new CompleterModel(this), this)
{
searchButton = 0;
advancedSearchWidget = 0;
showHideAdvancedSearchButton = 0;
defaultQuery = 0;
exactQuery = 0;
similarQuery = 0;
withoutQuery = 0;
allQuery = 0;
atLeastQuery = 0;
}
~QHelpSearchQueryWidgetPrivate()
{
// nothing todo
}
QString escapeString(const QString &text)
{
QString retValue = text;
const QString escape(QLatin1String("\\"));
QStringList escapableCharsList;
escapableCharsList << QLatin1String("\\") << QLatin1String("+")
<< QLatin1String("-") << QLatin1String("!") << QLatin1String("(")
<< QLatin1String(")") << QLatin1String(":") << QLatin1String("^")
<< QLatin1String("[") << QLatin1String("]") << QLatin1String("{")
<< QLatin1String("}") << QLatin1String("~");
// make sure we won't end up with an empty string
foreach (const QString escapeChar, escapableCharsList) {
if (retValue.contains(escapeChar))
retValue.replace(escapeChar, QLatin1String(""));
}
if (retValue.trimmed().isEmpty())
return retValue;
retValue = text; // now realy escape the string...
foreach (const QString escapeChar, escapableCharsList) {
if (retValue.contains(escapeChar))
retValue.replace(escapeChar, escape + escapeChar);
}
return retValue;
}
QStringList buildTermList(const QString query)
{
bool s = false;
QString phrase;
QStringList wordList;
QString searchTerm = query;
for (int i = 0; i < searchTerm.length(); ++i) {
if (searchTerm[i] == QLatin1Char('\"') && !s) {
s = true;
phrase = searchTerm[i];
continue;
}
if (searchTerm[i] != QLatin1Char('\"') && s)
phrase += searchTerm[i];
if (searchTerm[i] == QLatin1Char('\"') && s) {
s = false;
phrase += searchTerm[i];
wordList.append(phrase);
searchTerm.remove(phrase);
}
}
if (s)
searchTerm.replace(phrase, phrase.mid(1));
const QRegExp exp(QLatin1String("\\s+"));
wordList += searchTerm.split(exp, QString::SkipEmptyParts);
return wordList;
}
void saveQuery(const QList<QHelpSearchQuery> &query, QueryHistory &queryHist)
{
// We only add the query to the list if it is different from the last one.
bool insert = false;
if (queryHist.queries.empty())
insert = true;
else {
const QList<QHelpSearchQuery> &lastQuery = queryHist.queries.last();
if (lastQuery.size() != query.size()) {
insert = true;
} else {
for (int i = 0; i < query.size(); ++i) {
if (query.at(i).fieldName != lastQuery.at(i).fieldName
|| query.at(i).wordList != lastQuery.at(i).wordList) {
insert = true;
break;
}
}
}
}
if (insert) {
queryHist.queries.append(query);
foreach (const QHelpSearchQuery &queryPart, query) {
static_cast<CompleterModel *>(searchCompleter.model())->
addTerm(queryPart.wordList.join(" "));
}
}
}
void nextOrPrevQuery(int maxOrMinIndex, int addend,
QToolButton *thisButton, QToolButton *otherButton)
{
QueryHistory *queryHist;
QList<QLineEdit *> lineEdits;
if (simpleSearch) {
queryHist = &simpleQueries;
lineEdits << defaultQuery;
} else {
queryHist = &complexQueries;
lineEdits << allQuery << atLeastQuery << similarQuery
<< withoutQuery << exactQuery;
}
foreach (QLineEdit *lineEdit, lineEdits)
lineEdit->clear();
// Otherwise, the respective button would be disabled.
Q_ASSERT(queryHist->curQuery != maxOrMinIndex);
queryHist->curQuery += addend;
const QList<QHelpSearchQuery> &query =
queryHist->queries.at(queryHist->curQuery);
foreach (const QHelpSearchQuery &queryPart, query) {
QLineEdit *lineEdit;
switch (queryPart.fieldName) {
case QHelpSearchQuery::DEFAULT:
lineEdit = defaultQuery;
break;
case QHelpSearchQuery::ALL:
lineEdit = allQuery;
break;
case QHelpSearchQuery::ATLEAST:
lineEdit = atLeastQuery;
break;
case QHelpSearchQuery::FUZZY:
lineEdit = similarQuery;
break;
case QHelpSearchQuery::WITHOUT:
lineEdit = withoutQuery;
break;
case QHelpSearchQuery::PHRASE:
lineEdit = exactQuery;
break;
default:
Q_ASSERT(0);
}
lineEdit->setText(queryPart.wordList.join(" "));
}
if (queryHist->curQuery == maxOrMinIndex)
thisButton->setEnabled(false);
otherButton->setEnabled(true);
}
void enableOrDisableToolButtons()
{
const QueryHistory &queryHist =
simpleSearch ? simpleQueries : complexQueries;
prevQueryButton->setEnabled(queryHist.curQuery > 0);
nextQueryButton->setEnabled(queryHist.curQuery <
queryHist.queries.size() - 1);
}
private slots:
void showHideAdvancedSearch()
{
if (simpleSearch) {
advancedSearchWidget->show();
showHideAdvancedSearchButton->setText((QLatin1String("-")));
} else {
advancedSearchWidget->hide();
showHideAdvancedSearchButton->setText((QLatin1String("+")));
}
simpleSearch = !simpleSearch;
defaultQuery->setEnabled(simpleSearch);
enableOrDisableToolButtons();
}
void searchRequested()
{
QList<QHelpSearchQuery> queryList;
#if !defined(QT_CLUCENE_SUPPORT)
queryList.append(QHelSearchQuery(QHelpSearchQuery::DEFAULT,
QStringList(defaultQuery->text())));
#else
if (defaultQuery->isEnabled()) {
queryList.append(QHelpSearchQuery(QHelpSearchQuery::DEFAULT,
buildTermList(escapeString(defaultQuery->text()))));
} else {
const QRegExp exp(QLatin1String("\\s+"));
QStringList lst = similarQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList fuzzy;
foreach (const QString term, lst)
fuzzy += buildTermList(escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::FUZZY, fuzzy));
}
lst = withoutQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList without;
foreach (const QString term, lst)
without.append(escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::WITHOUT, without));
}
if (!exactQuery->text().isEmpty()) {
QString phrase = exactQuery->text().remove(QLatin1Char('\"'));
phrase = escapeString(phrase.simplified());
queryList.append(QHelpSearchQuery(QHelpSearchQuery::PHRASE, QStringList(phrase)));
}
lst = allQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList all;
foreach (const QString term, lst)
all.append(escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::ALL, all));
}
lst = atLeastQuery->text().split(exp, QString::SkipEmptyParts);
if (!lst.isEmpty()) {
QStringList atLeast;
foreach (const QString term, lst)
atLeast += buildTermList(escapeString(term));
queryList.append(QHelpSearchQuery(QHelpSearchQuery::ATLEAST, atLeast));
}
}
#endif
QueryHistory &queryHist = simpleSearch ? simpleQueries : complexQueries;
saveQuery(queryList, queryHist);
queryHist.curQuery = queryHist.queries.size() - 1;
if (queryHist.curQuery > 0)
prevQueryButton->setEnabled(true);
nextQueryButton->setEnabled(false);
}
void nextQuery()
{
nextOrPrevQuery((simpleSearch ? simpleQueries : complexQueries).queries.size() - 1,
1, nextQueryButton, prevQueryButton);
}
void prevQuery()
{
nextOrPrevQuery(0, -1, prevQueryButton, nextQueryButton);
}
private:
friend class QHelpSearchQueryWidget;
bool simpleSearch;
QPushButton *searchButton;
QWidget* advancedSearchWidget;
QToolButton *showHideAdvancedSearchButton;
QLineEdit *defaultQuery;
QLineEdit *exactQuery;
QLineEdit *similarQuery;
QLineEdit *withoutQuery;
QLineEdit *allQuery;
QLineEdit *atLeastQuery;
QToolButton *nextQueryButton;
QToolButton *prevQueryButton;
QueryHistory simpleQueries;
QueryHistory complexQueries;
QCompleter searchCompleter;
};
#include "qhelpsearchquerywidget.moc"
/*!
\class QHelpSearchQueryWidget
\since 4.4
\inmodule QtHelp
\brief The QHelpSearchQueryWidget class provides a simple line edit or
an advanced widget to enable the user to input a search term in a
standardized input mask.
*/
/*!
\fn void QHelpSearchQueryWidget::search()
This signal is emitted when a the user has the search button invoked.
After reciving the signal you can ask the QHelpSearchQueryWidget for the build list
of QHelpSearchQuery's that you may pass to the QHelpSearchEngine's search() function.
*/
/*!
Constructs a new search query widget with the given \a parent.
*/
QHelpSearchQueryWidget::QHelpSearchQueryWidget(QWidget *parent)
: QWidget(parent)
{
d = new QHelpSearchQueryWidgetPrivate();
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->setMargin(0);
QHBoxLayout* hBoxLayout = new QHBoxLayout();
QLabel *label = new QLabel(tr("Search for:"), this);
d->defaultQuery = new QLineEdit(this);
d->defaultQuery->setCompleter(&d->searchCompleter);
d->prevQueryButton = new QToolButton(this);
d->prevQueryButton->setArrowType(Qt::LeftArrow);
d->prevQueryButton->setToolTip(tr("Previous search"));
d->prevQueryButton->setEnabled(false);
d->nextQueryButton = new QToolButton(this);
d->nextQueryButton->setArrowType(Qt::RightArrow);
d->nextQueryButton->setToolTip(tr("Next search"));
d->nextQueryButton->setEnabled(false);
d->searchButton = new QPushButton(tr("Search"), this);
hBoxLayout->addWidget(label);
hBoxLayout->addWidget(d->defaultQuery);
hBoxLayout->addWidget(d->prevQueryButton);
hBoxLayout->addWidget(d->nextQueryButton);
hBoxLayout->addWidget(d->searchButton);
vLayout->addLayout(hBoxLayout);
connect(d->prevQueryButton, SIGNAL(clicked()), d, SLOT(prevQuery()));
connect(d->nextQueryButton, SIGNAL(clicked()), d, SLOT(nextQuery()));
connect(d->searchButton, SIGNAL(clicked()), this, SIGNAL(search()));
connect(d->defaultQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
#if defined(QT_CLUCENE_SUPPORT)
hBoxLayout = new QHBoxLayout();
d->showHideAdvancedSearchButton = new QToolButton(this);
d->showHideAdvancedSearchButton->setText(QLatin1String("+"));
d->showHideAdvancedSearchButton->setMinimumSize(25, 20);
label = new QLabel(tr("Advanced search"), this);
QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
sizePolicy.setHeightForWidth(label->sizePolicy().hasHeightForWidth());
label->setSizePolicy(sizePolicy);
QFrame* hLine = new QFrame(this);
hLine->setFrameStyle(QFrame::HLine);
hBoxLayout->addWidget(d->showHideAdvancedSearchButton);
hBoxLayout->addWidget(label);
hBoxLayout->addWidget(hLine);
vLayout->addLayout(hBoxLayout);
// setup advanced search layout
d->advancedSearchWidget = new QWidget(this);
QGridLayout *gLayout = new QGridLayout(d->advancedSearchWidget);
gLayout->setMargin(0);
label = new QLabel(tr("words <B>similar</B> to:"), this);
gLayout->addWidget(label, 0, 0);
d->similarQuery = new QLineEdit(this);
d->similarQuery->setCompleter(&d->searchCompleter);
gLayout->addWidget(d->similarQuery, 0, 1);
label = new QLabel(tr("<B>without</B> the words:"), this);
gLayout->addWidget(label, 1, 0);
d->withoutQuery = new QLineEdit(this);
d->withoutQuery->setCompleter(&d->searchCompleter);
gLayout->addWidget(d->withoutQuery, 1, 1);
label = new QLabel(tr("with <B>exact phrase</B>:"), this);
gLayout->addWidget(label, 2, 0);
d->exactQuery = new QLineEdit(this);
d->exactQuery->setCompleter(&d->searchCompleter);
gLayout->addWidget(d->exactQuery, 2, 1);
label = new QLabel(tr("with <B>all</B> of the words:"), this);
gLayout->addWidget(label, 3, 0);
d->allQuery = new QLineEdit(this);
d->allQuery->setCompleter(&d->searchCompleter);
gLayout->addWidget(d->allQuery, 3, 1);
label = new QLabel(tr("with <B>at least one</B> of the words:"), this);
gLayout->addWidget(label, 4, 0);
d->atLeastQuery = new QLineEdit(this);
d->atLeastQuery->setCompleter(&d->searchCompleter);
gLayout->addWidget(d->atLeastQuery, 4, 1);
vLayout->addWidget(d->advancedSearchWidget);
d->advancedSearchWidget->hide();
connect(d->exactQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->similarQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->withoutQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->allQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->atLeastQuery, SIGNAL(returnPressed()), this, SIGNAL(search()));
connect(d->showHideAdvancedSearchButton, SIGNAL(clicked()),
d, SLOT(showHideAdvancedSearch()));
#endif
connect(this, SIGNAL(search()), d, SLOT(searchRequested()));
}
/*!
Destroys the search query widget.
*/
QHelpSearchQueryWidget::~QHelpSearchQueryWidget()
{
delete d;
}
/*!
Returns a list of querys to use in combination with the search engines
search(QList<QHelpSearchQuery> &query) function.
*/
QList<QHelpSearchQuery> QHelpSearchQueryWidget::query() const
{
const QHelpSearchQueryWidgetPrivate::QueryHistory &queryHist =
d->simpleSearch ? d->simpleQueries : d->complexQueries;
return queryHist.queries.isEmpty() ?
QList<QHelpSearchQuery>() : queryHist.queries.last();
}
/*! \reimp
*/
void QHelpSearchQueryWidget::focusInEvent(QFocusEvent *focusEvent)
{
if (focusEvent->reason() != Qt::MouseFocusReason) {
d->defaultQuery->selectAll();
d->defaultQuery->setFocus();
}
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "chromeos/chromeos_switches.h"
#include "device/bluetooth/bluetooth_adapter.h"
#if defined(OS_CHROMEOS)
#include "device/bluetooth/bluetooth_adapter_chromeos.h"
#include "device/bluetooth/bluetooth_adapter_chromeos_experimental.h"
#elif defined(OS_WIN)
#include "device/bluetooth/bluetooth_adapter_win.h"
#elif defined(OS_MACOSX)
#include "device/bluetooth/bluetooth_adapter_mac.h"
#endif
namespace {
using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
// Shared default adapter instance, we don't want to keep this class around
// if nobody is using it so use a WeakPtr and create the object when needed;
// since Google C++ Style (and clang's static analyzer) forbids us having
// exit-time destructors we use a leaky lazy instance for it.
base::LazyInstance<base::WeakPtr<device::BluetoothAdapter> >::Leaky
default_adapter = LAZY_INSTANCE_INITIALIZER;
typedef std::vector<BluetoothAdapterFactory::AdapterCallback>
AdapterCallbackList;
// List of adapter callbacks to be called once the adapter is initialized.
// Since Google C++ Style (and clang's static analyzer) forbids us having
// exit-time destructors we use a lazy instance for it.
base::LazyInstance<AdapterCallbackList> adapter_callbacks =
LAZY_INSTANCE_INITIALIZER;
void RunAdapterCallbacks() {
CHECK(default_adapter.Get().get());
scoped_refptr<BluetoothAdapter> adapter(default_adapter.Get());
for (std::vector<BluetoothAdapterFactory::AdapterCallback>::const_iterator
iter = adapter_callbacks.Get().begin();
iter != adapter_callbacks.Get().end();
++iter) {
iter->Run(adapter);
}
adapter_callbacks.Get().clear();
}
} // namespace
namespace device {
// static
bool BluetoothAdapterFactory::IsBluetoothAdapterAvailable() {
#if defined(OS_CHROMEOS)
return true;
#elif defined(OS_WIN)
return true;
#elif defined(OS_MACOSX)
return true;
#endif
return false;
}
// static
void BluetoothAdapterFactory::GetAdapter(const AdapterCallback& callback) {
if (!default_adapter.Get().get()) {
#if defined(OS_CHROMEOS)
if (CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kEnableExperimentalBluetooth)) {
chromeos::BluetoothAdapterChromeOSExperimental* new_adapter =
new chromeos::BluetoothAdapterChromeOSExperimental;
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
} else {
chromeos::BluetoothAdapterChromeOS* new_adapter =
new chromeos::BluetoothAdapterChromeOS;
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
}
#elif defined(OS_WIN)
BluetoothAdapterWin* new_adapter = new BluetoothAdapterWin(
base::Bind(&RunAdapterCallbacks));
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
#elif defined(OS_MACOSX)
BluetoothAdapterMac* new_adapter = new BluetoothAdapterMac();
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
#endif
}
if (default_adapter.Get()->IsInitialized()) {
callback.Run(scoped_refptr<BluetoothAdapter>(default_adapter.Get()));
} else {
adapter_callbacks.Get().push_back(callback);
}
}
// static
scoped_refptr<BluetoothAdapter> BluetoothAdapterFactory::MaybeGetAdapter() {
return scoped_refptr<BluetoothAdapter>(default_adapter.Get());
}
} // namespace device
<commit_msg>Restricts BluetoothAdapterMac to OSX 10.7 or later.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "chromeos/chromeos_switches.h"
#include "device/bluetooth/bluetooth_adapter.h"
#if defined(OS_CHROMEOS)
#include "device/bluetooth/bluetooth_adapter_chromeos.h"
#include "device/bluetooth/bluetooth_adapter_chromeos_experimental.h"
#elif defined(OS_WIN)
#include "device/bluetooth/bluetooth_adapter_win.h"
#elif defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "device/bluetooth/bluetooth_adapter_mac.h"
#endif
namespace {
using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
// Shared default adapter instance, we don't want to keep this class around
// if nobody is using it so use a WeakPtr and create the object when needed;
// since Google C++ Style (and clang's static analyzer) forbids us having
// exit-time destructors we use a leaky lazy instance for it.
base::LazyInstance<base::WeakPtr<device::BluetoothAdapter> >::Leaky
default_adapter = LAZY_INSTANCE_INITIALIZER;
typedef std::vector<BluetoothAdapterFactory::AdapterCallback>
AdapterCallbackList;
// List of adapter callbacks to be called once the adapter is initialized.
// Since Google C++ Style (and clang's static analyzer) forbids us having
// exit-time destructors we use a lazy instance for it.
base::LazyInstance<AdapterCallbackList> adapter_callbacks =
LAZY_INSTANCE_INITIALIZER;
void RunAdapterCallbacks() {
CHECK(default_adapter.Get().get());
scoped_refptr<BluetoothAdapter> adapter(default_adapter.Get());
for (std::vector<BluetoothAdapterFactory::AdapterCallback>::const_iterator
iter = adapter_callbacks.Get().begin();
iter != adapter_callbacks.Get().end();
++iter) {
iter->Run(adapter);
}
adapter_callbacks.Get().clear();
}
} // namespace
namespace device {
// static
bool BluetoothAdapterFactory::IsBluetoothAdapterAvailable() {
#if defined(OS_CHROMEOS)
return true;
#elif defined(OS_WIN)
return true;
#elif defined(OS_MACOSX)
return base::mac::IsOSLionOrLater();
#endif
return false;
}
// static
void BluetoothAdapterFactory::GetAdapter(const AdapterCallback& callback) {
if (!default_adapter.Get().get()) {
#if defined(OS_CHROMEOS)
if (CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kEnableExperimentalBluetooth)) {
chromeos::BluetoothAdapterChromeOSExperimental* new_adapter =
new chromeos::BluetoothAdapterChromeOSExperimental;
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
} else {
chromeos::BluetoothAdapterChromeOS* new_adapter =
new chromeos::BluetoothAdapterChromeOS;
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
}
#elif defined(OS_WIN)
BluetoothAdapterWin* new_adapter = new BluetoothAdapterWin(
base::Bind(&RunAdapterCallbacks));
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
#elif defined(OS_MACOSX)
BluetoothAdapterMac* new_adapter = new BluetoothAdapterMac();
new_adapter->TrackDefaultAdapter();
default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr();
#endif
}
if (default_adapter.Get()->IsInitialized()) {
callback.Run(scoped_refptr<BluetoothAdapter>(default_adapter.Get()));
} else {
adapter_callbacks.Get().push_back(callback);
}
}
// static
scoped_refptr<BluetoothAdapter> BluetoothAdapterFactory::MaybeGetAdapter() {
return scoped_refptr<BluetoothAdapter>(default_adapter.Get());
}
} // namespace device
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 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: Andreas Sandberg
*/
#include "debug/VIOPci.hh"
#include "dev/virtio/pci.hh"
#include "mem/packet_access.hh"
#include "params/PciVirtIO.hh"
PciVirtIO::PciVirtIO(const Params *params)
: PciDevice(params), queueNotify(0), interruptDeliveryPending(false),
vio(*params->vio), callbackKick(this)
{
// Override the subsystem ID with the device ID from VirtIO
config.subsystemID = htole(vio.deviceId);
BARSize[0] = BAR0_SIZE_BASE + vio.configSize;
vio.registerKickCallback(&callbackKick);
}
PciVirtIO::~PciVirtIO()
{
}
Tick
PciVirtIO::read(PacketPtr pkt)
{
const unsigned M5_VAR_USED size(pkt->getSize());
int bar;
Addr offset;
if (!getBAR(pkt->getAddr(), bar, offset))
panic("Invalid PCI memory access to unmapped memory.\n");
assert(bar == 0);
DPRINTF(VIOPci, "Reading offset 0x%x [len: %i]\n", offset, size);
// Forward device configuration writes to the device VirtIO model
if (offset >= OFF_VIO_DEVICE) {
vio.readConfig(pkt, offset - OFF_VIO_DEVICE);
return 0;
}
pkt->makeResponse();
switch(offset) {
case OFF_DEVICE_FEATURES:
DPRINTF(VIOPci, " DEVICE_FEATURES request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.deviceFeatures);
break;
case OFF_GUEST_FEATURES:
DPRINTF(VIOPci, " GUEST_FEATURES request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.getGuestFeatures());
break;
case OFF_QUEUE_ADDRESS:
DPRINTF(VIOPci, " QUEUE_ADDRESS request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.getQueueAddress());
break;
case OFF_QUEUE_SIZE:
DPRINTF(VIOPci, " QUEUE_SIZE request\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(vio.getQueueSize());
break;
case OFF_QUEUE_SELECT:
DPRINTF(VIOPci, " QUEUE_SELECT\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(vio.getQueueSelect());
break;
case OFF_QUEUE_NOTIFY:
DPRINTF(VIOPci, " QUEUE_NOTIFY request\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(queueNotify);
break;
case OFF_DEVICE_STATUS:
DPRINTF(VIOPci, " DEVICE_STATUS request\n");
assert(size == sizeof(uint8_t));
pkt->set<uint8_t>(vio.getDeviceStatus());
break;
case OFF_ISR_STATUS: {
DPRINTF(VIOPci, " ISR_STATUS\n");
assert(size == sizeof(uint8_t));
uint8_t isr_status(interruptDeliveryPending ? 1 : 0);
interruptDeliveryPending = false;
pkt->set<uint8_t>(isr_status);
} break;
default:
panic("Unhandled read offset (0x%x)\n", offset);
}
return 0;
}
Tick
PciVirtIO::write(PacketPtr pkt)
{
const unsigned M5_VAR_USED size(pkt->getSize());
int bar;
Addr offset;
if (!getBAR(pkt->getAddr(), bar, offset))
panic("Invalid PCI memory access to unmapped memory.\n");
assert(bar == 0);
DPRINTF(VIOPci, "Writing offset 0x%x [len: %i]\n", offset, size);
// Forward device configuration writes to the device VirtIO model
if (offset >= OFF_VIO_DEVICE) {
vio.writeConfig(pkt, offset - OFF_VIO_DEVICE);
return 0;
}
pkt->makeResponse();
switch(offset) {
case OFF_DEVICE_FEATURES:
warn("Guest tried to write device features.");
break;
case OFF_GUEST_FEATURES:
DPRINTF(VIOPci, " WRITE GUEST_FEATURES request\n");
assert(size == sizeof(uint32_t));
vio.setGuestFeatures(pkt->get<uint32_t>());
break;
case OFF_QUEUE_ADDRESS:
DPRINTF(VIOPci, " WRITE QUEUE_ADDRESS\n");
assert(size == sizeof(uint32_t));
vio.setQueueAddress(pkt->get<uint32_t>());
break;
case OFF_QUEUE_SIZE:
panic("Guest tried to write queue size.");
break;
case OFF_QUEUE_SELECT:
DPRINTF(VIOPci, " WRITE QUEUE_SELECT\n");
assert(size == sizeof(uint16_t));
vio.setQueueSelect(pkt->get<uint16_t>());
break;
case OFF_QUEUE_NOTIFY:
DPRINTF(VIOPci, " WRITE QUEUE_NOTIFY\n");
assert(size == sizeof(uint16_t));
queueNotify = pkt->get<uint16_t>();
vio.onNotify(queueNotify);
break;
case OFF_DEVICE_STATUS: {
assert(size == sizeof(uint8_t));
uint8_t status(pkt->get<uint8_t>());
DPRINTF(VIOPci, "VirtIO set status: 0x%x\n", status);
vio.setDeviceStatus(status);
} break;
case OFF_ISR_STATUS:
warn("Guest tried to write ISR status.");
break;
default:
panic("Unhandled read offset (0x%x)\n", offset);
}
return 0;
}
void
PciVirtIO::kick()
{
DPRINTF(VIOPci, "kick(): Sending interrupt...\n");
interruptDeliveryPending = true;
intrPost();
}
PciVirtIO *
PciVirtIOParams::create()
{
return new PciVirtIO(this);
}
<commit_msg>dev: Correctly clear interrupts in VirtIO PCI<commit_after>/*
* Copyright (c) 2014 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: Andreas Sandberg
*/
#include "debug/VIOPci.hh"
#include "dev/virtio/pci.hh"
#include "mem/packet_access.hh"
#include "params/PciVirtIO.hh"
PciVirtIO::PciVirtIO(const Params *params)
: PciDevice(params), queueNotify(0), interruptDeliveryPending(false),
vio(*params->vio), callbackKick(this)
{
// Override the subsystem ID with the device ID from VirtIO
config.subsystemID = htole(vio.deviceId);
BARSize[0] = BAR0_SIZE_BASE + vio.configSize;
vio.registerKickCallback(&callbackKick);
}
PciVirtIO::~PciVirtIO()
{
}
Tick
PciVirtIO::read(PacketPtr pkt)
{
const unsigned M5_VAR_USED size(pkt->getSize());
int bar;
Addr offset;
if (!getBAR(pkt->getAddr(), bar, offset))
panic("Invalid PCI memory access to unmapped memory.\n");
assert(bar == 0);
DPRINTF(VIOPci, "Reading offset 0x%x [len: %i]\n", offset, size);
// Forward device configuration writes to the device VirtIO model
if (offset >= OFF_VIO_DEVICE) {
vio.readConfig(pkt, offset - OFF_VIO_DEVICE);
return 0;
}
pkt->makeResponse();
switch(offset) {
case OFF_DEVICE_FEATURES:
DPRINTF(VIOPci, " DEVICE_FEATURES request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.deviceFeatures);
break;
case OFF_GUEST_FEATURES:
DPRINTF(VIOPci, " GUEST_FEATURES request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.getGuestFeatures());
break;
case OFF_QUEUE_ADDRESS:
DPRINTF(VIOPci, " QUEUE_ADDRESS request\n");
assert(size == sizeof(uint32_t));
pkt->set<uint32_t>(vio.getQueueAddress());
break;
case OFF_QUEUE_SIZE:
DPRINTF(VIOPci, " QUEUE_SIZE request\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(vio.getQueueSize());
break;
case OFF_QUEUE_SELECT:
DPRINTF(VIOPci, " QUEUE_SELECT\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(vio.getQueueSelect());
break;
case OFF_QUEUE_NOTIFY:
DPRINTF(VIOPci, " QUEUE_NOTIFY request\n");
assert(size == sizeof(uint16_t));
pkt->set<uint16_t>(queueNotify);
break;
case OFF_DEVICE_STATUS:
DPRINTF(VIOPci, " DEVICE_STATUS request\n");
assert(size == sizeof(uint8_t));
pkt->set<uint8_t>(vio.getDeviceStatus());
break;
case OFF_ISR_STATUS: {
DPRINTF(VIOPci, " ISR_STATUS\n");
assert(size == sizeof(uint8_t));
const uint8_t isr_status(interruptDeliveryPending ? 1 : 0);
if (interruptDeliveryPending) {
interruptDeliveryPending = false;
intrClear();
}
pkt->set<uint8_t>(isr_status);
} break;
default:
panic("Unhandled read offset (0x%x)\n", offset);
}
return 0;
}
Tick
PciVirtIO::write(PacketPtr pkt)
{
const unsigned M5_VAR_USED size(pkt->getSize());
int bar;
Addr offset;
if (!getBAR(pkt->getAddr(), bar, offset))
panic("Invalid PCI memory access to unmapped memory.\n");
assert(bar == 0);
DPRINTF(VIOPci, "Writing offset 0x%x [len: %i]\n", offset, size);
// Forward device configuration writes to the device VirtIO model
if (offset >= OFF_VIO_DEVICE) {
vio.writeConfig(pkt, offset - OFF_VIO_DEVICE);
return 0;
}
pkt->makeResponse();
switch(offset) {
case OFF_DEVICE_FEATURES:
warn("Guest tried to write device features.");
break;
case OFF_GUEST_FEATURES:
DPRINTF(VIOPci, " WRITE GUEST_FEATURES request\n");
assert(size == sizeof(uint32_t));
vio.setGuestFeatures(pkt->get<uint32_t>());
break;
case OFF_QUEUE_ADDRESS:
DPRINTF(VIOPci, " WRITE QUEUE_ADDRESS\n");
assert(size == sizeof(uint32_t));
vio.setQueueAddress(pkt->get<uint32_t>());
break;
case OFF_QUEUE_SIZE:
panic("Guest tried to write queue size.");
break;
case OFF_QUEUE_SELECT:
DPRINTF(VIOPci, " WRITE QUEUE_SELECT\n");
assert(size == sizeof(uint16_t));
vio.setQueueSelect(pkt->get<uint16_t>());
break;
case OFF_QUEUE_NOTIFY:
DPRINTF(VIOPci, " WRITE QUEUE_NOTIFY\n");
assert(size == sizeof(uint16_t));
queueNotify = pkt->get<uint16_t>();
vio.onNotify(queueNotify);
break;
case OFF_DEVICE_STATUS: {
assert(size == sizeof(uint8_t));
uint8_t status(pkt->get<uint8_t>());
DPRINTF(VIOPci, "VirtIO set status: 0x%x\n", status);
vio.setDeviceStatus(status);
} break;
case OFF_ISR_STATUS:
warn("Guest tried to write ISR status.");
break;
default:
panic("Unhandled read offset (0x%x)\n", offset);
}
return 0;
}
void
PciVirtIO::kick()
{
DPRINTF(VIOPci, "kick(): Sending interrupt...\n");
interruptDeliveryPending = true;
intrPost();
}
PciVirtIO *
PciVirtIOParams::create()
{
return new PciVirtIO(this);
}
<|endoftext|> |
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
/* rev for v2.3 by JGG */
#include <globals.h>
#include <prototypes.h>
#include <ugens.h>
#include <stdio.h>
#include <assert.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"
#define INCHANS_DISCREPANCY_WARNING "\
The bus config for this instrument specifies %d input channels, \n\
but its input source has %d channels. Setting input channels to %d..."
/* ----------------------------------------------------------- rtsetinput --- */
/* Instruments call this to set their input file pointer (like setnote in cmix).
Returns 0 if ok, -1 if error.
*/
int
rtsetinput(float start_time, Instrument *inst)
{
int auxin_count = inst->bus_config->auxin_count;
int in_count = inst->bus_config->in_count;
char *inst_name = NULL; // FIXME: need this for better msgs
if (auxin_count == 0 && in_count == 0)
die(inst_name, "This instrument requires input from either an in bus "
"or an aux bus.\nChange this with bus_config().");
if (auxin_count > 0) {
if (start_time != 0.0)
die(inst_name, "Input start must be 0 when reading from an aux bus.");
}
if (in_count > 0) {
int src_chans;
int index = get_last_input_index();
if (index < 0 || inputFileTable[index].fd < 1)
die(inst_name, "No input source open for this instrument!");
/* File or audio device was opened in rtinput(). Here we store the
index into the inputFileTable for the file or device.
*/
inst->fdIndex = index;
/* Fill in relevant data members of instrument class. */
inst->inputsr = inputFileTable[index].srate;
src_chans = inputFileTable[index].chans;
if (inst->inputchans != src_chans) {
warn(inst_name, INCHANS_DISCREPANCY_WARNING, inst->inputchans,
src_chans, src_chans);
inst->inputchans = src_chans;
}
if (inputFileTable[index].is_audio_dev) {
if (start_time != 0.0)
die(inst_name, "Input start must be 0 when reading from the "
"real-time audio device.");
}
else {
int datum_size, inskip;
inst->sfile_on = 1;
inskip = (int) (start_time * inst->inputsr);
/* sndlib always uses 2 for datum size, even if the actual size is
different. However, we don't use sndlib to read float files, so
their datum size is the real thing.
*/
if (inputFileTable[index].is_float_format)
datum_size = sizeof(float);
else
datum_size = 2;
/* Offset is measured from the header size determined in rtinput(). */
inst->fileOffset = inputFileTable[index].data_location
+ (inskip * inst->inputchans * datum_size);
if (start_time >= inputFileTable[index].dur)
warn(inst_name, "Attempt to read past end of input file: %s",
inputFileTable[index].filename);
}
/* Increment the reference count for this file. */
inputFileTable[index].refcount++;
}
return 0;
}
<commit_msg>Comment out INCHANS_DISCREPANCY_WARNING. Match inst->inputchans to file chans only when file is a sound file (and not when it represents a real-time audio fd). Other minor cleanups.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
/* rev for v2.3 by JGG */
#include <globals.h>
#include <prototypes.h>
#include <ugens.h>
#include <stdio.h>
#include <assert.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"
#define INCHANS_DISCREPANCY_WARNING "\
The bus config for this instrument specifies %d input channels, \n\
but its input source has %d channels. Setting input channels to %d..."
/* ----------------------------------------------------------- rtsetinput --- */
/* Instruments call this to set their input file pointer (like setnote in cmix).
Returns 0 if ok, -1 if error.
*/
int
rtsetinput(float start_time, Instrument *inst)
{
int auxin_count = inst->bus_config->auxin_count;
int in_count = inst->bus_config->in_count;
char *inst_name = NULL; // FIXME: need this for better msgs
if (auxin_count == 0 && in_count == 0)
die(inst_name, "This instrument requires input from either an in bus "
"or an aux bus.\nChange this with bus_config().");
if (auxin_count > 0) {
if (start_time != 0.0)
die(inst_name, "Input start must be 0 when reading from an aux bus.");
}
if (in_count > 0) {
int src_chans;
int index = get_last_input_index();
if (index < 0 || inputFileTable[index].fd < 1)
die(inst_name, "No input source open for this instrument!");
/* File or audio device was opened in rtinput(). Here we store the
index into the inputFileTable for the file or device.
*/
inst->fdIndex = index;
/* Fill in relevant data members of instrument class. */
inst->inputsr = inputFileTable[index].srate;
src_chans = inputFileTable[index].chans;
if (inputFileTable[index].is_audio_dev) {
if (start_time != 0.0)
die(inst_name, "Input start must be 0 when reading from the "
"real-time audio device.");
}
else {
int datum_size, inskip_frames;
if (inst->inputchans != src_chans) {
#ifdef NOMORE // pointless ifdef IGNORE_BUS_COUNT_FOR_FILE_INPUT in rtgetin.C
advise(inst_name, INCHANS_DISCREPANCY_WARNING, inst->inputchans,
src_chans, src_chans);
#endif
inst->inputchans = src_chans;
}
inst->sfile_on = 1;
inskip_frames = (int) (start_time * inst->inputsr);
/* sndlib always uses 2 for datum size, even if the actual size is
different. However, we don't use sndlib to read float files, so
their datum size is the real thing.
*/
if (inputFileTable[index].is_float_format)
datum_size = sizeof(float);
else
datum_size = 2;
/* Offset is measured from the header size determined in rtinput(). */
inst->fileOffset = inputFileTable[index].data_location
+ (inskip_frames * inst->inputchans * datum_size);
if (start_time >= inputFileTable[index].dur)
warn(inst_name, "Attempt to read past end of input file: %s",
inputFileTable[index].filename);
}
/* Increment the reference count for this file. */
inputFileTable[index].refcount++;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2012 Steinwurf ApS
// 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 Steinwurf ApS 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 Steinwurf ApS 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 "endian_buffer.hpp"
#include "convert_endian.h"
#include <cassert>
namespace sak
{
endian_buffer::endian_buffer(uint8_t* buffer, uint32_t size)
: m_buffer(buffer),
m_position(0),
m_size(size)
{
assert(m_buffer != 0);
assert(m_position == 0);
assert(m_size);
}
void endian_buffer::write_u8(uint8_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint8_t);
assert(m_position <= m_size);
big_endian::put<uint8_t>(v, write_position);
}
void endian_buffer::write_u16(uint16_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint16_t);
assert(m_position <= m_size);
big_endian::put<uint16_t>(v, write_position);
}
void endian_buffer::write_u32(uint32_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint32_t);
assert(m_position <= m_size);
big_endian::put<uint32_t>(v, write_position);
}
void endian_buffer::write_u64(uint64_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint64_t);
assert(m_position <= m_size);
big_endian::put<uint64_t>(v, write_position);
}
uint8_t endian_buffer::read_u8()
{
m_position -= sizeof(uint8_t);
return big_endian::get<uint8_t>(m_buffer + m_position);
}
uint16_t endian_buffer::read_u16()
{
m_position -= sizeof(uint16_t);
return big_endian::get<uint16_t>(m_buffer + m_position);
}
uint32_t endian_buffer::read_u32()
{
m_position -= sizeof(uint32_t);
return big_endian::get<uint32_t>(m_buffer + m_position);
}
uint64_t endian_buffer::read_u64()
{
m_position -= sizeof(uint64_t);
return big_endian::get<uint64_t>(m_buffer + m_position);
}
uint32_t endian_buffer::size() const
{
return m_size;
}
uint32_t endian_buffer::position() const
{
return m_position;
}
}
<commit_msg>removed unneeded assert<commit_after>// Copyright (c) 2011-2012 Steinwurf ApS
// 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 Steinwurf ApS 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 Steinwurf ApS 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 "endian_buffer.hpp"
#include "convert_endian.h"
#include <cassert>
namespace sak
{
endian_buffer::endian_buffer(uint8_t* buffer, uint32_t size)
: m_buffer(buffer),
m_position(0),
m_size(size)
{
assert(m_buffer != 0);
assert(m_size);
}
void endian_buffer::write_u8(uint8_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint8_t);
assert(m_position <= m_size);
big_endian::put<uint8_t>(v, write_position);
}
void endian_buffer::write_u16(uint16_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint16_t);
assert(m_position <= m_size);
big_endian::put<uint16_t>(v, write_position);
}
void endian_buffer::write_u32(uint32_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint32_t);
assert(m_position <= m_size);
big_endian::put<uint32_t>(v, write_position);
}
void endian_buffer::write_u64(uint64_t v)
{
uint8_t* write_position = m_buffer+m_position;
m_position += sizeof(uint64_t);
assert(m_position <= m_size);
big_endian::put<uint64_t>(v, write_position);
}
uint8_t endian_buffer::read_u8()
{
m_position -= sizeof(uint8_t);
return big_endian::get<uint8_t>(m_buffer + m_position);
}
uint16_t endian_buffer::read_u16()
{
m_position -= sizeof(uint16_t);
return big_endian::get<uint16_t>(m_buffer + m_position);
}
uint32_t endian_buffer::read_u32()
{
m_position -= sizeof(uint32_t);
return big_endian::get<uint32_t>(m_buffer + m_position);
}
uint64_t endian_buffer::read_u64()
{
m_position -= sizeof(uint64_t);
return big_endian::get<uint64_t>(m_buffer + m_position);
}
uint32_t endian_buffer::size() const
{
return m_size;
}
uint32_t endian_buffer::position() const
{
return m_position;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <glkernel/sample.h>
#include <cassert>
#include <random>
#include <vector>
#include <array>
#include <list>
#include <iterator>
#include <tuple>
#include <algorithm>
#include <glkernel/glm_compatability.h>
namespace glkernel
{
namespace sample
{
// optimization grid for identifying adjacent points
template <typename T, glm::precision P>
struct poisson_square_map
{
poisson_square_map(const T min_dist)
: m_none{ static_cast<size_t>(-1) }
, m_side{ static_cast<size_t>(std::ceil(sqrt(2.0) / min_dist)) }
, m_dist2(min_dist * min_dist)
{
m_mask.resize(m_side * m_side, m_none);
}
void mask(const glm::tvec2<T, P> & point, const size_t k)
{
const auto s = static_cast<int>(m_side);
const auto o = static_cast<int>(point.y * s) * s + static_cast<int>(point.x * s);
assert(m_mask[o] == m_none);
m_mask[o] = k;
}
bool masked(const glm::tvec2<T, P> & probe, const tkernel<glm::tvec2<T, P>> & kernel) const
{
const auto s = static_cast<int>(m_side);
const auto x = static_cast<int>(probe.x * s);
const auto y = static_cast<int>(probe.y * s);
const auto corners = std::array<int, 4>{ { y - 2, x - 2, y + 2, x + 2 } };
for (int j = y - 2; j < y + 3; ++j)
for (int i = x - 2; i < x + 3; ++i)
{
// optimization: skip the 4 corner cases, since the fall not within distance anyway ...
if ((j == corners[0] || j == corners[2]) && (i == corners[1] || i == corners[3]))
continue;
const auto i_tiled = i < 0 ? i + s : i % s;
const auto j_tiled = j < 0 ? j + s : j % s;
const auto o = m_mask[j_tiled * s + i_tiled];
if (o == m_none)
continue;
auto masking_probe = kernel[o];
if (i < 0)
masking_probe.x -= 1.0;
else if (i >= s)
masking_probe.x += 1.0;
if (j < 0)
masking_probe.y -= 1.0;
else if (j >= s)
masking_probe.y += 1.0;
// also optimized by using square distance->skipping sqrt
const auto delta = masking_probe - probe;
if (glm::dot(delta, delta) < m_dist2)
return true;
}
return false;
}
protected:
size_t m_none;
size_t m_side;
T m_dist2;
std::vector<size_t> m_mask;
};
template <typename T, glm::precision P>
size_t poisson_square(tkernel<glm::tvec2<T, P>> & kernel, const unsigned int num_probes)
{
assert(kernel.depth() == 1);
const T min_dist = 1 / sqrt(static_cast<T>(kernel.size() * sqrt(2)));
return poisson_square(kernel, min_dist, num_probes);
}
template <typename T, glm::precision P>
size_t poisson_square(tkernel<glm::tvec2<T, P>> & kernel, const T min_dist, const unsigned int num_probes)
{
assert(kernel.depth() == 1);
std::random_device RD;
std::mt19937_64 generator(RD());
std::uniform_real_distribution<> radius_dist(min_dist, min_dist * 2.0);
std::uniform_real_distribution<> angle_dist(0.0, 2.0 * glm::pi<T>());
std::uniform_int_distribution<> int_distribute(0, std::numeric_limits<int>::max());
auto occupancy = poisson_square_map<T, P>{ min_dist };
size_t k = 0; // number of valid/final points within the kernel
kernel[k] = glm::tvec2<T, P>(0.5, 0.5);
auto actives = std::list<size_t>();
actives.push_back(k);
occupancy.mask(kernel[k], k);
while (!actives.empty() && k < kernel.size() - 1)
{
// randomly pick an active point
const auto pick = int_distribute(generator);
auto pick_it = actives.begin();
std::advance(pick_it, pick % actives.size());
const auto active = kernel[*pick_it];
std::vector<std::tuple<glm::tvec2<T, P>, T>> probes{ num_probes };
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(num_probes); ++i)
{
const auto r = radius_dist(generator);
const auto a = angle_dist(generator);
auto probe = glm::tvec2<T, P>{ active.x + r * cos(a), active.y + r * sin(a) };
// within square? (tilable)
if (probe.x < 0.0)
probe.x += 1.0;
else if (probe.x >= 1.0)
probe.x -= 1.0;
if (probe.y < 0.0)
probe.y += 1.0;
else if (probe.y >= 1.0)
probe.y -= 1.0;
// Note: do NOT make this optimization
//if (!tilable && (probe.x < 0.0 || probe.x > 1.0 || probe.y < 0.0 || probe.y > 1.0))
// continue;
// points within min_dist?
const auto masked = occupancy.masked(probe, kernel);
const auto delta = abs(active - probe);
probes[i] = std::make_tuple<glm::tvec2<T, P>, T>(std::move(probe), (masked ? static_cast<T>(-1.0) : glm::dot(delta, delta)));
}
// pick nearest probe from sample set
glm::vec2 nearest_probe;
auto nearest_dist = 4 * min_dist * min_dist;
auto nearest_found = false;
for (int i = 0; i < static_cast<int>(num_probes); ++i)
{
// is this nearest point yet? - optimized by using square distance -> skipping sqrt
const auto new_dist = std::get<1>(probes[i]);
if (new_dist < 0.0 || nearest_dist < new_dist)
continue;
if (!nearest_found)
nearest_found = true;
nearest_dist = new_dist;
nearest_probe = std::get<0>(probes[i]);
}
if (!nearest_found && (actives.size() > 0 || k > 1))
{
actives.erase(pick_it);
continue;
}
kernel[++k] = nearest_probe;
actives.push_back(k);
occupancy.mask(nearest_probe, k);
}
return k + 1;
}
template <typename T, glm::precision P>
size_t multi_jittered(tkernel<glm::tvec2<T, P>> & kernel)
{
assert(kernel.depth() == 1);
std::random_device RD;
std::mt19937_64 generator(RD());
auto stratum_size = 1.0 / (kernel.width() * kernel.height());
auto subcell_width = 1.0 / kernel.width();
auto subcell_height = 1.0 / kernel.height();
std::uniform_real_distribution<> jitter_dist(0.0, stratum_size);
std::vector<std::pair<int, int>> pool;
// reverse height and width inside subcells
for (auto x = 0; x < kernel.height(); x++)
{
for (auto y = 0; y < kernel.width(); y++)
{
pool.push_back({ x, y });
}
}
std::random_shuffle(pool.begin(), pool.end());
size_t k = 0;
for (auto x = 0; x < kernel.width(); x++)
{
for (auto y = 0; y < kernel.height(); y++)
{
auto x_coord = x * subcell_width + pool[k].first * stratum_size + jitter_dist(generator);
auto y_coord = y * subcell_height + pool[k].second * stratum_size + jitter_dist(generator);
auto sample = glm::tvec2<T, P>(x_coord, y_coord);
kernel[k++] = sample;
}
}
return k;
}
} // namespace sample
} // namespace glkernel
<commit_msg>Use pre-increment in loops<commit_after>#pragma once
#include <glkernel/sample.h>
#include <cassert>
#include <random>
#include <vector>
#include <array>
#include <list>
#include <iterator>
#include <tuple>
#include <algorithm>
#include <glkernel/glm_compatability.h>
namespace glkernel
{
namespace sample
{
// optimization grid for identifying adjacent points
template <typename T, glm::precision P>
struct poisson_square_map
{
poisson_square_map(const T min_dist)
: m_none{ static_cast<size_t>(-1) }
, m_side{ static_cast<size_t>(std::ceil(sqrt(2.0) / min_dist)) }
, m_dist2(min_dist * min_dist)
{
m_mask.resize(m_side * m_side, m_none);
}
void mask(const glm::tvec2<T, P> & point, const size_t k)
{
const auto s = static_cast<int>(m_side);
const auto o = static_cast<int>(point.y * s) * s + static_cast<int>(point.x * s);
assert(m_mask[o] == m_none);
m_mask[o] = k;
}
bool masked(const glm::tvec2<T, P> & probe, const tkernel<glm::tvec2<T, P>> & kernel) const
{
const auto s = static_cast<int>(m_side);
const auto x = static_cast<int>(probe.x * s);
const auto y = static_cast<int>(probe.y * s);
const auto corners = std::array<int, 4>{ { y - 2, x - 2, y + 2, x + 2 } };
for (int j = y - 2; j < y + 3; ++j)
for (int i = x - 2; i < x + 3; ++i)
{
// optimization: skip the 4 corner cases, since the fall not within distance anyway ...
if ((j == corners[0] || j == corners[2]) && (i == corners[1] || i == corners[3]))
continue;
const auto i_tiled = i < 0 ? i + s : i % s;
const auto j_tiled = j < 0 ? j + s : j % s;
const auto o = m_mask[j_tiled * s + i_tiled];
if (o == m_none)
continue;
auto masking_probe = kernel[o];
if (i < 0)
masking_probe.x -= 1.0;
else if (i >= s)
masking_probe.x += 1.0;
if (j < 0)
masking_probe.y -= 1.0;
else if (j >= s)
masking_probe.y += 1.0;
// also optimized by using square distance->skipping sqrt
const auto delta = masking_probe - probe;
if (glm::dot(delta, delta) < m_dist2)
return true;
}
return false;
}
protected:
size_t m_none;
size_t m_side;
T m_dist2;
std::vector<size_t> m_mask;
};
template <typename T, glm::precision P>
size_t poisson_square(tkernel<glm::tvec2<T, P>> & kernel, const unsigned int num_probes)
{
assert(kernel.depth() == 1);
const T min_dist = 1 / sqrt(static_cast<T>(kernel.size() * sqrt(2)));
return poisson_square(kernel, min_dist, num_probes);
}
template <typename T, glm::precision P>
size_t poisson_square(tkernel<glm::tvec2<T, P>> & kernel, const T min_dist, const unsigned int num_probes)
{
assert(kernel.depth() == 1);
std::random_device RD;
std::mt19937_64 generator(RD());
std::uniform_real_distribution<> radius_dist(min_dist, min_dist * 2.0);
std::uniform_real_distribution<> angle_dist(0.0, 2.0 * glm::pi<T>());
std::uniform_int_distribution<> int_distribute(0, std::numeric_limits<int>::max());
auto occupancy = poisson_square_map<T, P>{ min_dist };
size_t k = 0; // number of valid/final points within the kernel
kernel[k] = glm::tvec2<T, P>(0.5, 0.5);
auto actives = std::list<size_t>();
actives.push_back(k);
occupancy.mask(kernel[k], k);
while (!actives.empty() && k < kernel.size() - 1)
{
// randomly pick an active point
const auto pick = int_distribute(generator);
auto pick_it = actives.begin();
std::advance(pick_it, pick % actives.size());
const auto active = kernel[*pick_it];
std::vector<std::tuple<glm::tvec2<T, P>, T>> probes{ num_probes };
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(num_probes); ++i)
{
const auto r = radius_dist(generator);
const auto a = angle_dist(generator);
auto probe = glm::tvec2<T, P>{ active.x + r * cos(a), active.y + r * sin(a) };
// within square? (tilable)
if (probe.x < 0.0)
probe.x += 1.0;
else if (probe.x >= 1.0)
probe.x -= 1.0;
if (probe.y < 0.0)
probe.y += 1.0;
else if (probe.y >= 1.0)
probe.y -= 1.0;
// Note: do NOT make this optimization
//if (!tilable && (probe.x < 0.0 || probe.x > 1.0 || probe.y < 0.0 || probe.y > 1.0))
// continue;
// points within min_dist?
const auto masked = occupancy.masked(probe, kernel);
const auto delta = abs(active - probe);
probes[i] = std::make_tuple<glm::tvec2<T, P>, T>(std::move(probe), (masked ? static_cast<T>(-1.0) : glm::dot(delta, delta)));
}
// pick nearest probe from sample set
glm::vec2 nearest_probe;
auto nearest_dist = 4 * min_dist * min_dist;
auto nearest_found = false;
for (int i = 0; i < static_cast<int>(num_probes); ++i)
{
// is this nearest point yet? - optimized by using square distance -> skipping sqrt
const auto new_dist = std::get<1>(probes[i]);
if (new_dist < 0.0 || nearest_dist < new_dist)
continue;
if (!nearest_found)
nearest_found = true;
nearest_dist = new_dist;
nearest_probe = std::get<0>(probes[i]);
}
if (!nearest_found && (actives.size() > 0 || k > 1))
{
actives.erase(pick_it);
continue;
}
kernel[++k] = nearest_probe;
actives.push_back(k);
occupancy.mask(nearest_probe, k);
}
return k + 1;
}
template <typename T, glm::precision P>
size_t multi_jittered(tkernel<glm::tvec2<T, P>> & kernel)
{
assert(kernel.depth() == 1);
std::random_device RD;
std::mt19937_64 generator(RD());
auto stratum_size = 1.0 / (kernel.width() * kernel.height());
auto subcell_width = 1.0 / kernel.width();
auto subcell_height = 1.0 / kernel.height();
std::uniform_real_distribution<> jitter_dist(0.0, stratum_size);
std::vector<std::pair<int, int>> pool;
// reverse height and width inside subcells
for (auto x = 0; x < kernel.height(); ++x)
{
for (auto y = 0; y < kernel.width(); ++y)
{
pool.push_back({ x, y });
}
}
std::random_shuffle(pool.begin(), pool.end());
size_t k = 0;
for (auto x = 0; x < kernel.width(); ++x)
{
for (auto y = 0; y < kernel.height(); ++y)
{
auto x_coord = x * subcell_width + pool[k].first * stratum_size + jitter_dist(generator);
auto y_coord = y * subcell_height + pool[k].second * stratum_size + jitter_dist(generator);
auto sample = glm::tvec2<T, P>(x_coord, y_coord);
kernel[k++] = sample;
}
}
return k;
}
} // namespace sample
} // namespace glkernel
<|endoftext|> |
<commit_before>#include <albert/scraper.hpp>
#include <iostream>
#include <deque>
#include <fstream>
#include <boost/locale.hpp>
#include <albert/util.hpp>
#include <albert/interpreter.hpp>
namespace supermarx
{
static const std::string domain_uri = "http://www.ah.nl";
static const std::string rest_uri = domain_uri + "/service/rest";
scraper::scraper(product_callback_t _product_callback, tag_hierarchy_callback_t _tag_hierarchy_callback, unsigned int _ratelimit, bool _cache, bool _register_tags)
: product_callback(_product_callback)
, tag_hierarchy_callback(_tag_hierarchy_callback)
, dl("supermarx albert/1.2", _ratelimit, _cache ? boost::optional<std::string>("./cache") : boost::none)
, m(dl, [&]() { error_count++; })
, register_tags(_register_tags)
, todo()
, blacklist()
, tag_hierarchy()
, product_count(0)
, page_count(0)
, error_count(0)
{}
Json::Value scraper::parse(std::string const& uri, std::string const& body)
{
Json::Value root;
Json::Reader reader;
if(!body.empty() && !reader.parse(body, root, false))
{
dl.clear(uri);
throw std::runtime_error("Could not parse json feed");
}
return root;
}
Json::Value scraper::download(std::string const& uri)
{
return stubborn::attempt<Json::Value>([&](){
return parse(uri, dl.fetch(uri).body);
});
}
bool scraper::is_blacklisted(std::string const& uri)
{
if(!blacklist.insert(uri).second) // Already visited uri
return true;
if(uri.find("%2F") != std::string::npos) // Bug in AH server, will get 404
return true;
if(uri.find("merk=100%") != std::string::npos) // Ditto
return true;
return false;
}
void scraper::order(page_t const& p)
{
if(is_blacklisted(p.uri))
return;
m.schedule(p.uri, [&, p](downloader::response const& response) {
process(p, response);
});
}
void scraper::process(const page_t ¤t_page, const downloader::response &response)
{
page_count++;
/* Two modes:
* - register_tags, fetches all products via the "Filters", goes through them in-order.
* - !register_tags, fetches all products via inline ProductLanes and SeeMore widgets
* The first takes an order more time than the second.
* The first actually maps all categories and tags, which do not change often.
* I suggest you run a scrape with this tag at most once a week.
* Use sparingly.
*/
Json::Value cat_root(parse(current_page.uri, response.body));
for(auto const& lane : cat_root["_embedded"]["lanes"])
{
if(register_tags && lane["id"].asString() == "Filters" && current_page.expand)
{
// Only process filters exhaustively if register_tags is enabled
parse_filterlane(lane, current_page);
}
else if(lane["type"].asString() == "ProductLane")
{
parse_productlane(lane, current_page);
}
else if(!register_tags && lane["type"].asString() == "SeeMoreLane")
{
parse_seemorelane(lane, current_page);
}
}
}
void scraper::add_tag_to_hierarchy_f(std::vector<message::tag> const& _parent_tags, message::tag const& current_tag)
{
if(current_tag.category != "Soort")
return; // Other categories do not possess an hierarchy.
std::vector<message::tag> parent_tags(_parent_tags.size());
std::reverse_copy(std::begin(_parent_tags), std::end(_parent_tags), std::begin(parent_tags));
auto parent_it = std::find_if(std::begin(parent_tags), std::end(parent_tags), [&](message::tag const& t){
return t.category == current_tag.category;
});
if(parent_it == std::end(parent_tags))
return; // Do not add
message::tag const& parent_tag = *parent_it;
auto hierarchy_it(tag_hierarchy.find(parent_tag));
if(hierarchy_it == std::end(tag_hierarchy))
tag_hierarchy.emplace(parent_tag, std::set<message::tag>({ current_tag }));
else
{
if(!hierarchy_it->second.emplace(current_tag).second)
return;
}
// Emit hierarchy finding
tag_hierarchy_callback(parent_tag, current_tag);
}
void scraper::parse_filterlane(Json::Value const& lane, page_t const& current_page)
{
for(auto const& filter_bar : lane["_embedded"]["items"])
{
if(filter_bar["resourceType"].asString() != "FilterBar")
std::runtime_error("Unexpected element under Filters");
for(auto const& filter : filter_bar["_embedded"]["filters"])
{
std::string filter_label = filter["label"].asString();
for(auto const& cat : filter["_embedded"]["filterItems"])
{
std::string uri = cat["navItem"]["link"]["href"].asString();
std::string title = cat["label"].asString();
remove_hyphens(title);
message::tag tag({title, filter_label});
add_tag_to_hierarchy_f(current_page.tags, tag);
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back(tag);
order({rest_uri + uri, title, true, tags});
}
break; // Only process first in bar, until none are left. (will fetch everything eventually)
}
}
}
void scraper::parse_productlane(Json::Value const& lane, page_t const& current_page)
{
std::string lane_name = lane["id"].asString();
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back({lane_name, std::string("Soort")});
for(auto const& lane_item : lane["_embedded"]["items"])
{
std::string lane_type = lane_item["type"].asString();
if(lane_type == "Product")
{
auto const& product = lane_item["_embedded"]["productCard"]["_embedded"]["product"];
interpreter::interpret(product, current_page, product_callback);
product_count++;
}
else if(!register_tags && lane_type == "SeeMore")
{
if(lane_item["navItem"]["link"]["pageType"] == "legacy") // Old-style page in SeeMore Editorial
continue;
order({rest_uri + lane_item["navItem"]["link"]["href"].asString(), lane_name, true, tags});
}
}
}
void scraper::parse_seemorelane(Json::Value const& lane, page_t const& current_page)
{
for(auto const& lane_item : lane["_embedded"]["items"])
{
std::string title = lane_item["text"]["title"].asString();
remove_hyphens(title);
std::string uri = lane_item["navItem"]["link"]["href"].asString();
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back({title, std::string("Soort")});
order({rest_uri + uri, title, true, tags});
}
}
void scraper::scrape()
{
product_count = 0;
page_count = 0;
error_count = 0;
Json::Value producten_root(download(rest_uri + "/producten"));
for(auto const& lane : producten_root["_embedded"]["lanes"])
{
if(lane["id"].asString() != "productCategoryNavigation")
continue;
for(auto const& cat : lane["_embedded"]["items"])
{
std::string title = cat["title"].asString();
std::string uri = cat["navItem"]["link"]["href"].asString();
remove_hyphens(title);
order({rest_uri + uri, title, true, {message::tag{title, std::string("Soort")}}});
}
}
m.process_all();
std::cerr << "Pages: " << page_count << ", products: " << product_count << ", errors: " << error_count << std::endl;
}
raw scraper::download_image(const std::string& uri)
{
std::string buf(dl.fetch(uri).body);
return raw(buf.data(), buf.length());
}
}
<commit_msg>Updated product<commit_after>#include <albert/scraper.hpp>
#include <iostream>
#include <deque>
#include <fstream>
#include <boost/locale.hpp>
#include <albert/util.hpp>
#include <albert/interpreter.hpp>
namespace supermarx
{
static const std::string domain_uri = "http://www.ah.nl";
static const std::string rest_uri = domain_uri + "/service/rest";
scraper::scraper(product_callback_t _product_callback, tag_hierarchy_callback_t _tag_hierarchy_callback, unsigned int _ratelimit, bool _cache, bool _register_tags)
: product_callback(_product_callback)
, tag_hierarchy_callback(_tag_hierarchy_callback)
, dl("supermarx albert/1.2", _ratelimit, _cache ? boost::optional<std::string>("./cache") : boost::none)
, m(dl, [&]() { error_count++; })
, register_tags(_register_tags)
, todo()
, blacklist()
, tag_hierarchy()
, product_count(0)
, page_count(0)
, error_count(0)
{}
Json::Value scraper::parse(std::string const& uri, std::string const& body)
{
Json::Value root;
Json::Reader reader;
if(!body.empty() && !reader.parse(body, root, false))
{
dl.clear(uri);
throw std::runtime_error("Could not parse json feed");
}
return root;
}
Json::Value scraper::download(std::string const& uri)
{
return stubborn::attempt<Json::Value>([&](){
return parse(uri, dl.fetch(uri).body);
});
}
bool scraper::is_blacklisted(std::string const& uri)
{
if(!blacklist.insert(uri).second) // Already visited uri
return true;
if(uri.find("%2F") != std::string::npos) // Bug in AH server, will get 404
return true;
if(uri.find("merk=100%") != std::string::npos) // Ditto
return true;
return false;
}
void scraper::order(page_t const& p)
{
if(is_blacklisted(p.uri))
return;
m.schedule(p.uri, [&, p](downloader::response const& response) {
process(p, response);
});
}
void scraper::process(const page_t ¤t_page, const downloader::response &response)
{
page_count++;
/* Two modes:
* - register_tags, fetches all products via the "Filters", goes through them in-order.
* - !register_tags, fetches all products via inline ProductLanes and SeeMore widgets
* The first takes an order more time than the second.
* The first actually maps all categories and tags, which do not change often.
* I suggest you run a scrape with this tag at most once a week.
* Use sparingly.
*/
Json::Value cat_root(parse(current_page.uri, response.body));
for(auto const& lane : cat_root["_embedded"]["lanes"])
{
if(register_tags && lane["id"].asString() == "Filters" && current_page.expand)
{
// Only process filters exhaustively if register_tags is enabled
parse_filterlane(lane, current_page);
}
else if(lane["type"].asString() == "ProductLane")
{
parse_productlane(lane, current_page);
}
else if(!register_tags && lane["type"].asString() == "SeeMoreLane")
{
parse_seemorelane(lane, current_page);
}
}
}
void scraper::add_tag_to_hierarchy_f(std::vector<message::tag> const& _parent_tags, message::tag const& current_tag)
{
if(current_tag.category != "Soort")
return; // Other categories do not possess an hierarchy.
std::vector<message::tag> parent_tags(_parent_tags.size());
std::reverse_copy(std::begin(_parent_tags), std::end(_parent_tags), std::begin(parent_tags));
auto parent_it = std::find_if(std::begin(parent_tags), std::end(parent_tags), [&](message::tag const& t){
return t.category == current_tag.category;
});
if(parent_it == std::end(parent_tags))
return; // Do not add
message::tag const& parent_tag = *parent_it;
auto hierarchy_it(tag_hierarchy.find(parent_tag));
if(hierarchy_it == std::end(tag_hierarchy))
tag_hierarchy.emplace(parent_tag, std::set<message::tag>({ current_tag }));
else
{
if(!hierarchy_it->second.emplace(current_tag).second)
return;
}
// Emit hierarchy finding
tag_hierarchy_callback(parent_tag, current_tag);
}
void scraper::parse_filterlane(Json::Value const& lane, page_t const& current_page)
{
for(auto const& filter_bar : lane["_embedded"]["items"])
{
if(filter_bar["resourceType"].asString() != "FilterBar")
std::runtime_error("Unexpected element under Filters");
for(auto const& filter : filter_bar["_embedded"]["filters"])
{
std::string filter_label = filter["label"].asString();
for(auto const& cat : filter["_embedded"]["filterItems"])
{
std::string uri = cat["navItem"]["link"]["href"].asString();
std::string title = cat["label"].asString();
remove_hyphens(title);
message::tag tag({title, filter_label});
add_tag_to_hierarchy_f(current_page.tags, tag);
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back(tag);
order({rest_uri + uri, title, true, tags});
}
break; // Only process first in bar, until none are left. (will fetch everything eventually)
}
}
}
void scraper::parse_productlane(Json::Value const& lane, page_t const& current_page)
{
std::string lane_name = lane["id"].asString();
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back({lane_name, std::string("Soort")});
for(auto const& lane_item : lane["_embedded"]["items"])
{
std::string lane_type = lane_item["type"].asString();
if(lane_type == "Product")
{
auto const& product = lane_item["_embedded"]["product"];
interpreter::interpret(product, current_page, product_callback);
product_count++;
}
else if(!register_tags && lane_type == "SeeMore")
{
if(lane_item["navItem"]["link"]["pageType"] == "legacy") // Old-style page in SeeMore Editorial
continue;
order({rest_uri + lane_item["navItem"]["link"]["href"].asString(), lane_name, true, tags});
}
}
}
void scraper::parse_seemorelane(Json::Value const& lane, page_t const& current_page)
{
for(auto const& lane_item : lane["_embedded"]["items"])
{
std::string title = lane_item["text"]["title"].asString();
remove_hyphens(title);
std::string uri = lane_item["navItem"]["link"]["href"].asString();
std::vector<message::tag> tags;
tags.insert(tags.end(), current_page.tags.begin(), current_page.tags.end());
tags.push_back({title, std::string("Soort")});
order({rest_uri + uri, title, true, tags});
}
}
void scraper::scrape()
{
product_count = 0;
page_count = 0;
error_count = 0;
Json::Value producten_root(download(rest_uri + "/producten"));
for(auto const& lane : producten_root["_embedded"]["lanes"])
{
if(lane["id"].asString() != "productCategoryNavigation")
continue;
for(auto const& cat : lane["_embedded"]["items"])
{
std::string title = cat["title"].asString();
std::string uri = cat["navItem"]["link"]["href"].asString();
remove_hyphens(title);
order({rest_uri + uri, title, true, {message::tag{title, std::string("Soort")}}});
}
}
m.process_all();
std::cerr << "Pages: " << page_count << ", products: " << product_count << ", errors: " << error_count << std::endl;
}
raw scraper::download_image(const std::string& uri)
{
std::string buf(dl.fetch(uri).body);
return raw(buf.data(), buf.length());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 by Chani Armitage <[email protected]>
* Copyright 2013 by Thorsten Staerk <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "launch.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneWheelEvent>
#include <QFileInfo>
#include <KDebug>
#include <KIcon>
#include <KMenu>
#include <Plasma/DataEngine>
#include <Plasma/Containment>
#include <Plasma/Service>
ConTextMenu::ConTextMenu(QObject *parent, const QVariantList &args)
: Plasma::ContainmentActions(parent, args)
, m_action(new QAction(this))
{
m_menu = new KMenu();
connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(switchTo(QAction*)));
m_action->setMenu(m_menu);
}
ConTextMenu::~ConTextMenu()
{
delete m_menu;
}
void ConTextMenu::init(const KConfigGroup &)
{
}
void ConTextMenu::contextEvent(QEvent *event)
{
makeMenu();
m_menu->adjustSize();
m_menu->exec(popupPosition(m_menu->size(), event));
}
void ConTextMenu::makeMenu()
{
addApps(m_menu);
}
QList<QAction *> ConTextMenu::contextualActions()
{
m_menu->clear(); // otherwise every time you build it it will duplicate its content
makeMenu();
QList<QAction *> list;
list << m_action;
return list;
}
bool ConTextMenu::addApps(QMenu *menu)
{
menu->clear();
QAction* action = menu->addAction(KIcon("system-run"), "Open a console");
action->setData("kde4-konsole.desktop");
action = menu->addAction(KIcon("firefox"), "Surf the web");
action->setData("firefox.desktop");
action = menu->addAction(KIcon("ksnapshot"), "Take a screenshot");
action->setData("kde4-ksnapshot.desktop");
QAction* sep1 = new QAction(this);
sep1->setSeparator(true);
menu->addAction(sep1);
Plasma::Containment *c = containment();
Q_ASSERT(c);
menu->addAction(c->action("configure"));
return true;
}
void ConTextMenu::switchTo(QAction *action)
{
QString source = action->data().toString();
kDebug() << source;
Plasma::Service *service = dataEngine("apps")->serviceForSource(source);
if (service)
{
service->startOperationCall(service->operationDescription("launch"));
}
}
#include "launch.moc"
<commit_msg>starting with the KConfig frameWork<commit_after>/*
* Copyright 2009 by Chani Armitage <[email protected]>
* Copyright 2013 by Thorsten Staerk <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "launch.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneWheelEvent>
#include <QFileInfo>
#include <KDebug>
#include <KIcon>
#include <KMenu>
#include <KSharedConfig>
#include <Plasma/DataEngine>
#include <Plasma/Containment>
#include <Plasma/Service>
ConTextMenu::ConTextMenu(QObject *parent, const QVariantList &args)
: Plasma::ContainmentActions(parent, args)
, m_action(new QAction(this))
{
KSharedConfigPtr config = KGlobal::config();
// This only works with Linux but it will print the name of the actual config file
QString qs("echo '");
qs.append(config->name());
qs.append("' >>/tmp/test");
qs.toAscii().constData();
system(qs.toAscii().constData());
m_menu = new KMenu();
connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(switchTo(QAction*)));
m_action->setMenu(m_menu);
}
ConTextMenu::~ConTextMenu()
{
delete m_menu;
}
void ConTextMenu::init(const KConfigGroup &)
{
}
void ConTextMenu::contextEvent(QEvent *event)
{
makeMenu();
m_menu->adjustSize();
m_menu->exec(popupPosition(m_menu->size(), event));
}
void ConTextMenu::makeMenu()
{
addApps(m_menu);
}
QList<QAction *> ConTextMenu::contextualActions()
{
m_menu->clear(); // otherwise every time you build it it will duplicate its content
makeMenu();
QList<QAction *> list;
list << m_action;
return list;
}
bool ConTextMenu::addApps(QMenu *menu)
{
menu->clear();
QAction* action = menu->addAction(KIcon("system-run"), "Open a console");
action->setData("kde4-konsole.desktop");
action = menu->addAction(KIcon("firefox"), "Surf the web");
action->setData("firefox.desktop");
action = menu->addAction(KIcon("ksnapshot"), "Take a screenshot");
action->setData("kde4-ksnapshot.desktop");
QAction* sep1 = new QAction(this);
sep1->setSeparator(true);
menu->addAction(sep1);
Plasma::Containment *c = containment();
Q_ASSERT(c);
menu->addAction(c->action("configure"));
return true;
}
void ConTextMenu::switchTo(QAction *action)
{
QString source = action->data().toString();
kDebug() << source;
Plasma::Service *service = dataEngine("apps")->serviceForSource(source);
if (service)
{
service->startOperationCall(service->operationDescription("launch"));
}
}
#include "launch.moc"
<|endoftext|> |
<commit_before>
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "tool3.h"
#include <Richedit.h>
#include "MainFrm.h"
#include <map>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
extern VOID c(VOID *);
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CWnd)
ON_WM_CREATE()
ON_BN_CLICKED(2133,tr)
ON_BN_CLICKED(233,w)
ON_BN_CLICKED(2233,uw)
ON_BN_CLICKED(22,ef)
ON_WM_DESTROY()
ON_REGISTERED_MESSAGE(WM_ret, &CMainFrame::OnRet) //that's a piece of class wizard production after "Add cutom message" with "registered message".
// WM_ret stays undefined that moment so .
ON_WM_CLOSE()
ON_MESSAGE(WM_CTLCOLORSTATIC, &CMainFrame::OnCtlcolorstatic)
END_MESSAGE_MAP()
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
// CMainFrame message handlers
class r:public CFolderPickerDialog
{
public:
CString f;
int last;
void init() { f = m_szFileName; }
};
r *t;
HWND hc,hz;
CProgressCtrl *dc;
CProgressCtrl *t7;
CButton *bh;
CButton *q;
CButton *finA;
CButton *cmdos;
CStatic *b7;
ITaskbarList3 *bhr;
HANDLE cl;
DWORD CALLBACK E(DWORD_PTR dw, LPBYTE pb, LONG cb, LONG *pcb)
{
std::wstringstream *fr = (std::wstringstream *)dw;
fr->write((wchar_t *)pb, int(cb/2));
*pcb = cb;
return 0;
}
std::map< state , std::wstring> braze;
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
t7= new CProgressCtrl();
dc= new CProgressCtrl();
cl=CreateEvent(NULL,1,0,NULL);
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
bh=new CButton();
b7=new CStatic();
q=new CButton();
finA=new CButton();
cmdos=new CButton();
CBitmap wq[2];
wq[0].LoadBitmap(IDB_BITMAP1);
wq[1].LoadBitmap(IDB_BITMAP4);
wchar_t w[740];
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.",w,740);
FILE *xf;
_wfopen_s(&xf,w,L"r+");
DWORD c = 0;
if(xf)
{
fwscanf(xf,L"%[^\n]%*c",remmi); //stuff from msdn. works with and w/o \n
t=new r();
t->f = remmi;
if(!(feof(xf)))
{
ZeroMemory(remmi,1218*2);
fwscanf(xf,L"%[^\n]%*c",remmi);
}
else
{
wcscpy_s(remmi,L"--block-sync-size 20 --db-sync-mode fastest:async:8750 --prep-blocks-threads 4");
fwprintf(xf,L"\n%s",remmi); // r+ shifts write pos when read.
}
fclose(xf);
}
else
{
c=WS_DISABLED;
wcscpy_s(remmi,L"--block-sync-size 20 --db-sync-mode fastest:async:8750 --prep-blocks-threads 4");
t=NULL;
}
braze.insert(std::map< state , std::wstring>::value_type( q_quit, L"quit"));
braze.insert(std::map< state , std::wstring>::value_type( q_gundrop, L"gundrop"));
braze.insert(std::map< state , std::wstring>::value_type( q_stay, L"stay"));
braze.insert(std::map< state , std::wstring>::value_type( q_stop, L"q_stop"));
braze.insert(std::map< state , std::wstring>::value_type( q_torque, L"torque"));
bh->Create(L"start",BS_BITMAP|WS_CHILD|WS_VISIBLE|c,CRect(50,50,170,100),this,2133);
bh->SetBitmap(wq[0]);
q->Create(L"stop",BS_BITMAP|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(50+170,50,170+170,100),this,233);
q->SetBitmap(wq[1]);
finA->Create(L"locate",BS_TEXT|WS_CHILD|WS_VISIBLE,CRect(0+270,20+292,59+270,48+292),this,2233);
cmdos->Create(L"commandos",BS_TEXT|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(0+337,20+292,97+341,48+292),this,22);
dc->Create(WS_VISIBLE|WS_CHILD|PBS_SMOOTH,CRect(120,100+130,120+220,100+170),this,21);
t7->Create(WS_VISIBLE|WS_CHILD|PBS_VERTICAL|PBS_SMOOTHREVERSE|PBS_SMOOTH,CRect(10,200,10+19,200+140),this,129);
t7->SetRange(0,140);
b7->Create(L"to go :",WS_CHILD|WS_VISIBLE|SS_WHITEFRAME|SS_SIMPLE,CRect(40,290,373,320),this);
hc=CreateWindowEx(WS_EX_NOPARENTNOTIFY, MSFTEDIT_CLASS,remmi,
ES_MULTILINE|ES_AUTOVSCROLL| WS_VISIBLE | WS_CHILD |WS_TABSTOP|WS_VSCROLL,
1, 350, 450, 201,
this->m_hWnd, NULL, h, NULL);
HFONT newFont = CreateFont(22, 0, 0, 0,0 , FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_NATURAL_QUALITY,
DEFAULT_PITCH | FF_DECORATIVE, L"Lucida Console");
::PostMessage(hc,WM_SETFONT,(WPARAM)newFont,(LPARAM)0);
hz=this->m_hWnd;
::PostMessage(b7->m_hWnd,WM_SETFONT,(WPARAM)newFont,(LPARAM)0);
return 0;
}
HANDLE stdinRd, stdinWr, stdoutRd, stdoutWr;
state bren = q_stay;
int cr,f,terminator;
PROCESS_INFORMATION pi;
int terminator2;
void CMainFrame::tr() // bh->Create(L"start",BS_BITMAP|WS_CHILD|WS_VISIBLE|c,CRect(50,50,170,100),this,2133);
{
std::wstringstream fr;
EDITSTREAM es = {};
if(trigger)
{
es.dwCookie = (DWORD_PTR) &fr;
es.pfnCallback = E;
::SendMessage(hc, EM_STREAMOUT, SF_TEXT|SF_UNICODE, (LPARAM)&es);
if(!iswspace(*fr.str().cbegin())) fr.str(L' ' + fr.str());
ZeroMemory(remmi,1218*2);
fr.read(remmi,747);
trigger=0;
}
SECURITY_ATTRIBUTES sa={sizeof(SECURITY_ATTRIBUTES), NULL, true};
CreatePipe(&stdinRd, &stdinWr, &sa, 10000);
CreatePipe(&stdoutRd,&stdoutWr, &sa,500000);
if(pi.hProcess) CloseHandle(pi.hProcess);
STARTUPINFO si = {};
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = stdoutWr;
si.hStdError = stdoutWr;
si.hStdInput = stdinRd;
int h=CreateProcess(t->f + L"\\monerod.exe",remmi, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, NULL, t->f, &si, &pi);
if(!h)
{
MessageBox(L"Bad start,check location");
return;
}
bren=q_torque;
rew=AfxBeginThread((AFX_THREADPROC)c,NULL);
}
void CMainFrame::w() // q->Create(L"stop",BS_BITMAP|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(50+170,50,170+170,100),this,233);
{
bren = bren == q_quit ? bren : q_stop;
char k[100];
strcpy(k,"exit\n");
DWORD numberofbyteswritten;
WriteFile(stdinWr, k, 5, &numberofbyteswritten, NULL);
}
void CMainFrame::uw() // finA->Create(L"locate",BS_TEXT|WS_CHILD|WS_VISIBLE,CRect(0+280,20+292,59+280,48+292),this,2233);
{
if(!t) t=new r();
int c= t->DoModal();
wchar_t w[740];
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.",w,730);
FILE *xf;
if(c==IDOK)
{
xf=_wfopen(w,L"w+");
t->init();
fwprintf(xf,L"%s",t->f);
fwprintf(xf,L"\n%s",remmi);
fclose(xf);
bh->EnableWindow();
}
else if(t->f.IsEmpty()) { delete t; t=NULL; }
}
HBRUSH hbrBkgnd;
void CMainFrame::OnDestroy()
{
CWnd::OnDestroy();
if(t) delete t;
delete bh;
delete q;
delete dc;
delete finA;
delete cmdos;
delete t7;
delete b7;
// delete rew;
DeleteObject(hbrBkgnd);
}
VOID hammer(VOID *)
{
CoInitializeEx(NULL,COINIT_MULTITHREADED); //used only by extra thread for now
CoCreateInstance(CLSID_TaskbarList,NULL,CLSCTX_INPROC_SERVER,IID_ITaskbarList3,(LPVOID*)&bhr); //no inter-process here.pointer grabs smth finally
bhr->HrInit(); //not sure
WaitForSingleObject(cl,INFINITE);
bhr->Release();
bhr=NULL; // recommendation about to deal with COM
CoUninitialize();
}
afx_msg LRESULT CMainFrame::OnRet(WPARAM wParam, LPARAM lParam) //Win7 progress bar over a taskbar's bay of this app. WM_ret finished up here.
{
rewh = AfxBeginThread((AFX_THREADPROC)hammer,NULL);
return 0;
}
void CMainFrame::OnClose()
{
FILE *xf;
wchar_t w[840],ferrum[324];
DWORD c;
switch (bren)
{
case q_quit:
c = WaitForSingleObject(pi.hProcess, 0);
if (c != WAIT_TIMEOUT)
{
SetEvent(cl);
if (t)
{
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.", w, 930);
xf = _wfopen(w, L"w+");
fwprintf(xf, L"%s", t->f);
if (remmi[0] == L' ')fwprintf(xf, L"\n%s", &remmi[1]);
else fwprintf(xf, L"\n%s", remmi);
fclose(xf);
}
WaitForSingleObject(rewh->m_hThread, INFINITE);
CWnd::OnClose();
}
break;
case q_stay:
SetEvent(cl);
if (t)
{
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.", w, 1310);
xf = _wfopen(w, L"w+");
fwprintf(xf, L"%s", t->f);
if (remmi[0] == L' ') fwprintf(xf, L"\n%s", &remmi[1]);
else fwprintf(xf, L"\n%s", remmi);
fclose(xf);
}
WaitForSingleObject(rewh->m_hThread, INFINITE);
CWnd::OnClose();
break;
default:
if (*braze[bren].crbegin() != L'q') { bren = q_quit; this->w(); }
bren = q_quit;
break;
}
}
void CMainFrame::ef()
{
SETTEXTEX fw;
fw.flags=4;
fw.codepage=1200;
::SendMessage(hc,EM_SETTEXTEX,(WPARAM)&fw,(LPARAM)remmi);
trigger = bren == q_stay;
}
afx_msg LRESULT CMainFrame::OnCtlcolorstatic(WPARAM wParam, LPARAM lParam)
{
HDC hdcStatic = (HDC)wParam;
SetTextColor(hdcStatic, RGB(2, 5, 55));
SetBkColor(hdcStatic, RGB(255, 255, 255));
if (hbrBkgnd == NULL) hbrBkgnd = CreateSolidBrush(RGB(255, 255, 255));
return (INT_PTR)hbrBkgnd;
}
<commit_msg>no message<commit_after>
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "tool3.h"
#include <Richedit.h>
#include "MainFrm.h"
#include <map>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
extern VOID c(VOID *);
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CWnd)
ON_WM_CREATE()
ON_BN_CLICKED(2133,tr)
ON_BN_CLICKED(233,w)
ON_BN_CLICKED(2233,uw)
ON_BN_CLICKED(22,ef)
ON_WM_DESTROY()
ON_REGISTERED_MESSAGE(WM_ret, &CMainFrame::OnRet) //that's a piece of class wizard production after "Add cutom message" with "registered message".
// WM_ret stays undefined that moment so .
ON_WM_CLOSE()
ON_MESSAGE(WM_CTLCOLORSTATIC, &CMainFrame::OnCtlcolorstatic)
END_MESSAGE_MAP()
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
// CMainFrame message handlers
class r:public CFolderPickerDialog
{
public:
CString f;
int last;
void init() { f = m_szFileName; }
};
r *t;
HWND hc,hz;
CProgressCtrl *dc;
CProgressCtrl *t7;
CButton *bh;
CButton *q;
CButton *finA;
CButton *cmdos;
CStatic *b7;
ITaskbarList3 *bhr;
HANDLE cl;
DWORD CALLBACK E(DWORD_PTR dw, LPBYTE pb, LONG cb, LONG *pcb)
{
std::wstringstream *fr = (std::wstringstream *)dw;
fr->write((wchar_t *)pb, int(cb/2));
*pcb = cb;
return 0;
}
std::map< state , std::wstring> braze;
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
t7= new CProgressCtrl();
dc= new CProgressCtrl();
cl=CreateEvent(NULL,1,0,NULL);
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
bh=new CButton();
b7=new CStatic();
q=new CButton();
finA=new CButton();
cmdos=new CButton();
CBitmap wq[2];
wq[0].LoadBitmap(IDB_BITMAP1);
wq[1].LoadBitmap(IDB_BITMAP4);
wchar_t w[740];
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.",w,740);
FILE *xf;
_wfopen_s(&xf,w,L"r+");
DWORD c = 0;
if(xf)
{
fwscanf(xf,L"%[^\n]%*c",remmi); //stuff from msdn. works with and w/o \n
t=new r();
t->f = remmi;
if(!(feof(xf)))
{
ZeroMemory(remmi,1218*2);
fwscanf(xf,L"%[^\n]%*c",remmi);
}
else
{
wcscpy_s(remmi,L"--block-sync-size 20 --db-sync-mode fastest:async:8750 --prep-blocks-threads 4");
fwprintf(xf,L"\n%s",remmi); // r+ shifts write pos when read.
}
fclose(xf);
}
else
{
c=WS_DISABLED;
wcscpy_s(remmi,L"--block-sync-size 20 --db-sync-mode fastest:async:8750 --prep-blocks-threads 4");
t=NULL;
}
braze[q_quit]= L"quit";
braze[q_gundrop]= L"gundrop";
braze[q_stay] = L"stay";
braze[q_stop]= L"q_stop";
braze[q_torque] = L"torque";
bh->Create(L"start",BS_BITMAP|WS_CHILD|WS_VISIBLE|c,CRect(50,50,170,100),this,2133);
bh->SetBitmap(wq[0]);
q->Create(L"stop",BS_BITMAP|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(50+170,50,170+170,100),this,233);
q->SetBitmap(wq[1]);
finA->Create(L"locate",BS_TEXT|WS_CHILD|WS_VISIBLE,CRect(0+270,20+292,59+270,48+292),this,2233);
cmdos->Create(L"commandos",BS_TEXT|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(0+337,20+292,97+341,48+292),this,22);
dc->Create(WS_VISIBLE|WS_CHILD|PBS_SMOOTH,CRect(120,100+130,120+220,100+170),this,21);
t7->Create(WS_VISIBLE|WS_CHILD|PBS_VERTICAL|PBS_SMOOTHREVERSE|PBS_SMOOTH,CRect(10,200,10+19,200+140),this,129);
t7->SetRange(0,140);
b7->Create(L"to go :",WS_CHILD|WS_VISIBLE|SS_WHITEFRAME|SS_SIMPLE,CRect(40,290,373,320),this);
hc=CreateWindowEx(WS_EX_NOPARENTNOTIFY, MSFTEDIT_CLASS,remmi,
ES_MULTILINE|ES_AUTOVSCROLL| WS_VISIBLE | WS_CHILD |WS_TABSTOP|WS_VSCROLL,
1, 350, 450, 201,
this->m_hWnd, NULL, h, NULL);
HFONT newFont = CreateFont(22, 0, 0, 0,0 , FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_NATURAL_QUALITY,
DEFAULT_PITCH | FF_DECORATIVE, L"Lucida Console");
::PostMessage(hc,WM_SETFONT,(WPARAM)newFont,(LPARAM)0);
hz=this->m_hWnd;
::PostMessage(b7->m_hWnd,WM_SETFONT,(WPARAM)newFont,(LPARAM)0);
return 0;
}
HANDLE stdinRd, stdinWr, stdoutRd, stdoutWr;
state bren = q_stay;
int cr,f,terminator;
PROCESS_INFORMATION pi;
int terminator2;
void CMainFrame::tr() // bh->Create(L"start",BS_BITMAP|WS_CHILD|WS_VISIBLE|c,CRect(50,50,170,100),this,2133);
{
std::wstringstream fr;
EDITSTREAM es = {};
if(trigger)
{
es.dwCookie = (DWORD_PTR) &fr;
es.pfnCallback = E;
::SendMessage(hc, EM_STREAMOUT, SF_TEXT|SF_UNICODE, (LPARAM)&es);
if(!iswspace(*fr.str().cbegin())) fr.str(L' ' + fr.str());
ZeroMemory(remmi,1218*2);
fr.read(remmi,747);
trigger=0;
}
SECURITY_ATTRIBUTES sa={sizeof(SECURITY_ATTRIBUTES), NULL, true};
CreatePipe(&stdinRd, &stdinWr, &sa, 10000);
CreatePipe(&stdoutRd,&stdoutWr, &sa,500000);
if(pi.hProcess) CloseHandle(pi.hProcess);
STARTUPINFO si = {};
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = stdoutWr;
si.hStdError = stdoutWr;
si.hStdInput = stdinRd;
int h=CreateProcess(t->f + L"\\monerod.exe",remmi, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, NULL, t->f, &si, &pi);
if(!h)
{
MessageBox(L"Bad start,check location");
return;
}
bren=q_torque;
rew=AfxBeginThread((AFX_THREADPROC)c,NULL);
}
void CMainFrame::w() // q->Create(L"stop",BS_BITMAP|WS_CHILD|WS_VISIBLE|WS_DISABLED,CRect(50+170,50,170+170,100),this,233);
{
bren = bren == q_quit ? bren : q_stop;
char k[100];
strcpy(k,"exit\n");
DWORD numberofbyteswritten;
WriteFile(stdinWr, k, 5, &numberofbyteswritten, NULL);
}
void CMainFrame::uw() // finA->Create(L"locate",BS_TEXT|WS_CHILD|WS_VISIBLE,CRect(0+280,20+292,59+280,48+292),this,2233);
{
if(!t) t=new r();
int c= t->DoModal();
wchar_t w[740];
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.",w,730);
FILE *xf;
if(c==IDOK)
{
xf=_wfopen(w,L"w+");
t->init();
fwprintf(xf,L"%s",t->f);
fwprintf(xf,L"\n%s",remmi);
fclose(xf);
bh->EnableWindow();
}
else if(t->f.IsEmpty()) { delete t; t=NULL; }
}
HBRUSH hbrBkgnd;
void CMainFrame::OnDestroy()
{
CWnd::OnDestroy();
if(t) delete t;
delete bh;
delete q;
delete dc;
delete finA;
delete cmdos;
delete t7;
delete b7;
// delete rew;
DeleteObject(hbrBkgnd);
}
VOID hammer(VOID *)
{
CoInitializeEx(NULL,COINIT_MULTITHREADED); //used only by extra thread for now
CoCreateInstance(CLSID_TaskbarList,NULL,CLSCTX_INPROC_SERVER,IID_ITaskbarList3,(LPVOID*)&bhr); //no inter-process here.pointer grabs smth finally
bhr->HrInit(); //not sure
WaitForSingleObject(cl,INFINITE);
bhr->Release();
bhr=NULL; // recommendation about to deal with COM
CoUninitialize();
}
afx_msg LRESULT CMainFrame::OnRet(WPARAM wParam, LPARAM lParam) //Win7 progress bar over a taskbar's bay of this app. WM_ret finished up here.
{
rewh = AfxBeginThread((AFX_THREADPROC)hammer,NULL);
return 0;
}
void CMainFrame::OnClose()
{
FILE *xf;
wchar_t w[840],ferrum[324];
DWORD c;
switch (bren)
{
case q_quit:
c = WaitForSingleObject(pi.hProcess, 0);
if (c != WAIT_TIMEOUT)
{
SetEvent(cl);
if (t)
{
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.", w, 930);
xf = _wfopen(w, L"w+");
fwprintf(xf, L"%s", t->f);
if (remmi[0] == L' ')fwprintf(xf, L"\n%s", &remmi[1]);
else fwprintf(xf, L"\n%s", remmi);
fclose(xf);
}
WaitForSingleObject(rewh->m_hThread, INFINITE);
CWnd::OnClose();
}
break;
case q_stay:
SetEvent(cl);
if (t)
{
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents\\fold.", w, 1310);
xf = _wfopen(w, L"w+");
fwprintf(xf, L"%s", t->f);
if (remmi[0] == L' ') fwprintf(xf, L"\n%s", &remmi[1]);
else fwprintf(xf, L"\n%s", remmi);
fclose(xf);
}
WaitForSingleObject(rewh->m_hThread, INFINITE);
CWnd::OnClose();
break;
default:
if (*braze[bren].crbegin() != L'q') { bren = q_quit; this->w(); }
bren = q_quit;
break;
}
}
void CMainFrame::ef()
{
SETTEXTEX fw;
fw.flags=4;
fw.codepage=1200;
::SendMessage(hc,EM_SETTEXTEX,(WPARAM)&fw,(LPARAM)remmi);
trigger = bren == q_stay;
}
afx_msg LRESULT CMainFrame::OnCtlcolorstatic(WPARAM wParam, LPARAM lParam)
{
HDC hdcStatic = (HDC)wParam;
SetTextColor(hdcStatic, RGB(2, 5, 55));
SetBkColor(hdcStatic, RGB(255, 255, 255));
if (hbrBkgnd == NULL) hbrBkgnd = CreateSolidBrush(RGB(255, 255, 255));
return (INT_PTR)hbrBkgnd;
}
<|endoftext|> |
<commit_before>//======= Genetic.cpp - Guide to Exploration of Otimization's Set -*- C++ -*-==//
////
//// The LLVM Time Cost Analyser Infrastructure
////
//// This file is distributed under the MIT License. See LICENSE.txt for details.
////
////===----------------------------------------------------------------------===//
/////
///// \file
///// \brief This file implements a tool that, when given a llvm code and its
///// profiling information, returns the best otimization sequence from a genetic
///// algorithm.
/////
////===----------------------------------------------------------------------===//
#include "GEOS.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IR/LLVMContext.h"
#include "GEOSCommandLineParser.h"
#include "OfflineLearning/CodeMetricBase.h"
#include "OfflineLearning/AccuracyBase.h"
#include "OfflineLearning/CorrectionBase.h"
#include "OfflineLearning/OptAccuracyBase.h"
#include <vector>
#include <limits>
#include <random>
#include <signal.h>
#include <stdio.h>
#include <setjmp.h>
#include "papi.h"
#include <list>
#include <queue>
#include <float.h>
#include <cstdlib>
#include <ctime>
static cl::opt<std::string>
MBasePath("metrics", cl::desc("Base of metrics"),
cl::value_desc(".txt"));
static cl::alias
MBaseAlias("m", cl::desc("Alias for -metrics"), cl::aliasopt(MBasePath));
static cl::opt<std::string>
ABasePath("accuracy", cl::desc("Base of Accuracy"),
cl::value_desc(".txt"));
static cl::alias
ABaseAlias("a", cl::desc("Alias for -accuracy"), cl::aliasopt(ABasePath));
static cl::opt<std::string>
CBasePath("correction-folder", cl::desc("Folder with corrections"),
cl::value_desc(".txt"));
static cl::alias
CBaseAlias("cf", cl::desc("Alias for -correction-folder"), cl::aliasopt(CBasePath));
static cl::opt<std::string>
OABasePath("opt-accuracy-folder", cl::desc("Folder with accuracy for each otimization"),
cl::value_desc(".txt"));
static cl::alias
OABaseAlias("oaf", cl::desc("Alias for -opt-accuracy"), cl::aliasopt(OABasePath));
static cl::opt<unsigned> SIZE("pop-size", cl::desc("Size of population"));
static cl::alias SIZEAlias("s", cl::desc("Alias for -pop-size"),
cl::aliasopt(SIZE));
static cl::opt<unsigned> BSIZE("opt-list-size", cl::desc("Max size of best sequence list"));
static cl::alias BSIZEAlias("ols", cl::desc("Alias for best-sequence size"),
cl::aliasopt(BSIZE));
static cl::opt<unsigned> TSIZE("tournament-size", cl::desc("Max size of tournament"));
static cl::alias TSIZEAlias("ts", cl::desc("Alias for tournament size"),
cl::aliasopt(TSIZE));
static cl::opt<unsigned> NOPT("length-solution", cl::desc("Max total time (in seconds)"));
static cl::alias NOPTAlias("len", cl::desc("Alias for time-max"),
cl::aliasopt(NOPT));
static cl::opt<unsigned> TIME_MAX("time-max", cl::desc("Max total time (in seconds)"));
static cl::alias TIME_MAXAlias("tm", cl::desc("Alias for time-max"),
cl::aliasopt(TIME_MAX));
static cl::opt<unsigned> CYCLE_MAX("cycle-max", cl::desc("Max number of cycles"));
static cl::alias CYCLE_MAXAlias("cm", cl::desc("Alias for cycle-max"),
cl::aliasopt(CYCLE_MAX));
static cl::opt<double> MutationRate("mut-rate", cl::desc("Max total time (in seconds)"));
static cl::alias MutationRateAlias("pm", cl::desc("Alias for time-max"),
cl::aliasopt(MutationRate));
static cl::opt<double> CrossoverRate("cross-rate", cl::desc("Max total time (in seconds)"));
static cl::alias CrossoverRateAlias("pc", cl::desc("Alias for time-max"),
cl::aliasopt(CrossoverRate));
static cl::opt<int> Randomness("randomness", cl::desc("RandomCost"));
static cl::alias RandomnessAlias("rc", cl::desc("Alias for randomness"),
cl::aliasopt(Randomness));
#define SIZE_STD 100
#define NOPT_STD 70
#define BSIZE_STD 5
#define TSIZE_STD 5
#define TIME_MAX_STD 300
#define CYCLE_MAX_STD 50
#define CRATE_STD 0.8
#define MRATE_STD 0.01
double getRandomDouble() {
return rand()/RAND_MAX;
}
// ------------------------------- Types
typedef struct Solution {
PassSequence Sequence;
double Cost;
bool isCalculated;
Solution() {}
Solution(PassSequence P, double C = DBL_MAX, bool isC = false) {
Sequence = P;
Cost = C;
isCalculated = isC;
}
void setCost(double C) { Cost = C; isCalculated = true; }
Solution &operator=(Solution rhs) {
Sequence = rhs.Sequence;
Cost = rhs.Cost;
isCalculated = rhs.isCalculated;
return *this;
}
} Solution;
class CompareSolution {
double Accuracy;
bool getJudgement() const {
return (Accuracy >= getRandomDouble());
}
public:
CompareSolution(const double A = 1.0) {
Accuracy = (A + 1.0)/2;
}
bool operator()(Solution S1, Solution S2) const {
return ((S1.Cost > S2.Cost) == getJudgement());
}
};
typedef std::vector<Solution> PopT;
typedef std::priority_queue<Solution, PopT, CompareSolution> BestSeqT;
// ---------------------- Functions
void initializePopulation(PopT &Population) {
for (unsigned i = 0; i < SIZE; i++) {
PassSequence Sequence;
Sequence.randomize(NOPT);
Population.push_back(Solution(Sequence));
}
}
bool evaluate(Solution &S,
CorrectionBaseT CorrectionBase, OptAccuracyBaseT OptAccuracyBase,
std::shared_ptr<ProfileModule> PModule, CostEstimatorOptions Opts) {
if (S.isCalculated) return true;
auto NewCost = (rand() % 10) + 1;
if (!Randomness) {
auto PO = GEOS::applyPasses(PModule, S.Sequence);
if (!PO) return false;
NewCost = GEOS::analyseCost(PO, Opts);
}
if (MBasePath.empty()) {
auto OptAccuracy = getPassSequenceAccuracy
(S.Sequence, Opts, OptAccuracyBase);
NewCost /= getCorrectionFor(S.Sequence, Opts, CorrectionBase);
NewCost *= OptAccuracy;
}
S.setCost(NewCost);
return true;
}
void evaluatePopulation(PopT &Population,
CorrectionBaseT CorrectionBase, OptAccuracyBaseT OptAccuracyBase,
BestSeqT &BestSequences, std::shared_ptr<ProfileModule> PModule,
CostEstimatorOptions Opts, double EstimatedAccuracy) {
BestSeqT OrderedPop((CompareSolution(EstimatedAccuracy)));
BestSequences = BestSeqT(CompareSolution(EstimatedAccuracy));
for (auto &I : Population) {
evaluate(I, CorrectionBase, OptAccuracyBase, PModule, Opts);
OrderedPop.push(I);
}
for (unsigned i = 0; i < BSIZE; i++) {
BestSequences.push(OrderedPop.top());
OrderedPop.pop();
}
}
PopT selection(PopT Population, double EstimatedAccuracy) {
unsigned MSize = Population.size()/2, PSize = Population.size();
PopT MatingPool;
while (MatingPool.size() < MSize) {
BestSeqT Tournament((CompareSolution(EstimatedAccuracy)));
for (unsigned i = 0; i < TSIZE; i++) {
int Gene = rand() % PSize;
Tournament.push(Population[Gene]);
}
MatingPool.push_back(Tournament.top());
}
return MatingPool;
}
PopT crossover(PopT MatingPool) {
PopT NewPopulation;
int MSize = (int)MatingPool.size();
while (NewPopulation.size() <= SIZE) {
int ParentI = rand() % MSize;
int ParentJ = rand() % MSize;
if (CrossoverRate >= getRandomDouble()) {
PassSequence Crossover = MatingPool[ParentI].Sequence *
MatingPool[ParentJ].Sequence;
NewPopulation.push_back(Solution(Crossover));
} else {
NewPopulation.push_back(MatingPool[ParentI]);
NewPopulation.push_back(MatingPool[ParentJ]);
}
}
return NewPopulation;
}
void mutation(PopT &Population) {
PassSequence MutatedSeq;
int MaxOpt = static_cast<int>(OptimizationKind::tailcallelim);
for (auto S : Population) {
if (S.isCalculated) continue;
for (unsigned i = 0; i < S.Sequence.size(); i++) {
if (MutationRate >= getRandomDouble()) {
MutatedSeq.add(static_cast<OptimizationKind>(rand() % MaxOpt));
} else {
MutatedSeq.add(S.Sequence[i]);
}
}
S.Sequence = MutatedSeq;
}
}
bool isFinished(time_t Start, int Cycles) {
time_t total = time(0) - Start;
printf("Time:%ld\n", total);
if (CYCLE_MAX && TIME_MAX)
return (total >= (int)TIME_MAX || Cycles >= (int)CYCLE_MAX);
else if (TIME_MAX)
return (total >= (int)TIME_MAX);
else
return (Cycles >= (int)CYCLE_MAX);
}
int main(int argc, char** argv) {
srand(time(0));
GEOS::init();
LLVMContext &Context = getGlobalContext();
SMDiagnostic Error;
gcl::GEOSParseCommandLineOptions(argc, argv);
Module *MyModule =
parseIRFile(LLVMFilename.c_str(), Error, Context).release();
if (!SIZE) SIZE = SIZE_STD;
if (!BSIZE) BSIZE = BSIZE_STD;
if (!TSIZE) TSIZE = TSIZE_STD;
if (!NOPT) NOPT = NOPT_STD;
if (!TIME_MAX && !CYCLE_MAX) TIME_MAX = TIME_MAX_STD;
if (!MutationRate) MutationRate = MRATE_STD;
if (!CrossoverRate) CrossoverRate = CRATE_STD;
std::shared_ptr<ProfileModule> PModule(new ProfileModule(MyModule));
CostEstimatorOptions Opts = gcl::populatePModule(PModule);
double EstimatedAccuracy = 1;
OptAccuracyBaseT OptAccuracyBase;
CorrectionBaseT CorrectionBase;
if (!MBasePath.empty() && !ABasePath.empty() && !CBasePath.empty() && !OABasePath.empty()) {
auto MetricBase = loadMetricsBase(MBasePath);
auto AccuracyBase = loadAccuracyBase(ABasePath);
auto NearestMetricName = getNearestMetric(PModule, MetricBase);
EstimatedAccuracy =
getAccuracyFor(NearestMetricName, Opts, AccuracyBase);
CorrectionBase =
loadCorrectionBase(CBasePath+"/"+NearestMetricName+".estr");
OptAccuracyBase =
loadOptAccuracyBase(OABasePath+"/"+NearestMetricName+".ocor");
}
int PAPIEvents[1] = {PAPI_TOT_CYC};
double RealInitCost =
(GEOS::getPAPIProfile(PModule, ExecutionKind::JIT, PAPIEvents, 1))[0];
double InitCost;
if (Randomness)
InitCost = (rand() % 10) + 1;
else
InitCost = GEOS::analyseCost(PModule, Opts);
int Cycles = 0;
CompareSolution CompSolVar(EstimatedAccuracy);
BestSeqT BestSequences((CompareSolution(EstimatedAccuracy)));
BestSeqT GlobalBest((CompareSolution(EstimatedAccuracy)));
PopT Population;
printf("Starting genetic...\n");
initializePopulation(Population);
evaluatePopulation(Population, CorrectionBase, OptAccuracyBase,
BestSequences, PModule, Opts, EstimatedAccuracy);
time_t Start = time(0);
while (!isFinished(Start, Cycles)) {
PopT MatingPool =
selection(Population, EstimatedAccuracy);
Population =
crossover(MatingPool);
mutation(Population);
evaluatePopulation(Population, CorrectionBase, OptAccuracyBase,
BestSequences, PModule, Opts, EstimatedAccuracy);
BestSeqT Aux((CompareSolution(EstimatedAccuracy)));
for (unsigned i = 0; i < BSIZE; i++) {
Aux.push(BestSequences.top());
BestSequences.pop();
if (GlobalBest.size()) {
Aux.push(GlobalBest.top());
GlobalBest.pop();
}
}
GlobalBest = BestSeqT(CompareSolution(EstimatedAccuracy));
for (unsigned i = 0; i < BSIZE; i++) {
GlobalBest.push(Aux.top());
Aux.pop();
}
Cycles += 1;
printf("Cycles: %d - ", Cycles);
}
double BestRealSpeedUp = 0;
double BestEstSpeedUp = 0;
Solution BestSolution;
while (BestSequences.size() != 0) {
auto B = BestSequences.top();
auto PO = GEOS::applyPasses(PModule, B.Sequence);
double RealFinalCost =
(GEOS::getPAPIProfile(PO, ExecutionKind::JIT, PAPIEvents, 1))[0];
double FinalCost;
if (Randomness) FinalCost = (rand() % 10) + 1;
else FinalCost = GEOS::analyseCost(PO, Opts);
if ((RealInitCost/RealFinalCost) > BestRealSpeedUp) {
BestRealSpeedUp = RealInitCost/RealFinalCost;
BestEstSpeedUp = InitCost/FinalCost;
BestSolution = B;
}
BestSequences.pop();
}
while (GlobalBest.size() != 0) {
auto B = GlobalBest.top();
auto PO = GEOS::applyPasses(PModule, B.Sequence);
double RealFinalCost =
(GEOS::getPAPIProfile(PO, ExecutionKind::JIT, PAPIEvents, 1))[0];
double FinalCost;
if (Randomness) FinalCost = (rand() % 10) + 1;
else FinalCost = GEOS::analyseCost(PO, Opts);
if ((RealInitCost/RealFinalCost) > BestRealSpeedUp) {
BestRealSpeedUp = RealInitCost/RealFinalCost;
BestEstSpeedUp = InitCost/FinalCost;
BestSolution = B;
}
GlobalBest.pop();
}
printf("\n%f %f\n", BestEstSpeedUp,
BestRealSpeedUp);
return 0;
}
<commit_msg>Random in Genetic modified<commit_after>//======= Genetic.cpp - Guide to Exploration of Otimization's Set -*- C++ -*-==//
////
//// The LLVM Time Cost Analyser Infrastructure
////
//// This file is distributed under the MIT License. See LICENSE.txt for details.
////
////===----------------------------------------------------------------------===//
/////
///// \file
///// \brief This file implements a tool that, when given a llvm code and its
///// profiling information, returns the best otimization sequence from a genetic
///// algorithm.
/////
////===----------------------------------------------------------------------===//
#include "GEOS.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IR/LLVMContext.h"
#include "GEOSCommandLineParser.h"
#include "OfflineLearning/CodeMetricBase.h"
#include "OfflineLearning/AccuracyBase.h"
#include "OfflineLearning/CorrectionBase.h"
#include "OfflineLearning/OptAccuracyBase.h"
#include <vector>
#include <limits>
#include <random>
#include <signal.h>
#include <stdio.h>
#include <setjmp.h>
#include "papi.h"
#include <list>
#include <queue>
#include <float.h>
#include <cstdlib>
#include <ctime>
static cl::opt<std::string>
MBasePath("metrics", cl::desc("Base of metrics"),
cl::value_desc(".txt"));
static cl::alias
MBaseAlias("m", cl::desc("Alias for -metrics"), cl::aliasopt(MBasePath));
static cl::opt<std::string>
ABasePath("accuracy", cl::desc("Base of Accuracy"),
cl::value_desc(".txt"));
static cl::alias
ABaseAlias("a", cl::desc("Alias for -accuracy"), cl::aliasopt(ABasePath));
static cl::opt<std::string>
CBasePath("correction-folder", cl::desc("Folder with corrections"),
cl::value_desc(".txt"));
static cl::alias
CBaseAlias("cf", cl::desc("Alias for -correction-folder"), cl::aliasopt(CBasePath));
static cl::opt<std::string>
OABasePath("opt-accuracy-folder", cl::desc("Folder with accuracy for each otimization"),
cl::value_desc(".txt"));
static cl::alias
OABaseAlias("oaf", cl::desc("Alias for -opt-accuracy"), cl::aliasopt(OABasePath));
static cl::opt<unsigned> SIZE("pop-size", cl::desc("Size of population"));
static cl::alias SIZEAlias("s", cl::desc("Alias for -pop-size"),
cl::aliasopt(SIZE));
static cl::opt<unsigned> BSIZE("opt-list-size", cl::desc("Max size of best sequence list"));
static cl::alias BSIZEAlias("ols", cl::desc("Alias for best-sequence size"),
cl::aliasopt(BSIZE));
static cl::opt<unsigned> TSIZE("tournament-size", cl::desc("Max size of tournament"));
static cl::alias TSIZEAlias("ts", cl::desc("Alias for tournament size"),
cl::aliasopt(TSIZE));
static cl::opt<unsigned> NOPT("length-solution", cl::desc("Max total time (in seconds)"));
static cl::alias NOPTAlias("len", cl::desc("Alias for time-max"),
cl::aliasopt(NOPT));
static cl::opt<unsigned> TIME_MAX("time-max", cl::desc("Max total time (in seconds)"));
static cl::alias TIME_MAXAlias("tm", cl::desc("Alias for time-max"),
cl::aliasopt(TIME_MAX));
static cl::opt<unsigned> CYCLE_MAX("cycle-max", cl::desc("Max number of cycles"));
static cl::alias CYCLE_MAXAlias("cm", cl::desc("Alias for cycle-max"),
cl::aliasopt(CYCLE_MAX));
static cl::opt<double> MutationRate("mut-rate", cl::desc("Max total time (in seconds)"));
static cl::alias MutationRateAlias("pm", cl::desc("Alias for time-max"),
cl::aliasopt(MutationRate));
static cl::opt<double> CrossoverRate("cross-rate", cl::desc("Max total time (in seconds)"));
static cl::alias CrossoverRateAlias("pc", cl::desc("Alias for time-max"),
cl::aliasopt(CrossoverRate));
static cl::opt<int> Randomness("randomness", cl::desc("RandomCost"));
static cl::alias RandomnessAlias("rc", cl::desc("Alias for randomness"),
cl::aliasopt(Randomness));
#define SIZE_STD 100
#define NOPT_STD 70
#define BSIZE_STD 5
#define TSIZE_STD 5
#define TIME_MAX_STD 300
#define CYCLE_MAX_STD 50
#define CRATE_STD 0.8
#define MRATE_STD 0.01
double getRandomDouble() {
return rand()/RAND_MAX;
}
// ------------------------------- Types
typedef struct Solution {
PassSequence Sequence;
double Cost;
bool isCalculated;
Solution() {}
Solution(PassSequence P, double C = DBL_MAX, bool isC = false) {
Sequence = P;
Cost = C;
isCalculated = isC;
}
void setCost(double C) { Cost = C; isCalculated = true; }
Solution &operator=(Solution rhs) {
Sequence = rhs.Sequence;
Cost = rhs.Cost;
isCalculated = rhs.isCalculated;
return *this;
}
} Solution;
class CompareSolution {
double Accuracy;
bool getJudgement() const {
return (Accuracy >= getRandomDouble());
}
public:
CompareSolution(const double A = 1.0) {
Accuracy = (A + 1.0)/2;
}
bool operator()(Solution S1, Solution S2) const {
return ((S1.Cost > S2.Cost) == getJudgement());
}
};
typedef std::vector<Solution> PopT;
typedef std::priority_queue<Solution, PopT, CompareSolution> BestSeqT;
// ---------------------- Functions
void initializePopulation(PopT &Population) {
for (unsigned i = 0; i < SIZE; i++) {
PassSequence Sequence;
Sequence.randomize(NOPT);
Population.push_back(Solution(Sequence));
}
}
bool evaluate(Solution &S,
CorrectionBaseT CorrectionBase, OptAccuracyBaseT OptAccuracyBase,
std::shared_ptr<ProfileModule> PModule, CostEstimatorOptions Opts) {
if (S.isCalculated) return true;
auto NewCost = (rand() % 10) + 1;
if (!Randomness) {
auto PO = GEOS::applyPasses(PModule, S.Sequence);
if (!PO) return false;
NewCost = GEOS::analyseCost(PO, Opts);
}
if (MBasePath.empty()) {
auto OptAccuracy = getPassSequenceAccuracy
(S.Sequence, Opts, OptAccuracyBase);
NewCost /= getCorrectionFor(S.Sequence, Opts, CorrectionBase);
NewCost *= OptAccuracy;
}
S.setCost(NewCost);
return true;
}
void evaluatePopulation(PopT &Population,
CorrectionBaseT CorrectionBase, OptAccuracyBaseT OptAccuracyBase,
BestSeqT &BestSequences, std::shared_ptr<ProfileModule> PModule,
CostEstimatorOptions Opts, double EstimatedAccuracy) {
BestSeqT OrderedPop((CompareSolution(EstimatedAccuracy)));
BestSequences = BestSeqT(CompareSolution(EstimatedAccuracy));
for (auto &I : Population) {
evaluate(I, CorrectionBase, OptAccuracyBase, PModule, Opts);
OrderedPop.push(I);
}
for (unsigned i = 0; i < BSIZE; i++) {
BestSequences.push(OrderedPop.top());
OrderedPop.pop();
}
}
PopT selection(PopT Population, double EstimatedAccuracy) {
unsigned MSize = Population.size()/2, PSize = Population.size();
PopT MatingPool;
while (MatingPool.size() < MSize) {
BestSeqT Tournament((CompareSolution(EstimatedAccuracy)));
for (unsigned i = 0; i < TSIZE; i++) {
int Gene = rand() % PSize;
Tournament.push(Population[Gene]);
}
MatingPool.push_back(Tournament.top());
}
return MatingPool;
}
PopT crossover(PopT MatingPool) {
PopT NewPopulation;
int MSize = (int)MatingPool.size();
while (NewPopulation.size() <= SIZE) {
int ParentI = rand() % MSize;
int ParentJ = rand() % MSize;
if (CrossoverRate >= getRandomDouble()) {
PassSequence Crossover = MatingPool[ParentI].Sequence *
MatingPool[ParentJ].Sequence;
NewPopulation.push_back(Solution(Crossover));
} else {
NewPopulation.push_back(MatingPool[ParentI]);
NewPopulation.push_back(MatingPool[ParentJ]);
}
}
return NewPopulation;
}
void mutation(PopT &Population) {
PassSequence MutatedSeq;
int MaxOpt = static_cast<int>(OptimizationKind::tailcallelim);
for (auto S : Population) {
if (S.isCalculated) continue;
for (unsigned i = 0; i < S.Sequence.size(); i++) {
if (MutationRate >= getRandomDouble()) {
MutatedSeq.add(static_cast<OptimizationKind>(rand() % MaxOpt));
} else {
MutatedSeq.add(S.Sequence[i]);
}
}
S.Sequence = MutatedSeq;
}
}
bool isFinished(time_t Start, int Cycles) {
time_t total = time(0) - Start;
if (CYCLE_MAX && TIME_MAX)
return (total >= (int)TIME_MAX || Cycles >= (int)CYCLE_MAX);
else if (TIME_MAX)
return (total >= (int)TIME_MAX);
else
return (Cycles >= (int)CYCLE_MAX);
}
int main(int argc, char** argv) {
srand(time(0));
GEOS::init();
LLVMContext &Context = getGlobalContext();
SMDiagnostic Error;
gcl::GEOSParseCommandLineOptions(argc, argv);
Module *MyModule =
parseIRFile(LLVMFilename.c_str(), Error, Context).release();
if (!SIZE) SIZE = SIZE_STD;
if (!BSIZE) BSIZE = BSIZE_STD;
if (!TSIZE) TSIZE = TSIZE_STD;
if (!NOPT) NOPT = NOPT_STD;
if (!TIME_MAX && !CYCLE_MAX) TIME_MAX = TIME_MAX_STD;
if (!MutationRate) MutationRate = MRATE_STD;
if (!CrossoverRate) CrossoverRate = CRATE_STD;
std::shared_ptr<ProfileModule> PModule(new ProfileModule(MyModule));
CostEstimatorOptions Opts = gcl::populatePModule(PModule);
double EstimatedAccuracy = 1;
OptAccuracyBaseT OptAccuracyBase;
CorrectionBaseT CorrectionBase;
if (!MBasePath.empty() && !ABasePath.empty() && !CBasePath.empty() && !OABasePath.empty()) {
auto MetricBase = loadMetricsBase(MBasePath);
auto AccuracyBase = loadAccuracyBase(ABasePath);
auto NearestMetricName = getNearestMetric(PModule, MetricBase);
EstimatedAccuracy =
getAccuracyFor(NearestMetricName, Opts, AccuracyBase);
CorrectionBase =
loadCorrectionBase(CBasePath+"/"+NearestMetricName+".estr");
OptAccuracyBase =
loadOptAccuracyBase(OABasePath+"/"+NearestMetricName+".ocor");
}
int PAPIEvents[1] = {PAPI_TOT_CYC};
double RealInitCost =
(GEOS::getPAPIProfile(PModule, ExecutionKind::JIT, PAPIEvents, 1))[0];
double InitCost;
if (Randomness)
InitCost = (rand() % 10) + 1;
else
InitCost = GEOS::analyseCost(PModule, Opts);
int Cycles = 0;
CompareSolution CompSolVar(EstimatedAccuracy);
BestSeqT BestSequences((CompareSolution(EstimatedAccuracy)));
BestSeqT GlobalBest((CompareSolution(EstimatedAccuracy)));
PopT Population;
initializePopulation(Population);
evaluatePopulation(Population, CorrectionBase, OptAccuracyBase,
BestSequences, PModule, Opts, EstimatedAccuracy);
time_t Start = time(0);
while (!isFinished(Start, Cycles)) {
PopT MatingPool =
selection(Population, EstimatedAccuracy);
Population =
crossover(MatingPool);
mutation(Population);
evaluatePopulation(Population, CorrectionBase, OptAccuracyBase,
BestSequences, PModule, Opts, EstimatedAccuracy);
BestSeqT Aux((CompareSolution(EstimatedAccuracy)));
for (unsigned i = 0; i < BSIZE; i++) {
Aux.push(BestSequences.top());
BestSequences.pop();
if (GlobalBest.size()) {
Aux.push(GlobalBest.top());
GlobalBest.pop();
}
}
GlobalBest = BestSeqT(CompareSolution(EstimatedAccuracy));
for (unsigned i = 0; i < BSIZE; i++) {
GlobalBest.push(Aux.top());
Aux.pop();
}
Cycles += 1;
}
double BestRealSpeedUp = 0;
double BestEstSpeedUp = 0;
Solution BestSolution;
while (GlobalBest.size() != 0) {
auto B = GlobalBest.top();
auto PO = GEOS::applyPasses(PModule, B.Sequence);
double RealFinalCost =
(GEOS::getPAPIProfile(PO, ExecutionKind::JIT, PAPIEvents, 1))[0];
double FinalCost;
if (Randomness) FinalCost = (rand() % 10) + 1;
else FinalCost = GEOS::analyseCost(PO, Opts);
if ((RealInitCost/RealFinalCost) > BestRealSpeedUp) {
BestRealSpeedUp = RealInitCost/RealFinalCost;
BestEstSpeedUp = InitCost/FinalCost;
BestSolution = B;
}
if (Randomness) GlobalBest = BestSeqT();
else GlobalBest.pop();
}
printf("\n%f %f\n", BestEstSpeedUp,
BestRealSpeedUp);
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/escape_string.hpp" // for from_hex
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp" // for bencode()
#include "libtorrent/kademlia/item.hpp" // for sign_mutable_item
#include "ed25519.h"
#include <boost/bind.hpp>
#include <stdlib.h>
using namespace libtorrent;
void usage()
{
fprintf(stderr,
"USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n"
"get <hash> - retrieves and prints out the immutable\n"
" item stored under hash.\n"
"put <string> - puts the specified string as an immutable\n"
" item onto the DHT. The resulting target hash\n"
"gen-key <key-file> - generate ed25519 keypair and save it in\n"
" the specified file\n"
"mput <key-file> <string> - puts the specified string as a mutable\n"
" object under the public key in key-file\n"
"mget <public-key> - get a mutable object under the specified\n"
" public key\n"
);
exit(1);
}
std::auto_ptr<alert> wait_for_alert(session& s, int alert_type)
{
std::auto_ptr<alert> ret;
bool found = false;
while (!found)
{
s.wait_for_alert(seconds(5));
std::deque<alert*> alerts;
s.pop_alerts(&alerts);
for (std::deque<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
if ((*i)->type() != alert_type)
{
static int spinner = 0;
static const char anim[] = {'-', '\\', '|', '/'};
printf("\r%c", anim[spinner]);
fflush(stdout);
spinner = (spinner + 1) & 3;
//print some alerts?
delete *i;
continue;
}
ret = std::auto_ptr<alert>(*i);
found = true;
}
}
printf("\n");
return ret;
}
void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq
, std::string const& salt, char const* public_key, char const* private_key
, char const* str)
{
using libtorrent::dht::sign_mutable_item;
e = std::string(str);
std::vector<char> buf;
bencode(std::back_inserter(buf), e);
++seq;
sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size())
, std::pair<char const*, int>(&salt[0], salt.size())
, seq
, public_key
, private_key
, sig.data());
}
void bootstrap(session& s)
{
printf("bootstrapping\n");
wait_for_alert(s, dht_bootstrap_alert::alert_type);
}
int main(int argc, char* argv[])
{
// skip pointer to self
++argv;
--argc;
if (argc < 1) usage();
if (strcmp(argv[0], "gen-key") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
unsigned char seed[32];
ed25519_create_seed(seed);
FILE* f = fopen(argv[0], "wb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n"
, argv[0], errno, strerror(errno));
return 1;
}
fwrite(seed, 1, 32, f);
fclose(f);
return 0;
}
session s;
s.set_alert_mask(0xffffffff);
s.add_dht_router(std::pair<std::string, int>("router.utorrent.com", 6881));
FILE* f = fopen(".dht", "rb");
if (f != NULL)
{
fseek(f, 0, SEEK_END);
int size = ftell(f);
fseek(f, 0, SEEK_SET);
if (size > 0)
{
std::vector<char> state;
state.resize(size);
fread(&state[0], 1, state.size(), f);
lazy_entry e;
error_code ec;
lazy_bdecode(&state[0], &state[0] + state.size(), e, ec);
if (ec)
fprintf(stderr, "failed to parse .dht file: (%d) %s\n"
, ec.value(), ec.message().c_str());
else
s.load_state(e);
}
fclose(f);
}
if (strcmp(argv[0], "get") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
if (strlen(argv[0]) != 40)
{
fprintf(stderr, "the hash is expected to be 40 hex characters\n");
usage();
}
sha1_hash target;
bool ret = from_hex(argv[0], 40, (char*)&target[0]);
if (!ret)
{
fprintf(stderr, "invalid hex encoding of target hash\n");
return 1;
}
bootstrap(s);
s.dht_get_item(target);
printf("GET %s\n", to_hex(target.to_string()).c_str());
std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type);
dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get());
entry data;
if (item)
data.swap(item->item);
printf("%s", data.to_string().c_str());
}
else if (strcmp(argv[0], "put") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
entry data;
data = std::string(argv[0]);
bootstrap(s);
sha1_hash target = s.dht_put_item(data);
printf("PUT %s\n", to_hex(target.to_string()).c_str());
wait_for_alert(s, dht_put_alert::alert_type);
}
else if (strcmp(argv[0], "mput") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
FILE* f = fopen(argv[0], "rb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file \"%s\": (%d) %s\n"
, argv[0], errno, strerror(errno));
return 1;
}
unsigned char seed[32];
fread(seed, 1, 32, f);
fclose(f);
++argv;
--argc;
if (argc < 1) usage();
boost::array<char, 32> public_key;
boost::array<char, 64> private_key;
ed25519_create_keypair((unsigned char*)public_key.data()
, (unsigned char*)private_key.data(), seed);
bootstrap(s);
s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4
, public_key.data(), private_key.data(), argv[0]));
printf("public key: %s\n", to_hex(std::string(public_key.data()
, public_key.size())).c_str());
wait_for_alert(s, dht_put_alert::alert_type);
usleep(10000000);
}
else if (strcmp(argv[0], "mget") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
int len = strlen(argv[0]);
if (len != 64)
{
fprintf(stderr, "public key is expected to be 64 hex digits\n");
return 1;
}
boost::array<char, 32> public_key;
bool ret = from_hex(argv[0], len, &public_key[0]);
if (!ret)
{
fprintf(stderr, "invalid hex encoding of public key\n");
return 1;
}
bootstrap(s);
s.dht_get_item(public_key);
std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type);
dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get());
entry data;
if (item)
data.swap(item->item);
printf("%s", data.to_string().c_str());
}
else
{
usage();
}
entry e;
s.save_state(e, session::save_dht_state);
std::vector<char> state;
bencode(std::back_inserter(state), e);
f = fopen(".dht", "wb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file .dht for writing");
return 1;
}
fwrite(&state[0], 1, state.size(), f);
fclose(f);
}
<commit_msg>fix windows build<commit_after>/*
Copyright (c) 2014, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/escape_string.hpp" // for from_hex
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp" // for bencode()
#include "libtorrent/kademlia/item.hpp" // for sign_mutable_item
#include "ed25519.h"
#include <boost/bind.hpp>
#include <stdlib.h>
using namespace libtorrent;
void usage()
{
fprintf(stderr,
"USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n"
"get <hash> - retrieves and prints out the immutable\n"
" item stored under hash.\n"
"put <string> - puts the specified string as an immutable\n"
" item onto the DHT. The resulting target hash\n"
"gen-key <key-file> - generate ed25519 keypair and save it in\n"
" the specified file\n"
"mput <key-file> <string> - puts the specified string as a mutable\n"
" object under the public key in key-file\n"
"mget <public-key> - get a mutable object under the specified\n"
" public key\n"
);
exit(1);
}
std::auto_ptr<alert> wait_for_alert(session& s, int alert_type)
{
std::auto_ptr<alert> ret;
bool found = false;
while (!found)
{
s.wait_for_alert(seconds(5));
std::deque<alert*> alerts;
s.pop_alerts(&alerts);
for (std::deque<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
if ((*i)->type() != alert_type)
{
static int spinner = 0;
static const char anim[] = {'-', '\\', '|', '/'};
printf("\r%c", anim[spinner]);
fflush(stdout);
spinner = (spinner + 1) & 3;
//print some alerts?
delete *i;
continue;
}
ret = std::auto_ptr<alert>(*i);
found = true;
}
}
printf("\n");
return ret;
}
void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq
, std::string const& salt, char const* public_key, char const* private_key
, char const* str)
{
using libtorrent::dht::sign_mutable_item;
e = std::string(str);
std::vector<char> buf;
bencode(std::back_inserter(buf), e);
++seq;
sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size())
, std::pair<char const*, int>(&salt[0], salt.size())
, seq
, public_key
, private_key
, sig.data());
}
void bootstrap(session& s)
{
printf("bootstrapping\n");
wait_for_alert(s, dht_bootstrap_alert::alert_type);
}
int main(int argc, char* argv[])
{
// skip pointer to self
++argv;
--argc;
if (argc < 1) usage();
if (strcmp(argv[0], "gen-key") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
unsigned char seed[32];
ed25519_create_seed(seed);
FILE* f = fopen(argv[0], "wb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n"
, argv[0], errno, strerror(errno));
return 1;
}
fwrite(seed, 1, 32, f);
fclose(f);
return 0;
}
session s;
s.set_alert_mask(0xffffffff);
s.add_dht_router(std::pair<std::string, int>("router.utorrent.com", 6881));
FILE* f = fopen(".dht", "rb");
if (f != NULL)
{
fseek(f, 0, SEEK_END);
int size = ftell(f);
fseek(f, 0, SEEK_SET);
if (size > 0)
{
std::vector<char> state;
state.resize(size);
fread(&state[0], 1, state.size(), f);
lazy_entry e;
error_code ec;
lazy_bdecode(&state[0], &state[0] + state.size(), e, ec);
if (ec)
fprintf(stderr, "failed to parse .dht file: (%d) %s\n"
, ec.value(), ec.message().c_str());
else
s.load_state(e);
}
fclose(f);
}
if (strcmp(argv[0], "get") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
if (strlen(argv[0]) != 40)
{
fprintf(stderr, "the hash is expected to be 40 hex characters\n");
usage();
}
sha1_hash target;
bool ret = from_hex(argv[0], 40, (char*)&target[0]);
if (!ret)
{
fprintf(stderr, "invalid hex encoding of target hash\n");
return 1;
}
bootstrap(s);
s.dht_get_item(target);
printf("GET %s\n", to_hex(target.to_string()).c_str());
std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type);
dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get());
entry data;
if (item)
data.swap(item->item);
printf("%s", data.to_string().c_str());
}
else if (strcmp(argv[0], "put") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
entry data;
data = std::string(argv[0]);
bootstrap(s);
sha1_hash target = s.dht_put_item(data);
printf("PUT %s\n", to_hex(target.to_string()).c_str());
wait_for_alert(s, dht_put_alert::alert_type);
}
else if (strcmp(argv[0], "mput") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
FILE* f = fopen(argv[0], "rb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file \"%s\": (%d) %s\n"
, argv[0], errno, strerror(errno));
return 1;
}
unsigned char seed[32];
fread(seed, 1, 32, f);
fclose(f);
++argv;
--argc;
if (argc < 1) usage();
boost::array<char, 32> public_key;
boost::array<char, 64> private_key;
ed25519_create_keypair((unsigned char*)public_key.data()
, (unsigned char*)private_key.data(), seed);
bootstrap(s);
s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4
, public_key.data(), private_key.data(), argv[0]));
printf("public key: %s\n", to_hex(std::string(public_key.data()
, public_key.size())).c_str());
wait_for_alert(s, dht_put_alert::alert_type);
}
else if (strcmp(argv[0], "mget") == 0)
{
++argv;
--argc;
if (argc < 1) usage();
int len = strlen(argv[0]);
if (len != 64)
{
fprintf(stderr, "public key is expected to be 64 hex digits\n");
return 1;
}
boost::array<char, 32> public_key;
bool ret = from_hex(argv[0], len, &public_key[0]);
if (!ret)
{
fprintf(stderr, "invalid hex encoding of public key\n");
return 1;
}
bootstrap(s);
s.dht_get_item(public_key);
std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type);
dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get());
entry data;
if (item)
data.swap(item->item);
printf("%s", data.to_string().c_str());
}
else
{
usage();
}
entry e;
s.save_state(e, session::save_dht_state);
std::vector<char> state;
bencode(std::back_inserter(state), e);
f = fopen(".dht", "wb+");
if (f == NULL)
{
fprintf(stderr, "failed to open file .dht for writing");
return 1;
}
fwrite(&state[0], 1, state.size(), f);
fclose(f);
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "graph_serv.hpp"
#include "graph_types.hpp"
#include "../graph/graph_factory.hpp"
#include "../common/util.hpp"
#include "../common/membership.hpp"
#include "../framework/aggregators.hpp"
#include <pficommon/lang/cast.h>
#include <sstream>
#include <pficommon/system/time_util.h>
using pfi::system::time::clock_time;
using pfi::system::time::get_clock_time;
namespace jubatus { namespace server {
inline node_id uint642nodeid(uint64_t i){
return pfi::lang::lexical_cast<node_id, uint64_t>(i);
}
inline uint64_t nodeid2uint64(const node_id& id)
{
return pfi::lang::lexical_cast<uint64_t, node_id>(id);
}
inline node_id i2n(uint64_t i){
return uint642nodeid(i);
}
inline uint64_t n2i(const node_id& id){
return nodeid2uint64(id);
}
graph_serv::graph_serv(const framework::server_argv& a)
: jubatus_serv(a)
{
common::cshared_ptr<jubatus::graph::graph_base>
g(jubatus::graph::create_graph("graph_wo_index"));
g_.set_model(g);
register_mixable(mixable_cast(&g_));
}
graph_serv::~graph_serv()
{}
std::string graph_serv::create_node(){
uint64_t nid = idgen_.generate();
std::string nid_str = pfi::lang::lexical_cast<std::string>(nid);
// send true create_global_node to other machines.
if(not a_.is_standalone()){
// TODO: we need global locking
{
common::cht ht(zk_, a_.name);
std::vector<std::pair<std::string, int> > nodes;
ht.find(nid_str, nodes, 2); //replication number of local_node
if(nodes.empty()){
throw std::runtime_error("fatal: no server found in cht: "+nid_str);
}
if(nodes[0].first == a_.eth && nodes[0].second == a_.port){
create_node_here(nid_str);
}else{
pfi::network::mprpc::rpc_client c(nodes[0].first, nodes[0].second, 5.0);
pfi::lang::function<int(std::string)> f = c.call<int(std::string)>("craete_node_here");
f(nid_str);
}
for(size_t i = 1; i < nodes.size(); ++i){
try{
if(nodes[i].first == a_.eth && nodes[i].second == a_.port){
create_node_here(nid_str);
}else{
pfi::network::mprpc::rpc_client c(nodes[i].first, nodes[i].second, 5.0);
pfi::lang::function<int(std::string)> f = c.call<int(std::string)>("craete_node_here");
f(nid_str);
}
}catch(const std::runtime_error& e){
LOG(INFO) << i << "th replica: " << nodes[i].first << ":" << nodes[i].second << " " << e.what();
}
}
}
std::vector<std::pair<std::string, int> > members;
get_members(members);
if(not members.empty()){
common::mprpc::rpc_mclient c(members, a_.timeout); //create global node
c.call_async("create_global_node", a_.name, nid_str);
c.join_all<int>(pfi::lang::function<int(int,int)>(&jubatus::framework::add<int>));
}
}else{
create_node_here(nid_str);
}
//DLOG(INFO) << "new node created: " << nid_str;
return nid_str;
}
int graph_serv::update_node(const std::string& id, const property& p)
{
g_.get_model()->update_node(n2i(id), p);
return 0;
}
int graph_serv::remove_node(const std::string& nid){
g_.get_model()->remove_node(n2i(nid));
g_.get_model()->remove_global_node(n2i(nid));
if(not a_.is_standalone()){
// TODO: we need global locking
// send true remove_node_ to other machine,
std::vector<std::pair<std::string, int> > members;
get_members(members);
if(not members.empty()){
common::mprpc::rpc_mclient c(members, a_.timeout); //create global node
c.call_async("remove_global_node", a_.name, nid);
c.join_all<int>(pfi::lang::function<int(int,int)>(&jubatus::framework::add<int>));
}
}
DLOG(INFO) << "node removed: " << nid;
return 0;
}
//@cht
int graph_serv::create_edge(const std::string& id, const edge_info& ei)
{
edge_id_t eid = idgen_.generate();
g_.get_model()->create_edge(eid, n2i(ei.src), n2i(ei.tgt));
g_.get_model()->update_edge(eid, ei.p);
// DLOG(INFO) << "edge created (" << eid << ") " << ei.src << " => " << ei.tgt;
return eid;
}
//@random
int graph_serv::update_edge(const std::string&, edge_id_t eid, const edge_info& ei)
{
g_.get_model()->update_edge(eid, ei.p);
return 0;
}
int graph_serv::remove_edge(const std::string&, const edge_id_t& id){
g_.get_model()->remove_edge(id);
return 0;
}
//@random
double graph_serv::centrality(const std::string& id, const centrality_type& s,
const preset_query& q) const
{
if(s == 0){
jubatus::graph::preset_query q0;
return g_.get_model()->centrality(n2i(id),
jubatus::graph::EIGENSCORE,
q0);
}else{
std::stringstream msg;
msg << "unknown centrality type: " << s;
LOG(ERROR) << msg.str();
throw std::runtime_error(msg.str());
}
}
//@random
std::vector<node_id> graph_serv::shortest_path(const shortest_path_req& req) const
{
std::vector<jubatus::graph::node_id_t> ret0;
jubatus::graph::preset_query q;
g_.get_model()->shortest_path(n2i(req.src), n2i(req.tgt), req.max_hop, ret0, q);
std::vector<node_id> ret;
for(size_t i=0;i<ret0.size();++i){
ret.push_back(i2n(ret0[i]));
}
return ret;
}
//update, broadcast
bool graph_serv::add_centrality_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->add_centrality_query(q);
return true;
}
//update, broadcast
bool graph_serv::add_shortest_path_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->add_shortest_path_query(q);
return true;
}
//update, broadcast
bool graph_serv::remove_centrality_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->remove_centrality_query(q);
return true;
}
//update, broadcast
bool graph_serv::remove_shortest_path_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->remove_shortest_path_query(q);
return true;
}
node_info graph_serv::get_node(const std::string& nid)const
{
jubatus::graph::node_info info;
g_.get_model()->get_node(n2i(nid), info);
jubatus::node_info ret;
framework::convert<graph::node_info, jubatus::node_info>(info, ret);
return ret;
}
//@random
edge_info graph_serv::get_edge(const std::string& nid, const edge_id_t& id)const
{
jubatus::graph::edge_info info;
g_.get_model()->get_edge((jubatus::graph::edge_id_t)id, info);
jubatus::edge_info ret;
ret.p = info.p;
ret.src = i2n(info.src);
ret.tgt = i2n(info.tgt);
return ret;
}
//@broadcast
int graph_serv::update_index(){
if(not a_.is_standalone()){
throw std::runtime_error("manual mix is available only in standalone mode.");
}
clock_time start = get_clock_time();
g_.get_model()->update_index();
std::string diff;
g_.get_model()->get_diff(diff);
g_.get_model()->set_mixed_and_clear_diff(diff);
clock_time end = get_clock_time();
LOG(WARNING) << "mix done manually and locally; in " << (double)(end - start) << " secs.";
return 0;
}
int graph_serv::clear(){
if(g_.get_model())
g_.get_model()->clear();
return 0;
}
std::map<std::string, std::map<std::string,std::string> > graph_serv::get_status()const
{
std::map<std::string,std::string> ret0;
g_.get_model()->get_status(ret0);
std::map<std::string, std::map<std::string,std::string> > ret =
jubatus_serv::get_status();
ret[get_server_identifier()].insert(ret0.begin(), ret0.end());
return ret;
}
int graph_serv::create_node_here(const std::string& nid)
{
graph::node_id_t id = pfi::lang::lexical_cast<graph::node_id_t>(nid);
g_.get_model()->create_node(id);
g_.get_model()->create_global_node(id);
return 0;
}
int graph_serv::create_global_node(const std::string& nid)
{
g_.get_model()->create_global_node(n2i(nid));
return 0;
} //update internal
int graph_serv::remove_global_node(const std::string& nid)
{
g_.get_model()->remove_global_node(n2i(nid));
return 0;
} //update internal
void graph_serv::after_load(){}
}}
<commit_msg>better error ignor^H^H^H^H^Hhandling<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "graph_serv.hpp"
#include "graph_types.hpp"
#include "../graph/graph_factory.hpp"
#include "../common/util.hpp"
#include "../common/membership.hpp"
#include "graph_client.hpp"
#include "../framework/aggregators.hpp"
#include <pficommon/lang/cast.h>
#include <sstream>
#include <pficommon/system/time_util.h>
using pfi::system::time::clock_time;
using pfi::system::time::get_clock_time;
namespace jubatus { namespace server {
enum graph_serv_error {
NODE_ALREADY_EXISTS = 0xDEADBEEF
};
inline node_id uint642nodeid(uint64_t i){
return pfi::lang::lexical_cast<node_id, uint64_t>(i);
}
inline uint64_t nodeid2uint64(const node_id& id)
{
return pfi::lang::lexical_cast<uint64_t, node_id>(id);
}
inline node_id i2n(uint64_t i){
return uint642nodeid(i);
}
inline uint64_t n2i(const node_id& id){
return nodeid2uint64(id);
}
graph_serv::graph_serv(const framework::server_argv& a)
: jubatus_serv(a)
{
common::cshared_ptr<jubatus::graph::graph_base>
g(jubatus::graph::create_graph("graph_wo_index"));
g_.set_model(g);
register_mixable(mixable_cast(&g_));
}
graph_serv::~graph_serv()
{}
std::string graph_serv::create_node(){
uint64_t nid = idgen_.generate();
std::string nid_str = pfi::lang::lexical_cast<std::string>(nid);
// send true create_global_node to other machines.
//DLOG(INFO) << __func__ << " " << nid_str;
if(not a_.is_standalone()){
// we dont need global locking, because getting unique id from zk
// guarantees there'll be no data confliction
{
common::cht ht(zk_, a_.name);
std::vector<std::pair<std::string, int> > nodes;
ht.find(nid_str, nodes, 2); //replication number of local_node
if(nodes.empty()){
throw std::runtime_error("fatal: no server found in cht: "+nid_str);
}
// this sequences MUST success, in case of failures the whole request should be canceled
if(nodes[0].first == a_.eth && nodes[0].second == a_.port){
this->create_node_here(nid_str);
}else{
client::graph c(nodes[0].first, nodes[0].second, 5.0);
c.create_node_here(a_.name, nid_str);
}
for(size_t i = 1; i < nodes.size(); ++i){
try{
if(nodes[i].first == a_.eth && nodes[i].second == a_.port){
this->create_node_here(nid_str);
}else{
client::graph c(nodes[i].first, nodes[i].second, 5.0);
c.create_node_here(a_.name, nid_str);
}
}catch(const graph::local_node_exists& e){ // pass through
}catch(const graph::global_node_exists& e){// pass through
}catch(const std::runtime_error& e){ // error !
LOG(INFO) << i+1 << "th replica: " << nodes[i].first << ":" << nodes[i].second << " " << e.what();
}
}
}
std::vector<std::pair<std::string, int> > members;
get_members(members);
if(not members.empty()){
common::mprpc::rpc_mclient c(members, a_.timeout); //create global node
c.call_async("create_global_node", a_.name, nid_str);
try{
c.join_all<int>(pfi::lang::function<int(int,int)>(&jubatus::framework::add<int>));
}catch(const std::runtime_error & e){ // no results?, pass through
DLOG(INFO) << __func__ << " " << e.what();
}
}
}else{
this->create_node_here(nid_str);
}
DLOG(INFO) << "new node created: " << nid_str;
return nid_str;
}
int graph_serv::update_node(const std::string& id, const property& p)
{
g_.get_model()->update_node(n2i(id), p);
return 0;
}
int graph_serv::remove_node(const std::string& nid){
g_.get_model()->remove_node(n2i(nid));
g_.get_model()->remove_global_node(n2i(nid));
if(not a_.is_standalone()){
// send true remove_node_ to other machine,
// if conflicts with create_node, users should re-run to ensure removal
std::vector<std::pair<std::string, int> > members;
get_members(members);
if(not members.empty()){
common::mprpc::rpc_mclient c(members, a_.timeout); //create global node
c.call_async("remove_global_node", a_.name, nid);
c.join_all<int>(pfi::lang::function<int(int,int)>(&jubatus::framework::add<int>));
}
}
DLOG(INFO) << "node removed: " << nid;
return 0;
}
//@cht
int graph_serv::create_edge(const std::string& id, const edge_info& ei)
{
edge_id_t eid = idgen_.generate();
g_.get_model()->create_edge(eid, n2i(ei.src), n2i(ei.tgt));
g_.get_model()->update_edge(eid, ei.p);
// DLOG(INFO) << "edge created (" << eid << ") " << ei.src << " => " << ei.tgt;
return eid;
}
//@random
int graph_serv::update_edge(const std::string&, edge_id_t eid, const edge_info& ei)
{
g_.get_model()->update_edge(eid, ei.p);
return 0;
}
int graph_serv::remove_edge(const std::string&, const edge_id_t& id){
g_.get_model()->remove_edge(id);
return 0;
}
//@random
double graph_serv::centrality(const std::string& id, const centrality_type& s,
const preset_query& q) const
{
if(s == 0){
jubatus::graph::preset_query q0;
return g_.get_model()->centrality(n2i(id),
jubatus::graph::EIGENSCORE,
q0);
}else{
std::stringstream msg;
msg << "unknown centrality type: " << s;
LOG(ERROR) << msg.str();
throw std::runtime_error(msg.str());
}
}
//@random
std::vector<node_id> graph_serv::shortest_path(const shortest_path_req& req) const
{
std::vector<jubatus::graph::node_id_t> ret0;
jubatus::graph::preset_query q;
g_.get_model()->shortest_path(n2i(req.src), n2i(req.tgt), req.max_hop, ret0, q);
std::vector<node_id> ret;
for(size_t i=0;i<ret0.size();++i){
ret.push_back(i2n(ret0[i]));
}
return ret;
}
//update, broadcast
bool graph_serv::add_centrality_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->add_centrality_query(q);
return true;
}
//update, broadcast
bool graph_serv::add_shortest_path_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->add_shortest_path_query(q);
return true;
}
//update, broadcast
bool graph_serv::remove_centrality_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->remove_centrality_query(q);
return true;
}
//update, broadcast
bool graph_serv::remove_shortest_path_query(const preset_query& q0)
{
jubatus::graph::preset_query q;
framework::convert<jubatus::preset_query, jubatus::graph::preset_query>(q0, q);
g_.get_model()->remove_shortest_path_query(q);
return true;
}
node_info graph_serv::get_node(const std::string& nid)const
{
jubatus::graph::node_info info;
g_.get_model()->get_node(n2i(nid), info);
jubatus::node_info ret;
framework::convert<graph::node_info, jubatus::node_info>(info, ret);
return ret;
}
//@random
edge_info graph_serv::get_edge(const std::string& nid, const edge_id_t& id)const
{
jubatus::graph::edge_info info;
g_.get_model()->get_edge((jubatus::graph::edge_id_t)id, info);
jubatus::edge_info ret;
ret.p = info.p;
ret.src = i2n(info.src);
ret.tgt = i2n(info.tgt);
return ret;
}
//@broadcast
int graph_serv::update_index(){
if(not a_.is_standalone()){
throw std::runtime_error("manual mix is available only in standalone mode.");
}
clock_time start = get_clock_time();
g_.get_model()->update_index();
std::string diff;
g_.get_model()->get_diff(diff);
g_.get_model()->set_mixed_and_clear_diff(diff);
clock_time end = get_clock_time();
LOG(WARNING) << "mix done manually and locally; in " << (double)(end - start) << " secs.";
return 0;
}
int graph_serv::clear(){
if(g_.get_model())
g_.get_model()->clear();
return 0;
}
std::map<std::string, std::map<std::string,std::string> > graph_serv::get_status()const
{
std::map<std::string,std::string> ret0;
g_.get_model()->get_status(ret0);
std::map<std::string, std::map<std::string,std::string> > ret =
jubatus_serv::get_status();
ret[get_server_identifier()].insert(ret0.begin(), ret0.end());
return ret;
}
int graph_serv::create_node_here(const std::string& nid)
{
try{
graph::node_id_t id = pfi::lang::lexical_cast<graph::node_id_t>(nid);
g_.get_model()->create_node(id);
g_.get_model()->create_global_node(id);
}catch(const graph::local_node_exists& e){ //pass through
}catch(const graph::global_node_exists& e){//pass through
}catch(const std::runtime_error& e){
DLOG(INFO) << e.what() << " " << nid;
throw e;
}
return 0;
}
int graph_serv::create_global_node(const std::string& nid)
{
try{
g_.get_model()->create_global_node(n2i(nid));
}catch(const graph::local_node_exists& e){
}catch(const graph::global_node_exists& e){
}catch(const std::runtime_error& e){
DLOG(INFO) << e.what() << " " << nid;
throw e;
}
return 0;
} //update internal
int graph_serv::remove_global_node(const std::string& nid)
{
try{
g_.get_model()->remove_global_node(n2i(nid));
}catch(const graph::local_node_exists& e){
}catch(const graph::global_node_exists& e){
}catch(const std::runtime_error& e){
DLOG(INFO) << e.what() << " " << nid;
throw e;
}
return 0;
} //update internal
void graph_serv::after_load(){}
}}
<|endoftext|> |
<commit_before>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
//------------------------------------------------------------------------------
// Option declarations for LLC.
//------------------------------------------------------------------------------
// Make all registered optimization passes available to llc. These passes
// will all be run before the simplification and lowering steps used by the
// back-end code generator, and will be run in the order specified on the
// command line. The OptimizationList is automatically populated with
// registered Passes by the PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool>
DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode included in the executable"));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print bytecode before native code generation"),
cl::Hidden);
// GetFileNameRoot - Helper function to get the basename of a filename...
static inline std::string
GetFileNameRoot(const std::string &InputFilename)
{
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//
int
main(int argc, char **argv)
{
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
const TargetData &TD = Target.getTargetData();
// Load the module to be compiled...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0)
{
std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
// Build up all of the passes that we want to do to the module...
PassManager Passes;
Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Create a new optimization pass for each one specified on the command line
// Deal specially with tracing passes, which must be run differently than opt.
//
for (unsigned i = 0; i < OptimizationList.size(); ++i) {
const PassInfo *Opt = OptimizationList[i];
// handle other passes as normal optimization passes
if (Opt->getNormalCtor())
Passes.add(Opt->getNormalCtor()());
else if (Opt->getTargetCtor())
Passes.add(Opt->getTargetCtor()(Target));
else
std::cerr << argv[0] << ": cannot create pass: "
<< Opt->getPassName() << "\n";
}
// Decompose multi-dimensional refs into a sequence of 1D refs
// FIXME: This is sparc specific!
Passes.add(createDecomposeMultiDimRefsPass());
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
// FIXME: This is sparc specific!
Passes.add(createLowerAllocationsPass());
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpAsm)
Passes.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
Passes.add(createSymbolStrippingPass());
// Figure out where we are going to send the output...
std::ostream *Out = 0;
if (OutputFilename != "")
{ // Specified an output filename?
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
// Make sure that the Out file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
else
{
if (InputFilename == "-")
{
OutputFilename = "-";
Out = &std::cout;
}
else
{
std::string OutputFilename = GetFileNameRoot(InputFilename);
OutputFilename += ".s";
if (!Force && std::ifstream(OutputFilename.c_str()))
{
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good())
{
std::cerr << argv[0] << ": error opening " << OutputFilename
<< "!\n";
delete Out;
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
}
// Ask the target to add backend passes as neccesary
if (Target.addPassesToEmitAssembly(Passes, *Out)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< " does not support static compilation!\n";
} else {
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
}
// Delete the ostream if it's not a stdout stream
if (Out != &std::cout) delete Out;
return 0;
}
<commit_msg>Remove duplicate pass<commit_after>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
//------------------------------------------------------------------------------
// Option declarations for LLC.
//------------------------------------------------------------------------------
// Make all registered optimization passes available to llc. These passes
// will all be run before the simplification and lowering steps used by the
// back-end code generator, and will be run in the order specified on the
// command line. The OptimizationList is automatically populated with
// registered Passes by the PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool>
DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode included in the executable"));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print bytecode before native code generation"),
cl::Hidden);
// GetFileNameRoot - Helper function to get the basename of a filename...
static inline std::string
GetFileNameRoot(const std::string &InputFilename)
{
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//
int
main(int argc, char **argv)
{
cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
// Allocate a target... in the future this will be controllable on the
// command line.
std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
const TargetData &TD = Target.getTargetData();
// Load the module to be compiled...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0)
{
std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
// Build up all of the passes that we want to do to the module...
PassManager Passes;
Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Create a new optimization pass for each one specified on the command line
// Deal specially with tracing passes, which must be run differently than opt.
//
for (unsigned i = 0; i < OptimizationList.size(); ++i) {
const PassInfo *Opt = OptimizationList[i];
// handle other passes as normal optimization passes
if (Opt->getNormalCtor())
Passes.add(Opt->getNormalCtor()());
else if (Opt->getTargetCtor())
Passes.add(Opt->getTargetCtor()(Target));
else
std::cerr << argv[0] << ": cannot create pass: "
<< Opt->getPassName() << "\n";
}
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
// FIXME: This is sparc specific!
Passes.add(createLowerAllocationsPass());
// If LLVM dumping after transformations is requested, add it to the pipeline
if (DumpAsm)
Passes.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
Passes.add(createSymbolStrippingPass());
// Figure out where we are going to send the output...
std::ostream *Out = 0;
if (OutputFilename != "")
{ // Specified an output filename?
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
// Make sure that the Out file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
else
{
if (InputFilename == "-")
{
OutputFilename = "-";
Out = &std::cout;
}
else
{
std::string OutputFilename = GetFileNameRoot(InputFilename);
OutputFilename += ".s";
if (!Force && std::ifstream(OutputFilename.c_str()))
{
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good())
{
std::cerr << argv[0] << ": error opening " << OutputFilename
<< "!\n";
delete Out;
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
}
// Ask the target to add backend passes as neccesary
if (Target.addPassesToEmitAssembly(Passes, *Out)) {
std::cerr << argv[0] << ": target '" << Target.getName()
<< " does not support static compilation!\n";
} else {
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
}
// Delete the ostream if it's not a stdout stream
if (Out != &std::cout) delete Out;
return 0;
}
<|endoftext|> |
<commit_before>//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/lto.h"
#include "llvm-c/Core.h"
#include "LTOModule.h"
#include "LTOCodeGenerator.h"
// holds most recent error string
// *** not thread safe ***
static std::string sLastErrorString;
//
// returns a printable string
//
extern const char* lto_get_version()
{
return LTOCodeGenerator::getVersionString();
}
//
// returns the last error string or NULL if last operation was successful
//
const char* lto_get_error_message()
{
return sLastErrorString.c_str();
}
//
// validates if a file is a loadable object file
//
bool lto_module_is_object_file(const char* path)
{
return LTOModule::isBitcodeFile(path);
}
//
// validates if a file is a loadable object file compilable for requested target
//
bool lto_module_is_object_file_for_target(const char* path,
const char* target_triplet_prefix)
{
return LTOModule::isBitcodeFileForTarget(path, target_triplet_prefix);
}
//
// validates if a buffer is a loadable object file
//
bool lto_module_is_object_file_in_memory(const void* mem, size_t length)
{
return LTOModule::isBitcodeFile(mem, length);
}
//
// validates if a buffer is a loadable object file compilable for the target
//
bool lto_module_is_object_file_in_memory_for_target(const void* mem,
size_t length, const char* target_triplet_prefix)
{
return LTOModule::isBitcodeFileForTarget(mem, length, target_triplet_prefix);
}
//
// loads an object file from disk
// returns NULL on error (check lto_get_error_message() for details)
//
lto_module_t lto_module_create(const char* path)
{
return LTOModule::makeLTOModule(path, sLastErrorString);
}
//
// loads an object file from memory
// returns NULL on error (check lto_get_error_message() for details)
//
lto_module_t lto_module_create_from_memory(const void* mem, size_t length)
{
return LTOModule::makeLTOModule(mem, length, sLastErrorString);
}
//
// frees all memory for a module
// upon return the lto_module_t is no longer valid
//
void lto_module_dispose(lto_module_t mod)
{
delete mod;
}
//
// returns triplet string which the object module was compiled under
//
const char* lto_module_get_target_triple(lto_module_t mod)
{
return mod->getTargetTriple();
}
//
// returns the number of symbols in the object module
//
uint32_t lto_module_get_num_symbols(lto_module_t mod)
{
return mod->getSymbolCount();
}
//
// returns the name of the ith symbol in the object module
//
const char* lto_module_get_symbol_name(lto_module_t mod, uint32_t index)
{
return mod->getSymbolName(index);
}
//
// returns the attributes of the ith symbol in the object module
//
lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
uint32_t index)
{
return mod->getSymbolAttributes(index);
}
//
// instantiates a code generator
// returns NULL if there is an error
//
lto_code_gen_t lto_codegen_create(void)
{
return new LTOCodeGenerator();
}
//
// frees all memory for a code generator
// upon return the lto_code_gen_t is no longer valid
//
void lto_codegen_dispose(lto_code_gen_t cg)
{
delete cg;
}
//
// add an object module to the set of modules for which code will be generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod)
{
return cg->addModule(mod, sLastErrorString);
}
//
// sets what if any format of debug info should be generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug)
{
return cg->setDebugInfo(debug, sLastErrorString);
}
//
// sets what code model to generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model)
{
return cg->setCodePICModel(model, sLastErrorString);
}
//
// sets the path to gcc
//
void lto_codegen_set_gcc_path(lto_code_gen_t cg, const char* path)
{
cg->setGccPath(path);
}
//
// sets the path to the assembler tool
//
void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char* path)
{
cg->setAssemblerPath(path);
}
//
// adds to a list of all global symbols that must exist in the final
// generated code. If a function is not listed there, it might be
// inlined into every usage and optimized away.
//
void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol)
{
cg->addMustPreserveSymbol(symbol);
}
//
// writes a new file at the specified path that contains the
// merged contents of all modules added so far.
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path)
{
return cg->writeMergedModules(path, sLastErrorString);
}
//
// Generates code for all added modules into one native object file.
// On sucess returns a pointer to a generated mach-o/ELF buffer and
// length set to the buffer size. The buffer is owned by the
// lto_code_gen_t and will be freed when lto_codegen_dispose()
// is called, or lto_codegen_compile() is called again.
// On failure, returns NULL (check lto_get_error_message() for details).
//
extern const void*
lto_codegen_compile(lto_code_gen_t cg, size_t* length)
{
return cg->compile(length, sLastErrorString);
}
//
// Used to pass extra options to the code generator
//
extern void
lto_codegen_debug_options(lto_code_gen_t cg, const char * opt)
{
cg->setCodeGenDebugOptions(opt);
}<commit_msg>Add newline at end of file.<commit_after>//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Link Time Optimization library. This library is
// intended to be used by linker to optimize code at link time.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/lto.h"
#include "llvm-c/Core.h"
#include "LTOModule.h"
#include "LTOCodeGenerator.h"
// holds most recent error string
// *** not thread safe ***
static std::string sLastErrorString;
//
// returns a printable string
//
extern const char* lto_get_version()
{
return LTOCodeGenerator::getVersionString();
}
//
// returns the last error string or NULL if last operation was successful
//
const char* lto_get_error_message()
{
return sLastErrorString.c_str();
}
//
// validates if a file is a loadable object file
//
bool lto_module_is_object_file(const char* path)
{
return LTOModule::isBitcodeFile(path);
}
//
// validates if a file is a loadable object file compilable for requested target
//
bool lto_module_is_object_file_for_target(const char* path,
const char* target_triplet_prefix)
{
return LTOModule::isBitcodeFileForTarget(path, target_triplet_prefix);
}
//
// validates if a buffer is a loadable object file
//
bool lto_module_is_object_file_in_memory(const void* mem, size_t length)
{
return LTOModule::isBitcodeFile(mem, length);
}
//
// validates if a buffer is a loadable object file compilable for the target
//
bool lto_module_is_object_file_in_memory_for_target(const void* mem,
size_t length, const char* target_triplet_prefix)
{
return LTOModule::isBitcodeFileForTarget(mem, length, target_triplet_prefix);
}
//
// loads an object file from disk
// returns NULL on error (check lto_get_error_message() for details)
//
lto_module_t lto_module_create(const char* path)
{
return LTOModule::makeLTOModule(path, sLastErrorString);
}
//
// loads an object file from memory
// returns NULL on error (check lto_get_error_message() for details)
//
lto_module_t lto_module_create_from_memory(const void* mem, size_t length)
{
return LTOModule::makeLTOModule(mem, length, sLastErrorString);
}
//
// frees all memory for a module
// upon return the lto_module_t is no longer valid
//
void lto_module_dispose(lto_module_t mod)
{
delete mod;
}
//
// returns triplet string which the object module was compiled under
//
const char* lto_module_get_target_triple(lto_module_t mod)
{
return mod->getTargetTriple();
}
//
// returns the number of symbols in the object module
//
uint32_t lto_module_get_num_symbols(lto_module_t mod)
{
return mod->getSymbolCount();
}
//
// returns the name of the ith symbol in the object module
//
const char* lto_module_get_symbol_name(lto_module_t mod, uint32_t index)
{
return mod->getSymbolName(index);
}
//
// returns the attributes of the ith symbol in the object module
//
lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod,
uint32_t index)
{
return mod->getSymbolAttributes(index);
}
//
// instantiates a code generator
// returns NULL if there is an error
//
lto_code_gen_t lto_codegen_create(void)
{
return new LTOCodeGenerator();
}
//
// frees all memory for a code generator
// upon return the lto_code_gen_t is no longer valid
//
void lto_codegen_dispose(lto_code_gen_t cg)
{
delete cg;
}
//
// add an object module to the set of modules for which code will be generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod)
{
return cg->addModule(mod, sLastErrorString);
}
//
// sets what if any format of debug info should be generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug)
{
return cg->setDebugInfo(debug, sLastErrorString);
}
//
// sets what code model to generated
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model)
{
return cg->setCodePICModel(model, sLastErrorString);
}
//
// sets the path to gcc
//
void lto_codegen_set_gcc_path(lto_code_gen_t cg, const char* path)
{
cg->setGccPath(path);
}
//
// sets the path to the assembler tool
//
void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char* path)
{
cg->setAssemblerPath(path);
}
//
// adds to a list of all global symbols that must exist in the final
// generated code. If a function is not listed there, it might be
// inlined into every usage and optimized away.
//
void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol)
{
cg->addMustPreserveSymbol(symbol);
}
//
// writes a new file at the specified path that contains the
// merged contents of all modules added so far.
// returns true on error (check lto_get_error_message() for details)
//
bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path)
{
return cg->writeMergedModules(path, sLastErrorString);
}
//
// Generates code for all added modules into one native object file.
// On sucess returns a pointer to a generated mach-o/ELF buffer and
// length set to the buffer size. The buffer is owned by the
// lto_code_gen_t and will be freed when lto_codegen_dispose()
// is called, or lto_codegen_compile() is called again.
// On failure, returns NULL (check lto_get_error_message() for details).
//
extern const void*
lto_codegen_compile(lto_code_gen_t cg, size_t* length)
{
return cg->compile(length, sLastErrorString);
}
//
// Used to pass extra options to the code generator
//
extern void
lto_codegen_debug_options(lto_code_gen_t cg, const char * opt)
{
cg->setCodeGenDebugOptions(opt);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImage.h"
#include "SkOSFile.h"
#include "SkPictureRecorder.h"
#include "SkPngEncoder.h"
#include "Timer.h"
#include "ok.h"
#include <chrono>
#include <regex>
static std::unique_ptr<Src> proxy(Src* original, std::function<Status(SkCanvas*)> fn) {
struct : Src {
Src* original;
std::function<Status(SkCanvas*)> fn;
std::string name() override { return original->name(); }
SkISize size() override { return original->size(); }
Status draw(SkCanvas* canvas) override { return fn(canvas); }
} src;
src.original = original;
src.fn = fn;
return move_unique(src);
}
struct ViaPic : Dst {
std::unique_ptr<Dst> target;
bool rtree = false;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
ViaPic via;
via.target = std::move(dst);
if (options("bbh") == "rtree") { via.rtree = true; }
return move_unique(via);
}
Status draw(Src* src) override {
SkRTreeFactory factory;
SkPictureRecorder rec;
rec.beginRecording(SkRect::MakeSize(SkSize::Make(src->size())),
rtree ? &factory : nullptr);
for (auto status = src->draw(rec.getRecordingCanvas()); status != Status::OK; ) {
return status;
}
auto pic = rec.finishRecordingAsPicture();
return target->draw(proxy(src, [=](SkCanvas* canvas) {
pic->playback(canvas);
return Status::OK;
}).get());
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register via_pic{"via_pic", "record then play back an SkPicture", ViaPic::Create};
struct Png : Dst {
std::unique_ptr<Dst> target;
std::string dir;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Png via;
via.target = std::move(dst);
via.dir = options("dir", "ok");
return move_unique(via);
}
Status draw(Src* src) override {
for (auto status = target->draw(src); status != Status::OK; ) {
return status;
}
SkBitmap bm;
SkPixmap pm;
if (!target->image()->asLegacyBitmap(&bm, SkImage::kRO_LegacyBitmapMode) ||
!bm.peekPixels(&pm)) {
return Status::Failed;
}
sk_mkdir(dir.c_str());
SkFILEWStream dst{(dir + "/" + src->name() + ".png").c_str()};
SkPngEncoder::Options options;
options.fFilterFlags = SkPngEncoder::FilterFlag::kNone;
options.fZLibLevel = 1;
options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
: SkTransferFunctionBehavior::kIgnore;
return SkPngEncoder::Encode(&dst, pm, options) ? Status::OK
: Status::Failed;
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register png{"png", "dump PNGs to dir=ok" , Png::Create};
struct Filter : Dst {
std::unique_ptr<Dst> target;
std::regex match, search;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Filter via;
via.target = std::move(dst);
via.match = options("match", ".*");
via.search = options("search", ".*");
return move_unique(via);
}
Status draw(Src* src) override {
auto name = src->name();
if (!std::regex_match (name, match) ||
!std::regex_search(name, search)) {
return Status::Skipped;
}
return target->draw(src);
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register filter{"filter",
"run only srcs matching match=.* exactly and search=.* somewhere",
Filter::Create};
struct Time : Dst {
std::unique_ptr<Dst> target;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Time via;
via.target = std::move(dst);
return move_unique(via);
}
Status draw(Src* src) override {
auto start = std::chrono::steady_clock::now();
Status status = target->draw(src);
std::chrono::duration<double, std::milli> elapsed = std::chrono::steady_clock::now()
- start;
auto msg = HumanizeMs(elapsed.count());
ok_log(msg.c_str());
return status;
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register _time{"time",
"print wall run time",
Time::Create};
<commit_msg>add memory via to ok<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImage.h"
#include "SkOSFile.h"
#include "SkPictureRecorder.h"
#include "SkPngEncoder.h"
#include "ProcStats.h"
#include "Timer.h"
#include "ok.h"
#include <chrono>
#include <regex>
static std::unique_ptr<Src> proxy(Src* original, std::function<Status(SkCanvas*)> fn) {
struct : Src {
Src* original;
std::function<Status(SkCanvas*)> fn;
std::string name() override { return original->name(); }
SkISize size() override { return original->size(); }
Status draw(SkCanvas* canvas) override { return fn(canvas); }
} src;
src.original = original;
src.fn = fn;
return move_unique(src);
}
struct ViaPic : Dst {
std::unique_ptr<Dst> target;
bool rtree = false;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
ViaPic via;
via.target = std::move(dst);
if (options("bbh") == "rtree") { via.rtree = true; }
return move_unique(via);
}
Status draw(Src* src) override {
SkRTreeFactory factory;
SkPictureRecorder rec;
rec.beginRecording(SkRect::MakeSize(SkSize::Make(src->size())),
rtree ? &factory : nullptr);
for (auto status = src->draw(rec.getRecordingCanvas()); status != Status::OK; ) {
return status;
}
auto pic = rec.finishRecordingAsPicture();
return target->draw(proxy(src, [=](SkCanvas* canvas) {
pic->playback(canvas);
return Status::OK;
}).get());
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register via_pic{"via_pic", "record then play back an SkPicture", ViaPic::Create};
struct Png : Dst {
std::unique_ptr<Dst> target;
std::string dir;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Png via;
via.target = std::move(dst);
via.dir = options("dir", "ok");
return move_unique(via);
}
Status draw(Src* src) override {
for (auto status = target->draw(src); status != Status::OK; ) {
return status;
}
SkBitmap bm;
SkPixmap pm;
if (!target->image()->asLegacyBitmap(&bm, SkImage::kRO_LegacyBitmapMode) ||
!bm.peekPixels(&pm)) {
return Status::Failed;
}
sk_mkdir(dir.c_str());
SkFILEWStream dst{(dir + "/" + src->name() + ".png").c_str()};
SkPngEncoder::Options options;
options.fFilterFlags = SkPngEncoder::FilterFlag::kNone;
options.fZLibLevel = 1;
options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
: SkTransferFunctionBehavior::kIgnore;
return SkPngEncoder::Encode(&dst, pm, options) ? Status::OK
: Status::Failed;
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register png{"png", "dump PNGs to dir=ok" , Png::Create};
struct Filter : Dst {
std::unique_ptr<Dst> target;
std::regex match, search;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Filter via;
via.target = std::move(dst);
via.match = options("match", ".*");
via.search = options("search", ".*");
return move_unique(via);
}
Status draw(Src* src) override {
auto name = src->name();
if (!std::regex_match (name, match) ||
!std::regex_search(name, search)) {
return Status::Skipped;
}
return target->draw(src);
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register filter{"filter",
"run only srcs matching match=.* exactly and search=.* somewhere",
Filter::Create};
struct Time : Dst {
std::unique_ptr<Dst> target;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Time via;
via.target = std::move(dst);
return move_unique(via);
}
Status draw(Src* src) override {
auto start = std::chrono::steady_clock::now();
Status status = target->draw(src);
std::chrono::duration<double, std::milli> elapsed = std::chrono::steady_clock::now()
- start;
auto msg = HumanizeMs(elapsed.count());
ok_log(msg.c_str());
return status;
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register _time{"time", "print wall run time", Time::Create};
struct Memory : Dst {
std::unique_ptr<Dst> target;
static std::unique_ptr<Dst> Create(Options options, std::unique_ptr<Dst> dst) {
Memory via;
via.target = std::move(dst);
return move_unique(via);
}
Status draw(Src* src) override {
Status status = target->draw(src);
auto msg = SkStringPrintf("%dMB", sk_tools::getMaxResidentSetSizeMB());
ok_log(msg.c_str());
return status;
}
sk_sp<SkImage> image() override {
return target->image();
}
};
static Register memory{"memory", "print process maximum memory usage", Memory::Create};
<|endoftext|> |
<commit_before>#include "Settings.h"
TypeHandle Settings::_type_handle;
Settings::Settings() {
m_vfs = VirtualFileSystem::get_global_ptr();
m_file = Filename("/useropt"); //First let's use this to set our dir.
m_file = Filename(m_file.to_os_long_name()); //Now let's do the real file.
m_file.set_binary();
//Now to define our default settings.
m_want_music = 1;
m_want_sfx = 1;
m_sfx_volume = 100.0f;
m_music_volume = 100.0f;
m_force_sw_midi = 0;
m_embedded_mode = 0;
m_log_chat = 0;
m_current_driver = 0;
m_resolution = 1;
m_windowed_mode = 0;
m_resolution_dimensions[0] = 800;
m_resolution_dimensions[1] = 600;
}
Settings::~Settings() {
}
void Settings::read_settings() {
Filename found(m_file);
if (!m_vfs->exists(found)) {
libotp_cat.debug() << "Failed to find Settings! Creating file...." << std::endl;
m_vfs->create_file(m_file);
write_settings();
return;
}
m_vfs->read_file(found, m_data, true);
m_data = decompress_string(m_data);
Datagram dg(m_data);
DatagramIterator dgi(dg);
m_data = "";
m_want_music = dgi.get_bool();
m_want_sfx = dgi.get_bool();
m_sfx_volume = dgi.get_stdfloat();
m_music_volume = dgi.get_stdfloat();
m_force_sw_midi = dgi.get_bool();
m_embedded_mode = dgi.get_bool();
m_log_chat = dgi.get_bool();
m_current_driver = dgi.get_uint8();
m_resolution = dgi.get_uint8();
m_windowed_mode = dgi.get_uint8();
m_resolution_dimensions[0] = dgi.get_uint16();
m_resolution_dimensions[1] = dgi.get_uint16();
}
void Settings::write_settings() {
Datagram dg;
dg.add_bool(m_want_music);
dg.add_bool(m_want_sfx);
dg.add_stdfloat(m_sfx_volume);
dg.add_stdfloat(m_music_volume);
dg.add_bool(m_force_sw_midi);
dg.add_bool(m_embedded_mode);
dg.add_bool(m_log_chat);
dg.add_uint8(m_current_driver);
dg.add_uint8(m_resolution);
dg.add_uint8(m_windowed_mode);
dg.add_uint16(m_resolution_dimensions[0]);
dg.add_uint16(m_resolution_dimensions[1]);
DatagramIterator dgi(dg);
m_data = dgi.get_remaining_bytes();
m_data = compress_string(m_data, 9);
if (m_vfs->exists(m_file)) {
m_vfs->delete_file(m_file);
}
m_vfs->write_file(m_file, m_data, 0);
m_data = "";
}
void Settings::set_music(bool mode) {
m_want_music = mode;
}
void Settings::set_sfx(bool mode) {
m_want_sfx = mode;
}
void Settings::set_force_sw_midi(bool mode) {
m_force_sw_midi = mode;
}
void Settings::set_embedded_mode(bool mode) {
m_embedded_mode = mode;
}
void Settings::set_chat_log(bool mode) {
m_log_chat = mode;
}
void Settings::set_sfx_volume(float volume) {
m_sfx_volume = volume;
}
void Settings::set_music_volume(float volume) {
m_music_volume = volume;
}
void Settings::set_display_driver(unsigned int driver) {
m_current_driver = driver;
}
void Settings::set_windowed_mode(unsigned int mode) {
m_windowed_mode = mode;
}
void Settings::set_resolution(unsigned int resolution) {
m_resolution = resolution;
}
void Settings::set_resolution_dimensions(unsigned int xsize, unsigned int ysize) {
m_resolution_dimensions[0] = xsize;
m_resolution_dimensions[1] = ysize;
}
int Settings::get_resolution() {
return m_resolution;
}
int Settings::get_windowed_mode() {
return m_windowed_mode;
}
bool Settings::get_music() {
return m_want_music;
}
bool Settings::get_sfx() {
return m_want_sfx;
}
float Settings::get_sfx_volume() {
return m_sfx_volume;
}
float Settings::get_music_volume() {
return m_music_volume;
}
bool Settings::get_embedded_mode() {
return m_embedded_mode;
}
bool Settings::do_saved_settings_exist() {
return 0;
}
<commit_msg>That's better!<commit_after>#include "Settings.h"
TypeHandle Settings::_type_handle;
Settings::Settings() {
m_vfs = VirtualFileSystem::get_global_ptr();
m_file = Filename("/useropt"); //First let's use this to set our dir.
m_file = Filename(m_file.to_os_long_name()); //Now let's do the real file.
m_file.set_binary();
//Now to define our default settings.
m_want_music = 1;
m_want_sfx = 1;
m_sfx_volume = 100.0f;
m_music_volume = 100.0f;
m_force_sw_midi = 0;
m_embedded_mode = 0;
m_log_chat = 0;
m_current_driver = 0;
m_resolution = 1;
m_windowed_mode = 0;
m_resolution_dimensions[0] = 800;
m_resolution_dimensions[1] = 600;
}
Settings::~Settings() {
delete[] m_vfs;
}
void Settings::read_settings() {
Filename found(m_file);
if (!m_vfs->exists(found)) {
libotp_cat.debug() << "Failed to find Settings! Creating file...." << std::endl;
m_vfs->create_file(m_file);
write_settings();
return;
}
m_vfs->read_file(found, m_data, true);
m_data = decompress_string(m_data);
Datagram dg(m_data);
DatagramIterator dgi(dg);
m_data = "";
m_want_music = dgi.get_bool();
m_want_sfx = dgi.get_bool();
m_sfx_volume = dgi.get_stdfloat();
m_music_volume = dgi.get_stdfloat();
m_force_sw_midi = dgi.get_bool();
m_embedded_mode = dgi.get_bool();
m_log_chat = dgi.get_bool();
m_current_driver = dgi.get_uint8();
m_resolution = dgi.get_uint8();
m_windowed_mode = dgi.get_uint8();
m_resolution_dimensions[0] = dgi.get_uint16();
m_resolution_dimensions[1] = dgi.get_uint16();
}
void Settings::write_settings() {
Datagram dg;
dg.add_bool(m_want_music);
dg.add_bool(m_want_sfx);
dg.add_stdfloat(m_sfx_volume);
dg.add_stdfloat(m_music_volume);
dg.add_bool(m_force_sw_midi);
dg.add_bool(m_embedded_mode);
dg.add_bool(m_log_chat);
dg.add_uint8(m_current_driver);
dg.add_uint8(m_resolution);
dg.add_uint8(m_windowed_mode);
dg.add_uint16(m_resolution_dimensions[0]);
dg.add_uint16(m_resolution_dimensions[1]);
DatagramIterator dgi(dg);
m_data = dgi.get_remaining_bytes();
m_data = compress_string(m_data, 9);
if (m_vfs->exists(m_file)) {
m_vfs->delete_file(m_file);
}
m_vfs->write_file(m_file, m_data, 0);
m_data = "";
}
void Settings::set_music(bool mode) {
m_want_music = mode;
}
void Settings::set_sfx(bool mode) {
m_want_sfx = mode;
}
void Settings::set_force_sw_midi(bool mode) {
m_force_sw_midi = mode;
}
void Settings::set_embedded_mode(bool mode) {
m_embedded_mode = mode;
}
void Settings::set_chat_log(bool mode) {
m_log_chat = mode;
}
void Settings::set_sfx_volume(float volume) {
m_sfx_volume = volume;
}
void Settings::set_music_volume(float volume) {
m_music_volume = volume;
}
void Settings::set_display_driver(unsigned int driver) {
m_current_driver = driver;
}
void Settings::set_windowed_mode(unsigned int mode) {
m_windowed_mode = mode;
}
void Settings::set_resolution(unsigned int resolution) {
m_resolution = resolution;
}
void Settings::set_resolution_dimensions(unsigned int xsize, unsigned int ysize) {
m_resolution_dimensions[0] = xsize;
m_resolution_dimensions[1] = ysize;
}
int Settings::get_resolution() {
return m_resolution;
}
int Settings::get_windowed_mode() {
return m_windowed_mode;
}
bool Settings::get_music() {
return m_want_music;
}
bool Settings::get_sfx() {
return m_want_sfx;
}
float Settings::get_sfx_volume() {
return m_sfx_volume;
}
float Settings::get_music_volume() {
return m_music_volume;
}
bool Settings::get_embedded_mode() {
return m_embedded_mode;
}
bool Settings::do_saved_settings_exist() {
return m_vfs->exists(m_file);
}
<|endoftext|> |
<commit_before>#pragma once
#include "file_monitor.hpp"
#include "filesystem.hpp"
#include "gcd_utility.hpp"
#include "spdlog_utility.hpp"
#include <deque>
#include <fstream>
#include <spdlog/spdlog.h>
#include <thread>
#include <vector>
namespace krbn {
class log_monitor final {
public:
typedef std::function<void(const std::string& line)> new_log_line_callback;
log_monitor(const log_monitor&) = delete;
// FSEvents (file_monitor) notifies file changes only when the target file is just closed.
// So, it is not usable for log_monitor since spdlog keeps opening log files and appending lines.
//
// We use timer to observe file changes instead.
log_monitor(const std::vector<std::string>& targets,
const new_log_line_callback& callback) : callback_(callback), timer_count_(timer_count(0)) {
// setup initial_lines_
for (const auto& target : targets) {
add_initial_lines(target + ".1.txt");
add_initial_lines(target + ".txt");
files_.push_back(target + ".txt");
}
}
~log_monitor(void) {
timer_ = nullptr;
}
void start(void) {
timer_ = std::make_unique<gcd_utility::main_queue_timer>(
dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC),
1.0 * NSEC_PER_SEC,
0,
^{
timer_count_ = timer_count(static_cast<uint64_t>(timer_count_) + 1);
for (const auto& file : files_) {
if (auto size = filesystem::file_size(file)) {
auto it = read_position_.find(file);
if (it != read_position_.end()) {
if (it->second != *size) {
add_lines(file);
}
}
}
}
call_callback();
});
}
const std::vector<std::pair<uint64_t, std::string>>& get_initial_lines(void) const {
return initial_lines_;
}
private:
enum class timer_count : uint64_t {};
void add_initial_lines(const std::string& file_path) {
std::ifstream stream(file_path);
std::string line;
std::streampos read_position;
while (std::getline(stream, line)) {
if (add_initial_line(line)) {
const size_t max_initial_lines = 250;
while (initial_lines_.size() > max_initial_lines) {
initial_lines_.erase(initial_lines_.begin());
}
}
read_position = stream.tellg();
}
read_position_[file_path] = read_position;
}
bool add_initial_line(const std::string& line) {
if (auto sort_key = spdlog_utility::get_sort_key(line)) {
if (initial_lines_.empty()) {
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
if (*sort_key < initial_lines_.front().first) {
// line is too old
return false;
}
if (*sort_key > initial_lines_.back().first) {
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
for (auto it = initial_lines_.begin(); it != initial_lines_.end(); ++it) {
if (*sort_key < it->first) {
initial_lines_.insert(it, std::make_pair(*sort_key, line));
return true;
}
}
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
return false;
}
void add_lines(const std::string& file_path) {
std::ifstream stream(file_path);
if (!stream) {
return;
}
// ----------------------------------------
// seek
auto it = read_position_.find(file_path);
if (it != read_position_.end()) {
if (auto size = filesystem::file_size(file_path)) {
if (it->second < *size) {
stream.seekg(it->second);
}
}
}
// ----------------------------------------
// read
std::string line;
std::streampos read_position;
while (std::getline(stream, line)) {
if (auto sort_key = spdlog_utility::get_sort_key(line)) {
added_lines_.push_back(std::make_tuple(timer_count_, *sort_key, line));
}
read_position = stream.tellg();
}
read_position_[file_path] = read_position;
// ----------------------------------------
// sort
std::stable_sort(added_lines_.begin(), added_lines_.end(), [](const auto& a, const auto& b) {
return std::get<1>(a) < std::get<1>(b);
});
}
void call_callback(void) {
while (true) {
if (added_lines_.empty()) {
return;
}
auto front = added_lines_.front();
if (std::get<0>(front) != timer_count_) {
// Wait if front is just added.
return;
}
if (callback_) {
callback_(std::get<2>(front));
}
added_lines_.pop_front();
}
}
new_log_line_callback callback_;
std::unique_ptr<gcd_utility::main_queue_timer> timer_;
timer_count timer_count_;
std::vector<std::pair<uint64_t, std::string>> initial_lines_;
std::unordered_map<std::string, std::streampos> read_position_;
std::vector<std::string> files_;
std::deque<std::tuple<timer_count, uint64_t, std::string>> added_lines_;
};
}
<commit_msg>update #include<commit_after>#pragma once
#include "filesystem.hpp"
#include "gcd_utility.hpp"
#include "spdlog_utility.hpp"
#include <deque>
#include <fstream>
#include <spdlog/spdlog.h>
#include <thread>
#include <vector>
namespace krbn {
class log_monitor final {
public:
typedef std::function<void(const std::string& line)> new_log_line_callback;
log_monitor(const log_monitor&) = delete;
// FSEvents (file_monitor) notifies file changes only when the target file is just closed.
// So, it is not usable for log_monitor since spdlog keeps opening log files and appending lines.
//
// We use timer to observe file changes instead.
log_monitor(const std::vector<std::string>& targets,
const new_log_line_callback& callback) : callback_(callback), timer_count_(timer_count(0)) {
// setup initial_lines_
for (const auto& target : targets) {
add_initial_lines(target + ".1.txt");
add_initial_lines(target + ".txt");
files_.push_back(target + ".txt");
}
}
~log_monitor(void) {
timer_ = nullptr;
}
void start(void) {
timer_ = std::make_unique<gcd_utility::main_queue_timer>(
dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC),
1.0 * NSEC_PER_SEC,
0,
^{
timer_count_ = timer_count(static_cast<uint64_t>(timer_count_) + 1);
for (const auto& file : files_) {
if (auto size = filesystem::file_size(file)) {
auto it = read_position_.find(file);
if (it != read_position_.end()) {
if (it->second != *size) {
add_lines(file);
}
}
}
}
call_callback();
});
}
const std::vector<std::pair<uint64_t, std::string>>& get_initial_lines(void) const {
return initial_lines_;
}
private:
enum class timer_count : uint64_t {};
void add_initial_lines(const std::string& file_path) {
std::ifstream stream(file_path);
std::string line;
std::streampos read_position;
while (std::getline(stream, line)) {
if (add_initial_line(line)) {
const size_t max_initial_lines = 250;
while (initial_lines_.size() > max_initial_lines) {
initial_lines_.erase(initial_lines_.begin());
}
}
read_position = stream.tellg();
}
read_position_[file_path] = read_position;
}
bool add_initial_line(const std::string& line) {
if (auto sort_key = spdlog_utility::get_sort_key(line)) {
if (initial_lines_.empty()) {
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
if (*sort_key < initial_lines_.front().first) {
// line is too old
return false;
}
if (*sort_key > initial_lines_.back().first) {
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
for (auto it = initial_lines_.begin(); it != initial_lines_.end(); ++it) {
if (*sort_key < it->first) {
initial_lines_.insert(it, std::make_pair(*sort_key, line));
return true;
}
}
initial_lines_.push_back(std::make_pair(*sort_key, line));
return true;
}
return false;
}
void add_lines(const std::string& file_path) {
std::ifstream stream(file_path);
if (!stream) {
return;
}
// ----------------------------------------
// seek
auto it = read_position_.find(file_path);
if (it != read_position_.end()) {
if (auto size = filesystem::file_size(file_path)) {
if (it->second < *size) {
stream.seekg(it->second);
}
}
}
// ----------------------------------------
// read
std::string line;
std::streampos read_position;
while (std::getline(stream, line)) {
if (auto sort_key = spdlog_utility::get_sort_key(line)) {
added_lines_.push_back(std::make_tuple(timer_count_, *sort_key, line));
}
read_position = stream.tellg();
}
read_position_[file_path] = read_position;
// ----------------------------------------
// sort
std::stable_sort(added_lines_.begin(), added_lines_.end(), [](const auto& a, const auto& b) {
return std::get<1>(a) < std::get<1>(b);
});
}
void call_callback(void) {
while (true) {
if (added_lines_.empty()) {
return;
}
auto front = added_lines_.front();
if (std::get<0>(front) != timer_count_) {
// Wait if front is just added.
return;
}
if (callback_) {
callback_(std::get<2>(front));
}
added_lines_.pop_front();
}
}
new_log_line_callback callback_;
std::unique_ptr<gcd_utility::main_queue_timer> timer_;
timer_count timer_count_;
std::vector<std::pair<uint64_t, std::string>> initial_lines_;
std::unordered_map<std::string, std::streampos> read_position_;
std::vector<std::string> files_;
std::deque<std::tuple<timer_count, uint64_t, std::string>> added_lines_;
};
}
<|endoftext|> |
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include "ingen/shared/AtomReader.hpp"
#include "lv2/lv2plug.in/ns/ext/atom/util.h"
#include "raul/Path.hpp"
#include "raul/log.hpp"
namespace Ingen {
namespace Shared {
AtomReader::AtomReader(LV2URIMap& map, URIs& uris, Forge& forge, Interface& iface)
: _map(map)
, _uris(uris)
, _forge(forge)
, _iface(iface)
{
}
void
AtomReader::get_uri(const LV2_Atom* in, Raul::Atom& out)
{
if (in) {
if (in->type == _uris.atom_URID) {
const LV2_Atom_URID* urid = (const LV2_Atom_URID*)in;
out = _forge.alloc_uri(_map.unmap_uri(urid->body));
} else {
out = _forge.alloc(in->size, in->type, LV2_ATOM_BODY(in));
}
}
}
void
AtomReader::get_props(const LV2_Atom_Object* obj,
Ingen::Resource::Properties& props)
{
LV2_ATOM_OBJECT_FOREACH(obj, p) {
Raul::Atom val;
get_uri(&p->value, val);
props.insert(std::make_pair(_map.unmap_uri(p->key), val));
}
}
void
AtomReader::write(const LV2_Atom* msg)
{
if (msg->type != _uris.atom_Blank) {
Raul::warn << "Unknown message type " << msg->type << std::endl;
return;
}
const LV2_Atom_Object* obj = (const LV2_Atom_Object*)msg;
const LV2_Atom* subject = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_subject, &subject, NULL);
const char* subject_uri = NULL;
if (subject && subject->type == _uris.atom_URI) {
subject_uri = (const char*)LV2_ATOM_BODY(subject);
} else if (subject && subject->type == _uris.atom_URID) {
subject_uri = _map.unmap_uri(((LV2_Atom_URID*)subject)->body);
}
if (obj->body.otype == _uris.patch_Get) {
_iface.set_response_id(obj->body.id);
_iface.get(subject_uri);
} else if (obj->body.otype == _uris.patch_Delete) {
if (subject_uri) {
_iface.del(subject_uri);
return;
}
const LV2_Atom_Object* body = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_body, &body, 0);
if (body && body->body.otype == _uris.ingen_Edge) {
const LV2_Atom* tail = NULL;
const LV2_Atom* head = NULL;
lv2_atom_object_get(body,
(LV2_URID)_uris.ingen_tail, &tail,
(LV2_URID)_uris.ingen_head, &head,
NULL);
Raul::Atom tail_atom;
Raul::Atom head_atom;
get_uri(tail, tail_atom);
get_uri(head, head_atom);
if (tail_atom.is_valid() && head_atom.is_valid()) {
_iface.disconnect(Raul::Path(tail_atom.get_uri()),
Raul::Path(head_atom.get_uri()));
} else {
Raul::warn << "Delete of unknown object." << std::endl;
}
}
} else if (obj->body.otype == _uris.patch_Put) {
const LV2_Atom_Object* body = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_body, &body, 0);
if (!body) {
Raul::warn << "Put message has no body" << std::endl;
return;
} else if (!subject_uri) {
Raul::warn << "Put message has no subject" << std::endl;
return;
}
if (body->body.otype == _uris.ingen_Edge) {
LV2_Atom* tail = NULL;
LV2_Atom* head = NULL;
lv2_atom_object_get(body,
(LV2_URID)_uris.ingen_tail, &tail,
(LV2_URID)_uris.ingen_head, &head,
NULL);
if (!tail || !head) {
Raul::warn << "Edge has no tail or head" << std::endl;
return;
}
Raul::Atom tail_atom;
Raul::Atom head_atom;
get_uri(tail, tail_atom);
get_uri(head, head_atom);
_iface.connect(Raul::Path(tail_atom.get_uri()),
Raul::Path(head_atom.get_uri()));
} else {
Ingen::Resource::Properties props;
get_props(body, props);
_iface.set_response_id(obj->body.id);
_iface.put(subject_uri, props);
}
} else if (obj->body.otype == _uris.patch_Patch) {
if (!subject_uri) {
Raul::warn << "Put message has no subject" << std::endl;
return;
}
const LV2_Atom_Object* remove = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_remove, &remove, 0);
if (!remove) {
Raul::warn << "Patch message has no remove" << std::endl;
return;
}
const LV2_Atom_Object* add = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_add, &add, 0);
if (!add) {
Raul::warn << "Patch message has no add" << std::endl;
return;
}
Ingen::Resource::Properties add_props;
get_props(remove, add_props);
Ingen::Resource::Properties remove_props;
get_props(remove, remove_props);
_iface.delta(subject_uri, remove_props, add_props);
} else {
Raul::warn << "Unknown object type <"
<< _map.unmap_uri(obj->body.otype)
<< ">" << std::endl;
}
}
} // namespace Shared
} // namespace Ingen
<commit_msg>Implement set_property via atom interface (working blinkenlights).<commit_after>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include "ingen/shared/AtomReader.hpp"
#include "lv2/lv2plug.in/ns/ext/atom/util.h"
#include "raul/Path.hpp"
#include "raul/log.hpp"
namespace Ingen {
namespace Shared {
AtomReader::AtomReader(LV2URIMap& map, URIs& uris, Forge& forge, Interface& iface)
: _map(map)
, _uris(uris)
, _forge(forge)
, _iface(iface)
{
}
void
AtomReader::get_uri(const LV2_Atom* in, Raul::Atom& out)
{
if (in) {
if (in->type == _uris.atom_URID) {
const LV2_Atom_URID* urid = (const LV2_Atom_URID*)in;
out = _forge.alloc_uri(_map.unmap_uri(urid->body));
} else {
out = _forge.alloc(in->size, in->type, LV2_ATOM_BODY(in));
}
}
}
void
AtomReader::get_props(const LV2_Atom_Object* obj,
Ingen::Resource::Properties& props)
{
LV2_ATOM_OBJECT_FOREACH(obj, p) {
Raul::Atom val;
get_uri(&p->value, val);
props.insert(std::make_pair(_map.unmap_uri(p->key), val));
}
}
void
AtomReader::write(const LV2_Atom* msg)
{
if (msg->type != _uris.atom_Blank) {
Raul::warn << "Unknown message type " << msg->type << std::endl;
return;
}
const LV2_Atom_Object* obj = (const LV2_Atom_Object*)msg;
const LV2_Atom* subject = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_subject, &subject, NULL);
const char* subject_uri = NULL;
if (subject && subject->type == _uris.atom_URI) {
subject_uri = (const char*)LV2_ATOM_BODY(subject);
} else if (subject && subject->type == _uris.atom_URID) {
subject_uri = _map.unmap_uri(((LV2_Atom_URID*)subject)->body);
}
if (obj->body.otype == _uris.patch_Get) {
_iface.set_response_id(obj->body.id);
_iface.get(subject_uri);
} else if (obj->body.otype == _uris.patch_Delete) {
if (subject_uri) {
_iface.del(subject_uri);
return;
}
const LV2_Atom_Object* body = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_body, &body, 0);
if (body && body->body.otype == _uris.ingen_Edge) {
const LV2_Atom* tail = NULL;
const LV2_Atom* head = NULL;
lv2_atom_object_get(body,
(LV2_URID)_uris.ingen_tail, &tail,
(LV2_URID)_uris.ingen_head, &head,
NULL);
Raul::Atom tail_atom;
Raul::Atom head_atom;
get_uri(tail, tail_atom);
get_uri(head, head_atom);
if (tail_atom.is_valid() && head_atom.is_valid()) {
_iface.disconnect(Raul::Path(tail_atom.get_uri()),
Raul::Path(head_atom.get_uri()));
} else {
Raul::warn << "Delete of unknown object." << std::endl;
}
}
} else if (obj->body.otype == _uris.patch_Put) {
const LV2_Atom_Object* body = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_body, &body, 0);
if (!body) {
Raul::warn << "Put message has no body" << std::endl;
return;
} else if (!subject_uri) {
Raul::warn << "Put message has no subject" << std::endl;
return;
}
if (body->body.otype == _uris.ingen_Edge) {
LV2_Atom* tail = NULL;
LV2_Atom* head = NULL;
lv2_atom_object_get(body,
(LV2_URID)_uris.ingen_tail, &tail,
(LV2_URID)_uris.ingen_head, &head,
NULL);
if (!tail || !head) {
Raul::warn << "Edge has no tail or head" << std::endl;
return;
}
Raul::Atom tail_atom;
Raul::Atom head_atom;
get_uri(tail, tail_atom);
get_uri(head, head_atom);
_iface.connect(Raul::Path(tail_atom.get_uri()),
Raul::Path(head_atom.get_uri()));
} else {
Ingen::Resource::Properties props;
get_props(body, props);
_iface.set_response_id(obj->body.id);
_iface.put(subject_uri, props);
}
} else if (obj->body.otype == _uris.patch_Set) {
const LV2_Atom_Object* body = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_body, &body, 0);
if (!body) {
Raul::warn << "Set message has no body" << std::endl;
return;
} else if (!subject_uri) {
Raul::warn << "Set message has no subject" << std::endl;
return;
}
LV2_ATOM_OBJECT_FOREACH(body, p) {
Raul::Atom val;
get_uri(&p->value, val);
_iface.set_property(subject_uri, _map.unmap_uri(p->key), val);
}
} else if (obj->body.otype == _uris.patch_Patch) {
if (!subject_uri) {
Raul::warn << "Put message has no subject" << std::endl;
return;
}
const LV2_Atom_Object* remove = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_remove, &remove, 0);
if (!remove) {
Raul::warn << "Patch message has no remove" << std::endl;
return;
}
const LV2_Atom_Object* add = NULL;
lv2_atom_object_get(obj, (LV2_URID)_uris.patch_add, &add, 0);
if (!add) {
Raul::warn << "Patch message has no add" << std::endl;
return;
}
Ingen::Resource::Properties add_props;
get_props(remove, add_props);
Ingen::Resource::Properties remove_props;
get_props(remove, remove_props);
_iface.delta(subject_uri, remove_props, add_props);
} else {
Raul::warn << "Unknown object type <"
<< _map.unmap_uri(obj->body.otype)
<< ">" << std::endl;
}
}
} // namespace Shared
} // namespace Ingen
<|endoftext|> |
<commit_before>#ifndef K3_RUNTIME_COMMON_H
#define K3_RUNTIME_COMMON_H
#include <list>
#include <map>
#include <memory>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <boost/any.hpp>
#include <boost/asio.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/log/core.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/sources/severity_feature.hpp>
#include <boost/log/trivial.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/stl/algorithm.hpp>
namespace K3 {
using namespace std;
using boost::any;
using namespace boost::log;
using namespace boost::log::sources;
using namespace boost::log::trivial;
using namespace boost::phoenix;
typedef string Identifier;
typedef tuple<boost::asio::ip::address, unsigned short> Address;
enum class Builtin { Stdin, Stdout, Stderr };
enum class IOMode { Read, Write, Append, ReadWrite };
//---------------
// Addresses.
Address make_address(const string& host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
Address make_address(const char* host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
Address make_address(const string&& host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
inline string addressHost(const Address& addr) { return get<0>(addr).to_string(); }
inline string addressHost(Address&& addr) { return get<0>(std::forward<Address>(addr)).to_string(); }
inline int addressPort(const Address& addr) { return get<1>(addr); }
inline int addressPort(Address&& addr) { return get<1>(std::forward<Address>(addr)); }
string addressAsString(const Address& addr) {
return addressHost(addr) + ":" + to_string(addressPort(addr));
}
string addressAsString(Address&& addr) {
return addressHost(std::forward<Address>(addr))
+ ":" + to_string(addressPort(std::forward<Address>(addr)));
}
Address internalSendAddress(const Address& addr) {
return make_address(addressHost(addr), addressPort(addr)+1);
}
Address internalSendAddress(Address&& addr) {
return make_address(addressHost(std::forward<Address>(addr)),
addressPort(std::forward<Address>(addr))+1);
}
Address externalSendAddress(const Address& addr) {
return make_address(addressHost(addr), addressPort(addr)+2);
}
Address externalSendAddress(Address&& addr) {
return make_address(addressHost(std::forward<Address>(addr)),
addressPort(std::forward<Address>(addr))+2);
}
Address defaultAddress = make_address("127.0.0.1", 40000);
//-------------
// Messages.
template<typename Value>
class Message : public tuple<Address, Identifier, Value> {
public:
Message(Address addr, Identifier id, const Value& v)
: tuple<Address, Identifier, Value>(std::move(addr), std::move(id), v)
{}
Message(Address addr, Identifier id, Value&& v)
: tuple<Address, Identifier, Value>(std::move(addr), std::move(id), std::forward<Value>(v))
{}
Message(Address&& addr, Identifier&& id, Value&& v)
: tuple<Address, Identifier, Value>(std::forward<Address>(addr),
std::forward<Identifier>(id),
std::forward<Value>(v))
{}
Address& address() { return get<0>(*this); }
Identifier& id() { return get<1>(*this); }
Value& contents() { return get<2>(*this); }
string target() { return id() + "@" + addressAsString(address()); }
};
//--------------------
// System environment.
// Literals are native values rather than an AST reprensentation as in Haskell.
typedef any Literal;
typedef map<Identifier, Literal> PeerBootstrap;
typedef map<Address, PeerBootstrap> SystemEnvironment;
list<Address> deployedNodes(const SystemEnvironment& sysEnv) {
list<Address> r;
for ( auto x : sysEnv ) { r.push_back(x.first); }
return std::move(r);
}
bool isDeployedNode(const SystemEnvironment& sysEnv, Address addr) {
return sysEnv.find(addr) != sysEnv.end();
}
//-------------
// Logging.
class Log {
public:
Log() {}
Log(severity_level lvl) : defaultLevel(lvl) {}
virtual void log(const string& msg) = 0;
virtual void log(const char* msg) = 0;
virtual void logAt(severity_level lvl, const string& msg) = 0;
virtual void logAt(severity_level lvl, const char* msg) = 0;
protected:
severity_level defaultLevel;
};
class LogST : public severity_channel_logger<severity_level,string>, public Log
{
public:
typedef severity_channel_logger<severity_level,string> logger;
LogST(string chan) : logger(keywords::channel = chan), Log(severity_level::info) {}
LogST(string chan, severity_level lvl) : logger(keywords::channel = chan), Log(lvl) {}
void log(const string& msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void log(const char* msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void logAt(severity_level lvl, const string& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
void logAt(severity_level lvl, const char& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
};
class LogMT : public severity_channel_logger_mt<severity_level,string>, public Log
{
public:
typedef severity_channel_logger_mt<severity_level,string> logger;
LogMT(string chan) : logger(keywords::channel = chan), Log(severity_level::info) {}
LogMT(string chan, severity_level lvl) : logger(keywords::channel = chan), Log(lvl) {}
void log(const string& msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void log(const char* msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void logAt(severity_level lvl, const string& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
void logAt(severity_level lvl, const char* msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
};
//--------------------
// Wire descriptions
// A generic exception that can be thrown by wire descriptor methods.
class WireDescException : public runtime_error {
public:
WireDescException(const string& msg) : runtime_error(msg) {}
WireDescException(const char* msg) : runtime_error(msg) {}
};
// Message serializtion/deserialization abstract base class.
// Implementations can encapsulate framing concerns as well as serdes operations.
//
// The unpack method may be supplied a complete or incomplete string corresponding
// to a value. It is left to the implementation to determine the scope of functionality
// supported, for example partial unpacking (e.g., for network sockets).
// The semantics of repeated invocations are dependent on the actual implementation
// of the wire description (including factors such as message loss).
// This includes the conditions under which an exception is thrown.
template<typename T>
class WireDesc : public virtual LogMT {
public:
WireDesc() : LogMT("WireDesc") {}
virtual string pack(const T& payload) = 0;
virtual shared_ptr<T> unpack(const string& message) = 0;
};
class DefaultWireDesc : public WireDesc<string> {
public:
DefaultWireDesc() : LogMT("DefaultWireDesc") {}
string pack(const string& payload) { return payload; }
shared_ptr<string> unpack(const string& message) { return shared_ptr<string>(new string(message)); }
};
template <class T>
class BoostWireDesc : public virtual LogMT {
public:
BoostWireDesc() : LogMT("BoostWireDesc") {}
static string pack(const T& payload) {
ostringstream out_sstream;
boost::archive::text_oarchive out_archive(out_sstream);
out_archive << payload;
return out_sstream.str();
}
static shared_ptr<T> unpack(const string& message) {
istringstream in_sstream(message);
boost::archive::text_iarchive in_archive(in_sstream);
shared_ptr<T> p;
in_archive >> *p;
return p;
}
};
/*
template <template<class> class F>
class WireDesc : public virtual LogMT {
public:
WireDesc() : LogMT("WireDesc") {}
template <class T>
string pack(const T& payload) {
return F<T>::pack(payload);
}
template <class T>
shared_ptr<T> unpack(const string& message) {
return F<T>::unpack(message);
}
};
template <class T>
class BoostWireDesc : public WireDesc<BoostWireDesc> {
public:
BoostWireDesc() : WireDesc(), LogMT("BoostWireDesc") {}
static string pack(const T& payload) {
ostringstream out_sstream;
boost::archive::text_oarchive out_archive(out_sstream);
out_archive << payload;
return out_sstream.str();
}
static shared_ptr<T> unpack(const string& message) {
istringstream in_sstream(message);
boost::archive::text_iarchive in_archive(in_sstream);
shared_ptr<T> p;
in_archive >> *p;
return p;
}
};
*/
// TODO: protobuf, msgpack, json WireDesc implementations.
}
#endif
<commit_msg>Add const methods to return const ref in Message<commit_after>#ifndef K3_RUNTIME_COMMON_H
#define K3_RUNTIME_COMMON_H
#include <list>
#include <map>
#include <memory>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <boost/any.hpp>
#include <boost/asio.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/log/core.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/sources/severity_feature.hpp>
#include <boost/log/trivial.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/stl/algorithm.hpp>
namespace K3 {
using namespace std;
using boost::any;
using namespace boost::log;
using namespace boost::log::sources;
using namespace boost::log::trivial;
using namespace boost::phoenix;
typedef string Identifier;
typedef tuple<boost::asio::ip::address, unsigned short> Address;
enum class Builtin { Stdin, Stdout, Stderr };
enum class IOMode { Read, Write, Append, ReadWrite };
//---------------
// Addresses.
Address make_address(const string& host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
Address make_address(const char* host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
Address make_address(const string&& host, unsigned short port) {
return Address(boost::asio::ip::address::from_string(host), port);
}
inline string addressHost(const Address& addr) { return get<0>(addr).to_string(); }
inline string addressHost(Address&& addr) { return get<0>(std::forward<Address>(addr)).to_string(); }
inline int addressPort(const Address& addr) { return get<1>(addr); }
inline int addressPort(Address&& addr) { return get<1>(std::forward<Address>(addr)); }
string addressAsString(const Address& addr) {
return addressHost(addr) + ":" + to_string(addressPort(addr));
}
string addressAsString(Address&& addr) {
return addressHost(std::forward<Address>(addr))
+ ":" + to_string(addressPort(std::forward<Address>(addr)));
}
Address internalSendAddress(const Address& addr) {
return make_address(addressHost(addr), addressPort(addr)+1);
}
Address internalSendAddress(Address&& addr) {
return make_address(addressHost(std::forward<Address>(addr)),
addressPort(std::forward<Address>(addr))+1);
}
Address externalSendAddress(const Address& addr) {
return make_address(addressHost(addr), addressPort(addr)+2);
}
Address externalSendAddress(Address&& addr) {
return make_address(addressHost(std::forward<Address>(addr)),
addressPort(std::forward<Address>(addr))+2);
}
Address defaultAddress = make_address("127.0.0.1", 40000);
//-------------
// Messages.
template<typename Value>
class Message : public tuple<Address, Identifier, Value> {
public:
Message(Address addr, Identifier id, const Value& v)
: tuple<Address, Identifier, Value>(std::move(addr), std::move(id), v)
{}
Message(Address addr, Identifier id, Value&& v)
: tuple<Address, Identifier, Value>(std::move(addr), std::move(id), std::forward<Value>(v))
{}
Message(Address&& addr, Identifier&& id, Value&& v)
: tuple<Address, Identifier, Value>(std::forward<Address>(addr),
std::forward<Identifier>(id),
std::forward<Value>(v))
{}
Address& address() { return get<0>(*this); }
Identifier& id() { return get<1>(*this); }
Value& contents() { return get<2>(*this); }
string target() { return id() + "@" + addressAsString(address()); }
const Address& address() const { return get<0>(*this); }
const Identifier& id() const { return get<1>(*this); }
const Value& contents() const { return get<2>(*this); }
const string target() const { return id() + "@" + addressAsString(address()); }
};
//--------------------
// System environment.
// Literals are native values rather than an AST reprensentation as in Haskell.
typedef any Literal;
typedef map<Identifier, Literal> PeerBootstrap;
typedef map<Address, PeerBootstrap> SystemEnvironment;
list<Address> deployedNodes(const SystemEnvironment& sysEnv) {
list<Address> r;
for ( auto x : sysEnv ) { r.push_back(x.first); }
return std::move(r);
}
bool isDeployedNode(const SystemEnvironment& sysEnv, Address addr) {
return sysEnv.find(addr) != sysEnv.end();
}
//-------------
// Logging.
class Log {
public:
Log() {}
Log(severity_level lvl) : defaultLevel(lvl) {}
virtual void log(const string& msg) = 0;
virtual void log(const char* msg) = 0;
virtual void logAt(severity_level lvl, const string& msg) = 0;
virtual void logAt(severity_level lvl, const char* msg) = 0;
protected:
severity_level defaultLevel;
};
class LogST : public severity_channel_logger<severity_level,string>, public Log
{
public:
typedef severity_channel_logger<severity_level,string> logger;
LogST(string chan) : logger(keywords::channel = chan), Log(severity_level::info) {}
LogST(string chan, severity_level lvl) : logger(keywords::channel = chan), Log(lvl) {}
void log(const string& msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void log(const char* msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void logAt(severity_level lvl, const string& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
void logAt(severity_level lvl, const char& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
};
class LogMT : public severity_channel_logger_mt<severity_level,string>, public Log
{
public:
typedef severity_channel_logger_mt<severity_level,string> logger;
LogMT(string chan) : logger(keywords::channel = chan), Log(severity_level::info) {}
LogMT(string chan, severity_level lvl) : logger(keywords::channel = chan), Log(lvl) {}
void log(const string& msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void log(const char* msg) { BOOST_LOG_SEV(*this, defaultLevel) << msg; }
void logAt(severity_level lvl, const string& msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
void logAt(severity_level lvl, const char* msg) { BOOST_LOG_SEV(*this, lvl) << msg; }
};
//--------------------
// Wire descriptions
// A generic exception that can be thrown by wire descriptor methods.
class WireDescException : public runtime_error {
public:
WireDescException(const string& msg) : runtime_error(msg) {}
WireDescException(const char* msg) : runtime_error(msg) {}
};
// Message serializtion/deserialization abstract base class.
// Implementations can encapsulate framing concerns as well as serdes operations.
//
// The unpack method may be supplied a complete or incomplete string corresponding
// to a value. It is left to the implementation to determine the scope of functionality
// supported, for example partial unpacking (e.g., for network sockets).
// The semantics of repeated invocations are dependent on the actual implementation
// of the wire description (including factors such as message loss).
// This includes the conditions under which an exception is thrown.
template<typename T>
class WireDesc : public virtual LogMT {
public:
WireDesc() : LogMT("WireDesc") {}
virtual string pack(const T& payload) = 0;
virtual shared_ptr<T> unpack(const string& message) = 0;
};
class DefaultWireDesc : public WireDesc<string> {
public:
DefaultWireDesc() : LogMT("DefaultWireDesc") {}
string pack(const string& payload) { return payload; }
shared_ptr<string> unpack(const string& message) { return shared_ptr<string>(new string(message)); }
};
template <class T>
class BoostWireDesc : public virtual LogMT {
public:
BoostWireDesc() : LogMT("BoostWireDesc") {}
static string pack(const T& payload) {
ostringstream out_sstream;
boost::archive::text_oarchive out_archive(out_sstream);
out_archive << payload;
return out_sstream.str();
}
static shared_ptr<T> unpack(const string& message) {
istringstream in_sstream(message);
boost::archive::text_iarchive in_archive(in_sstream);
shared_ptr<T> p;
in_archive >> *p;
return p;
}
};
/*
template <template<class> class F>
class WireDesc : public virtual LogMT {
public:
WireDesc() : LogMT("WireDesc") {}
template <class T>
string pack(const T& payload) {
return F<T>::pack(payload);
}
template <class T>
shared_ptr<T> unpack(const string& message) {
return F<T>::unpack(message);
}
};
template <class T>
class BoostWireDesc : public WireDesc<BoostWireDesc> {
public:
BoostWireDesc() : WireDesc(), LogMT("BoostWireDesc") {}
static string pack(const T& payload) {
ostringstream out_sstream;
boost::archive::text_oarchive out_archive(out_sstream);
out_archive << payload;
return out_sstream.str();
}
static shared_ptr<T> unpack(const string& message) {
istringstream in_sstream(message);
boost::archive::text_iarchive in_archive(in_sstream);
shared_ptr<T> p;
in_archive >> *p;
return p;
}
};
*/
// TODO: protobuf, msgpack, json WireDesc implementations.
}
#endif
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2019 by Contributors
* \file eliminate_common_expr.cc
* \brief Eliminate common expressions in the graph
* \author Przemyslaw Tredak
*/
#include <mxnet/base.h>
#include <mxnet/op_attr_types.h>
#include <vector>
#include <map>
#include <utility>
#include <sstream>
namespace mxnet {
namespace exec {
namespace {
using nnvm::Node;
using nnvm::ObjectPtr;
using nnvm::Graph;
using nnvm::IndexedGraph;
// NodeInput holds the sufficient subset of NodeEntry fields for Node-input equality tests
using NodeInput = std::pair<const Node*, uint32_t>;
/*!
* \brief Convert a Node's input vector of `NodeEntry` to a vector of the simpler `NodeInput`
*/
std::vector<NodeInput> ConvertInputs(const std::vector<nnvm::NodeEntry>& inputs) {
std::vector<NodeInput> ret;
ret.reserve(inputs.size());
for (const auto& entry : inputs) {
ret.emplace_back(entry.node.get(), entry.index);
}
return ret;
}
/*!
* \brief Determine if two Nodes have equal function such that one Node can be eliminated.
*/
bool NodeEqual(const Node* n, const Node* m) {
if (n->is_variable() || m->is_variable()) return false;
if (n->op() != m->op()) return false;
// Nodes with different attributes are considered not identical,
// though this may reject Node pairs that are in fact functionally the same.
if (n->attrs.dict != m->attrs.dict) return false;
// Ops that mutate inputs cannot be optimized out
static auto& fmutate_inputs = Op::GetAttr<nnvm::FMutateInputs>("FMutateInputs");
if (fmutate_inputs.get(n->op(), nullptr) != nullptr) return false;
// Stateful ops cannot be be equal to each other
static auto& fstateful = Op::GetAttr<FCreateOpState>("FCreateOpState");
if (fstateful.get(n->op(), nullptr) != nullptr)
return false;
// Check to see if the user has explicitly set THasDeterministicOutput to override the
// subsequent determination of Node equality based on resource use.
static auto& deterministic_output =
Op::GetAttr<THasDeterministicOutput>("THasDeterministicOutput");
if (deterministic_output.contains(n->op()))
return deterministic_output[n->op()];
// Ops that require resource could ask for
// random resource, so need to be explicitly marked
// to be eligible
static auto& resource_request = Op::GetAttr<FResourceRequest>("FResourceRequest");
static auto& resource_request_ex = Op::GetAttr<FResourceRequestEx>("FResourceRequestEx");
if (resource_request.get(n->op(), nullptr) != nullptr) return false;
if (resource_request_ex.get(n->op(), nullptr) != nullptr) return false;
return true;
}
// Graph traversal to create a list of pairs of identical-function nodes that can be combined.
std::vector<std::pair<ObjectPtr, ObjectPtr> > GetCommonNodes(const Graph& g) {
std::vector<std::pair<ObjectPtr, ObjectPtr> > ret;
// A map between a vector of inputs and those nodes that have those inputs
std::map<std::vector<NodeInput>, std::vector<const ObjectPtr*> > grouped_nodes;
// Traverse the graph and group the nodes by their vector of inputs
nnvm::DFSVisit(g.outputs, [&grouped_nodes](const ObjectPtr& n) {
if (n->inputs.size() != 0) {
grouped_nodes[ConvertInputs(n->inputs)].push_back(&n);
}
});
// Now check for identical node ops within the node groups (having identical inputs)
for (const auto& pair : grouped_nodes) {
auto &node_group = pair.second; // Group of nodes that share the same vector of inputs
if (node_group.size() > 1) {
std::unordered_set<size_t> visited;
for (size_t i = 0; i < node_group.size(); ++i) {
if (visited.count(i)) continue;
for (size_t j = i + 1; j < node_group.size(); ++j) {
// If the two Nodes have equal function, then one Node (called the 'replaced') can
// be eliminated in favor of the other Node (the 'src').
if (NodeEqual(node_group[i]->get(), node_group[j]->get())) {
visited.insert(j);
ObjectPtr src = *node_group[i];
ObjectPtr replaced = *node_group[j];
ret.emplace_back(src, replaced);
}
}
}
}
}
return ret;
}
/*!
* \brief Do a single pass of Node elimination given pairs of identical Nodes.
*/
void EliminateCommonNodes(Graph* g,
const std::vector<std::pair<ObjectPtr, ObjectPtr> >& common_nodes) {
for (const auto &p : common_nodes) {
std::vector <ObjectPtr> nodes_to_change;
const ObjectPtr &src = p.first;
const ObjectPtr &replaced = p.second;
// Create a `nodes_to_change` list containing the Nodes that refer to the `replaced` Node
// that is targeted for elimination.
DFSVisit(g->outputs, [replaced, &nodes_to_change](const ObjectPtr &n) {
for (const auto &dep : n->control_deps) {
if (dep == replaced) {
nodes_to_change.push_back(n);
return;
}
}
for (const auto &inp : n->inputs) {
if (inp.node == replaced) {
nodes_to_change.push_back(n);
return;
}
}
});
// Change references to the `replaced` Node within the `nodes_to_change` list to be
// references to the equivalent `src` Node.
for (auto &n : nodes_to_change) {
for (auto &dep : n->control_deps) {
if (dep == replaced) {
dep = src;
}
}
for (auto &inp : n->inputs) {
if (inp.node == replaced) {
inp.node = src;
}
}
}
// Add `replaced` Node control dependencies to those of the `src` Node.
for (const auto &n : replaced->control_deps) {
src->control_deps.push_back(n);
}
// Change graph outputs driven by the `replaced` Node to now point to the `src` Node.
for (auto& out : g->outputs) {
if (out.node == replaced) {
out.node = src;
}
}
}
// Check for duplicates in outputs and
// insert Copy nodes as appropriate
const Op* copy_op = Op::Get("_copy");
nnvm::NodeEntryMap<size_t> unique_outputs;
for (auto & output : g->outputs) {
auto kv = unique_outputs.find(output);
if (kv == unique_outputs.end()) {
unique_outputs.emplace(output, 0);
} else {
ObjectPtr copy_node = Node::Create();
std::ostringstream os;
os << kv->first.node->attrs.name << "_" << kv->second << "_copy";
kv->second++;
copy_node->attrs.op = copy_op;
copy_node->attrs.name = os.str();
copy_node->inputs.emplace_back(kv->first);
output = nnvm::NodeEntry{copy_node, 0, 0};
}
}
}
} // namespace
/*!
* \brief Simplify a graph by iteratively eliminating Nodes with identical inputs and function.
*/
nnvm::Graph EliminateCommonExpr(nnvm::Graph&& g) {
using nnvm::ObjectPtr;
bool keep_running = true;
while (keep_running) {
const auto& common_nodes = GetCommonNodes(g);
if (common_nodes.empty()) {
keep_running = false;
} else {
EliminateCommonNodes(&g, common_nodes);
}
}
return std::move(g);
}
} // namespace exec
} // namespace mxnet
<commit_msg>Allow eliminating common subexpressions when temp space is used (#19486)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2019 by Contributors
* \file eliminate_common_expr.cc
* \brief Eliminate common expressions in the graph
* \author Przemyslaw Tredak
*/
#include <mxnet/base.h>
#include <mxnet/op_attr_types.h>
#include <vector>
#include <map>
#include <utility>
#include <sstream>
namespace mxnet {
namespace exec {
namespace {
using nnvm::Node;
using nnvm::ObjectPtr;
using nnvm::Graph;
using nnvm::IndexedGraph;
// NodeInput holds the sufficient subset of NodeEntry fields for Node-input equality tests
using NodeInput = std::pair<const Node*, uint32_t>;
/*!
* \brief Convert a Node's input vector of `NodeEntry` to a vector of the simpler `NodeInput`
*/
std::vector<NodeInput> ConvertInputs(const std::vector<nnvm::NodeEntry>& inputs) {
std::vector<NodeInput> ret;
ret.reserve(inputs.size());
for (const auto& entry : inputs) {
ret.emplace_back(entry.node.get(), entry.index);
}
return ret;
}
/*!
* \brief Determine if two Nodes have equal function such that one Node can be eliminated.
*/
bool NodeEqual(const Node* n, const Node* m) {
if (n->is_variable() || m->is_variable()) return false;
if (n->op() != m->op()) return false;
// Nodes with different attributes are considered not identical,
// though this may reject Node pairs that are in fact functionally the same.
if (n->attrs.dict != m->attrs.dict) return false;
// Ops that mutate inputs cannot be optimized out
static auto& fmutate_inputs = Op::GetAttr<nnvm::FMutateInputs>("FMutateInputs");
if (fmutate_inputs.get(n->op(), nullptr) != nullptr) return false;
// Stateful ops cannot be be equal to each other
static auto& fstateful = Op::GetAttr<FCreateOpState>("FCreateOpState");
if (fstateful.get(n->op(), nullptr) != nullptr)
return false;
// Check to see if the user has explicitly set THasDeterministicOutput to override the
// subsequent determination of Node equality based on resource use.
static auto& deterministic_output =
Op::GetAttr<THasDeterministicOutput>("THasDeterministicOutput");
if (deterministic_output.contains(n->op()))
return deterministic_output[n->op()];
// Ops that require resource could ask for
// random resource, so need to be explicitly marked
// to be eligible
static auto& resource_request = Op::GetAttr<FResourceRequest>("FResourceRequest");
static auto& resource_request_ex = Op::GetAttr<FResourceRequestEx>("FResourceRequestEx");
const auto fresource_request = resource_request.get(n->op(), nullptr);
if (fresource_request != nullptr) {
const auto& requests = fresource_request(n->attrs);
for (const auto& req : requests) {
if (req.type != ResourceRequest::kTempSpace) {
return false;
}
}
}
if (resource_request_ex.get(n->op(), nullptr) != nullptr) return false;
return true;
}
// Graph traversal to create a list of pairs of identical-function nodes that can be combined.
std::vector<std::pair<ObjectPtr, ObjectPtr> > GetCommonNodes(const Graph& g) {
std::vector<std::pair<ObjectPtr, ObjectPtr> > ret;
// A map between a vector of inputs and those nodes that have those inputs
std::map<std::vector<NodeInput>, std::vector<const ObjectPtr*> > grouped_nodes;
// Traverse the graph and group the nodes by their vector of inputs
nnvm::DFSVisit(g.outputs, [&grouped_nodes](const ObjectPtr& n) {
if (n->inputs.size() != 0) {
grouped_nodes[ConvertInputs(n->inputs)].push_back(&n);
}
});
// Now check for identical node ops within the node groups (having identical inputs)
for (const auto& pair : grouped_nodes) {
auto &node_group = pair.second; // Group of nodes that share the same vector of inputs
if (node_group.size() > 1) {
std::unordered_set<size_t> visited;
for (size_t i = 0; i < node_group.size(); ++i) {
if (visited.count(i)) continue;
for (size_t j = i + 1; j < node_group.size(); ++j) {
// If the two Nodes have equal function, then one Node (called the 'replaced') can
// be eliminated in favor of the other Node (the 'src').
if (NodeEqual(node_group[i]->get(), node_group[j]->get())) {
visited.insert(j);
ObjectPtr src = *node_group[i];
ObjectPtr replaced = *node_group[j];
ret.emplace_back(src, replaced);
}
}
}
}
}
return ret;
}
/*!
* \brief Do a single pass of Node elimination given pairs of identical Nodes.
*/
void EliminateCommonNodes(Graph* g,
const std::vector<std::pair<ObjectPtr, ObjectPtr> >& common_nodes) {
for (const auto &p : common_nodes) {
std::vector <ObjectPtr> nodes_to_change;
const ObjectPtr &src = p.first;
const ObjectPtr &replaced = p.second;
// Create a `nodes_to_change` list containing the Nodes that refer to the `replaced` Node
// that is targeted for elimination.
DFSVisit(g->outputs, [replaced, &nodes_to_change](const ObjectPtr &n) {
for (const auto &dep : n->control_deps) {
if (dep == replaced) {
nodes_to_change.push_back(n);
return;
}
}
for (const auto &inp : n->inputs) {
if (inp.node == replaced) {
nodes_to_change.push_back(n);
return;
}
}
});
// Change references to the `replaced` Node within the `nodes_to_change` list to be
// references to the equivalent `src` Node.
for (auto &n : nodes_to_change) {
for (auto &dep : n->control_deps) {
if (dep == replaced) {
dep = src;
}
}
for (auto &inp : n->inputs) {
if (inp.node == replaced) {
inp.node = src;
}
}
}
// Add `replaced` Node control dependencies to those of the `src` Node.
for (const auto &n : replaced->control_deps) {
src->control_deps.push_back(n);
}
// Change graph outputs driven by the `replaced` Node to now point to the `src` Node.
for (auto& out : g->outputs) {
if (out.node == replaced) {
out.node = src;
}
}
}
// Check for duplicates in outputs and
// insert Copy nodes as appropriate
const Op* copy_op = Op::Get("_copy");
nnvm::NodeEntryMap<size_t> unique_outputs;
for (auto & output : g->outputs) {
auto kv = unique_outputs.find(output);
if (kv == unique_outputs.end()) {
unique_outputs.emplace(output, 0);
} else {
ObjectPtr copy_node = Node::Create();
std::ostringstream os;
os << kv->first.node->attrs.name << "_" << kv->second << "_copy";
kv->second++;
copy_node->attrs.op = copy_op;
copy_node->attrs.name = os.str();
copy_node->inputs.emplace_back(kv->first);
output = nnvm::NodeEntry{copy_node, 0, 0};
}
}
}
} // namespace
/*!
* \brief Simplify a graph by iteratively eliminating Nodes with identical inputs and function.
*/
nnvm::Graph EliminateCommonExpr(nnvm::Graph&& g) {
using nnvm::ObjectPtr;
bool keep_running = true;
while (keep_running) {
const auto& common_nodes = GetCommonNodes(g);
if (common_nodes.empty()) {
keep_running = false;
} else {
EliminateCommonNodes(&g, common_nodes);
}
}
return std::move(g);
}
} // namespace exec
} // namespace mxnet
<|endoftext|> |
<commit_before>/*************************************************************************/
/* config_file.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 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 "config_file.h"
#include "core/io/file_access_encrypted.h"
#include "core/os/keyboard.h"
#include "core/variant/variant_parser.h"
PackedStringArray ConfigFile::_get_sections() const {
List<String> s;
get_sections(&s);
PackedStringArray arr;
arr.resize(s.size());
int idx = 0;
for (const String &E : s) {
arr.set(idx++, E);
}
return arr;
}
PackedStringArray ConfigFile::_get_section_keys(const String &p_section) const {
List<String> s;
get_section_keys(p_section, &s);
PackedStringArray arr;
arr.resize(s.size());
int idx = 0;
for (const String &E : s) {
arr.set(idx++, E);
}
return arr;
}
void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL) {
//erase
if (!values.has(p_section)) {
return; // ?
}
values[p_section].erase(p_key);
if (values[p_section].is_empty()) {
values.erase(p_section);
}
} else {
if (!values.has(p_section)) {
values[p_section] = HashMap<String, Variant>();
}
values[p_section][p_key] = p_value;
}
}
Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const {
if (!values.has(p_section) || !values[p_section].has(p_key)) {
ERR_FAIL_COND_V_MSG(p_default.get_type() == Variant::NIL, Variant(),
vformat("Couldn't find the given section \"%s\" and key \"%s\", and no default was given.", p_section, p_key));
return p_default;
}
return values[p_section][p_key];
}
bool ConfigFile::has_section(const String &p_section) const {
return values.has(p_section);
}
bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const {
if (!values.has(p_section)) {
return false;
}
return values[p_section].has(p_key);
}
void ConfigFile::get_sections(List<String> *r_sections) const {
for (const KeyValue<String, HashMap<String, Variant>> &E : values) {
r_sections->push_back(E.key);
}
}
void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot get keys from nonexistent section \"%s\".", p_section));
for (const KeyValue<String, Variant> &E : values[p_section]) {
r_keys->push_back(E.key);
}
}
void ConfigFile::erase_section(const String &p_section) {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot erase nonexistent section \"%s\".", p_section));
values.erase(p_section);
}
void ConfigFile::erase_section_key(const String &p_section, const String &p_key) {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot erase key \"%s\" from nonexistent section \"%s\".", p_key, p_section));
ERR_FAIL_COND_MSG(!values[p_section].has(p_key), vformat("Cannot erase nonexistent key \"%s\" from section \"%s\".", p_key, p_section));
values[p_section].erase(p_key);
}
Error ConfigFile::save(const String &p_path) {
Error err;
Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
return _internal_save(file);
}
Error ConfigFile::save_encrypted(const String &p_path, const Vector<uint8_t> &p_key) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_WRITE_AES256);
if (err) {
return err;
}
return _internal_save(fae);
}
Error ConfigFile::save_encrypted_pass(const String &p_path, const String &p_pass) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_WRITE_AES256);
if (err) {
return err;
}
return _internal_save(fae);
}
Error ConfigFile::_internal_save(Ref<FileAccess> file) {
bool first = true;
for (const KeyValue<String, HashMap<String, Variant>> &E : values) {
if (first) {
first = false;
} else {
file->store_string("\n");
}
if (!E.key.is_empty()) {
file->store_string("[" + E.key + "]\n\n");
}
for (const KeyValue<String, Variant> &F : E.value) {
String vstr;
VariantWriter::write_to_string(F.value, vstr);
file->store_string(F.key.property_name_encode() + "=" + vstr + "\n");
}
}
return OK;
}
Error ConfigFile::load(const String &p_path) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (f.is_null()) {
return err;
}
return _internal_load(p_path, f);
}
Error ConfigFile::load_encrypted(const String &p_path, const Vector<uint8_t> &p_key) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_READ);
if (err) {
return err;
}
return _internal_load(p_path, fae);
}
Error ConfigFile::load_encrypted_pass(const String &p_path, const String &p_pass) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_READ);
if (err) {
return err;
}
return _internal_load(p_path, fae);
}
Error ConfigFile::_internal_load(const String &p_path, Ref<FileAccess> f) {
VariantParser::StreamFile stream;
stream.f = f;
Error err = _parse(p_path, &stream);
return err;
}
Error ConfigFile::parse(const String &p_data) {
VariantParser::StreamString stream;
stream.s = p_data;
return _parse("<string>", &stream);
}
Error ConfigFile::_parse(const String &p_path, VariantParser::Stream *p_stream) {
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
String section;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
Error err = VariantParser::parse_tag_assign_eof(p_stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
return OK;
} else if (err != OK) {
ERR_PRINT(vformat("ConfigFile parse error at %s:%d: %s.", p_path, lines, error_text));
return err;
}
if (!assign.is_empty()) {
set_value(section, assign, value);
} else if (!next_tag.name.is_empty()) {
section = next_tag.name;
}
}
return OK;
}
void ConfigFile::clear() {
values.clear();
}
void ConfigFile::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_value", "section", "key", "value"), &ConfigFile::set_value);
ClassDB::bind_method(D_METHOD("get_value", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant()));
ClassDB::bind_method(D_METHOD("has_section", "section"), &ConfigFile::has_section);
ClassDB::bind_method(D_METHOD("has_section_key", "section", "key"), &ConfigFile::has_section_key);
ClassDB::bind_method(D_METHOD("get_sections"), &ConfigFile::_get_sections);
ClassDB::bind_method(D_METHOD("get_section_keys", "section"), &ConfigFile::_get_section_keys);
ClassDB::bind_method(D_METHOD("erase_section", "section"), &ConfigFile::erase_section);
ClassDB::bind_method(D_METHOD("erase_section_key", "section", "key"), &ConfigFile::erase_section_key);
ClassDB::bind_method(D_METHOD("load", "path"), &ConfigFile::load);
ClassDB::bind_method(D_METHOD("parse", "data"), &ConfigFile::parse);
ClassDB::bind_method(D_METHOD("save", "path"), &ConfigFile::save);
BIND_METHOD_ERR_RETURN_DOC("load", ERR_FILE_CANT_OPEN);
ClassDB::bind_method(D_METHOD("load_encrypted", "path", "key"), &ConfigFile::load_encrypted);
ClassDB::bind_method(D_METHOD("load_encrypted_pass", "path", "password"), &ConfigFile::load_encrypted_pass);
ClassDB::bind_method(D_METHOD("save_encrypted", "path", "key"), &ConfigFile::save_encrypted);
ClassDB::bind_method(D_METHOD("save_encrypted_pass", "path", "password"), &ConfigFile::save_encrypted_pass);
ClassDB::bind_method(D_METHOD("clear"), &ConfigFile::clear);
}
<commit_msg>Fix saving section-less keys in `ConfigFile`<commit_after>/*************************************************************************/
/* config_file.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 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 "config_file.h"
#include "core/io/file_access_encrypted.h"
#include "core/os/keyboard.h"
#include "core/variant/variant_parser.h"
PackedStringArray ConfigFile::_get_sections() const {
List<String> s;
get_sections(&s);
PackedStringArray arr;
arr.resize(s.size());
int idx = 0;
for (const String &E : s) {
arr.set(idx++, E);
}
return arr;
}
PackedStringArray ConfigFile::_get_section_keys(const String &p_section) const {
List<String> s;
get_section_keys(p_section, &s);
PackedStringArray arr;
arr.resize(s.size());
int idx = 0;
for (const String &E : s) {
arr.set(idx++, E);
}
return arr;
}
void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL) { // Erase key.
if (!values.has(p_section)) {
return;
}
values[p_section].erase(p_key);
if (values[p_section].is_empty()) {
values.erase(p_section);
}
} else {
if (!values.has(p_section)) {
// Insert section-less keys at the beginning.
values.insert(p_section, HashMap<String, Variant>(), p_section.is_empty());
}
values[p_section][p_key] = p_value;
}
}
Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const {
if (!values.has(p_section) || !values[p_section].has(p_key)) {
ERR_FAIL_COND_V_MSG(p_default.get_type() == Variant::NIL, Variant(),
vformat("Couldn't find the given section \"%s\" and key \"%s\", and no default was given.", p_section, p_key));
return p_default;
}
return values[p_section][p_key];
}
bool ConfigFile::has_section(const String &p_section) const {
return values.has(p_section);
}
bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const {
if (!values.has(p_section)) {
return false;
}
return values[p_section].has(p_key);
}
void ConfigFile::get_sections(List<String> *r_sections) const {
for (const KeyValue<String, HashMap<String, Variant>> &E : values) {
r_sections->push_back(E.key);
}
}
void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot get keys from nonexistent section \"%s\".", p_section));
for (const KeyValue<String, Variant> &E : values[p_section]) {
r_keys->push_back(E.key);
}
}
void ConfigFile::erase_section(const String &p_section) {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot erase nonexistent section \"%s\".", p_section));
values.erase(p_section);
}
void ConfigFile::erase_section_key(const String &p_section, const String &p_key) {
ERR_FAIL_COND_MSG(!values.has(p_section), vformat("Cannot erase key \"%s\" from nonexistent section \"%s\".", p_key, p_section));
ERR_FAIL_COND_MSG(!values[p_section].has(p_key), vformat("Cannot erase nonexistent key \"%s\" from section \"%s\".", p_key, p_section));
values[p_section].erase(p_key);
if (values[p_section].is_empty()) {
values.erase(p_section);
}
}
Error ConfigFile::save(const String &p_path) {
Error err;
Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
return _internal_save(file);
}
Error ConfigFile::save_encrypted(const String &p_path, const Vector<uint8_t> &p_key) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_WRITE_AES256);
if (err) {
return err;
}
return _internal_save(fae);
}
Error ConfigFile::save_encrypted_pass(const String &p_path, const String &p_pass) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_WRITE_AES256);
if (err) {
return err;
}
return _internal_save(fae);
}
Error ConfigFile::_internal_save(Ref<FileAccess> file) {
bool first = true;
for (const KeyValue<String, HashMap<String, Variant>> &E : values) {
if (first) {
first = false;
} else {
file->store_string("\n");
}
if (!E.key.is_empty()) {
file->store_string("[" + E.key + "]\n\n");
}
for (const KeyValue<String, Variant> &F : E.value) {
String vstr;
VariantWriter::write_to_string(F.value, vstr);
file->store_string(F.key.property_name_encode() + "=" + vstr + "\n");
}
}
return OK;
}
Error ConfigFile::load(const String &p_path) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (f.is_null()) {
return err;
}
return _internal_load(p_path, f);
}
Error ConfigFile::load_encrypted(const String &p_path, const Vector<uint8_t> &p_key) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_READ);
if (err) {
return err;
}
return _internal_load(p_path, fae);
}
Error ConfigFile::load_encrypted_pass(const String &p_path, const String &p_pass) {
Error err;
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
return err;
}
Ref<FileAccessEncrypted> fae;
fae.instantiate();
err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_READ);
if (err) {
return err;
}
return _internal_load(p_path, fae);
}
Error ConfigFile::_internal_load(const String &p_path, Ref<FileAccess> f) {
VariantParser::StreamFile stream;
stream.f = f;
Error err = _parse(p_path, &stream);
return err;
}
Error ConfigFile::parse(const String &p_data) {
VariantParser::StreamString stream;
stream.s = p_data;
return _parse("<string>", &stream);
}
Error ConfigFile::_parse(const String &p_path, VariantParser::Stream *p_stream) {
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
String section;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
Error err = VariantParser::parse_tag_assign_eof(p_stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
return OK;
} else if (err != OK) {
ERR_PRINT(vformat("ConfigFile parse error at %s:%d: %s.", p_path, lines, error_text));
return err;
}
if (!assign.is_empty()) {
set_value(section, assign, value);
} else if (!next_tag.name.is_empty()) {
section = next_tag.name;
}
}
return OK;
}
void ConfigFile::clear() {
values.clear();
}
void ConfigFile::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_value", "section", "key", "value"), &ConfigFile::set_value);
ClassDB::bind_method(D_METHOD("get_value", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant()));
ClassDB::bind_method(D_METHOD("has_section", "section"), &ConfigFile::has_section);
ClassDB::bind_method(D_METHOD("has_section_key", "section", "key"), &ConfigFile::has_section_key);
ClassDB::bind_method(D_METHOD("get_sections"), &ConfigFile::_get_sections);
ClassDB::bind_method(D_METHOD("get_section_keys", "section"), &ConfigFile::_get_section_keys);
ClassDB::bind_method(D_METHOD("erase_section", "section"), &ConfigFile::erase_section);
ClassDB::bind_method(D_METHOD("erase_section_key", "section", "key"), &ConfigFile::erase_section_key);
ClassDB::bind_method(D_METHOD("load", "path"), &ConfigFile::load);
ClassDB::bind_method(D_METHOD("parse", "data"), &ConfigFile::parse);
ClassDB::bind_method(D_METHOD("save", "path"), &ConfigFile::save);
BIND_METHOD_ERR_RETURN_DOC("load", ERR_FILE_CANT_OPEN);
ClassDB::bind_method(D_METHOD("load_encrypted", "path", "key"), &ConfigFile::load_encrypted);
ClassDB::bind_method(D_METHOD("load_encrypted_pass", "path", "password"), &ConfigFile::load_encrypted_pass);
ClassDB::bind_method(D_METHOD("save_encrypted", "path", "key"), &ConfigFile::save_encrypted);
ClassDB::bind_method(D_METHOD("save_encrypted_pass", "path", "password"), &ConfigFile::save_encrypted_pass);
ClassDB::bind_method(D_METHOD("clear"), &ConfigFile::clear);
}
<|endoftext|> |
<commit_before>/*
* File: SDFLoader.cpp
* Author: Benedikt Vogler
*
* Created on 8. Juli 2014, 18:52
*/
#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
#include "Composite.hpp"
using namespace std;
/**
* Loads a scene file and reacts to the commands in it
* @param scenefile the string to the file
* @return
*/
Scene SDFLoader::load(std::string const& scenefile) {
cout << "Loading file: " << scenefile << endl;
Scene scene = Scene();
std::map<std::string, Material> mMap;
std::map<std::string, LightPoint> lMap;
std::map<std::string, RenderObject*> roMap;
string line;
ifstream file(scenefile);
stringstream ss;
//file.open(scenefile, ios::in);
if (file.is_open()) {
while (getline (file,line)){//get line
ss = stringstream(line);//fill the line into stringstream
string firstWord;
ss >> firstWord;
//is first string define?
if (firstWord=="define"){
cout << "defininig: ";
ss >> firstWord;
if (firstWord=="material"){
cout << "a material: "<<endl;
//extract name
string name;
ss>>name;
//extract color
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color ca(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cd(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cs(red, green, blue);
float m;
ss >> m;
Material mat(ca, cd, cs,m, name);
cout << "Material specs: "<<endl<<mat;
mMap[name]=mat;
} else if (firstWord=="camera"){
string cameraname;
ss >> cameraname;
int fovX;
ss >> fovX;
scene.camera = Camera(cameraname,fovX);
cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;
} else if (firstWord=="light"){
string type;
ss>>type;
if (type=="diffuse") {
string name;
ss >> name;
glm::vec3 pos;
ss >> pos.x;
ss >> pos.y;
ss >> pos.z;
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color diff(red, green, blue);
LightPoint light = LightPoint(name, pos, diff);
cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
lMap[name] = light;
}else if (type=="ambient") {
string lightname;
ss >> lightname;//name get's ignored
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color amb(red, green, blue);
scene.amb = amb;
cout << "ambient light "<<amb<<endl;
} else {
cout << "type not supported yet."<<endl;
}
} else if (firstWord=="shape"){
string classname;
ss >> classname;
cout << "Shape \""<< classname << "\"."<<endl;
transform(classname.begin(), classname.end(),classname.begin(), ::toupper);
string name;
ss >> name;
RenderObject* rObject = nullptr;
if (classname=="BOX"){
int edge1x, edge1y, edge1z;
ss>> edge1x;
ss>> edge1y;
ss>> edge1z;
int edge2x, edge2y, edge2z;
ss>> edge2x;
ss>> edge2y;
ss>> edge2z;
string materialName;
ss>>materialName;
Material material = mMap[materialName];
rObject = new Box(
name,
glm::vec3(edge1x, edge1y, edge1z),
glm::vec3(edge2x, edge2y, edge2z),
material
);
} else if (classname=="SPHERE") {
int posX, posY, posZ;
ss>> posX;
ss>> posY;
ss>> posZ;
float radius;
ss>>radius;
string materialString;
ss>>materialString;
rObject = new Sphere(
name,
glm::vec3(posX, posY, posZ),
radius,
mMap[materialString]
);
cout << "Sphere \""<< name << "\" aus Material "<<materialString<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl;
} else if(classname=="COMPOSITE") {
rObject = new Composite(name);
cout << "Composite \""<< name << "\" (" ;
string objectString;
while (!ss.eof()){
ss>>objectString;
auto linkedObject = roMap.find(objectString);
if (linkedObject == roMap.end()){
cout << "Error: "<<objectString <<" not found!";
} else {
((Composite*)rObject)->add_child(linkedObject->second);
cout<<", "<<objectString;
}
}
cout<<")"<<endl;
} else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;
if (rObject != nullptr)
roMap[name] = rObject;
} else
cout << "object to define not implemented:"<<ss.str() <<endl;
} else if (firstWord=="render"){
ss >> scene.camname;
ss >> scene.outputFile;
ss >> scene.resX;
ss >> scene.resY;
ss >> scene.antialiase;
//set default if not set
if (scene.resX<=0) scene.resX=480;
if (scene.resY<=0) scene.resY=320;
cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<<"with "<< scene.antialiase<<"x SSAA to "<<scene.outputFile<<endl;
} else if (firstWord=="#" || firstWord.substr(0,1)=="#"){
cout << line << endl;//just print comment lines
} else if (firstWord == "transform"){
string name, transform;
double X, Y, Z;
RenderObject* object;
ss >> name;
ss >> transform;
auto linkedObject = roMap.find(name);
if (linkedObject == roMap.end()){//check if object can be found
cout << "Error: " << name << " not found!";
} else {
object = linkedObject->second;
if (transform == "scale") {
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->scale(coords);
} else if (transform == "rotate") {
double angle;
ss >> angle;
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->rotate(angle,coords);
} else if (transform == "translate"){
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->translate(coords);
} else {
cout << "Unknown transformation" << endl;
}
}
} else cout << "???:"<<line <<endl;//print unknown lines
}
file.close();
}else cout << "Unable to open file";
//save collected data in scene
scene.materials = mMap;
scene.renderObjects = roMap;
scene.lights = lMap;
return scene;
}<commit_msg>improved logging<commit_after>/*
* File: SDFLoader.cpp
* Author: Benedikt Vogler
*
* Created on 8. Juli 2014, 18:52
*/
#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
#include "Composite.hpp"
using namespace std;
/**
* Loads a scene file and reacts to the commands in it
* @param scenefile the string to the file
* @return
*/
Scene SDFLoader::load(std::string const& scenefile) {
cout << "Loading file: " << scenefile << endl;
Scene scene = Scene();
std::map<std::string, Material> mMap;
std::map<std::string, LightPoint> lMap;
std::map<std::string, RenderObject*> roMap;
string line;
ifstream file(scenefile);
stringstream ss;
//file.open(scenefile, ios::in);
if (file.is_open()) {
while (getline (file,line)){//get line
ss = stringstream(line);//fill the line into stringstream
string firstWord;
ss >> firstWord;
//is first string define?
if (firstWord=="define"){
cout << "defininig: ";
ss >> firstWord;
if (firstWord=="material"){
cout << "a material: "<<endl;
//extract name
string name;
ss>>name;
//extract color
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color ca(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cd(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cs(red, green, blue);
float m;
ss >> m;
Material mat(ca, cd, cs,m, name);
cout << "Material specs: "<<endl<<mat;
mMap[name]=mat;
} else if (firstWord=="camera"){
string cameraname;
ss >> cameraname;
int fovX;
ss >> fovX;
scene.camera = Camera(cameraname,fovX);
cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;
} else if (firstWord=="light"){
string type;
ss>>type;
if (type=="diffuse") {
string name;
ss >> name;
glm::vec3 pos;
ss >> pos.x;
ss >> pos.y;
ss >> pos.z;
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color diff(red, green, blue);
LightPoint light = LightPoint(name, pos, diff);
cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
lMap[name] = light;
}else if (type=="ambient") {
string lightname;
ss >> lightname;//name get's ignored
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color amb(red, green, blue);
scene.amb = amb;
cout << "ambient light "<<amb<<endl;
} else {
cout << "type not supported yet."<<endl;
}
} else if (firstWord=="shape"){
string classname;
ss >> classname;
transform(classname.begin(), classname.end(),classname.begin(), ::toupper);
string name;
ss >> name;
RenderObject* rObject = nullptr;
if (classname=="BOX"){
int edge1x, edge1y, edge1z;
ss>> edge1x;
ss>> edge1y;
ss>> edge1z;
int edge2x, edge2y, edge2z;
ss>> edge2x;
ss>> edge2y;
ss>> edge2z;
string materialName;
ss>>materialName;
Material material = mMap[materialName];
rObject = new Box(
name,
glm::vec3(edge1x, edge1y, edge1z),
glm::vec3(edge2x, edge2y, edge2z),
material
);
} else if (classname=="SPHERE") {
int posX, posY, posZ;
ss>> posX;
ss>> posY;
ss>> posZ;
float radius;
ss>>radius;
string materialString;
ss>>materialString;
rObject = new Sphere(
name,
glm::vec3(posX, posY, posZ),
radius,
mMap[materialString]
);
cout << "Sphere \""<< name << "\" aus Material "<<materialString<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl;
} else if(classname=="COMPOSITE") {
rObject = new Composite(name);
cout << "Composite \""<< name << "\" (" ;
string objectString;
while (!ss.eof()){
ss>>objectString;
auto linkedObject = roMap.find(objectString);
if (linkedObject == roMap.end()){
cout << "Error: "<<objectString <<" not found!";
} else {
((Composite*)rObject)->add_child(linkedObject->second);
cout<<", "<<objectString;
}
}
cout<<")"<<endl;
} else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;
if (rObject != nullptr)
roMap[name] = rObject;
} else
cout << "object to define not implemented:"<<ss.str() <<endl;
} else if (firstWord=="render"){
ss >> scene.camname;
ss >> scene.outputFile;
ss >> scene.resX;
ss >> scene.resY;
ss >> scene.antialiase;
//set default if not set
if (scene.resX<=0) scene.resX=480;
if (scene.resY<=0) scene.resY=320;
cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<<"with "<< scene.antialiase<<"x SSAA to "<<scene.outputFile<<endl;
} else if (firstWord=="#" || firstWord.substr(0,1)=="#"){
cout << line << endl;//just print comment lines
} else if (firstWord == "transform"){
string name, transform;
double X, Y, Z;
RenderObject* object;
ss >> name;
ss >> transform;
auto linkedObject = roMap.find(name);
if (linkedObject == roMap.end()){//check if object can be found
cout << "Error: " << name << " not found!";
} else {
object = linkedObject->second;
if (transform == "scale") {
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->scale(coords);
} else if (transform == "rotate") {
double angle;
ss >> angle;
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->rotate(angle,coords);
} else if (transform == "translate"){
ss >> X;
ss >> Y;
ss >> Z;
glm::vec3 coords(X, Y, Z);
object->translate(coords);
} else {
cout << "Unknown transformation" << endl;
}
}
} else if (firstWord.length()<1){
} else cout << "???:"<<line <<endl;//print unknown lines
}
file.close();
}else cout << "Unable to open file";
//save collected data in scene
scene.materials = mMap;
scene.renderObjects = roMap;
scene.lights = lMap;
return scene;
}<|endoftext|> |
<commit_before>// clang-format off
CppKeySet { 10,
keyNew (PREFIX "key", KEY_END),
keyNew (PREFIX "key/map", KEY_END),
keyNew (PREFIX "key/array", KEY_END),
keyNew (PREFIX "key/array/#0", KEY_END),
keyNew (PREFIX "key/array/#1", KEY_END),
keyNew (PREFIX "key/array/#2/nested", KEY_END),
keyNew (PREFIX "key/array/#2/nested/#0", KEY_END),
keyNew (PREFIX "key/array/#2/nested/#1", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array/#0", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array/key", KEY_END),
keyNew (PREFIX "key/array/#4/array/without/parent/#0", KEY_END),
keyNew (PREFIX "key/array/#4/array/without/parent/#1", KEY_END),
keyNew (PREFIX "key/empty/array", KEY_META, "array", "", KEY_END),
KS_END }
<commit_msg>Directory Value: Update test data<commit_after>// clang-format off
CppKeySet { 10,
keyNew (PREFIX "key", KEY_END),
keyNew (PREFIX "key/map", KEY_END),
keyNew (PREFIX "key/array", KEY_META, "array", "#4", KEY_END),
keyNew (PREFIX "key/array/#0", KEY_END),
keyNew (PREFIX "key/array/#1", KEY_END),
keyNew (PREFIX "key/array/#2/nested", KEY_META, "array", "#1", KEY_END),
keyNew (PREFIX "key/array/#2/nested/#0", KEY_END),
keyNew (PREFIX "key/array/#2/nested/#1", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array/#0", KEY_END),
keyNew (PREFIX "key/array/#3/not/an/array/key", KEY_END),
keyNew (PREFIX "key/array/#4/no/array/#0", KEY_END),
keyNew (PREFIX "key/array/#4/no/array/#1", KEY_END),
keyNew (PREFIX "key/empty/array", KEY_META, "array", "", KEY_END),
KS_END }
<|endoftext|> |
<commit_before>#include "AutoTrace.h"
// ITK
#include "itkAndImageFilter.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkConnectedThresholdImageFilter.h"
#include "itkImage.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
void Trace(const RGBImageType::Pointer image, const itk::CovariantVector<unsigned char, 3>& color, const itk::Index<2>& seed)
{
// Create a color epsilon lower than the user supplied color
int epsilon = 10;
RGBImageType::PixelType lowerColor;
RGBImageType::PixelType upperColor;
for(unsigned int component = 0; component < 3; ++component)
{
lowerColor[component] = std::max(static_cast<int>(color[component]) - epsilon, 0); // Truncate negative values
upperColor[component] = std::min(static_cast<int>(color[component]) + epsilon, 255); // Truncate values above 255
}
std::cout << "Lower color: ";
for(unsigned int i = 0; i < 3; ++i)
{
std::cout << static_cast<int>(lowerColor[i]) << " ";
}
std::cout << std::endl;
std::cout << "Upper color: ";
for(unsigned int i = 0; i < 3; ++i)
{
std::cout << static_cast<int>(upperColor[i]) << " ";
}
std::cout << std::endl;
// Threshold all 3 channels and AND the result
std::vector<ScalarImageType::Pointer> thresholdedChannels(3);
for(unsigned int channel = 0; channel < 3; ++channel)
{
typedef itk::VectorIndexSelectionCastImageFilter<RGBImageType, ScalarImageType> IndexSelectionType;
IndexSelectionType::Pointer indexSelectionFilter = IndexSelectionType::New();
indexSelectionFilter->SetIndex(channel);
indexSelectionFilter->SetInput(image);
indexSelectionFilter->Update();
// Use the color of the selection to threshold the image (looking for similar colors)
typedef itk::BinaryThresholdImageFilter <ScalarImageType, ScalarImageType> BinaryThresholdImageFilterType;
// Color pixels inside the threshold white. Color pixels outside the threshold black.
BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New();
thresholdFilter->SetInput(indexSelectionFilter->GetOutput());
thresholdFilter->SetLowerThreshold(lowerColor[channel]);
thresholdFilter->SetUpperThreshold(upperColor[channel]);
thresholdFilter->SetInsideValue(255); // White
thresholdFilter->SetOutsideValue(0); // Black
thresholdFilter->Update();
thresholdedChannels[channel] = ScalarImageType::New();
DeepCopy<ScalarImageType>(thresholdFilter->GetOutput(), thresholdedChannels[channel]);
}
// Keep only region where all channels passed the threshold test
typedef itk::AndImageFilter <ScalarImageType> AndImageFilterType;
AndImageFilterType::Pointer andFilter1 = AndImageFilterType::New();
andFilter1->SetInput(0, thresholdedChannels[0]);
andFilter1->SetInput(1, thresholdedChannels[1]);
andFilter1->Update();
AndImageFilterType::Pointer andFilter2 = AndImageFilterType::New();
andFilter2->SetInput(0, andFilter1->GetOutput());
andFilter2->SetInput(1, thresholdedChannels[2]);
andFilter2->Update();
ScalarImageType::Pointer thresholdedImage = ScalarImageType::New();
DeepCopy<ScalarImageType>(andFilter2->GetOutput(), thresholdedImage);
WriteImage<ScalarImageType>(thresholdedImage, "Thresholded.png");
// Dilate the image.
typedef itk::BinaryBallStructuringElement<ScalarImageType::PixelType, 2> StructuringElementType;
StructuringElementType structuringElement;
unsigned int radius = 5; // How big of holes we want to connect.
structuringElement.SetRadius(radius);
structuringElement.CreateStructuringElement();
typedef itk::BinaryDilateImageFilter <ScalarImageType, ScalarImageType, StructuringElementType> BinaryDilateImageFilterType;
BinaryDilateImageFilterType::Pointer dilateFilter = BinaryDilateImageFilterType::New();
dilateFilter->SetInput(thresholdedImage);
dilateFilter->SetKernel(structuringElement);
dilateFilter->SetDilateValue(255);
dilateFilter->Update();
ScalarImageType::Pointer dilatedImage = ScalarImageType::New();
DeepCopy<ScalarImageType>(dilateFilter->GetOutput(), dilatedImage);
WriteImage<ScalarImageType>(dilatedImage, "Dilated.png");
// Get pixels that are connected to the selected point.
typedef itk::ConnectedThresholdImageFilter<ScalarImageType, ScalarImageType> ConnectedFilterType;
ConnectedFilterType::Pointer connectedThreshold = ConnectedFilterType::New();
connectedThreshold->SetLower(255);
connectedThreshold->SetUpper(255);
connectedThreshold->SetReplaceValue(255);
connectedThreshold->SetSeed(seed);
connectedThreshold->SetInput(dilatedImage);
connectedThreshold->Update();
WriteImage<ScalarImageType>(connectedThreshold->GetOutput(), "connectedThreshold.png");
}
<commit_msg>Skeletonize the image after the dilation of the thresholded image and before the connectivity search.<commit_after>#include "AutoTrace.h"
// ITK
#include "itkAndImageFilter.h"
#include "itkBinaryBallStructuringElement.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryThinningImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkConnectedThresholdImageFilter.h"
#include "itkImage.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
void Trace(const RGBImageType::Pointer image, const itk::CovariantVector<unsigned char, 3>& color, const itk::Index<2>& seed)
{
// Create a color epsilon lower than the user supplied color
int epsilon = 10;
RGBImageType::PixelType lowerColor;
RGBImageType::PixelType upperColor;
for(unsigned int component = 0; component < 3; ++component)
{
lowerColor[component] = std::max(static_cast<int>(color[component]) - epsilon, 0); // Truncate negative values
upperColor[component] = std::min(static_cast<int>(color[component]) + epsilon, 255); // Truncate values above 255
}
std::cout << "Lower color: ";
for(unsigned int i = 0; i < 3; ++i)
{
std::cout << static_cast<int>(lowerColor[i]) << " ";
}
std::cout << std::endl;
std::cout << "Upper color: ";
for(unsigned int i = 0; i < 3; ++i)
{
std::cout << static_cast<int>(upperColor[i]) << " ";
}
std::cout << std::endl;
// Threshold all 3 channels and AND the result
std::vector<ScalarImageType::Pointer> thresholdedChannels(3);
for(unsigned int channel = 0; channel < 3; ++channel)
{
typedef itk::VectorIndexSelectionCastImageFilter<RGBImageType, ScalarImageType> IndexSelectionType;
IndexSelectionType::Pointer indexSelectionFilter = IndexSelectionType::New();
indexSelectionFilter->SetIndex(channel);
indexSelectionFilter->SetInput(image);
indexSelectionFilter->Update();
// Use the color of the selection to threshold the image (looking for similar colors)
typedef itk::BinaryThresholdImageFilter <ScalarImageType, ScalarImageType> BinaryThresholdImageFilterType;
// Color pixels inside the threshold white. Color pixels outside the threshold black.
BinaryThresholdImageFilterType::Pointer thresholdFilter = BinaryThresholdImageFilterType::New();
thresholdFilter->SetInput(indexSelectionFilter->GetOutput());
thresholdFilter->SetLowerThreshold(lowerColor[channel]);
thresholdFilter->SetUpperThreshold(upperColor[channel]);
thresholdFilter->SetInsideValue(255); // White
thresholdFilter->SetOutsideValue(0); // Black
thresholdFilter->Update();
thresholdedChannels[channel] = ScalarImageType::New();
DeepCopy<ScalarImageType>(thresholdFilter->GetOutput(), thresholdedChannels[channel]);
}
// Keep only region where all channels passed the threshold test
typedef itk::AndImageFilter <ScalarImageType> AndImageFilterType;
AndImageFilterType::Pointer andFilter1 = AndImageFilterType::New();
andFilter1->SetInput(0, thresholdedChannels[0]);
andFilter1->SetInput(1, thresholdedChannels[1]);
andFilter1->Update();
AndImageFilterType::Pointer andFilter2 = AndImageFilterType::New();
andFilter2->SetInput(0, andFilter1->GetOutput());
andFilter2->SetInput(1, thresholdedChannels[2]);
andFilter2->Update();
ScalarImageType::Pointer thresholdedImage = ScalarImageType::New();
DeepCopy<ScalarImageType>(andFilter2->GetOutput(), thresholdedImage);
WriteImage<ScalarImageType>(thresholdedImage, "Thresholded.png");
// Dilate the image.
typedef itk::BinaryBallStructuringElement<ScalarImageType::PixelType, 2> StructuringElementType;
StructuringElementType structuringElement;
unsigned int radius = 5; // How big of holes we want to connect.
structuringElement.SetRadius(radius);
structuringElement.CreateStructuringElement();
typedef itk::BinaryDilateImageFilter <ScalarImageType, ScalarImageType, StructuringElementType> BinaryDilateImageFilterType;
BinaryDilateImageFilterType::Pointer dilateFilter = BinaryDilateImageFilterType::New();
dilateFilter->SetInput(thresholdedImage);
dilateFilter->SetKernel(structuringElement);
dilateFilter->SetDilateValue(255);
dilateFilter->Update();
ScalarImageType::Pointer dilatedImage = ScalarImageType::New();
DeepCopy<ScalarImageType>(dilateFilter->GetOutput(), dilatedImage);
WriteImage<ScalarImageType>(dilatedImage, "Dilated.png");
// Thin/skeletonize the image
typedef itk::BinaryThinningImageFilter <ScalarImageType, ScalarImageType> BinaryThinningImageFilterType;
BinaryThinningImageFilterType::Pointer binaryThinningImageFilter = BinaryThinningImageFilterType::New();
binaryThinningImageFilter->SetInput(dilatedImage);
binaryThinningImageFilter->Update();
// Rescale the output of the thinning filter so that it can be seen (the output is 0 and 1, we want 0 and 255)
typedef itk::RescaleIntensityImageFilter< ScalarImageType, ScalarImageType > RescaleType;
RescaleType::Pointer rescaler = RescaleType::New();
rescaler->SetInput( binaryThinningImageFilter->GetOutput() );
rescaler->SetOutputMinimum(0);
rescaler->SetOutputMaximum(255);
rescaler->Update();
WriteImage<ScalarImageType>(rescaler->GetOutput(), "Thinned.png");
// Get pixels that are connected to the selected point.
typedef itk::ConnectedThresholdImageFilter<ScalarImageType, ScalarImageType> ConnectedFilterType;
ConnectedFilterType::Pointer connectedThreshold = ConnectedFilterType::New();
connectedThreshold->SetLower(255);
connectedThreshold->SetUpper(255);
connectedThreshold->SetReplaceValue(255);
connectedThreshold->SetSeed(seed);
connectedThreshold->SetInput(rescaler->GetOutput());
connectedThreshold->SetConnectivity(ConnectedFilterType::FullConnectivity); // consider 8 neighbors when deciding connectivity
connectedThreshold->Update();
WriteImage<ScalarImageType>(connectedThreshold->GetOutput(), "connectedThreshold.png");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 Stef Busking
// Distributed under the terms of the MIT License.
#include "GLTextureManager.h"
#include <sstream>
#ifndef NDEBUG
#include <iostream>
#endif
#include <cassert>
// ----------------------------------------------------------------------------
GLTextureManager *GLTextureManager::New()
{
if (GLEW_VERSION_1_3)
{
#ifndef NDEBUG
std::cout
<< "GLTextureManager: Using OpenGL 1.3 or higher"
<< std::endl;
#endif
return new GLTextureManager();
}
else if (GLEW_ARB_multitexture)
{
// TODO: add ARB fallback
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: Falling back to ARB (not implemented!)"
<< std::endl;
#endif
return 0;
}
else
{
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: Multitexturing not supported!"
<< std::endl;
#endif
return 0;
}
}
// ----------------------------------------------------------------------------
GLTextureManager::GLTextureManager() : currentProgram(0)
{
// Get maximum number of texture units
// NOTE: this seems to be the right parameter, but I'm not 100% sure...
// GL_MAX_TEXTURE_UNITS is stuck at 4 on nvidia, however
// GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS might be used as well.
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
// Initialize current bindings
currentBinding.resize(maxTextureUnits, 0);
}
// ----------------------------------------------------------------------------
GLTextureManager::~GLTextureManager()
{
// Make sure our textures are no longer bound
Unbind();
// Delete all managed textures
std::map<std::string, GLTexture*>::iterator it = textures.begin();
while (it != textures.end())
{
//const string name = it->first;
GLTexture *tex = it->second;
assert(tex);
++it;
delete tex;
}
}
// ----------------------------------------------------------------------------
// Add a new sampler with the given name and texture, optionally add to store
GLTextureManager::SamplerId GLTextureManager::AddTexture(
const std::string &name, GLTexture *tex, bool takeOwnership)
{
// Do we already have a sampler with this name?
SamplerId sampler = GetSampler(name);
if (sampler == BAD_SAMPLER_ID)
{
// Find an unused SamplerId to register a new sampler
if (!unusedSamplers.empty())
{
sampler = unusedSamplers.front();
unusedSamplers.pop();
}
else
{
// No unused SamplerIds, add a new one
sampler = samplers.size();
samplers.push_back(0);
}
samplersByName[name] = sampler;
}
// If the sampler already has a texture and we own it, delete it
GLTexture *samplerTex = samplers[sampler];
if (samplerTex)
{
GLTexture *oldTex = GetTexture(name);
// TODO: the sampler and store can be different if it was swapped out
//assert(oldTex == samplers[sampler]);
// For now, we DO NOT assume ownership of swapped in textures here;
// the destructor won't either unless the SwapTexture TODO is fixed!
// AddTexture however is a true replace operation, and therefore
// deletes the old texture from the store.
if (oldTex != tex) delete oldTex;
}
// Assign this texture to the sampler
samplers[sampler] = tex;
if (takeOwnership)
{
// Add the texture to the list
textures[name] = tex;
}
return sampler;
}
// ----------------------------------------------------------------------------
// Get the sampler with the given name
GLTextureManager::SamplerId GLTextureManager::GetSampler(
const std::string &name)
{
std::map<std::string, SamplerId>::iterator sit = samplersByName.find(name);
if (sit != samplersByName.end())
{
return sit->second;
}
else
{
return BAD_SAMPLER_ID;
}
}
// ----------------------------------------------------------------------------
// Swap the texture assigned to the given sampler, returns the old texture
GLTexture *GLTextureManager::SwapTexture(SamplerId sampler, GLTexture *tex)
{
assert(sampler >= 0
&& static_cast<unsigned int>(sampler) < samplers.size());
// Replace the texture on this sampler
GLTexture *oldTex = samplers[sampler];
samplers[sampler] = tex;
// TODO: we should replace the stored copy as well (if we own this texture)
// however, this operation should be as fast as possible, and we don't
// know if tex is owned by us without knowing its name (see AddTexture)
return oldTex;
}
// ----------------------------------------------------------------------------
// Unregister the given name as a sampler
void GLTextureManager::RemoveSampler(const std::string &name)
{
// Find the sampler
SamplerId sampler = GetSampler(name);
if (sampler != BAD_SAMPLER_ID)
{
// TODO: invalidate any programs in cache that use this sampler?
unusedSamplers.push(sampler);
samplers[sampler] = 0;
samplersByName.erase(name);
}
}
// ----------------------------------------------------------------------------
// Specify that the given unit is managed elsewhere, but should be registered
// on programs using the given name
bool GLTextureManager::AddReservedSlot(const std::string &name, int unit)
{
assert(0 <= unit && unit < maxTextureUnits);
// Register reserved slot
reserved[name] = unit;
// Is any texture bound here?
if (currentBinding[unit])
{
glActiveTexture(GL_TEXTURE0 + unit);
currentBinding[unit]->UnbindCurrent();
currentBinding[unit] = 0;
glActiveTexture(GL_TEXTURE0);
}
// TODO: some more error checking could be useful (aliasing...)
return true;
}
// ----------------------------------------------------------------------------
// Get a texture from the store
GLTexture *GLTextureManager::GetTexture(const std::string &name)
{
// Do we know this texture?
std::map<std::string, GLTexture*>::iterator texit =
textures.find(name);
if (texit == textures.end()) return 0;
return texit->second;
}
// ----------------------------------------------------------------------------
// Get a texture from the store
const GLTexture *GLTextureManager::GetTexture(const std::string &name) const
{
// Do we know this texture?
std::map<std::string, GLTexture*>::const_iterator texit =
textures.find(name);
if (texit == textures.end()) return 0;
return texit->second;
}
// ----------------------------------------------------------------------------
// Remove and return a texture from the store, or delete a reserved slot
GLTexture *GLTextureManager::RemoveTexture(const std::string &name)
{
// Is this a reserved slot?
std::map<std::string, int>::iterator rit = reserved.find(name);
if (rit != reserved.end())
{
// Remove the reserved slot
reserved.erase(name);
return 0;
}
else
{
GLTexture *tex = GetTexture(name);
// Ignore invalid removals
if (!tex) return 0;
// If this texture is currently bound, unbind it
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
if (currentBinding[unit] == tex)
{
glActiveTexture(GL_TEXTURE0 + unit);
tex->UnbindCurrent();
currentBinding[unit] = 0;
}
}
glActiveTexture(GL_TEXTURE0);
// Remove the texture from the store
textures.erase(name);
return tex;
}
}
// ----------------------------------------------------------------------------
// Delete a texture from the store, or delete a reserved slot
void GLTextureManager::DeleteTexture(const std::string &name)
{
GLTexture *tex = RemoveTexture(name);
if (tex)
{
#ifndef NDEBUG
/*
std::cout
<< "GLTextureManager: Deleting texture '"
<< name << "'" << std::endl;
*/
#endif
delete tex;
}
}
// ----------------------------------------------------------------------------
// Reset all assignments, except reserved slots
void GLTextureManager::BeginNewPass()
{
// Essentially, this means we simply unregister all programs
std::map<GLProgram*, SamplerBindings>::iterator it = bindings.begin();
while (it != bindings.end())
{
GLProgram *prog = it->first;
++it;
UnregisterProgram(prog);
}
currentProgram = 0;
}
// ----------------------------------------------------------------------------
// Bind all textures required by the currently active program
void GLTextureManager::Bind()
{
// Make sure we have a current program
if (!currentProgram) return;
SamplerBindings &binding = bindings[currentProgram];
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
SamplerId samplerId = binding[unit];
// Ignore unused / reserved units
if (samplerId >= 0)
{
// Get the texture
GLTexture *tex = samplers[samplerId];
// This could be NULL due to programmer error
// (removing a sampler without resetting programs that use it)
//assert(tex);
// Check if anything is bound to this unit
GLTexture *oldTex = currentBinding[unit];
if (oldTex == tex) continue;
// Set up texture in OpenGL
glActiveTexture(GL_TEXTURE0 + unit);
if (oldTex) oldTex->UnbindCurrent();
if (tex) tex->BindToCurrent();
// Update current binding
currentBinding[unit] = tex;
}
}
glActiveTexture(GL_TEXTURE0);
}
// ----------------------------------------------------------------------------
// Unbind all currently bound textures
void GLTextureManager::Unbind()
{
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
GLTexture *tex = currentBinding[unit];
if (tex)
{
glActiveTexture(GL_TEXTURE0 + unit);
tex->UnbindCurrent();
currentBinding[unit] = 0;
}
}
glActiveTexture(GL_TEXTURE0);
}
// ----------------------------------------------------------------------------
bool GLTextureManager::SetupProgram(GLProgram *prog, bool updateIfKnown)
{
// Set current program
currentProgram = prog;
bool ok = true;
// Do we know this program?
std::map<GLProgram*, SamplerBindings>::iterator it =
bindings.find(prog);
if (it == bindings.end() || updateIfKnown)
{
// Add new (or get and clear) bindings for this program
SamplerBindings &binding = bindings[prog];
binding.clear();
binding.resize(maxTextureUnits, -1);
// For finding available texture units
unsigned int nextFreeUnit = 0;
std::vector<bool> inUse;
inUse.resize(maxTextureUnits, false);
// Mark all reserved slots
for (std::map<std::string, int>::const_iterator rit =
reserved.begin(); rit != reserved.end(); ++rit)
{
inUse[rit->second] = true;
}
// Get the uniforms required for this program
std::vector<GLUniformInfo> uniforms = prog->GetActiveUniforms();
for (std::vector<GLUniformInfo>::iterator it = uniforms.begin();
it != uniforms.end(); ++it)
{
// Is this a sampler?
if (it->type == GL_SAMPLER_1D
|| it->type == GL_SAMPLER_2D
|| it->type == GL_SAMPLER_3D
|| it->type == GL_SAMPLER_CUBE
|| it->type == GL_SAMPLER_1D_SHADOW
|| it->type == GL_SAMPLER_2D_SHADOW
|| it->type == GL_SAMPLER_2D_RECT_ARB
|| it->type == GL_SAMPLER_2D_RECT_SHADOW_ARB)
{
// Is this a reserved texture unit?
// TODO: how to handle reserved slots in arrays?
std::map<std::string, int>::const_iterator rit =
reserved.find(it->name);
if (rit != reserved.end())
{
// Reserved unit, only set location in program
prog->UseTexture(it->name, rit->second);
}
else
{
// Is this a texture array?
for (int element = 0; element < it->size; ++element)
{
// Build the name for this element
std::string name;
if (it->size > 1)
{
// Some implementations return name[0],
// others just return name...
std::string arrayName = it->name.substr(0,
it->name.find('['));
std::ostringstream elementName;
elementName << arrayName << "[" << element << "]";
name = elementName.str();
}
else
{
name = it->name;
}
// Find the matching SamplerId
SamplerId sampler = GetSampler(name);
// If size == 1 this could be a single-element array
if (it->size == 1 && sampler == BAD_SAMPLER_ID)
{
std::string arrayName = it->name.substr(0,
it->name.find('['));
std::ostringstream elementName;
elementName << arrayName << "[0]";
sampler = GetSampler(elementName.str());
}
if (sampler == BAD_SAMPLER_ID)
{
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: "
<< "Program requires unknown sampler '"
<< name << "'" << std::endl;
#endif
// TODO: we might want to re-check this sampler
// Continue for now, but inform the caller
ok = false;
}
else
{
// Find the next free texture unit
while (nextFreeUnit != maxTextureUnits
&& inUse[nextFreeUnit])
{
++nextFreeUnit;
}
if (nextFreeUnit == maxTextureUnits)
{
// We ran out of texture units!
#ifndef NDEBUG
std::cerr
<< "GLProgram: "
<< "ran out of available texture units!"
<< std::endl;
#endif
return false;
}
// Assign sampler to unit
binding[nextFreeUnit] = sampler;
inUse[nextFreeUnit] = true;
// Pass the unit id to program
prog->UseTexture(name, nextFreeUnit);
}
}
}
}
}
}
return ok;
}
// ----------------------------------------------------------------------------
// Remove bindings for the given program
void GLTextureManager::UnregisterProgram(GLProgram *prog)
{
bindings.erase(prog);
}
<commit_msg>Fixed warning in GLTextureManager::SetupProgram.<commit_after>// Copyright (c) 2009 Stef Busking
// Distributed under the terms of the MIT License.
#include "GLTextureManager.h"
#include <sstream>
#ifndef NDEBUG
#include <iostream>
#endif
#include <cassert>
// ----------------------------------------------------------------------------
GLTextureManager *GLTextureManager::New()
{
if (GLEW_VERSION_1_3)
{
#ifndef NDEBUG
std::cout
<< "GLTextureManager: Using OpenGL 1.3 or higher"
<< std::endl;
#endif
return new GLTextureManager();
}
else if (GLEW_ARB_multitexture)
{
// TODO: add ARB fallback
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: Falling back to ARB (not implemented!)"
<< std::endl;
#endif
return 0;
}
else
{
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: Multitexturing not supported!"
<< std::endl;
#endif
return 0;
}
}
// ----------------------------------------------------------------------------
GLTextureManager::GLTextureManager() : currentProgram(0)
{
// Get maximum number of texture units
// NOTE: this seems to be the right parameter, but I'm not 100% sure...
// GL_MAX_TEXTURE_UNITS is stuck at 4 on nvidia, however
// GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS might be used as well.
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
// Initialize current bindings
currentBinding.resize(maxTextureUnits, 0);
}
// ----------------------------------------------------------------------------
GLTextureManager::~GLTextureManager()
{
// Make sure our textures are no longer bound
Unbind();
// Delete all managed textures
std::map<std::string, GLTexture*>::iterator it = textures.begin();
while (it != textures.end())
{
//const string name = it->first;
GLTexture *tex = it->second;
assert(tex);
++it;
delete tex;
}
}
// ----------------------------------------------------------------------------
// Add a new sampler with the given name and texture, optionally add to store
GLTextureManager::SamplerId GLTextureManager::AddTexture(
const std::string &name, GLTexture *tex, bool takeOwnership)
{
// Do we already have a sampler with this name?
SamplerId sampler = GetSampler(name);
if (sampler == BAD_SAMPLER_ID)
{
// Find an unused SamplerId to register a new sampler
if (!unusedSamplers.empty())
{
sampler = unusedSamplers.front();
unusedSamplers.pop();
}
else
{
// No unused SamplerIds, add a new one
sampler = samplers.size();
samplers.push_back(0);
}
samplersByName[name] = sampler;
}
// If the sampler already has a texture and we own it, delete it
GLTexture *samplerTex = samplers[sampler];
if (samplerTex)
{
GLTexture *oldTex = GetTexture(name);
// TODO: the sampler and store can be different if it was swapped out
//assert(oldTex == samplers[sampler]);
// For now, we DO NOT assume ownership of swapped in textures here;
// the destructor won't either unless the SwapTexture TODO is fixed!
// AddTexture however is a true replace operation, and therefore
// deletes the old texture from the store.
if (oldTex != tex) delete oldTex;
}
// Assign this texture to the sampler
samplers[sampler] = tex;
if (takeOwnership)
{
// Add the texture to the list
textures[name] = tex;
}
return sampler;
}
// ----------------------------------------------------------------------------
// Get the sampler with the given name
GLTextureManager::SamplerId GLTextureManager::GetSampler(
const std::string &name)
{
std::map<std::string, SamplerId>::iterator sit = samplersByName.find(name);
if (sit != samplersByName.end())
{
return sit->second;
}
else
{
return BAD_SAMPLER_ID;
}
}
// ----------------------------------------------------------------------------
// Swap the texture assigned to the given sampler, returns the old texture
GLTexture *GLTextureManager::SwapTexture(SamplerId sampler, GLTexture *tex)
{
assert(sampler >= 0
&& static_cast<unsigned int>(sampler) < samplers.size());
// Replace the texture on this sampler
GLTexture *oldTex = samplers[sampler];
samplers[sampler] = tex;
// TODO: we should replace the stored copy as well (if we own this texture)
// however, this operation should be as fast as possible, and we don't
// know if tex is owned by us without knowing its name (see AddTexture)
return oldTex;
}
// ----------------------------------------------------------------------------
// Unregister the given name as a sampler
void GLTextureManager::RemoveSampler(const std::string &name)
{
// Find the sampler
SamplerId sampler = GetSampler(name);
if (sampler != BAD_SAMPLER_ID)
{
// TODO: invalidate any programs in cache that use this sampler?
unusedSamplers.push(sampler);
samplers[sampler] = 0;
samplersByName.erase(name);
}
}
// ----------------------------------------------------------------------------
// Specify that the given unit is managed elsewhere, but should be registered
// on programs using the given name
bool GLTextureManager::AddReservedSlot(const std::string &name, int unit)
{
assert(0 <= unit && unit < maxTextureUnits);
// Register reserved slot
reserved[name] = unit;
// Is any texture bound here?
if (currentBinding[unit])
{
glActiveTexture(GL_TEXTURE0 + unit);
currentBinding[unit]->UnbindCurrent();
currentBinding[unit] = 0;
glActiveTexture(GL_TEXTURE0);
}
// TODO: some more error checking could be useful (aliasing...)
return true;
}
// ----------------------------------------------------------------------------
// Get a texture from the store
GLTexture *GLTextureManager::GetTexture(const std::string &name)
{
// Do we know this texture?
std::map<std::string, GLTexture*>::iterator texit =
textures.find(name);
if (texit == textures.end()) return 0;
return texit->second;
}
// ----------------------------------------------------------------------------
// Get a texture from the store
const GLTexture *GLTextureManager::GetTexture(const std::string &name) const
{
// Do we know this texture?
std::map<std::string, GLTexture*>::const_iterator texit =
textures.find(name);
if (texit == textures.end()) return 0;
return texit->second;
}
// ----------------------------------------------------------------------------
// Remove and return a texture from the store, or delete a reserved slot
GLTexture *GLTextureManager::RemoveTexture(const std::string &name)
{
// Is this a reserved slot?
std::map<std::string, int>::iterator rit = reserved.find(name);
if (rit != reserved.end())
{
// Remove the reserved slot
reserved.erase(name);
return 0;
}
else
{
GLTexture *tex = GetTexture(name);
// Ignore invalid removals
if (!tex) return 0;
// If this texture is currently bound, unbind it
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
if (currentBinding[unit] == tex)
{
glActiveTexture(GL_TEXTURE0 + unit);
tex->UnbindCurrent();
currentBinding[unit] = 0;
}
}
glActiveTexture(GL_TEXTURE0);
// Remove the texture from the store
textures.erase(name);
return tex;
}
}
// ----------------------------------------------------------------------------
// Delete a texture from the store, or delete a reserved slot
void GLTextureManager::DeleteTexture(const std::string &name)
{
GLTexture *tex = RemoveTexture(name);
if (tex)
{
#ifndef NDEBUG
/*
std::cout
<< "GLTextureManager: Deleting texture '"
<< name << "'" << std::endl;
*/
#endif
delete tex;
}
}
// ----------------------------------------------------------------------------
// Reset all assignments, except reserved slots
void GLTextureManager::BeginNewPass()
{
// Essentially, this means we simply unregister all programs
std::map<GLProgram*, SamplerBindings>::iterator it = bindings.begin();
while (it != bindings.end())
{
GLProgram *prog = it->first;
++it;
UnregisterProgram(prog);
}
currentProgram = 0;
}
// ----------------------------------------------------------------------------
// Bind all textures required by the currently active program
void GLTextureManager::Bind()
{
// Make sure we have a current program
if (!currentProgram) return;
SamplerBindings &binding = bindings[currentProgram];
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
SamplerId samplerId = binding[unit];
// Ignore unused / reserved units
if (samplerId >= 0)
{
// Get the texture
GLTexture *tex = samplers[samplerId];
// This could be NULL due to programmer error
// (removing a sampler without resetting programs that use it)
//assert(tex);
// Check if anything is bound to this unit
GLTexture *oldTex = currentBinding[unit];
if (oldTex == tex) continue;
// Set up texture in OpenGL
glActiveTexture(GL_TEXTURE0 + unit);
if (oldTex) oldTex->UnbindCurrent();
if (tex) tex->BindToCurrent();
// Update current binding
currentBinding[unit] = tex;
}
}
glActiveTexture(GL_TEXTURE0);
}
// ----------------------------------------------------------------------------
// Unbind all currently bound textures
void GLTextureManager::Unbind()
{
for (int unit = 0; unit < maxTextureUnits; ++unit)
{
GLTexture *tex = currentBinding[unit];
if (tex)
{
glActiveTexture(GL_TEXTURE0 + unit);
tex->UnbindCurrent();
currentBinding[unit] = 0;
}
}
glActiveTexture(GL_TEXTURE0);
}
// ----------------------------------------------------------------------------
bool GLTextureManager::SetupProgram(GLProgram *prog, bool updateIfKnown)
{
// Set current program
currentProgram = prog;
bool ok = true;
// Do we know this program?
std::map<GLProgram*, SamplerBindings>::iterator it =
bindings.find(prog);
if (it == bindings.end() || updateIfKnown)
{
// Add new (or get and clear) bindings for this program
SamplerBindings &binding = bindings[prog];
binding.clear();
binding.resize(maxTextureUnits, -1);
// For finding available texture units
int nextFreeUnit = 0;
std::vector<bool> inUse;
inUse.resize(maxTextureUnits, false);
// Mark all reserved slots
for (std::map<std::string, int>::const_iterator rit =
reserved.begin(); rit != reserved.end(); ++rit)
{
inUse[rit->second] = true;
}
// Get the uniforms required for this program
std::vector<GLUniformInfo> uniforms = prog->GetActiveUniforms();
for (std::vector<GLUniformInfo>::iterator it = uniforms.begin();
it != uniforms.end(); ++it)
{
// Is this a sampler?
if (it->type == GL_SAMPLER_1D
|| it->type == GL_SAMPLER_2D
|| it->type == GL_SAMPLER_3D
|| it->type == GL_SAMPLER_CUBE
|| it->type == GL_SAMPLER_1D_SHADOW
|| it->type == GL_SAMPLER_2D_SHADOW
|| it->type == GL_SAMPLER_2D_RECT_ARB
|| it->type == GL_SAMPLER_2D_RECT_SHADOW_ARB)
{
// Is this a reserved texture unit?
// TODO: how to handle reserved slots in arrays?
std::map<std::string, int>::const_iterator rit =
reserved.find(it->name);
if (rit != reserved.end())
{
// Reserved unit, only set location in program
prog->UseTexture(it->name, rit->second);
}
else
{
// Is this a texture array?
for (int element = 0; element < it->size; ++element)
{
// Build the name for this element
std::string name;
if (it->size > 1)
{
// Some implementations return name[0],
// others just return name...
std::string arrayName = it->name.substr(0,
it->name.find('['));
std::ostringstream elementName;
elementName << arrayName << "[" << element << "]";
name = elementName.str();
}
else
{
name = it->name;
}
// Find the matching SamplerId
SamplerId sampler = GetSampler(name);
// If size == 1 this could be a single-element array
if (it->size == 1 && sampler == BAD_SAMPLER_ID)
{
std::string arrayName = it->name.substr(0,
it->name.find('['));
std::ostringstream elementName;
elementName << arrayName << "[0]";
sampler = GetSampler(elementName.str());
}
if (sampler == BAD_SAMPLER_ID)
{
#ifndef NDEBUG
std::cerr
<< "GLTextureManager: "
<< "Program requires unknown sampler '"
<< name << "'" << std::endl;
#endif
// TODO: we might want to re-check this sampler
// Continue for now, but inform the caller
ok = false;
}
else
{
// Find the next free texture unit
while (nextFreeUnit != maxTextureUnits
&& inUse[nextFreeUnit])
{
++nextFreeUnit;
}
if (nextFreeUnit == maxTextureUnits)
{
// We ran out of texture units!
#ifndef NDEBUG
std::cerr
<< "GLProgram: "
<< "ran out of available texture units!"
<< std::endl;
#endif
return false;
}
// Assign sampler to unit
binding[nextFreeUnit] = sampler;
inUse[nextFreeUnit] = true;
// Pass the unit id to program
prog->UseTexture(name, nextFreeUnit);
}
}
}
}
}
}
return ok;
}
// ----------------------------------------------------------------------------
// Remove bindings for the given program
void GLTextureManager::UnregisterProgram(GLProgram *prog)
{
bindings.erase(prog);
}
<|endoftext|> |
<commit_before>#include "plot.h"
#include "curvedata.h"
#include "signaldata.h"
#include <qwt_plot_grid.h>
#include <qwt_plot_layout.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_directpainter.h>
#include <qwt_curve_fitter.h>
#include <qwt_painter.h>
#include <qwt_scale_engine.h>
#include <qwt_scale_draw.h>
#include <qwt_plot_zoomer.h>
#include <qwt_plot_panner.h>
#include <qwt_plot_magnifier.h>
#include <qwt_text.h>
#include <qevent.h>
#include <limits>
#include <cassert>
class MyScaleDraw : public QwtScaleDraw
{
virtual QwtText label(double value) const
{
return QString::number(value, 'f', 2);
}
};
class MyZoomer: public QwtPlotZoomer
{
public:
MyZoomer(QwtPlotCanvas *canvas):
QwtPlotZoomer(canvas)
{
setTrackerMode(AlwaysOn);
}
virtual QwtText trackerTextF(const QPointF &pos) const
{
QColor bg(Qt::white);
bg.setAlpha(200);
QwtText text = QwtPlotZoomer::trackerTextF(pos);
text.setBackgroundBrush( QBrush( bg ));
return text;
}
};
class MyMagnifier: public QwtPlotMagnifier
{
public:
MyMagnifier(QwtPlotCanvas *canvas):
QwtPlotMagnifier(canvas)
{
}
protected:
// Normally, a value < 1.0 zooms in, a value > 1.0 zooms out.
// This function is overloaded to invert the magnification direction.
virtual void rescale( double factor )
{
factor = qAbs( factor );
factor = (1-factor) + 1;
this->QwtPlotMagnifier::rescale(factor);
}
};
Plot::Plot(QWidget *parent):
QwtPlot(parent),
d_interval(0.0, 10.0),
d_timerId(-1)
{
setAutoReplot(false);
// The backing store is important, when working with widget
// overlays ( f.e rubberbands for zooming ).
// Here we don't have them and the internal
// backing store of QWidget is good enough.
canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false);
#if defined(Q_WS_X11)
// Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent
// works on X11. This has a nice effect on the performance.
canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true);
// Disabling the backing store of Qt improves the performance
// for the direct painter even more, but the canvas becomes
// a native window of the window system, receiving paint events
// for resize and expose operations. Those might be expensive
// when there are many points and the backing store of
// the canvas is disabled. So in this application
// we better don't both backing stores.
if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) )
{
canvas()->setAttribute(Qt::WA_PaintOnScreen, true);
canvas()->setAttribute(Qt::WA_NoSystemBackground, true);
}
#endif
initGradient();
plotLayout()->setAlignCanvasToScales(true);
setAxisTitle(QwtPlot::xBottom, "Time [s]");
setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue());
setAxisScale(QwtPlot::yLeft, -4.0, 4.0);
setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw);
QwtPlotGrid *grid = new QwtPlotGrid();
grid->setPen(QPen(Qt::gray, 0.0, Qt::DotLine));
grid->enableX(false);
grid->enableXMin(false);
grid->enableY(true);
grid->enableYMin(false);
grid->attach(this);
d_origin = new QwtPlotMarker();
d_origin->setLineStyle(QwtPlotMarker::HLine);
d_origin->setValue(d_interval.minValue() + d_interval.width() / 2.0, 0.0);
d_origin->setLinePen(QPen(Qt::gray, 0.0, Qt::DashLine));
d_origin->attach(this);
QwtPlotZoomer* zoomer = new MyZoomer(canvas());
zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1,
Qt::LeftButton, Qt::ShiftModifier);
// zoomer->setMousePattern(QwtEventPattern::MouseSelect3,
// Qt::RightButton);
QwtPlotPanner *panner = new QwtPlotPanner(canvas());
//panner->setAxisEnabled(QwtPlot::yRight, false);
panner->setMouseButton(Qt::LeftButton);
// zoom in/out with the wheel
QwtPlotMagnifier* magnifier = new MyMagnifier(canvas());
magnifier->setMouseButton(Qt::MiddleButton);
const QColor c(Qt::darkBlue);
zoomer->setRubberBandPen(c);
zoomer->setTrackerPen(c);
this->setMinimumHeight(200);
}
Plot::~Plot()
{
}
void Plot::addSignal(SignalData* signalData, QColor color)
{
QwtPlotCurve* d_curve = new QwtPlotCurve();
d_curve->setStyle(QwtPlotCurve::Lines);
d_curve->setPen(QPen(color));
#if 1
d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
#endif
#if 1
d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false);
#endif
d_curve->setData(new CurveData(signalData));
d_curve->attach(this);
mSignals[signalData] = d_curve;
}
void Plot::removeSignal(SignalData* signalData)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
curve->detach();
delete curve;
mSignals.remove(signalData);
}
void Plot::setSignalVisible(SignalData* signalData, bool visible)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
if (visible)
{
curve->attach(this);
}
else
{
curve->detach();
}
}
void Plot::setSignalColor(SignalData* signalData, QColor color)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
curve->setPen(QPen(color));
}
void Plot::initGradient()
{
QPalette pal = canvas()->palette();
#if QT_VERSION >= 0x040400
QLinearGradient gradient( 0.0, 0.0, 1.0, 0.0 );
gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
//gradient.setColorAt(0.0, QColor( 0, 49, 110 ) );
//gradient.setColorAt(1.0, QColor( 0, 87, 174 ) );
gradient.setColorAt(0.0, QColor( 255, 255, 255 ) );
gradient.setColorAt(1.0, QColor( 255, 255, 255 ) );
pal.setBrush(QPalette::Window, QBrush(gradient));
#else
pal.setBrush(QPalette::Window, QBrush( color ));
#endif
canvas()->setPalette(pal);
}
void Plot::start()
{
d_timerId = startTimer(33);
}
void Plot::stop()
{
killTimer(d_timerId);
}
void Plot::replot()
{
// Lock the signal data objects, then plot the data and unlock.
QList<SignalData*> signalDataList = mSignals.keys();
foreach (SignalData* signalData, signalDataList)
{
signalData->lock();
}
QwtPlot::replot();
foreach (SignalData* signalData, signalDataList)
{
signalData->unlock();
}
}
double Plot::timeWindow()
{
return d_interval.width();
}
void Plot::setTimeWindow(double interval)
{
if ( interval > 0.0 && interval != d_interval.width() )
{
d_interval.setMinValue(d_interval.maxValue() - interval);
}
}
void Plot::setYScale(double scale)
{
setAxisScale(QwtPlot::yLeft, -scale, scale);
}
void Plot::timerEvent(QTimerEvent *event)
{
if ( event->timerId() == d_timerId )
{
if (!mSignals.size())
{
return;
}
float maxTime = std::numeric_limits<float>::min();
QList<SignalData*> signalDataList = mSignals.keys();
foreach (SignalData* signalData, signalDataList)
{
signalData->updateValues();
if (signalData->size())
{
float signalMaxTime = signalData->value(signalData->size() - 1).x();
if (signalMaxTime > maxTime)
{
maxTime = signalMaxTime;
}
}
}
if (maxTime != std::numeric_limits<float>::min())
{
d_interval = QwtInterval(maxTime - d_interval.width(), maxTime);
setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue());
QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom);
//engine->setAttribute(QwtScaleEngine::Floating, true);
//engine->setMargins(0,50.0);
QwtScaleDiv scaleDiv = engine->divideScale(d_interval.minValue(), d_interval.maxValue(), 0, 0);
QList<double> majorTicks;
double majorStep = scaleDiv.range() / 5.0;
for (int i = 0; i <= 5; ++i)
{
majorTicks << scaleDiv.lowerBound() + i*majorStep;
}
majorTicks.back() = scaleDiv.upperBound();
QList<double> minorTicks;
double minorStep = scaleDiv.range() / 25.0;
for (int i = 0; i <= 25; ++i)
{
minorTicks << scaleDiv.lowerBound() + i*minorStep;
}
minorTicks.back() = scaleDiv.upperBound();
scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks);
scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks);
setAxisScaleDiv(QwtPlot::xBottom, scaleDiv);
/*
QwtScaleDiv scaleDiv;// = *axisScaleDiv(QwtPlot::xBottom);
scaleDiv.setInterval(d_interval);
QList<double> majorTicks;
majorTicks << d_interval.minValue() << d_interval.maxValue();
scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks);
setAxisScaleDiv(QwtPlot::xBottom, scaleDiv);
*/
//printf("update x axis interval: [%f, %f]\n", d_interval.minValue(), d_interval.maxValue());
}
this->replot();
}
QwtPlot::timerEvent(event);
}
<commit_msg>signal_scope: replot after changing signal visibility<commit_after>#include "plot.h"
#include "curvedata.h"
#include "signaldata.h"
#include <qwt_plot_grid.h>
#include <qwt_plot_layout.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_directpainter.h>
#include <qwt_curve_fitter.h>
#include <qwt_painter.h>
#include <qwt_scale_engine.h>
#include <qwt_scale_draw.h>
#include <qwt_plot_zoomer.h>
#include <qwt_plot_panner.h>
#include <qwt_plot_magnifier.h>
#include <qwt_text.h>
#include <qevent.h>
#include <limits>
#include <cassert>
class MyScaleDraw : public QwtScaleDraw
{
virtual QwtText label(double value) const
{
return QString::number(value, 'f', 2);
}
};
class MyZoomer: public QwtPlotZoomer
{
public:
MyZoomer(QwtPlotCanvas *canvas):
QwtPlotZoomer(canvas)
{
setTrackerMode(AlwaysOn);
}
virtual QwtText trackerTextF(const QPointF &pos) const
{
QColor bg(Qt::white);
bg.setAlpha(200);
QwtText text = QwtPlotZoomer::trackerTextF(pos);
text.setBackgroundBrush( QBrush( bg ));
return text;
}
};
class MyMagnifier: public QwtPlotMagnifier
{
public:
MyMagnifier(QwtPlotCanvas *canvas):
QwtPlotMagnifier(canvas)
{
}
protected:
// Normally, a value < 1.0 zooms in, a value > 1.0 zooms out.
// This function is overloaded to invert the magnification direction.
virtual void rescale( double factor )
{
factor = qAbs( factor );
factor = (1-factor) + 1;
this->QwtPlotMagnifier::rescale(factor);
}
};
Plot::Plot(QWidget *parent):
QwtPlot(parent),
d_interval(0.0, 10.0),
d_timerId(-1)
{
setAutoReplot(false);
// The backing store is important, when working with widget
// overlays ( f.e rubberbands for zooming ).
// Here we don't have them and the internal
// backing store of QWidget is good enough.
canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false);
#if defined(Q_WS_X11)
// Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent
// works on X11. This has a nice effect on the performance.
canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true);
// Disabling the backing store of Qt improves the performance
// for the direct painter even more, but the canvas becomes
// a native window of the window system, receiving paint events
// for resize and expose operations. Those might be expensive
// when there are many points and the backing store of
// the canvas is disabled. So in this application
// we better don't both backing stores.
if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) )
{
canvas()->setAttribute(Qt::WA_PaintOnScreen, true);
canvas()->setAttribute(Qt::WA_NoSystemBackground, true);
}
#endif
initGradient();
plotLayout()->setAlignCanvasToScales(true);
setAxisTitle(QwtPlot::xBottom, "Time [s]");
setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue());
setAxisScale(QwtPlot::yLeft, -4.0, 4.0);
setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw);
QwtPlotGrid *grid = new QwtPlotGrid();
grid->setPen(QPen(Qt::gray, 0.0, Qt::DotLine));
grid->enableX(false);
grid->enableXMin(false);
grid->enableY(true);
grid->enableYMin(false);
grid->attach(this);
d_origin = new QwtPlotMarker();
d_origin->setLineStyle(QwtPlotMarker::HLine);
d_origin->setValue(d_interval.minValue() + d_interval.width() / 2.0, 0.0);
d_origin->setLinePen(QPen(Qt::gray, 0.0, Qt::DashLine));
d_origin->attach(this);
QwtPlotZoomer* zoomer = new MyZoomer(canvas());
zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1,
Qt::LeftButton, Qt::ShiftModifier);
// zoomer->setMousePattern(QwtEventPattern::MouseSelect3,
// Qt::RightButton);
QwtPlotPanner *panner = new QwtPlotPanner(canvas());
//panner->setAxisEnabled(QwtPlot::yRight, false);
panner->setMouseButton(Qt::LeftButton);
// zoom in/out with the wheel
QwtPlotMagnifier* magnifier = new MyMagnifier(canvas());
magnifier->setMouseButton(Qt::MiddleButton);
const QColor c(Qt::darkBlue);
zoomer->setRubberBandPen(c);
zoomer->setTrackerPen(c);
this->setMinimumHeight(200);
}
Plot::~Plot()
{
}
void Plot::addSignal(SignalData* signalData, QColor color)
{
QwtPlotCurve* d_curve = new QwtPlotCurve();
d_curve->setStyle(QwtPlotCurve::Lines);
d_curve->setPen(QPen(color));
#if 1
d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
#endif
#if 1
d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false);
#endif
d_curve->setData(new CurveData(signalData));
d_curve->attach(this);
mSignals[signalData] = d_curve;
}
void Plot::removeSignal(SignalData* signalData)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
curve->detach();
delete curve;
mSignals.remove(signalData);
}
void Plot::setSignalVisible(SignalData* signalData, bool visible)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
if (visible)
{
curve->attach(this);
}
else
{
curve->detach();
}
this->replot();
}
void Plot::setSignalColor(SignalData* signalData, QColor color)
{
if (!signalData)
{
return;
}
QwtPlotCurve* curve = mSignals.value(signalData);
assert(curve);
curve->setPen(QPen(color));
}
void Plot::initGradient()
{
QPalette pal = canvas()->palette();
#if QT_VERSION >= 0x040400
QLinearGradient gradient( 0.0, 0.0, 1.0, 0.0 );
gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
//gradient.setColorAt(0.0, QColor( 0, 49, 110 ) );
//gradient.setColorAt(1.0, QColor( 0, 87, 174 ) );
gradient.setColorAt(0.0, QColor( 255, 255, 255 ) );
gradient.setColorAt(1.0, QColor( 255, 255, 255 ) );
pal.setBrush(QPalette::Window, QBrush(gradient));
#else
pal.setBrush(QPalette::Window, QBrush( color ));
#endif
canvas()->setPalette(pal);
}
void Plot::start()
{
d_timerId = startTimer(33);
}
void Plot::stop()
{
killTimer(d_timerId);
}
void Plot::replot()
{
// Lock the signal data objects, then plot the data and unlock.
QList<SignalData*> signalDataList = mSignals.keys();
foreach (SignalData* signalData, signalDataList)
{
signalData->lock();
}
QwtPlot::replot();
foreach (SignalData* signalData, signalDataList)
{
signalData->unlock();
}
}
double Plot::timeWindow()
{
return d_interval.width();
}
void Plot::setTimeWindow(double interval)
{
if ( interval > 0.0 && interval != d_interval.width() )
{
d_interval.setMinValue(d_interval.maxValue() - interval);
}
}
void Plot::setYScale(double scale)
{
setAxisScale(QwtPlot::yLeft, -scale, scale);
}
void Plot::timerEvent(QTimerEvent *event)
{
if ( event->timerId() == d_timerId )
{
if (!mSignals.size())
{
return;
}
float maxTime = std::numeric_limits<float>::min();
QList<SignalData*> signalDataList = mSignals.keys();
foreach (SignalData* signalData, signalDataList)
{
signalData->updateValues();
if (signalData->size())
{
float signalMaxTime = signalData->value(signalData->size() - 1).x();
if (signalMaxTime > maxTime)
{
maxTime = signalMaxTime;
}
}
}
if (maxTime != std::numeric_limits<float>::min())
{
d_interval = QwtInterval(maxTime - d_interval.width(), maxTime);
setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue());
QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom);
//engine->setAttribute(QwtScaleEngine::Floating, true);
//engine->setMargins(0,50.0);
QwtScaleDiv scaleDiv = engine->divideScale(d_interval.minValue(), d_interval.maxValue(), 0, 0);
QList<double> majorTicks;
double majorStep = scaleDiv.range() / 5.0;
for (int i = 0; i <= 5; ++i)
{
majorTicks << scaleDiv.lowerBound() + i*majorStep;
}
majorTicks.back() = scaleDiv.upperBound();
QList<double> minorTicks;
double minorStep = scaleDiv.range() / 25.0;
for (int i = 0; i <= 25; ++i)
{
minorTicks << scaleDiv.lowerBound() + i*minorStep;
}
minorTicks.back() = scaleDiv.upperBound();
scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks);
scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks);
setAxisScaleDiv(QwtPlot::xBottom, scaleDiv);
/*
QwtScaleDiv scaleDiv;// = *axisScaleDiv(QwtPlot::xBottom);
scaleDiv.setInterval(d_interval);
QList<double> majorTicks;
majorTicks << d_interval.minValue() << d_interval.maxValue();
scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks);
setAxisScaleDiv(QwtPlot::xBottom, scaleDiv);
*/
//printf("update x axis interval: [%f, %f]\n", d_interval.minValue(), d_interval.maxValue());
}
this->replot();
}
QwtPlot::timerEvent(event);
}
<|endoftext|> |
<commit_before>#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "automata.h"
DFA dfa;
NDFA ndfa;
set<string> tokens, final;
struct enumstate {
string name;
enumstate() { name = string(); incremento(); }
string& operator++() { incremento(); return name; }
string operator++(int) { string tmp(name); incremento(); return tmp; }
void incremento() {
int i;
do {
for (i = 0; i < (int) name.length(); i++)
if (name[i] < 'Z') { name[i]++; break; }
else name[i] = 'A';
if (i == (int) name.length()) name.append("A");
}
while (!name.compare(S) || !name.compare(X) ||
ndfa.find(name) != ndfa.end());
}
};
void debugprint() {
for (NDFA::iterator src = ndfa.begin(); src != ndfa.end(); src++) {
printf("%s ", (src -> first).c_str());
for (ntransition::iterator tgt = (src -> second).begin(); tgt != (src -> second).end(); tgt++)
for (int i = 0; i < (int) (tgt -> second).size(); i++)
printf("(%c, %s)", tgt -> first, (tgt -> second)[i].c_str());
printf("\n");
}
}
void debugd() {
for (DFA::iterator src = dfa.begin(); src != dfa.end(); src++) {
printf("%s ", (src -> first).c_str());
for (dtransition::iterator tgt = (src -> second).begin(); tgt != (src -> second).end(); tgt++)
printf("(%c, %s)", tgt -> first, (tgt -> second).c_str());
printf("\n");
}
}
int readgrammar() {
int i, top;
string src, tgt;
enumstate state;
map<string, string> states;
char s[MAX], word[MAX], flag, term;
states[S] = S; states[X] = X;
while (fgets(s, MAX, stdin) != NULL && strlen(s) > 1) {
s[strlen(s) - 1] = '|';
for (top = i = 0; s[i] != ':'; i++) {
if (s[i] == '<' || s[i] == '>' || s[i] == ' ') continue;
word[top++] = s[i];
}
word[top] = '\0';
// for (j = i + 1; word[j] != '='; j++);
// if (j - i != 2) return 0;
// i = j + 1;
i += 2;
src = string(word);
printf("%s ::= ", states[src].c_str());
if (states.find(src) == states.end()) states[src] = state++;
while (s[++i] != '\0') {
for (top = flag = 0; s[i] != '|'; i++) {
if (s[i] == ' ') continue;
if (s[i] == '<') flag = 1;
else if (s[i] == '>') flag = 0;
else if (!flag) term = s[i];
else word[top++] = s[i];
}
word[top] = '\0';
tgt = string(word);
if (states.find(tgt) == states.end()) states[tgt] = state++;
ndfa[states[src]][term].push_back(states[tgt]);
printf("%c%s%s", term, states[tgt].c_str(), s[i + 1] == '\0' ? "\n" : " | ");
}
printf("\n");
}
src = states[""]; final.insert(src); //scr is a final state
printf("final state: %s\n", src.c_str());
for (i = 33; i < 127; i++)
ndfa[src][(char) i].push_back(X);
return 1;
}
int readtokens(int N) {
int i;
char word[MAX];
enumstate current;
while (N--) {
if (fgets(word, MAX, stdin) == NULL || word[0] == '\n') return 0;
word[strlen(word) - 1] = '\0';
// map.insert().second returns true or false if
// successfully inserted that key or it was
// already there (and thus did nothing), respectively
if (!tokens.insert(string(word)).second) continue;
printf("%s\n", word);
ndfa[S][word[0]].push_back(current.name);
for (i = 1; word[i] != '\0'; i++)
ndfa[current++][word[i]].push_back(current.name);
printf("readtokens X: %s\n", current.name.c_str());
for (i = 33; i < 127; i++)
ndfa[current.name][(char) i].push_back(X);
final.insert(current.name);
current++;
}
return 1;
}
void debugf() {
printf("\n\nEstados finais:\n");
for (set<string>::iterator i = final.begin(); i != final.end(); i++)
printf("%s\n", i -> c_str());
}
void makedet() {
int i, j, k;
set<string> done;
vector<string> states;
states.push_back("S|"); done.insert("S|");
for (i = 0; i < (int) states.size(); i++) {
j = 0;
string src;
vector< set<string> > trans(312);
while (j < (int) states[i].length()) {
k = j;
// searching for the first '|' in order to
// find the 'src' state to look at its transitions
// 'j' stops 1 position after that '|'
while (states[i][j++] != '|');
src = states[i].substr(k, j - k - 1);
if (final.find(src) != final.end()) continue;
for (ntransition::iterator t = ndfa[src].begin(); t != ndfa[src].end(); t++) {
string tgt;
for (k = 0; k < (int) (t -> second).size(); k++)
tgt.append((t -> second)[k]).append("|");
trans[(int) t -> first].insert(tgt);
}
}
for (j = 0; j < 312; j++) {
string tr;
if (trans[j].size() == 0) continue;
for (set<string>::iterator s = trans[j].begin(); s != trans[j].end(); s++)
tr.append(*s);
dfa[states[i]][(char) j] = tr;
if (done.find(tr) == done.end()) {
states.push_back(tr);
done.insert(tr);
}
}
}
// for (auto fs: final) {
// for (set<string>::iterator fs = final.begin(); fs != final.end(); fs++) {
// printf("+++++++++++++++= %s\n", fs -> c_str());
// for (auto s: dfa) {
// printf("%s\n", s.first.c_str());
// }
// }
}
int minimize(string u) {
int i; bool flag = false, tmp;
for (i = 33; i < 127; i++, flag |= !tmp)
if ((tmp = !minimize(dfa[u][(char) i]))) dfa[u][(char) i] = X;
if (final.find(u) != final.end() || flag) return 1;
dfa.erase(u);
return 0;
}
<commit_msg>Now updating final states after determinization<commit_after>#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "automata.h"
DFA dfa;
NDFA ndfa;
set<string> tokens, final;
struct enumstate {
string name;
enumstate() { name = string(); incremento(); }
string& operator++() { incremento(); return name; }
string operator++(int) { string tmp(name); incremento(); return tmp; }
void incremento() {
int i;
do {
for (i = 0; i < (int) name.length(); i++)
if (name[i] < 'Z') { name[i]++; break; }
else name[i] = 'A';
if (i == (int) name.length()) name.append("A");
}
while (!name.compare(S) || !name.compare(X) ||
ndfa.find(name) != ndfa.end());
}
};
void debugprint() {
for (NDFA::iterator src = ndfa.begin(); src != ndfa.end(); src++) {
printf("%s ", (src -> first).c_str());
for (ntransition::iterator tgt = (src -> second).begin(); tgt != (src -> second).end(); tgt++)
for (int i = 0; i < (int) (tgt -> second).size(); i++)
printf("(%c, %s)", tgt -> first, (tgt -> second)[i].c_str());
printf("\n");
}
}
void debugd() {
for (DFA::iterator src = dfa.begin(); src != dfa.end(); src++) {
printf("%s ", (src -> first).c_str());
for (dtransition::iterator tgt = (src -> second).begin(); tgt != (src -> second).end(); tgt++)
printf("(%c, %s)", tgt -> first, (tgt -> second).c_str());
printf("\n");
}
}
int readgrammar() {
int i, top;
string src, tgt;
enumstate state;
map<string, string> states;
char s[MAX], word[MAX], flag, term;
states[S] = S; states[X] = X;
while (fgets(s, MAX, stdin) != NULL && strlen(s) > 1) {
s[strlen(s) - 1] = '|';
for (top = i = 0; s[i] != ':'; i++) {
if (s[i] == '<' || s[i] == '>' || s[i] == ' ') continue;
word[top++] = s[i];
}
word[top] = '\0';
// for (j = i + 1; word[j] != '='; j++);
// if (j - i != 2) return 0;
// i = j + 1;
i += 2;
src = string(word);
printf("%s ::= ", states[src].c_str());
if (states.find(src) == states.end()) states[src] = state++;
while (s[++i] != '\0') {
for (top = flag = 0; s[i] != '|'; i++) {
if (s[i] == ' ') continue;
if (s[i] == '<') flag = 1;
else if (s[i] == '>') flag = 0;
else if (!flag) term = s[i];
else word[top++] = s[i];
}
word[top] = '\0';
tgt = string(word);
if (states.find(tgt) == states.end()) states[tgt] = state++;
ndfa[states[src]][term].push_back(states[tgt]);
printf("%c%s%s", term, states[tgt].c_str(), s[i + 1] == '\0' ? "\n" : " | ");
}
printf("\n");
}
src = states[""]; final.insert(src); //scr is a final state
printf("final state: %s\n", src.c_str());
for (i = 33; i < 127; i++)
ndfa[src][(char) i].push_back(X);
return 1;
}
int readtokens(int N) {
int i;
char word[MAX];
enumstate current;
while (N--) {
if (fgets(word, MAX, stdin) == NULL || word[0] == '\n') return 0;
word[strlen(word) - 1] = '\0';
// map.insert().second returns true or false if
// successfully inserted that key or it was
// already there (and thus did nothing), respectively
if (!tokens.insert(string(word)).second) continue;
printf("%s\n", word);
ndfa[S][word[0]].push_back(current.name);
for (i = 1; word[i] != '\0'; i++)
ndfa[current++][word[i]].push_back(current.name);
printf("readtokens X: %s\n", current.name.c_str());
for (i = 33; i < 127; i++)
ndfa[current.name][(char) i].push_back(X);
final.insert(current.name);
current++;
}
return 1;
}
void debugf() {
printf("\n\nEstados finais:\n");
for (set<string>::iterator i = final.begin(); i != final.end(); i++)
printf("%s\n", i -> c_str());
}
void makedet() {
int i, j, k;
set<string> done;
vector<string> states;
states.push_back("S|"); done.insert("S|");
for (i = 0; i < (int) states.size(); i++) {
j = 0;
string src;
vector< set<string> > trans(312);
while (j < (int) states[i].length()) {
k = j;
// searching for the first '|' in order to
// find the 'src' state to look at its transitions
// 'j' stops 1 position after that '|'
while (states[i][j++] != '|');
src = states[i].substr(k, j - k - 1);
if (final.find(src) != final.end()) continue;
for (ntransition::iterator t = ndfa[src].begin(); t != ndfa[src].end(); t++) {
string tgt;
for (k = 0; k < (int) (t -> second).size(); k++)
tgt.append((t -> second)[k]).append("|");
trans[(int) t -> first].insert(tgt);
}
}
for (j = 0; j < 312; j++) {
string tr;
if (trans[j].size() == 0) continue;
for (set<string>::iterator s = trans[j].begin(); s != trans[j].end(); s++)
tr.append(*s);
dfa[states[i]][(char) j] = tr;
if (done.find(tr) == done.end()) {
states.push_back(tr);
done.insert(tr);
}
}
}
done.clear();
for (auto fs: final) {
for (auto s: dfa)
if (s.first.find(fs))
done.insert(s.first);
final.erase(fs);
}
for (auto s: done) final.insert(s);
}
int minimize(string u) {
int i;
bool flag = false, tmp;
for (i = 33; i < 127; i++, flag |= !tmp)
if ((tmp = !minimize(dfa[u][(char) i]))) dfa[u][(char) i] = X;
if (final.find(u) != final.end() || flag) return 1;
dfa.erase(u);
return 0;
}
<|endoftext|> |
<commit_before>/*
* File: SDFLoader.cpp
* Author: Benedikt Vogler
*
* Created on 8. Juli 2014, 18:52
*/
#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
using namespace std;
SDFLoader::SDFLoader() {
}
SDFLoader::SDFLoader(const SDFLoader& orig) {
}
SDFLoader::~SDFLoader() {
}
/**
* Loads a scene file and reacts to the commands in it
* @param scenefile the string to the file
* @return
*/
Scene SDFLoader::load(std::string const& scenefile) {
cout << "Loading file: " << scenefile << endl;
Scene scene = Scene();
std::map<std::string, Material> mMap;
std::map<std::string, LightPoint> lMap;
std::map<std::string, RenderObject*> roMap;
string line;
ifstream file(scenefile);
stringstream ss;
//file.open(scenefile, ios::in);
if (file.is_open()) {
while (getline (file,line)){//get line
ss = stringstream(line);//fill the line into stringstream
string tmpString;
ss >> tmpString;
//is first string define?
if (tmpString=="define"){
cout << "defininig: ";
ss >> tmpString;
if (tmpString=="material"){
cout << "a material: "<<endl;
//extract name
string name;
ss>>name;
//extract color
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color ca(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cd(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cs(red, green, blue);
float m;
ss >> m;
Material mat(ca, cd, cs,m, name);
cout << "Material specs: "<<endl<<mat;
mMap[name]=mat;
} else if (tmpString=="camera"){
string cameraname;
ss >> cameraname;
int fovX;
ss >> fovX;
scene.camera = Camera(cameraname,fovX);
cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;
} else if (tmpString=="light"){
string type;
ss>>type;
if (type=="diffuse") {
string name;
ss >> name;
glm::vec3 pos;
ss >> pos.x;
ss >> pos.y;
ss >> pos.z;
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color diff(red, green, blue);
LightPoint light = LightPoint(name, pos, diff);
cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
lMap[name] = light;
}else if (type=="ambient") {
string lightname;
ss >> lightname;//name get's ignored
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color amb(red, green, blue);
scene.amb = amb;
cout << "ambient light "<<amb<<endl;
} else {
cout << "type not supported yet."<<endl;
}
} else if (tmpString=="shape"){
string classname;
ss >> classname;
cout << "Shape \""<< classname << "\"."<<endl;
transform(classname.begin(), classname.end(),classname.begin(), ::toupper);
string name;
ss >> name;
RenderObject* rObject = nullptr;
if (classname=="BOX"){
int edge1x, edge1y, edge1z;
ss>> edge1x;
ss>> edge1y;
ss>> edge1z;
int edge2x, edge2y, edge2z;
ss>> edge2x;
ss>> edge2y;
ss>> edge2z;
string materialString;
ss>>materialString;
Material material = mMap[materialString];
rObject = new Box(
name,
glm::vec3(edge1x, edge1y, edge1z),
glm::vec3(edge2x, edge2y, edge2z),
material
);
}else if (classname=="SPHERE") {
int posX, posY, posZ;
ss>> posX;
ss>> posY;
ss>> posZ;
float radius;
ss>>radius;
string materialString;
ss>>materialString;
Material material = mMap[materialString];
rObject = new Sphere(
name,
glm::vec3(posX, posY, posZ),
radius,
material
);
}else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;
if (rObject != nullptr)
roMap[name] = rObject;
} else
cout << "object to define not implemented:"<<ss.str() <<endl;
} else if (tmpString=="render"){
ss >> scene.camname;
ss >> scene.outputFile;
ss >> scene.resX;
ss >> scene.resY;
//set default if not set
if (scene.resX<=0) scene.resX=100;
if (scene.resY<=0) scene.resY=100;
cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<< " to "<<scene.outputFile<<endl;
} else if (tmpString=="#"){
cout << line << endl;//just print comment lines
} else
cout << "Line not supported:"<<line <<endl;
}
file.close();
}else cout << "Unable to open file";
//save collected data in scene
scene.materials = mMap;
scene.renderObjects = roMap;
scene.lights = lMap;
return scene;
}<commit_msg>changed default size<commit_after>/*
* File: SDFLoader.cpp
* Author: Benedikt Vogler
*
* Created on 8. Juli 2014, 18:52
*/
#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
using namespace std;
SDFLoader::SDFLoader() {
}
SDFLoader::SDFLoader(const SDFLoader& orig) {
}
SDFLoader::~SDFLoader() {
}
/**
* Loads a scene file and reacts to the commands in it
* @param scenefile the string to the file
* @return
*/
Scene SDFLoader::load(std::string const& scenefile) {
cout << "Loading file: " << scenefile << endl;
Scene scene = Scene();
std::map<std::string, Material> mMap;
std::map<std::string, LightPoint> lMap;
std::map<std::string, RenderObject*> roMap;
string line;
ifstream file(scenefile);
stringstream ss;
//file.open(scenefile, ios::in);
if (file.is_open()) {
while (getline (file,line)){//get line
ss = stringstream(line);//fill the line into stringstream
string tmpString;
ss >> tmpString;
//is first string define?
if (tmpString=="define"){
cout << "defininig: ";
ss >> tmpString;
if (tmpString=="material"){
cout << "a material: "<<endl;
//extract name
string name;
ss>>name;
//extract color
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color ca(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cd(red, green, blue);
ss >> red;
ss >> green;
ss >> blue;
Color cs(red, green, blue);
float m;
ss >> m;
Material mat(ca, cd, cs,m, name);
cout << "Material specs: "<<endl<<mat;
mMap[name]=mat;
} else if (tmpString=="camera"){
string cameraname;
ss >> cameraname;
int fovX;
ss >> fovX;
scene.camera = Camera(cameraname,fovX);
cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;
} else if (tmpString=="light"){
string type;
ss>>type;
if (type=="diffuse") {
string name;
ss >> name;
glm::vec3 pos;
ss >> pos.x;
ss >> pos.y;
ss >> pos.z;
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color diff(red, green, blue);
LightPoint light = LightPoint(name, pos, diff);
cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
lMap[name] = light;
}else if (type=="ambient") {
string lightname;
ss >> lightname;//name get's ignored
float red, green, blue;
ss >> red;
ss >> green;
ss >> blue;
Color amb(red, green, blue);
scene.amb = amb;
cout << "ambient light "<<amb<<endl;
} else {
cout << "type not supported yet."<<endl;
}
} else if (tmpString=="shape"){
string classname;
ss >> classname;
cout << "Shape \""<< classname << "\"."<<endl;
transform(classname.begin(), classname.end(),classname.begin(), ::toupper);
string name;
ss >> name;
RenderObject* rObject = nullptr;
if (classname=="BOX"){
int edge1x, edge1y, edge1z;
ss>> edge1x;
ss>> edge1y;
ss>> edge1z;
int edge2x, edge2y, edge2z;
ss>> edge2x;
ss>> edge2y;
ss>> edge2z;
string materialString;
ss>>materialString;
Material material = mMap[materialString];
rObject = new Box(
name,
glm::vec3(edge1x, edge1y, edge1z),
glm::vec3(edge2x, edge2y, edge2z),
material
);
}else if (classname=="SPHERE") {
int posX, posY, posZ;
ss>> posX;
ss>> posY;
ss>> posZ;
float radius;
ss>>radius;
string materialString;
ss>>materialString;
Material material = mMap[materialString];
rObject = new Sphere(
name,
glm::vec3(posX, posY, posZ),
radius,
material
);
}else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;
if (rObject != nullptr)
roMap[name] = rObject;
} else
cout << "object to define not implemented:"<<ss.str() <<endl;
} else if (tmpString=="render"){
ss >> scene.camname;
ss >> scene.outputFile;
ss >> scene.resX;
ss >> scene.resY;
//set default if not set
if (scene.resX<=0) scene.resX=480;
if (scene.resY<=0) scene.resY=320;
cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<< " to "<<scene.outputFile<<endl;
} else if (tmpString=="#"){
cout << line << endl;//just print comment lines
} else
cout << "Line not supported:"<<line <<endl;
}
file.close();
}else cout << "Unable to open file";
//save collected data in scene
scene.materials = mMap;
scene.renderObjects = roMap;
scene.lights = lMap;
return scene;
}<|endoftext|> |
<commit_before>#include "Game.hpp"
Game::Game()
{
}
Game::~Game()
{
Destroy();
}
bool Game::Initialize(Score * score)
{
scoreHandler = score;
enemyDirection = true;
finished = false;
victory = false;
return true;
}
bool Game::Destroy()
{
player.Shutdown();
enemies.clear();
walls.clear();
bullets.clear();
return true;
}
int Game::RenderGame(sf::RenderWindow * window, const sf::Time &frameTime)
{
FinishGameCheck(window, frameTime);
if (!finished)
{
//InputCheck(frameTime.asSeconds());
for (int i = 0; i < bullets.size(); ++i)
{
if (bullets.at(i).IsAlive())
{
if (bullets.at(i).GetPosY() < -1)
{
bullets.at(i).Kill();
continue;
}
if (CheckCollision(bullets.at(i), player))
{
player.Kill();
}
for (int j = 0; j < enemies.size(); ++j)
{
if (enemies.at(j).IsAlive())
{
if (CheckCollision(bullets.at(i), enemies.at(j)))
{
scoreHandler->ChangeScore(enemies.at(j).GetPoints());
enemies.at(j).Kill();
bullets.at(i).Kill();
break;
}
}
}
for (int j = 0; j < walls.size(); ++j)
{
if (walls.at(j).IsAlive())
{
if (CheckCollision(bullets.at(i), walls.at(j)))
{
walls.at(j).Kill();
bullets.at(i).Kill();
break;
}
}
}
}
}
aiMove(frameTime);
enemyFire();
window->draw(*player.GetModel());
for (int i = 0; i < bullets.size(); ++i)
{
if (bullets.at(i).IsAlive())
{
bullets.at(i).Move(100 * frameTime.asSeconds());
window->draw(*bullets.at(i).GetModel());
}
}
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
if ((enemies.at(i).GetPosX() < 0 || enemies.at(i).GetPosX() > 800) && !enemyDescent)
{
enemyDirection = !enemyDirection;
enemyDescent = true;
if (enemies.at(i).GetPosX() < 0)
{
boundaryCompensation = -enemies.at(i).GetPosX();
}
else
{
boundaryCompensation = 800 - enemies.at(i).GetPosX();
}
}
window->draw(*enemies.at(i).GetModel());
}
}
for (int i = 0; i < walls.size(); ++i)
{
if (walls.at(i).IsAlive())
{
window->draw(*walls.at(i).GetModel());
}
}
window->draw(scoreHandler->GetTotalScore());
window->draw(scoreHandler->GetHighScore());
}
else
{
if (victory)
{
if (scoreHandler->winScore(window))
{
scoreHandler->SaveScore();
return 1;
}
}
else
{
if (scoreHandler->loseScore(window))
{
scoreHandler->SaveScore();
return 1;
}
}
}
return 0;
}
void Game::InputCheck(const float &frameTime)
{
if (sf::Event::KeyPressed)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
finished = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
player.Move(frameTime, true);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
player.Move(frameTime, false);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !player.IsShooting())
{
playerFire();
}
else if (!sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
player.SetShooting(false);
}
}
}
bool Game::CheckCollision(Object& object1, Object& object2)
{
if (object1.GetModel()->getGlobalBounds().intersects(object2.GetModel()->getGlobalBounds()))
{
if (object1.GetTeam() != object2.GetTeam())
{
return true;
}
}
return false;
}
void Game::aiMove(const sf::Time &frameTime)
{
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
if (!enemyDescent)
{
enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
}
else
{
enemies.at(i).Descend();
enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
}
}
}
enemyDescent = false;
}
void Game::playerFire()
{
bullets.emplace_back();
bullets.back().Initialize(player.GetPosX() + 9, player.GetPosY(), 1);
player.SetShooting(true);
}
void Game::enemyFire()
{
int enemyShoot;
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
enemyShoot = rand() % 10000;
if (enemyShoot == 1)
{
bullets.emplace_back();
bullets.back().Initialize(enemies.at(i).GetPosX(), enemies.at(i).GetPosY(), 2);
}
}
}
}
bool Game::PlaceWall(int startPosX, int startPosY)
{
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 3; ++j)
{
walls.emplace_back();
walls.back().Initialize(startPosX + i * 15, startPosY + j * 15, 0);
}
}
return true;
}
bool Game::CreatePlayer(int startPosX, int startPosY)
{
player.Initialize(startPosX, startPosY, 1);
return true;
}
bool Game::CreateEnemy(int startPosX, int startPosY)
{
enemies.emplace_back();
enemies.back().Initialize(startPosX, startPosY, 2);
return true;
}
void Game::FinishGameCheck(sf::RenderWindow * window, const sf::Time &frameTime)
{
if (!player.IsAlive())
{
finished = true;
}
bool isAnyEnemyAlive = false;
for each(Enemy enemy in enemies) //Check if any enemy is alive
{
if (enemy.IsAlive())
{
isAnyEnemyAlive = true;
}
}
if (!isAnyEnemyAlive) // Victory if all enemies are dead
{
victory = true;
finished = true;
}
}
<commit_msg>Changed for each loop slightly<commit_after>#include "Game.hpp"
Game::Game()
{
}
Game::~Game()
{
Destroy();
}
bool Game::Initialize(Score * score)
{
scoreHandler = score;
enemyDirection = true;
finished = false;
victory = false;
return true;
}
bool Game::Destroy()
{
player.Shutdown();
enemies.clear();
walls.clear();
bullets.clear();
return true;
}
int Game::RenderGame(sf::RenderWindow * window, const sf::Time &frameTime)
{
FinishGameCheck(window, frameTime);
if (!finished)
{
//InputCheck(frameTime.asSeconds());
for (int i = 0; i < bullets.size(); ++i)
{
if (bullets.at(i).IsAlive())
{
if (bullets.at(i).GetPosY() < -1)
{
bullets.at(i).Kill();
continue;
}
if (CheckCollision(bullets.at(i), player))
{
player.Kill();
}
for (int j = 0; j < enemies.size(); ++j)
{
if (enemies.at(j).IsAlive())
{
if (CheckCollision(bullets.at(i), enemies.at(j)))
{
scoreHandler->ChangeScore(enemies.at(j).GetPoints());
enemies.at(j).Kill();
bullets.at(i).Kill();
break;
}
}
}
for (int j = 0; j < walls.size(); ++j)
{
if (walls.at(j).IsAlive())
{
if (CheckCollision(bullets.at(i), walls.at(j)))
{
walls.at(j).Kill();
bullets.at(i).Kill();
break;
}
}
}
}
}
aiMove(frameTime);
enemyFire();
window->draw(*player.GetModel());
for (int i = 0; i < bullets.size(); ++i)
{
if (bullets.at(i).IsAlive())
{
bullets.at(i).Move(100 * frameTime.asSeconds());
window->draw(*bullets.at(i).GetModel());
}
}
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
if ((enemies.at(i).GetPosX() < 0 || enemies.at(i).GetPosX() > 800) && !enemyDescent)
{
enemyDirection = !enemyDirection;
enemyDescent = true;
if (enemies.at(i).GetPosX() < 0)
{
boundaryCompensation = -enemies.at(i).GetPosX();
}
else
{
boundaryCompensation = 800 - enemies.at(i).GetPosX();
}
}
window->draw(*enemies.at(i).GetModel());
}
}
for (int i = 0; i < walls.size(); ++i)
{
if (walls.at(i).IsAlive())
{
window->draw(*walls.at(i).GetModel());
}
}
window->draw(scoreHandler->GetTotalScore());
window->draw(scoreHandler->GetHighScore());
}
else
{
if (victory)
{
if (scoreHandler->winScore(window))
{
scoreHandler->SaveScore();
return 1;
}
}
else
{
if (scoreHandler->loseScore(window))
{
scoreHandler->SaveScore();
return 1;
}
}
}
return 0;
}
void Game::InputCheck(const float &frameTime)
{
if (sf::Event::KeyPressed)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
finished = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
player.Move(frameTime, true);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
player.Move(frameTime, false);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !player.IsShooting())
{
playerFire();
}
else if (!sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
player.SetShooting(false);
}
}
}
bool Game::CheckCollision(Object& object1, Object& object2)
{
if (object1.GetModel()->getGlobalBounds().intersects(object2.GetModel()->getGlobalBounds()))
{
if (object1.GetTeam() != object2.GetTeam())
{
return true;
}
}
return false;
}
void Game::aiMove(const sf::Time &frameTime)
{
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
if (!enemyDescent)
{
enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
}
else
{
enemies.at(i).Descend();
enemies.at(i).Move(frameTime.asSeconds(), enemyDirection);
}
}
}
enemyDescent = false;
}
void Game::playerFire()
{
bullets.emplace_back();
bullets.back().Initialize(player.GetPosX() + 9, player.GetPosY(), 1);
player.SetShooting(true);
}
void Game::enemyFire()
{
int enemyShoot;
for (int i = 0; i < enemies.size(); ++i)
{
if (enemies.at(i).IsAlive())
{
enemyShoot = rand() % 10000;
if (enemyShoot == 1)
{
bullets.emplace_back();
bullets.back().Initialize(enemies.at(i).GetPosX(), enemies.at(i).GetPosY(), 2);
}
}
}
}
bool Game::PlaceWall(int startPosX, int startPosY)
{
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 3; ++j)
{
walls.emplace_back();
walls.back().Initialize(startPosX + i * 15, startPosY + j * 15, 0);
}
}
return true;
}
bool Game::CreatePlayer(int startPosX, int startPosY)
{
player.Initialize(startPosX, startPosY, 1);
return true;
}
bool Game::CreateEnemy(int startPosX, int startPosY)
{
enemies.emplace_back();
enemies.back().Initialize(startPosX, startPosY, 2);
return true;
}
void Game::FinishGameCheck(sf::RenderWindow * window, const sf::Time &frameTime)
{
if (!player.IsAlive())
{
finished = true;
}
bool isAnyEnemyAlive = false;
for (auto& enemy : enemies) //Check if any enemy is alive
{
if (enemy.IsAlive())
{
isAnyEnemyAlive = true;
}
}
if (!isAnyEnemyAlive) // Victory if all enemies are dead
{
victory = true;
finished = true;
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Sun Jun 19 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/falagard/TextComponent.h"
#include "CEGUI/falagard/XMLEnumHelper.h"
#include "CEGUI/falagard/XMLHandler.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/Font.h"
#include "CEGUI/LeftAlignedRenderedString.h"
#include "CEGUI/RightAlignedRenderedString.h"
#include "CEGUI/CentredRenderedString.h"
#include "CEGUI/JustifiedRenderedString.h"
#include "CEGUI/RenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUI/FribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUI/MinibidiVisualMapping.h"
#else
#include "CEGUI/BidiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(CEGUI_NEW_AO LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
CEGUI_DELETE_AO d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BidiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const
{
return d_vertFormatting.get(wnd);
}
VerticalTextFormatting TextComponent::getVerticalFormattingFromComponent() const
{
return d_vertFormatting.getValue();
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting.set(fmt);
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const
{
return d_horzFormatting.get(wnd);
}
HorizontalTextFormatting TextComponent::getHorizontalFormattingFromComponent() const
{
return d_horzFormatting.getValue();
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting.set(fmt);
}
void TextComponent::setHorizontalFormattingPropertySource(
const String& property_name)
{
d_horzFormatting.setPropertySource(property_name);
}
void TextComponent::setVerticalFormattingPropertySource(
const String& property_name)
{
d_vertFormatting.setPropertySource(property_name);
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window);
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const
{
const Font* font = getFontObject(srcWindow);
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, 0);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, 0);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, 0);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(&srcWindow, destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow);
// handle dest area adjustments for vertical formatting.
const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow);
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_min.d_y += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_min.d_y = destRect.d_max.d_y - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// add geometry for text to the target window.
d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
const Font* TextComponent::getFontObject(const Window& window) const
{
CEGUI_TRY
{
return d_fontPropertyName.empty() ?
(d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
return 0;
}
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag(Falagard_xmlHandler::TextComponentElement);
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag(Falagard_xmlHandler::TextElement);
if (!d_font.empty())
xml_stream.attribute(Falagard_xmlHandler::FontAttribute, d_font);
if (!getText().empty())
xml_stream.attribute(Falagard_xmlHandler::StringAttribute, getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag(Falagard_xmlHandler::TextPropertyElement)
.attribute(Falagard_xmlHandler::NameAttribute, d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag(Falagard_xmlHandler::FontPropertyElement)
.attribute(Falagard_xmlHandler::NameAttribute, d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
d_vertFormatting.writeXMLToStream(xml_stream);
d_horzFormatting.writeXMLToStream(xml_stream);
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getHorizontalExtent(&window);
}
float TextComponent::getVerticalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getVerticalExtent(&window);
}
bool TextComponent::handleFontRenderSizeChange(Window& window,
const Font* font) const
{
const bool res =
FalagardComponentBase::handleFontRenderSizeChange(window, font);
if (font == getFontObject(window))
{
window.invalidate();
return true;
}
return res;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveText(const Window& wnd) const
{
if (!d_textPropertyName.empty())
return wnd.getProperty(d_textPropertyName);
else if (d_textLogical.empty())
return wnd.getText();
else
return d_textLogical;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveVisualText(const Window& wnd) const
{
#ifndef CEGUI_BIDI_SUPPORT
return getEffectiveText(wnd);
#else
if (!d_textPropertyName.empty())
{
String visual;
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
wnd.getProperty(d_textPropertyName), visual, l2v, v2l);
return visual;
}
// do we use a static text string from the looknfeel
else if (d_textLogical.empty())
return wnd.getTextVisual();
else
getTextVisual();
#endif
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveFont(const Window& wnd) const
{
if (!d_fontPropertyName.empty())
return wnd.getProperty(d_fontPropertyName);
else if (d_font.empty())
{
if (const Font* font = wnd.getFont())
return font->getName();
else
return String();
}
else
return d_font;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: Adding missing functions to TextComponent.cpp<commit_after>/***********************************************************************
created: Sun Jun 19 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/falagard/TextComponent.h"
#include "CEGUI/falagard/XMLEnumHelper.h"
#include "CEGUI/falagard/XMLHandler.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/PropertyHelper.h"
#include "CEGUI/Font.h"
#include "CEGUI/LeftAlignedRenderedString.h"
#include "CEGUI/RightAlignedRenderedString.h"
#include "CEGUI/CentredRenderedString.h"
#include "CEGUI/JustifiedRenderedString.h"
#include "CEGUI/RenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUI/FribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUI/MinibidiVisualMapping.h"
#else
#include "CEGUI/BidiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(CEGUI_NEW_AO LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
CEGUI_DELETE_AO d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BidiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting(const Window& wnd) const
{
return d_vertFormatting.get(wnd);
}
VerticalTextFormatting TextComponent::getVerticalFormattingFromComponent() const
{
return d_vertFormatting.getValue();
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting.set(fmt);
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting(const Window& wnd) const
{
return d_horzFormatting.get(wnd);
}
HorizontalTextFormatting TextComponent::getHorizontalFormattingFromComponent() const
{
return d_horzFormatting.getValue();
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting.set(fmt);
}
const String& TextComponent::getHorizontalFormattingPropertySource() const
{
return d_horzFormatting.getPropertySource();
}
void TextComponent::setHorizontalFormattingPropertySource(
const String& property_name)
{
d_horzFormatting.setPropertySource(property_name);
}
const String& TextComponent::getVerticalFormattingPropertySource() const
{
return d_vertFormatting.getPropertySource();
}
void TextComponent::setVerticalFormattingPropertySource(
const String& property_name)
{
d_vertFormatting.setPropertySource(property_name);
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatting.get(window);
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
CEGUI_NEW_AO RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const
{
const Font* font = getFontObject(srcWindow);
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, 0);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, 0);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, 0);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(&srcWindow, destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent(&srcWindow);
// handle dest area adjustments for vertical formatting.
const VerticalTextFormatting vertFormatting = d_vertFormatting.get(srcWindow);
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_min.d_y += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_min.d_y = destRect.d_max.d_y - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// add geometry for text to the target window.
d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
const Font* TextComponent::getFontObject(const Window& window) const
{
CEGUI_TRY
{
return d_fontPropertyName.empty() ?
(d_font.empty() ? window.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(window.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
return 0;
}
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag(Falagard_xmlHandler::TextComponentElement);
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag(Falagard_xmlHandler::TextElement);
if (!d_font.empty())
xml_stream.attribute(Falagard_xmlHandler::FontAttribute, d_font);
if (!getText().empty())
xml_stream.attribute(Falagard_xmlHandler::StringAttribute, getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag(Falagard_xmlHandler::TextPropertyElement)
.attribute(Falagard_xmlHandler::NameAttribute, d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag(Falagard_xmlHandler::FontPropertyElement)
.attribute(Falagard_xmlHandler::NameAttribute, d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
d_vertFormatting.writeXMLToStream(xml_stream);
d_horzFormatting.writeXMLToStream(xml_stream);
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getHorizontalExtent(&window);
}
float TextComponent::getVerticalTextExtent(const Window& window) const
{
return d_formattedRenderedString->getVerticalExtent(&window);
}
bool TextComponent::handleFontRenderSizeChange(Window& window,
const Font* font) const
{
const bool res =
FalagardComponentBase::handleFontRenderSizeChange(window, font);
if (font == getFontObject(window))
{
window.invalidate();
return true;
}
return res;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveText(const Window& wnd) const
{
if (!d_textPropertyName.empty())
return wnd.getProperty(d_textPropertyName);
else if (d_textLogical.empty())
return wnd.getText();
else
return d_textLogical;
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveVisualText(const Window& wnd) const
{
#ifndef CEGUI_BIDI_SUPPORT
return getEffectiveText(wnd);
#else
if (!d_textPropertyName.empty())
{
String visual;
BidiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
wnd.getProperty(d_textPropertyName), visual, l2v, v2l);
return visual;
}
// do we use a static text string from the looknfeel
else if (d_textLogical.empty())
return wnd.getTextVisual();
else
getTextVisual();
#endif
}
//----------------------------------------------------------------------------//
String TextComponent::getEffectiveFont(const Window& wnd) const
{
if (!d_fontPropertyName.empty())
return wnd.getProperty(d_fontPropertyName);
else if (d_font.empty())
{
if (const Font* font = wnd.getFont())
return font->getName();
else
return String();
}
else
return d_font;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/coverage.h"
#include "include/dart_api.h"
#include "vm/compiler.h"
#include "vm/isolate.h"
#include "vm/json_stream.h"
#include "vm/longjump.h"
#include "vm/object.h"
#include "vm/object_store.h"
namespace dart {
DEFINE_FLAG(charp, coverage_dir, NULL,
"Enable writing coverage data into specified directory.");
class CoverageFilterAll : public CoverageFilter {
public:
bool ShouldOutputCoverageFor(const Library& lib,
const Script& script,
const Class& cls,
const Function& func) const {
return true;
}
};
// map[token_pos] -> line-number.
static void ComputeTokenPosToLineNumberMap(const Script& script,
GrowableArray<intptr_t>* map) {
const TokenStream& tkns = TokenStream::Handle(script.tokens());
const intptr_t len = ExternalTypedData::Handle(tkns.GetStream()).Length();
map->SetLength(len);
#if defined(DEBUG)
for (intptr_t i = 0; i < len; i++) {
(*map)[i] = -1;
}
#endif
TokenStream::Iterator tkit(tkns, 0, TokenStream::Iterator::kAllTokens);
intptr_t cur_line = script.line_offset() + 1;
while (tkit.CurrentTokenKind() != Token::kEOS) {
(*map)[tkit.CurrentPosition()] = cur_line;
if (tkit.CurrentTokenKind() == Token::kNEWLINE) {
cur_line++;
}
tkit.Advance();
}
}
void CodeCoverage::CompileAndAdd(const Function& function,
const JSONArray& hits_or_sites,
const GrowableArray<intptr_t>& pos_to_line,
bool as_call_sites) {
// If the function should not be compiled for coverage analysis, then just
// skip this method.
// TODO(iposva): Maybe we should skip synthesized methods in general too.
if (function.is_abstract() || function.IsRedirectingFactory()) {
return;
}
if (function.IsNonImplicitClosureFunction() &&
(function.context_scope() == ContextScope::null())) {
// TODO(iposva): This can arise if we attempt to compile an inner function
// before we have compiled its enclosing function or if the enclosing
// function failed to compile.
return;
}
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
// Make sure we have the unoptimized code for this function available.
if (Compiler::EnsureUnoptimizedCode(thread, function) != Error::null()) {
// Ignore the error and this function entirely.
return;
}
const Code& code = Code::Handle(zone, function.unoptimized_code());
ASSERT(!code.IsNull());
// Print the hit counts for all IC datas.
ZoneGrowableArray<const ICData*>* ic_data_array =
new(zone) ZoneGrowableArray<const ICData*>();
function.RestoreICDataMap(ic_data_array);
const PcDescriptors& descriptors = PcDescriptors::Handle(
zone, code.pc_descriptors());
const intptr_t begin_pos = function.token_pos();
const intptr_t end_pos = function.end_token_pos();
intptr_t last_line = -1;
intptr_t last_count = 0;
// Only IC based calls have counting.
PcDescriptors::Iterator iter(descriptors,
RawPcDescriptors::kIcCall | RawPcDescriptors::kUnoptStaticCall);
while (iter.MoveNext()) {
HANDLESCOPE(thread);
const ICData* ic_data = (*ic_data_array)[iter.DeoptId()];
if (!ic_data->IsNull()) {
const intptr_t token_pos = iter.TokenPos();
// Filter out descriptors that do not map to tokens in the source code.
if ((token_pos < begin_pos) || (token_pos > end_pos)) {
continue;
}
intptr_t line = pos_to_line[token_pos];
#if defined(DEBUG)
const Script& script = Script::Handle(zone, function.script());
intptr_t test_line = -1;
script.GetTokenLocation(token_pos, &test_line, NULL);
ASSERT(test_line == line);
#endif
// Merge hit data where possible.
if (last_line == line) {
last_count += ic_data->AggregateCount();
} else {
if ((last_line != -1) && !as_call_sites) {
hits_or_sites.AddValue(last_line);
hits_or_sites.AddValue(last_count);
}
last_count = ic_data->AggregateCount();
last_line = line;
}
if (as_call_sites) {
bool is_static_call = iter.Kind() == RawPcDescriptors::kUnoptStaticCall;
ic_data->PrintToJSONArray(hits_or_sites, token_pos, is_static_call);
}
}
}
// Write last hit value if needed.
if ((last_line != -1) && !as_call_sites) {
hits_or_sites.AddValue(last_line);
hits_or_sites.AddValue(last_count);
}
}
void CodeCoverage::PrintClass(const Library& lib,
const Class& cls,
const JSONArray& jsarr,
CoverageFilter* filter,
bool as_call_sites) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
if (cls.EnsureIsFinalized(isolate) != Error::null()) {
// Only classes that have been finalized do have a meaningful list of
// functions.
return;
}
Array& functions = Array::Handle(cls.functions());
ASSERT(!functions.IsNull());
Function& function = Function::Handle();
Script& script = Script::Handle();
String& saved_url = String::Handle();
String& url = String::Handle();
GrowableArray<intptr_t> pos_to_line;
int i = 0;
while (i < functions.Length()) {
HANDLESCOPE(thread);
function ^= functions.At(i);
script = function.script();
saved_url = script.url();
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
ComputeTokenPosToLineNumberMap(script, &pos_to_line);
JSONObject jsobj(&jsarr);
jsobj.AddProperty("source", saved_url.ToCString());
jsobj.AddProperty("script", script);
JSONArray hits_or_sites(&jsobj, as_call_sites ? "callSites" : "hits");
// We stay within this loop while we are seeing functions from the same
// source URI.
while (i < functions.Length()) {
function ^= functions.At(i);
script = function.script();
url = script.url();
if (!url.Equals(saved_url)) {
pos_to_line.Clear();
break;
}
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
CompileAndAdd(function, hits_or_sites, pos_to_line, as_call_sites);
i++;
}
}
GrowableObjectArray& closures =
GrowableObjectArray::Handle(cls.closures());
if (!closures.IsNull()) {
i = 0;
pos_to_line.Clear();
// We need to keep rechecking the length of the closures array, as handling
// a closure potentially adds new entries to the end.
while (i < closures.Length()) {
HANDLESCOPE(thread);
function ^= closures.At(i);
script = function.script();
saved_url = script.url();
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
ComputeTokenPosToLineNumberMap(script, &pos_to_line);
JSONObject jsobj(&jsarr);
jsobj.AddProperty("source", saved_url.ToCString());
jsobj.AddProperty("script", script);
JSONArray hits_or_sites(&jsobj, as_call_sites ? "callSites" : "hits");
// We stay within this loop while we are seeing functions from the same
// source URI.
while (i < closures.Length()) {
function ^= closures.At(i);
script = function.script();
url = script.url();
if (!url.Equals(saved_url)) {
pos_to_line.Clear();
break;
}
CompileAndAdd(function, hits_or_sites, pos_to_line, as_call_sites);
i++;
}
}
}
}
void CodeCoverage::Write(Isolate* isolate) {
if (FLAG_coverage_dir == NULL) {
return;
}
Dart_FileOpenCallback file_open = Isolate::file_open_callback();
Dart_FileWriteCallback file_write = Isolate::file_write_callback();
Dart_FileCloseCallback file_close = Isolate::file_close_callback();
if ((file_open == NULL) || (file_write == NULL) || (file_close == NULL)) {
return;
}
JSONStream stream;
PrintJSON(isolate, &stream, NULL, false);
const char* format = "%s/dart-cov-%" Pd "-%" Pd64 ".json";
intptr_t pid = OS::ProcessId();
intptr_t len = OS::SNPrint(NULL, 0, format,
FLAG_coverage_dir, pid, isolate->main_port());
char* filename = Thread::Current()->zone()->Alloc<char>(len + 1);
OS::SNPrint(filename, len + 1, format,
FLAG_coverage_dir, pid, isolate->main_port());
void* file = (*file_open)(filename, true);
if (file == NULL) {
OS::Print("Failed to write coverage file: %s\n", filename);
return;
}
(*file_write)(stream.buffer()->buf(), stream.buffer()->length(), file);
(*file_close)(file);
}
void CodeCoverage::PrintJSON(Isolate* isolate,
JSONStream* stream,
CoverageFilter* filter,
bool as_call_sites) {
CoverageFilterAll default_filter;
if (filter == NULL) {
filter = &default_filter;
}
const GrowableObjectArray& libs = GrowableObjectArray::Handle(
isolate, isolate->object_store()->libraries());
Library& lib = Library::Handle();
Class& cls = Class::Handle();
JSONObject coverage(stream);
coverage.AddProperty("type", "CodeCoverage");
{
JSONArray jsarr(&coverage, "coverage");
for (int i = 0; i < libs.Length(); i++) {
lib ^= libs.At(i);
ClassDictionaryIterator it(lib, ClassDictionaryIterator::kIteratePrivate);
while (it.HasNext()) {
cls = it.GetNextClass();
ASSERT(!cls.IsNull());
PrintClass(lib, cls, jsarr, filter, as_call_sites);
}
}
}
}
} // namespace dart
<commit_msg>Do less work while computing call site info.<commit_after>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/coverage.h"
#include "include/dart_api.h"
#include "vm/compiler.h"
#include "vm/isolate.h"
#include "vm/json_stream.h"
#include "vm/longjump.h"
#include "vm/object.h"
#include "vm/object_store.h"
namespace dart {
DEFINE_FLAG(charp, coverage_dir, NULL,
"Enable writing coverage data into specified directory.");
class CoverageFilterAll : public CoverageFilter {
public:
bool ShouldOutputCoverageFor(const Library& lib,
const Script& script,
const Class& cls,
const Function& func) const {
return true;
}
};
// map[token_pos] -> line-number.
static void ComputeTokenPosToLineNumberMap(const Script& script,
GrowableArray<intptr_t>* map) {
const TokenStream& tkns = TokenStream::Handle(script.tokens());
const intptr_t len = ExternalTypedData::Handle(tkns.GetStream()).Length();
map->SetLength(len);
#if defined(DEBUG)
for (intptr_t i = 0; i < len; i++) {
(*map)[i] = -1;
}
#endif
TokenStream::Iterator tkit(tkns, 0, TokenStream::Iterator::kAllTokens);
intptr_t cur_line = script.line_offset() + 1;
while (tkit.CurrentTokenKind() != Token::kEOS) {
(*map)[tkit.CurrentPosition()] = cur_line;
if (tkit.CurrentTokenKind() == Token::kNEWLINE) {
cur_line++;
}
tkit.Advance();
}
}
void CodeCoverage::CompileAndAdd(const Function& function,
const JSONArray& hits_or_sites,
const GrowableArray<intptr_t>& pos_to_line,
bool as_call_sites) {
// If the function should not be compiled for coverage analysis, then just
// skip this method.
// TODO(iposva): Maybe we should skip synthesized methods in general too.
if (function.is_abstract() || function.IsRedirectingFactory()) {
return;
}
if (function.IsNonImplicitClosureFunction() &&
(function.context_scope() == ContextScope::null())) {
// TODO(iposva): This can arise if we attempt to compile an inner function
// before we have compiled its enclosing function or if the enclosing
// function failed to compile.
return;
}
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
// Make sure we have the unoptimized code for this function available.
if (Compiler::EnsureUnoptimizedCode(thread, function) != Error::null()) {
// Ignore the error and this function entirely.
return;
}
const Code& code = Code::Handle(zone, function.unoptimized_code());
ASSERT(!code.IsNull());
// Print the hit counts for all IC datas.
ZoneGrowableArray<const ICData*>* ic_data_array =
new(zone) ZoneGrowableArray<const ICData*>();
function.RestoreICDataMap(ic_data_array);
const PcDescriptors& descriptors = PcDescriptors::Handle(
zone, code.pc_descriptors());
const intptr_t begin_pos = function.token_pos();
const intptr_t end_pos = function.end_token_pos();
intptr_t last_line = -1;
intptr_t last_count = 0;
// Only IC based calls have counting.
PcDescriptors::Iterator iter(descriptors,
RawPcDescriptors::kIcCall | RawPcDescriptors::kUnoptStaticCall);
while (iter.MoveNext()) {
HANDLESCOPE(thread);
const ICData* ic_data = (*ic_data_array)[iter.DeoptId()];
if (!ic_data->IsNull()) {
const intptr_t token_pos = iter.TokenPos();
// Filter out descriptors that do not map to tokens in the source code.
if ((token_pos < begin_pos) || (token_pos > end_pos)) {
continue;
}
if (as_call_sites) {
bool is_static_call = iter.Kind() == RawPcDescriptors::kUnoptStaticCall;
ic_data->PrintToJSONArray(hits_or_sites, token_pos, is_static_call);
} else {
intptr_t line = pos_to_line[token_pos];
#if defined(DEBUG)
const Script& script = Script::Handle(zone, function.script());
intptr_t test_line = -1;
script.GetTokenLocation(token_pos, &test_line, NULL);
ASSERT(test_line == line);
#endif
// Merge hit data where possible.
if (last_line == line) {
last_count += ic_data->AggregateCount();
} else {
if ((last_line != -1)) {
hits_or_sites.AddValue(last_line);
hits_or_sites.AddValue(last_count);
}
last_count = ic_data->AggregateCount();
last_line = line;
}
}
}
}
// Write last hit value if needed.
if (!as_call_sites && (last_line != -1)) {
hits_or_sites.AddValue(last_line);
hits_or_sites.AddValue(last_count);
}
}
void CodeCoverage::PrintClass(const Library& lib,
const Class& cls,
const JSONArray& jsarr,
CoverageFilter* filter,
bool as_call_sites) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
if (cls.EnsureIsFinalized(isolate) != Error::null()) {
// Only classes that have been finalized do have a meaningful list of
// functions.
return;
}
Array& functions = Array::Handle(cls.functions());
ASSERT(!functions.IsNull());
Function& function = Function::Handle();
Script& script = Script::Handle();
String& saved_url = String::Handle();
String& url = String::Handle();
GrowableArray<intptr_t> pos_to_line;
int i = 0;
while (i < functions.Length()) {
HANDLESCOPE(thread);
function ^= functions.At(i);
script = function.script();
saved_url = script.url();
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
if (!as_call_sites) {
ComputeTokenPosToLineNumberMap(script, &pos_to_line);
}
JSONObject jsobj(&jsarr);
jsobj.AddProperty("source", saved_url.ToCString());
jsobj.AddProperty("script", script);
JSONArray hits_or_sites(&jsobj, as_call_sites ? "callSites" : "hits");
// We stay within this loop while we are seeing functions from the same
// source URI.
while (i < functions.Length()) {
function ^= functions.At(i);
script = function.script();
url = script.url();
if (!url.Equals(saved_url)) {
pos_to_line.Clear();
break;
}
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
CompileAndAdd(function, hits_or_sites, pos_to_line, as_call_sites);
i++;
}
}
GrowableObjectArray& closures =
GrowableObjectArray::Handle(cls.closures());
if (!closures.IsNull()) {
i = 0;
pos_to_line.Clear();
// We need to keep rechecking the length of the closures array, as handling
// a closure potentially adds new entries to the end.
while (i < closures.Length()) {
HANDLESCOPE(thread);
function ^= closures.At(i);
script = function.script();
saved_url = script.url();
if (!filter->ShouldOutputCoverageFor(lib, script, cls, function)) {
i++;
continue;
}
ComputeTokenPosToLineNumberMap(script, &pos_to_line);
JSONObject jsobj(&jsarr);
jsobj.AddProperty("source", saved_url.ToCString());
jsobj.AddProperty("script", script);
JSONArray hits_or_sites(&jsobj, as_call_sites ? "callSites" : "hits");
// We stay within this loop while we are seeing functions from the same
// source URI.
while (i < closures.Length()) {
function ^= closures.At(i);
script = function.script();
url = script.url();
if (!url.Equals(saved_url)) {
pos_to_line.Clear();
break;
}
CompileAndAdd(function, hits_or_sites, pos_to_line, as_call_sites);
i++;
}
}
}
}
void CodeCoverage::Write(Isolate* isolate) {
if (FLAG_coverage_dir == NULL) {
return;
}
Dart_FileOpenCallback file_open = Isolate::file_open_callback();
Dart_FileWriteCallback file_write = Isolate::file_write_callback();
Dart_FileCloseCallback file_close = Isolate::file_close_callback();
if ((file_open == NULL) || (file_write == NULL) || (file_close == NULL)) {
return;
}
JSONStream stream;
PrintJSON(isolate, &stream, NULL, false);
const char* format = "%s/dart-cov-%" Pd "-%" Pd64 ".json";
intptr_t pid = OS::ProcessId();
intptr_t len = OS::SNPrint(NULL, 0, format,
FLAG_coverage_dir, pid, isolate->main_port());
char* filename = Thread::Current()->zone()->Alloc<char>(len + 1);
OS::SNPrint(filename, len + 1, format,
FLAG_coverage_dir, pid, isolate->main_port());
void* file = (*file_open)(filename, true);
if (file == NULL) {
OS::Print("Failed to write coverage file: %s\n", filename);
return;
}
(*file_write)(stream.buffer()->buf(), stream.buffer()->length(), file);
(*file_close)(file);
}
void CodeCoverage::PrintJSON(Isolate* isolate,
JSONStream* stream,
CoverageFilter* filter,
bool as_call_sites) {
CoverageFilterAll default_filter;
if (filter == NULL) {
filter = &default_filter;
}
const GrowableObjectArray& libs = GrowableObjectArray::Handle(
isolate, isolate->object_store()->libraries());
Library& lib = Library::Handle();
Class& cls = Class::Handle();
JSONObject coverage(stream);
coverage.AddProperty("type", "CodeCoverage");
{
JSONArray jsarr(&coverage, "coverage");
for (int i = 0; i < libs.Length(); i++) {
lib ^= libs.At(i);
ClassDictionaryIterator it(lib, ClassDictionaryIterator::kIteratePrivate);
while (it.HasNext()) {
cls = it.GetNextClass();
ASSERT(!cls.IsNull());
PrintClass(lib, cls, jsarr, filter, as_call_sites);
}
}
}
}
} // namespace dart
<|endoftext|> |
<commit_before>351f75c2-2e4f-11e5-9284-b827eb9e62be<commit_msg>35247388-2e4f-11e5-9284-b827eb9e62be<commit_after>35247388-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>#include "TaskFS.hpp"
#include <iostream>
#include "Task.hpp"
#include "Category.hpp"
#include <cstdlib>
#include <posix/sys/stat.h>
#include <kernel/fs_index.h>
TaskFS::TaskFS()
{
error=new BAlert("FileSystem error",
"There was an error in the BeFS backend",
"OK",NULL,NULL,B_WIDTH_AS_USUAL,B_OFFSET_SPACING, B_STOP_ALERT);
BPath path;
if(find_directory(B_USER_SETTINGS_DIRECTORY,&path)!=B_OK)
{
error->Go();
exit(2);
}
BDirectory storage;
BDirectory tasksDir;
BDirectory categoriesDir;
BDirectory settings(path.Path());
settings.CreateDirectory("HaikuToDo",&storage);
storage.CreateDirectory("Tasks",&tasksDir);
storage.CreateDirectory("Categories",&categoriesDir);
path.Append("HaikuToDo");
BPath taskPath=path;
taskPath.Append("Tasks");
BPath categoriesPath=path;
categoriesPath.Append("Categories");
tasks=BString(taskPath.Path());
categories=BString(categoriesPath.Path());
struct stat st;
settings.GetStat(&st);
volume=st.st_dev;
fs_create_index(st.st_dev,"HAIKU_TO_DO:Category",B_STRING_TYPE,0);
}
TaskFS::~TaskFS()
{
}
void
TaskFS::LoadTasks(const char* category, BListView* tasksList)
{
BString predicate("HAIKU_TO_DO:Category=**");
if(strcmp(category,"ALL")==0)
predicate.Append("**");
else
predicate.Append(category);
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
char name[8192];
entry.GetName(name);
BFile file(&entry,B_READ_ONLY);
off_t file_size=0;
file.GetSize(&file_size);
char buffer[file_size+1024];
file.Read(buffer,file_size);
BString finished;
file.ReadAttrString("HAIKU_TO_DO:Finished",&finished);
bool fin;
if(finished.Compare("FINISHED")==0)
{
fin=true;
}
else
{
fin=false;
}
Task* tk=new Task((const char*)name,(const char*)buffer,"ALL",fin);
tasksList->AddItem(tk);
}
}
}
}
void
TaskFS::LoadCategories(BListView* categoriesList)
{
BDirectory dir(categories);
int32 entries=dir.CountEntries();
for(int32 i=0;i<entries;i++)
{
char name[8192];
BEntry entry;
dir.GetNextEntry(&entry);
entry.GetName(name);
BFile file(&entry,B_READ_ONLY);
off_t file_size=0;
file.GetSize(&file_size);
char buffer[file_size+1024];
file.Read(buffer,file_size);
Category* cat=new Category((const char*)name,(const char*)buffer);
categoriesList->AddItem(cat);
}
}
bool
TaskFS::AddCategory(const char* name, const char* filename)
{
BString filn(filename);
BDirectory dir(categories);
BFile file;
dir.CreateFile(name,&file);
file.Write(filn,filn.Length());
}
bool
TaskFS::AddTask(const char* title, const char* description, const char* category)
{
BString desc(description);
BDirectory dir(tasks);
BFile file;
dir.CreateFile(title,&file);
file.Write(desc,desc.Length());
file.WriteAttrString("HAIKU_TO_DO:Category",new BString(category));
file.WriteAttrString("HAIKU_TO_DO:Finished",new BString("UNFINISHED"));
}
bool
TaskFS::RemoveTask(const char* title, const char* description, const char* category)
{
BString predicate("(HAIKU_TO_DO:Category=**)&&(name=");
predicate.Append(title);
predicate.Append(")");
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
entry.Remove();
}
}
}
}
bool
TaskFS::MarkAsComplete(const char* title, const char* description, const char* category)
{
BString predicate("(HAIKU_TO_DO:Category=**)&&(name=");
predicate.Append(title);
predicate.Append(")");
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
BFile file(&entry,B_READ_ONLY);
file.WriteAttrString("HAIKU_TO_DO:Finished",new BString("FINISHED"));
}
}
}
}
<commit_msg>HAIKU_TO_DO:Finished is now a boolean type<commit_after>#include "TaskFS.hpp"
#include <iostream>
#include "Task.hpp"
#include "Category.hpp"
#include <cstdlib>
#include <TypeConstants.h>
#include <posix/sys/stat.h>
#include <kernel/fs_index.h>
TaskFS::TaskFS()
{
error=new BAlert("FileSystem error",
"There was an error in the BeFS backend",
"OK",NULL,NULL,B_WIDTH_AS_USUAL,B_OFFSET_SPACING, B_STOP_ALERT);
BPath path;
if(find_directory(B_USER_SETTINGS_DIRECTORY,&path)!=B_OK)
{
error->Go();
exit(2);
}
BDirectory storage;
BDirectory tasksDir;
BDirectory categoriesDir;
BDirectory settings(path.Path());
settings.CreateDirectory("HaikuToDo",&storage);
storage.CreateDirectory("Tasks",&tasksDir);
storage.CreateDirectory("Categories",&categoriesDir);
path.Append("HaikuToDo");
BPath taskPath=path;
taskPath.Append("Tasks");
BPath categoriesPath=path;
categoriesPath.Append("Categories");
tasks=BString(taskPath.Path());
categories=BString(categoriesPath.Path());
struct stat st;
settings.GetStat(&st);
volume=st.st_dev;
fs_create_index(st.st_dev,"HAIKU_TO_DO:Category",B_STRING_TYPE,0);
}
TaskFS::~TaskFS()
{
}
void
TaskFS::LoadTasks(const char* category, BListView* tasksList)
{
BString predicate("HAIKU_TO_DO:Category=**");
if(strcmp(category,"ALL")==0)
predicate.Append("**");
else
predicate.Append(category);
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
char name[8192];
entry.GetName(name);
BFile file(&entry,B_READ_ONLY);
off_t file_size=0;
file.GetSize(&file_size);
char buffer[file_size+1024];
file.Read(buffer,file_size);
bool finished;
file.ReadAttr("HAIKU_TO_DO:Finished",B_BOOL_TYPE,0,&finished,sizeof(bool));
Task* tk=new Task((const char*)name,(const char*)buffer,"ALL",finished);
tasksList->AddItem(tk);
}
}
}
}
void
TaskFS::LoadCategories(BListView* categoriesList)
{
BDirectory dir(categories);
int32 entries=dir.CountEntries();
for(int32 i=0;i<entries;i++)
{
char name[8192];
BEntry entry;
dir.GetNextEntry(&entry);
entry.GetName(name);
BFile file(&entry,B_READ_ONLY);
off_t file_size=0;
file.GetSize(&file_size);
char buffer[file_size+1024];
file.Read(buffer,file_size);
Category* cat=new Category((const char*)name,(const char*)buffer);
categoriesList->AddItem(cat);
}
}
bool
TaskFS::AddCategory(const char* name, const char* filename)
{
BString filn(filename);
BDirectory dir(categories);
BFile file;
dir.CreateFile(name,&file);
file.Write(filn,filn.Length());
}
bool
TaskFS::AddTask(const char* title, const char* description, const char* category)
{
BString desc(description);
BDirectory dir(tasks);
BFile file;
dir.CreateFile(title,&file);
file.Write(desc,desc.Length());
file.WriteAttrString("HAIKU_TO_DO:Category",new BString(category));
bool finished=false;
file.WriteAttr("HAIKU_TO_DO:Finished",B_BOOL_TYPE,0,&finished,sizeof(bool));
}
bool
TaskFS::RemoveTask(const char* title, const char* description, const char* category)
{
BString predicate("(HAIKU_TO_DO:Category=**)&&(name=");
predicate.Append(title);
predicate.Append(")");
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
entry.Remove();
}
}
}
}
bool
TaskFS::MarkAsComplete(const char* title, const char* description, const char* category)
{
BString predicate("(HAIKU_TO_DO:Category=**)&&(name=");
predicate.Append(title);
predicate.Append(")");
BQuery query;
BVolume volume;
BVolumeRoster volumeRoster;
while(volumeRoster.GetNextVolume(&volume)==B_OK)
{
if(volume.KnowsQuery())
{
query.Clear();
query.SetVolume(&volume);
query.SetPredicate(predicate.String());
status_t rc=query.Fetch();
if(rc!=B_OK)
{
error->Go();
}
BEntry entry;
while(query.GetNextEntry(&entry)==B_OK)
{
BFile file(&entry,B_READ_ONLY);
bool finished=true;
file.WriteAttr("HAIKU_TO_DO:Finished",B_BOOL_TYPE,0,&finished,sizeof(bool));
}
}
}
}
<|endoftext|> |
<commit_before>4c9b74cc-2e4e-11e5-9284-b827eb9e62be<commit_msg>4ca08714-2e4e-11e5-9284-b827eb9e62be<commit_after>4ca08714-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>#pragma once
#include <stdint.h>
#include <vector>
#include "Vector.hpp"
#include "APIQuadcopter.hpp"
#include "APIFormation.hpp"
#include "APICamera.hpp"
#include "APICameraSystem.hpp"
#include "APIMessageListener.hpp"
#include "api_application/Announce.h"
namespace kitrokopter {
class API {
public:
API(int argc, char **argv);
~API();
bool announce(
api_application::Announce::Request &req,
api_application::Announce::Response &res);
void initializeCameras();
/* Quadcopter mutation */
APIQuadcopter* getQuadcpoter(int id);
bool removeQuadcopter(int id);
/* Formation */
void setFormation(APIFormation formation);
APIFormation* getFormation();
/* Cameras */
APICameraSystem* getCameraSystem();
std::vector<APICamera*> getCameras();
std::vector<APICamera*> getCalibratedCameras();
std::vector<APICamera*> getUncalibratedCameras();
int getCameraAmount();
int getCalibratedCameraAmount();
int getUncalibratedCameraAmount();
/* Quadcopter getters */
std::vector<APIQuadcopter*> getQuadcopters();
std::vector<APIQuadcopter*> getQuadcoptersSelectedForFlight();
std::vector<APIQuadcopter*> getQuadcoptersNotSelectedForFlight();
/* TODO: Also selectors for quadcopters currently flying or on the ground? */
std::vector<APIQuadcopter*> getQuadcoptersTracked();
std::vector<APIQuadcopter*> getQuadcoptersUntracked();
std::vector<APIQuadcopter*> getQuadcoptersInFormation();
std::vector<APIQuadcopter*> getQuadcoptersNotInFormation();
int* scanChannels();
/* Quadcopter amount */
int getQuadcopterAmount();
int getQuadcoptersFlyingAmount();
int getQuadcoptersOnGroundAmount();
int getQuadcoptersTrackedAmount();
int getQuadcoptersUntrackedAmount();
int getQuadcoptersInFormationAmount();
int getQuadcoptersNotInFormationAmount();
/* message listeners */
void addMessageListener(APIMessageListener*);
void removeMessageListener(APIMessageListener*);
/* Launch / Land */
// TODO
void launchQuadcopters(int height) {}
double getLaunchProgress();
bool quadcoptersLaunched();
void landQuadcopters();
void shutdownSystem();
/* Settings */
Cuboid getMaximumOperatingArea();
bool setOperatingArea(Cuboid);
int getMaximumHorizontalSpeed();
int getMaximumVerticalSpeed();
int getMaximumHorizontalAcceleration();
int getMaximumVerticalAcceleration();
void setReceiveTargetMovementData(bool);
void setReceiveActualMovementData(bool);
void setReceiveQuadcopterState(bool);
/* Movement */
void moveFormation(Vector);
void rotateFormation(Vector);
private:
int idCounter;
ros::AsyncSpinner *spinner;
//the ids of modules by category
std::vector<int> controllerIds;
std::vector<int> positionIds;
APICameraSystem cameraSystem;
std::map <uint32_t, APIQuadcopter> quadcopters;
APIFormation formation;
};
}
<commit_msg>Add shutdownSystem() dummy<commit_after>#pragma once
#include <stdint.h>
#include <vector>
#include "Vector.hpp"
#include "APIQuadcopter.hpp"
#include "APIFormation.hpp"
#include "APICamera.hpp"
#include "APICameraSystem.hpp"
#include "APIMessageListener.hpp"
#include "api_application/Announce.h"
namespace kitrokopter {
class API {
public:
API(int argc, char **argv);
~API();
bool announce(
api_application::Announce::Request &req,
api_application::Announce::Response &res);
void initializeCameras();
/* Quadcopter mutation */
APIQuadcopter* getQuadcpoter(int id);
bool removeQuadcopter(int id);
/* Formation */
void setFormation(APIFormation formation);
APIFormation* getFormation();
/* Cameras */
APICameraSystem* getCameraSystem();
std::vector<APICamera*> getCameras();
std::vector<APICamera*> getCalibratedCameras();
std::vector<APICamera*> getUncalibratedCameras();
int getCameraAmount();
int getCalibratedCameraAmount();
int getUncalibratedCameraAmount();
/* Quadcopter getters */
std::vector<APIQuadcopter*> getQuadcopters();
std::vector<APIQuadcopter*> getQuadcoptersSelectedForFlight();
std::vector<APIQuadcopter*> getQuadcoptersNotSelectedForFlight();
/* TODO: Also selectors for quadcopters currently flying or on the ground? */
std::vector<APIQuadcopter*> getQuadcoptersTracked();
std::vector<APIQuadcopter*> getQuadcoptersUntracked();
std::vector<APIQuadcopter*> getQuadcoptersInFormation();
std::vector<APIQuadcopter*> getQuadcoptersNotInFormation();
int* scanChannels();
/* Quadcopter amount */
int getQuadcopterAmount();
int getQuadcoptersFlyingAmount();
int getQuadcoptersOnGroundAmount();
int getQuadcoptersTrackedAmount();
int getQuadcoptersUntrackedAmount();
int getQuadcoptersInFormationAmount();
int getQuadcoptersNotInFormationAmount();
/* message listeners */
void addMessageListener(APIMessageListener*);
void removeMessageListener(APIMessageListener*);
/* Launch / Land */
// TODO
void launchQuadcopters(int height) {}
double getLaunchProgress();
bool quadcoptersLaunched();
void landQuadcopters();
// TODO
void shutdownSystem() {}
/* Settings */
Cuboid getMaximumOperatingArea();
bool setOperatingArea(Cuboid);
int getMaximumHorizontalSpeed();
int getMaximumVerticalSpeed();
int getMaximumHorizontalAcceleration();
int getMaximumVerticalAcceleration();
void setReceiveTargetMovementData(bool);
void setReceiveActualMovementData(bool);
void setReceiveQuadcopterState(bool);
/* Movement */
void moveFormation(Vector);
void rotateFormation(Vector);
private:
int idCounter;
ros::AsyncSpinner *spinner;
//the ids of modules by category
std::vector<int> controllerIds;
std::vector<int> positionIds;
APICameraSystem cameraSystem;
std::map <uint32_t, APIQuadcopter> quadcopters;
APIFormation formation;
};
}
<|endoftext|> |
<commit_before>d51212bc-2e4d-11e5-9284-b827eb9e62be<commit_msg>d5170eac-2e4d-11e5-9284-b827eb9e62be<commit_after>d5170eac-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>df0f46f4-2e4d-11e5-9284-b827eb9e62be<commit_msg>df144f5a-2e4d-11e5-9284-b827eb9e62be<commit_after>df144f5a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0fc90898-2e4e-11e5-9284-b827eb9e62be<commit_msg>0fce019a-2e4e-11e5-9284-b827eb9e62be<commit_after>0fce019a-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>56a46aaa-2e4e-11e5-9284-b827eb9e62be<commit_msg>56a982e2-2e4e-11e5-9284-b827eb9e62be<commit_after>56a982e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>294ef0a2-2e4e-11e5-9284-b827eb9e62be<commit_msg>295adce6-2e4e-11e5-9284-b827eb9e62be<commit_after>295adce6-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>67f0b4e0-2e4d-11e5-9284-b827eb9e62be<commit_msg>67f5c368-2e4d-11e5-9284-b827eb9e62be<commit_after>67f5c368-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>496e11c0-2e4d-11e5-9284-b827eb9e62be<commit_msg>49732192-2e4d-11e5-9284-b827eb9e62be<commit_after>49732192-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>18c62cea-2e4f-11e5-9284-b827eb9e62be<commit_msg>18cb3c6c-2e4f-11e5-9284-b827eb9e62be<commit_after>18cb3c6c-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>350d65cc-2e4e-11e5-9284-b827eb9e62be<commit_msg>351256c2-2e4e-11e5-9284-b827eb9e62be<commit_after>351256c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>66a575e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>66aa771e-2e4e-11e5-9284-b827eb9e62be<commit_after>66aa771e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>cd321a46-2e4e-11e5-9284-b827eb9e62be<commit_msg>cd371942-2e4e-11e5-9284-b827eb9e62be<commit_after>cd371942-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>5e3863c6-2e4d-11e5-9284-b827eb9e62be<commit_msg>5e3d7096-2e4d-11e5-9284-b827eb9e62be<commit_after>5e3d7096-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7b6d3d4e-2e4e-11e5-9284-b827eb9e62be<commit_msg>7b724604-2e4e-11e5-9284-b827eb9e62be<commit_after>7b724604-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>61b82d6e-2e4e-11e5-9284-b827eb9e62be<commit_msg>61bd3408-2e4e-11e5-9284-b827eb9e62be<commit_after>61bd3408-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>bc4c6f30-2e4c-11e5-9284-b827eb9e62be<commit_msg>bc516008-2e4c-11e5-9284-b827eb9e62be<commit_after>bc516008-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>bb9e634a-2e4c-11e5-9284-b827eb9e62be<commit_msg>bba36296-2e4c-11e5-9284-b827eb9e62be<commit_after>bba36296-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>5bbd10e2-2e4d-11e5-9284-b827eb9e62be<commit_msg>5bc216be-2e4d-11e5-9284-b827eb9e62be<commit_after>5bc216be-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>#include "ImageThresholder.h"
#include <chrono>
#include <thread>
#define EDSIZE 24
#define ERODESIZE 10
//#define IMAGETHRESHOLDER_PARALLEL_FOR
//#define IMAGETHRESHOLDER_PARALLEL_THREADS
#define IMAGETHRESHOLDER_PARALLEL_INRANGE
#ifdef IMAGETHRESHOLDER_PARALLEL_FOR
#include <ppl.h>
#endif
ImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass("ImageThresholder"), thresholdedImages(images), objectMap(objectMap)
{
stop_thread = false;
running = false;
m_iWorkersInProgress = 0;
#if defined(IMAGETHRESHOLDER_PARALLEL_THREADS)
for (auto objectRange : objectMap) {
auto object = objectRange.first;
//threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first));
threads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first));
}
#endif
elemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); //millega hiljem erode ja dilatet teha
elemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6));
elemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE));
};
ImageThresholder::~ImageThresholder(){
WaitForStop();
};
void ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) {
#if defined(IMAGETHRESHOLDER_PARALLEL_FOR)
concurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) {
auto r = objectMap[object];
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
});
#elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS)
if (m_iWorkersInProgress > 0) {
std::cout << "Still working" << std::endl;
}
frame = frameHSV;
int mask = 0;
for (auto &object : objectList) {
//std::cout << "mask " << (1 << object) << " " <<( mask | (1 << object)) << std::endl;
mask = mask | (1 << object);
}
m_iWorkersInProgress = mask;
while (m_iWorkersInProgress > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // limit fps to about 50fps
}
/*
for (auto &object : objectList) {
threads.create_thread([&frameHSV, object, this]{
auto r = objectMap[object];
do {
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
} while (thresholdedImages[object].size().height == 0);
});
}
*/
#elif defined(IMAGETHRESHOLDER_PARALLEL_INRANGE)
for (auto &object : objectList) {
auto r = objectMap[object];
thresholdedImages[object] = cv::Mat(frameHSV.rows, frameHSV.cols, CV_8U, cv::Scalar::all(0));
int lhue = r.hue.low;
int hhue = r.hue.high;
int lsat = r.sat.low;
int hsat = r.sat.high;
int lval = r.val.low;
int hval = r.val.high;
for (int row = 0; row < frameHSV.rows; ++row) {
uchar * p_src = frameHSV.ptr(row);
uchar * p_dst = thresholdedImages[object].ptr(row);
for (int col = 0; col < frameHSV.cols; ++col) {
int srcH = *p_src++;
int srcS = *p_src++;
int srcV = *p_src++;
if (srcH >= lhue && srcH <= hhue &&
srcS >= lsat && srcS <= hsat &&
srcV >= lval && srcV <= hval) {
*p_dst = 255;
}
*p_dst++;
}
}
/*
for (int i = 0; i < frameHSV.rows; i++) {
for (int j = 0; j < frameHSV.cols; j++) {
cv::Vec3b p = frameHSV.at<cv::Vec3b>(i, j);
if (p[0] >= lhue && p[0] <= hhue &&
p[1] >= lsat && p[1] <= hsat &&
p[2] >= lval && p[2] <= hval) {
thresholdedImages[object].at<unsigned char>(i, j) = 255;
}
}
}
*/
}
#else
for (auto &object : objectList) {
auto r = objectMap[object];
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
}
#endif
/*
if (object == BLUE_GATE || object == YELLOW_GATE) {
cv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2);
}
cv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2);
*/
}
void ImageThresholder::Run2(OBJECT object){
while (!stop_thread) {
if (m_iWorkersInProgress & (1 << object)) {
auto r = objectMap[object];
inRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
m_iWorkersInProgress &= ~(1 << object);
}
else {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
};
<commit_msg>try nr2<commit_after>#include "ImageThresholder.h"
#include <chrono>
#include <thread>
#define EDSIZE 24
#define ERODESIZE 10
//#define IMAGETHRESHOLDER_PARALLEL_FOR
//#define IMAGETHRESHOLDER_PARALLEL_THREADS
#define IMAGETHRESHOLDER_PARALLEL_INRANGE
#ifdef IMAGETHRESHOLDER_PARALLEL_FOR
#include <ppl.h>
#endif
ImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass("ImageThresholder"), thresholdedImages(images), objectMap(objectMap)
{
stop_thread = false;
running = false;
m_iWorkersInProgress = 0;
#if defined(IMAGETHRESHOLDER_PARALLEL_THREADS)
for (auto objectRange : objectMap) {
auto object = objectRange.first;
//threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first));
threads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first));
}
#endif
elemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); //millega hiljem erode ja dilatet teha
elemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6));
elemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE));
};
ImageThresholder::~ImageThresholder(){
WaitForStop();
};
void ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) {
#if defined(IMAGETHRESHOLDER_PARALLEL_FOR)
concurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) {
auto r = objectMap[object];
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
});
#elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS)
if (m_iWorkersInProgress > 0) {
std::cout << "Still working" << std::endl;
}
frame = frameHSV;
int mask = 0;
for (auto &object : objectList) {
//std::cout << "mask " << (1 << object) << " " <<( mask | (1 << object)) << std::endl;
mask = mask | (1 << object);
}
m_iWorkersInProgress = mask;
while (m_iWorkersInProgress > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // limit fps to about 50fps
}
/*
for (auto &object : objectList) {
threads.create_thread([&frameHSV, object, this]{
auto r = objectMap[object];
do {
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
} while (thresholdedImages[object].size().height == 0);
});
}
*/
#elif defined(IMAGETHRESHOLDER_PARALLEL_INRANGE)
for (auto &object : objectList) {
thresholdedImages[object] = cv::Mat(frameHSV.rows, frameHSV.cols, CV_8U, cv::Scalar::all(0));
}
std::map<OBJECT, uchar*> pMap;
for (int row = 0; row < frameHSV.rows; ++row) {
uchar * p_src = frameHSV.ptr(row);
for (auto &object : objectList) {
pMap[object] = thresholdedImages[object].ptr(row);
}
for (int col = 0; col < frameHSV.cols; ++col) {
int srcH = *p_src++;
int srcS = *p_src++;
int srcV = *p_src++;
for (auto &object : objectList) {
auto r = objectMap[object];
int lhue = r.hue.low;
int hhue = r.hue.high;
int lsat = r.sat.low;
int hsat = r.sat.high;
int lval = r.val.low;
int hval = r.val.high;
if (srcH >= lhue && srcH <= hhue &&
srcS >= lsat && srcS <= hsat &&
srcV >= lval && srcV <= hval) {
*(pMap[object]) = 255;
}
(*pMap[object])++;
}
}
/*
for (int i = 0; i < frameHSV.rows; i++) {
for (int j = 0; j < frameHSV.cols; j++) {
cv::Vec3b p = frameHSV.at<cv::Vec3b>(i, j);
if (p[0] >= lhue && p[0] <= hhue &&
p[1] >= lsat && p[1] <= hsat &&
p[2] >= lval && p[2] <= hval) {
thresholdedImages[object].at<unsigned char>(i, j) = 255;
}
}
}
*/
}
#else
for (auto &object : objectList) {
auto r = objectMap[object];
inRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
}
#endif
/*
if (object == BLUE_GATE || object == YELLOW_GATE) {
cv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2);
}
cv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2);
*/
}
void ImageThresholder::Run2(OBJECT object){
while (!stop_thread) {
if (m_iWorkersInProgress & (1 << object)) {
auto r = objectMap[object];
inRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);
m_iWorkersInProgress &= ~(1 << object);
}
else {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MutexContainer.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:19:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART_MUTEXCONTAINER_HXX
#define CHART_MUTEXCONTAINER_HXX
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
namespace chart
{
class MutexContainer
{
public:
virtual ~MutexContainer();
protected:
mutable ::osl::Mutex m_aMutex;
virtual ::osl::Mutex & GetMutex() const;
};
} // namespace chart
// CHART_MUTEXCONTAINER_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.126); FILE MERGED 2008/04/01 15:04:13 thb 1.3.126.2: #i85898# Stripping all external header guards 2008/03/28 16:43:55 rt 1.3.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MutexContainer.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CHART_MUTEXCONTAINER_HXX
#define CHART_MUTEXCONTAINER_HXX
#include <osl/mutex.hxx>
namespace chart
{
class MutexContainer
{
public:
virtual ~MutexContainer();
protected:
mutable ::osl::Mutex m_aMutex;
virtual ::osl::Mutex & GetMutex() const;
};
} // namespace chart
// CHART_MUTEXCONTAINER_HXX
#endif
<|endoftext|> |
<commit_before>3fb3cfa2-2e4e-11e5-9284-b827eb9e62be<commit_msg>3fb8d222-2e4e-11e5-9284-b827eb9e62be<commit_after>3fb8d222-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>28769950-2e4e-11e5-9284-b827eb9e62be<commit_msg>287ba738-2e4e-11e5-9284-b827eb9e62be<commit_after>287ba738-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>8164cce4-2e4e-11e5-9284-b827eb9e62be<commit_msg>8169d3e2-2e4e-11e5-9284-b827eb9e62be<commit_after>8169d3e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>cef6d07e-2e4e-11e5-9284-b827eb9e62be<commit_msg>cefbe9e2-2e4e-11e5-9284-b827eb9e62be<commit_after>cefbe9e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ff57a5c4-2e4c-11e5-9284-b827eb9e62be<commit_msg>ff5c9a98-2e4c-11e5-9284-b827eb9e62be<commit_after>ff5c9a98-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ebe40b68-2e4c-11e5-9284-b827eb9e62be<commit_msg>ebe8f966-2e4c-11e5-9284-b827eb9e62be<commit_after>ebe8f966-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>6450c2e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>6455cc66-2e4e-11e5-9284-b827eb9e62be<commit_after>6455cc66-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7c6b6d9c-2e4e-11e5-9284-b827eb9e62be<commit_msg>7c7077a6-2e4e-11e5-9284-b827eb9e62be<commit_after>7c7077a6-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>3cbd1f60-2e4e-11e5-9284-b827eb9e62be<commit_msg>3cc227ee-2e4e-11e5-9284-b827eb9e62be<commit_after>3cc227ee-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0dcc6f8a-2e4e-11e5-9284-b827eb9e62be<commit_msg>0dd16e40-2e4e-11e5-9284-b827eb9e62be<commit_after>0dd16e40-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>152905aa-2e4d-11e5-9284-b827eb9e62be<commit_msg>152e1ea0-2e4d-11e5-9284-b827eb9e62be<commit_after>152e1ea0-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c6857f90-2e4d-11e5-9284-b827eb9e62be<commit_msg>c68a83aa-2e4d-11e5-9284-b827eb9e62be<commit_after>c68a83aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>dd431c38-2e4d-11e5-9284-b827eb9e62be<commit_msg>dd4825fc-2e4d-11e5-9284-b827eb9e62be<commit_after>dd4825fc-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e4f040f0-2e4d-11e5-9284-b827eb9e62be<commit_msg>e4f54b4a-2e4d-11e5-9284-b827eb9e62be<commit_after>e4f54b4a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0148fc50-2e4f-11e5-9284-b827eb9e62be<commit_msg>014df2a0-2e4f-11e5-9284-b827eb9e62be<commit_after>014df2a0-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>16e1209e-2e4d-11e5-9284-b827eb9e62be<commit_msg>16e63dc2-2e4d-11e5-9284-b827eb9e62be<commit_after>16e63dc2-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>cc8010dc-2e4c-11e5-9284-b827eb9e62be<commit_msg>cc85027c-2e4c-11e5-9284-b827eb9e62be<commit_after>cc85027c-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>95a26fcc-2e4e-11e5-9284-b827eb9e62be<commit_msg>95a76770-2e4e-11e5-9284-b827eb9e62be<commit_after>95a76770-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e3ea6c8e-2e4e-11e5-9284-b827eb9e62be<commit_msg>e3ef7e90-2e4e-11e5-9284-b827eb9e62be<commit_after>e3ef7e90-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>14b46a1a-2e4d-11e5-9284-b827eb9e62be<commit_msg>14b97e56-2e4d-11e5-9284-b827eb9e62be<commit_after>14b97e56-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ad7e31b4-2e4c-11e5-9284-b827eb9e62be<commit_msg>ad8327be-2e4c-11e5-9284-b827eb9e62be<commit_after>ad8327be-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ea0d3f52-2e4d-11e5-9284-b827eb9e62be<commit_msg>ea123778-2e4d-11e5-9284-b827eb9e62be<commit_after>ea123778-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ec517914-2e4c-11e5-9284-b827eb9e62be<commit_msg>ec566488-2e4c-11e5-9284-b827eb9e62be<commit_after>ec566488-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>85f35722-2e4d-11e5-9284-b827eb9e62be<commit_msg>85f84c78-2e4d-11e5-9284-b827eb9e62be<commit_after>85f84c78-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>caed5c2e-2e4d-11e5-9284-b827eb9e62be<commit_msg>caf254f4-2e4d-11e5-9284-b827eb9e62be<commit_after>caf254f4-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d5d33bf0-2e4c-11e5-9284-b827eb9e62be<commit_msg>d5d84712-2e4c-11e5-9284-b827eb9e62be<commit_after>d5d84712-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>579483f0-2e4e-11e5-9284-b827eb9e62be<commit_msg>579998cc-2e4e-11e5-9284-b827eb9e62be<commit_after>579998cc-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c82d6d20-2e4e-11e5-9284-b827eb9e62be<commit_msg>c8326816-2e4e-11e5-9284-b827eb9e62be<commit_after>c8326816-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b3cd5620-2e4d-11e5-9284-b827eb9e62be<commit_msg>b3d255c6-2e4d-11e5-9284-b827eb9e62be<commit_after>b3d255c6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>c7818b74-2e4c-11e5-9284-b827eb9e62be<commit_msg>c7868354-2e4c-11e5-9284-b827eb9e62be<commit_after>c7868354-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f35d88ec-2e4c-11e5-9284-b827eb9e62be<commit_msg>f3628fb8-2e4c-11e5-9284-b827eb9e62be<commit_after>f3628fb8-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f47999b4-2e4c-11e5-9284-b827eb9e62be<commit_msg>f47ebdc2-2e4c-11e5-9284-b827eb9e62be<commit_after>f47ebdc2-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fb6dc2e8-2e4e-11e5-9284-b827eb9e62be<commit_msg>fb72d24c-2e4e-11e5-9284-b827eb9e62be<commit_after>fb72d24c-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2c0a9034-2e4f-11e5-9284-b827eb9e62be<commit_msg>2c0f8648-2e4f-11e5-9284-b827eb9e62be<commit_after>2c0f8648-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
class PreferenceServiceTest : public UITest {
public:
void SetUp() {
PathService::Get(base::DIR_TEMP, &tmp_profile_);
tmp_profile_ = tmp_profile_.AppendASCII("tmp_profile");
// Create a fresh, empty copy of this directory.
file_util::Delete(tmp_profile_, true);
file_util::CreateDirectory(tmp_profile_);
FilePath reference_pref_file =
test_data_directory_
.AppendASCII("profiles")
.AppendASCII("window_placement")
.Append(chrome::kLocalStateFilename);
tmp_pref_file_ = tmp_profile_.Append(chrome::kLocalStateFilename);
ASSERT_TRUE(file_util::PathExists(reference_pref_file));
// Copy only the Local State file, the rest will be automatically created
ASSERT_TRUE(file_util::CopyFile(reference_pref_file, tmp_pref_file_));
#if defined(OS_WIN)
// Make the copy writable. On POSIX we assume the umask allows files
// we create to be writable.
ASSERT_TRUE(::SetFileAttributesW(tmp_pref_file_.value().c_str(),
FILE_ATTRIBUTE_NORMAL));
#endif
launch_arguments_.AppendSwitchWithValue(switches::kUserDataDir,
tmp_profile_.ToWStringHack());
}
bool LaunchAppWithProfile() {
if (!file_util::PathExists(tmp_pref_file_))
return false;
UITest::SetUp();
return true;
}
void TearDown() {
UITest::TearDown();
EXPECT_TRUE(DieFileDie(tmp_profile_, true));
}
public:
FilePath tmp_pref_file_;
FilePath tmp_profile_;
};
#if defined(OS_WIN)
// This test verifies that the window position from the prefs file is restored
// when the app restores. This doesn't really make sense on Linux, where
// the window manager might fight with you over positioning. However, we
// might be able to make this work on buildbots.
// Also, not sure what should happen on the mac. In any case, the code below
// (minus the Windows bits) compiles fine on my Linux box now.
// TODO(port): revisit this.
TEST_F(PreferenceServiceTest, PreservedWindowPlacementIsLoaded) {
// The window should open with the reference profile
ASSERT_TRUE(LaunchAppWithProfile());
ASSERT_TRUE(file_util::PathExists(tmp_pref_file_));
JSONFileValueSerializer deserializer(tmp_pref_file_);
scoped_ptr<Value> root(deserializer.Deserialize(NULL));
ASSERT_TRUE(root.get());
ASSERT_TRUE(root->IsType(Value::TYPE_DICTIONARY));
DictionaryValue* root_dict = static_cast<DictionaryValue*>(root.get());
// Retrieve the screen rect for the launched window
scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_ptr<WindowProxy> window(browser->GetWindow());
HWND hWnd;
ASSERT_TRUE(window->GetHWND(&hWnd));
WINDOWPLACEMENT window_placement;
ASSERT_TRUE(GetWindowPlacement(hWnd, &window_placement));
// Retrieve the expected rect values from "Preferences"
int bottom = 0;
std::wstring kBrowserWindowPlacement(prefs::kBrowserWindowPlacement);
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".bottom",
&bottom));
EXPECT_EQ(bottom, window_placement.rcNormalPosition.bottom);
int top = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".top",
&top));
EXPECT_EQ(top, window_placement.rcNormalPosition.top);
int left = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".left",
&left));
EXPECT_EQ(left, window_placement.rcNormalPosition.left);
int right = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".right",
&right));
EXPECT_EQ(right, window_placement.rcNormalPosition.right);
// Find if launched window is maximized
bool is_window_maximized = (window_placement.showCmd == SW_MAXIMIZE);
bool is_maximized = false;
EXPECT_TRUE(root_dict->GetBoolean(kBrowserWindowPlacement + L".maximized",
&is_maximized));
EXPECT_EQ(is_maximized, is_window_maximized);
}
#endif
<commit_msg>Re-disable the PrefService PreservedWindowPlacementIsLoaded UI test until I figure out why the official builder doesn't like it.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
class PreferenceServiceTest : public UITest {
public:
void SetUp() {
PathService::Get(base::DIR_TEMP, &tmp_profile_);
tmp_profile_ = tmp_profile_.AppendASCII("tmp_profile");
// Create a fresh, empty copy of this directory.
file_util::Delete(tmp_profile_, true);
file_util::CreateDirectory(tmp_profile_);
FilePath reference_pref_file =
test_data_directory_
.AppendASCII("profiles")
.AppendASCII("window_placement")
.Append(chrome::kLocalStateFilename);
tmp_pref_file_ = tmp_profile_.Append(chrome::kLocalStateFilename);
ASSERT_TRUE(file_util::PathExists(reference_pref_file));
// Copy only the Local State file, the rest will be automatically created
ASSERT_TRUE(file_util::CopyFile(reference_pref_file, tmp_pref_file_));
#if defined(OS_WIN)
// Make the copy writable. On POSIX we assume the umask allows files
// we create to be writable.
ASSERT_TRUE(::SetFileAttributesW(tmp_pref_file_.value().c_str(),
FILE_ATTRIBUTE_NORMAL));
#endif
launch_arguments_.AppendSwitchWithValue(switches::kUserDataDir,
tmp_profile_.ToWStringHack());
}
bool LaunchAppWithProfile() {
if (!file_util::PathExists(tmp_pref_file_))
return false;
UITest::SetUp();
return true;
}
void TearDown() {
UITest::TearDown();
EXPECT_TRUE(DieFileDie(tmp_profile_, true));
}
public:
FilePath tmp_pref_file_;
FilePath tmp_profile_;
};
#if defined(OS_WIN)
// This test verifies that the window position from the prefs file is restored
// when the app restores. This doesn't really make sense on Linux, where
// the window manager might fight with you over positioning. However, we
// might be able to make this work on buildbots.
// Also, not sure what should happen on the mac. In any case, the code below
// (minus the Windows bits) compiles fine on my Linux box now.
// TODO(port): revisit this.
TEST_F(PreferenceServiceTest, DISABLED_PreservedWindowPlacementIsLoaded) {
// The window should open with the reference profile
ASSERT_TRUE(LaunchAppWithProfile());
ASSERT_TRUE(file_util::PathExists(tmp_pref_file_));
JSONFileValueSerializer deserializer(tmp_pref_file_);
scoped_ptr<Value> root(deserializer.Deserialize(NULL));
ASSERT_TRUE(root.get());
ASSERT_TRUE(root->IsType(Value::TYPE_DICTIONARY));
DictionaryValue* root_dict = static_cast<DictionaryValue*>(root.get());
// Retrieve the screen rect for the launched window
scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_ptr<WindowProxy> window(browser->GetWindow());
HWND hWnd;
ASSERT_TRUE(window->GetHWND(&hWnd));
WINDOWPLACEMENT window_placement;
ASSERT_TRUE(GetWindowPlacement(hWnd, &window_placement));
// Retrieve the expected rect values from "Preferences"
int bottom = 0;
std::wstring kBrowserWindowPlacement(prefs::kBrowserWindowPlacement);
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".bottom",
&bottom));
EXPECT_EQ(bottom, window_placement.rcNormalPosition.bottom);
int top = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".top",
&top));
EXPECT_EQ(top, window_placement.rcNormalPosition.top);
int left = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".left",
&left));
EXPECT_EQ(left, window_placement.rcNormalPosition.left);
int right = 0;
EXPECT_TRUE(root_dict->GetInteger(kBrowserWindowPlacement + L".right",
&right));
EXPECT_EQ(right, window_placement.rcNormalPosition.right);
// Find if launched window is maximized
bool is_window_maximized = (window_placement.showCmd == SW_MAXIMIZE);
bool is_maximized = false;
EXPECT_TRUE(root_dict->GetBoolean(kBrowserWindowPlacement + L".maximized",
&is_maximized));
EXPECT_EQ(is_maximized, is_window_maximized);
}
#endif
<|endoftext|> |
<commit_before>ad0327e2-2e4e-11e5-9284-b827eb9e62be<commit_msg>ad082486-2e4e-11e5-9284-b827eb9e62be<commit_after>ad082486-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b9d44fa0-2e4e-11e5-9284-b827eb9e62be<commit_msg>b9d9b260-2e4e-11e5-9284-b827eb9e62be<commit_after>b9d9b260-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>/*
* 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) 2012 Sergey Lisitsyn
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/evaluation/CrossValidationPrintOutput.h>
#include <shogun/machine/LinearMachine.h>
#include <shogun/machine/LinearMulticlassMachine.h>
#include <shogun/machine/KernelMachine.h>
#include <shogun/machine/KernelMulticlassMachine.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/classifier/mkl/MKL.h>
using namespace shogun;
void CCrossValidationPrintOutput::init_num_runs(index_t num_runs,
const char* prefix)
{
SG_PRINT("%scross validation number of runs %d\n", prefix, num_runs);
}
/** init number of folds */
void CCrossValidationPrintOutput::init_num_folds(index_t num_folds,
const char* prefix)
{
SG_PRINT("%scross validation number of folds %d\n", prefix, num_folds);
}
void CCrossValidationPrintOutput::update_run_index(index_t run_index,
const char* prefix)
{
SG_PRINT("%scross validation run %d\n", prefix, run_index);
}
void CCrossValidationPrintOutput::update_fold_index(index_t fold_index,
const char* prefix)
{
SG_PRINT("%sfold %d\n", prefix, fold_index);
}
void CCrossValidationPrintOutput::update_train_indices(
SGVector<index_t> indices, const char* prefix)
{
indices.display_vector("train_indices", prefix);
}
void CCrossValidationPrintOutput::update_test_indices(
SGVector<index_t> indices, const char* prefix)
{
indices.display_vector("test_indices", prefix);
}
void CCrossValidationPrintOutput::update_trained_machine(
CMachine* machine, const char* prefix)
{
if (dynamic_cast<CLinearMachine*>(machine))
{
CLinearMachine* linear_machine=(CLinearMachine*)machine;
linear_machine->get_w().display_vector("learned_w", prefix);
SG_PRINT("%slearned_bias=%f\n", prefix, linear_machine->get_bias());
}
if (dynamic_cast<CKernelMachine*>(machine))
{
CKernelMachine* kernel_machine=(CKernelMachine*)machine;
kernel_machine->get_alphas().display_vector("learned_alphas", prefix);
SG_PRINT("%slearned_bias=%f\n", prefix, kernel_machine->get_bias());
}
if (dynamic_cast<CLinearMulticlassMachine*>(machine)
|| dynamic_cast<CKernelMulticlassMachine*>(machine))
{
/* append one tab to prefix */
char* new_prefix=append_tab_to_string(prefix);
CMulticlassMachine* mc_machine=(CMulticlassMachine*)machine;
for (int i=0; i<mc_machine->get_num_machines(); i++)
{
CMachine* sub_machine=mc_machine->get_machine(i);
//SG_PRINT("%smulti-class machine %d:\n", i, sub_machine);
this->update_trained_machine(sub_machine, new_prefix);
SG_UNREF(sub_machine);
}
/* clean up */
SG_FREE(new_prefix);
}
if (dynamic_cast<CMKL*>(machine))
{
CMKL* mkl=(CMKL*)machine;
CCombinedKernel* kernel=dynamic_cast<CCombinedKernel*>(
mkl->get_kernel());
kernel->get_subkernel_weights().display_vector("MKL sub-kernel weights",
prefix);
SG_UNREF(kernel);
}
}
void CCrossValidationPrintOutput::update_test_result(CLabels* results,
const char* prefix)
{
results->get_confidences().display_vector("test_labels", prefix);
}
void CCrossValidationPrintOutput::update_test_true_result(CLabels* results,
const char* prefix)
{
results->get_confidences().display_vector("true_labels", prefix);
}
void CCrossValidationPrintOutput::update_evaluation_result(float64_t result,
const char* prefix)
{
SG_PRINT("%sevaluation result=%f\n", prefix, result);
}
char* CCrossValidationPrintOutput::append_tab_to_string(const char* string)
{
/* allocate memory, concatenate and add termination character */
index_t len=strlen(string);
char* new_prefix=SG_MALLOC(char, len+2);
memcpy(new_prefix, string, sizeof(char*)*len);
new_prefix[len]='\t';
new_prefix[len+1]='\0';
return new_prefix;
}
<commit_msg>Added MKL multiclass handling in CV print output<commit_after>/*
* 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) 2012 Sergey Lisitsyn
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/evaluation/CrossValidationPrintOutput.h>
#include <shogun/machine/LinearMachine.h>
#include <shogun/machine/LinearMulticlassMachine.h>
#include <shogun/machine/KernelMachine.h>
#include <shogun/machine/KernelMulticlassMachine.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/classifier/mkl/MKL.h>
#include <shogun/classifier/mkl/MKLMulticlass.h>
using namespace shogun;
void CCrossValidationPrintOutput::init_num_runs(index_t num_runs,
const char* prefix)
{
SG_PRINT("%scross validation number of runs %d\n", prefix, num_runs);
}
/** init number of folds */
void CCrossValidationPrintOutput::init_num_folds(index_t num_folds,
const char* prefix)
{
SG_PRINT("%scross validation number of folds %d\n", prefix, num_folds);
}
void CCrossValidationPrintOutput::update_run_index(index_t run_index,
const char* prefix)
{
SG_PRINT("%scross validation run %d\n", prefix, run_index);
}
void CCrossValidationPrintOutput::update_fold_index(index_t fold_index,
const char* prefix)
{
SG_PRINT("%sfold %d\n", prefix, fold_index);
}
void CCrossValidationPrintOutput::update_train_indices(
SGVector<index_t> indices, const char* prefix)
{
indices.display_vector("train_indices", prefix);
}
void CCrossValidationPrintOutput::update_test_indices(
SGVector<index_t> indices, const char* prefix)
{
indices.display_vector("test_indices", prefix);
}
void CCrossValidationPrintOutput::update_trained_machine(
CMachine* machine, const char* prefix)
{
if (dynamic_cast<CLinearMachine*>(machine))
{
CLinearMachine* linear_machine=(CLinearMachine*)machine;
linear_machine->get_w().display_vector("learned_w", prefix);
SG_PRINT("%slearned_bias=%f\n", prefix, linear_machine->get_bias());
}
if (dynamic_cast<CKernelMachine*>(machine))
{
CKernelMachine* kernel_machine=(CKernelMachine*)machine;
kernel_machine->get_alphas().display_vector("learned_alphas", prefix);
SG_PRINT("%slearned_bias=%f\n", prefix, kernel_machine->get_bias());
}
if (dynamic_cast<CLinearMulticlassMachine*>(machine)
|| dynamic_cast<CKernelMulticlassMachine*>(machine))
{
/* append one tab to prefix */
char* new_prefix=append_tab_to_string(prefix);
CMulticlassMachine* mc_machine=(CMulticlassMachine*)machine;
for (int i=0; i<mc_machine->get_num_machines(); i++)
{
CMachine* sub_machine=mc_machine->get_machine(i);
//SG_PRINT("%smulti-class machine %d:\n", i, sub_machine);
this->update_trained_machine(sub_machine, new_prefix);
SG_UNREF(sub_machine);
}
/* clean up */
SG_FREE(new_prefix);
}
if (dynamic_cast<CMKL*>(machine))
{
CMKL* mkl=(CMKL*)machine;
CCombinedKernel* kernel=dynamic_cast<CCombinedKernel*>(
mkl->get_kernel());
kernel->get_subkernel_weights().display_vector("MKL sub-kernel weights",
prefix);
SG_UNREF(kernel);
}
if (dynamic_cast<CMKLMulticlass*>(machine))
{
CMKLMulticlass* mkl=(CMKLMulticlass*)machine;
CCombinedKernel* kernel=dynamic_cast<CCombinedKernel*>(
mkl->get_kernel());
kernel->get_subkernel_weights().display_vector("MKL sub-kernel weights",
prefix);
SG_UNREF(kernel);
}
}
void CCrossValidationPrintOutput::update_test_result(CLabels* results,
const char* prefix)
{
results->get_confidences().display_vector("test_labels", prefix);
}
void CCrossValidationPrintOutput::update_test_true_result(CLabels* results,
const char* prefix)
{
results->get_confidences().display_vector("true_labels", prefix);
}
void CCrossValidationPrintOutput::update_evaluation_result(float64_t result,
const char* prefix)
{
SG_PRINT("%sevaluation result=%f\n", prefix, result);
}
char* CCrossValidationPrintOutput::append_tab_to_string(const char* string)
{
/* allocate memory, concatenate and add termination character */
index_t len=strlen(string);
char* new_prefix=SG_MALLOC(char, len+2);
memcpy(new_prefix, string, sizeof(char*)*len);
new_prefix[len]='\t';
new_prefix[len+1]='\0';
return new_prefix;
}
<|endoftext|> |
<commit_before>1b72ab26-2e4f-11e5-9284-b827eb9e62be<commit_msg>1b77b9c2-2e4f-11e5-9284-b827eb9e62be<commit_after>1b77b9c2-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>/*
* 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) 2013 Roman Votyakov
* Copyright (C) 2012 Jacob Walker
*/
#ifdef USE_GPL_SHOGUN
#include <shogun/modelselection/GradientModelSelection.h>
#ifdef HAVE_NLOPT
#include <shogun/evaluation/GradientResult.h>
#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/modelselection/ModelSelectionParameters.h>
#include <shogun/machine/Machine.h>
#include <nlopt.h>
using namespace shogun;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** structure used for NLopt callback function */
struct nlopt_params
{
/** pointer to machine evaluation */
CMachineEvaluation* machine_eval;
/** pointer to current combination */
CParameterCombination* current_combination;
/** pointer to parmeter dictionary */
CMap<TParameter*, CSGObject*>* parameter_dictionary;
/** do we want to print the state? */
bool print_state;
};
/** NLopt callback function wrapper
*
* @param n number of parameters
* @param x vector of parameter values
* @param grad vector of gradient values with respect to parameter
* @param func_data data needed for the callback function. In this case, its a
* nlopt_params
*
* @return function value
*/
double nlopt_function(unsigned n, const double* x, double* grad, void* func_data)
{
nlopt_params* params=(nlopt_params*)func_data;
CMachineEvaluation* machine_eval=params->machine_eval;
CParameterCombination* current_combination=params->current_combination;
CMap<TParameter*, CSGObject*>* parameter_dictionary=params->parameter_dictionary;
bool print_state=params->print_state;
index_t offset=0;
// set parameters from vector x
for (index_t i=0; i<parameter_dictionary->get_num_elements(); i++)
{
CMapNode<TParameter*, CSGObject*>* node=parameter_dictionary->get_node_ptr(i);
TParameter* param=node->key;
CSGObject* parent=node->data;
if (param->m_datatype.m_ctype==CT_VECTOR ||
param->m_datatype.m_ctype==CT_SGVECTOR ||
param->m_datatype.m_ctype==CT_SGMATRIX ||
param->m_datatype.m_ctype==CT_MATRIX)
{
for (index_t j=0; j<param->m_datatype.get_num_elements(); j++)
{
bool result=current_combination->set_parameter(param->m_name,
(float64_t)x[offset++], parent, j);
REQUIRE(result, "Parameter %s not found in combination tree\n",
param->m_name)
}
}
else
{
bool result=current_combination->set_parameter(param->m_name,
(float64_t)x[offset++], parent);
REQUIRE(result, "Parameter %s not found in combination tree\n",
param->m_name)
}
}
// apply current combination to the machine
CMachine* machine=machine_eval->get_machine();
current_combination->apply_to_machine(machine);
if (print_state)
{
SG_SPRINT("Current combination\n");
current_combination->print_tree();
}
SG_UNREF(machine);
// evaluate the machine
CEvaluationResult* evaluation_result=machine_eval->evaluate();
CGradientResult* gradient_result=CGradientResult::obtain_from_generic(
evaluation_result);
SG_UNREF(evaluation_result);
if (print_state)
{
SG_SPRINT("Current result\n");
gradient_result->print_result();
}
// get value of the function, gradients and parameter dictionary
SGVector<float64_t> value=gradient_result->get_value();
CMap<TParameter*, SGVector<float64_t> >* gradient=gradient_result->get_gradient();
CMap<TParameter*, CSGObject*>* gradient_dictionary=
gradient_result->get_paramter_dictionary();
SG_UNREF(gradient_result);
offset=0;
// set derivative for each parameter from parameter dictionary
for (index_t i=0; i<parameter_dictionary->get_num_elements(); i++)
{
CMapNode<TParameter*, CSGObject*>* node=parameter_dictionary->get_node_ptr(i);
SGVector<float64_t> derivative;
for (index_t j=0; j<gradient_dictionary->get_num_elements(); j++)
{
CMapNode<TParameter*, CSGObject*>* gradient_node=
gradient_dictionary->get_node_ptr(j);
if (gradient_node->data==node->data &&
!strcmp(gradient_node->key->m_name, node->key->m_name))
{
derivative=gradient->get_element(gradient_node->key);
}
}
REQUIRE(derivative.vlen, "Can't find gradient wrt %s parameter!\n",
node->key->m_name);
memcpy(grad+offset, derivative.vector, sizeof(double)*derivative.vlen);
offset+=derivative.vlen;
}
SG_UNREF(gradient);
SG_UNREF(gradient_dictionary);
return (double)(SGVector<float64_t>::sum(value));
}
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
CGradientModelSelection::CGradientModelSelection() : CModelSelection()
{
init();
}
CGradientModelSelection::CGradientModelSelection(CMachineEvaluation* machine_eval,
CModelSelectionParameters* model_parameters)
: CModelSelection(machine_eval, model_parameters)
{
init();
}
CGradientModelSelection::~CGradientModelSelection()
{
}
void CGradientModelSelection::init()
{
m_max_evaluations=1000;
m_grad_tolerance=1e-6;
SG_ADD(&m_grad_tolerance, "gradient_tolerance", "Gradient tolerance",
MS_NOT_AVAILABLE);
SG_ADD(&m_max_evaluations, "max_evaluations", "Maximum number of evaluations",
MS_NOT_AVAILABLE);
}
CParameterCombination* CGradientModelSelection::select_model(bool print_state)
{
if (!m_model_parameters)
{
CMachine* machine=m_machine_eval->get_machine();
CParameterCombination* current_combination=new CParameterCombination(machine);
SG_REF(current_combination);
if (print_state)
{
SG_PRINT("Initial combination:\n");
current_combination->print_tree();
}
// get total length of variables
index_t total_variables=current_combination->get_parameters_length();
// build parameter->value map
CMap<TParameter*, SGVector<float64_t> >* argument=
new CMap<TParameter*, SGVector<float64_t> >();
current_combination->build_parameter_values_map(argument);
// unroll current parameter combination into vector
SGVector<double> x(total_variables);
index_t offset=0;
for (index_t i=0; i<argument->get_num_elements(); i++)
{
CMapNode<TParameter*, SGVector<float64_t> >* node=argument->get_node_ptr(i);
memcpy(x.vector+offset, node->data.vector, sizeof(double)*node->data.vlen);
offset+=node->data.vlen;
}
SG_UNREF(argument);
// create nlopt object and choose MMA (Method of Moving Asymptotes)
// optimization algorithm
nlopt_opt opt=nlopt_create(NLOPT_LD_MMA, total_variables);
// currently we assume all parameters are positive
// (this is NOT true when inducing points and Full Matrix GaussianARDKernel are optimized)
// create lower bound vector (lb=-inf)
//SGVector<double> lower_bound(total_variables);
//lower_bound.set_const(1e-6);
// create upper bound vector (ub=inf)
//SGVector<double> upper_bound(total_variables);
//upper_bound.set_const(HUGE_VAL);
// set upper and lower bound
//nlopt_set_lower_bounds(opt, lower_bound.vector);
//nlopt_set_upper_bounds(opt, upper_bound.vector);
// set maximum number of evaluations
nlopt_set_maxeval(opt, m_max_evaluations);
// set absolute argument tolearance
nlopt_set_xtol_abs1(opt, m_grad_tolerance);
nlopt_set_ftol_abs(opt, m_grad_tolerance);
// build parameter->sgobject map from current parameter combination
CMap<TParameter*, CSGObject*>* parameter_dictionary=
new CMap<TParameter*, CSGObject*>();
current_combination->build_parameter_parent_map(parameter_dictionary);
// nlopt parameters
nlopt_params params;
params.current_combination=current_combination;
params.machine_eval=m_machine_eval;
params.print_state=print_state;
params.parameter_dictionary=parameter_dictionary;
// choose evaluation direction (minimize or maximize objective function)
if (m_machine_eval->get_evaluation_direction()==ED_MINIMIZE)
{
if (print_state)
SG_PRINT("Minimizing objective function:\n");
nlopt_set_min_objective(opt, nlopt_function, ¶ms);
}
else
{
if (print_state)
SG_PRINT("Maximizing objective function:\n");
nlopt_set_max_objective(opt, nlopt_function, ¶ms);
}
// the minimum objective value, upon return
double minf;
// optimize our function
nlopt_result result=nlopt_optimize(opt, x.vector, &minf);
REQUIRE(result>0, "NLopt failed while optimizing objective function!\n");
if (print_state)
{
SG_PRINT("Best combination:\n");
current_combination->print_tree();
}
// clean up
nlopt_destroy(opt);
SG_UNREF(machine);
SG_UNREF(parameter_dictionary);
return current_combination;
}
else
{
SG_NOTIMPLEMENTED
return NULL;
}
}
#endif /* HAVE_NLOPT */
#endif //USE_GPL_SHOGUN
<commit_msg>fix guard<commit_after>/*
* 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) 2013 Roman Votyakov
* Copyright (C) 2012 Jacob Walker
*/
#include <shogun/modelselection/GradientModelSelection.h>
#ifdef USE_GPL_SHOGUN
#ifdef HAVE_NLOPT
#include <shogun/evaluation/GradientResult.h>
#include <shogun/modelselection/ParameterCombination.h>
#include <shogun/modelselection/ModelSelectionParameters.h>
#include <shogun/machine/Machine.h>
#include <nlopt.h>
using namespace shogun;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** structure used for NLopt callback function */
struct nlopt_params
{
/** pointer to machine evaluation */
CMachineEvaluation* machine_eval;
/** pointer to current combination */
CParameterCombination* current_combination;
/** pointer to parmeter dictionary */
CMap<TParameter*, CSGObject*>* parameter_dictionary;
/** do we want to print the state? */
bool print_state;
};
/** NLopt callback function wrapper
*
* @param n number of parameters
* @param x vector of parameter values
* @param grad vector of gradient values with respect to parameter
* @param func_data data needed for the callback function. In this case, its a
* nlopt_params
*
* @return function value
*/
double nlopt_function(unsigned n, const double* x, double* grad, void* func_data)
{
nlopt_params* params=(nlopt_params*)func_data;
CMachineEvaluation* machine_eval=params->machine_eval;
CParameterCombination* current_combination=params->current_combination;
CMap<TParameter*, CSGObject*>* parameter_dictionary=params->parameter_dictionary;
bool print_state=params->print_state;
index_t offset=0;
// set parameters from vector x
for (index_t i=0; i<parameter_dictionary->get_num_elements(); i++)
{
CMapNode<TParameter*, CSGObject*>* node=parameter_dictionary->get_node_ptr(i);
TParameter* param=node->key;
CSGObject* parent=node->data;
if (param->m_datatype.m_ctype==CT_VECTOR ||
param->m_datatype.m_ctype==CT_SGVECTOR ||
param->m_datatype.m_ctype==CT_SGMATRIX ||
param->m_datatype.m_ctype==CT_MATRIX)
{
for (index_t j=0; j<param->m_datatype.get_num_elements(); j++)
{
bool result=current_combination->set_parameter(param->m_name,
(float64_t)x[offset++], parent, j);
REQUIRE(result, "Parameter %s not found in combination tree\n",
param->m_name)
}
}
else
{
bool result=current_combination->set_parameter(param->m_name,
(float64_t)x[offset++], parent);
REQUIRE(result, "Parameter %s not found in combination tree\n",
param->m_name)
}
}
// apply current combination to the machine
CMachine* machine=machine_eval->get_machine();
current_combination->apply_to_machine(machine);
if (print_state)
{
SG_SPRINT("Current combination\n");
current_combination->print_tree();
}
SG_UNREF(machine);
// evaluate the machine
CEvaluationResult* evaluation_result=machine_eval->evaluate();
CGradientResult* gradient_result=CGradientResult::obtain_from_generic(
evaluation_result);
SG_UNREF(evaluation_result);
if (print_state)
{
SG_SPRINT("Current result\n");
gradient_result->print_result();
}
// get value of the function, gradients and parameter dictionary
SGVector<float64_t> value=gradient_result->get_value();
CMap<TParameter*, SGVector<float64_t> >* gradient=gradient_result->get_gradient();
CMap<TParameter*, CSGObject*>* gradient_dictionary=
gradient_result->get_paramter_dictionary();
SG_UNREF(gradient_result);
offset=0;
// set derivative for each parameter from parameter dictionary
for (index_t i=0; i<parameter_dictionary->get_num_elements(); i++)
{
CMapNode<TParameter*, CSGObject*>* node=parameter_dictionary->get_node_ptr(i);
SGVector<float64_t> derivative;
for (index_t j=0; j<gradient_dictionary->get_num_elements(); j++)
{
CMapNode<TParameter*, CSGObject*>* gradient_node=
gradient_dictionary->get_node_ptr(j);
if (gradient_node->data==node->data &&
!strcmp(gradient_node->key->m_name, node->key->m_name))
{
derivative=gradient->get_element(gradient_node->key);
}
}
REQUIRE(derivative.vlen, "Can't find gradient wrt %s parameter!\n",
node->key->m_name);
memcpy(grad+offset, derivative.vector, sizeof(double)*derivative.vlen);
offset+=derivative.vlen;
}
SG_UNREF(gradient);
SG_UNREF(gradient_dictionary);
return (double)(SGVector<float64_t>::sum(value));
}
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
CGradientModelSelection::CGradientModelSelection() : CModelSelection()
{
init();
}
CGradientModelSelection::CGradientModelSelection(CMachineEvaluation* machine_eval,
CModelSelectionParameters* model_parameters)
: CModelSelection(machine_eval, model_parameters)
{
init();
}
CGradientModelSelection::~CGradientModelSelection()
{
}
void CGradientModelSelection::init()
{
m_max_evaluations=1000;
m_grad_tolerance=1e-6;
SG_ADD(&m_grad_tolerance, "gradient_tolerance", "Gradient tolerance",
MS_NOT_AVAILABLE);
SG_ADD(&m_max_evaluations, "max_evaluations", "Maximum number of evaluations",
MS_NOT_AVAILABLE);
}
CParameterCombination* CGradientModelSelection::select_model(bool print_state)
{
if (!m_model_parameters)
{
CMachine* machine=m_machine_eval->get_machine();
CParameterCombination* current_combination=new CParameterCombination(machine);
SG_REF(current_combination);
if (print_state)
{
SG_PRINT("Initial combination:\n");
current_combination->print_tree();
}
// get total length of variables
index_t total_variables=current_combination->get_parameters_length();
// build parameter->value map
CMap<TParameter*, SGVector<float64_t> >* argument=
new CMap<TParameter*, SGVector<float64_t> >();
current_combination->build_parameter_values_map(argument);
// unroll current parameter combination into vector
SGVector<double> x(total_variables);
index_t offset=0;
for (index_t i=0; i<argument->get_num_elements(); i++)
{
CMapNode<TParameter*, SGVector<float64_t> >* node=argument->get_node_ptr(i);
memcpy(x.vector+offset, node->data.vector, sizeof(double)*node->data.vlen);
offset+=node->data.vlen;
}
SG_UNREF(argument);
// create nlopt object and choose MMA (Method of Moving Asymptotes)
// optimization algorithm
nlopt_opt opt=nlopt_create(NLOPT_LD_MMA, total_variables);
// currently we assume all parameters are positive
// (this is NOT true when inducing points and Full Matrix GaussianARDKernel are optimized)
// create lower bound vector (lb=-inf)
//SGVector<double> lower_bound(total_variables);
//lower_bound.set_const(1e-6);
// create upper bound vector (ub=inf)
//SGVector<double> upper_bound(total_variables);
//upper_bound.set_const(HUGE_VAL);
// set upper and lower bound
//nlopt_set_lower_bounds(opt, lower_bound.vector);
//nlopt_set_upper_bounds(opt, upper_bound.vector);
// set maximum number of evaluations
nlopt_set_maxeval(opt, m_max_evaluations);
// set absolute argument tolearance
nlopt_set_xtol_abs1(opt, m_grad_tolerance);
nlopt_set_ftol_abs(opt, m_grad_tolerance);
// build parameter->sgobject map from current parameter combination
CMap<TParameter*, CSGObject*>* parameter_dictionary=
new CMap<TParameter*, CSGObject*>();
current_combination->build_parameter_parent_map(parameter_dictionary);
// nlopt parameters
nlopt_params params;
params.current_combination=current_combination;
params.machine_eval=m_machine_eval;
params.print_state=print_state;
params.parameter_dictionary=parameter_dictionary;
// choose evaluation direction (minimize or maximize objective function)
if (m_machine_eval->get_evaluation_direction()==ED_MINIMIZE)
{
if (print_state)
SG_PRINT("Minimizing objective function:\n");
nlopt_set_min_objective(opt, nlopt_function, ¶ms);
}
else
{
if (print_state)
SG_PRINT("Maximizing objective function:\n");
nlopt_set_max_objective(opt, nlopt_function, ¶ms);
}
// the minimum objective value, upon return
double minf;
// optimize our function
nlopt_result result=nlopt_optimize(opt, x.vector, &minf);
REQUIRE(result>0, "NLopt failed while optimizing objective function!\n");
if (print_state)
{
SG_PRINT("Best combination:\n");
current_combination->print_tree();
}
// clean up
nlopt_destroy(opt);
SG_UNREF(machine);
SG_UNREF(parameter_dictionary);
return current_combination;
}
else
{
SG_NOTIMPLEMENTED
return NULL;
}
}
#endif /* HAVE_NLOPT */
#endif //USE_GPL_SHOGUN
<|endoftext|> |
<commit_before>4363789c-2e4d-11e5-9284-b827eb9e62be<commit_msg>43687cb6-2e4d-11e5-9284-b827eb9e62be<commit_after>43687cb6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>382f83de-2e4e-11e5-9284-b827eb9e62be<commit_msg>383476b4-2e4e-11e5-9284-b827eb9e62be<commit_after>383476b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.